-
-
Notifications
You must be signed in to change notification settings - Fork 68
/
statsprinter.go
791 lines (678 loc) · 25.9 KB
/
statsprinter.go
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
package main
import (
"encoding/json"
"fmt"
"math"
"os"
"time"
"github.com/gookit/color"
)
const (
timeFormat = "2006-01-02 15:04:05"
hourFormat = "15:04:05"
)
// MARK: COLOR PRINTER
var (
colorYellow = color.Yellow.Printf
colorGreen = color.Green.Printf
colorRed = color.Red.Printf
colorCyan = color.Cyan.Printf
colorLightYellow = color.LightYellow.Printf
colorLightBlue = color.FgLightBlue.Printf
colorLightGreen = color.LightGreen.Printf
colorLightCyan = color.LightCyan.Printf
)
type colorPrinter struct {
showTimestamp *bool
}
func newColorPrinter(showTimestamp *bool) *colorPrinter {
return &colorPrinter{showTimestamp: showTimestamp}
}
func (p *colorPrinter) printStart(hostname string, port uint16) {
colorLightCyan("TCPinging %s on port %d\n", hostname, port)
}
func (p *colorPrinter) printStatistics(t tcping) {
totalPackets := t.totalSuccessfulProbes + t.totalUnsuccessfulProbes
packetLoss := (float32(t.totalUnsuccessfulProbes) / float32(totalPackets)) * 100
if math.IsNaN(float64(packetLoss)) {
packetLoss = 0
}
/* general stats */
if !t.destIsIP {
colorYellow("\n--- %s (%s) TCPing statistics ---\n", t.userInput.hostname, t.userInput.ip)
} else {
colorYellow("\n--- %s TCPing statistics ---\n", t.userInput.hostname)
}
colorYellow("%d probes transmitted on port %d | ", totalPackets, t.userInput.port)
colorYellow("%d received, ", t.totalSuccessfulProbes)
/* packet loss stats */
if packetLoss == 0 {
colorGreen("%.2f%%", packetLoss)
} else if packetLoss > 0 && packetLoss <= 30 {
colorLightYellow("%.2f%%", packetLoss)
} else {
colorRed("%.2f%%", packetLoss)
}
colorYellow(" packet loss\n")
/* successful packet stats */
colorYellow("successful probes: ")
colorGreen("%d\n", t.totalSuccessfulProbes)
/* unsuccessful packet stats */
colorYellow("unsuccessful probes: ")
colorRed("%d\n", t.totalUnsuccessfulProbes)
colorYellow("last successful probe: ")
if t.lastSuccessfulProbe.IsZero() {
colorRed("Never succeeded\n")
} else {
colorGreen("%v\n", t.lastSuccessfulProbe.Format(timeFormat))
}
colorYellow("last unsuccessful probe: ")
if t.lastUnsuccessfulProbe.IsZero() {
colorGreen("Never failed\n")
} else {
colorRed("%v\n", t.lastUnsuccessfulProbe.Format(timeFormat))
}
/* uptime and downtime stats */
colorYellow("total uptime: ")
colorGreen(" %s\n", durationToString(t.totalUptime))
colorYellow("total downtime: ")
colorRed("%s\n", durationToString(t.totalDowntime))
/* longest uptime stats */
if t.longestUptime.duration != 0 {
uptime := durationToString(t.longestUptime.duration)
colorYellow("longest consecutive uptime: ")
colorGreen("%v ", uptime)
colorYellow("from ")
colorLightBlue("%v ", t.longestUptime.start.Format(timeFormat))
colorYellow("to ")
colorLightBlue("%v\n", t.longestUptime.end.Format(timeFormat))
}
/* longest downtime stats */
if t.longestDowntime.duration != 0 {
downtime := durationToString(t.longestDowntime.duration)
colorYellow("longest consecutive downtime: ")
colorRed("%v ", downtime)
colorYellow("from ")
colorLightBlue("%v ", t.longestDowntime.start.Format(timeFormat))
colorYellow("to ")
colorLightBlue("%v\n", t.longestDowntime.end.Format(timeFormat))
}
/* resolve retry stats */
if !t.destIsIP {
colorYellow("retried to resolve hostname ")
colorRed("%d ", t.retriedHostnameLookups)
colorYellow("times\n")
if len(t.hostnameChanges) >= 2 {
colorYellow("IP address changes:\n")
for i := 0; i < len(t.hostnameChanges)-1; i++ {
colorYellow(" from ")
colorRed(t.hostnameChanges[i].Addr.String())
colorYellow(" to ")
colorGreen(t.hostnameChanges[i+1].Addr.String())
colorYellow(" at ")
colorLightBlue("%v\n", t.hostnameChanges[i+1].When.Format(timeFormat))
}
}
}
if t.rttResults.hasResults {
colorYellow("rtt ")
colorGreen("min")
colorYellow("/")
colorCyan("avg")
colorYellow("/")
colorRed("max: ")
colorGreen("%.3f", t.rttResults.min)
colorYellow("/")
colorCyan("%.3f", t.rttResults.average)
colorYellow("/")
colorRed("%.3f", t.rttResults.max)
colorYellow(" ms\n")
}
colorYellow("--------------------------------------\n")
colorYellow("TCPing started at: %v\n", t.startTime.Format(timeFormat))
/* If the program was not terminated, no need to show the end time */
if !t.endTime.IsZero() {
colorYellow("TCPing ended at: %v\n", t.endTime.Format(timeFormat))
}
durationTime := time.Time{}.Add(t.totalDowntime + t.totalUptime)
colorYellow("duration (HH:MM:SS): %v\n\n", durationTime.Format(hourFormat))
}
func (p *colorPrinter) printProbeSuccess(localAddr string, userInput userInput, streak uint, rtt float32) {
timestamp := ""
if *p.showTimestamp {
timestamp = time.Now().Format(timeFormat)
}
if userInput.hostname == "" {
if timestamp == "" {
if userInput.showLocalAddress {
colorLightGreen("Reply from %s on port %d using %s TCP_conn=%d time=%.3f ms\n", userInput.ip.String(), userInput.port, localAddr, streak, rtt)
} else {
colorLightGreen("Reply from %s on port %d TCP_conn=%d time=%.3f ms\n", userInput.ip.String(), userInput.port, streak, rtt)
}
} else {
if userInput.showLocalAddress {
colorLightGreen("%s Reply from %s on port %d using %s TCP_conn=%d time=%.3f ms\n", timestamp, userInput.ip.String(), userInput.port, localAddr, streak, rtt)
} else {
colorLightGreen("%s Reply from %s on port %d TCP_conn=%d time=%.3f ms\n", timestamp, userInput.ip.String(), userInput.port, streak, rtt)
}
}
} else {
if timestamp == "" {
if userInput.showLocalAddress {
colorLightGreen("Reply from %s (%s) on port %d using %s TCP_conn=%d time=%.3f ms\n", userInput.hostname, userInput.ip.String(), userInput.port, localAddr, streak, rtt)
} else {
colorLightGreen("Reply from %s (%s) on port %d TCP_conn=%d time=%.3f ms\n", userInput.hostname, userInput.ip.String(), userInput.port, streak, rtt)
}
} else {
if userInput.showLocalAddress {
colorLightGreen("%s Reply from %s (%s) on port %d using %s TCP_conn=%d time=%.3f ms\n", timestamp, userInput.hostname, userInput.ip.String(), userInput.port, localAddr, streak, rtt)
} else {
colorLightGreen("%s Reply from %s (%s) on port %d TCP_conn=%d time=%.3f ms\n", timestamp, userInput.hostname, userInput.ip.String(), userInput.port, streak, rtt)
}
}
}
}
func (p *colorPrinter) printProbeFail(userInput userInput, streak uint) {
timestamp := ""
if *p.showTimestamp {
timestamp = time.Now().Format(timeFormat)
}
if userInput.hostname == "" {
if timestamp == "" {
colorRed("No reply from %s on port %d TCP_conn=%d\n", userInput.ip, userInput.port, streak)
} else {
colorRed("%s No reply from %s on port %d TCP_conn=%d\n", timestamp, userInput.ip, userInput.port, streak)
}
} else {
if timestamp == "" {
colorRed("No reply from %s (%s) on port %d TCP_conn=%d\n", userInput.hostname, userInput.ip, userInput.port, streak)
} else {
colorRed("%s No reply from %s (%s) on port %d TCP_conn=%d\n", timestamp, userInput.hostname, userInput.ip, userInput.port, streak)
}
}
}
func (p *colorPrinter) printTotalDownTime(downtime time.Duration) {
colorYellow("No response received for %s\n", durationToString(downtime))
}
func (p *colorPrinter) printRetryingToResolve(hostname string) {
colorLightYellow("retrying to resolve %s\n", hostname)
}
func (p *colorPrinter) printInfo(format string, args ...any) {
colorLightBlue(format+"\n", args...)
}
func (p *colorPrinter) printError(format string, args ...any) {
colorRed(format+"\n", args...)
}
func (p *colorPrinter) printVersion() {
colorGreen("TCPING version %s\n", version)
}
// MARK: PLANE PRINTER
type planePrinter struct {
showTimestamp *bool
}
func newPlanePrinter(showTimestamp *bool) *planePrinter {
return &planePrinter{showTimestamp: showTimestamp}
}
func (p *planePrinter) printStart(hostname string, port uint16) {
fmt.Printf("TCPinging %s on port %d\n", hostname, port)
}
func (p *planePrinter) printStatistics(t tcping) {
totalPackets := t.totalSuccessfulProbes + t.totalUnsuccessfulProbes
packetLoss := (float32(t.totalUnsuccessfulProbes) / float32(totalPackets)) * 100
if math.IsNaN(float64(packetLoss)) {
packetLoss = 0
}
/* general stats */
if !t.destIsIP {
fmt.Printf("\n--- %s (%s) TCPing statistics ---\n", t.userInput.hostname, t.userInput.ip)
} else {
fmt.Printf("\n--- %s TCPing statistics ---\n", t.userInput.hostname)
}
fmt.Printf("%d probes transmitted on port %d | %d received", totalPackets, t.userInput.port, t.totalSuccessfulProbes)
/* packet loss stats */
fmt.Printf("%.2f%% packet loss\n", packetLoss)
/* successful packet stats */
fmt.Printf("successful probes: %d\n", t.totalSuccessfulProbes)
/* unsuccessful packet stats */
fmt.Printf("unsuccessful probes: %d\n", t.totalUnsuccessfulProbes)
fmt.Printf("last successful probe: ")
if t.lastSuccessfulProbe.IsZero() {
fmt.Printf("Never succeeded\n")
} else {
fmt.Printf("%v\n", t.lastSuccessfulProbe.Format(timeFormat))
}
fmt.Printf("last unsuccessful probe: ")
if t.lastUnsuccessfulProbe.IsZero() {
fmt.Printf("Never failed\n")
} else {
fmt.Printf("%v\n", t.lastUnsuccessfulProbe.Format(timeFormat))
}
/* uptime and downtime stats */
fmt.Printf("total uptime: %s\n", durationToString(t.totalUptime))
fmt.Printf("total downtime: %s\n", durationToString(t.totalDowntime))
/* longest uptime stats */
if t.longestUptime.duration != 0 {
uptime := durationToString(t.longestUptime.duration)
fmt.Printf("longest consecutive uptime: ")
fmt.Printf("%v ", uptime)
fmt.Printf("from %v ", t.longestUptime.start.Format(timeFormat))
fmt.Printf("to %v\n", t.longestUptime.end.Format(timeFormat))
}
/* longest downtime stats */
if t.longestDowntime.duration != 0 {
downtime := durationToString(t.longestDowntime.duration)
fmt.Printf("longest consecutive downtime: %v ", downtime)
fmt.Printf("from %v ", t.longestDowntime.start.Format(timeFormat))
fmt.Printf("to %v\n", t.longestDowntime.end.Format(timeFormat))
}
/* resolve retry stats */
if !t.destIsIP {
fmt.Printf("retried to resolve hostname %d times\n", t.retriedHostnameLookups)
if len(t.hostnameChanges) >= 2 {
fmt.Printf("IP address changes:\n")
for i := 0; i < len(t.hostnameChanges)-1; i++ {
fmt.Printf(" from %s", t.hostnameChanges[i].Addr.String())
fmt.Printf(" to %s", t.hostnameChanges[i+1].Addr.String())
fmt.Printf(" at %v\n", t.hostnameChanges[i+1].When.Format(timeFormat))
}
}
}
if t.rttResults.hasResults {
fmt.Printf("rtt min/avg/max: ")
fmt.Printf("%.3f/%.3f/%.3f ms\n", t.rttResults.min, t.rttResults.average, t.rttResults.max)
}
fmt.Printf("--------------------------------------\n")
fmt.Printf("TCPing started at: %v\n", t.startTime.Format(timeFormat))
/* If the program was not terminated, no need to show the end time */
if !t.endTime.IsZero() {
fmt.Printf("TCPing ended at: %v\n", t.endTime.Format(timeFormat))
}
durationTime := time.Time{}.Add(t.totalDowntime + t.totalUptime)
fmt.Printf("duration (HH:MM:SS): %v\n\n", durationTime.Format(hourFormat))
}
func (p *planePrinter) printProbeSuccess(localAddr string, userInput userInput, streak uint, rtt float32) {
timestamp := ""
if *p.showTimestamp {
timestamp = time.Now().Format(timeFormat)
}
if userInput.hostname == "" {
if timestamp == "" {
if userInput.showLocalAddress {
fmt.Printf("Reply from %s on port %d using %s TCP_conn=%d time=%.3f ms\n", userInput.ip.String(), userInput.port, localAddr, streak, rtt)
} else {
fmt.Printf("Reply from %s on port %d TCP_conn=%d time=%.3f ms\n", userInput.ip.String(), userInput.port, streak, rtt)
}
} else {
if userInput.showLocalAddress {
fmt.Printf("%s Reply from %s on port %d using %s TCP_conn=%d time=%.3f ms\n", timestamp, userInput.ip.String(), userInput.port, localAddr, streak, rtt)
} else {
fmt.Printf("%s Reply from %s on port %d TCP_conn=%d time=%.3f ms\n", timestamp, userInput.ip.String(), userInput.port, streak, rtt)
}
}
} else {
if timestamp == "" {
if userInput.showLocalAddress {
fmt.Printf("Reply from %s (%s) on port %d using %s TCP_conn=%d time=%.3f ms\n", userInput.hostname, userInput.ip.String(), userInput.port, localAddr, streak, rtt)
} else {
fmt.Printf("Reply from %s (%s) on port %d TCP_conn=%d time=%.3f ms\n", userInput.hostname, userInput.ip.String(), userInput.port, streak, rtt)
}
} else {
if userInput.showLocalAddress {
fmt.Printf("%s Reply from %s (%s) on port %d using %s TCP_conn=%d time=%.3f ms\n", timestamp, userInput.hostname, userInput.ip.String(), userInput.port, localAddr, streak, rtt)
} else {
fmt.Printf("%s Reply from %s (%s) on port %d TCP_conn=%d time=%.3f ms\n", timestamp, userInput.hostname, userInput.ip.String(), userInput.port, streak, rtt)
}
}
}
}
func (p *planePrinter) printProbeFail(userInput userInput, streak uint) {
timestamp := ""
if *p.showTimestamp {
timestamp = time.Now().Format(timeFormat)
}
if userInput.hostname == "" {
if timestamp == "" {
fmt.Printf("No reply from %s on port %d TCP_conn=%d\n", userInput.ip, userInput.port, streak)
} else {
fmt.Printf("%s No reply from %s on port %d TCP_conn=%d\n", timestamp, userInput.ip, userInput.port, streak)
}
} else {
if timestamp == "" {
fmt.Printf("No reply from %s (%s) on port %d TCP_conn=%d\n", userInput.hostname, userInput.ip, userInput.port, streak)
} else {
fmt.Printf("%s No reply from %s (%s) on port %d TCP_conn=%d\n", timestamp, userInput.hostname, userInput.ip, userInput.port, streak)
}
}
}
func (p *planePrinter) printTotalDownTime(downtime time.Duration) {
fmt.Printf("No response received for %s\n", durationToString(downtime))
}
func (p *planePrinter) printRetryingToResolve(hostname string) {
fmt.Printf("retrying to resolve %s\n", hostname)
}
func (p *planePrinter) printInfo(format string, args ...any) {
fmt.Printf(format+"\n", args...)
}
func (p *planePrinter) printError(format string, args ...any) {
fmt.Printf(format+"\n", args...)
}
func (p *planePrinter) printVersion() {
fmt.Printf("TCPING version %s\n", version)
}
// MARK: JSON PRINTER
type jsonPrinter struct {
e *json.Encoder
}
func newJSONPrinter(withIndent bool) *jsonPrinter {
encoder := json.NewEncoder(os.Stdout)
if withIndent {
encoder.SetIndent("", "\t")
}
return &jsonPrinter{e: encoder}
}
// print is a little helper method for p.e.Encode.
// at also sets data.Timestamp to Now().
func (p *jsonPrinter) print(data JSONData) {
data.Timestamp = time.Now()
p.e.Encode(data)
}
// JSONEventType is a special type, each for each method
// in the printer interface so that automatic tools
// can understand what kind of an event they've received.
type JSONEventType string
const (
// startEvent is an event type for [printStart] method.
startEvent JSONEventType = "start"
// probeEvent is a general event type for both
// [printProbeSuccess] and [printProbeFail].
probeEvent JSONEventType = "probe"
// retryEvent is an event type for [printRetryingToResolve] method.
retryEvent JSONEventType = "retry"
// retrySuccessEvent is an event type for [printTotalDowntime] method.
retrySuccessEvent JSONEventType = "retry-success"
// statisticsEvent is a event type for [printStatistics] method.
statisticsEvent JSONEventType = "statistics"
// infoEvent is a event type for [printInfo] method.
infoEvent JSONEventType = "info"
// versionEvent is a event type for [printVersion] method.
versionEvent JSONEventType = "version"
// errorEvent is a event type for [printError] method.
errorEvent JSONEventType = "error"
)
// JSONData contains all possible fields for JSON output.
// Because one event usually contains only a subset of fields,
// other fields will be omitted in the output.
type JSONData struct {
// Type is a mandatory field that specifies type of a message/event.
Type JSONEventType `json:"type"`
// Message contains a human-readable message.
Message string `json:"message"`
// Timestamp contains data when a message was sent.
Timestamp time.Time `json:"timestamp"`
// Optional fields below
Addr string `json:"addr,omitempty"`
LocalAddr string `json:"local_address,omitempty"`
Hostname string `json:"hostname,omitempty"`
HostnameResolveTries uint `json:"hostname_resolve_tries,omitempty"`
HostnameChanges []hostnameChange `json:"hostname_changes,omitempty"`
DestIsIP *bool `json:"dst_is_ip,omitempty"`
Port uint16 `json:"port,omitempty"`
Rtt float32 `json:"time,omitempty"`
// Success is a special field from probe messages, containing information
// whether request was successful or not.
// It's a pointer on purpose, otherwise success=false will be omitted,
// but we still need to omit it for non-probe messages.
Success *bool `json:"success,omitempty"`
// Latency in ms for a successful probe messages.
Latency float32 `json:"latency,omitempty"`
// LatencyMin is a latency stat for the stats event.
//
// It's a string on purpose, as we'd like to have exactly
// 3 decimal places without doing extra math.
LatencyMin string `json:"latency_min,omitempty"`
// LatencyAvg is a latency stat for the stats event.
//
// It's a string on purpose, as we'd like to have exactly
// 3 decimal places without doing extra math.
LatencyAvg string `json:"latency_avg,omitempty"`
// LatencyMax is a latency stat for the stats event.
//
// It's a string on purpose, as we'd like to have exactly
// 3 decimal places without doing extra math.
LatencyMax string `json:"latency_max,omitempty"`
// TotalDuration is a total amount of seconds that program was running.
//
// It's a string on purpose, as we'd like to have exactly
// 3 decimal places without doing extra math.
TotalDuration string `json:"total_duration,omitempty"`
// StartTimestamp is used as a start time of TotalDuration for stats messages.
StartTimestamp *time.Time `json:"start_timestamp,omitempty"`
// EndTimestamp is used as an end of TotalDuration for stats messages.
EndTimestamp *time.Time `json:"end_timestamp,omitempty"`
LastSuccessfulProbe *time.Time `json:"last_successful_probe,omitempty"`
LastUnsuccessfulProbe *time.Time `json:"last_unsuccessful_probe,omitempty"`
// LongestUptime in seconds.
//
// It's a string on purpose, as we'd like to have exactly
// 3 decimal places without doing extra math.
LongestUptime string `json:"longest_uptime,omitempty"`
LongestUptimeEnd *time.Time `json:"longest_uptime_end,omitempty"`
LongestUptimeStart *time.Time `json:"longest_uptime_start,omitempty"`
// LongestDowntime in seconds.
//
// It's a string on purpose, as we'd like to have exactly
// 3 decimal places without doing extra math.
LongestDowntime string `json:"longest_downtime,omitempty"`
LongestDowntimeEnd *time.Time `json:"longest_downtime_end,omitempty"`
LongestDowntimeStart *time.Time `json:"longest_downtime_start,omitempty"`
// TotalPacketLoss in seconds.
//
// It's a string on purpose, as we'd like to have exactly
// 3 decimal places without doing extra math.
TotalPacketLoss string `json:"total_packet_loss,omitempty"`
TotalPackets uint `json:"total_packets,omitempty"`
TotalSuccessfulProbes uint `json:"total_successful_probes,omitempty"`
TotalUnsuccessfulProbes uint `json:"total_unsuccessful_probes,omitempty"`
// TotalUptime in seconds.
TotalUptime float64 `json:"total_uptime,omitempty"`
// TotalDowntime in seconds.
TotalDowntime float64 `json:"total_downtime,omitempty"`
}
// printStart prints the initial message before doing probes.
func (p *jsonPrinter) printStart(hostname string, port uint16) {
p.print(JSONData{
Type: startEvent,
Message: fmt.Sprintf("TCPinging %s on port %d", hostname, port),
Hostname: hostname,
Port: port,
})
}
// printReply prints TCP probe replies according to our policies in JSON format.
func (p *jsonPrinter) printProbeSuccess(localAddr string, userInput userInput, streak uint, rtt float32) {
var (
// for *bool fields
f = false
t = true
data = JSONData{
Type: probeEvent,
Hostname: userInput.hostname,
Addr: userInput.ip.String(),
Port: userInput.port,
Rtt: rtt,
DestIsIP: &t,
Success: &t,
TotalSuccessfulProbes: streak,
}
)
if userInput.showLocalAddress {
data.LocalAddr = localAddr
}
if userInput.hostname != "" {
data.DestIsIP = &f
if userInput.showLocalAddress {
data.Message = fmt.Sprintf("Reply from %s (%s) on port %d using %s time=%.3f ms",
userInput.hostname, userInput.ip.String(), userInput.port, localAddr, rtt)
} else {
data.Message = fmt.Sprintf("Reply from %s (%s) on port %d time=%.3f ms",
userInput.hostname, userInput.ip.String(), userInput.port, rtt)
}
} else {
if userInput.showLocalAddress {
data.Message = fmt.Sprintf("Reply from %s on port %d using %s time=%.3f ms",
userInput.ip.String(), userInput.port, localAddr, rtt)
} else {
data.Message = fmt.Sprintf("Reply from %s on port %d time=%.3f ms",
userInput.ip.String(), userInput.port, rtt)
}
}
p.print(data)
}
func (p *jsonPrinter) printProbeFail(userInput userInput, streak uint) {
var (
// for *bool fields
f = false
t = true
data = JSONData{
Type: probeEvent,
Hostname: userInput.hostname,
Addr: userInput.ip.String(),
Port: userInput.port,
DestIsIP: &t,
Success: &f,
TotalUnsuccessfulProbes: streak,
}
)
if userInput.hostname != "" {
data.DestIsIP = &f
data.Message = fmt.Sprintf("No reply from %s (%s) on port %d",
userInput.hostname, userInput.ip.String(), userInput.port)
} else {
data.Message = fmt.Sprintf("No reply from %s on port %d",
userInput.ip.String(), userInput.port)
}
p.print(data)
}
// printStatistics prints all gathered stats when program exits.
func (p *jsonPrinter) printStatistics(t tcping) {
data := JSONData{
Type: statisticsEvent,
Message: fmt.Sprintf("stats for %s", t.userInput.hostname),
Addr: t.userInput.ip.String(),
Hostname: t.userInput.hostname,
StartTimestamp: &t.startTime,
TotalDowntime: t.totalDowntime.Seconds(),
TotalPackets: t.totalSuccessfulProbes + t.totalUnsuccessfulProbes,
TotalSuccessfulProbes: t.totalSuccessfulProbes,
TotalUnsuccessfulProbes: t.totalUnsuccessfulProbes,
TotalUptime: t.totalUptime.Seconds(),
}
if len(t.hostnameChanges) > 1 {
data.HostnameChanges = t.hostnameChanges
}
loss := (float32(data.TotalUnsuccessfulProbes) / float32(data.TotalPackets)) * 100
if math.IsNaN(float64(loss)) {
loss = 0
}
data.TotalPacketLoss = fmt.Sprintf("%.2f", loss)
if !t.lastSuccessfulProbe.IsZero() {
data.LastSuccessfulProbe = &t.lastSuccessfulProbe
}
if !t.lastUnsuccessfulProbe.IsZero() {
data.LastUnsuccessfulProbe = &t.lastUnsuccessfulProbe
}
if t.longestUptime.duration != 0 {
data.LongestUptime = fmt.Sprintf("%.0f", t.longestUptime.duration.Seconds())
data.LongestUptimeStart = &t.longestUptime.start
data.LongestUptimeEnd = &t.longestUptime.end
}
if t.longestDowntime.duration != 0 {
data.LongestDowntime = fmt.Sprintf("%.0f", t.longestDowntime.duration.Seconds())
data.LongestDowntimeStart = &t.longestDowntime.start
data.LongestDowntimeEnd = &t.longestDowntime.end
}
if !t.destIsIP {
data.HostnameResolveTries = t.retriedHostnameLookups
}
if t.rttResults.hasResults {
data.LatencyMin = fmt.Sprintf("%.3f", t.rttResults.min)
data.LatencyAvg = fmt.Sprintf("%.3f", t.rttResults.average)
data.LatencyMax = fmt.Sprintf("%.3f", t.rttResults.max)
}
if !t.endTime.IsZero() {
data.EndTimestamp = &t.endTime
}
totalDuration := t.totalDowntime + t.totalUptime
data.TotalDuration = fmt.Sprintf("%.0f", totalDuration.Seconds())
p.print(data)
}
// printTotalDownTime prints the total downtime,
// if the next retry was successful.
func (p *jsonPrinter) printTotalDownTime(downtime time.Duration) {
p.print(JSONData{
Type: retrySuccessEvent,
Message: fmt.Sprintf("no response received for %s", durationToString(downtime)),
TotalDowntime: downtime.Seconds(),
})
}
// printRetryingToResolve print the message retrying to resolve,
// after n failed probes.
func (p *jsonPrinter) printRetryingToResolve(hostname string) {
p.print(JSONData{
Type: retryEvent,
Message: fmt.Sprintf("retrying to resolve %s", hostname),
Hostname: hostname,
})
}
func (p *jsonPrinter) printInfo(format string, args ...any) {
p.print(JSONData{
Type: infoEvent,
Message: fmt.Sprintf(format, args...),
})
}
func (p *jsonPrinter) printError(format string, args ...any) {
p.print(JSONData{
Type: errorEvent,
Message: fmt.Sprintf(format, args...),
})
}
func (p *jsonPrinter) printVersion() {
p.print(JSONData{
Type: versionEvent,
Message: fmt.Sprintf("TCPING version %s\n", version),
})
}
// durationToString creates a human-readable string for a given duration
func durationToString(duration time.Duration) string {
hours := math.Floor(duration.Hours())
if hours > 0 {
duration -= time.Duration(hours * float64(time.Hour))
}
minutes := math.Floor(duration.Minutes())
if minutes > 0 {
duration -= time.Duration(minutes * float64(time.Minute))
}
seconds := duration.Seconds()
switch {
// Hours
case hours >= 2:
return fmt.Sprintf("%.0f hours %.0f minutes %.0f seconds", hours, minutes, seconds)
case hours == 1 && minutes == 0 && seconds == 0:
return fmt.Sprintf("%.0f hour", hours)
case hours == 1:
return fmt.Sprintf("%.0f hour %.0f minutes %.0f seconds", hours, minutes, seconds)
// Minutes
case minutes >= 2:
return fmt.Sprintf("%.0f minutes %.0f seconds", minutes, seconds)
case minutes == 1 && seconds == 0:
return fmt.Sprintf("%.0f minute", minutes)
case minutes == 1:
return fmt.Sprintf("%.0f minute %.0f seconds", minutes, seconds)
// Seconds
case seconds == 0 || seconds == 1 || seconds >= 1 && seconds < 1.1:
return fmt.Sprintf("%.0f second", seconds)
case seconds < 1:
return fmt.Sprintf("%.1f seconds", seconds)
default:
return fmt.Sprintf("%.0f seconds", seconds)
}
}