-
-
Notifications
You must be signed in to change notification settings - Fork 66
Expand file tree
/
Copy pathpacketloss.go
More file actions
1332 lines (1174 loc) · 36.8 KB
/
Copy pathpacketloss.go
File metadata and controls
1332 lines (1174 loc) · 36.8 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
// Copyright (c) 2024-2025, s0up and the autobrr contributors.
// SPDX-License-Identifier: GPL-2.0-or-later
package speedtest
import (
"context"
"encoding/json"
"fmt"
"io"
"net"
"os/exec"
"runtime"
"strings"
"sync"
"time"
probing "github.com/prometheus-community/pro-bing"
"github.com/rs/zerolog/log"
"github.com/autobrr/netronome/internal/database"
"github.com/autobrr/netronome/internal/notifications"
"github.com/autobrr/netronome/internal/types"
)
// PacketLossMonitor represents a single packet loss monitor
type PacketLossMonitor struct {
ID int64
Host string
Name string
PacketCount int
Threshold float64
Enabled bool
Cancel context.CancelFunc
ctx context.Context
}
// PacketLossService manages packet loss monitoring
type PacketLossService struct {
monitors map[int64]*PacketLossMonitor
progress map[int64]float64 // Track current progress for each monitor
completed map[int64]time.Time // Track recently completed tests
mtrData map[int64]string // Store MTR JSON data temporarily
mtrPrivileged map[int64]bool // Track if MTR ran in privileged mode
mu sync.RWMutex
db database.Service
notifier *notifications.Notifier
broadcast func(types.PacketLossUpdate)
scheduler interface {
UpdateMonitorSchedule(monitorID int64, interval string) error
}
maxConcurrent int
privilegedMode bool
enableDNS bool
}
// NewPacketLossService creates a new packet loss monitoring service
func NewPacketLossService(db database.Service, notifier *notifications.Notifier, broadcast func(types.PacketLossUpdate), maxConcurrent int, privilegedMode bool, enableDNS bool) *PacketLossService {
if maxConcurrent <= 0 {
maxConcurrent = 10
}
return &PacketLossService{
monitors: make(map[int64]*PacketLossMonitor),
progress: make(map[int64]float64),
completed: make(map[int64]time.Time),
mtrData: make(map[int64]string),
mtrPrivileged: make(map[int64]bool),
db: db,
notifier: notifier,
broadcast: broadcast,
maxConcurrent: maxConcurrent,
privilegedMode: privilegedMode,
enableDNS: enableDNS,
}
}
// SetBroadcast sets the broadcast function for the service
func (s *PacketLossService) SetBroadcast(broadcast func(types.PacketLossUpdate)) {
s.mu.Lock()
defer s.mu.Unlock()
s.broadcast = broadcast
}
// SetScheduler sets the scheduler for the service
func (s *PacketLossService) SetScheduler(scheduler interface {
UpdateMonitorSchedule(monitorID int64, interval string) error
}) {
s.mu.Lock()
defer s.mu.Unlock()
s.scheduler = scheduler
}
// StartMonitor starts monitoring for a specific monitor configuration
func (s *PacketLossService) StartMonitor(monitorID int64) error {
s.mu.Lock()
defer s.mu.Unlock()
// Check if already monitoring
if _, exists := s.monitors[monitorID]; exists {
return fmt.Errorf("monitor %d is already running", monitorID)
}
// Check concurrent limit
if len(s.monitors) >= s.maxConcurrent {
return fmt.Errorf("maximum concurrent monitors (%d) reached", s.maxConcurrent)
}
// Get monitor config from database
monitorConfig, err := s.db.GetPacketLossMonitor(monitorID)
if err != nil {
return fmt.Errorf("failed to get monitor config: %w", err)
}
// Create monitor instance
ctx, cancel := context.WithCancel(context.Background())
monitor := &PacketLossMonitor{
ID: monitorConfig.ID,
Host: monitorConfig.Host,
Name: monitorConfig.Name,
PacketCount: monitorConfig.PacketCount,
Threshold: monitorConfig.Threshold,
Enabled: true,
Cancel: cancel,
ctx: ctx,
}
// Store monitor
s.monitors[monitorID] = monitor
// Start monitoring in goroutine
go s.runMonitor(monitor)
log.Info().
Int64("monitorID", monitorID).
Str("host", monitorConfig.Host).
Msg("Started packet loss monitor")
return nil
}
// StopMonitor stops monitoring for a specific monitor
func (s *PacketLossService) StopMonitor(monitorID int64) error {
s.mu.Lock()
defer s.mu.Unlock()
monitor, exists := s.monitors[monitorID]
if !exists {
return fmt.Errorf("monitor %d is not running", monitorID)
}
// Cancel context to stop the monitor
monitor.Cancel()
// Remove from active monitors
delete(s.monitors, monitorID)
// Clear progress
delete(s.progress, monitorID)
log.Info().
Int64("monitorID", monitorID).
Str("host", monitor.Host).
Msg("Stopped packet loss monitor")
return nil
}
// runMonitor runs a single test for manual start
func (s *PacketLossService) runMonitor(monitor *PacketLossMonitor) {
log.Info().
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Int("packetCount", monitor.PacketCount).
Msg("Running manual packet loss test")
// Run a single test when manually started
s.runSingleTest(monitor)
// Remove from active monitors after completion
s.mu.Lock()
delete(s.monitors, monitor.ID)
delete(s.progress, monitor.ID)
s.mu.Unlock()
log.Info().
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Msg("Manual packet loss test completed")
}
// runSingleTest runs a single packet loss test
func (s *PacketLossService) runSingleTest(monitor *PacketLossMonitor) {
log.Debug().
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Msg("Running packet loss test")
// Initialize progress to 0
s.mu.Lock()
s.progress[monitor.ID] = 0
s.mu.Unlock()
// Broadcast start update
if s.broadcast != nil {
s.broadcast(types.PacketLossUpdate{
Type: "packetloss",
MonitorID: monitor.ID,
Host: monitor.Host,
IsRunning: true,
IsComplete: false,
Progress: 0,
})
}
// Try MTR first if available
if s.checkMTRAvailable() {
log.Info().
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Msg("MTR is available, attempting MTR test")
if result, err := s.runMTRTest(monitor); err == nil {
s.processResults(monitor, result)
return
} else {
log.Warn().
Err(err).
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Msg("MTR test failed, falling back to ping")
}
}
// Fall back to regular ping test
s.runPingTest(monitor)
}
// checkMTRAvailable checks if MTR is available on the system
func (s *PacketLossService) checkMTRAvailable() bool {
_, err := exec.LookPath("mtr")
return err == nil
}
// runPingTest runs a traditional ping-based packet loss test
func (s *PacketLossService) runPingTest(monitor *PacketLossMonitor) {
// Try privileged mode first if configured
if s.privilegedMode {
if err := s.runPingWithPrivilege(monitor, true); err == nil {
return // Success
} else if strings.Contains(err.Error(), "operation not permitted") {
log.Warn().
Err(err).
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Msg("Privileged ping failed, trying unprivileged mode")
// Try unprivileged mode
if err := s.runPingWithPrivilege(monitor, false); err == nil {
return // Success with unprivileged
}
// If unprivileged also failed, let it fail naturally
// The error has already been handled in runPingWithPrivilege
} else {
// Other error in privileged mode, try unprivileged as fallback
s.runPingWithPrivilege(monitor, false)
}
} else {
// Not using privileged mode, run unprivileged directly
s.runPingWithPrivilege(monitor, false)
}
}
// runPingWithPrivilege runs the ping test with specified privilege mode
func (s *PacketLossService) runPingWithPrivilege(monitor *PacketLossMonitor, usePrivileged bool) error {
// Create a new pinger for this test
pinger, err := probing.NewPinger(monitor.Host)
if err != nil {
log.Error().
Err(err).
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Msg("Failed to create pinger")
// Broadcast error
if s.broadcast != nil {
s.broadcast(types.PacketLossUpdate{
Type: "packetloss",
MonitorID: monitor.ID,
Host: monitor.Host,
IsRunning: false,
IsComplete: true,
Error: fmt.Sprintf("Failed to create pinger: %v", err),
})
}
return err
}
// Configure pinger
pinger.Interval = 1 * time.Second // Send one packet per second
pinger.Count = monitor.PacketCount
pinger.Timeout = time.Duration(monitor.PacketCount*2) * time.Second // 2 seconds per packet timeout
pinger.SetPrivileged(usePrivileged)
log.Info().
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Bool("privilegedMode", usePrivileged).
Msg("Configured pinger")
// Create results channel for this test
results := make(chan *probing.Statistics, 1)
// Set up callbacks
packetsReceived := 0
packetsSent := 0
// Track when packets are sent
pinger.OnSend = func(pkt *probing.Packet) {
packetsSent++
progress := float64(packetsSent) / float64(monitor.PacketCount) * 100
// Store progress based on sent packets
s.mu.Lock()
s.progress[monitor.ID] = progress
s.mu.Unlock()
log.Debug().
Int64("monitorID", monitor.ID).
Int("seq", pkt.Seq).
Int("sent", packetsSent).
Float64("progress", progress).
Msg("Packet sent")
// Broadcast progress update based on sent packets
if s.broadcast != nil {
s.broadcast(types.PacketLossUpdate{
Type: "packetloss",
MonitorID: monitor.ID,
Host: monitor.Host,
IsRunning: true,
IsComplete: false,
Progress: progress,
PacketsSent: packetsSent,
PacketsRecv: packetsReceived,
})
}
}
pinger.OnRecv = func(pkt *probing.Packet) {
packetsReceived++
log.Debug().
Int64("monitorID", monitor.ID).
Int("seq", pkt.Seq).
Dur("rtt", pkt.Rtt).
Int("ttl", pkt.TTL).
Int("received", packetsReceived).
Msg("Packet received")
// Update with latest receive count
if s.broadcast != nil {
s.mu.RLock()
progress := s.progress[monitor.ID]
s.mu.RUnlock()
s.broadcast(types.PacketLossUpdate{
Type: "packetloss",
MonitorID: monitor.ID,
Host: monitor.Host,
IsRunning: true,
IsComplete: false,
Progress: progress,
PacketsSent: packetsSent,
PacketsRecv: packetsReceived,
})
}
}
// Create context with timeout for goroutine management
timeoutDuration := time.Duration(monitor.PacketCount*2) * time.Second
pingerCtx, pingerCancel := context.WithTimeout(context.Background(), timeoutDuration)
defer pingerCancel()
// Channel to track pinger completion
pingerDone := make(chan struct{})
var pingerStats *probing.Statistics
var pingerMutex sync.Mutex
var pingerError error
pinger.OnFinish = func(stats *probing.Statistics) {
pingerMutex.Lock()
pingerStats = stats
pingerMutex.Unlock()
log.Debug().
Int64("monitorID", monitor.ID).
Float64("packetLoss", stats.PacketLoss).
Int("packetsSent", stats.PacketsSent).
Int("packetsRecv", stats.PacketsRecv).
Msg("Pinger OnFinish called")
select {
case results <- stats:
default:
// Channel full, should not happen with buffer of 1
}
}
// Run the pinger in a goroutine with context management
go func() {
defer func() {
log.Debug().
Int64("monitorID", monitor.ID).
Msg("Pinger goroutine exiting")
close(pingerDone)
}()
log.Info().
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Dur("timeout", timeoutDuration).
Msg("Starting pinger")
err := pinger.Run()
if err != nil {
// Check if it's a permission error and we were using privileged mode
if usePrivileged && strings.Contains(err.Error(), "operation not permitted") {
log.Warn().
Err(err).
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Msg("Privileged ping failed, will retry with unprivileged mode")
// Store the error
pingerMutex.Lock()
pingerError = err
pingerMutex.Unlock()
} else {
log.Error().
Err(err).
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Msg("Pinger run failed")
// Store the error
pingerMutex.Lock()
pingerError = err
pingerMutex.Unlock()
}
}
log.Debug().
Int64("monitorID", monitor.ID).
Msg("Pinger.Run() completed")
}()
// Wait for results with multiple completion paths
completed := false
defer func() {
if !completed {
log.Warn().
Int64("monitorID", monitor.ID).
Msg("Test completed via fallback cleanup")
}
// Always ensure pinger is stopped and progress is cleared
pinger.Stop()
pingerCancel()
s.mu.Lock()
delete(s.progress, monitor.ID)
s.mu.Unlock()
}()
select {
case <-monitor.ctx.Done():
log.Info().
Int64("monitorID", monitor.ID).
Msg("Test cancelled via monitor context")
completed = true
return nil
case stats := <-results:
log.Info().
Int64("monitorID", monitor.ID).
Float64("packetLoss", stats.PacketLoss).
Msg("Test completed via OnFinish callback")
completed = true
// Process results
s.processResults(monitor, stats)
case <-pingerCtx.Done():
log.Warn().
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Msg("Test timed out - pinger context cancelled")
completed = true
// Check if we got stats from OnFinish before timeout
pingerMutex.Lock()
stats := pingerStats
pingerMutex.Unlock()
if stats != nil {
log.Info().
Int64("monitorID", monitor.ID).
Msg("Using stats from OnFinish despite timeout")
s.processResults(monitor, stats)
} else {
log.Warn().
Int64("monitorID", monitor.ID).
Msg("No stats from OnFinish, creating timeout result")
// Create timeout result with 100% packet loss
timeoutStats := &probing.Statistics{
PacketsSent: monitor.PacketCount,
PacketsRecv: 0,
PacketLoss: 100.0,
MinRtt: 0,
MaxRtt: 0,
AvgRtt: 0,
StdDevRtt: 0,
}
s.processResults(monitor, timeoutStats)
}
// Broadcast timeout completion
if s.broadcast != nil {
packetLoss := 100.0
if stats != nil {
packetLoss = stats.PacketLoss
}
s.broadcast(types.PacketLossUpdate{
Type: "packetloss",
MonitorID: monitor.ID,
Host: monitor.Host,
IsRunning: false,
IsComplete: true,
PacketLoss: packetLoss,
PacketsSent: monitor.PacketCount,
PacketsRecv: 0,
})
}
case <-pingerDone:
log.Debug().
Int64("monitorID", monitor.ID).
Msg("Pinger goroutine completed, waiting for OnFinish")
// Check if there was an immediate error that should be returned
pingerMutex.Lock()
errorToCheck := pingerError
pingerMutex.Unlock()
// If this was a privileged mode permission error, don't create a fallback result
if errorToCheck != nil && usePrivileged && strings.Contains(errorToCheck.Error(), "operation not permitted") {
log.Debug().
Int64("monitorID", monitor.ID).
Msg("Skipping fallback result creation for privileged mode permission error")
completed = true
// Error will be returned at the end of the function
break
}
// Give OnFinish a short time to trigger after goroutine completes
select {
case stats := <-results:
log.Info().
Int64("monitorID", monitor.ID).
Msg("Test completed via delayed OnFinish")
completed = true
s.processResults(monitor, stats)
case <-time.After(1 * time.Second):
log.Warn().
Int64("monitorID", monitor.ID).
Msg("OnFinish never called after pinger completed")
completed = true
// Use cached stats if available, otherwise create timeout result
pingerMutex.Lock()
stats := pingerStats
pingerMutex.Unlock()
if stats != nil {
log.Info().
Int64("monitorID", monitor.ID).
Msg("Using cached stats from OnFinish")
s.processResults(monitor, stats)
} else {
log.Warn().
Int64("monitorID", monitor.ID).
Msg("No cached stats, creating fallback result")
timeoutStats := &probing.Statistics{
PacketsSent: monitor.PacketCount,
PacketsRecv: 0,
PacketLoss: 100.0,
MinRtt: 0,
MaxRtt: 0,
AvgRtt: 0,
StdDevRtt: 0,
}
s.processResults(monitor, timeoutStats)
}
}
}
// Check if there was an error
pingerMutex.Lock()
finalErr := pingerError
pingerMutex.Unlock()
// Return the error if privileged mode failed
if finalErr != nil && usePrivileged && strings.Contains(finalErr.Error(), "operation not permitted") {
return finalErr
}
// Return nil on success
return nil
}
// processResults processes the test results
func (s *PacketLossService) processResults(monitor *PacketLossMonitor, stats *probing.Statistics) {
log.Info().
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Float64("packetLoss", stats.PacketLoss).
Int("packetsSent", stats.PacketsSent).
Int("packetsRecv", stats.PacketsRecv).
Dur("minRtt", stats.MinRtt).
Dur("maxRtt", stats.MaxRtt).
Dur("avgRtt", stats.AvgRtt).
Msg("Packet loss test completed")
// Mark test as completed
s.mu.Lock()
s.completed[monitor.ID] = time.Now()
// Clean up old completed entries (older than 1 minute)
for id, completedTime := range s.completed {
if time.Since(completedTime) > time.Minute {
delete(s.completed, id)
}
}
s.mu.Unlock()
// Check if this was an MTR test
usedMTR := false
hopCount := 0
var mtrDataStr *string
privilegedMode := false
s.mu.RLock()
if mtrJSON, exists := s.mtrData[monitor.ID]; exists {
usedMTR = true
mtrDataStr = &mtrJSON
// Extract hop count from Rtts hack
if len(stats.Rtts) > 0 {
hopCount = int(stats.Rtts[0])
}
// Get the privileged mode status
if priv, exists := s.mtrPrivileged[monitor.ID]; exists {
privilegedMode = priv
}
}
s.mu.RUnlock()
// Save results to database
result := &types.PacketLossResult{
MonitorID: monitor.ID,
PacketLoss: stats.PacketLoss,
MinRTT: float64(stats.MinRtt.Milliseconds()),
MaxRTT: float64(stats.MaxRtt.Milliseconds()),
AvgRTT: float64(stats.AvgRtt.Milliseconds()),
StdDevRTT: float64(stats.StdDevRtt.Milliseconds()),
PacketsSent: stats.PacketsSent,
PacketsRecv: stats.PacketsRecv,
UsedMTR: usedMTR,
HopCount: hopCount,
MTRData: mtrDataStr,
PrivilegedMode: privilegedMode,
CreatedAt: time.Now(),
}
// Clean up MTR data after use
if usedMTR {
s.mu.Lock()
delete(s.mtrData, monitor.ID)
delete(s.mtrPrivileged, monitor.ID)
s.mu.Unlock()
}
if s.db != nil {
if err := s.db.SavePacketLossResult(result); err != nil {
log.Error().
Err(err).
Int64("monitorID", monitor.ID).
Msg("Failed to save packet loss result")
}
}
// Broadcast complete update
if s.broadcast != nil {
s.broadcast(types.PacketLossUpdate{
Type: "packetloss",
MonitorID: monitor.ID,
Host: monitor.Host,
IsRunning: false,
IsComplete: true,
PacketLoss: stats.PacketLoss,
MinRTT: result.MinRTT,
MaxRTT: result.MaxRTT,
AvgRTT: result.AvgRTT,
StdDevRTT: result.StdDevRTT,
PacketsSent: stats.PacketsSent,
PacketsRecv: stats.PacketsRecv,
UsedMTR: usedMTR,
HopCount: hopCount,
})
}
// Check notification conditions and track state
if s.notifier != nil && s.db != nil {
// Get full monitor from database to check state
dbMonitor, err := s.db.GetPacketLossMonitor(monitor.ID)
if err != nil {
log.Error().
Err(err).
Int64("monitorID", monitor.ID).
Msg("Failed to get monitor from database for state tracking")
return
}
// Determine current state
var currentState string
if stats.PacketLoss >= 100.0 {
currentState = "down"
} else if stats.PacketLoss > monitor.Threshold {
currentState = "threshold_exceeded"
} else {
currentState = "ok"
}
// Get previous state from database
previousState := dbMonitor.LastState
if previousState == "" {
previousState = "unknown"
}
// Determine state transitions and send appropriate notifications
if previousState != currentState {
// State has changed
if currentState == "down" {
// Monitor went down
s.sendPacketLossNotification(monitor, stats, database.NotificationEventPacketLossDown)
} else if currentState == "threshold_exceeded" {
// Threshold exceeded (but not down)
s.sendPacketLossNotification(monitor, stats, database.NotificationEventPacketLossHigh)
} else if currentState == "ok" && (previousState == "down" || previousState == "threshold_exceeded") {
// Monitor recovered
s.sendPacketLossNotification(monitor, stats, database.NotificationEventPacketLossRecovered)
}
// Update state in database
if err := s.db.UpdatePacketLossMonitorState(monitor.ID, currentState); err != nil {
log.Error().
Err(err).
Int64("monitorID", monitor.ID).
Str("state", currentState).
Msg("Failed to update monitor state")
}
}
}
}
// sendPacketLossNotification sends a notification for packet loss events
func (s *PacketLossService) sendPacketLossNotification(monitor *PacketLossMonitor, stats *probing.Statistics, eventType string) {
// Create packet loss notification data
monitorName := monitor.Name
if monitorName == "" {
monitorName = monitor.Host
}
// Determine if monitor is down or recovered
isDown := eventType == database.NotificationEventPacketLossDown
isRecovered := eventType == database.NotificationEventPacketLossRecovered
// Send notification with appropriate parameters
if err := s.notifier.SendPacketLossNotification(monitorName, monitor.Host, stats.PacketLoss, isDown, isRecovered); err != nil {
log.Error().
Err(err).
Int64("monitorID", monitor.ID).
Str("eventType", eventType).
Msg("Failed to send packet loss notification")
} else {
log.Info().
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Float64("packetLoss", stats.PacketLoss).
Str("eventType", eventType).
Msg("Packet loss notification sent")
}
}
// GetMonitorStatus returns the current status of a monitor
func (s *PacketLossService) GetMonitorStatus(monitorID int64) (*types.PacketLossUpdate, error) {
s.mu.RLock()
defer s.mu.RUnlock()
// First, get monitor configuration from database to check if it's enabled
monitorConfig, err := s.db.GetPacketLossMonitor(monitorID)
if err != nil {
return nil, fmt.Errorf("failed to get monitor config: %w", err)
}
// Check if monitor is currently in memory (actively testing)
activeMonitor, isInMemory := s.monitors[monitorID]
progress := s.progress[monitorID]
// Check if test was recently completed (within last 5 seconds)
completedTime, wasCompleted := s.completed[monitorID]
isRecentlyCompleted := wasCompleted && time.Since(completedTime) < 5*time.Second
// Quad-state logic:
// 1. Actively testing: in memory + has progress > 0
// 2. Recently completed: marked as completed within last 5 seconds
// 3. Scheduled monitoring: enabled in DB but not actively testing
// 4. Disabled: not enabled in DB
if isInMemory && progress > 0 {
// State 1: Actively testing - show progress
return &types.PacketLossUpdate{
Type: "packetloss",
MonitorID: monitorID,
Host: activeMonitor.Host,
IsRunning: true,
IsComplete: false,
Progress: progress,
}, nil
} else if isRecentlyCompleted {
// State 2: Recently completed - return completion status
// Get latest result to show values
result, err := s.db.GetLatestPacketLossResult(monitorID)
if err != nil {
// Return completion status without results
return &types.PacketLossUpdate{
Type: "packetloss",
MonitorID: monitorID,
Host: monitorConfig.Host,
IsRunning: false,
IsComplete: true,
}, nil
}
// Return completion status with results
return &types.PacketLossUpdate{
Type: "packetloss",
MonitorID: monitorID,
Host: monitorConfig.Host,
IsRunning: false,
IsComplete: true,
PacketLoss: result.PacketLoss,
MinRTT: result.MinRTT,
MaxRTT: result.MaxRTT,
AvgRTT: result.AvgRTT,
PacketsSent: result.PacketsSent,
PacketsRecv: result.PacketsRecv,
}, nil
} else if monitorConfig.Enabled {
// State 3: Scheduled monitoring - enabled but waiting for next test
// Get latest result to show last known values
result, err := s.db.GetLatestPacketLossResult(monitorID)
if err != nil {
// No previous results, return basic monitoring status
return &types.PacketLossUpdate{
Type: "packetloss",
MonitorID: monitorID,
Host: monitorConfig.Host,
IsRunning: false,
IsComplete: false, // Not complete, just waiting for next test
}, nil
}
// Return monitoring status with last known results
return &types.PacketLossUpdate{
Type: "packetloss",
MonitorID: monitorID,
Host: monitorConfig.Host,
IsRunning: false,
IsComplete: false, // Not complete, just scheduled monitoring
PacketLoss: result.PacketLoss,
MinRTT: result.MinRTT,
MaxRTT: result.MaxRTT,
AvgRTT: result.AvgRTT,
PacketsSent: result.PacketsSent,
PacketsRecv: result.PacketsRecv,
}, nil
} else {
// State 4: Disabled - monitor is not enabled
return &types.PacketLossUpdate{
Type: "packetloss",
MonitorID: monitorID,
Host: monitorConfig.Host,
IsRunning: false,
IsComplete: true, // Mark as complete since it's disabled
}, nil
}
}
// GetActiveMonitors returns all currently active monitors
func (s *PacketLossService) GetActiveMonitors() []int64 {
s.mu.RLock()
defer s.mu.RUnlock()
monitors := make([]int64, 0, len(s.monitors))
for id := range s.monitors {
monitors = append(monitors, id)
}
return monitors
}
// StartAllEnabledMonitors starts all enabled monitors from the database
func (s *PacketLossService) StartAllEnabledMonitors() error {
monitors, err := s.db.GetEnabledPacketLossMonitors()
if err != nil {
return fmt.Errorf("failed to get enabled monitors: %w", err)
}
for _, monitor := range monitors {
if err := s.StartMonitor(monitor.ID); err != nil {
log.Error().
Err(err).
Int64("monitorID", monitor.ID).
Str("host", monitor.Host).
Msg("Failed to start monitor")
}
}
return nil
}
// StopAllMonitors stops all active monitors
func (s *PacketLossService) StopAllMonitors() {
s.mu.Lock()
monitorIDs := make([]int64, 0, len(s.monitors))
for id := range s.monitors {
monitorIDs = append(monitorIDs, id)
}
s.mu.Unlock()
for _, id := range monitorIDs {
if err := s.StopMonitor(id); err != nil {
log.Error().
Err(err).
Int64("monitorID", id).
Msg("Failed to stop monitor")
}
}
}
// MTR JSON output structure
type mtrReport struct {
Report struct {
MTR struct {
Src string `json:"src"`
Dst string `json:"dst"`
Tests int `json:"tests"`
} `json:"mtr"`
Hubs []struct {
Count int `json:"count"`
Host string `json:"host"`
Loss float64 `json:"Loss%"`
Snt int `json:"Snt"`
Last float64 `json:"Last"`
Avg float64 `json:"Avg"`
Best float64 `json:"Best"`
Wrst float64 `json:"Wrst"`
StDev float64 `json:"StDev"`
} `json:"hubs"`
} `json:"report"`
}
// runMTRTest runs an MTR test and returns statistics
func (s *PacketLossService) runMTRTest(monitor *PacketLossMonitor) (*probing.Statistics, error) {
if _, err := exec.LookPath("mtr"); err != nil {
if runtime.GOOS == "windows" {
return nil, fmt.Errorf("WinMTRCmd not found: please install from https://github.com/dqos/WinMTRCmd/releases and add to PATH")
}
return nil, fmt.Errorf("mtr not found: please install mtr package for your system")
}
// Initialize GeoIP databases if not already done
// This is a workaround since PacketLossService doesn't have access to the main service
if countryDB == nil && asnDB == nil {
log.Info().Msg("GeoIP databases not initialized for MTR. GeoIP enrichment will be unavailable.")
log.Info().Msg("To enable GeoIP for MTR, ensure GeoIP is configured in the [geoip] section of your config file.")
}
// Broadcast that MTR is starting
if s.broadcast != nil {
s.broadcast(types.PacketLossUpdate{
Type: "packetloss",
MonitorID: monitor.ID,
Host: monitor.Host,
IsRunning: true,