| Tim Windelschmidt | 6d33a43 | 2025-02-04 14:34:25 +0100 | [diff] [blame^] | 1 | // Copyright The Monogon Project Authors. |
| 2 | // SPDX-License-Identifier: Apache-2.0 |
| 3 | |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 4 | package manager |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "errors" |
| 9 | "flag" |
| 10 | "fmt" |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 11 | "time" |
| 12 | |
| 13 | "github.com/google/uuid" |
| 14 | "golang.org/x/sync/errgroup" |
| 15 | "golang.org/x/time/rate" |
| 16 | "k8s.io/klog/v2" |
| 17 | |
| 18 | "source.monogon.dev/cloud/bmaas/bmdb" |
| Serge Bazanski | c50f694 | 2023-04-24 18:27:22 +0200 | [diff] [blame] | 19 | "source.monogon.dev/cloud/bmaas/bmdb/metrics" |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 20 | "source.monogon.dev/cloud/bmaas/bmdb/model" |
| Tim Windelschmidt | b6308cd | 2023-10-10 21:19:03 +0200 | [diff] [blame] | 21 | "source.monogon.dev/go/mflags" |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 22 | ) |
| 23 | |
| 24 | // task describes a single server currently being processed by a control loop. |
| 25 | type task struct { |
| 26 | // machine is the machine data (including provider and provider ID) retrieved |
| 27 | // from the BMDB. |
| 28 | machine *model.MachineProvided |
| 29 | // work is a machine lock facilitated by BMDB that prevents machines from |
| 30 | // being processed by multiple workers at the same time. |
| 31 | work *bmdb.Work |
| Serge Bazanski | 00cf57d | 2023-04-20 11:19:00 +0200 | [diff] [blame] | 32 | // backoff is configured from processInfo.defaultBackoff but can be overridden by |
| 33 | // processMachine to set a different backoff policy for specific failure modes. |
| 34 | backoff bmdb.Backoff |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 35 | } |
| 36 | |
| 37 | // controlLoop is implemented by any component which should act as a BMDB-based |
| 38 | // control loop. Implementing these methods allows the given component to be |
| 39 | // started using RunControlLoop. |
| 40 | type controlLoop interface { |
| Serge Bazanski | 00cf57d | 2023-04-20 11:19:00 +0200 | [diff] [blame] | 41 | getProcessInfo() processInfo |
| 42 | |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 43 | // getMachines must return the list of machines ready to be processed by the |
| 44 | // control loop for a given control loop implementation. |
| 45 | getMachines(ctx context.Context, q *model.Queries, limit int32) ([]model.MachineProvided, error) |
| 46 | // processMachine will be called within the scope of an active task/BMDB work by |
| 47 | // the control loop logic. |
| 48 | processMachine(ctx context.Context, t *task) error |
| 49 | |
| 50 | // getControlLoopConfig is implemented by ControlLoopConfig which should be |
| 51 | // embedded by the control loop component. If not embedded, this method will have |
| 52 | // to be implemented, too. |
| 53 | getControlLoopConfig() *ControlLoopConfig |
| 54 | } |
| 55 | |
| Serge Bazanski | 00cf57d | 2023-04-20 11:19:00 +0200 | [diff] [blame] | 56 | type processInfo struct { |
| 57 | process model.Process |
| Serge Bazanski | c50f694 | 2023-04-24 18:27:22 +0200 | [diff] [blame] | 58 | processor metrics.Processor |
| Serge Bazanski | 00cf57d | 2023-04-20 11:19:00 +0200 | [diff] [blame] | 59 | defaultBackoff bmdb.Backoff |
| 60 | } |
| 61 | |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 62 | // ControlLoopConfig should be embedded the every component which acts as a |
| 63 | // control loop. RegisterFlags should be called by the component whenever it is |
| 64 | // registering its own flags. Check should be called whenever the component is |
| 65 | // instantiated, after RegisterFlags has been called. |
| 66 | type ControlLoopConfig struct { |
| 67 | // DBQueryLimiter limits the rate at which BMDB is queried for servers ready |
| 68 | // for BMaaS agent initialization. Must be set. |
| 69 | DBQueryLimiter *rate.Limiter |
| 70 | |
| 71 | // Parallelism is how many instances of the Initializer will be allowed to run in |
| 72 | // parallel against the BMDB. This speeds up the process of starting/restarting |
| 73 | // agents significantly, as one initializer instance can handle at most one agent |
| 74 | // (re)starting process. |
| 75 | // |
| 76 | // If not set (ie. 0), default to 1. A good starting value for production |
| 77 | // deployments is 10 or so. |
| 78 | Parallelism int |
| 79 | } |
| 80 | |
| 81 | func (c *ControlLoopConfig) getControlLoopConfig() *ControlLoopConfig { |
| 82 | return c |
| 83 | } |
| 84 | |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 85 | // RegisterFlags should be called on this configuration whenever the embeddeding |
| 86 | // component/configuration is registering its own flags. The prefix should be the |
| 87 | // name of the component. |
| 88 | func (c *ControlLoopConfig) RegisterFlags(prefix string) { |
| Tim Windelschmidt | b6308cd | 2023-10-10 21:19:03 +0200 | [diff] [blame] | 89 | mflags.Limiter(&c.DBQueryLimiter, prefix+"_db_query_rate", "250ms,8", "Rate limiting for BMDB queries") |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 90 | flag.IntVar(&c.Parallelism, prefix+"_loop_parallelism", 1, "How many initializer instances to run in parallel, ie. how many agents to attempt to (re)start at once") |
| 91 | } |
| 92 | |
| 93 | // Check should be called after RegisterFlags but before the control loop is ran. |
| 94 | // If an error is returned, the control loop cannot start. |
| 95 | func (c *ControlLoopConfig) Check() error { |
| 96 | if c.DBQueryLimiter == nil { |
| 97 | return fmt.Errorf("DBQueryLimiter must be configured") |
| 98 | } |
| 99 | if c.Parallelism == 0 { |
| 100 | c.Parallelism = 1 |
| 101 | } |
| 102 | return nil |
| 103 | } |
| 104 | |
| 105 | // RunControlLoop runs the given controlLoop implementation against the BMDB. The |
| 106 | // loop will be run with the parallelism and rate configured by the |
| 107 | // ControlLoopConfig embedded or otherwise returned by the controlLoop. |
| 108 | func RunControlLoop(ctx context.Context, conn *bmdb.Connection, loop controlLoop) error { |
| 109 | clr := &controlLoopRunner{ |
| 110 | loop: loop, |
| 111 | config: loop.getControlLoopConfig(), |
| 112 | } |
| 113 | return clr.run(ctx, conn) |
| 114 | } |
| 115 | |
| 116 | // controlLoopRunner is a configured control loop with an underlying control loop |
| 117 | // implementation. |
| 118 | type controlLoopRunner struct { |
| 119 | config *ControlLoopConfig |
| 120 | loop controlLoop |
| 121 | } |
| 122 | |
| 123 | // run the control loops(s) (depending on opts.Parallelism) blocking the current |
| 124 | // goroutine until the given context expires and all provisioners quit. |
| 125 | func (r *controlLoopRunner) run(ctx context.Context, conn *bmdb.Connection) error { |
| Serge Bazanski | 00cf57d | 2023-04-20 11:19:00 +0200 | [diff] [blame] | 126 | pinfo := r.loop.getProcessInfo() |
| 127 | |
| Tim Windelschmidt | 3b5a917 | 2024-05-23 13:33:52 +0200 | [diff] [blame] | 128 | var eg errgroup.Group |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 129 | for j := 0; j < r.config.Parallelism; j += 1 { |
| 130 | eg.Go(func() error { |
| Serge Bazanski | 00cf57d | 2023-04-20 11:19:00 +0200 | [diff] [blame] | 131 | return r.runOne(ctx, conn, &pinfo) |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 132 | }) |
| 133 | } |
| 134 | return eg.Wait() |
| 135 | } |
| 136 | |
| 137 | // run the control loop blocking the current goroutine until the given context |
| 138 | // expires. |
| Serge Bazanski | 00cf57d | 2023-04-20 11:19:00 +0200 | [diff] [blame] | 139 | func (r *controlLoopRunner) runOne(ctx context.Context, conn *bmdb.Connection, pinfo *processInfo) error { |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 140 | var err error |
| 141 | |
| 142 | // Maintain a BMDB session as long as possible. |
| 143 | var sess *bmdb.Session |
| 144 | for { |
| 145 | if sess == nil { |
| Serge Bazanski | c50f694 | 2023-04-24 18:27:22 +0200 | [diff] [blame] | 146 | sess, err = conn.StartSession(ctx, bmdb.SessionOption{Processor: pinfo.processor}) |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 147 | if err != nil { |
| 148 | return fmt.Errorf("could not start BMDB session: %w", err) |
| 149 | } |
| 150 | } |
| 151 | // Inside that session, run the main logic. |
| Serge Bazanski | 00cf57d | 2023-04-20 11:19:00 +0200 | [diff] [blame] | 152 | err := r.runInSession(ctx, sess, pinfo) |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 153 | |
| 154 | switch { |
| 155 | case err == nil: |
| 156 | case errors.Is(err, ctx.Err()): |
| 157 | return err |
| 158 | case errors.Is(err, bmdb.ErrSessionExpired): |
| 159 | klog.Errorf("Session expired, restarting...") |
| 160 | sess = nil |
| 161 | time.Sleep(time.Second) |
| Tim Windelschmidt | 438ae2e | 2024-04-11 23:23:12 +0200 | [diff] [blame] | 162 | default: |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 163 | klog.Errorf("Processing failed: %v", err) |
| 164 | // TODO(q3k): close session |
| 165 | time.Sleep(time.Second) |
| 166 | } |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | // runInSession executes one iteration of the control loop within a BMDB session. |
| 171 | // This control loop attempts to start or re-start the agent on any machines that |
| 172 | // need this per the BMDB. |
| Serge Bazanski | 00cf57d | 2023-04-20 11:19:00 +0200 | [diff] [blame] | 173 | func (r *controlLoopRunner) runInSession(ctx context.Context, sess *bmdb.Session, pinfo *processInfo) error { |
| 174 | t, err := r.source(ctx, sess, pinfo) |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 175 | if err != nil { |
| 176 | return fmt.Errorf("could not source machine: %w", err) |
| 177 | } |
| 178 | if t == nil { |
| 179 | return nil |
| 180 | } |
| 181 | defer t.work.Cancel(ctx) |
| 182 | |
| 183 | if err := r.loop.processMachine(ctx, t); err != nil { |
| 184 | klog.Errorf("Failed to process machine %s: %v", t.machine.MachineID, err) |
| Serge Bazanski | 00cf57d | 2023-04-20 11:19:00 +0200 | [diff] [blame] | 185 | err = t.work.Fail(ctx, &t.backoff, fmt.Sprintf("failed to process: %v", err)) |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 186 | return err |
| 187 | } |
| 188 | return nil |
| 189 | } |
| 190 | |
| 191 | // source supplies returns a BMDB-locked server ready for processing by the |
| 192 | // control loop, locked by a work item. If both task and error are nil, then |
| 193 | // there are no machines needed to be initialized. The returned work item in task |
| 194 | // _must_ be canceled or finished by the caller. |
| Serge Bazanski | 00cf57d | 2023-04-20 11:19:00 +0200 | [diff] [blame] | 195 | func (r *controlLoopRunner) source(ctx context.Context, sess *bmdb.Session, pinfo *processInfo) (*task, error) { |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 196 | r.config.DBQueryLimiter.Wait(ctx) |
| 197 | |
| 198 | var machine *model.MachineProvided |
| Serge Bazanski | 00cf57d | 2023-04-20 11:19:00 +0200 | [diff] [blame] | 199 | work, err := sess.Work(ctx, pinfo.process, func(q *model.Queries) ([]uuid.UUID, error) { |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 200 | machines, err := r.loop.getMachines(ctx, q, 1) |
| 201 | if err != nil { |
| 202 | return nil, err |
| 203 | } |
| 204 | if len(machines) < 1 { |
| 205 | return nil, bmdb.ErrNothingToDo |
| 206 | } |
| 207 | machine = &machines[0] |
| 208 | return []uuid.UUID{machines[0].MachineID}, nil |
| 209 | }) |
| 210 | |
| 211 | if errors.Is(err, bmdb.ErrNothingToDo) { |
| 212 | return nil, nil |
| 213 | } |
| 214 | |
| 215 | if err != nil { |
| 216 | return nil, fmt.Errorf("while querying BMDB agent candidates: %w", err) |
| 217 | } |
| 218 | |
| 219 | return &task{ |
| 220 | machine: machine, |
| 221 | work: work, |
| Serge Bazanski | 00cf57d | 2023-04-20 11:19:00 +0200 | [diff] [blame] | 222 | backoff: pinfo.defaultBackoff, |
| Serge Bazanski | 86a714d | 2023-04-17 15:54:21 +0200 | [diff] [blame] | 223 | }, nil |
| 224 | } |