blob: 3f703932bb774e3fe8014badc58b51a7f3c8b52d [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"
Serge Bazanski35e8d792022-10-11 11:32:30 +020016)
17
Serge Bazanski35e8d792022-10-11 11:32:30 +020018// StartSession creates a new BMDB session which will be maintained in a
19// background goroutine as long as the given context is valid. Each Session is
20// represented by an entry in a sessions table within the BMDB, and subsequent
21// Transact calls emit SQL transactions which depend on that entry still being
22// present and up to date. A garbage collection system (to be implemented) will
23// remove expired sessions from the BMDB, but this mechanism is not necessary
24// for the session expiry mechanism to work.
25//
26// When the session becomes invalid (for example due to network partition),
27// subsequent attempts to call Transact will fail with ErrSessionExpired. This
28// means that the caller within the component is responsible for recreating a
29// new Session if a previously used one expires.
30func (c *Connection) StartSession(ctx context.Context) (*Session, error) {
31 intervalSeconds := 5
32
33 res, err := model.New(c.db).NewSession(ctx, model.NewSessionParams{
34 SessionComponentName: c.bmdb.ComponentName,
35 SessionRuntimeInfo: c.bmdb.RuntimeInfo,
36 SessionIntervalSeconds: int64(intervalSeconds),
37 })
38 if err != nil {
39 return nil, fmt.Errorf("creating session failed: %w", err)
40 }
41
42 klog.Infof("Started session %s", res.SessionID)
43
44 ctx2, ctxC := context.WithCancel(ctx)
45
46 s := &Session{
47 connection: c,
48 interval: time.Duration(intervalSeconds) * time.Second,
49
50 UUID: res.SessionID,
51
52 ctx: ctx2,
53 ctxC: ctxC,
54 }
55 go s.maintainHeartbeat(ctx2)
56 return s, nil
57}
58
59// Session is a session (identified by UUID) that has been started in the BMDB.
60// Its liveness is maintained by a background goroutine, and as long as that
61// session is alive, it can perform transactions and work on the BMDB.
62type Session struct {
63 connection *Connection
64 interval time.Duration
65
66 UUID uuid.UUID
67
68 ctx context.Context
69 ctxC context.CancelFunc
70}
71
72var (
73 // ErrSessionExpired is returned when attempting to Transact or Work on a
74 // Session that has expired or been canceled. Once a Session starts returning
75 // these errors, it must be re-created by another StartSession call, as no other
76 // calls will succeed.
77 ErrSessionExpired = errors.New("session expired")
78 // ErrWorkConflict is returned when attempting to Work on a Session with a
79 // process name that's already performing some work, concurrently, on the
80 // requested machine.
81 ErrWorkConflict = errors.New("conflicting work on machine")
82)
83
84// maintainHeartbeat will attempt to repeatedly poke the session at a frequency
85// twice of that of the minimum frequency mandated by the configured 5-second
86// interval. It will exit if it detects that the session cannot be maintained
87// anymore, canceling the session's internal context and causing future
88// Transact/Work calls to fail.
89func (s *Session) maintainHeartbeat(ctx context.Context) {
90 // Internal deadline, used to check whether we haven't dropped the ball on
91 // performing the updates due to a lot of transient errors.
92 deadline := time.Now().Add(s.interval)
93 for {
94 if ctx.Err() != nil {
95 klog.Infof("Session %s: context over, exiting: %v", s.UUID, ctx.Err())
96 return
97 }
98
99 err := s.Transact(ctx, func(q *model.Queries) error {
100 sessions, err := q.SessionCheck(ctx, s.UUID)
101 if err != nil {
102 return fmt.Errorf("when retrieving session: %w", err)
103 }
104 if len(sessions) < 1 {
105 return ErrSessionExpired
106 }
107 err = q.SessionPoke(ctx, s.UUID)
108 if err != nil {
109 return fmt.Errorf("when poking session: %w", err)
110 }
111 return nil
112 })
113 if err != nil {
114 klog.Errorf("Session %s: update failed: %v", s.UUID, err)
115 if errors.Is(err, ErrSessionExpired) || deadline.After(time.Now()) {
116 // No way to recover.
117 klog.Errorf("Session %s: exiting", s.UUID)
118 s.ctxC()
119 return
120 }
121 // Just retry in a bit. One second seems about right for a 5 second interval.
122 //
123 // TODO(q3k): calculate this based on the configured interval.
124 time.Sleep(time.Second)
125 }
126 // Success. Keep going.
127 deadline = time.Now().Add(s.interval)
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100128 select {
129 case <-ctx.Done():
130 // Do nothing, next loop iteration will exit.
131 case <-time.After(s.interval / 2):
132 // Do nothing, next loop iteration will heartbeat.
133 }
Serge Bazanski35e8d792022-10-11 11:32:30 +0200134 }
135}
136
137// Transact runs a given function in the context of both a CockroachDB and BMDB
138// transaction, retrying as necessary.
139//
140// Most pure (meaning without side effects outside the database itself) BMDB
141// transactions should be run this way.
142func (s *Session) Transact(ctx context.Context, fn func(q *model.Queries) error) error {
143 return crdb.ExecuteTx(ctx, s.connection.db, nil, func(tx *sql.Tx) error {
144 qtx := model.New(tx)
145 sessions, err := qtx.SessionCheck(ctx, s.UUID)
146 if err != nil {
147 return fmt.Errorf("when retrieving session: %w", err)
148 }
149 if len(sessions) < 1 {
150 return ErrSessionExpired
151 }
152
153 if err := fn(qtx); err != nil {
154 return err
155 }
156
157 return nil
158 })
159}
160
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100161var (
162 ErrNothingToDo = errors.New("nothing to do")
163 // PostgresUniqueViolation is returned by the lib/pq driver when a mutation
164 // cannot be performed due to a UNIQUE constraint being violated as a result of
165 // the query.
166 postgresUniqueViolation = pq.ErrorCode("23505")
167)
Serge Bazanski35e8d792022-10-11 11:32:30 +0200168
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100169// Work starts work on a machine. Full work execution is performed in three
170// phases:
171//
172// 1. Retrieval phase. This is performed by 'fn' given to this function.
173// The retrieval function must return zero or more machines that some work
174// should be performed on per the BMDB. The first returned machine will be
175// locked for work under the given process and made available in the Work
176// structure returned by this call. The function may be called multiple times,
177// as it's run within a CockroachDB transaction which may be retried an
178// arbitrary number of times. Thus, it should be side-effect free, ideally only
179// performing read queries to the database.
180// 2. Work phase. This is performed by user code while holding on to the Work
181// structure instance.
182// 3. Commit phase. This is performed by the function passed to Work.Finish. See
183// that method's documentation for more details.
184//
185// Important: after retrieving Work successfully, either Finish or Cancel must be
186// called, otherwise the machine will be locked until the parent session expires
187// or is closed! It's safe and recommended to `defer work.Close()` after calling
188// Work().
189//
190// If no machine is eligible for work, ErrNothingToDo should be returned by the
191// retrieval function, and the same error (wrapped) will be returned by Work. In
192// case the retrieval function returns no machines and no error, that error will
193// also be returned.
194//
195// The returned Work object is _not_ goroutine safe.
196func (s *Session) Work(ctx context.Context, process model.Process, fn func(q *model.Queries) ([]uuid.UUID, error)) (*Work, error) {
197 var mid *uuid.UUID
198 err := s.Transact(ctx, func(q *model.Queries) error {
199 mids, err := fn(q)
200 if err != nil {
201 return fmt.Errorf("could not retrieve machines for work: %w", err)
202 }
203 if len(mids) < 1 {
204 return ErrNothingToDo
205 }
206 mid = &mids[0]
207 err = q.StartWork(ctx, model.StartWorkParams{
208 MachineID: mids[0],
Serge Bazanski35e8d792022-10-11 11:32:30 +0200209 SessionID: s.UUID,
210 Process: process,
211 })
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100212 if err != nil {
213 var perr *pq.Error
214 if errors.As(err, &perr) && perr.Code == postgresUniqueViolation {
215 return ErrWorkConflict
216 }
217 return fmt.Errorf("could not start work on %q: %w", mids[0], err)
Serge Bazanski35e8d792022-10-11 11:32:30 +0200218 }
Serge Bazanskia9580a72023-01-12 14:44:35 +0100219 err = q.WorkHistoryInsert(ctx, model.WorkHistoryInsertParams{
220 MachineID: mids[0],
221 Event: model.WorkHistoryEventStarted,
222 Process: process,
223 })
224 if err != nil {
225 return fmt.Errorf("could not insert history event: %w", err)
226 }
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100227 return nil
228 })
229 if err != nil {
230 return nil, err
231 }
232 klog.Infof("Started work %q on machine %q (sess %q)", process, *mid, s.UUID)
233 return &Work{
234 Machine: *mid,
235 s: s,
236 process: process,
237 }, nil
238}
Serge Bazanski35e8d792022-10-11 11:32:30 +0200239
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100240// Work being performed on a machine.
241type Work struct {
242 // Machine that this work is being performed on, as retrieved by the retrieval
243 // function passed to the Work method.
244 Machine uuid.UUID
245 // s is the parent session.
246 s *Session
247 // done marks that this work has already been canceled or finished.
248 done bool
249 // process that this work performs.
250 process model.Process
251}
252
253// Cancel the Work started on a machine. If the work has already been finished
254// or canceled, this is a no-op. In case of error, a log line will be emitted.
255func (w *Work) Cancel(ctx context.Context) {
256 if w.done {
257 return
258 }
259 w.done = true
260
261 klog.Infof("Canceling work %q on machine %q (sess %q)", w.process, w.Machine, w.s.UUID)
262 // Eat error and log. There's nothing we can do if this fails, and if it does, it's
263 // probably because our connectivity to the BMDB has failed. If so, our session
264 // will be invalidated soon and so will the work being performed on this
265 // machine.
266 err := w.s.Transact(ctx, func(q *model.Queries) error {
Serge Bazanskia9580a72023-01-12 14:44:35 +0100267 err := q.FinishWork(ctx, model.FinishWorkParams{
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100268 MachineID: w.Machine,
269 SessionID: w.s.UUID,
270 Process: w.process,
271 })
Serge Bazanskia9580a72023-01-12 14:44:35 +0100272 if err != nil {
273 return err
274 }
275 return q.WorkHistoryInsert(ctx, model.WorkHistoryInsertParams{
276 MachineID: w.Machine,
277 Process: w.process,
278 Event: model.WorkHistoryEventCanceled,
279 })
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100280 })
281 if err != nil {
282 klog.Errorf("Failed to cancel work %q on %q (sess %q): %v", w.process, w.Machine, w.s.UUID, err)
283 }
284}
285
286// Finish work by executing a commit function 'fn' and releasing the machine
287// from the work performed. The function given should apply tags to the
288// processed machine in a way that causes it to not be eligible for retrieval
289// again. As with the retriever function, the commit function might be called an
290// arbitrary number of times as part of cockroachdb transaction retries.
291//
292// This may be called only once.
293func (w *Work) Finish(ctx context.Context, fn func(q *model.Queries) error) error {
294 if w.done {
295 return fmt.Errorf("already finished")
296 }
297 w.done = true
298 klog.Infof("Finishing work %q on machine %q (sess %q)", w.process, w.Machine, w.s.UUID)
299 return w.s.Transact(ctx, func(q *model.Queries) error {
300 err := q.FinishWork(ctx, model.FinishWorkParams{
301 MachineID: w.Machine,
302 SessionID: w.s.UUID,
303 Process: w.process,
304 })
305 if err != nil {
306 return err
307 }
Serge Bazanskia9580a72023-01-12 14:44:35 +0100308 err = q.WorkHistoryInsert(ctx, model.WorkHistoryInsertParams{
309 MachineID: w.Machine,
310 Process: w.process,
311 Event: model.WorkHistoryEventFinished,
312 })
313 if err != nil {
314 return err
315 }
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100316 return fn(q)
317 })
Serge Bazanski35e8d792022-10-11 11:32:30 +0200318}
Serge Bazanskia9580a72023-01-12 14:44:35 +0100319
320// Fail work and introduce backoff for a given duration (if given backoff is
321// non-nil). As long as that backoff is active, no further work for this
322// machine/process will be started. The given cause is an operator-readable
323// string that will be persisted alongside the backoff and the work history/audit
324// table.
325func (w *Work) Fail(ctx context.Context, backoff *time.Duration, cause string) error {
326 if w.done {
327 return fmt.Errorf("already finished")
328 }
329 w.done = true
330
331 return w.s.Transact(ctx, func(q *model.Queries) error {
332 err := q.FinishWork(ctx, model.FinishWorkParams{
333 MachineID: w.Machine,
334 SessionID: w.s.UUID,
335 Process: w.process,
336 })
337 if err != nil {
338 return err
339 }
340 err = q.WorkHistoryInsert(ctx, model.WorkHistoryInsertParams{
341 MachineID: w.Machine,
342 Process: w.process,
343 Event: model.WorkHistoryEventFailed,
344 FailedCause: sql.NullString{
345 String: cause,
346 Valid: true,
347 },
348 })
349 if err != nil {
350 return err
351 }
352 if backoff != nil && backoff.Seconds() >= 1.0 {
353 seconds := int64(backoff.Seconds())
354 klog.Infof("Adding backoff for %q on machine %q (%d seconds)", w.process, w.Machine, seconds)
355 return q.WorkBackoffInsert(ctx, model.WorkBackoffInsertParams{
356 MachineID: w.Machine,
357 Process: w.process,
358 Seconds: seconds,
359 Cause: cause,
360 })
361 } else {
362 return nil
363 }
364 })
365}