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