blob: 6b19171ebd1b482e4fea3158b7637a925412dabb [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)
201 time.Sleep(s.interval / 2)
202 }
203}
204
205// Transact runs a given function in the context of both a CockroachDB and BMDB
206// transaction, retrying as necessary.
207//
208// Most pure (meaning without side effects outside the database itself) BMDB
209// transactions should be run this way.
210func (s *Session) Transact(ctx context.Context, fn func(q *model.Queries) error) error {
211 return crdb.ExecuteTx(ctx, s.connection.db, nil, func(tx *sql.Tx) error {
212 qtx := model.New(tx)
213 sessions, err := qtx.SessionCheck(ctx, s.UUID)
214 if err != nil {
215 return fmt.Errorf("when retrieving session: %w", err)
216 }
217 if len(sessions) < 1 {
218 return ErrSessionExpired
219 }
220
221 if err := fn(qtx); err != nil {
222 return err
223 }
224
225 return nil
226 })
227}
228
229// Work runs a given function as a work item with a given process name against
230// some identified machine. Not more than one process of a given name can run
231// against a machine concurrently.
232//
233// Most impure (meaning with side effects outside the database itself) BMDB
234// transactions should be run this way.
235func (s *Session) Work(ctx context.Context, machine uuid.UUID, process model.Process, fn func() error) error {
236 err := model.New(s.connection.db).StartWork(ctx, model.StartWorkParams{
237 MachineID: machine,
238 SessionID: s.UUID,
239 Process: process,
240 })
241 if err != nil {
242 var perr *pq.Error
243 if errors.As(err, &perr) && perr.Code == "23505" {
244 return ErrWorkConflict
245 }
246 return fmt.Errorf("could not start work: %w", err)
247 }
248 klog.Infof("Started work: %q on machine %s, session %s", process, machine, s.UUID)
249
250 defer func() {
251 err := model.New(s.connection.db).FinishWork(s.ctx, model.FinishWorkParams{
252 MachineID: machine,
253 SessionID: s.UUID,
254 Process: process,
255 })
256 klog.Errorf("Finished work: %q on machine %s, session %s", process, machine, s.UUID)
257 if err != nil && !errors.Is(err, s.ctx.Err()) {
258 klog.Errorf("Failed to finish work: %v", err)
259 klog.Errorf("Closing session out of an abundance of caution")
260 s.ctxC()
261 }
262 }()
263
264 return fn()
265}