Fixed few memory leaks. Implement testing of the functionality.

This commit is contained in:
Kalzu Rekku
2026-01-08 18:55:32 +02:00
parent c663ec0431
commit 1130b7fb8c
10 changed files with 1334 additions and 13 deletions

View File

@@ -77,10 +77,11 @@ var (
dbMux sync.RWMutex
stats Stats
statsMux sync.RWMutex
sentHops = make(map[string]bool) // Track sent hops to avoid duplicates
sentHops = make(map[string]time.Time) // Track sent hops with timestamp for eviction
sentHopsMux sync.RWMutex
verbose bool
startTime time.Time
sentHopsTTL = 24 * time.Hour // Time-to-live for hop deduplication cache
)
func main() {
@@ -168,6 +169,9 @@ func main() {
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
// Start cleanup goroutine for sentHops map to prevent unbounded growth
go cleanupSentHops()
go func() {
log.Printf("🚀 Output Service v%s starting...", VERSION)
log.Printf("📥 Listening for results on http://localhost:%d/results", config.Port)
@@ -549,11 +553,14 @@ func extractAndSendHops(result *PingResult) {
var newHops []string
sentHopsMux.Lock()
now := time.Now()
for _, hop := range result.Traceroute.Hops {
if hop.IP != "" && !hop.Timeout && hop.IP != "*" {
if !sentHops[hop.IP] {
// Check if we've seen this hop recently (within TTL)
lastSent, exists := sentHops[hop.IP]
if !exists || now.Sub(lastSent) > sentHopsTTL {
newHops = append(newHops, hop.IP)
sentHops[hop.IP] = true
sentHops[hop.IP] = now
statsMux.Lock()
stats.HopsDiscovered++
@@ -602,6 +609,31 @@ func extractAndSendHops(result *PingResult) {
}
}
// cleanupSentHops periodically removes old entries from sentHops map to prevent unbounded growth
func cleanupSentHops() {
ticker := time.NewTicker(1 * time.Hour)
defer ticker.Stop()
for range ticker.C {
sentHopsMux.Lock()
now := time.Now()
removed := 0
for ip, timestamp := range sentHops {
if now.Sub(timestamp) > sentHopsTTL {
delete(sentHops, ip)
removed++
}
}
if verbose && removed > 0 {
log.Printf("🧹 Cleaned up %d expired hop entries (total: %d)", removed, len(sentHops))
}
sentHopsMux.Unlock()
}
}
func handleRotate(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)