-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwatchdog.go
64 lines (55 loc) · 1.33 KB
/
watchdog.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
package main
import (
"os/exec"
"sync"
"time"
log "github.com/sirupsen/logrus"
)
type SubdomainState struct {
Mutex sync.Mutex
Starting bool
LastSeen time.Time
Cmd *exec.Cmd
}
var subdomains sync.Map
func updateSubdomainState(subdomain string, cmd *exec.Cmd, starting bool) {
now := time.Now()
info, ok := subdomains.Load(subdomain)
if !ok {
subdomains.Store(subdomain, &SubdomainState{
LastSeen: now,
Cmd: cmd,
Starting: starting,
})
} else {
existingInfo := info.(*SubdomainState)
existingInfo.Mutex.Lock()
defer existingInfo.Mutex.Unlock()
if cmd != nil {
existingInfo.Cmd = cmd
}
existingInfo.LastSeen = now
existingInfo.Starting = starting
}
}
func startWatchdog(timeout time.Duration) {
ticker := time.NewTicker(10 * time.Second)
defer ticker.Stop()
for range ticker.C {
subdomains.Range(func(key, value interface{}) bool {
subdomain := key.(string)
state := value.(*SubdomainState)
state.Mutex.Lock()
defer state.Mutex.Unlock()
if time.Since(state.LastSeen) > timeout && state.Cmd != nil {
if err := state.Cmd.Process.Kill(); err != nil {
log.Errorf("Failed to kill process for subdomain %s: %v", subdomain, err)
} else {
log.Infof("Killed inactive process for subdomain %s", subdomain)
subdomains.Delete(subdomain)
}
}
return true
})
}
}