blob: e1fdd1dc86ac719e092ff6ee5d361204cf7b51cf [file] [log] [blame]
Serge Bazanski86a714d2023-04-17 15:54:21 +02001package manager
2
3import (
4 "context"
5 "errors"
6 "flag"
7 "fmt"
Serge Bazanski86a714d2023-04-17 15:54:21 +02008 "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 Bazanskic50f6942023-04-24 18:27:22 +020016 "source.monogon.dev/cloud/bmaas/bmdb/metrics"
Serge Bazanski86a714d2023-04-17 15:54:21 +020017 "source.monogon.dev/cloud/bmaas/bmdb/model"
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020018 "source.monogon.dev/go/mflags"
Serge Bazanski86a714d2023-04-17 15:54:21 +020019)
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
Serge Bazanskic50f6942023-04-24 18:27:22 +020055 processor metrics.Processor
Serge Bazanski00cf57d2023-04-20 11:19:00 +020056 defaultBackoff bmdb.Backoff
57}
58
Serge Bazanski86a714d2023-04-17 15:54:21 +020059// 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.
63type 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
78func (c *ControlLoopConfig) getControlLoopConfig() *ControlLoopConfig {
79 return c
80}
81
Serge Bazanski86a714d2023-04-17 15:54:21 +020082// 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.
85func (c *ControlLoopConfig) RegisterFlags(prefix string) {
Tim Windelschmidtb6308cd2023-10-10 21:19:03 +020086 mflags.Limiter(&c.DBQueryLimiter, prefix+"_db_query_rate", "250ms,8", "Rate limiting for BMDB queries")
Serge Bazanski86a714d2023-04-17 15:54:21 +020087 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.
92func (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.
105func 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.
115type 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.
122func (r *controlLoopRunner) run(ctx context.Context, conn *bmdb.Connection) error {
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200123 pinfo := r.loop.getProcessInfo()
124
Serge Bazanski86a714d2023-04-17 15:54:21 +0200125 eg := errgroup.Group{}
126 for j := 0; j < r.config.Parallelism; j += 1 {
127 eg.Go(func() error {
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200128 return r.runOne(ctx, conn, &pinfo)
Serge Bazanski86a714d2023-04-17 15:54:21 +0200129 })
130 }
131 return eg.Wait()
132}
133
134// run the control loop blocking the current goroutine until the given context
135// expires.
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200136func (r *controlLoopRunner) runOne(ctx context.Context, conn *bmdb.Connection, pinfo *processInfo) error {
Serge Bazanski86a714d2023-04-17 15:54:21 +0200137 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 Bazanskic50f6942023-04-24 18:27:22 +0200143 sess, err = conn.StartSession(ctx, bmdb.SessionOption{Processor: pinfo.processor})
Serge Bazanski86a714d2023-04-17 15:54:21 +0200144 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 Bazanski00cf57d2023-04-20 11:19:00 +0200149 err := r.runInSession(ctx, sess, pinfo)
Serge Bazanski86a714d2023-04-17 15:54:21 +0200150
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 Bazanski00cf57d2023-04-20 11:19:00 +0200170func (r *controlLoopRunner) runInSession(ctx context.Context, sess *bmdb.Session, pinfo *processInfo) error {
171 t, err := r.source(ctx, sess, pinfo)
Serge Bazanski86a714d2023-04-17 15:54:21 +0200172 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 Bazanski00cf57d2023-04-20 11:19:00 +0200182 err = t.work.Fail(ctx, &t.backoff, fmt.Sprintf("failed to process: %v", err))
Serge Bazanski86a714d2023-04-17 15:54:21 +0200183 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 Bazanski00cf57d2023-04-20 11:19:00 +0200192func (r *controlLoopRunner) source(ctx context.Context, sess *bmdb.Session, pinfo *processInfo) (*task, error) {
Serge Bazanski86a714d2023-04-17 15:54:21 +0200193 r.config.DBQueryLimiter.Wait(ctx)
194
195 var machine *model.MachineProvided
Serge Bazanski00cf57d2023-04-20 11:19:00 +0200196 work, err := sess.Work(ctx, pinfo.process, func(q *model.Queries) ([]uuid.UUID, error) {
Serge Bazanski86a714d2023-04-17 15:54:21 +0200197 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 Bazanski00cf57d2023-04-20 11:19:00 +0200219 backoff: pinfo.defaultBackoff,
Serge Bazanski86a714d2023-04-17 15:54:21 +0200220 }, nil
221}