-
Notifications
You must be signed in to change notification settings - Fork 13
/
watcher.go
150 lines (128 loc) · 4.12 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
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
package rtwatcher
import (
"encoding/json"
"os"
"runtime/debug"
"strconv"
"strings"
"time"
anaConst "github.com/ActiveState/cli/internal/analytics/constants"
"github.com/ActiveState/cli/internal/analytics/dimensions"
"github.com/ActiveState/cli/internal/config"
"github.com/ActiveState/cli/internal/constants"
"github.com/ActiveState/cli/internal/errs"
"github.com/ActiveState/cli/internal/logging"
"github.com/ActiveState/cli/internal/multilog"
"github.com/ActiveState/cli/internal/rtutils/ptr"
"github.com/ActiveState/cli/internal/runbits/panics"
)
const defaultInterval = 1 * time.Minute
const CfgKey = "runtime-watchers"
type Watcher struct {
an analytics
cfg *config.Instance
watching []entry
stop chan struct{}
interval time.Duration
}
type analytics interface {
EventWithSource(category, action, source string, dim ...*dimensions.Values)
}
func New(cfg *config.Instance, an analytics) *Watcher {
w := &Watcher{an: an, stop: make(chan struct{}, 1), cfg: cfg, interval: defaultInterval}
if watchersJson := w.cfg.GetString(CfgKey); watchersJson != "" {
watchers := []entry{}
err := json.Unmarshal([]byte(watchersJson), &watchers)
if err != nil {
multilog.Error("Could not unmarshal watchersL %s", errs.JoinMessage(err))
} else {
w.watching = watchers
}
}
if v := os.Getenv(constants.HeartbeatIntervalEnvVarName); v != "" {
vv, err := strconv.Atoi(v)
if err != nil {
logging.Warning("Invalid value for %s: %s", constants.HeartbeatIntervalEnvVarName, v)
} else {
w.interval = time.Duration(vv) * time.Millisecond
}
}
go w.ticker(w.check)
return w
}
func (w *Watcher) ticker(cb func()) {
defer func() { panics.LogPanics(recover(), debug.Stack()) }()
logging.Debug("Starting watcher ticker with interval %s", w.interval.String())
ticker := time.NewTicker(w.interval)
for {
select {
case <-ticker.C:
cb()
case <-w.stop:
logging.Debug("Stopping watcher ticker")
return
}
}
}
func (w *Watcher) check() {
watching := w.watching[:0]
for i := range w.watching {
e := w.watching[i] // Must use index, because we are deleting indexes further down
running, err := e.IsRunning()
if err != nil && !errs.Matches(err, &processError{}) {
multilog.Error("Could not check if runtime process is running: %s", errs.JoinMessage(err))
// Don't return yet, the conditional below still needs to clear this entry
}
if !running {
logging.Debug("Runtime process %d:%s is not running, removing from watcher", e.PID, e.Exec)
continue
}
watching = append(watching, e)
go w.RecordUsage(e)
}
w.watching = watching
}
func (w *Watcher) RecordUsage(e entry) {
logging.Debug("Recording usage of %s (%d)", e.Exec, e.PID)
w.an.EventWithSource(anaConst.CatRuntimeUsage, anaConst.ActRuntimeHeartbeat, e.Source, e.Dims)
}
func (w *Watcher) GetProcessesInUse(execDir string) []entry {
inUse := make([]entry, 0)
execDir = strings.ToLower(execDir) // match case-insensitively
for _, proc := range w.watching {
if !strings.Contains(strings.ToLower(proc.Exec), execDir) {
continue
}
isRunning, err := proc.IsRunning()
if err != nil && !errs.Matches(err, &processError{}) {
multilog.Error("Could not check if runtime process is running: %s", errs.JoinMessage(err))
// Any errors should not affect fetching which processes are currently in use. We just won't
// include this one in the list.
}
if !isRunning {
logging.Debug("Runtime process %d:%s is not running", proc.PID, proc.Exec)
continue
}
inUse = append(inUse, proc) // append a copy
}
return inUse
}
func (w *Watcher) Close() error {
logging.Debug("Closing runtime watcher")
close(w.stop)
if len(w.watching) > 0 {
watchingJson, err := json.Marshal(w.watching)
if err != nil {
return errs.Wrap(err, "Could not marshal watchers")
}
return w.cfg.Set(CfgKey, watchingJson)
}
return nil
}
func (w *Watcher) Watch(pid int, exec, source string, dims *dimensions.Values) {
logging.Debug("Watching %s (%d)", exec, pid)
dims.Sequence = ptr.To(-1) // sequence is meaningless for heartbeat events
e := entry{pid, exec, source, dims}
w.watching = append(w.watching, e)
go w.RecordUsage(e) // initial event
}