blob: ef7b909d22efefd59ffaa3546747823e22e21b24 [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
Serge Bazanski216fe7b2021-05-21 18:36:16 +020019// The service supervision library allows for writing of reliable,
20// service-style software within a Metropolis node. It builds upon the
21// Erlang/OTP supervision tree system, adapted to be more Go-ish. For detailed
22// design see go/supervision.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010023
24import (
25 "context"
Serge Bazanski26d52252022-02-07 15:57:54 +010026 "fmt"
Serge Bazanskic7359672020-10-30 16:38:57 +010027 "io"
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010028 "sync"
29
Serge Bazanski31370b02021-01-07 16:31:14 +010030 "source.monogon.dev/metropolis/pkg/logtree"
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010031)
32
Serge Bazanski216fe7b2021-05-21 18:36:16 +020033// A Runnable is a function that will be run in a goroutine, and supervised
34// throughout its lifetime. It can in turn start more runnables as its
35// children, and those will form part of a supervision tree.
36// The context passed to a runnable is very important and needs to be handled
37// properly. It will be live (non-errored) as long as the runnable should be
38// running, and canceled (ctx.Err() will be non-nil) when the supervisor wants
39// it to exit. This means this context is also perfectly usable for performing
40// any blocking operations.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010041type Runnable func(ctx context.Context) error
42
Serge Bazanski216fe7b2021-05-21 18:36:16 +020043// RunGroup starts a set of runnables as a group. These runnables will run
44// together, and if any one of them quits unexpectedly, the result will be
45// canceled and restarted.
46// The context here must be an existing Runnable context, and the spawned
47// runnables will run under the node that this context represents.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010048func RunGroup(ctx context.Context, runnables map[string]Runnable) error {
49 node, unlock := fromContext(ctx)
50 defer unlock()
51 return node.runGroup(runnables)
52}
53
54// Run starts a single runnable in its own group.
55func Run(ctx context.Context, name string, runnable Runnable) error {
56 return RunGroup(ctx, map[string]Runnable{
57 name: runnable,
58 })
59}
60
Serge Bazanski216fe7b2021-05-21 18:36:16 +020061// Signal tells the supervisor that the calling runnable has reached a certain
62// state of its lifecycle. All runnables should SignalHealthy when they are
63// ready with set up, running other child runnables and are now 'serving'.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010064func Signal(ctx context.Context, signal SignalType) {
65 node, unlock := fromContext(ctx)
66 defer unlock()
67 node.signal(signal)
68}
69
70type SignalType int
71
72const (
Serge Bazanski216fe7b2021-05-21 18:36:16 +020073 // The runnable is healthy, done with setup, done with spawning more
74 // Runnables, and ready to serve in a loop. The runnable needs to check
75 // the parent context and ensure that if that context is done, the runnable
76 // exits.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010077 SignalHealthy SignalType = iota
Serge Bazanski216fe7b2021-05-21 18:36:16 +020078 // The runnable is done - it does not need to run any loop. This is useful
79 // for Runnables that only set up other child runnables. This runnable will
80 // be restarted if a related failure happens somewhere in the supervision
81 // tree.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010082 SignalDone
83)
84
Serge Bazanski216fe7b2021-05-21 18:36:16 +020085// supervisor represents and instance of the supervision system. It keeps track
86// of a supervision tree and a request channel to its internal processor
87// goroutine.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010088type supervisor struct {
89 // mu guards the entire state of the supervisor.
90 mu sync.RWMutex
Serge Bazanski216fe7b2021-05-21 18:36:16 +020091 // root is the root node of the supervision tree, named 'root'. It
92 // represents the Runnable started with the supervisor.New call.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010093 root *node
Serge Bazanskic7359672020-10-30 16:38:57 +010094 // logtree is the main logtree exposed to runnables and used internally.
95 logtree *logtree.LogTree
96 // ilogger is the internal logger logging to "supervisor" in the logtree.
97 ilogger logtree.LeveledLogger
Serge Bazanski9c09c4e2020-03-24 13:58:01 +010098
Serge Bazanski216fe7b2021-05-21 18:36:16 +020099 // pReq is an interface channel to the lifecycle processor of the
100 // supervisor.
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100101 pReq chan *processorRequest
Serge Bazanski19bb4122020-05-04 17:57:50 +0200102
103 // propagate panics, ie. don't catch them.
104 propagatePanic bool
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100105}
106
Serge Bazanski19bb4122020-05-04 17:57:50 +0200107// SupervisorOpt are runtime configurable options for the supervisor.
108type SupervisorOpt func(s *supervisor)
109
110var (
Serge Bazanski216fe7b2021-05-21 18:36:16 +0200111 // WithPropagatePanic prevents the Supervisor from catching panics in
112 // runnables and treating them as failures. This is useful to enable for
113 // testing and local debugging.
Serge Bazanski19bb4122020-05-04 17:57:50 +0200114 WithPropagatePanic = func(s *supervisor) {
115 s.propagatePanic = true
116 }
117)
118
Serge Bazanskic7359672020-10-30 16:38:57 +0100119func WithExistingLogtree(lt *logtree.LogTree) SupervisorOpt {
120 return func(s *supervisor) {
121 s.logtree = lt
122 }
123}
124
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100125// New creates a new supervisor with its root running the given root runnable.
126// The given context can be used to cancel the entire supervision tree.
Serge Bazanskif8a8e652021-07-06 16:23:43 +0200127//
128// For tests, we reccomend using TestHarness instead, which will also stream
129// logs to stderr and take care of propagating root runnable errors to the test
130// output.
Serge Bazanskic7359672020-10-30 16:38:57 +0100131func New(ctx context.Context, rootRunnable Runnable, opts ...SupervisorOpt) *supervisor {
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100132 sup := &supervisor{
Serge Bazanskic7359672020-10-30 16:38:57 +0100133 logtree: logtree.New(),
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100134 pReq: make(chan *processorRequest),
135 }
Serge Bazanski19bb4122020-05-04 17:57:50 +0200136
137 for _, o := range opts {
138 o(sup)
139 }
140
Serge Bazanskic7359672020-10-30 16:38:57 +0100141 sup.ilogger = sup.logtree.MustLeveledFor("supervisor")
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100142 sup.root = newNode("root", rootRunnable, sup, nil)
143
144 go sup.processor(ctx)
145
146 sup.pReq <- &processorRequest{
147 schedule: &processorRequestSchedule{dn: "root"},
148 }
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200149
150 return sup
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100151}
Serge Bazanskic7359672020-10-30 16:38:57 +0100152
153func Logger(ctx context.Context) logtree.LeveledLogger {
154 node, unlock := fromContext(ctx)
155 defer unlock()
156 return node.sup.logtree.MustLeveledFor(logtree.DN(node.dn()))
157}
158
159func RawLogger(ctx context.Context) io.Writer {
160 node, unlock := fromContext(ctx)
161 defer unlock()
162 return node.sup.logtree.MustRawFor(logtree.DN(node.dn()))
163}
Serge Bazanski26d52252022-02-07 15:57:54 +0100164
165// SubLogger returns a LeveledLogger for a given name. The name is used to
166// placed that logger within the logtree hierarchy. For example, if the
167// runnable `root.foo` requests a SubLogger for name `bar`, the returned logger
168// will log to `root.foo.bar` in the logging tree.
169//
170// An error is returned if the given name is invalid or conflicts with a child
171// runnable of the current runnable. In addition, whenever a node uses a
172// sub-logger with a given name, that name also becomes unavailable for use as
173// a child runnable (no runnable and sub-logger may ever log into the same
174// logtree DN).
175func SubLogger(ctx context.Context, name string) (logtree.LeveledLogger, error) {
176 node, unlock := fromContext(ctx)
177 defer unlock()
178
179 if _, ok := node.children[name]; ok {
180 return nil, fmt.Errorf("name %q already in use by child runnable", name)
181 }
182 if !reNodeName.MatchString(name) {
183 return nil, fmt.Errorf("sub-logger name %q is invalid", name)
184 }
185 node.reserved[name] = true
186
187 dn := fmt.Sprintf("%s.%s", node.dn(), name)
188 return node.sup.logtree.LeveledFor(logtree.DN(dn))
189}