-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexecution.go
More file actions
369 lines (331 loc) · 7.67 KB
/
Copy pathexecution.go
File metadata and controls
369 lines (331 loc) · 7.67 KB
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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package timeout
import (
"context"
"sync"
"time"
)
// Execution is the supervised run handle passed to Func.
type Execution interface {
Context() context.Context
Heartbeat()
Status(message string)
Progress(progress Progress)
ProgressTo(current, total int64)
BeginUnit(name string) Unit
Unit(name string, fn func(context.Context) error) error
Snapshot() Snapshot
}
type execution struct {
mu sync.Mutex
ctx context.Context
cancel context.CancelFunc
clock Clock
policy Policy
startedAt time.Time
lastActivityAt time.Time
lastProgressAt time.Time
statusMsg string
progress ProgressSnapshot
series progressSeries
units map[uint64]*unitState
nextUnitID uint64
state State
timedOut bool
kind TimeoutKind
timeoutUnit *UnitSnapshot
finishedOnce sync.Once
done chan struct{}
observer *asyncObserver
}
func runExecution(parent context.Context, cfg Config, fn Func) Result {
clock := cfg.clock
if clock == nil {
clock = realClock{}
}
ctx, cancel := context.WithCancel(parent)
start := clock.Now()
obs := newAsyncObserver(cfg.observer, cfg.observerSize, cfg.observerDrop)
exec := &execution{
ctx: ctx,
cancel: cancel,
clock: clock,
policy: cfg.policy,
startedAt: start,
lastActivityAt: start,
lastProgressAt: start,
units: make(map[uint64]*unitState),
state: StateRunning,
done: make(chan struct{}),
observer: obs,
}
exec.emit(EventStarted)
go exec.monitor()
var fnErr error
func() {
defer func() {
if r := recover(); r != nil {
fnErr = errString("timeout: panic in Func")
}
}()
fnErr = fn(exec)
}()
result := exec.finish(parent, fnErr)
obs.close()
return result
}
func (e *execution) Context() context.Context { return e.ctx }
func (e *execution) Heartbeat() {
e.mu.Lock()
defer e.mu.Unlock()
if e.timedOut || e.state != StateRunning {
return
}
now := e.clock.Now()
e.lastActivityAt = now
e.emitLocked(EventHeartbeat, now)
}
func (e *execution) Status(message string) {
e.mu.Lock()
defer e.mu.Unlock()
if e.timedOut || e.state != StateRunning {
return
}
now := e.clock.Now()
e.statusMsg = message
e.lastActivityAt = now
e.emitLocked(EventStatus, now)
}
func (e *execution) Progress(progress Progress) {
e.mu.Lock()
defer e.mu.Unlock()
if e.timedOut || e.state != StateRunning {
return
}
if progress.Total > 0 && progress.Current < 0 {
return
}
now := e.clock.Now()
idle, stall, next := classifyProgress(e.series, progress)
e.series = next
e.progress = progressSnapshotFrom(progress, now)
if idle {
e.lastActivityAt = now
}
ev := EventProgress
if stall {
e.lastProgressAt = now
ev = EventMeaningfulProgress
}
e.emitLocked(ev, now)
}
func (e *execution) ProgressTo(current, total int64) {
e.Progress(Progress{Current: current, Total: total})
}
func (e *execution) BeginUnit(name string) Unit {
e.mu.Lock()
defer e.mu.Unlock()
now := e.clock.Now()
e.nextUnitID++
id := e.nextUnitID
e.units[id] = &unitState{id: id, name: name, startedAt: now}
e.emitLocked(EventUnitStarted, now)
return &unitHandle{exec: e, id: id, name: name}
}
func (e *execution) endUnit(id uint64) {
e.mu.Lock()
defer e.mu.Unlock()
u, ok := e.units[id]
if !ok || u.ended {
return
}
u.ended = true
e.emitLocked(EventUnitEnded, e.clock.Now())
}
func (e *execution) Unit(name string, fn func(context.Context) error) error {
u := e.BeginUnit(name)
defer u.End()
if fn == nil {
return nil
}
return fn(e.Context())
}
func (e *execution) Snapshot() Snapshot {
e.mu.Lock()
defer e.mu.Unlock()
return e.snapshotLocked(e.clock.Now())
}
func (e *execution) snapshotLocked(now time.Time) Snapshot {
units := make([]UnitSnapshot, 0, len(e.units))
for _, u := range e.units {
elapsed := now.Sub(u.startedAt)
if u.ended {
// Elapsed frozen at end is not tracked separately; use now for active only.
elapsed = now.Sub(u.startedAt)
}
units = append(units, UnitSnapshot{
ID: u.id,
Name: u.name,
StartedAt: u.startedAt,
Elapsed: elapsed,
Limit: e.policy.Unit,
Active: !u.ended,
})
}
return Snapshot{
State: e.state,
StartedAt: e.startedAt,
Elapsed: now.Sub(e.startedAt),
LastActivityAt: e.lastActivityAt,
IdleFor: now.Sub(e.lastActivityAt),
LastProgressAt: e.lastProgressAt,
StallFor: now.Sub(e.lastProgressAt),
Status: e.statusMsg,
Progress: e.progress,
Units: units,
}
}
func (e *execution) monitor() {
defer close(e.done)
var ticker *time.Ticker
var tickerC <-chan time.Time
if e.clock.Watcher() == nil {
ticker = time.NewTicker(10 * time.Millisecond)
defer ticker.Stop()
tickerC = ticker.C
}
for {
if e.tryTimeout() {
return
}
select {
case <-e.ctx.Done():
// Parent cancel or timeout cancel — exit monitor.
return
case <-e.clock.Watcher():
continue
case <-tickerC:
continue
}
}
}
func (e *execution) tryTimeout() bool {
e.mu.Lock()
defer e.mu.Unlock()
if e.timedOut || e.state != StateRunning {
return e.timedOut
}
now := e.clock.Now()
kind, unitSnap := e.evaluateLocked(now)
if kind == KindNone {
return false
}
e.timedOut = true
e.kind = kind
e.timeoutUnit = unitSnap
e.emitLocked(EventTimeout, now)
e.emitLocked(EventTerminationRequested, now)
e.cancel()
return true
}
// evaluateLocked applies Hard > Unit > Stall > Idle.
func (e *execution) evaluateLocked(now time.Time) (TimeoutKind, *UnitSnapshot) {
if e.policy.Hard > 0 && now.Sub(e.startedAt) >= e.policy.Hard {
return KindHard, nil
}
if e.policy.Unit > 0 {
for _, u := range e.units {
if u.ended {
continue
}
if now.Sub(u.startedAt) >= e.policy.Unit {
snap := UnitSnapshot{
ID: u.id,
Name: u.name,
StartedAt: u.startedAt,
Elapsed: now.Sub(u.startedAt),
Limit: e.policy.Unit,
Active: true,
}
return KindUnit, &snap
}
}
}
if e.policy.Stall > 0 && now.Sub(e.lastProgressAt) >= e.policy.Stall {
return KindStall, nil
}
if e.policy.Idle > 0 && now.Sub(e.lastActivityAt) >= e.policy.Idle {
return KindIdle, nil
}
return KindNone, nil
}
func (e *execution) finish(parent context.Context, fnErr error) Result {
var result Result
e.finishedOnce.Do(func() {
// Stop monitor by canceling if still running without timeout.
e.mu.Lock()
timedOut := e.timedOut
kind := e.kind
unitSnap := e.timeoutUnit
started := e.startedAt
e.mu.Unlock()
if !timedOut {
e.cancel()
}
<-e.done
now := e.clock.Now()
e.mu.Lock()
e.state = StateFinished
snap := e.snapshotLocked(now)
timedOut = e.timedOut
kind = e.kind
unitSnap = e.timeoutUnit
e.mu.Unlock()
result = Result{
Snapshot: snap,
StartedAt: started,
FinishedAt: now,
Elapsed: now.Sub(started),
TimeoutUnit: unitSnap,
EventsDropped: e.observer.EventsDropped(),
}
switch {
case timedOut:
result.Status = StatusTimeout
result.Kind = kind
case parent.Err() != nil:
result.Status = StatusCanceled
result.Kind = KindNone
result.Err = parent.Err()
case fnErr != nil:
result.Status = StatusFailed
result.Err = fnErr
if isProbeFailure(fnErr) {
result.Kind = KindProbe
} else {
result.Kind = KindNone
}
default:
result.Status = StatusSucceeded
result.Kind = KindNone
}
e.mu.Lock()
e.emitLocked(EventFinished, now)
e.mu.Unlock()
})
return result
}
func (e *execution) emit(typ EventType) {
e.mu.Lock()
defer e.mu.Unlock()
e.emitLocked(typ, e.clock.Now())
}
func (e *execution) emitLocked(typ EventType, now time.Time) {
if e.observer == nil {
return
}
e.observer.emit(Event{
Type: typ,
Timestamp: now,
Snapshot: e.snapshotLocked(now),
})
}