-
Notifications
You must be signed in to change notification settings - Fork 0
/
pingo.go
1693 lines (1433 loc) · 42.2 KB
/
pingo.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
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
package main
// Pingo is a small & light go-based tool for IP reachability administration tasks with rich user interface.
// Version : 1.0.0
// Author : Jerome AMON
// Created : 19 November 2021
import (
"bufio"
"context"
"fmt"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/jroimartin/gocui"
)
const (
IPLIST = "ips"
STATS = "stats"
INFOS = "infos"
CONFIG = "config"
OUTPUTS = "outputs"
HELP = "help"
IPSWIDTH = 22
HWIDTH = 46
HHEIGHT = 35
)
const helpDetails = `
-------------+------------------------------
CTRL + A | add multiple ip addresses
-------------+------------------------------
CTRL + D | delete focused ip address
-------------+------------------------------
CTRL + E | edit focused ip's configs
-------------+------------------------------
CTRL + F | search an ip and focus on
-------------+------------------------------
CTRL + L | load & add ip from files
-------------+------------------------------
CTRL + Q | close help or stop action
-------------+------------------------------
CTRL + P | start pinging focused ip
-------------+------------------------------
CTRL + R | clear outputs view content
-------------+------------------------------
CTRL + T | traceroute the focused ip
-------------+------------------------------
F1 & Esc | display or close help view
-------------+------------------------------
<Enter> | start pinging focused ip
-------------+------------------------------
P or T | Ping or Trace focused ip
-------------+------------------------------
Tab Key | move focus between views
-------------+------------------------------
↕ and ↔ | navigate into the IP list
-------------+------------------------------
CTRL + C | close the full program
-------------+------------------------------
::::::: Crafted with ♥ by Jerome Amon ::::::
`
type config struct {
start string
requests int
threshold int
timeout int
size int
backup bool
}
type stat struct {
min int
avg int
max int
fails int
match int
above int
under int
}
var (
// global datastore.
dbs *databases
// cursor Y line.
focusedIPChan = make(chan string, 10)
// IP to ping and to trace.
ipToPingChan = make(chan string, 1)
ipToTraceChan = make(chan string, 1)
// keep ongoing pinging IP, useful to
// avoid its deletion on CTRL+D.
currentOnPingIP string
// ping and traceroute output entries.
outputsDataChan = make(chan string, 10)
// ping output entries for statistics.
outputsStatsChan = make(chan string, 10)
clearStatsViewChan = make(chan struct{})
// cleanup outputs view.
clearOutputsViewChan = make(chan struct{})
// stop ongoing processing (ping or trace).
stopProcessingChan = make(chan struct{})
// custom title of output view.
outputsTitleChan = make(chan string, 1)
// control all goroutines.
exit = make(chan struct{})
wg sync.WaitGroup
LinuxShell = "/bin/sh"
)
// struct of a datastore.
type databases struct {
ips map[string]struct{}
configs map[string]*config
stats map[string]*stat
ipslock *sync.RWMutex
cfglock *sync.RWMutex
slock *sync.RWMutex
}
// newDatabases creates new databases.
func newDatabases() *databases {
return &databases{
ips: map[string]struct{}{},
configs: make(map[string]*config),
stats: make(map[string]*stat),
ipslock: &sync.RWMutex{},
cfglock: &sync.RWMutex{},
slock: &sync.RWMutex{},
}
}
// isExists checks if given ip exists.
func (db *databases) isExistsIP(ip string) bool {
// check if ip is present.
db.ipslock.RLock()
if _, ok := db.ips[ip]; ok {
db.ipslock.RUnlock()
return true
}
db.ipslock.RUnlock()
return false
}
// addOneMoreIPs take a string of comma-separated IPs and
// initialize their configs & stats then add them.
func (db *databases) addOneMoreIPs(ips string) {
ipList := strings.Split(ips, ",")
if len(ipList) == 0 {
return
}
for _, ip := range ipList {
db.addNewIP(ip)
}
}
// addNewIP inserts a new ip with its initial configs & stats.
func (db *databases) addNewIP(ip string) {
ip = strings.TrimSpace(ip)
if !isValidIP(ip) || db.isExistsIP(ip) {
return
}
db.addIP(ip)
db.addConfig(ip)
db.initStats(ip)
}
// addIP inserts a new ip with empty struct as value.
func (db *databases) addIP(ip string) {
db.ipslock.Lock()
db.ips[ip] = struct{}{}
db.ipslock.Unlock()
}
// addConfig inserts a new ip with 0 values as initial configs.
func (db *databases) addConfig(ip string) {
db.cfglock.Lock()
db.configs[ip] = &config{start: "n/a"}
db.cfglock.Unlock()
}
// updateConfig replace the existing configs values of an ip by new ones.
func (db *databases) updateConfig(ip string, cfg *config) {
db.cfglock.Lock()
db.configs[ip] = cfg
db.cfglock.Unlock()
}
// initStats initialize an ip with 0 values as initial stats.
func (db *databases) initStats(ip string) {
db.slock.Lock()
db.stats[ip] = &stat{}
db.slock.Unlock()
}
// getJob retrieves a given job data based on its id from jobs store.
func (db *databases) getConfig(ip string) *config {
var cfg *config
db.cfglock.RLock()
cfg = db.configs[ip]
db.cfglock.RUnlock()
return cfg
}
// getAction retrieves a given action data based on its id from actions store.
func (db *databases) getStats(ip string) *stat {
var s *stat
db.slock.RLock()
s = db.stats[ip]
db.slock.RUnlock()
return s
}
// getAllIPs returns a sorted (by length) list of current IPs.
func (db *databases) getAllIPs() []string {
dbs.ipslock.RLock()
ips := make([]string, 0, len(dbs.ips))
for ip, _ := range dbs.ips {
ips = append(ips, ip)
}
dbs.ipslock.RUnlock()
sort.Strings(ips)
sort.SliceStable(ips, func(i, j int) bool {
return len(ips[i]) < len(ips[j])
})
return ips
}
// deleteOneMoreIPs take a string of comma-separated IPs
// and remove them completely from the database.
func (db *databases) deleteOneMoreIPs(ips string) {
ipList := strings.Split(ips, ",")
if len(ipList) == 0 {
return
}
for _, ip := range ipList {
if ip == currentOnPingIP {
continue
}
db.deleteIP(ip)
}
}
// deleteIP remove completely an ip from datastore.
func (db *databases) deleteIP(ip string) {
ip = strings.TrimSpace(ip)
if !isValidIP(ip) || !db.isExistsIP(ip) {
return
}
// remove from ips.
db.ipslock.Lock()
delete(db.ips, ip)
db.ipslock.Unlock()
// remove from configs.
db.cfglock.Lock()
delete(db.configs, ip)
db.cfglock.Unlock()
// remove from stats.
db.slock.Lock()
delete(db.stats, ip)
db.slock.Unlock()
}
// isValidIP returns true if ip is valid.
func isValidIP(ip string) bool {
return net.ParseIP(ip) != nil
}
// formatIPConfig formats a given IP configuration.
func (db *databases) formatIPConfig(ip string) string {
cfg := db.getConfig(ip)
return fmt.Sprintf("backup : %v\ntimeout : %d\nstarted : %s\nrequests : %d\npkts size: %d\nthreshold: %d",
cfg.backup, cfg.timeout, cfg.start, cfg.requests, cfg.size, cfg.threshold)
}
// formatIPStats formats a given IP statistics.
func (db *databases) formatIPStats(ip string) string {
s := db.getStats(ip)
return fmt.Sprintf("min : %d\navg : %d\nmax : %d\nfails: %d\nmatch: %d\nabove: %d\nunder: %d\n",
s.min, s.avg, s.max, s.fails, s.match, s.above, s.under)
}
// loadInitialInfos is called at startup and loads any data piped
// and from all files passed as arguments then fill the databases
// of IP infos with only valid IP addresses.
func (db *databases) loadInitialInfos() {
// retrieve standard input info.
fi, _ := os.Stdin.Stat()
if (fi.Mode() & os.ModeCharDevice) == 0 {
var entries []string
// there is data from pipe input, so grab the
// full content and build a list of entries.
content, _ := ioutil.ReadAll(os.Stdin)
entries = strings.Split(string(content), "\n")
// keep only valid IP addresses.
for _, e := range entries {
if isValidIP(strings.TrimSpace(e)) {
db.addNewIP(strings.TrimSpace(e))
}
}
}
// parse any files content.
db.loadInfosFromFiles(os.Args[1:])
}
// loadInfosFromFiles loads data from all files passed as
// input on <CTRL+L> press and fill the databases of IP infos
// with only valid IP addresses.
func (db *databases) loadInfosFromFiles(filenames []string) {
if len(filenames) == 0 {
return
}
// for each valid file path, grab its full
// content and build a list of entries.
var lines []string
var entries []string
for _, file := range filenames {
content, err := ioutil.ReadFile(file)
if err != nil {
continue
}
// construct the list based on "\n" as sep.
// then add lines content to entries list.
lines = strings.Split(string(content), "\n")
entries = append(entries, lines...)
}
if len(entries) == 0 {
// no data input.
return
}
// keep only valid IP addresses.
for _, e := range entries {
if isValidIP(strings.TrimSpace(e)) {
db.addNewIP(strings.TrimSpace(e))
}
}
}
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
// on windows only change terminal title.
if runtime.GOOS == "windows" {
exec.Command("cmd", "/c", "title [ PinGo By Jerome Amon ]").Run()
}
f, err := os.OpenFile("logs.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Println("failed to create logs file.")
}
defer f.Close()
log.SetFlags(log.LstdFlags | log.Lshortfile)
log.SetOutput(f)
// for linux-based platform lets find the current shell binary path
// if environnement shell is set and not empty we use it as default.
if runtime.GOOS != "windows" {
if len(os.Getenv("SHELL")) > 0 {
LinuxShell = os.Getenv("SHELL")
}
}
// init databases and loads any passed infos.
dbs = newDatabases()
dbs.loadInitialInfos()
g, err := gocui.NewGui(gocui.OutputNormal)
if err != nil {
log.Println("Failed to initialize the gui:", err)
return
}
defer g.Close()
g.Highlight = true
g.SelFgColor = gocui.ColorRed
g.BgColor = gocui.ColorBlack
g.FgColor = gocui.ColorWhite
g.InputEsc = true
// g.Mouse = true
g.Cursor = false
g.SetManagerFunc(layout)
err = g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit)
if err != nil {
log.Println("Could not set key [CtrlC] binding to main view:", err)
return
}
maxX, maxY := g.Size()
// IPs list view.
ipsView, err := g.SetView(IPLIST, 0, 0, IPSWIDTH, maxY-19)
if err != nil && err != gocui.ErrUnknownView {
log.Println("Failed to create ips list view:", err)
return
}
ipsView.Title = " IP Addresses "
ipsView.FgColor = gocui.ColorYellow
ipsView.SelBgColor = gocui.ColorGreen
ipsView.SelFgColor = gocui.ColorBlack
ipsView.Highlight = true
// Outputs view.
outputsView, err := g.SetView(OUTPUTS, IPSWIDTH+1, 0, maxX-1, maxY-1)
if err != nil && err != gocui.ErrUnknownView {
log.Println("Failed to create outputs view:", err)
return
}
outputsView.Title = " Ping Outputs "
outputsView.FgColor = gocui.ColorYellow
outputsView.SelBgColor = gocui.ColorGreen
outputsView.SelFgColor = gocui.ColorBlack
outputsView.Autoscroll = true
outputsView.Wrap = false
outputsView.Highlight = true
// Current Ping Configs view.
configView, err := g.SetView(CONFIG, 0, maxY-18, IPSWIDTH, maxY-11)
if err != nil && err != gocui.ErrUnknownView {
log.Println("Failed to create config view:", err)
return
}
configView.Title = " Configs "
configView.FgColor = gocui.ColorYellow
configView.SelBgColor = gocui.ColorGreen
configView.SelFgColor = gocui.ColorBlack
configView.Highlight = false
// Current Ping Statistics view.
statsView, err := g.SetView(STATS, 0, maxY-10, IPSWIDTH, maxY-2)
if err != nil && err != gocui.ErrUnknownView {
log.Println("Failed to create stats view:", err)
return
}
statsView.Title = " Stats "
statsView.FgColor = gocui.ColorYellow
statsView.SelBgColor = gocui.ColorGreen
statsView.SelFgColor = gocui.ColorBlack
statsView.Highlight = false
statsView.Editable = false
// Infos view.
infosView, err := g.SetView(INFOS, 0, maxY-2, IPSWIDTH, maxY)
if err != nil && err != gocui.ErrUnknownView {
log.Println("Failed to create infos view:", err)
return
}
infosView.FgColor = gocui.ColorRed
infosView.Highlight = false
infosView.Editable = false
infosView.Frame = false
fmt.Fprint(infosView, " Press F1 For Help ")
// Apply keybindings to ui.
if err = keybindings(g); err != nil {
log.Println("Failed to setup keybindings:", err)
return
}
// move the focus on the jobs list box.
if _, err = g.SetCurrentView(IPLIST); err != nil {
log.Println("Failed to set focus on ips view:", err)
return
}
// set the cursor & origin to highlight first IP.
ipsView.SetCursor(0, 0)
ipsView.SetOrigin(0, 0)
// display current ips.
g.Update(updateIPsView)
wg.Add(1)
go scheduler()
wg.Add(1)
go updateConfigView(g, configView)
wg.Add(1)
go updateOutputsView(g, outputsView)
wg.Add(1)
go updateStatsView(g, statsView)
if err := g.MainLoop(); err != nil && err != gocui.ErrQuit {
close(exit)
log.Println("Exited from the main loop:", err)
}
wg.Wait()
}
// updateIPsView loads and displays all ips.
// Formats each IP - 15 witdh and left align.
func updateIPsView(g *gocui.Gui) error {
v, err := g.View(IPLIST)
if err != nil {
log.Println("Failed to update list of ips:", err)
return err
}
v.Clear()
ips := dbs.getAllIPs()
for i, ip := range ips {
fmt.Fprintf(v, "[%02d] %-15s\n", i, ip)
}
return nil
}
// updateConfigView displays focused IP configs.
func updateConfigView(g *gocui.Gui, configView *gocui.View) {
defer wg.Done()
var ip string
for {
select {
case <-exit:
return
case ip = <-focusedIPChan:
g.Update(func(g *gocui.Gui) error {
configView.Clear()
fmt.Fprint(configView, dbs.formatIPConfig(ip))
return nil
})
}
time.Sleep(10 * time.Millisecond)
}
}
// updateOutputsView displays each ping execution output.
// It cleans the outputs view when requested.
func updateOutputsView(g *gocui.Gui, outputsView *gocui.View) {
defer wg.Done()
var output string
for {
select {
case output = <-outputsDataChan:
g.Update(func(g *gocui.Gui) error {
fmt.Fprint(outputsView, "\n"+output)
return nil
})
case <-clearOutputsViewChan:
g.Update(func(g *gocui.Gui) error {
outputsView.Clear()
outputsView.SetCursor(0, 0)
outputsView.SetOrigin(0, 0)
return nil
})
case title := <-outputsTitleChan:
g.Update(func(g *gocui.Gui) error {
outputsView.Title = title
return nil
})
case <-exit:
return
}
// pause the infinite loop to avoid cpu spike.
time.Sleep(10 * time.Millisecond)
}
}
// updateStatsView displays ongoing Ping statistics.
func updateStatsView(g *gocui.Gui, statsView *gocui.View) {
defer wg.Done()
var data string
//var latestStats stats
for {
select {
case data = <-outputsStatsChan:
g.Update(func(g *gocui.Gui) error {
if ip, ok := buildStats(data); ok {
statsView.Clear()
fmt.Fprint(statsView, dbs.formatIPStats(ip))
}
return nil
})
case <-clearStatsViewChan:
//latestStats = &stats{}
g.Update(func(g *gocui.Gui) error {
statsView.Clear()
return nil
})
case <-exit:
return
}
time.Sleep(10 * time.Millisecond)
}
}
// buildStats updates the Ping statistics from a given response data.
// rt == -1 means the output is not a successful reply.
// true means the output states for a ping failure.
// false means to ignore the output (statistics data).
func buildStats(data string) (string, bool) {
ip, threshold, output := strings.Split(data, "@")[0], strings.Split(data, "@")[1], strings.Split(data, "@")[2]
stats := dbs.getStats(ip)
rt, failed := getResponseTime(output)
if rt == -1 && !failed {
// ignore output.
return ip, false
}
if rt == -1 && failed {
// failure response.
stats.fails += 1
return ip, true
}
// reply response.
modif := false
if stats.min == 0 && stats.max == 0 {
// matches the first output data.
stats.min, stats.max = rt, rt
modif = true
} else {
// this for following outputs.
if rt < stats.min {
stats.min = rt
modif = true
} else if stats.max < rt {
stats.max = rt
modif = true
}
}
// compute average only if there was a change.
if modif {
stats.avg = (stats.min + stats.max) / 2
}
thres, _ := strconv.Atoi(threshold)
if rt == thres {
stats.match += 1
} else if rt > thres {
stats.above += 1
} else if rt < thres {
stats.under += 1
}
return ip, true
}
func layout(g *gocui.Gui) error {
maxX, maxY := g.Size()
// IPs list view.
_, err := g.SetView(IPLIST, 0, 0, IPSWIDTH, maxY-19)
if err != nil && err != gocui.ErrUnknownView {
log.Println("Failed to create ips list view:", err)
return err
}
// Outputs view.
_, err = g.SetView(OUTPUTS, IPSWIDTH+1, 0, maxX-1, maxY-1)
if err != nil && err != gocui.ErrUnknownView {
log.Println("Failed to create outputs view:", err)
return err
}
// Current Ping Configs view.
_, err = g.SetView(CONFIG, 0, maxY-18, IPSWIDTH, maxY-11)
if err != nil && err != gocui.ErrUnknownView {
log.Println("Failed to create config view:", err)
return err
}
// Current Ping Statistics view.
_, err = g.SetView(STATS, 0, maxY-10, IPSWIDTH, maxY-2)
if err != nil && err != gocui.ErrUnknownView {
log.Println("Failed to create stats view:", err)
return err
}
// Infos view.
_, err = g.SetView(INFOS, 0, maxY-2, IPSWIDTH, maxY)
if err != nil && err != gocui.ErrUnknownView {
log.Println("Failed to create infos view:", err)
return err
}
return nil
}
func quit(g *gocui.Gui, v *gocui.View) error {
close(exit)
return gocui.ErrQuit
}
// keybindings binds multiple keys to views.
func keybindings(g *gocui.Gui) error {
if err := g.SetKeybinding("", gocui.KeyCtrlC, gocui.ModNone, quit); err != nil {
return err
}
if err := g.SetKeybinding("", gocui.KeyTab, gocui.ModNone, nextView); err != nil {
return err
}
// use F1 to display help message when the focus is on OUPUTS or IPLIST view.
if err := g.SetKeybinding(IPLIST, gocui.KeyF1, gocui.ModNone, displayHelpView); err != nil {
return err
}
if err := g.SetKeybinding(OUTPUTS, gocui.KeyF1, gocui.ModNone, displayHelpView); err != nil {
return err
}
// Ctrl+A to create & add one or more new ip addresses (comma-separated input).
if err := g.SetKeybinding(IPLIST, gocui.KeyCtrlA, gocui.ModNone, addIPInputView); err != nil {
return err
}
if err := g.SetKeybinding(OUTPUTS, gocui.KeyCtrlA, gocui.ModNone, addIPInputView); err != nil {
return err
}
// Ctrl+D to delete one or more existing ip addresses (comma-separated input).
if err := g.SetKeybinding(IPLIST, gocui.KeyCtrlD, gocui.ModNone, deleteIPInputView); err != nil {
return err
}
if err := g.SetKeybinding(OUTPUTS, gocui.KeyCtrlD, gocui.ModNone, deleteIPInputView); err != nil {
return err
}
// Ctrl+F to find and move cursor on existing ip address.
if err := g.SetKeybinding(IPLIST, gocui.KeyCtrlF, gocui.ModNone, searchIPInputView); err != nil {
return err
}
if err := g.SetKeybinding(OUTPUTS, gocui.KeyCtrlF, gocui.ModNone, searchIPInputView); err != nil {
return err
}
// Ctrl+L to load new IP infos from a set of files entered into an input box.
if err := g.SetKeybinding(IPLIST, gocui.KeyCtrlL, gocui.ModNone, loadIPsInputView); err != nil {
return err
}
if err := g.SetKeybinding(OUTPUTS, gocui.KeyCtrlL, gocui.ModNone, loadIPsInputView); err != nil {
return err
}
// Ctrl+R to clear the outputs view content.
if err := g.SetKeybinding(OUTPUTS, gocui.KeyCtrlR, gocui.ModNone, clearOutputsView); err != nil {
return err
}
// Press <Enter> key or <P> or <Ctrl+P> to add current focused IP to Ping scheduler.
if err := g.SetKeybinding(IPLIST, gocui.KeyEnter, gocui.ModNone, addPing); err != nil {
return err
}
if err := g.SetKeybinding(IPLIST, gocui.KeyCtrlP, gocui.ModNone, addPing); err != nil {
return err
}
if err := g.SetKeybinding(IPLIST, 'P', gocui.ModNone, addPing); err != nil {
return err
}
// Press <T> key or <Ctrl+T> to add current focused IP to Traceroute scheduler.
if err := g.SetKeybinding(IPLIST, 'T', gocui.ModNone, addTraceroute); err != nil {
return err
}
if err := g.SetKeybinding(IPLIST, gocui.KeyCtrlT, gocui.ModNone, addTraceroute); err != nil {
return err
}
// arrow keys binding to navigate over the list of items.
if err := g.SetKeybinding(IPLIST, gocui.KeyArrowUp, gocui.ModNone, ipsMoveCursorUp); err != nil {
return err
}
if err := g.SetKeybinding(IPLIST, gocui.KeyArrowDown, gocui.ModNone, ipsMoveCursorDown); err != nil {
return err
}
if err := g.SetKeybinding(OUTPUTS, gocui.KeyArrowUp, gocui.ModNone, outMoveCursorUp); err != nil {
return err
}
if err := g.SetKeybinding(OUTPUTS, gocui.KeyArrowDown, gocui.ModNone, outMoveCursorDown); err != nil {
return err
}
// stop current ongoing action (if any) - which could be Ping or Traceroute.
if err := g.SetKeybinding(IPLIST, gocui.KeyCtrlQ, gocui.ModNone, stopCurrentProcessing); err != nil {
return err
}
if err := g.SetKeybinding(OUTPUTS, gocui.KeyCtrlQ, gocui.ModNone, stopCurrentProcessing); err != nil {
return err
}
if err := g.SetKeybinding(CONFIG, gocui.KeyCtrlQ, gocui.ModNone, stopCurrentProcessing); err != nil {
return err
}
if err := g.SetKeybinding(STATS, gocui.KeyCtrlQ, gocui.ModNone, stopCurrentProcessing); err != nil {
return err
}
// Ctrl+E to edit focused IP configuration details.
if err := g.SetKeybinding(IPLIST, gocui.KeyCtrlE, gocui.ModNone, editIPConfigView); err != nil {
return err
}
return nil
}
// stopCurrentProcessing triggered on CTRL+Q send stop flag to channel.
func stopCurrentProcessing(g *gocui.Gui, v *gocui.View) error {
stopProcessingChan <- struct{}{}
currentOnPingIP = ""
return nil
}
// displayHelpView displays help details but trying to center it.
func displayHelpView(g *gocui.Gui, cv *gocui.View) error {
maxX, maxY := g.Size()
// construct the input box and position at the center of the screen.
if helpView, err := g.SetView(HELP, (maxX-HWIDTH)/2, (maxY-HHEIGHT)/2, maxX/2+HWIDTH, (maxY+HHEIGHT)/2); err != nil {
if err != gocui.ErrUnknownView {
log.Println("Failed to create help view:", err)
return err
}
helpView.FgColor = gocui.ColorGreen
helpView.SelBgColor = gocui.ColorBlack
helpView.SelFgColor = gocui.ColorYellow
helpView.Editable = false
helpView.Autoscroll = true
helpView.Wrap = true
helpView.Frame = false
if _, err := g.SetCurrentView(HELP); err != nil {
log.Println("Failed to set focus on help view:", err)
return err
}
g.Cursor = false
// bind Ctrl+Q and Escape and F1 keys to close the input box.
if err := g.SetKeybinding(HELP, gocui.KeyCtrlQ, gocui.ModNone, closeHelpView); err != nil {
log.Println("Failed to bind keys (CtrlQ) to help view:", err)
return err
}
if err := g.SetKeybinding(HELP, gocui.KeyF1, gocui.ModNone, closeHelpView); err != nil {
log.Println("Failed to bind keys (F1) to help view:", err)
return err
}
if err := g.SetKeybinding(HELP, gocui.KeyEsc, gocui.ModNone, closeHelpView); err != nil {
log.Println("Failed to bind keys (Esc) to help view:", err)
return err
}
fmt.Fprint(helpView, helpDetails)
}
return nil
}
// closeHelpView closes help view then move the focus on IP list view.
func closeHelpView(g *gocui.Gui, hv *gocui.View) error {
hv.Clear()
g.Cursor = false
g.DeleteKeybindings(hv.Name())
if err := g.DeleteView(hv.Name()); err != nil {
log.Println("Failed to delete help view:", err)
return err
}
return setCurrentDefaultView(g)
}
// clearOutputsView clears outputs view content.
func clearOutputsView(g *gocui.Gui, v *gocui.View) error {
v.Clear()
return nil
}
// addIPInputView displays a temporary input box to enter
// a comma-separated list of IP addresses.
func addIPInputView(g *gocui.Gui, cv *gocui.View) error {
maxX, maxY := g.Size()
const name = "addIP"
// construct the input box and position at the center of the screen.
if inputView, err := g.SetView(name, maxX/2-25, maxY/2, maxX/2+25, maxY/2+2); err != nil {
if err != gocui.ErrUnknownView {
log.Println("Failed to display input view: ", err)
return err
}
inputView.Title = " Enter IP Addresses (Separated By Comma) "
inputView.FgColor = gocui.ColorYellow
inputView.SelBgColor = gocui.ColorBlack
inputView.SelFgColor = gocui.ColorYellow
inputView.Editable = true
if _, err := g.SetCurrentView(name); err != nil {
log.Println(err)
return err
}
g.Cursor = true
inputView.Highlight = true
// bind Enter key to processInput function.
if err := g.SetKeybinding(name, gocui.KeyEnter, gocui.ModNone, processInput); err != nil {
log.Println(err)
return err
}
// bind Ctrl+Q and Escape keys to close the input box.
if err := g.SetKeybinding(name, gocui.KeyCtrlQ, gocui.ModNone, closeInputView); err != nil {
log.Println(err)
return err
}
if err := g.SetKeybinding(name, gocui.KeyEsc, gocui.ModNone, closeInputView); err != nil {
log.Println(err)
return err
}
}
return nil
}
// deleteIPInputView displays a temporary input box to delete an IP.
func deleteIPInputView(g *gocui.Gui, cv *gocui.View) error {
maxX, maxY := g.Size()
const name = "deleteIP"
// construct the input box and position at the center of the screen.
if inputView, err := g.SetView(name, maxX/2-12, maxY/2, maxX/2+12, maxY/2+2); err != nil {
if err != gocui.ErrUnknownView {
log.Println("Failed to display input view: ", err)
return err
}
inputView.Title = " Delete IP Addresses "
inputView.FgColor = gocui.ColorYellow
inputView.SelBgColor = gocui.ColorBlack
inputView.SelFgColor = gocui.ColorYellow
inputView.Editable = true
if _, err := g.SetCurrentView(name); err != nil {
log.Println(err)
return err
}
g.Cursor = true
inputView.Highlight = true
// bind Enter key to processInput function.
if err := g.SetKeybinding(name, gocui.KeyEnter, gocui.ModNone, processInput); err != nil {