blob: 6058b92f07565fd45a23c8e046b7831b91bc74da [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
Serge Bazanski42f13462023-04-19 15:00:06 +020072// Expired returns true if this session is expired and will fail all subsequent
73// transactions/work.
74func (s *Session) Expired() bool {
75 return s.ctx.Err() != nil
76}
77
78// expire is a helper which marks this session as expired and returns
79// ErrSessionExpired.
80func (s *Session) expire() error {
81 s.ctxC()
82 return ErrSessionExpired
83}
84
Serge Bazanski35e8d792022-10-11 11:32:30 +020085var (
86 // ErrSessionExpired is returned when attempting to Transact or Work on a
87 // Session that has expired or been canceled. Once a Session starts returning
88 // these errors, it must be re-created by another StartSession call, as no other
89 // calls will succeed.
90 ErrSessionExpired = errors.New("session expired")
91 // ErrWorkConflict is returned when attempting to Work on a Session with a
92 // process name that's already performing some work, concurrently, on the
93 // requested machine.
94 ErrWorkConflict = errors.New("conflicting work on machine")
95)
96
97// maintainHeartbeat will attempt to repeatedly poke the session at a frequency
98// twice of that of the minimum frequency mandated by the configured 5-second
99// interval. It will exit if it detects that the session cannot be maintained
100// anymore, canceling the session's internal context and causing future
101// Transact/Work calls to fail.
102func (s *Session) maintainHeartbeat(ctx context.Context) {
103 // Internal deadline, used to check whether we haven't dropped the ball on
104 // performing the updates due to a lot of transient errors.
105 deadline := time.Now().Add(s.interval)
106 for {
107 if ctx.Err() != nil {
108 klog.Infof("Session %s: context over, exiting: %v", s.UUID, ctx.Err())
109 return
110 }
111
112 err := s.Transact(ctx, func(q *model.Queries) error {
113 sessions, err := q.SessionCheck(ctx, s.UUID)
114 if err != nil {
115 return fmt.Errorf("when retrieving session: %w", err)
116 }
117 if len(sessions) < 1 {
Serge Bazanski42f13462023-04-19 15:00:06 +0200118 return s.expire()
Serge Bazanski35e8d792022-10-11 11:32:30 +0200119 }
120 err = q.SessionPoke(ctx, s.UUID)
121 if err != nil {
122 return fmt.Errorf("when poking session: %w", err)
123 }
124 return nil
125 })
126 if err != nil {
127 klog.Errorf("Session %s: update failed: %v", s.UUID, err)
128 if errors.Is(err, ErrSessionExpired) || deadline.After(time.Now()) {
129 // No way to recover.
130 klog.Errorf("Session %s: exiting", s.UUID)
131 s.ctxC()
132 return
133 }
134 // Just retry in a bit. One second seems about right for a 5 second interval.
135 //
136 // TODO(q3k): calculate this based on the configured interval.
137 time.Sleep(time.Second)
138 }
139 // Success. Keep going.
140 deadline = time.Now().Add(s.interval)
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100141 select {
142 case <-ctx.Done():
143 // Do nothing, next loop iteration will exit.
144 case <-time.After(s.interval / 2):
145 // Do nothing, next loop iteration will heartbeat.
146 }
Serge Bazanski35e8d792022-10-11 11:32:30 +0200147 }
148}
149
150// Transact runs a given function in the context of both a CockroachDB and BMDB
151// transaction, retrying as necessary.
152//
153// Most pure (meaning without side effects outside the database itself) BMDB
154// transactions should be run this way.
155func (s *Session) Transact(ctx context.Context, fn func(q *model.Queries) error) error {
156 return crdb.ExecuteTx(ctx, s.connection.db, nil, func(tx *sql.Tx) error {
157 qtx := model.New(tx)
158 sessions, err := qtx.SessionCheck(ctx, s.UUID)
159 if err != nil {
160 return fmt.Errorf("when retrieving session: %w", err)
161 }
162 if len(sessions) < 1 {
Serge Bazanski42f13462023-04-19 15:00:06 +0200163 return s.expire()
Serge Bazanski35e8d792022-10-11 11:32:30 +0200164 }
165
166 if err := fn(qtx); err != nil {
167 return err
168 }
169
170 return nil
171 })
172}
173
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100174var (
175 ErrNothingToDo = errors.New("nothing to do")
176 // PostgresUniqueViolation is returned by the lib/pq driver when a mutation
177 // cannot be performed due to a UNIQUE constraint being violated as a result of
178 // the query.
179 postgresUniqueViolation = pq.ErrorCode("23505")
180)
Serge Bazanski35e8d792022-10-11 11:32:30 +0200181
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100182// Work starts work on a machine. Full work execution is performed in three
183// phases:
184//
185// 1. Retrieval phase. This is performed by 'fn' given to this function.
186// The retrieval function must return zero or more machines that some work
187// should be performed on per the BMDB. The first returned machine will be
188// locked for work under the given process and made available in the Work
189// structure returned by this call. The function may be called multiple times,
190// as it's run within a CockroachDB transaction which may be retried an
191// arbitrary number of times. Thus, it should be side-effect free, ideally only
192// performing read queries to the database.
193// 2. Work phase. This is performed by user code while holding on to the Work
194// structure instance.
195// 3. Commit phase. This is performed by the function passed to Work.Finish. See
196// that method's documentation for more details.
197//
198// Important: after retrieving Work successfully, either Finish or Cancel must be
199// called, otherwise the machine will be locked until the parent session expires
200// or is closed! It's safe and recommended to `defer work.Close()` after calling
201// Work().
202//
203// If no machine is eligible for work, ErrNothingToDo should be returned by the
204// retrieval function, and the same error (wrapped) will be returned by Work. In
205// case the retrieval function returns no machines and no error, that error will
206// also be returned.
207//
208// The returned Work object is _not_ goroutine safe.
209func (s *Session) Work(ctx context.Context, process model.Process, fn func(q *model.Queries) ([]uuid.UUID, error)) (*Work, error) {
210 var mid *uuid.UUID
211 err := s.Transact(ctx, func(q *model.Queries) error {
212 mids, err := fn(q)
213 if err != nil {
214 return fmt.Errorf("could not retrieve machines for work: %w", err)
215 }
216 if len(mids) < 1 {
217 return ErrNothingToDo
218 }
219 mid = &mids[0]
220 err = q.StartWork(ctx, model.StartWorkParams{
221 MachineID: mids[0],
Serge Bazanski35e8d792022-10-11 11:32:30 +0200222 SessionID: s.UUID,
223 Process: process,
224 })
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100225 if err != nil {
226 var perr *pq.Error
227 if errors.As(err, &perr) && perr.Code == postgresUniqueViolation {
228 return ErrWorkConflict
229 }
230 return fmt.Errorf("could not start work on %q: %w", mids[0], err)
Serge Bazanski35e8d792022-10-11 11:32:30 +0200231 }
Serge Bazanskia9580a72023-01-12 14:44:35 +0100232 err = q.WorkHistoryInsert(ctx, model.WorkHistoryInsertParams{
233 MachineID: mids[0],
234 Event: model.WorkHistoryEventStarted,
235 Process: process,
236 })
237 if err != nil {
238 return fmt.Errorf("could not insert history event: %w", err)
239 }
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100240 return nil
241 })
242 if err != nil {
243 return nil, err
244 }
245 klog.Infof("Started work %q on machine %q (sess %q)", process, *mid, s.UUID)
246 return &Work{
247 Machine: *mid,
248 s: s,
249 process: process,
250 }, nil
251}
Serge Bazanski35e8d792022-10-11 11:32:30 +0200252
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100253// Work being performed on a machine.
254type Work struct {
255 // Machine that this work is being performed on, as retrieved by the retrieval
256 // function passed to the Work method.
257 Machine uuid.UUID
258 // s is the parent session.
259 s *Session
260 // done marks that this work has already been canceled or finished.
261 done bool
262 // process that this work performs.
263 process model.Process
264}
265
266// Cancel the Work started on a machine. If the work has already been finished
267// or canceled, this is a no-op. In case of error, a log line will be emitted.
268func (w *Work) Cancel(ctx context.Context) {
269 if w.done {
270 return
271 }
272 w.done = true
273
274 klog.Infof("Canceling work %q on machine %q (sess %q)", w.process, w.Machine, w.s.UUID)
275 // Eat error and log. There's nothing we can do if this fails, and if it does, it's
276 // probably because our connectivity to the BMDB has failed. If so, our session
277 // will be invalidated soon and so will the work being performed on this
278 // machine.
279 err := w.s.Transact(ctx, func(q *model.Queries) error {
Serge Bazanskia9580a72023-01-12 14:44:35 +0100280 err := q.FinishWork(ctx, model.FinishWorkParams{
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100281 MachineID: w.Machine,
282 SessionID: w.s.UUID,
283 Process: w.process,
284 })
Serge Bazanskia9580a72023-01-12 14:44:35 +0100285 if err != nil {
286 return err
287 }
288 return q.WorkHistoryInsert(ctx, model.WorkHistoryInsertParams{
289 MachineID: w.Machine,
290 Process: w.process,
291 Event: model.WorkHistoryEventCanceled,
292 })
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100293 })
294 if err != nil {
295 klog.Errorf("Failed to cancel work %q on %q (sess %q): %v", w.process, w.Machine, w.s.UUID, err)
296 }
297}
298
299// Finish work by executing a commit function 'fn' and releasing the machine
300// from the work performed. The function given should apply tags to the
301// processed machine in a way that causes it to not be eligible for retrieval
302// again. As with the retriever function, the commit function might be called an
303// arbitrary number of times as part of cockroachdb transaction retries.
304//
305// This may be called only once.
306func (w *Work) Finish(ctx context.Context, fn func(q *model.Queries) error) error {
307 if w.done {
308 return fmt.Errorf("already finished")
309 }
310 w.done = true
311 klog.Infof("Finishing work %q on machine %q (sess %q)", w.process, w.Machine, w.s.UUID)
312 return w.s.Transact(ctx, func(q *model.Queries) error {
313 err := q.FinishWork(ctx, model.FinishWorkParams{
314 MachineID: w.Machine,
315 SessionID: w.s.UUID,
316 Process: w.process,
317 })
318 if err != nil {
319 return err
320 }
Serge Bazanskia9580a72023-01-12 14:44:35 +0100321 err = q.WorkHistoryInsert(ctx, model.WorkHistoryInsertParams{
322 MachineID: w.Machine,
323 Process: w.process,
324 Event: model.WorkHistoryEventFinished,
325 })
326 if err != nil {
327 return err
328 }
Serge Bazanskibe6c3ad2022-12-12 15:11:39 +0100329 return fn(q)
330 })
Serge Bazanski35e8d792022-10-11 11:32:30 +0200331}
Serge Bazanskia9580a72023-01-12 14:44:35 +0100332
333// Fail work and introduce backoff for a given duration (if given backoff is
334// non-nil). As long as that backoff is active, no further work for this
335// machine/process will be started. The given cause is an operator-readable
336// string that will be persisted alongside the backoff and the work history/audit
337// table.
338func (w *Work) Fail(ctx context.Context, backoff *time.Duration, cause string) error {
339 if w.done {
340 return fmt.Errorf("already finished")
341 }
342 w.done = true
343
344 return w.s.Transact(ctx, func(q *model.Queries) error {
345 err := q.FinishWork(ctx, model.FinishWorkParams{
346 MachineID: w.Machine,
347 SessionID: w.s.UUID,
348 Process: w.process,
349 })
350 if err != nil {
351 return err
352 }
353 err = q.WorkHistoryInsert(ctx, model.WorkHistoryInsertParams{
354 MachineID: w.Machine,
355 Process: w.process,
356 Event: model.WorkHistoryEventFailed,
357 FailedCause: sql.NullString{
358 String: cause,
359 Valid: true,
360 },
361 })
362 if err != nil {
363 return err
364 }
365 if backoff != nil && backoff.Seconds() >= 1.0 {
366 seconds := int64(backoff.Seconds())
367 klog.Infof("Adding backoff for %q on machine %q (%d seconds)", w.process, w.Machine, seconds)
368 return q.WorkBackoffInsert(ctx, model.WorkBackoffInsertParams{
369 MachineID: w.Machine,
370 Process: w.process,
371 Seconds: seconds,
372 Cause: cause,
373 })
374 } else {
375 return nil
376 }
377 })
378}