forked from moby/swarmkit
/
restart.go
383 lines (317 loc) · 10.1 KB
/
restart.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
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
package orchestrator
import (
"container/list"
"sync"
"time"
"github.com/docker/go-events"
"github.com/docker/swarmkit/api"
"github.com/docker/swarmkit/log"
"github.com/docker/swarmkit/manager/state"
"github.com/docker/swarmkit/manager/state/store"
"github.com/docker/swarmkit/protobuf/ptypes"
"golang.org/x/net/context"
)
const defaultOldTaskTimeout = time.Minute
const defaultRestartDelay = 5 * time.Second
type restartedInstance struct {
timestamp time.Time
}
type instanceRestartInfo struct {
// counter of restarts for this instance.
totalRestarts uint64
// Linked list of restartedInstance structs. Only used when
// Restart.MaxAttempts and Restart.Window are both
// nonzero.
restartedInstances *list.List
}
type delayedStart struct {
cancel func()
doneCh chan struct{}
}
// RestartSupervisor initiates and manages restarts. It's responsible for
// delaying restarts when applicable.
type RestartSupervisor struct {
mu sync.Mutex
store *store.MemoryStore
delays map[string]delayedStart
history map[instanceTuple]*instanceRestartInfo
historyByService map[string]map[instanceTuple]struct{}
taskTimeout time.Duration
}
// NewRestartSupervisor creates a new RestartSupervisor.
func NewRestartSupervisor(store *store.MemoryStore) *RestartSupervisor {
return &RestartSupervisor{
store: store,
delays: make(map[string]delayedStart),
history: make(map[instanceTuple]*instanceRestartInfo),
historyByService: make(map[string]map[instanceTuple]struct{}),
taskTimeout: defaultOldTaskTimeout,
}
}
// Restart initiates a new task to replace t if appropriate under the service's
// restart policy.
func (r *RestartSupervisor) Restart(ctx context.Context, tx store.Tx, service *api.Service, t api.Task) error {
// TODO(aluzzardi): This function should not depend on `service`.
t.DesiredState = api.TaskStateShutdown
err := store.UpdateTask(tx, &t)
if err != nil {
log.G(ctx).WithError(err).Errorf("failed to set task desired state to dead")
return err
}
if !r.shouldRestart(ctx, &t, service) {
return nil
}
var restartTask *api.Task
if isReplicatedService(service) {
restartTask = newTask(service, t.Instance)
} else if isGlobalService(service) {
restartTask = newTask(service, 0)
restartTask.NodeID = t.NodeID
} else {
log.G(ctx).Error("service not supported by restart supervisor")
return nil
}
n := store.GetNode(tx, t.NodeID)
restartTask.DesiredState = api.TaskStateAccepted
var restartDelay time.Duration
// Restart delay does not applied to drained nodes
if n == nil || n.Spec.Availability != api.NodeAvailabilityDrain {
if t.Spec.Restart != nil && t.Spec.Restart.Delay != nil {
var err error
restartDelay, err = ptypes.Duration(t.Spec.Restart.Delay)
if err != nil {
log.G(ctx).WithError(err).Error("invalid restart delay; using default")
restartDelay = defaultRestartDelay
}
} else {
restartDelay = defaultRestartDelay
}
}
waitStop := true
// Normally we wait for the old task to stop running, but we skip this
// if the old task is already dead or the node it's assigned to is down.
if (n != nil && n.Status.State == api.NodeStatus_DOWN) || t.Status.State > api.TaskStateRunning {
waitStop = false
}
if err := store.CreateTask(tx, restartTask); err != nil {
log.G(ctx).WithError(err).WithField("task.id", restartTask.ID).Error("task create failed")
return err
}
r.recordRestartHistory(restartTask)
r.DelayStart(ctx, tx, &t, restartTask.ID, restartDelay, waitStop)
return nil
}
func (r *RestartSupervisor) shouldRestart(ctx context.Context, t *api.Task, service *api.Service) bool {
// TODO(aluzzardi): This function should not depend on `service`.
condition := restartCondition(t)
if condition != api.RestartOnAny &&
(condition != api.RestartOnFailure || t.Status.State == api.TaskStateCompleted) {
return false
}
if t.Spec.Restart == nil || t.Spec.Restart.MaxAttempts == 0 {
return true
}
instanceTuple := instanceTuple{
instance: t.Instance,
serviceID: t.ServiceID,
}
// Instance is not meaningful for "global" tasks, so they need to be
// indexed by NodeID.
if isGlobalService(service) {
instanceTuple.nodeID = t.NodeID
}
r.mu.Lock()
defer r.mu.Unlock()
restartInfo := r.history[instanceTuple]
if restartInfo == nil {
return true
}
if t.Spec.Restart.Window == nil || (t.Spec.Restart.Window.Seconds == 0 && t.Spec.Restart.Window.Nanos == 0) {
return restartInfo.totalRestarts < t.Spec.Restart.MaxAttempts
}
if restartInfo.restartedInstances == nil {
return true
}
window, err := ptypes.Duration(t.Spec.Restart.Window)
if err != nil {
log.G(ctx).WithError(err).Error("invalid restart lookback window")
return restartInfo.totalRestarts < t.Spec.Restart.MaxAttempts
}
lookback := time.Now().Add(-window)
var next *list.Element
for e := restartInfo.restartedInstances.Front(); e != nil; e = next {
next = e.Next()
if e.Value.(restartedInstance).timestamp.After(lookback) {
break
}
restartInfo.restartedInstances.Remove(e)
}
numRestarts := uint64(restartInfo.restartedInstances.Len())
if numRestarts == 0 {
restartInfo.restartedInstances = nil
}
return numRestarts < t.Spec.Restart.MaxAttempts
}
func (r *RestartSupervisor) recordRestartHistory(restartTask *api.Task) {
if restartTask.Spec.Restart == nil || restartTask.Spec.Restart.MaxAttempts == 0 {
// No limit on the number of restarts, so no need to record
// history.
return
}
tuple := instanceTuple{
instance: restartTask.Instance,
serviceID: restartTask.ServiceID,
nodeID: restartTask.NodeID,
}
r.mu.Lock()
defer r.mu.Unlock()
if r.history[tuple] == nil {
r.history[tuple] = &instanceRestartInfo{}
}
restartInfo := r.history[tuple]
restartInfo.totalRestarts++
if r.historyByService[restartTask.ServiceID] == nil {
r.historyByService[restartTask.ServiceID] = make(map[instanceTuple]struct{})
}
r.historyByService[restartTask.ServiceID][tuple] = struct{}{}
if restartTask.Spec.Restart.Window != nil && (restartTask.Spec.Restart.Window.Seconds != 0 || restartTask.Spec.Restart.Window.Nanos != 0) {
if restartInfo.restartedInstances == nil {
restartInfo.restartedInstances = list.New()
}
restartedInstance := restartedInstance{
timestamp: time.Now(),
}
restartInfo.restartedInstances.PushBack(restartedInstance)
}
}
// DelayStart starts a timer that moves the task from READY to RUNNING once:
// - The restart delay has elapsed (if applicable)
// - The old task that it's replacing has stopped running (or this times out)
// It must be called during an Update transaction to ensure that it does not
// miss events. The purpose of the store.Tx argument is to avoid accidental
// calls outside an Update transaction.
func (r *RestartSupervisor) DelayStart(ctx context.Context, _ store.Tx, oldTask *api.Task, newTaskID string, delay time.Duration, waitStop bool) <-chan struct{} {
ctx, cancel := context.WithCancel(context.Background())
doneCh := make(chan struct{})
r.mu.Lock()
for {
oldDelay, ok := r.delays[newTaskID]
if !ok {
break
}
oldDelay.cancel()
r.mu.Unlock()
// Note that this channel read should only block for a very
// short time, because we cancelled the existing delay and
// that should cause it to stop immediately.
<-oldDelay.doneCh
r.mu.Lock()
}
r.delays[newTaskID] = delayedStart{cancel: cancel, doneCh: doneCh}
r.mu.Unlock()
var watch chan events.Event
cancelWatch := func() {}
if waitStop && oldTask != nil {
// Wait for either the old task to complete, or the old task's
// node to become unavailable.
watch, cancelWatch = state.Watch(
r.store.WatchQueue(),
state.EventUpdateTask{
Task: &api.Task{ID: oldTask.ID, Status: api.TaskStatus{State: api.TaskStateRunning}},
Checks: []state.TaskCheckFunc{state.TaskCheckID, state.TaskCheckStateGreaterThan},
},
state.EventUpdateNode{
Node: &api.Node{ID: oldTask.NodeID, Status: api.NodeStatus{State: api.NodeStatus_DOWN}},
Checks: []state.NodeCheckFunc{state.NodeCheckID, state.NodeCheckState},
},
state.EventDeleteNode{
Node: &api.Node{ID: oldTask.NodeID},
Checks: []state.NodeCheckFunc{state.NodeCheckID},
},
)
}
go func() {
defer func() {
cancelWatch()
r.mu.Lock()
delete(r.delays, newTaskID)
r.mu.Unlock()
close(doneCh)
}()
oldTaskTimeout := time.After(r.taskTimeout)
// Wait for the delay to elapse, if one is specified.
if delay != 0 {
select {
case <-time.After(delay):
case <-ctx.Done():
return
}
}
if waitStop {
select {
case <-watch:
case <-oldTaskTimeout:
case <-ctx.Done():
return
}
}
err := r.store.Update(func(tx store.Tx) error {
err := r.StartNow(tx, newTaskID)
if err != nil {
log.G(ctx).WithError(err).WithField("task.id", newTaskID).Error("moving task out of delayed state failed")
}
return nil
})
if err != nil {
log.G(ctx).WithError(err).WithField("task.id", newTaskID).Error("task restart transaction failed")
}
}()
return doneCh
}
// StartNow moves the task into the RUNNING state so it will proceed to start
// up.
func (r *RestartSupervisor) StartNow(tx store.Tx, taskID string) error {
t := store.GetTask(tx, taskID)
if t == nil || t.DesiredState > api.TaskStateReady {
return nil
}
t.DesiredState = api.TaskStateRunning
return store.UpdateTask(tx, t)
}
// Cancel cancels a pending restart.
func (r *RestartSupervisor) Cancel(taskID string) {
r.mu.Lock()
delay, ok := r.delays[taskID]
r.mu.Unlock()
if !ok {
return
}
delay.cancel()
<-delay.doneCh
}
// CancelAll aborts all pending restarts and waits for any instances of
// StartNow that have already triggered to complete.
func (r *RestartSupervisor) CancelAll() {
var cancelled []delayedStart
r.mu.Lock()
for _, delay := range r.delays {
delay.cancel()
}
r.mu.Unlock()
for _, delay := range cancelled {
<-delay.doneCh
}
}
// ClearServiceHistory forgets restart history related to a given service ID.
func (r *RestartSupervisor) ClearServiceHistory(serviceID string) {
r.mu.Lock()
defer r.mu.Unlock()
tuples := r.historyByService[serviceID]
if tuples == nil {
return
}
delete(r.historyByService, serviceID)
for t := range tuples {
delete(r.history, t)
}
}