-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOut-PingStats.ps1
More file actions
1774 lines (1578 loc) · 71.7 KB
/
Copy pathOut-PingStats.ps1
File metadata and controls
1774 lines (1578 loc) · 71.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<#
.SYNOPSIS
Continuously pings a host, or a small set of public hosts, and displays live connection-quality statistics.
.DESCRIPTION
Out-PingStats is an interactive terminal monitor for ICMP latency and packet loss.
When you specify -Target, it continuously pings that host and renders live graphs and summaries for:
- recent RTT values
- RTT histogram
- rolling loss percentage
- rolling one-way jitter estimate
- rolling RTT 95th percentile
When you omit -Target, it probes a few well-known Internet hosts in parallel and treats the result as a rough
"Internet reachability and quality" indicator rather than a measurement for one exact destination.
The display updates continuously until you stop it, typically with Ctrl+C.
This command is intended for human monitoring in a console window. Its primary output is a live screen display,
not pipeline-friendly structured objects.
For best-looking graphs, use a monospace font with good Unicode block-character support. DejaVu Sans Mono works
well. Consolas usually forces lower-resolution graph characters.
.INTERACTIVE CONTROLS
While the monitor is running, you can use:
Ctrl-H Toggle RTT histogram
Ctrl-R Toggle recent-RTT graph
Ctrl-L Toggle loss graph
Ctrl-J Toggle jitter graph
Ctrl-S Toggle graph character set / font mode
.PARAMETER Target
Host name or IP address to probe.
If omitted, the command monitors general Internet quality by pinging several public hosts in parallel.
.PARAMETER Title
Custom title shown at the top of the screen.
By default, the title is derived from -Target, or shows a generic Internet-oriented title when -Target is omitted.
.PARAMETER GraphMax
Upper Y-axis limit for RTT graphs.
By default, the command chooses a sensible value automatically.
.PARAMETER PingsPerSec
Deprecated. Currently has no practical effect.
.PARAMETER GraphMin
Lower Y-axis limit for RTT graphs.
By default, the command chooses a sensible value automatically.
.PARAMETER HistBucketsCount
Number of buckets to use in the RTT histogram.
.PARAMETER AggregationSeconds
Number of seconds per aggregation period for the slower trend graphs such as loss, jitter, and RTT 95th percentile.
.PARAMETER HistSamples
Number of recent samples to include in the RTT histogram.
If omitted, the default is at least 100 samples and otherwise about one minute of samples.
.PARAMETER Visual
Reserved legacy parameter. Do not rely on it.
.PARAMETER DebugMode
Enables diagnostic behavior and reduces screen-clearing behavior to help troubleshoot parsing, aggregation,
or rendering issues.
.PARAMETER DebugData
Enables extra debug-data collection.
.PARAMETER HighResFont
Controls graph-character mode.
-1 = auto-detect
0 = force low-resolution characters
1 = force high-resolution characters
Use low-resolution mode for terminals or fonts that do not render the Unicode block characters cleanly.
.PARAMETER UpdateScreenEvery
How often, in seconds, the screen is refreshed.
Lower values make the display more responsive but may increase CPU use.
.PARAMETER BarGraphSamples
How many recent samples to show in the scrolling bar graphs.
By default, the command derives this from the current console width.
.EXAMPLE
Out-PingStats google.com
Continuously monitors latency, loss, jitter, and latency distribution to google.com.
.EXAMPLE
Out-PingStats 1.1.1.1 -Title "Cloudflare DNS"
Monitors 1.1.1.1 and shows a custom title.
.EXAMPLE
Out-PingStats
Shows a rough live view of general Internet quality by probing several public hosts in parallel.
.EXAMPLE
Out-PingStats 8.8.8.8 -GraphMin 0 -GraphMax 100 -AggregationSeconds 60
Monitors 8.8.8.8 with fixed RTT graph limits and 1-minute aggregation windows.
.NOTES
This command starts background jobs and cleans them up when it exits.
It also writes temporary screen/statistics data files under $env:TEMP.
Loss, jitter, and percentile values are intended for operational monitoring, not for strict scientific measurement.
.OUTPUTS
None. This command is designed for interactive console display.
.INPUTS
None. This command does not accept pipeline input.
#>
# Re: colored printing
$ESC = [char]27
$COL_RST ="$ESC[0m"
$fr = 84; $fg = 255; $fb = 255; $COL_TITLE="$ESC[38;2;$fr;$fg;${Fb}m"
$fr = 107; $fg = 235; $fb = 163; $COL_H1 ="$ESC[38;2;$fr;$fg;${Fb}m"
$fr = 255; $fg = 0; $fb = 0; $col_hilite ="$ESC[38;2;$fr;$fg;${Fb}m"
$fr = 25; $fg = 163; $fb = 147; $COL_IMP_LOW="$ESC[38;2;$fr;$fg;${Fb}m"
# Most graph colors
$Br = 14; $Bg = 70; $Bb = 70
$fr = 243; $fg = 151; $fb = 214; $COL_GRAPH ="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$fr = 107; $fg = 235; $fb = 163; $COL_GRAPH_LOW ="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$fr = 0; $fg = 0; $fb = 0; $COL_GRAPH_EMPTY="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$fr = 255; $fg = 0; $fb = 0; $COL_GRAPH_HILITE ="$ESC[38;2;$fr;$fg;${Fb}m"
$Br = 243; $Bg = 151; $Bb = 214
$fr = 255; $fg = 0; $fb = 0; $COL_GRAPH_HI="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
# LOSS_BAR_GRAPH_THEME
$Br = 14; $Bg = 70; $Bb = 70
$fr = 255; $fg = 50; $fb = 80; $col_base ="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$fr = 107; $fg = 235; $fb = 163; $col_low ="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$fr = 0; $fg = 0; $fb = 0; $col_empty="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$fr = 255; $fg = 255; $fb = 0; $col_hilite ="$ESC[38;2;$fr;$fg;${Fb}m"
$Br = 255; $Bg = 50; $Bb = 80
$fr = 255; $fg = 255; $fb = 0; $col_HI="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$LOSS_BAR_GRAPH_THEME=@{base=$col_base;
low=$col_low;
empty=$col_empty;
hilite=$col_hilite;
HI=$col_HI
}
# RTTMIN_BAR_GRAPH_THEME
$Br = 14; $Bg = 70; $Bb = 70
$fr = 107; $fg = 235; $fb = 163; $col_base ="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$fr = 107; $fg = 235; $fb = 255; $col_low ="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$fr = 0; $fg = 0; $fb = 0; $col_empty="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$fr = 255; $fg = 0; $fb = 0; $col_hilite ="$ESC[38;2;$fr;$fg;${Fb}m"
$Br = 243; $Bg = 151; $Bb = 214
$fr = 255; $fg = 0; $fb = 0; $col_HI="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$RTTMIN_BAR_GRAPH_THEME=@{base=$col_base ;
low=$col_low ;
empty=$col_empty ;
hilite=$col_hilite ;
HI=$col_HI
}
# Jitter graph colors
$Br = 14; $Bg = 70; $Bb = 70
$fr = 200; $fg = 200; $fb = 200; $col_base ="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$fr = 107; $fg = 235; $fb = 163; $col_low ="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$fr = 0; $fg = 0; $fb = 0; $col_empty="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$fr = 255; $fg = 0; $fb = 0; $col_hilite ="$ESC[38;2;$fr;$fg;${Fb}m"
$Br = 243; $Bg = 151; $Bb = 214
$fr = 255; $fg = 0; $fb = 0; $col_HI="$esc[38;2;$Fr;$Fg;${Fb}m$esc[48;2;$Br;$Bg;${Bb}m"
$JITTER_BAR_GRAPH_THEME=@{base=$col_base ;
low=$col_low ;
empty=$col_empty ;
hilite=$col_hilite ;
HI=$col_HI
}
#----------------------------------------------------------------
# What chars to use to draw bars
#----------------------------------------------------------------
# HIGH RESOLUTION Use these, if you have rich fonts like deja vus
#-----------------------------------------------------------
# chars used to draw the horizontal bars
$HR_BAR_CHR_H_COUNT = 8
$HR_BAR_CHR_H_ = " " + `
[char]0x258F + [char]0x258E + [char]0x258D + [char]0x258C + `
[char]0x258B + [char]0x258A + [char]0x2589
$HR_BAR_CHR_FULL = [string][char]0x2589
# chars used to draw the vertical bars
$HR_BAR_CHR_V_COUNT = 8
$HR_BAR_CHR_V_ = '_' + `
[char]0x2581 + [char]0x2582 + [char]0x2583 + [char]0x2584 + `
[char]0x2585 + [char]0x2586 + [char]0x2587 + [char]0x2588
# LOW RESOLUTION Use these, for less rich fonts like consolas & courier
#-----------------------------------------------------------
# chars used to draw the horizontal bars
$LR_BAR_CHR_H_COUNT = 3
$LR_BAR_CHR_H_ = " " + [char]9612 + [char]9608
$LR_BAR_CHR_FULL = [string][char]9608
# chars used to draw the vertical bars # _‗₌▄◘█
$LR_BAR_CHR_V_COUNT = 5
$LR_BAR_CHR_V_ = '_' +[char]8215 +[char]8332 +[char]9604 +[char]9688 +[char]9608
#----------------------------------------------------------------
$TOTAL_RAM_MB = (Get-CimInstance -ClassName Win32_ComputerSystem).TotalPhysicalMemory / 1MB
$BarGraphSamples = $Host.UI.RawUI.WindowSize.Width - 6
$HistBucketsCount=10
$script:DebugMode=0
$script:AggPeriodSeconds = 0
$script:status = ""
<#
#################################################################################
# The code of Start-MultiPings is very close to this quick'n'dirty working code:
#################################################################################
echo "$(get-date -Format "hh:mm:ss") STARTING";
Start-Job -ScriptBlock { $hostn="127.0.0.1"; while ($true) {ping -t $hostn | sls "time[<=]" | %{ echo "$(get-date -UFormat %s ) $hostn $_"}}}
Start-Job -ScriptBlock {sleep 0.5; $hostn="127.0.0.1"; while ($true) {ping -t $hostn | sls "time[<=]" | %{ echo "$(get-date -UFormat %s ) $hostn $_"}}}
Start-Job -ScriptBlock { $hostn="1.1.1.1" ; while ($true) {ping -t $hostn | sls "time[<=]" | %{ echo "$(get-date -UFormat %s ) $hostn $_"}}}
Start-Job -ScriptBlock {sleep 0.1; $hostn="1.1.1.2" ; while ($true) {ping -t $hostn | sls "time[<=]" | %{ echo "$(get-date -UFormat %s ) $hostn $_"}}}
Start-Job -ScriptBlock {sleep 0.2; $hostn="8.8.8.8" ; while ($true) {ping -t $hostn | sls "time[<=]" | %{ echo "$(get-date -UFormat %s ) $hostn $_"}}}
Start-Job -ScriptBlock {sleep 0.3; $hostn="8.8.4.4" ; while ($true) {ping -t $hostn | sls "time[<=]" | %{ echo "$(get-date -UFormat %s ) $hostn $_"}}}
echo "$(get-date -Format "hh:mm:ss") MONITORING"; while ($true) {get-job | receive-job; sleep 1}
#>
Set-strictmode -version latest
filter isNumeric($x) {
return $x -is [int16] -or $x -is [int32] -or $x -is [int64] `
-or $x -is [uint16] -or $x -is [uint32] -or $x -is [uint64] `
-or $x -is [float] -or $x -is [double] -or $x -is [decimal]
}
function std_num_le($x) {
# select the maximum of these standard numbers that is
# Less-than or Equal to $x
# 1,2,5, 10,20,50, 100,200,500, 1000,2000,5000, ...
$power = [math]::floor([math]::log($x + 1, 10))
$candidate = [math]::pow(10, $power)
if ($candidate -gt $x) {$candidate = $candidate / 10}
if ($candidate*5 -le $x) {$candidate = $candidate * 5}
if ($candidate*2 -le $x) {$candidate = $candidate * 2}
$candidate
}
function std_num_ge($x) {
# select the maximum of these standard numbers that is
# Greater-than or Equal to $x
# 1.5, 3, 6, 9, 15, 30, 60, 90, 150, 300, 600, 900, ...
# I have no idead how this code works (yes I wrote it)
$power = [math]::ceiling([math]::log($x + 1, 10))
$candidate = [math]::pow(10, $power)
<# ^^^ these two lines do this magic:
The $candidate for $x= 9 is 10
The $candidate for $x= 10 is 100
The $candidate for $x= 20 is 100
The $candidate for $x= 90 is 100
The $candidate for $x=100 is 1000
... ...
#>
if (($candidate*1.5 -ge $x) -and ($candidate*0.9 -lt $x)) {return ($candidate * 1.5)}
if (($candidate*0.9 -ge $x) -and ($candidate*0.6 -lt $x)) {return ($candidate * 0.9)}
if (($candidate*0.6 -ge $x) -and ($candidate*0.3 -lt $x)) {return ($candidate * 0.6)}
if (($candidate*0.3 -ge $x) -and ($candidate*0.15 -lt $x)) {return ($candidate * 0.3)}
return ($candidate * 0.15)
}
function aprox_num($num) {
# rounds $num to "enough" decimals
# see get_enough_decimal_digits for understanding enough
try {
return [math]::round($num, (get_enough_decimal_digits $num))
} catch {
return "???"
}
}
function within_same_second($time1, $time2) {
# returns true if both times are within the same integer second
# (note that this is not always the same as being less than 1sec appart)
if ($time1.second -eq $time2.second) {
return ([math]::abs(($time2 - $time1).TotalSeconds) -lt 1)
} else {return $false}
}
function get_enough_decimal_digits($num) {
<#
Return how many decimal digits are "enough" for printing $num without
loosing too much precission. See examples
PS C:\> $num = 12.123456; [math]::round($num, (get_enough_decimal_digits $num))
12.12
PS C:\> $num = 123.123456; [math]::round($num, (get_enough_decimal_digits $num))
123.1
PS C:\> $num = 1234.123456; [math]::round($num, (get_enough_decimal_digits $num))
1234
PS C:\> $num = 1.123456; [math]::round($num, (get_enough_decimal_digits $num))
1.123
PS C:\> $num = 0.123456; [math]::round($num, (get_enough_decimal_digits $num))
0.123
PS C:\> $num = 0.0123456; [math]::round($num, (get_enough_decimal_digits $num))
0.0123
PS C:\> $num = 0.00123456; [math]::round($num, (get_enough_decimal_digits $num))
0.00123
#>
# how many digits do we need for the integer part
$integer_digits = ("{0}" -f [int]$num).length
if ($num -eq 0) {
$decimal_digits = 0
} elseif ([int]$num -eq 0) {
$decimal_digits = [math]::abs([math]::floor([math]::log10($num))) + 2
} elseif ($integer_digits -ge 4) {
# integer part is too large -- no decimals
$decimal_digits = 0
} else {
$decimal_digits = 4-$integer_digits
}
return $decimal_digits
}
function get_aprox_median($series){
# Returns the integer part of the median of $series after ignoring any 9999 items
# It returns 9999 if series is empty (or contains only 9999 items)
#
# Regarding "aprox": if $series has odd number of items we
# calculate the corect median but if it has even number of items
# we calculate an aproximation. Specificaly the value of the element
# just before the midle one instead of the average of that and the next one.
$sorted = [array]($series | ?{$_ -ne 9999} | sort-object)
if ($sorted) {
[int]$sorted[[int]($sorted.count/2)]
} else {
9999 # $series is empty or contains only 9999
}
}
function get_baseline($Baseline, $RTT_list){
# Calculates a "Baseline" given a series of RTTs and the current
# Baseline. The baseline will eventually be the minimum of all the values
# but if the minimum changes fast the baseline follows _slowly_
# If however the minimum strays too far from the baseline, baseline
# gets adjusted with one big step.
#
# (Remember that RTT values are "normalized" by getting moved towards the
# baseline so it's important for the baseline not to jitter around since
# that jitter will also appear on all the RTTs that follow it)
$old_Baseline = $Baseline
$calculated_baseline_now = ($RTT_list | ?{$_ -ne 9999} | measure -Minimum).Minimum
if ($Baseline -eq $null) {
# Initial value
$Baseline = $calculated_baseline_now
} elseif ([math]::abs($calculated_baseline_now - $old_Baseline) -gt 50) {
# Difference too big, we are forced to make a big jump :-(
Write-Verbose "get_baseline was forced to jump from $Baseline to $calculated_baseline_now"
$Baseline = $calculated_baseline_now
} elseif ($calculated_baseline_now -gt $old_Baseline) {
# we will jump by +1...4 msec
$Baseline += [math]::Ceiling(($calculated_baseline_now - $old_Baseline)/10)
} elseif ($calculated_baseline_now -lt $old_Baseline) {
# we will jump by -1...4 msec
$Baseline -= [math]::Ceiling(($old_Baseline - $calculated_baseline_now)/10)
}
return $Baseline
}
function stats_of_series($series){
# returns min, median, 95th percentile, max
# TODO median is not real median if $series has even number of elements
$sorted = [array]($series | sort-object)
$min = $sorted[0]
$p5_position = ([int]($sorted.count * 0.05) -1)
$p5_position = [math]::max(0, $p5_position)
$p5 = $sorted[$p5_position]
$median = $sorted[[int]($sorted.count/2)]
$p95_position = ([int]($sorted.count * 0.95) -1)
$p95_position = [math]::max(0, $p95_position)
$p95 = $sorted[$p95_position]
$max = $sorted[-1]
return @{
min = $min;
p5 = $p5;
median = $median;
p95 = $p95;
max = $max;
}
}
function p95_of_jitter($RTT_values){
# computes the 95th percentile of the jitter for the RTTs
# NOTE I CHOSE TO IGNORE LOST PACKETS
# (I could consider the jitter to also be 9999)
write-verbose "RTTs = $($RTT_values -join ',')"
$prev = $RTT_values | select -first 1
$jitter = @($RTT_values | select -last ($RTT_values.count -1) | %{
if (($_ -ne 9999) -and ($prev -ne 9999)) {
# /2 is a very rough approximation of oneway jitter.
# (rough because I assume that half the jitter is from sending
# the packet and half from receiving. That's not always true. E.g.
# if upload is satturated I can have a lot of jitter mostly while
# sending and hardly any while receiving.)
echo ([math]::round([math]::abs($_ - $prev)/2, 0))
}
$prev = $_
})
write-verbose "jitter = $($jitter -join ',')"
$p95 = (stats_of_series $jitter).p95
write-verbose "p95 of jitter = $p95"
return $p95
}
function Get-FontName {
if ([System.Environment]::OSVersion.Platform -like 'Win*') {
if ( -not ('Win32test.ConsoleTest' -as [type]) ) {
$defConsoleTest = @'
using System.Runtime.InteropServices;
using System;
namespace Win32test
{
public static class ConsoleTest
{
[DllImport( "kernel32.dll",
CharSet = CharSet.Unicode, SetLastError = true)]
extern static bool GetCurrentConsoleFontEx(
IntPtr hConsoleOutput,
bool bMaximumWindow,
ref CONSOLE_FONT_INFOEX lpConsoleCurrentFont);
private enum StdHandle
{
OutputHandle = -11 // The standard output device.
}
[DllImport("kernel32")]
private static extern IntPtr GetStdHandle(StdHandle index);
public static string GetFontName()
{
// Instantiating CONSOLE_FONT_INFOEX and setting cbsize
CONSOLE_FONT_INFOEX ConsoleFontInfo = new CONSOLE_FONT_INFOEX();
ConsoleFontInfo.cbSize = (uint)Marshal.SizeOf(ConsoleFontInfo);
GetCurrentConsoleFontEx( GetStdHandle(StdHandle.OutputHandle),
false,
ref ConsoleFontInfo);
return ConsoleFontInfo.FaceName ;
}
[StructLayout(LayoutKind.Sequential)]
private struct COORD
{
public short X;
public short Y;
public COORD(short x, short y)
{
X = x;
Y = y;
}
}
// learn.microsoft.com/en-us/windows/console/console-font-infoex
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct CONSOLE_FONT_INFOEX
{
public uint cbSize;
public uint nFont;
public COORD dwFontSize;
public int FontFamily;
public int FontWeight;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)]
public string FaceName;
}
}
}
'@
Add-Type -TypeDefinition $defConsoleTest
}
return [Win32test.ConsoleTest]::GetFontName()
} else {
# for non-windows OS I assume courier
return 'Courier'
}
}
function configure_graph_charset {
if ($script:HighResFont -eq -1) {
$font = (Get-FontName)
echo "Console uses font: $font"
$script:HighResFont=-not ($font -in @('courier','consolas'))
}
if (!($script:HighResFont)) {
echo "(Low resolution font)"
}
if ($script:HighResFont) {
$script:BAR_CHR_H_COUNT = $HR_BAR_CHR_H_COUNT
$script:BAR_CHR_H_ = $HR_BAR_CHR_H_
$script:BAR_CHR_FULL = $HR_BAR_CHR_FULL
$script:BAR_CHR_V_COUNT = $HR_BAR_CHR_V_COUNT
$script:BAR_CHR_V_ = $HR_BAR_CHR_V_
} else {
$script:BAR_CHR_H_COUNT = $LR_BAR_CHR_H_COUNT
$script:BAR_CHR_H_ = $LR_BAR_CHR_H_
$script:BAR_CHR_FULL = $LR_BAR_CHR_FULL
$script:BAR_CHR_V_COUNT = $LR_BAR_CHR_V_COUNT
$script:BAR_CHR_V_ = $LR_BAR_CHR_V_
}
}
function y_axis_max($min, $max, $y_min, $min_range) {
# select a Y-axis max
# for a graph with values from $min to $max
# having and Y-axis min of $y_min
# and requiring a range of at least $min_range
#
$y_max = (std_num_ge ([math]::max($y_min + $min_range, $max)))
if ($y_max -eq $y_min) {
$y_max = (std_num_ge ($y_max + 1))
}
return $y_max
}
function percent_to_bar($percent, $Chars_for_100perc) {
# used by render_histogram
try {
$float_length = [double]($percent/100*$Chars_for_100perc)
} catch {
return ""
}
$full_blocks = [int][Math]::floor($float_length)
$remeinder = [int]([Math]::floor(($float_length - [Math]::floor($float_length)) * $script:BAR_CHR_H_COUNT))
$eights = $script:BAR_CHR_H_[$remeinder]
$bar = $script:BAR_CHR_FULL * $full_blocks
if ($remeinder -ne 0) {$bar += $script:BAR_CHR_H_[$remeinder]}
return $bar
}
function series_to_histogram($y_values) {
# returns an array with the values of the histogram
$buckets = @(0..$HistBucketsCount)
For ($i=0; $i -le $HistBucketsCount; $i++) { $buckets[$i] = 0 }
$stats = (stats_of_series $y_values)
if ($GraphMin -eq -1) { # by default Y axis min is min
$y_min = [int]$stats.min
} else {
$y_min = $GraphMin
}
if ($GraphMax -eq -1) { # by default Y axis max is the 95 percentile + 10% but no more than 999
$y_max = [math]::min(999, [int]($stats.p95 * 1.1))
} else {
$y_max = $GraphMax
}
if ($y_max -lt ($y_min + $HistBucketsCount)) {$y_max = $y_min + $HistBucketsCount}
$y_values | %{
$ms = $_
if ($ms -eq 9999) {
$buckets[$HistBucketsCount] += 1 # $buckets[$HistBucketsCount] counts failures
} else {
# line about a reply
$norm_ms = [math]::min($y_max-1,[math]::max($y_min,$ms))
[double]$bucket = ($norm_ms-$y_min)/($y_max-$y_min)
[double]$bucket = [Math]::Floor($bucket*$HistBucketsCount)
#echo "$ms => +1 in bucket #$bucket"
$buckets[$bucket] += 1
}
}
return @($buckets, $y_min, $y_max)
}
function render_histogram($y_values) {
($buckets, $y_min, $y_max) = (series_to_histogram $y_values)
# the following fancy line makes sure I buckets divided exactly at integer values
$y_max = [math]::Ceiling(($y_max - $y_min) / $HistBucketsCount) * $HistBucketsCount + $y_min
#echo "HIST min=$y_min, max=$y_max "
[double]$perc_cumul = 0
[double]$max_perc = 0
For ($i=0; $i -le $HistBucketsCount; $i++) {
[double]$percent = [Math]::Round(100 * $buckets[$i] / $y_values.count,1)
$max_perc = [Math]::max($max_perc, $percent)
}
# 28 characters are available
# if max percent is 0.5 then by setting scale to 28/0.5=56 chars the 50% will fill 28 chars
$Chars_for_100perc = 28/($max_perc/100)
For ($i=0; $i -lt $HistBucketsCount; $i++) {
[double]$from = $y_min + $i * ($y_max-$y_min)/$HistBucketsCount
[double]$to = $y_min + ($i+1) * ($y_max-$y_min)/$HistBucketsCount
$count = $buckets[$i]
[double]$percent = [Math]::Round(100 * $buckets[$i] / $y_values.count,1)
$perc_cumul = [Math]::min(100, [Math]::Round($perc_cumul + $percent,1))
$max_perc = [Math]::max($max_perc, $percent)
if ($i -eq 0) {
$from_str="{0,3}" -f $y_min
$cumul_str=" Cumul"
} else {
$from_str="{0,3}" -f $from; $cumul_str=" {0,3}% " -f $perc_cumul
}
if ($i -eq ($HistBucketsCount - 1)) {
$to_str="MAX"
} else {
$to_str="{0,3}" -f $to
}
$bars = (percent_to_bar $percent $Chars_for_100perc)
$spaces = 28-($bars.length)
$spaces = " " * [math]::max(0,$spaces)
$bars = "{0}{1}" -f $bars, $spaces
"{0}...{1} $COL_IMP_LOW{2,4}$COL_RST {3,4}%$COL_IMP_LOW{4,5}$COL_GRAPH{5}$COL_RST" -f $from_str, $to_str, $count, $percent, $cumul_str, $bars
}
$failed_perc = $buckets[$HistBucketsCount] # failures
[double]$percent = [Math]::Round(100 * $failed_perc / ($y_values.count),1)
if ($percent -gt 0) {$color = $col_hilite} else {$color = $COL_H1}
"Failures: {0}{1,4} {2,4}% {3}{4}" -f $color, $failed_perc, $percent, (percent_to_bar $percent $Chars_for_100perc), $COL_RST
}
function render_bar_graph($y_values, $title="", $options="", $special_value, $default_y_min, $default_y_max, $theme) {
# It can display 24 or 25 different heights
# (25 if you count a zero height that gives an empty bar as an increment,
# 24 if you count only heights that give a visible line with "▁" being the lowest)
#
# - Everything except $y_values is optional
# - If you specify $col_base you must specify ALL other colors too
# - A special value of your choosing will be displayed... specially (***)
# - if $options contains "<H_grid>" you get horizontal grid lines
# - if $options contains "<min_no_color>" you get no coloring for when y=Y-axis-min
# - if $options contains "<stats>" then these special strings in $title:
# <min> <median> <p95> <p5> <max> <last>
# will be replaced with statistical info about y_values
# if (!(($y_values.pstypenames -eq 'System.Object[]') -or ($y_values.pstypenames -eq 'System.Collections.Queue'))) {return}
if (!($theme)) {
$col_base = $COL_GRAPH
$col_low = $COL_GRAPH_LOW
$col_empty = $COL_GRAPH_EMPTY
$col_hilite = $COL_GRAPH_HILITE
$col_hi = $COL_GRAPH_HI
} else {
$col_base = $theme.base
$col_low = $theme.low
$col_empty = $theme.empty
$col_hilite = $theme.hilite
$col_hi = $theme.hi
}
if (($options -like "*<stats>*") -or (($abs_min -eq $null) -and (($default_y_min -eq $null) -or ($default_y_max -eq $null)))) {
# calculate some statistical properties
# (we either need to display them or use them to calacl Y axis limits)
$stats = (stats_of_series $y_values)
($abs_min, $p5, $median, $p95, $abs_max) = ($stats.min, $stats.p5, $stats.median, $stats.p95, $stats.max)
}
if ($default_y_min -eq $null) {
# calculate a sensible Y axis min based on 5th percentile
$Y_min = [Math]::max($abs_min, $p5*0.9)
} else {
$Y_min = $default_y_min
}
if ($default_y_max -eq $null) {
# by default Y axis max is the 95 percentile + 10%
$Y_max = [int]($p95 * 1.1)
} else {
$Y_max = $default_y_max
}
if ($Y_min -eq $Y_max) {$Y_max = $Y_min + 1}
$Y_max_str = "{0,4}" -f $Y_max
$width = $Y_max_str.length
$Y_min_str = "{0,$width}" -f $Y_min
$width = $Y_min_str.length
$topline="{0,$width}|" -f $Y_max
$midline="{0,$width}|" -f " " # (($Y_min + $Y_max)/2)
$botline="{0,$width}|" -f $Y_min
$topline += $col_base
$midline += $col_base
$botline += $col_base
$Y_max = $Y_max + 0.1 # will make graphs like for 1,1,2,1,1 more beutiful
if ($options -like "*<H_grid>*") {$space = $col_empty + "_" + $col_base} else {$space = " "}
$y_values | %{
if ($_ -eq $special_value) {
$topline += $col_hilite + '*' + $col_base
$midline += $col_hilite + '*' + $col_base
$botline += $col_hilite + '*' + $col_base
} elseif ($_ -lt $Y_min ) {
$topline += $space
$midline += $space
$botline += $col_low + [char]0x25bc + $col_base
} elseif ($_ -eq $Y_min ) {
$topline += $space
$midline += $space
if ($options -like "*<min_no_color>*") {
$botline += $space
} else {
$botline += '_'
}
} else {
# 16__ __24
# | __17 |
# __9 || |
# 8__ | || |
# || |v v
# _0 |v v▁▂▃▄▅▆▇█
# | v▁▂▃▄▅▆▇█████████
# v▁▂▃▄▅▆▇█████████████████
# 0123456789012345678901234
$step = (($Y_max - $Y_min) / $script:BAR_CHR_V_COUNT / 3) # 3 lines
$quantized = [Math]::Round( ($_ - $Y_min) / $step, 0)
if ($quantized -gt (3 * $script:BAR_CHR_V_COUNT)) {
$topline += $col_hi + [char]0x25B2 + $col_base# '▲'
$midline += [char]0x2588 # '█'
$botline += [char]0x2588 # '█'
} elseif ($quantized -ge (2 * $script:BAR_CHR_V_COUNT)) {
$topline += $script:BAR_CHR_V_[$quantized - (2 * $script:BAR_CHR_V_COUNT) ]
$midline += [char]0x2588 # '█'
$botline += [char]0x2588 # '█'
} elseif ($quantized -ge (1 * $script:BAR_CHR_V_COUNT)) {
$topline += $space
$midline += $script:BAR_CHR_V_[$quantized - (1 * $script:BAR_CHR_V_COUNT) ]
$botline += [char]0x2588 # '█'
} else {
$topline += $space
$midline += $space
$botline += $script:BAR_CHR_V_[$quantized]
}
}
# echo "max=$Y_max min=$Y_min chars=$chars_max step=$step quantized=$quantized"
# echo "$topline<"
# echo "$midline<"
# echo "$botline<"
# echo ""
}
$topline += $COL_RST
$midline += $COL_RST
$botline += $COL_RST
# ($abs_min, $median, $p95, $abs_max)
if ($title) {
if ($options -like "*<stats>*") {
$abs_min = (aprox_num $abs_min)
$median = (aprox_num $median)
$p5 = (aprox_num $p5)
$p95 = (aprox_num $p95)
$abs_max = (aprox_num $abs_max)
$last = (aprox_num ($y_values | select -last 1))
$title = $title -replace "<min>", "$abs_min"
$title = $title -replace "<median>", "$median"
$title = $title -replace "<p5>", "$p5"
$title = $title -replace "<p95>", "$p95"
$title = $title -replace "<max>", "$abs_max"
$title = $title -replace "<last>", "$last"
}
$ticks = $('` '*[math]::ceiling($y_values.count/10))
if ($y_values.count % 10) {$ticks = $ticks.Substring(10 - $y_values.count % 10)}
}
echo "${COL_TITLE}$(" " * ($width)) $title${COL_RST}"
echo $topline
echo $midline
echo $botline
echo "${COL_TITLE}$(" " * ($width)) $ticks${COL_RST}"
# echo "Oldest-> $y_values"
}
function render_slow_updating_graphs() {
# describe the sampling period and the total time we collect samples
# e.g. per 2' for 14'
$AggPeriodDescr = "per $([math]::round($AggregationSeconds/60,1))' "+`
"for $([math]::round($AggregationSeconds*$p95_values.count/60,1))'"
# X axis limits
$MaxItems = $Host.UI.RawUI.WindowSize.Width - 6
# display $p95_values
#------------------------------
$values = @($p95_values | select -last $MaxItems)
$stats = (stats_of_series $values)
$y_min = 0
if ($GraphMax -ne -1) {$y_max = $GraphMax} else {
$y_max = (y_axis_max $stats.min $stats.max $y_min 10)
if ($y_max -eq $y_min) {$y_max = (std_num_ge $y_max + 1)}
if ($y_max -gt 300) {$y_max = 300} # 300msec is a high enough value
}
$title = "RTT 95th PERCENTILE, $AggPeriodDescr, min=<min>, p95=<p95>, max=<max>, last=<last> (ms)"
render_bar_graph $values $title "<stats><H_grid>" 9999 `
$y_min $y_max
if ($script:show_loss_graph) {
# display the lost% bar graph
#------------------------------
$stats = (stats_of_series $Loss_values)
$y_min = 0
# I used to allow for ymax = 24% but why bother?
# if you have more than 12% loss your line is seat(sic) anyway
# if ($stats.max -le 12) {$y_max = 12} else {$y_max = 24}
$y_max = 6 # 6% is a high enough value
$title = "LOSS%, $AggPeriodDescr, min=<min>%, p95=<p95>%, max=<max>%, last=<last>% (Ctrl-L)"
render_bar_graph @($Loss_values | select -last $MaxItems) $title "<stats><H_grid><min_no_color>" 100 `
$y_min $y_max $LOSS_BAR_GRAPH_THEME
}
if ($script:show_jitter_graph) {
# display the jitter bar graph
#------------------------------
$title = "ONE-WAY JITTER, $AggPeriodDescr, min=<min>, p95=<p95>, max=<max>, last=<last> (ms) (Ctrl-J)"
$stats = (stats_of_series $Jitter_values)
$y_min = 0
$y_max = 50 # 50msec is a high enough value
render_bar_graph @($Jitter_values | select -last $MaxItems) $title "<stats><H_grid>" $null `
$y_min $y_max $JITTER_BAR_GRAPH_THEME
}
}
function render_all($last_input, $PingsPerSec) {
While ([Console]::KeyAvailable) {
$keyInfo = [Console]::ReadKey($true)
if ($keyinfo.Key -eq 'H' -and $keyinfo.Modifiers -eq 'Control') {
$script:show_histogram = ! $script:show_histogram
clear # if show_ turns false we need to clear the whole screen
}
if ($keyinfo.Key -eq 'R' -and $keyinfo.Modifiers -eq 'Control') {
$script:show_real_time_graph = ! $script:show_real_time_graph
clear # if show_ turns false we need to clear the whole screen
}
if ($keyinfo.Key -eq 'L' -and $keyinfo.Modifiers -eq 'Control') {
$script:show_loss_graph = ! $script:show_loss_graph
clear # if show_ turns false we need to clear the whole screen
}
if ($keyinfo.Key -eq 'J' -and $keyinfo.Modifiers -eq 'Control') {
$script:show_jitter_graph = ! $script:show_jitter_graph
clear # if show_ turns false we need to clear the whole screen
}
if ($keyinfo.Key -eq 'S' -and $keyinfo.Modifiers -eq 'Control') {
$script:HighResFont = ! $script:HighResFont
configure_graph_charset
}
}
if (($BarGraphSamples -eq -1) -or (!(Test-Path variable:script:EffBarsThatFit))) {
$script:EffBarsThatFit = $Host.UI.RawUI.WindowSize.Width - 6
}
[long]$secs = [math]::ceiling(($(get-date) - $SamplingStart).TotalSeconds)
# display the header
$header = "$Title - $all_pings_cnt pings, $secs`", ~$($PingsPerSec)pings/s, " + `
"min=$all_min_RTT, max=$($all_max_RTT)ms, lost=$all_lost_cnt"
echo "$COL_H1$header$COL_RST"
#if ($last_input.Status -ne 'Success') {
# # instead of the status line show last failure in red
#echo "${col_hilite}Last ping failed: $($last_input.Status)$COL_RST"
#} else {
# # show status if any
# echo "$COL_IMP_LOW $($script:status)$COL_RST"
#}
# show $script:status if any
echo "$COL_IMP_LOW $($script:status)$COL_RST"
if ($script:show_real_time_graph) {
# display the RTT bar graph
$graph_values = @($RTT_values | select -last $script:EffBarsThatFit)
# decide Y axis limits
$graph_values_excl_999 = ($graph_values | ?{$_ -ne 9999})
if ($graph_values_excl_999) {
$stats = (stats_of_series $graph_values_excl_999)
} else {
$stats = @{min=0; p5=0; median=0; p95=0; max=0}
}
($time_graph_abs_min, $p5, $p95, $time_graph_abs_max) = ($stats.min, $stats.p5, $stats.p95, $stats.max)
$title = "LAST RTTs, $($graph_values.count) pings, min=$($stats.min), p95=$($stats.p95), max=$($stats.max), last=<last> (ms) (Ctrl-R)"
$y_min = (std_num_le $stats.min)
if ($y_min -lt 10) {$y_min = 0}
$max_to_show = $stats.p95
if ($stats.max -gt $stats.p95*3) {
$max_to_show = $stats.p95 * 3
} elseif (($stats.max -gt $stats.p95) -and ($stats.max -le $stats.p95*2)) {
$max_to_show = $stats.p95 * 2
} else {
$max_to_show = $stats.p95
}
$y_max = (y_axis_max $stats.min $max_to_show $y_min 9)
if ($y_max -gt 300) {$y_max = 300} # 300 is a high enough value
if ($y_min -ge $y_max) {$y_min = 0}
if ($GraphMin -ne -1) {$y_min = $GraphMin}
if ($GraphMax -ne -1) {$y_max = $GraphMax}
render_bar_graph $graph_values "$title" "<stats><H_grid>" 9999 $y_min $y_max
}
if ($script:show_histogram) {
# display the histogram
if ($RTT_values.count) {
#echo ([string][char]9472*75)
$p95 = [int](stats_of_series $RTT_values).p95
echo " ${COL_TITLE}RTT HISTOGRAM, last $HistSamples samples, p95=${COL_H1}${p95}${COL_TITLE}ms (Ctrl-H)$COL_RST"
render_histogram @($RTT_values | select -last $HistSamples)
#echo ""
}
}
if ($p95_values.count) {
render_slow_updating_graphs
if (Test-Path variable:script:SCREEN_DUMP_FILE) {
$filename = ($script:SCREEN_DUMP_FILE -replace ($env:TEMP -replace '\\','\\'), '$env:TEMP')
echo "$COL_IMP_LOW (Saving to $filename)"
}
$error = $null # empty $error which collects errors from pings
[gc]::Collect() # force garbage collection
} else {
echo "$($COL_IMP_LOW)You can use Ctrl-H,J,L,R to hide/show Graphs and -S to change font"
if (!($script:HighResFont)) {
echo "$($COL_IMP_LOW)We are using Low resolution characters (Ctrl-S to try high resolution)"
}
}
if ($script:DebugMode) {
#echo "AggPeriodSeconds=$script:AggPeriodSeconds"
#echo "p95_values=$p95_values"
echo "Jitter_values=$Jitter_values"
#sleep 0.1
}
$used_RAM_MB = (Get-Process -Id $PID).WorkingSet64 / 1MB
if ($used_RAM_MB -gt $TOTAL_RAM_MB/10) {
write-host -for red "WARNING: I am using $used_RAM_MB MBs of RAM"
if ($used_RAM_MB -gt $TOTAL_RAM_MB/4) {
throw "RAM usage exceeded 25%"
}
}
}
function append_to_pingtimes($ToSave_values, $file) {
# Record EVERY ping response to a text file named like:
# First line is
# pingrec-v1,2022-05-12,5 pings/sec,google.com
# Then we have one line per minute starting with the timestamp "hhmm:"
# Finaly one char per ping follows. The char is [char](ttl+34)
# (e.g. "A" for 33msec, "B" for 34msec...)
# Notably the time out is comming as a -1 value (not a 9999 value
# like in the rest of the code) and thus it is recorded as a "!"
$line = (get-date -format 'HHmm:')
$ToSave_values | %{
$line += [char]($_ + 34)
}
$line >> $file
}
function Format-PingTimes {
<#
.SYNOPSIS
Visualizes ping times in histogram and bar graphs
.DESCRIPTION
Pipe the output of Test-Connection to this cmdlet and it will present
the ping times in histograms and bar graphs.
You need a monospace font containing the unicode block characters: ▁▂▃▄▅▆▇█▉
DejaVu sans mono is good (Consolas is not)
.EXAMPLE
Test-Connection google.com -ping -Continuous | Format-PingTimes
.PARAMETER Items
Receives ping lines from standard input. Just pipe ping to this cmdlet and ignore this parameter.
#>
<#
If I need a color scale I can use color scales A) or B) from http://www.andrewnoske.com/wiki/Code_-_heatmaps_and_color_gradients
#>
[CmdletBinding()]
param (
[Parameter(ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[object[]]$Items,
[Parameter(Position=1)]
[string]$Property,
[string]$Title = "",
[string]$Target = "",