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