blob: 965a667231d74b211b2d4cdd59ecd89b188d94fa [file] [log] [blame]
Serge Bazanski9c09c4e2020-03-24 13:58:01 +01001// Copyright 2020 The Monogon Project Authors.
2//
3// SPDX-License-Identifier: Apache-2.0
4//
5// Licensed under the Apache License, Version 2.0 (the "License");
6// you may not use this file except in compliance with the License.
7// You may obtain a copy of the License at
8//
9// http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing, software
12// distributed under the License is distributed on an "AS IS" BASIS,
13// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14// See the License for the specific language governing permissions and
15// limitations under the License.
16
17package supervisor
18
19import (
20 "context"
21 "errors"
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010022 "fmt"
23 "runtime/debug"
24 "time"
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010025)
26
27// The processor maintains runnable goroutines - ie., when requested will start one, and then once it exists it will
28// record the result and act accordingly. It is also responsible for detecting and acting upon supervision subtrees that
29// need to be restarted after death (via a 'GC' process)
30
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010031// processorRequest is a request for the processor. Only one of the fields can be set.
32type processorRequest struct {
Serge Bazanskiac6b6442020-05-06 19:13:43 +020033 schedule *processorRequestSchedule
34 died *processorRequestDied
35 waitSettled *processorRequestWaitSettled
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010036}
37
38// processorRequestSchedule requests that a given node's runnable be started.
39type processorRequestSchedule struct {
40 dn string
41}
42
43// processorRequestDied is a signal from a runnable goroutine that the runnable has died.
44type processorRequestDied struct {
45 dn string
46 err error
47}
48
Serge Bazanskiac6b6442020-05-06 19:13:43 +020049type processorRequestWaitSettled struct {
50 waiter chan struct{}
51}
52
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010053// processor is the main processing loop.
54func (s *supervisor) processor(ctx context.Context) {
55 s.ilogger.Info("supervisor processor started")
56
Serge Bazanskiac6b6442020-05-06 19:13:43 +020057 // Waiters waiting for the GC to be settled.
58 var waiters []chan struct{}
59
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010060 // The GC will run every millisecond if needed. Any time the processor requests a change in the supervision tree
61 // (ie a death or a new runnable) it will mark the state as dirty and run the GC on the next millisecond cycle.
62 gc := time.NewTicker(1 * time.Millisecond)
63 defer gc.Stop()
64 clean := true
65
Serge Bazanskiac6b6442020-05-06 19:13:43 +020066 // How long has the GC been clean. This is used to notify 'settled' waiters.
67 cleanCycles := 0
68
69 markDirty := func() {
70 clean = false
71 cleanCycles = 0
72 }
73
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010074 for {
75 select {
76 case <-ctx.Done():
Serge Bazanskic7359672020-10-30 16:38:57 +010077 s.ilogger.Infof("supervisor processor exiting: %v", ctx.Err())
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010078 s.processKill()
79 s.ilogger.Info("supervisor exited")
80 return
81 case <-gc.C:
82 if !clean {
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010083 s.processGC()
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010084 }
85 clean = true
Serge Bazanskiac6b6442020-05-06 19:13:43 +020086 cleanCycles += 1
87
88 // This threshold is somewhat arbitrary. It's a balance between test speed and test reliability.
89 if cleanCycles > 50 {
90 for _, w := range waiters {
91 close(w)
92 }
93 waiters = nil
94 }
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010095 case r := <-s.pReq:
96 switch {
97 case r.schedule != nil:
98 s.processSchedule(r.schedule)
Serge Bazanskiac6b6442020-05-06 19:13:43 +020099 markDirty()
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100100 case r.died != nil:
101 s.processDied(r.died)
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200102 markDirty()
103 case r.waitSettled != nil:
104 waiters = append(waiters, r.waitSettled.waiter)
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100105 default:
106 panic(fmt.Errorf("unhandled request %+v", r))
107 }
108 }
109 }
110}
111
112// processKill cancels all nodes in the supervision tree. This is only called right before exiting the processor, so
113// they do not get automatically restarted.
114func (s *supervisor) processKill() {
115 s.mu.Lock()
116 defer s.mu.Unlock()
117
118 // Gather all context cancel functions.
119 var cancels []func()
120 queue := []*node{s.root}
121 for {
122 if len(queue) == 0 {
123 break
124 }
125
126 cur := queue[0]
127 queue = queue[1:]
128
129 cancels = append(cancels, cur.ctxC)
130 for _, c := range cur.children {
131 queue = append(queue, c)
132 }
133 }
134
135 // Call all context cancels.
136 for _, c := range cancels {
137 c()
138 }
139}
140
141// processSchedule starts a node's runnable in a goroutine and records its output once it's done.
142func (s *supervisor) processSchedule(r *processorRequestSchedule) {
143 s.mu.Lock()
144 defer s.mu.Unlock()
145
146 n := s.nodeByDN(r.dn)
147 go func() {
Serge Bazanski19bb4122020-05-04 17:57:50 +0200148 if !s.propagatePanic {
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100149 defer func() {
150 if rec := recover(); rec != nil {
151 s.pReq <- &processorRequest{
152 died: &processorRequestDied{
153 dn: r.dn,
154 err: fmt.Errorf("panic: %v, stacktrace: %s", rec, string(debug.Stack())),
155 },
156 }
157 }
158 }()
159 }
160
161 res := n.runnable(n.ctx)
162
163 s.pReq <- &processorRequest{
164 died: &processorRequestDied{
165 dn: r.dn,
166 err: res,
167 },
168 }
169 }()
170}
171
172// processDied records the result from a runnable goroutine, and updates its node state accordingly. If the result
173// is a death and not an expected exit, related nodes (ie. children and group siblings) are canceled accordingly.
174func (s *supervisor) processDied(r *processorRequestDied) {
175 s.mu.Lock()
176 defer s.mu.Unlock()
177
178 // Okay, so a Runnable has quit. What now?
179 n := s.nodeByDN(r.dn)
180 ctx := n.ctx
181
182 // Simple case: it was marked as Done and quit with no error.
183 if n.state == nodeStateDone && r.err == nil {
184 // Do nothing. This was supposed to happen. Keep the process as DONE.
185 return
186 }
187
188 // Find innermost error to check if it's a context canceled error.
189 perr := r.err
190 for {
191 if inner := errors.Unwrap(perr); inner != nil {
192 perr = inner
193 continue
194 }
195 break
196 }
197
198 // Simple case: the context was canceled and the returned error is the context error.
199 if err := ctx.Err(); err != nil && perr == err {
200 // Mark the node as canceled successfully.
201 n.state = nodeStateCanceled
202 return
203 }
204
205 // Otherwise, the Runnable should not have died or quit. Handle accordingly.
206 err := r.err
207 // A lack of returned error is also an error.
208 if err == nil {
209 err = fmt.Errorf("returned when %s", n.state)
210 } else {
211 err = fmt.Errorf("returned error when %s: %w", n.state, err)
212 }
213
Serge Bazanskic7359672020-10-30 16:38:57 +0100214 s.ilogger.Errorf("Runnable %s died: %v", n.dn(), err)
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100215 // Mark as dead.
216 n.state = nodeStateDead
217
218 // Cancel that node's context, just in case something still depends on it.
219 n.ctxC()
220
221 // Cancel all siblings.
222 if n.parent != nil {
223 for name, _ := range n.parent.groupSiblings(n.name) {
224 if name == n.name {
225 continue
226 }
227 sibling := n.parent.children[name]
228 // TODO(q3k): does this need to run in a goroutine, ie. can a context cancel block?
229 sibling.ctxC()
230 }
231 }
232}
233
234// processGC runs the GC process. It's not really Garbage Collection, as in, it doesn't remove unnecessary tree nodes -
235// but it does find nodes that need to be restarted, find the subset that can and then schedules them for running.
236// As such, it's less of a Garbage Collector and more of a Necromancer. However, GC is a friendlier name.
237func (s *supervisor) processGC() {
238 s.mu.Lock()
239 defer s.mu.Unlock()
240
241 // The 'GC' serves is the main business logic of the supervision tree. It traverses a locked tree and tries to
242 // find subtrees that must be restarted (because of a DEAD/CANCELED runnable). It then finds which of these
243 // subtrees that should be restarted can be restarted, ie. which ones are fully recursively DEAD/CANCELED. It
244 // also finds the smallest set of largest subtrees that can be restarted, ie. if there's multiple DEAD runnables
245 // that can be restarted at once, it will do so.
246
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100247 // Phase one: Find all leaves.
248 // This is a simple DFS that finds all the leaves of the tree, ie all nodes that do not have children nodes.
249 leaves := make(map[string]bool)
250 queue := []*node{s.root}
251 for {
252 if len(queue) == 0 {
253 break
254 }
255 cur := queue[0]
256 queue = queue[1:]
257
258 for _, c := range cur.children {
259 queue = append([]*node{c}, queue...)
260 }
261
262 if len(cur.children) == 0 {
263 leaves[cur.dn()] = true
264 }
265 }
266
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100267 // Phase two: traverse tree from node to root and make note of all subtrees that can be restarted.
268 // A subtree is restartable/ready iff every node in that subtree is either CANCELED, DEAD or DONE.
269 // Such a 'ready' subtree can be restarted by the supervisor if needed.
270
271 // DNs that we already visited.
272 visited := make(map[string]bool)
273 // DNs whose subtrees are ready to be restarted.
274 // These are all subtrees recursively - ie., root.a.a and root.a will both be marked here.
275 ready := make(map[string]bool)
276
277 // We build a queue of nodes to visit, starting from the leaves.
278 queue = []*node{}
279 for l, _ := range leaves {
280 queue = append(queue, s.nodeByDN(l))
281 }
282
283 for {
284 if len(queue) == 0 {
285 break
286 }
287
288 cur := queue[0]
289 curDn := cur.dn()
290
291 queue = queue[1:]
292
293 // Do we have a decision about our children?
294 allVisited := true
295 for _, c := range cur.children {
296 if !visited[c.dn()] {
297 allVisited = false
298 break
299 }
300 }
301
302 // If no decision about children is available, it means we ended up in this subtree through some shorter path
303 // of a shorter/lower-order leaf. There is a path to a leaf that's longer than the one that caused this node
304 // to be enqueued. Easy solution: just push back the current element and retry later.
305 if !allVisited {
306 // Push back to queue and wait for a decision later.
307 queue = append(queue, cur)
308 continue
309 }
310
311 // All children have been visited and we have an idea about whether they're ready/restartable. All of the node's
312 // children must be restartable in order for this node to be restartable.
313 childrenReady := true
314 for _, c := range cur.children {
315 if !ready[c.dn()] {
316 childrenReady = false
317 break
318 }
319 }
320
321 // In addition to children, the node itself must be restartable (ie. DONE, DEAD or CANCELED).
322 curReady := false
323 switch cur.state {
324 case nodeStateDone:
325 curReady = true
326 case nodeStateCanceled:
327 curReady = true
328 case nodeStateDead:
329 curReady = true
330 }
331
332 // Note down that we have an opinion on this node, and note that opinion down.
333 visited[curDn] = true
334 ready[curDn] = childrenReady && curReady
335
336 // Now we can also enqueue the parent of this node for processing.
337 if cur.parent != nil && !visited[cur.parent.dn()] {
338 queue = append(queue, cur.parent)
339 }
340 }
341
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100342 // Phase 3: traverse tree from root to find largest subtrees that need to be restarted and are ready to be
343 // restarted.
344
345 // All DNs that need to be restarted by the GC process.
346 want := make(map[string]bool)
347 // All DNs that need to be restarted and can be restarted by the GC process - a subset of 'want' DNs.
348 can := make(map[string]bool)
349 // The set difference between 'want' and 'can' are all nodes that should be restarted but can't yet (ie. because
350 // a child is still in the process of being canceled).
351
352 // DFS from root.
353 queue = []*node{s.root}
354 for {
355 if len(queue) == 0 {
356 break
357 }
358
359 cur := queue[0]
360 queue = queue[1:]
361
362 // If this node is DEAD or CANCELED it should be restarted.
363 if cur.state == nodeStateDead || cur.state == nodeStateCanceled {
364 want[cur.dn()] = true
365 }
366
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200367 // If it should be restarted and is ready to be restarted...
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100368 if want[cur.dn()] && ready[cur.dn()] {
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200369 // And its parent context is valid (ie hasn't been canceled), mark it as restartable.
370 if cur.parent == nil || cur.parent.ctx.Err() == nil {
371 can[cur.dn()] = true
372 continue
373 }
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100374 }
375
376 // Otherwise, traverse further down the tree to see if something else needs to be done.
377 for _, c := range cur.children {
378 queue = append(queue, c)
379 }
380 }
381
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100382 // Reinitialize and reschedule all subtrees
383 for dn, _ := range can {
384 n := s.nodeByDN(dn)
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200385
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100386 // Only back off when the node unexpectedly died - not when it got canceled.
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200387 bo := time.Duration(0)
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100388 if n.state == nodeStateDead {
389 bo = n.bo.NextBackOff()
390 }
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200391
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100392 // Prepare node for rescheduling - remove its children, reset its state to new.
393 n.reset()
Serge Bazanskic7359672020-10-30 16:38:57 +0100394 s.ilogger.Infof("rescheduling supervised node %s with backoff %s", dn, bo.String())
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100395
396 // Reschedule node runnable to run after backoff.
397 go func(n *node, bo time.Duration) {
398 time.Sleep(bo)
399 s.pReq <- &processorRequest{
400 schedule: &processorRequestSchedule{dn: n.dn()},
401 }
402 }(n, bo)
403 }
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100404}