blob: ccb15105da833b10c37180c20c6144b112e5e490 [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 Bazanskibe6c3ad2022-12-12 15:11:39 +0100292 return nil
293 })
294 if err != nil {
295 return nil, err
296 }
297 klog.Infof("Started work %q on machine %q (sess %q)", process, *mid, s.UUID)
298 return &Work{
299 Machine: *mid,
300 s: s,
301 process: process,
302 }, nil
303}
Serge Bazanski35e8d792022-10-11 11:32:30 +0200304
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100305// Work being performed on a machine.
306type Work struct {
307 // Machine that this work is being performed on, as retrieved by the retrieval
308 // function passed to the Work method.
309 Machine uuid.UUID
310 // s is the parent session.
311 s *Session
312 // done marks that this work has already been canceled or finished.
313 done bool
314 // process that this work performs.
315 process model.Process
316}
317
318// Cancel the Work started on a machine. If the work has already been finished
319// or canceled, this is a no-op. In case of error, a log line will be emitted.
320func (w *Work) Cancel(ctx context.Context) {
321 if w.done {
322 return
323 }
324 w.done = true
325
326 klog.Infof("Canceling work %q on machine %q (sess %q)", w.process, w.Machine, w.s.UUID)
327 // Eat error and log. There's nothing we can do if this fails, and if it does, it's
328 // probably because our connectivity to the BMDB has failed. If so, our session
329 // will be invalidated soon and so will the work being performed on this
330 // machine.
331 err := w.s.Transact(ctx, func(q *model.Queries) error {
332 return q.FinishWork(ctx, model.FinishWorkParams{
333 MachineID: w.Machine,
334 SessionID: w.s.UUID,
335 Process: w.process,
336 })
337 })
338 if err != nil {
339 klog.Errorf("Failed to cancel work %q on %q (sess %q): %v", w.process, w.Machine, w.s.UUID, err)
340 }
341}
342
343// Finish work by executing a commit function 'fn' and releasing the machine
344// from the work performed. The function given should apply tags to the
345// processed machine in a way that causes it to not be eligible for retrieval
346// again. As with the retriever function, the commit function might be called an
347// arbitrary number of times as part of cockroachdb transaction retries.
348//
349// This may be called only once.
350func (w *Work) Finish(ctx context.Context, fn func(q *model.Queries) error) error {
351 if w.done {
352 return fmt.Errorf("already finished")
353 }
354 w.done = true
355 klog.Infof("Finishing work %q on machine %q (sess %q)", w.process, w.Machine, w.s.UUID)
356 return w.s.Transact(ctx, func(q *model.Queries) error {
357 err := q.FinishWork(ctx, model.FinishWorkParams{
358 MachineID: w.Machine,
359 SessionID: w.s.UUID,
360 Process: w.process,
361 })
362 if err != nil {
363 return err
364 }
365 return fn(q)
366 })
Serge Bazanski35e8d792022-10-11 11:32:30 +0200367}