/
controller.go
265 lines (220 loc) · 5.96 KB
/
controller.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
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
package local
import (
"context"
"fmt"
"sync"
"time"
"github.com/windmilleng/tilt/internal/store"
"github.com/windmilleng/tilt/pkg/logger"
"github.com/windmilleng/tilt/pkg/model"
"github.com/windmilleng/tilt/pkg/model/logstore"
)
type Controller struct {
execer Execer
procs map[model.ManifestName]*currentProcess
procCount int
}
var _ store.Subscriber = &Controller{}
var _ store.TearDowner = &Controller{}
func NewController(execer Execer) *Controller {
return &Controller{
execer: execer,
procs: make(map[model.ManifestName]*currentProcess),
}
}
func (c *Controller) OnChange(ctx context.Context, st store.RStore) {
specs := c.determineServeSpecs(ctx, st)
c.update(ctx, specs, st)
}
func (c *Controller) determineServeSpecs(ctx context.Context, st store.RStore) []ServeSpec {
state := st.RLockState()
defer st.RUnlockState()
var r []ServeSpec
for _, mt := range state.Targets() {
if !mt.Manifest.IsLocal() {
continue
}
lt := mt.Manifest.LocalTarget()
if lt.ServeCmd.Empty() ||
mt.State.LastSuccessfulDeployTime.IsZero() {
continue
}
r = append(r, ServeSpec{
mt.Manifest.Name,
lt.ServeCmd,
mt.State.LastSuccessfulDeployTime,
})
}
return r
}
func (c *Controller) update(ctx context.Context, specs []ServeSpec, st store.RStore) {
var toStop []model.ManifestName
var toStart []ServeSpec
seen := make(map[model.ManifestName]bool)
for _, spec := range specs {
seen[spec.ManifestName] = true
proc := c.getOrMakeProc(spec.ManifestName)
if c.shouldStart(spec, proc) {
toStart = append(toStart, spec)
}
}
for name := range c.procs {
if !seen[name] {
toStop = append(toStop, name)
}
}
// stop old ones
for _, name := range toStop {
c.stop(name)
delete(c.procs, name)
}
// now start them
for _, spec := range toStart {
c.start(ctx, spec, st)
}
}
func (c *Controller) shouldStart(spec ServeSpec, proc *currentProcess) bool {
if proc.cancelFunc == nil {
// nothing is running, so start it
return true
}
if spec.TriggerTime.After(proc.spec.TriggerTime) {
// there's been a new trigger, so start it
return true
}
return false
}
func (c *Controller) stop(name model.ManifestName) {
proc := c.procs[name]
// change the process's current number so that any further events received by the existing process will be considered out of date
proc.incrProcNum()
if proc.cancelFunc == nil {
return
}
proc.cancelFunc()
<-proc.doneCh
proc.cancelFunc = nil
proc.doneCh = nil
}
func (c *Controller) getOrMakeProc(name model.ManifestName) *currentProcess {
if c.procs[name] == nil {
c.procs[name] = ¤tProcess{}
}
return c.procs[name]
}
func (c *Controller) TearDown(ctx context.Context) {
for name := range c.procs {
c.stop(name)
}
}
func (c *Controller) start(ctx context.Context, spec ServeSpec, st store.RStore) {
c.stop(spec.ManifestName)
proc := c.procs[spec.ManifestName]
proc.spec = spec
c.procCount++
proc.procNum = c.procCount
ctx, proc.cancelFunc = context.WithCancel(ctx)
w := LocalServeLogActionWriter{
store: st,
manifestName: spec.ManifestName,
procNum: proc.procNum,
stillHasSameProcNum: proc.stillHasSameProcNum(),
}
ctx = logger.CtxWithLogHandler(ctx, w)
statusCh := make(chan statusAndMetadata)
go processStatuses(statusCh, st, spec.ManifestName, proc.stillHasSameProcNum())
spanID := SpanIDForServeLog(proc.procNum)
proc.doneCh = c.execer.Start(ctx, spec.ServeCmd, logger.Get(ctx).Writer(logger.InfoLvl), statusCh, spanID)
}
func processStatuses(
statusCh chan statusAndMetadata,
st store.RStore,
manifestName model.ManifestName,
stillHasSameProcNum func() bool) {
for sm := range statusCh {
if !stillHasSameProcNum() {
continue
}
runtimeStatus := sm.status.ToRuntime()
if runtimeStatus != "" {
// TODO(matt) when we get an error, the dot is red in the web ui, but green in the TUI
st.Dispatch(LocalServeStatusAction{
ManifestName: manifestName,
Status: runtimeStatus,
PID: sm.pid,
SpanID: sm.spanID,
})
}
}
}
// currentProcess represents the current process for a Manifest, so that Controller can
// make sure there's at most one process per Manifest.
// (note: it may not be running yet, or may have already finished)
type currentProcess struct {
spec ServeSpec
procNum int
cancelFunc context.CancelFunc
// closed when the process finishes executing, intentionally or not
doneCh chan struct{}
mu sync.Mutex
}
func (p *currentProcess) stillHasSameProcNum() func() bool {
s := p.currentProcNum()
return func() bool {
return s == p.currentProcNum()
}
}
func (p *currentProcess) incrProcNum() {
p.mu.Lock()
defer p.mu.Unlock()
p.procNum++
}
func (p *currentProcess) currentProcNum() int {
p.mu.Lock()
defer p.mu.Unlock()
return p.procNum
}
type LocalServeLogActionWriter struct {
store store.RStore
manifestName model.ManifestName
stillHasSameProcNum func() bool
procNum int
}
func (w LocalServeLogActionWriter) Write(level logger.Level, fields logger.Fields, p []byte) error {
if !w.stillHasSameProcNum() {
return nil
}
w.store.Dispatch(store.NewLogAction(w.manifestName, SpanIDForServeLog(w.procNum), level, fields, p))
return nil
}
func SpanIDForServeLog(procNum int) logstore.SpanID {
return logstore.SpanID(fmt.Sprintf("localserve:%d", procNum))
}
// ServeSpec describes what Runner should be running
type ServeSpec struct {
ManifestName model.ManifestName
ServeCmd model.Cmd
TriggerTime time.Time // TriggerTime is how Runner knows to restart; if it's newer than the TriggerTime of the currently running command, then Runner should restart it
}
type statusAndMetadata struct {
pid int
status status
spanID model.LogSpanID
}
type status int
const (
Unknown status = iota
Running status = iota
Done status = iota
Error status = iota
)
func (s status) ToRuntime() model.RuntimeStatus {
switch s {
case Running:
return model.RuntimeStatusOK
case Error:
return model.RuntimeStatusError
default:
return ""
}
}