Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 1 | // 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 | |
| 17 | package supervisor |
| 18 | |
| 19 | import ( |
| 20 | "context" |
| 21 | "errors" |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 22 | "fmt" |
| 23 | "runtime/debug" |
| 24 | "time" |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 25 | ) |
| 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 Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 31 | // processorRequest is a request for the processor. Only one of the fields can be set. |
| 32 | type processorRequest struct { |
Serge Bazanski | ac6b644 | 2020-05-06 19:13:43 +0200 | [diff] [blame] | 33 | schedule *processorRequestSchedule |
| 34 | died *processorRequestDied |
| 35 | waitSettled *processorRequestWaitSettled |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 36 | } |
| 37 | |
| 38 | // processorRequestSchedule requests that a given node's runnable be started. |
| 39 | type processorRequestSchedule struct { |
| 40 | dn string |
| 41 | } |
| 42 | |
| 43 | // processorRequestDied is a signal from a runnable goroutine that the runnable has died. |
| 44 | type processorRequestDied struct { |
| 45 | dn string |
| 46 | err error |
| 47 | } |
| 48 | |
Serge Bazanski | ac6b644 | 2020-05-06 19:13:43 +0200 | [diff] [blame] | 49 | type processorRequestWaitSettled struct { |
| 50 | waiter chan struct{} |
| 51 | } |
| 52 | |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 53 | // processor is the main processing loop. |
| 54 | func (s *supervisor) processor(ctx context.Context) { |
| 55 | s.ilogger.Info("supervisor processor started") |
| 56 | |
Serge Bazanski | ac6b644 | 2020-05-06 19:13:43 +0200 | [diff] [blame] | 57 | // Waiters waiting for the GC to be settled. |
| 58 | var waiters []chan struct{} |
| 59 | |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 60 | // 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 Bazanski | ac6b644 | 2020-05-06 19:13:43 +0200 | [diff] [blame] | 66 | // 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 Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 74 | for { |
| 75 | select { |
| 76 | case <-ctx.Done(): |
Serge Bazanski | c735967 | 2020-10-30 16:38:57 +0100 | [diff] [blame] | 77 | s.ilogger.Infof("supervisor processor exiting: %v", ctx.Err()) |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 78 | s.processKill() |
| 79 | s.ilogger.Info("supervisor exited") |
| 80 | return |
| 81 | case <-gc.C: |
| 82 | if !clean { |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 83 | s.processGC() |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 84 | } |
| 85 | clean = true |
Serge Bazanski | ac6b644 | 2020-05-06 19:13:43 +0200 | [diff] [blame] | 86 | 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 Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 95 | case r := <-s.pReq: |
| 96 | switch { |
| 97 | case r.schedule != nil: |
| 98 | s.processSchedule(r.schedule) |
Serge Bazanski | ac6b644 | 2020-05-06 19:13:43 +0200 | [diff] [blame] | 99 | markDirty() |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 100 | case r.died != nil: |
| 101 | s.processDied(r.died) |
Serge Bazanski | ac6b644 | 2020-05-06 19:13:43 +0200 | [diff] [blame] | 102 | markDirty() |
| 103 | case r.waitSettled != nil: |
| 104 | waiters = append(waiters, r.waitSettled.waiter) |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 105 | 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. |
| 114 | func (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. |
| 142 | func (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 Bazanski | 19bb412 | 2020-05-04 17:57:50 +0200 | [diff] [blame] | 148 | if !s.propagatePanic { |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 149 | 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. |
| 174 | func (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 Bazanski | c735967 | 2020-10-30 16:38:57 +0100 | [diff] [blame] | 214 | s.ilogger.Errorf("Runnable %s died: %v", n.dn(), err) |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 215 | // 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. |
| 237 | func (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 Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 247 | // 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 Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 267 | // 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 Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 342 | // 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 Bazanski | ac6b644 | 2020-05-06 19:13:43 +0200 | [diff] [blame] | 367 | // If it should be restarted and is ready to be restarted... |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 368 | if want[cur.dn()] && ready[cur.dn()] { |
Serge Bazanski | ac6b644 | 2020-05-06 19:13:43 +0200 | [diff] [blame] | 369 | // 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 Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 374 | } |
| 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 Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 382 | // Reinitialize and reschedule all subtrees |
| 383 | for dn, _ := range can { |
| 384 | n := s.nodeByDN(dn) |
Serge Bazanski | ac6b644 | 2020-05-06 19:13:43 +0200 | [diff] [blame] | 385 | |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 386 | // Only back off when the node unexpectedly died - not when it got canceled. |
Serge Bazanski | ac6b644 | 2020-05-06 19:13:43 +0200 | [diff] [blame] | 387 | bo := time.Duration(0) |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 388 | if n.state == nodeStateDead { |
| 389 | bo = n.bo.NextBackOff() |
| 390 | } |
Serge Bazanski | ac6b644 | 2020-05-06 19:13:43 +0200 | [diff] [blame] | 391 | |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 392 | // Prepare node for rescheduling - remove its children, reset its state to new. |
| 393 | n.reset() |
Serge Bazanski | c735967 | 2020-10-30 16:38:57 +0100 | [diff] [blame] | 394 | s.ilogger.Infof("rescheduling supervised node %s with backoff %s", dn, bo.String()) |
Serge Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 395 | |
| 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 Bazanski | 9c09c4e | 2020-03-24 13:58:01 +0100 | [diff] [blame] | 404 | } |