blob: 4896c15d341c6ddf54f5c3a68c33a4e54ae2e235 [file] [log] [blame]
Serge Bazanski86a714d2023-04-17 15:54:21 +02001package manager
2
3import (
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"
18 "source.monogon.dev/cloud/bmaas/bmdb/model"
19)
20
21// task describes a single server currently being processed by a control loop.
22type 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 Bazanski00cf57d2023-04-20 11:19:00 +020029 // 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 Bazanski86a714d2023-04-17 15:54:21 +020032}
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.
37type controlLoop interface {
Serge Bazanski00cf57d2023-04-20 11:19:00 +020038 getProcessInfo() processInfo
39
Serge Bazanski86a714d2023-04-17 15:54:21 +020040 // 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 Bazanski00cf57d2023-04-20 11:19:00 +020053type processInfo struct {
54 process model.Process
55 defaultBackoff bmdb.Backoff
56}
57
Serge Bazanski86a714d2023-04-17 15:54:21 +020058// ControlLoopConfig should be embedded the every component which acts as a
59// control loop. RegisterFlags should be called by the component whenever it is
60// registering its own flags. Check should be called whenever the component is
61// instantiated, after RegisterFlags has been called.
62type ControlLoopConfig struct {
63 // DBQueryLimiter limits the rate at which BMDB is queried for servers ready
64 // for BMaaS agent initialization. Must be set.
65 DBQueryLimiter *rate.Limiter
66
67 // Parallelism is how many instances of the Initializer will be allowed to run in
68 // parallel against the BMDB. This speeds up the process of starting/restarting
69 // agents significantly, as one initializer instance can handle at most one agent
70 // (re)starting process.
71 //
72 // If not set (ie. 0), default to 1. A good starting value for production
73 // deployments is 10 or so.
74 Parallelism int
75}
76
77func (c *ControlLoopConfig) getControlLoopConfig() *ControlLoopConfig {
78 return c
79}
80
81// flagLimiter configures a *rate.Limiter as a flag.
82func flagLimiter(l **rate.Limiter, name, defval, help string) {
83 syntax := "'duration,count' eg. '2m,10' for a 10-sized bucket refilled at one token every 2 minutes"
84 help = help + fmt.Sprintf(" (default: %q, syntax: %s)", defval, syntax)
85 flag.Func(name, help, func(val string) error {
86 if val == "" {
87 val = defval
88 }
89 parts := strings.Split(val, ",")
90 if len(parts) != 2 {
91 return fmt.Errorf("invalid syntax, want: %s", syntax)
92 }
93 duration, err := time.ParseDuration(parts[0])
94 if err != nil {
95 return fmt.Errorf("invalid duration: %w", err)
96 }
97 refill, err := strconv.ParseUint(parts[1], 10, 31)
98 if err != nil {
99 return fmt.Errorf("invalid refill rate: %w", err)
100 }
101 *l = rate.NewLimiter(rate.Every(duration), int(refill))
102 return nil
103 })
104 flag.Set(name, defval)
105}
106
107// RegisterFlags should be called on this configuration whenever the embeddeding
108// component/configuration is registering its own flags. The prefix should be the
109// name of the component.
110func (c *ControlLoopConfig) RegisterFlags(prefix string) {
111 flagLimiter(&c.DBQueryLimiter, prefix+"_db_query_rate", "250ms,8", "Rate limiting for BMDB queries")
112 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")
113}
114
115// Check should be called after RegisterFlags but before the control loop is ran.
116// If an error is returned, the control loop cannot start.
117func (c *ControlLoopConfig) Check() error {
118 if c.DBQueryLimiter == nil {
119 return fmt.Errorf("DBQueryLimiter must be configured")
120 }
121 if c.Parallelism == 0 {
122 c.Parallelism = 1
123 }
124 return nil
125}
126
127// RunControlLoop runs the given controlLoop implementation against the BMDB. The
128// loop will be run with the parallelism and rate configured by the
129// ControlLoopConfig embedded or otherwise returned by the controlLoop.
130func RunControlLoop(ctx context.Context, conn *bmdb.Connection, loop controlLoop) error {
131 clr := &controlLoopRunner{
132 loop: loop,
133 config: loop.getControlLoopConfig(),
134 }
135 return clr.run(ctx, conn)
136}
137
138// controlLoopRunner is a configured control loop with an underlying control loop
139// implementation.
140type controlLoopRunner struct {
141 config *ControlLoopConfig
142 loop controlLoop
143}
144
145// run the control loops(s) (depending on opts.Parallelism) blocking the current
146// goroutine until the given context expires and all provisioners quit.
147func (r *controlLoopRunner) run(ctx context.Context, conn *bmdb.Connection) error {
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200148 pinfo := r.loop.getProcessInfo()
149
Serge Bazanski86a714d2023-04-17 15:54:21 +0200150 eg := errgroup.Group{}
151 for j := 0; j < r.config.Parallelism; j += 1 {
152 eg.Go(func() error {
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200153 return r.runOne(ctx, conn, &pinfo)
Serge Bazanski86a714d2023-04-17 15:54:21 +0200154 })
155 }
156 return eg.Wait()
157}
158
159// run the control loop blocking the current goroutine until the given context
160// expires.
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200161func (r *controlLoopRunner) runOne(ctx context.Context, conn *bmdb.Connection, pinfo *processInfo) error {
Serge Bazanski86a714d2023-04-17 15:54:21 +0200162 var err error
163
164 // Maintain a BMDB session as long as possible.
165 var sess *bmdb.Session
166 for {
167 if sess == nil {
168 sess, err = conn.StartSession(ctx)
169 if err != nil {
170 return fmt.Errorf("could not start BMDB session: %w", err)
171 }
172 }
173 // Inside that session, run the main logic.
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200174 err := r.runInSession(ctx, sess, pinfo)
Serge Bazanski86a714d2023-04-17 15:54:21 +0200175
176 switch {
177 case err == nil:
178 case errors.Is(err, ctx.Err()):
179 return err
180 case errors.Is(err, bmdb.ErrSessionExpired):
181 klog.Errorf("Session expired, restarting...")
182 sess = nil
183 time.Sleep(time.Second)
184 case err != nil:
185 klog.Errorf("Processing failed: %v", err)
186 // TODO(q3k): close session
187 time.Sleep(time.Second)
188 }
189 }
190}
191
192// runInSession executes one iteration of the control loop within a BMDB session.
193// This control loop attempts to start or re-start the agent on any machines that
194// need this per the BMDB.
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200195func (r *controlLoopRunner) runInSession(ctx context.Context, sess *bmdb.Session, pinfo *processInfo) error {
196 t, err := r.source(ctx, sess, pinfo)
Serge Bazanski86a714d2023-04-17 15:54:21 +0200197 if err != nil {
198 return fmt.Errorf("could not source machine: %w", err)
199 }
200 if t == nil {
201 return nil
202 }
203 defer t.work.Cancel(ctx)
204
205 if err := r.loop.processMachine(ctx, t); err != nil {
206 klog.Errorf("Failed to process machine %s: %v", t.machine.MachineID, err)
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200207 err = t.work.Fail(ctx, &t.backoff, fmt.Sprintf("failed to process: %v", err))
Serge Bazanski86a714d2023-04-17 15:54:21 +0200208 return err
209 }
210 return nil
211}
212
213// source supplies returns a BMDB-locked server ready for processing by the
214// control loop, locked by a work item. If both task and error are nil, then
215// there are no machines needed to be initialized. The returned work item in task
216// _must_ be canceled or finished by the caller.
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200217func (r *controlLoopRunner) source(ctx context.Context, sess *bmdb.Session, pinfo *processInfo) (*task, error) {
Serge Bazanski86a714d2023-04-17 15:54:21 +0200218 r.config.DBQueryLimiter.Wait(ctx)
219
220 var machine *model.MachineProvided
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200221 work, err := sess.Work(ctx, pinfo.process, func(q *model.Queries) ([]uuid.UUID, error) {
Serge Bazanski86a714d2023-04-17 15:54:21 +0200222 machines, err := r.loop.getMachines(ctx, q, 1)
223 if err != nil {
224 return nil, err
225 }
226 if len(machines) < 1 {
227 return nil, bmdb.ErrNothingToDo
228 }
229 machine = &machines[0]
230 return []uuid.UUID{machines[0].MachineID}, nil
231 })
232
233 if errors.Is(err, bmdb.ErrNothingToDo) {
234 return nil, nil
235 }
236
237 if err != nil {
238 return nil, fmt.Errorf("while querying BMDB agent candidates: %w", err)
239 }
240
241 return &task{
242 machine: machine,
243 work: work,
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200244 backoff: pinfo.defaultBackoff,
Serge Bazanski86a714d2023-04-17 15:54:21 +0200245 }, nil
246}