blob: ff87a25a621dc89f1b2d93658edcccd980f42222 [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
Tim Windelschmidt9f21f532024-05-07 15:14:20 +020030 "source.monogon.dev/osbase/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 Bazanskicf864da2024-07-31 11:23:34 +0000105
106 metrics *metricsFanout
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100107}
108
Serge Bazanski19bb4122020-05-04 17:57:50 +0200109// SupervisorOpt are runtime configurable options for the supervisor.
110type SupervisorOpt func(s *supervisor)
111
Tim Windelschmidtae076612024-04-08 21:31:29 +0200112// WithPropagatePanic prevents the Supervisor from catching panics in
113// runnables and treating them as failures. This is useful to enable for
114// testing and local debugging.
115func WithPropagatePanic(s *supervisor) {
116 s.propagatePanic = true
117}
Serge Bazanski19bb4122020-05-04 17:57:50 +0200118
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 Bazanskicf864da2024-07-31 11:23:34 +0000125// WithMetrics makes the Supervisor export per-DN metrics into a given Metrics
126// implementation. This can be called repeatedly to export the same data into
127// multiple Metrics implementations.
128func WithMetrics(m Metrics) SupervisorOpt {
129 return func(s *supervisor) {
130 s.metrics.sub = append(s.metrics.sub, m)
131 }
132}
133
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100134// New creates a new supervisor with its root running the given root runnable.
135// The given context can be used to cancel the entire supervision tree.
Serge Bazanskif8a8e652021-07-06 16:23:43 +0200136//
137// For tests, we reccomend using TestHarness instead, which will also stream
138// logs to stderr and take care of propagating root runnable errors to the test
139// output.
Serge Bazanskic7359672020-10-30 16:38:57 +0100140func New(ctx context.Context, rootRunnable Runnable, opts ...SupervisorOpt) *supervisor {
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100141 sup := &supervisor{
Serge Bazanskic7359672020-10-30 16:38:57 +0100142 logtree: logtree.New(),
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100143 pReq: make(chan *processorRequest),
Serge Bazanskicf864da2024-07-31 11:23:34 +0000144 metrics: &metricsFanout{},
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100145 }
Serge Bazanski19bb4122020-05-04 17:57:50 +0200146
147 for _, o := range opts {
148 o(sup)
149 }
150
Serge Bazanskic7359672020-10-30 16:38:57 +0100151 sup.ilogger = sup.logtree.MustLeveledFor("supervisor")
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100152 sup.root = newNode("root", rootRunnable, sup, nil)
153
154 go sup.processor(ctx)
155
156 sup.pReq <- &processorRequest{
157 schedule: &processorRequestSchedule{dn: "root"},
158 }
Serge Bazanskiac6b6442020-05-06 19:13:43 +0200159
160 return sup
Serge Bazanski9c09c4e2020-03-24 13:58:01 +0100161}
Serge Bazanskic7359672020-10-30 16:38:57 +0100162
163func Logger(ctx context.Context) logtree.LeveledLogger {
164 node, unlock := fromContext(ctx)
165 defer unlock()
166 return node.sup.logtree.MustLeveledFor(logtree.DN(node.dn()))
167}
168
169func RawLogger(ctx context.Context) io.Writer {
170 node, unlock := fromContext(ctx)
171 defer unlock()
172 return node.sup.logtree.MustRawFor(logtree.DN(node.dn()))
173}
Serge Bazanski26d52252022-02-07 15:57:54 +0100174
175// SubLogger returns a LeveledLogger for a given name. The name is used to
176// placed that logger within the logtree hierarchy. For example, if the
177// runnable `root.foo` requests a SubLogger for name `bar`, the returned logger
178// will log to `root.foo.bar` in the logging tree.
179//
180// An error is returned if the given name is invalid or conflicts with a child
181// runnable of the current runnable. In addition, whenever a node uses a
182// sub-logger with a given name, that name also becomes unavailable for use as
183// a child runnable (no runnable and sub-logger may ever log into the same
184// logtree DN).
185func SubLogger(ctx context.Context, name string) (logtree.LeveledLogger, error) {
186 node, unlock := fromContext(ctx)
187 defer unlock()
188
189 if _, ok := node.children[name]; ok {
190 return nil, fmt.Errorf("name %q already in use by child runnable", name)
191 }
192 if !reNodeName.MatchString(name) {
193 return nil, fmt.Errorf("sub-logger name %q is invalid", name)
194 }
195 node.reserved[name] = true
196
197 dn := fmt.Sprintf("%s.%s", node.dn(), name)
198 return node.sup.logtree.LeveledFor(logtree.DN(dn))
199}
Serge Bazanski5a637b02022-02-18 12:18:04 +0100200
201// MustSubLogger is a wrapper around SubLogger which panics on error. Errors
202// should only happen due to invalid names, so as long as the given name is
203// compile-time constant and valid, this function is safe to use.
204func MustSubLogger(ctx context.Context, name string) logtree.LeveledLogger {
205 l, err := SubLogger(ctx, name)
206 if err != nil {
207 panic(err)
208 }
209 return l
210}