blob: b30edbc8a32ca23849216afe67bb42e455f4eb5d [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"
Serge Bazanskic50f6942023-04-24 18:27:22 +020018 "source.monogon.dev/cloud/bmaas/bmdb/metrics"
Serge Bazanski86a714d2023-04-17 15:54:21 +020019 "source.monogon.dev/cloud/bmaas/bmdb/model"
20)
21
22// task describes a single server currently being processed by a control loop.
23type 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 Bazanski00cf57d2023-04-20 11:19:00 +020030 // 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 Bazanski86a714d2023-04-17 15:54:21 +020033}
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.
38type controlLoop interface {
Serge Bazanski00cf57d2023-04-20 11:19:00 +020039 getProcessInfo() processInfo
40
Serge Bazanski86a714d2023-04-17 15:54:21 +020041 // 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 Bazanski00cf57d2023-04-20 11:19:00 +020054type processInfo struct {
55 process model.Process
Serge Bazanskic50f6942023-04-24 18:27:22 +020056 processor metrics.Processor
Serge Bazanski00cf57d2023-04-20 11:19:00 +020057 defaultBackoff bmdb.Backoff
58}
59
Serge Bazanski86a714d2023-04-17 15:54:21 +020060// 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.
64type 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
79func (c *ControlLoopConfig) getControlLoopConfig() *ControlLoopConfig {
80 return c
81}
82
83// flagLimiter configures a *rate.Limiter as a flag.
84func 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.
112func (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.
119func (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.
132func 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.
142type 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.
149func (r *controlLoopRunner) run(ctx context.Context, conn *bmdb.Connection) error {
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200150 pinfo := r.loop.getProcessInfo()
151
Serge Bazanski86a714d2023-04-17 15:54:21 +0200152 eg := errgroup.Group{}
153 for j := 0; j < r.config.Parallelism; j += 1 {
154 eg.Go(func() error {
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200155 return r.runOne(ctx, conn, &pinfo)
Serge Bazanski86a714d2023-04-17 15:54:21 +0200156 })
157 }
158 return eg.Wait()
159}
160
161// run the control loop blocking the current goroutine until the given context
162// expires.
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200163func (r *controlLoopRunner) runOne(ctx context.Context, conn *bmdb.Connection, pinfo *processInfo) error {
Serge Bazanski86a714d2023-04-17 15:54:21 +0200164 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 Bazanskic50f6942023-04-24 18:27:22 +0200170 sess, err = conn.StartSession(ctx, bmdb.SessionOption{Processor: pinfo.processor})
Serge Bazanski86a714d2023-04-17 15:54:21 +0200171 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 Bazanski00cf57d2023-04-20 11:19:00 +0200176 err := r.runInSession(ctx, sess, pinfo)
Serge Bazanski86a714d2023-04-17 15:54:21 +0200177
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 Bazanski00cf57d2023-04-20 11:19:00 +0200197func (r *controlLoopRunner) runInSession(ctx context.Context, sess *bmdb.Session, pinfo *processInfo) error {
198 t, err := r.source(ctx, sess, pinfo)
Serge Bazanski86a714d2023-04-17 15:54:21 +0200199 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 Bazanski00cf57d2023-04-20 11:19:00 +0200209 err = t.work.Fail(ctx, &t.backoff, fmt.Sprintf("failed to process: %v", err))
Serge Bazanski86a714d2023-04-17 15:54:21 +0200210 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 Bazanski00cf57d2023-04-20 11:19:00 +0200219func (r *controlLoopRunner) source(ctx context.Context, sess *bmdb.Session, pinfo *processInfo) (*task, error) {
Serge Bazanski86a714d2023-04-17 15:54:21 +0200220 r.config.DBQueryLimiter.Wait(ctx)
221
222 var machine *model.MachineProvided
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200223 work, err := sess.Work(ctx, pinfo.process, func(q *model.Queries) ([]uuid.UUID, error) {
Serge Bazanski86a714d2023-04-17 15:54:21 +0200224 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 Bazanski00cf57d2023-04-20 11:19:00 +0200246 backoff: pinfo.defaultBackoff,
Serge Bazanski86a714d2023-04-17 15:54:21 +0200247 }, nil
248}