blob: 433612197b251902cf796dbe26c268630a02b780 [file] [log] [blame]
Serge Bazanski35e8d792022-10-11 11:32:30 +02001package bmdb
2
3import (
4 "context"
5 "database/sql"
6 "errors"
7 "fmt"
8 "time"
9
10 "github.com/cockroachdb/cockroach-go/v2/crdb"
11 "github.com/google/uuid"
12 "github.com/lib/pq"
13 "k8s.io/klog/v2"
14
15 "source.monogon.dev/cloud/bmaas/bmdb/model"
16 "source.monogon.dev/cloud/lib/component"
17)
18
19// BMDB is the Bare Metal Database, a common schema to store information about
20// bare metal machines in CockroachDB. This struct is supposed to be
21// embedded/contained by different components that interact with the BMDB, and
22// provides a common interface to BMDB operations to these components.
23//
24// The BMDB provides two mechanisms facilitating a 'reactive work system' being
25// implemented on the bare metal machine data:
26//
27// - Sessions, which are maintained by heartbeats by components and signal the
28// liveness of said components to other components operating on the BMDB. These
29// effectively extend CockroachDB's transactions to be visible as row data. Any
30// session that is not actively being updated by a component can be expired by a
31// component responsible for lease garbage collection.
32// - Work locking, which bases on Sessions and allows long-standing
33// multi-transaction work to be performed on given machines, preventing
34// conflicting work from being performed by other components. As both Work
35// locking and Sessions are plain row data, other components can use SQL queries
36// to exclude machines to act on by constraining SELECT queries to not return
37// machines with some active work being performed on them.
38type BMDB struct {
39 Config
40}
41
42// Config is the configuration of the BMDB connector.
43type Config struct {
44 Database component.CockroachConfig
45
46 // ComponentName is a human-readable name of the component connecting to the
47 // BMDB, and is stored in any Sessions managed by this component's connector.
48 ComponentName string
49 // RuntimeInfo is a human-readable 'runtime information' (eg. software version,
50 // host machine/job information, IP address, etc.) stored alongside the
51 // ComponentName in active Sessions.
52 RuntimeInfo string
53}
54
55// Open creates a new Connection to the BMDB for the calling component. Multiple
56// connections can be opened (although there is no advantage to doing so, as
57// Connections manage an underlying CockroachDB connection pool, which performs
58// required reconnects and connection pooling automatically).
59func (b *BMDB) Open(migrate bool) (*Connection, error) {
60 if migrate {
61 if b.Config.Database.Migrations == nil {
62 klog.Infof("Using default migrations source.")
63 m, err := model.MigrationsSource()
64 if err != nil {
65 klog.Exitf("failed to prepare migrations source: %w", err)
66 }
67 b.Config.Database.Migrations = m
68 }
69 if err := b.Database.MigrateUp(); err != nil {
70 return nil, fmt.Errorf("migration failed: %w", err)
71 }
72 }
73 db, err := b.Database.Connect()
74 if err != nil {
75 return nil, err
76 }
77 return &Connection{
78 bmdb: b,
79 db: db,
80 }, nil
81}
82
83// Connection to the BMDB. Internally, this contains a sql.DB connection pool,
84// so components can (and likely should) reuse Connections as much as possible
85// internally.
86type Connection struct {
87 bmdb *BMDB
88 db *sql.DB
89}
90
91// StartSession creates a new BMDB session which will be maintained in a
92// background goroutine as long as the given context is valid. Each Session is
93// represented by an entry in a sessions table within the BMDB, and subsequent
94// Transact calls emit SQL transactions which depend on that entry still being
95// present and up to date. A garbage collection system (to be implemented) will
96// remove expired sessions from the BMDB, but this mechanism is not necessary
97// for the session expiry mechanism to work.
98//
99// When the session becomes invalid (for example due to network partition),
100// subsequent attempts to call Transact will fail with ErrSessionExpired. This
101// means that the caller within the component is responsible for recreating a
102// new Session if a previously used one expires.
103func (c *Connection) StartSession(ctx context.Context) (*Session, error) {
104 intervalSeconds := 5
105
106 res, err := model.New(c.db).NewSession(ctx, model.NewSessionParams{
107 SessionComponentName: c.bmdb.ComponentName,
108 SessionRuntimeInfo: c.bmdb.RuntimeInfo,
109 SessionIntervalSeconds: int64(intervalSeconds),
110 })
111 if err != nil {
112 return nil, fmt.Errorf("creating session failed: %w", err)
113 }
114
115 klog.Infof("Started session %s", res.SessionID)
116
117 ctx2, ctxC := context.WithCancel(ctx)
118
119 s := &Session{
120 connection: c,
121 interval: time.Duration(intervalSeconds) * time.Second,
122
123 UUID: res.SessionID,
124
125 ctx: ctx2,
126 ctxC: ctxC,
127 }
128 go s.maintainHeartbeat(ctx2)
129 return s, nil
130}
131
132// Session is a session (identified by UUID) that has been started in the BMDB.
133// Its liveness is maintained by a background goroutine, and as long as that
134// session is alive, it can perform transactions and work on the BMDB.
135type Session struct {
136 connection *Connection
137 interval time.Duration
138
139 UUID uuid.UUID
140
141 ctx context.Context
142 ctxC context.CancelFunc
143}
144
145var (
146 // ErrSessionExpired is returned when attempting to Transact or Work on a
147 // Session that has expired or been canceled. Once a Session starts returning
148 // these errors, it must be re-created by another StartSession call, as no other
149 // calls will succeed.
150 ErrSessionExpired = errors.New("session expired")
151 // ErrWorkConflict is returned when attempting to Work on a Session with a
152 // process name that's already performing some work, concurrently, on the
153 // requested machine.
154 ErrWorkConflict = errors.New("conflicting work on machine")
155)
156
157// maintainHeartbeat will attempt to repeatedly poke the session at a frequency
158// twice of that of the minimum frequency mandated by the configured 5-second
159// interval. It will exit if it detects that the session cannot be maintained
160// anymore, canceling the session's internal context and causing future
161// Transact/Work calls to fail.
162func (s *Session) maintainHeartbeat(ctx context.Context) {
163 // Internal deadline, used to check whether we haven't dropped the ball on
164 // performing the updates due to a lot of transient errors.
165 deadline := time.Now().Add(s.interval)
166 for {
167 if ctx.Err() != nil {
168 klog.Infof("Session %s: context over, exiting: %v", s.UUID, ctx.Err())
169 return
170 }
171
172 err := s.Transact(ctx, func(q *model.Queries) error {
173 sessions, err := q.SessionCheck(ctx, s.UUID)
174 if err != nil {
175 return fmt.Errorf("when retrieving session: %w", err)
176 }
177 if len(sessions) < 1 {
178 return ErrSessionExpired
179 }
180 err = q.SessionPoke(ctx, s.UUID)
181 if err != nil {
182 return fmt.Errorf("when poking session: %w", err)
183 }
184 return nil
185 })
186 if err != nil {
187 klog.Errorf("Session %s: update failed: %v", s.UUID, err)
188 if errors.Is(err, ErrSessionExpired) || deadline.After(time.Now()) {
189 // No way to recover.
190 klog.Errorf("Session %s: exiting", s.UUID)
191 s.ctxC()
192 return
193 }
194 // Just retry in a bit. One second seems about right for a 5 second interval.
195 //
196 // TODO(q3k): calculate this based on the configured interval.
197 time.Sleep(time.Second)
198 }
199 // Success. Keep going.
200 deadline = time.Now().Add(s.interval)
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100201 select {
202 case <-ctx.Done():
203 // Do nothing, next loop iteration will exit.
204 case <-time.After(s.interval / 2):
205 // Do nothing, next loop iteration will heartbeat.
206 }
Serge Bazanski35e8d792022-10-11 11:32:30 +0200207 }
208}
209
210// Transact runs a given function in the context of both a CockroachDB and BMDB
211// transaction, retrying as necessary.
212//
213// Most pure (meaning without side effects outside the database itself) BMDB
214// transactions should be run this way.
215func (s *Session) Transact(ctx context.Context, fn func(q *model.Queries) error) error {
216 return crdb.ExecuteTx(ctx, s.connection.db, nil, func(tx *sql.Tx) error {
217 qtx := model.New(tx)
218 sessions, err := qtx.SessionCheck(ctx, s.UUID)
219 if err != nil {
220 return fmt.Errorf("when retrieving session: %w", err)
221 }
222 if len(sessions) < 1 {
223 return ErrSessionExpired
224 }
225
226 if err := fn(qtx); err != nil {
227 return err
228 }
229
230 return nil
231 })
232}
233
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100234var (
235 ErrNothingToDo = errors.New("nothing to do")
236 // PostgresUniqueViolation is returned by the lib/pq driver when a mutation
237 // cannot be performed due to a UNIQUE constraint being violated as a result of
238 // the query.
239 postgresUniqueViolation = pq.ErrorCode("23505")
240)
Serge Bazanski35e8d792022-10-11 11:32:30 +0200241
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100242// Work starts work on a machine. Full work execution is performed in three
243// phases:
244//
245// 1. Retrieval phase. This is performed by 'fn' given to this function.
246// The retrieval function must return zero or more machines that some work
247// should be performed on per the BMDB. The first returned machine will be
248// locked for work under the given process and made available in the Work
249// structure returned by this call. The function may be called multiple times,
250// as it's run within a CockroachDB transaction which may be retried an
251// arbitrary number of times. Thus, it should be side-effect free, ideally only
252// performing read queries to the database.
253// 2. Work phase. This is performed by user code while holding on to the Work
254// structure instance.
255// 3. Commit phase. This is performed by the function passed to Work.Finish. See
256// that method's documentation for more details.
257//
258// Important: after retrieving Work successfully, either Finish or Cancel must be
259// called, otherwise the machine will be locked until the parent session expires
260// or is closed! It's safe and recommended to `defer work.Close()` after calling
261// Work().
262//
263// If no machine is eligible for work, ErrNothingToDo should be returned by the
264// retrieval function, and the same error (wrapped) will be returned by Work. In
265// case the retrieval function returns no machines and no error, that error will
266// also be returned.
267//
268// The returned Work object is _not_ goroutine safe.
269func (s *Session) Work(ctx context.Context, process model.Process, fn func(q *model.Queries) ([]uuid.UUID, error)) (*Work, error) {
270 var mid *uuid.UUID
271 err := s.Transact(ctx, func(q *model.Queries) error {
272 mids, err := fn(q)
273 if err != nil {
274 return fmt.Errorf("could not retrieve machines for work: %w", err)
275 }
276 if len(mids) < 1 {
277 return ErrNothingToDo
278 }
279 mid = &mids[0]
280 err = q.StartWork(ctx, model.StartWorkParams{
281 MachineID: mids[0],
Serge Bazanski35e8d792022-10-11 11:32:30 +0200282 SessionID: s.UUID,
283 Process: process,
284 })
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100285 if err != nil {
286 var perr *pq.Error
287 if errors.As(err, &perr) && perr.Code == postgresUniqueViolation {
288 return ErrWorkConflict
289 }
290 return fmt.Errorf("could not start work on %q: %w", mids[0], err)
Serge Bazanski35e8d792022-10-11 11:32:30 +0200291 }
Serge Bazanskia9580a72023-01-12 14:44:35 +0100292 err = q.WorkHistoryInsert(ctx, model.WorkHistoryInsertParams{
293 MachineID: mids[0],
294 Event: model.WorkHistoryEventStarted,
295 Process: process,
296 })
297 if err != nil {
298 return fmt.Errorf("could not insert history event: %w", err)
299 }
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100300 return nil
301 })
302 if err != nil {
303 return nil, err
304 }
305 klog.Infof("Started work %q on machine %q (sess %q)", process, *mid, s.UUID)
306 return &Work{
307 Machine: *mid,
308 s: s,
309 process: process,
310 }, nil
311}
Serge Bazanski35e8d792022-10-11 11:32:30 +0200312
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100313// Work being performed on a machine.
314type Work struct {
315 // Machine that this work is being performed on, as retrieved by the retrieval
316 // function passed to the Work method.
317 Machine uuid.UUID
318 // s is the parent session.
319 s *Session
320 // done marks that this work has already been canceled or finished.
321 done bool
322 // process that this work performs.
323 process model.Process
324}
325
326// Cancel the Work started on a machine. If the work has already been finished
327// or canceled, this is a no-op. In case of error, a log line will be emitted.
328func (w *Work) Cancel(ctx context.Context) {
329 if w.done {
330 return
331 }
332 w.done = true
333
334 klog.Infof("Canceling work %q on machine %q (sess %q)", w.process, w.Machine, w.s.UUID)
335 // Eat error and log. There's nothing we can do if this fails, and if it does, it's
336 // probably because our connectivity to the BMDB has failed. If so, our session
337 // will be invalidated soon and so will the work being performed on this
338 // machine.
339 err := w.s.Transact(ctx, func(q *model.Queries) error {
Serge Bazanskia9580a72023-01-12 14:44:35 +0100340 err := q.FinishWork(ctx, model.FinishWorkParams{
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100341 MachineID: w.Machine,
342 SessionID: w.s.UUID,
343 Process: w.process,
344 })
Serge Bazanskia9580a72023-01-12 14:44:35 +0100345 if err != nil {
346 return err
347 }
348 return q.WorkHistoryInsert(ctx, model.WorkHistoryInsertParams{
349 MachineID: w.Machine,
350 Process: w.process,
351 Event: model.WorkHistoryEventCanceled,
352 })
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100353 })
354 if err != nil {
355 klog.Errorf("Failed to cancel work %q on %q (sess %q): %v", w.process, w.Machine, w.s.UUID, err)
356 }
357}
358
359// Finish work by executing a commit function 'fn' and releasing the machine
360// from the work performed. The function given should apply tags to the
361// processed machine in a way that causes it to not be eligible for retrieval
362// again. As with the retriever function, the commit function might be called an
363// arbitrary number of times as part of cockroachdb transaction retries.
364//
365// This may be called only once.
366func (w *Work) Finish(ctx context.Context, fn func(q *model.Queries) error) error {
367 if w.done {
368 return fmt.Errorf("already finished")
369 }
370 w.done = true
371 klog.Infof("Finishing work %q on machine %q (sess %q)", w.process, w.Machine, w.s.UUID)
372 return w.s.Transact(ctx, func(q *model.Queries) error {
373 err := q.FinishWork(ctx, model.FinishWorkParams{
374 MachineID: w.Machine,
375 SessionID: w.s.UUID,
376 Process: w.process,
377 })
378 if err != nil {
379 return err
380 }
Serge Bazanskia9580a72023-01-12 14:44:35 +0100381 err = q.WorkHistoryInsert(ctx, model.WorkHistoryInsertParams{
382 MachineID: w.Machine,
383 Process: w.process,
384 Event: model.WorkHistoryEventFinished,
385 })
386 if err != nil {
387 return err
388 }
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100389 return fn(q)
390 })
Serge Bazanski35e8d792022-10-11 11:32:30 +0200391}
Serge Bazanskia9580a72023-01-12 14:44:35 +0100392
393// Fail work and introduce backoff for a given duration (if given backoff is
394// non-nil). As long as that backoff is active, no further work for this
395// machine/process will be started. The given cause is an operator-readable
396// string that will be persisted alongside the backoff and the work history/audit
397// table.
398func (w *Work) Fail(ctx context.Context, backoff *time.Duration, cause string) error {
399 if w.done {
400 return fmt.Errorf("already finished")
401 }
402 w.done = true
403
404 return w.s.Transact(ctx, func(q *model.Queries) error {
405 err := q.FinishWork(ctx, model.FinishWorkParams{
406 MachineID: w.Machine,
407 SessionID: w.s.UUID,
408 Process: w.process,
409 })
410 if err != nil {
411 return err
412 }
413 err = q.WorkHistoryInsert(ctx, model.WorkHistoryInsertParams{
414 MachineID: w.Machine,
415 Process: w.process,
416 Event: model.WorkHistoryEventFailed,
417 FailedCause: sql.NullString{
418 String: cause,
419 Valid: true,
420 },
421 })
422 if err != nil {
423 return err
424 }
425 if backoff != nil && backoff.Seconds() >= 1.0 {
426 seconds := int64(backoff.Seconds())
427 klog.Infof("Adding backoff for %q on machine %q (%d seconds)", w.process, w.Machine, seconds)
428 return q.WorkBackoffInsert(ctx, model.WorkBackoffInsertParams{
429 MachineID: w.Machine,
430 Process: w.process,
431 Seconds: seconds,
432 Cause: cause,
433 })
434 } else {
435 return nil
436 }
437 })
438}