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