-
Notifications
You must be signed in to change notification settings - Fork 0
/
watcher.go
92 lines (84 loc) · 1.93 KB
/
watcher.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
package watch
import (
"fmt"
"log"
"os"
"os/exec"
"time"
"github.com/mitchellh/go-ps"
)
// Watcher is a process monitor
type Watcher struct {
CheckInterval time.Duration
Command string
Args []string
DedupeCmd string
IdleInterval time.Duration
Cwd string
}
// Start starts up
func (w *Watcher) Start() {
w.killOtherInstances()
// we start immediately, and then if it dies or is stopped by user we wait
// for idle timer to restart it
w.startIfNotRunning()
go w.run()
}
func (w *Watcher) run() {
c := time.NewTicker(w.CheckInterval).C
for {
<-c
idle, err := GetIdleTime()
if err != nil {
fmt.Println("error getting idle time: ", err)
}
if idle >= w.IdleInterval {
w.startIfNotRunning()
}
}
}
func (w *Watcher) startIfNotRunning() {
procs, err := ps.Processes()
if err != nil {
log.Fatal("could not get proc list:", err)
}
for _, proc := range procs {
if proc.Executable() == w.DedupeCmd {
log.Print("not starting as already found proc")
return
}
}
if w.Cwd != "" {
os.Chdir(w.Cwd)
}
cmd := exec.Command(w.Command, w.Args...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
log.Print("starting command", cmd.Args)
err = cmd.Run()
if err != nil {
log.Fatal(err)
}
}
func (w *Watcher) killOtherInstances() {
thisPid := os.Getpid()
thisProc, err := ps.FindProcess(thisPid)
execName := thisProc.Executable()
procs, err := ps.Processes()
if err != nil {
log.Fatal("could not get proc list:", err)
}
for _, proc := range procs {
if proc.Executable() == execName && proc.Pid() != thisPid {
fmt.Println("Killing other watcher exec =", execName, "pid =", proc.Pid())
osP, err := os.FindProcess(proc.Pid())
if err != nil {
log.Fatal("could not get os proc:", err)
}
err = osP.Kill()
if err != nil {
log.Fatal("could not kill os proc:", err)
}
}
}
}