| 1 | package team |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "net/url" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "sync" |
| 14 | "time" |
| 15 | |
| 16 | _ "modernc.org/sqlite" |
| 17 | ) |
| 18 | |
| 19 | // SchemaVersion is the one schema this binary writes. A database with a |
| 20 | // newer version is refused (ErrStaleStore): the binary would not know the |
| 21 | // rows it was reading. |
| 22 | const SchemaVersion = 8 |
| 23 | |
| 24 | // Adapter executes one operation class against an external system. Execute |
| 25 | // runs an admitted dispatch and returns its receipt; an error from Execute |
| 26 | // means the reply was lost and the outcome is unknown, never that nothing |
| 27 | // happened. Reconcile asks whether the dispatch with that key happened; |
| 28 | // Classify declares how the operation may be replayed. Adapters are pure |
| 29 | // with respect to the store: they never see a transaction. |
| 30 | type Adapter interface { |
| 31 | Classify(op Operation) (ReplayClass, error) |
| 32 | Execute(ctx context.Context, d Dispatch) (Receipt, error) |
| 33 | Reconcile(ctx context.Context, d Dispatch) (ReconcileResult, error) |
| 34 | } |
| 35 | |
| 36 | // CommitObserver captures the final transaction state before commit. Its |
| 37 | // returned function runs after a successful SQL commit and guard release. |
| 38 | type CommitObserver func(context.Context, *sql.Tx) (func(), error) |
| 39 | |
| 40 | // Options configures Open. Clock and Authority are required; Adapters maps |
| 41 | // each external operation the store may dispatch. Marker is the path of |
| 42 | // the incarnation marker kept outside the database; it defaults to the |
| 43 | // database path plus ".incarnation". |
| 44 | type Options struct { |
| 45 | ObserverFailed func() |
| 46 | ObserveWrite func(context.Context, *sql.Tx) (CommitObserver, error) |
| 47 | RenderedApproval RenderedApprovalValidator |
| 48 | SourceReference SourceReferenceValidator |
| 49 | ExecutorEvidence ExecutorEvidenceValidator |
| 50 | Provenance ProvenanceResolver |
| 51 | Clock Clock |
| 52 | Authority Authority |
| 53 | Adapters map[Operation]Adapter |
| 54 | Marker string |
| 55 | commitHook func(string) error // tests terminate a process at exact commit boundaries |
| 56 | } |
| 57 | |
| 58 | // Store is the durable core. A process-shared guard serializes each SQLite |
| 59 | // commit with its external witness. Open launches no goroutine or network |
| 60 | // connection. The database, witness and lock live in trusted local storage. |
| 61 | type Store struct { |
| 62 | observerFailed func() |
| 63 | observeWrite func(context.Context, *sql.Tx) (CommitObserver, error) |
| 64 | renderedApproval RenderedApprovalValidator |
| 65 | sourceReference SourceReferenceValidator |
| 66 | executorEvidence ExecutorEvidenceValidator |
| 67 | provenance ProvenanceResolver |
| 68 | db *sql.DB |
| 69 | ownsDB bool |
| 70 | closed bool |
| 71 | path string |
| 72 | marker string |
| 73 | clock Clock |
| 74 | auth Authority |
| 75 | adapters map[Operation]Adapter |
| 76 | incarnation int64 |
| 77 | recoveryMu sync.Mutex |
| 78 | commitHook func(string) error |
| 79 | writeMu sync.Mutex |
| 80 | broken error // guarded by writeMu; only a new Open can recover it |
| 81 | } |
| 82 | |
| 83 | // Open opens or creates the database at path. Admission is paused on every |
| 84 | // open; Resume lifts it after online revalidation. A database whose marker |
| 85 | // is missing, names another incarnation or records an unclean shutdown |
| 86 | // opens in quarantine. |
| 87 | func Open(ctx context.Context, path string, o Options) (*Store, error) { |
| 88 | if o.Clock == nil || o.Authority == nil { |
| 89 | return nil, fail(CodeInvalid, "open needs a clock and an authority") |
| 90 | } |
| 91 | path, err := canonicalStorePath(path) |
| 92 | if err != nil { |
| 93 | return nil, err |
| 94 | } |
| 95 | if o.Marker == "" { |
| 96 | o.Marker = path + ".incarnation" |
| 97 | } |
| 98 | o.Marker, err = filepath.Abs(o.Marker) |
| 99 | if err != nil { |
| 100 | return nil, err |
| 101 | } |
| 102 | u := url.URL{Scheme: "file", Path: filepath.ToSlash(path), OmitHost: true} |
| 103 | dsn := u.String() + "?_txlock=immediate&_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)&_pragma=foreign_keys(1)" |
| 104 | db, err := sql.Open("sqlite", dsn) |
| 105 | if err != nil { |
| 106 | return nil, fail(CodeInvalid, "open: %v", err) |
| 107 | } |
| 108 | db.SetMaxOpenConns(4) |
| 109 | s := &Store{db: db, ownsDB: true, path: path, marker: o.Marker, clock: &storeClock{source: o.Clock}, auth: o.Authority, adapters: o.Adapters, provenance: o.Provenance, executorEvidence: o.ExecutorEvidence, renderedApproval: o.RenderedApproval, sourceReference: o.SourceReference} |
| 110 | if s.adapters == nil { |
| 111 | s.adapters = map[Operation]Adapter{} |
| 112 | } |
| 113 | if err := s.migrate(ctx); err != nil { |
| 114 | db.Close() |
| 115 | return nil, err |
| 116 | } |
| 117 | s.commitHook = o.commitHook |
| 118 | s.observeWrite = o.ObserveWrite |
| 119 | s.observerFailed = o.ObserverFailed |
| 120 | if err := s.start(ctx); err != nil { |
| 121 | db.Close() |
| 122 | return nil, err |
| 123 | } |
| 124 | return s, nil |
| 125 | } |
| 126 | |
| 127 | // Close pauses admission, records a clean shutdown in the marker and |
| 128 | // closes the database only when Open created the pool. |
| 129 | func (s *Store) Close() error { |
| 130 | ctx := context.Background() |
| 131 | err := s.transact(ctx, true, func(tx *sql.Tx) error { |
| 132 | if err := s.observeClock(ctx, tx); err != nil { |
| 133 | return err |
| 134 | } |
| 135 | _, err := tx.ExecContext(ctx, `UPDATE service SET admission_paused=1 WHERE id=1`) |
| 136 | return err |
| 137 | }) |
| 138 | if s.ownsDB { |
| 139 | if cerr := s.db.Close(); err == nil { |
| 140 | err = cerr |
| 141 | } |
| 142 | } |
| 143 | return err |
| 144 | } |
| 145 | |
| 146 | // Status reports the service row. |
| 147 | func (s *Store) Status(ctx context.Context) (Status, error) { |
| 148 | var st Status |
| 149 | var paused, quarantine int |
| 150 | err := s.read(ctx, func(tx *sql.Tx) error { |
| 151 | return tx.QueryRowContext(ctx, `SELECT schema_version, incarnation, admission_paused, quarantine, quarantine_why FROM service WHERE id=1`). |
| 152 | Scan(&st.SchemaVersion, &st.Incarnation, &paused, &quarantine, &st.QuarantineWhy) |
| 153 | }) |
| 154 | if err != nil { |
| 155 | return st, err |
| 156 | } |
| 157 | st.AdmissionPaused = paused != 0 |
| 158 | st.Quarantine = quarantine != 0 |
| 159 | return st, nil |
| 160 | } |
| 161 | |
| 162 | const schema = ` |
| 163 | CREATE TABLE IF NOT EXISTS service ( |
| 164 | id INTEGER PRIMARY KEY CHECK (id = 1), |
| 165 | schema_version INTEGER NOT NULL, |
| 166 | incarnation INTEGER NOT NULL, |
| 167 | revision INTEGER NOT NULL DEFAULT 0, |
| 168 | restore_uncertain INTEGER NOT NULL DEFAULT 0, |
| 169 | admission_paused INTEGER NOT NULL, |
| 170 | quarantine INTEGER NOT NULL, |
| 171 | quarantine_why TEXT NOT NULL |
| 172 | ); |
| 173 | CREATE TABLE IF NOT EXISTS jobs ( |
| 174 | id INTEGER PRIMARY KEY, |
| 175 | account TEXT NOT NULL, |
| 176 | parent INTEGER NOT NULL, |
| 177 | depth INTEGER NOT NULL, |
| 178 | requester TEXT NOT NULL, |
| 179 | target TEXT NOT NULL, |
| 180 | evidence TEXT NOT NULL, |
| 181 | policy_version INTEGER NOT NULL, |
| 182 | policy TEXT NOT NULL, |
| 183 | grant_ref TEXT NOT NULL, |
| 184 | grant_version INTEGER NOT NULL, |
| 185 | grant_epoch INTEGER NOT NULL, |
| 186 | grant_observed_at TEXT NOT NULL, |
| 187 | state TEXT NOT NULL, |
| 188 | wait TEXT NOT NULL, |
| 189 | revision INTEGER NOT NULL, |
| 190 | outcome TEXT NOT NULL, |
| 191 | created_at TEXT NOT NULL, |
| 192 | updated_at TEXT NOT NULL |
| 193 | ); |
| 194 | CREATE INDEX IF NOT EXISTS jobs_account ON jobs(account, state); |
| 195 | CREATE TABLE IF NOT EXISTS steps ( |
| 196 | id INTEGER PRIMARY KEY, |
| 197 | job_id INTEGER NOT NULL REFERENCES jobs(id), |
| 198 | key TEXT NOT NULL, |
| 199 | capability TEXT NOT NULL, |
| 200 | version INTEGER NOT NULL, |
| 201 | depends_on TEXT NOT NULL, |
| 202 | state TEXT NOT NULL, |
| 203 | fence INTEGER NOT NULL, |
| 204 | holder INTEGER NOT NULL, |
| 205 | attempts INTEGER NOT NULL, |
| 206 | UNIQUE(job_id, key) |
| 207 | ); |
| 208 | CREATE TABLE IF NOT EXISTS attempts ( |
| 209 | id INTEGER PRIMARY KEY, |
| 210 | job_id INTEGER NOT NULL REFERENCES jobs(id), |
| 211 | step_id INTEGER NOT NULL REFERENCES steps(id), |
| 212 | number INTEGER NOT NULL, |
| 213 | runner TEXT NOT NULL, |
| 214 | workspace TEXT NOT NULL, |
| 215 | fence INTEGER NOT NULL, |
| 216 | lease_deadline TEXT NOT NULL, |
| 217 | state TEXT NOT NULL, |
| 218 | containment TEXT NOT NULL, |
| 219 | stop_requested TEXT NOT NULL, |
| 220 | stop_acked TEXT NOT NULL, |
| 221 | provider TEXT NOT NULL, |
| 222 | model TEXT NOT NULL, |
| 223 | effort TEXT NOT NULL, |
| 224 | outcome TEXT NOT NULL, |
| 225 | created_at TEXT NOT NULL, |
| 226 | updated_at TEXT NOT NULL, |
| 227 | UNIQUE(job_id, workspace) |
| 228 | ); |
| 229 | CREATE UNIQUE INDEX IF NOT EXISTS attempts_one_live ON attempts(step_id) WHERE containment = 'pending'; |
| 230 | CREATE INDEX IF NOT EXISTS attempts_job ON attempts(job_id, containment); |
| 231 | CREATE TABLE IF NOT EXISTS reservations ( |
| 232 | id INTEGER PRIMARY KEY, |
| 233 | account TEXT NOT NULL, |
| 234 | job_id INTEGER NOT NULL REFERENCES jobs(id), |
| 235 | step_id INTEGER NOT NULL, |
| 236 | attempt_id INTEGER NOT NULL, |
| 237 | action_id INTEGER NOT NULL, |
| 238 | r_calls INTEGER NOT NULL, r_input INTEGER NOT NULL, r_output INTEGER NOT NULL, r_cost INTEGER NOT NULL, |
| 239 | s_calls INTEGER NOT NULL, s_input INTEGER NOT NULL, s_output INTEGER NOT NULL, s_cost INTEGER NOT NULL, |
| 240 | state TEXT NOT NULL, |
| 241 | receipt_id TEXT NOT NULL, |
| 242 | settled_by TEXT NOT NULL, |
| 243 | created_at TEXT NOT NULL, |
| 244 | settled_at TEXT NOT NULL |
| 245 | ); |
| 246 | CREATE INDEX IF NOT EXISTS reservations_job ON reservations(job_id, state); |
| 247 | CREATE INDEX IF NOT EXISTS reservations_account ON reservations(account, state); |
| 248 | CREATE TABLE IF NOT EXISTS actions ( |
| 249 | id INTEGER PRIMARY KEY, |
| 250 | job_id INTEGER NOT NULL REFERENCES jobs(id), |
| 251 | step_id INTEGER NOT NULL, |
| 252 | attempt_id INTEGER NOT NULL, |
| 253 | fence INTEGER NOT NULL, |
| 254 | key TEXT NOT NULL, |
| 255 | operation TEXT NOT NULL, |
| 256 | class TEXT NOT NULL, |
| 257 | payload_hash TEXT NOT NULL, |
| 258 | payload BLOB NOT NULL, |
| 259 | state TEXT NOT NULL, |
| 260 | reservation_id INTEGER NOT NULL, |
| 261 | grant_ref TEXT NOT NULL, |
| 262 | grant_version INTEGER NOT NULL, |
| 263 | grant_epoch INTEGER NOT NULL, |
| 264 | admitted_at TEXT NOT NULL, |
| 265 | admission_ends TEXT NOT NULL, |
| 266 | receipt TEXT NOT NULL, |
| 267 | last_error TEXT NOT NULL, |
| 268 | created_at TEXT NOT NULL, |
| 269 | updated_at TEXT NOT NULL, |
| 270 | admitted_incarnation INTEGER NOT NULL DEFAULT 0, |
| 271 | UNIQUE(job_id, key) |
| 272 | ); |
| 273 | CREATE INDEX IF NOT EXISTS actions_state ON actions(state); |
| 274 | CREATE TABLE IF NOT EXISTS events ( |
| 275 | job_id INTEGER NOT NULL REFERENCES jobs(id), |
| 276 | seq INTEGER NOT NULL, |
| 277 | type TEXT NOT NULL, |
| 278 | actor TEXT NOT NULL, |
| 279 | payload BLOB NOT NULL, |
| 280 | source_at TEXT NOT NULL, |
| 281 | PRIMARY KEY(job_id, seq) |
| 282 | ); |
| 283 | CREATE TABLE IF NOT EXISTS artifacts ( |
| 284 | id INTEGER PRIMARY KEY, |
| 285 | job_id INTEGER NOT NULL REFERENCES jobs(id), |
| 286 | step_id INTEGER NOT NULL, |
| 287 | attempt_id INTEGER NOT NULL, |
| 288 | fence INTEGER NOT NULL, |
| 289 | role TEXT NOT NULL, |
| 290 | hash TEXT NOT NULL, |
| 291 | media_type TEXT NOT NULL, |
| 292 | size INTEGER NOT NULL, |
| 293 | provenance TEXT NOT NULL, |
| 294 | payload BLOB NOT NULL, |
| 295 | created_at TEXT NOT NULL |
| 296 | ); |
| 297 | CREATE INDEX IF NOT EXISTS artifacts_job ON artifacts(job_id, role); |
| 298 | ` |
| 299 | |
| 300 | func (s *Store) migrate(ctx context.Context) error { |
| 301 | return s.tx(ctx, func(tx *sql.Tx) error { |
| 302 | if _, err := tx.ExecContext(ctx, schema); err != nil { |
| 303 | return fail(CodeInvalid, "schema: %v", err) |
| 304 | } |
| 305 | var v int |
| 306 | err := tx.QueryRowContext(ctx, `SELECT schema_version FROM service WHERE id=1`).Scan(&v) |
| 307 | switch { |
| 308 | case errors.Is(err, sql.ErrNoRows): |
| 309 | _, err = tx.ExecContext(ctx, `INSERT INTO service(id, schema_version, incarnation, admission_paused, quarantine, quarantine_why) VALUES (1, ?, 0, 1, 0, '')`, 3) |
| 310 | if err != nil { |
| 311 | return fail(CodeInvalid, "service row: %v", err) |
| 312 | } |
| 313 | case err != nil: |
| 314 | return fail(CodeInvalid, "service row: %v", err) |
| 315 | case v > SchemaVersion: |
| 316 | return fail(CodeStaleStore, "schema %d newer than %d", v, SchemaVersion) |
| 317 | case v == 1: |
| 318 | for _, statement := range []string{ |
| 319 | `ALTER TABLE service ADD COLUMN revision INTEGER NOT NULL DEFAULT 0`, |
| 320 | `ALTER TABLE service ADD COLUMN restore_uncertain INTEGER NOT NULL DEFAULT 0`, |
| 321 | `ALTER TABLE actions ADD COLUMN admitted_incarnation INTEGER NOT NULL DEFAULT 0`, |
| 322 | } { |
| 323 | if _, err := tx.ExecContext(ctx, statement); err != nil { |
| 324 | return fail(CodeInvalid, "migration: %v", err) |
| 325 | } |
| 326 | } |
| 327 | if _, err := tx.ExecContext(ctx, `UPDATE service SET schema_version=2 WHERE id=1`); err != nil { |
| 328 | return err |
| 329 | } |
| 330 | v = 2 |
| 331 | case v != 2 && v != 3 && v != 4 && v != 5 && v != 6 && v != 7 && v != SchemaVersion: |
| 332 | return fail(CodeStaleStore, "unsupported schema %d", v) |
| 333 | } |
| 334 | rows, err := tx.QueryContext(ctx, `PRAGMA table_info(jobs)`) |
| 335 | if err != nil { |
| 336 | return err |
| 337 | } |
| 338 | hasProject := false |
| 339 | for rows.Next() { |
| 340 | var cid, notnull, pk int |
| 341 | var name, typ string |
| 342 | var def any |
| 343 | if err := rows.Scan(&cid, &name, &typ, ¬null, &def, &pk); err != nil { |
| 344 | rows.Close() |
| 345 | return err |
| 346 | } |
| 347 | if name == "project_id" { |
| 348 | hasProject = true |
| 349 | } |
| 350 | } |
| 351 | err = rows.Err() |
| 352 | rows.Close() |
| 353 | if err != nil { |
| 354 | return err |
| 355 | } |
| 356 | if !hasProject { |
| 357 | if _, err := tx.ExecContext(ctx, `ALTER TABLE jobs ADD COLUMN project_id INTEGER NOT NULL DEFAULT 0`); err != nil { |
| 358 | return err |
| 359 | } |
| 360 | } |
| 361 | if _, err := tx.ExecContext(ctx, periodSchema); err != nil { |
| 362 | return err |
| 363 | } |
| 364 | if v > 0 && v < 3 { |
| 365 | if _, err = tx.ExecContext(ctx, `UPDATE service SET schema_version=3 WHERE id=1`); err != nil { |
| 366 | return err |
| 367 | } |
| 368 | } |
| 369 | if v < 4 { |
| 370 | if _, err = tx.ExecContext(ctx, recoverySchema); err != nil { |
| 371 | return err |
| 372 | } |
| 373 | if v < 3 { |
| 374 | if err := migrateTimeReservations(ctx, tx); err != nil { |
| 375 | return err |
| 376 | } |
| 377 | } |
| 378 | _, err = tx.ExecContext(ctx, `UPDATE service SET schema_version=4 WHERE id=1`) |
| 379 | } |
| 380 | if err != nil { |
| 381 | return err |
| 382 | } |
| 383 | if v < 5 { |
| 384 | _, err = tx.ExecContext(ctx, runnerPolicySchema) |
| 385 | } |
| 386 | if err != nil { |
| 387 | return err |
| 388 | } |
| 389 | if v < 6 { |
| 390 | _, err = tx.ExecContext(ctx, jobRequestSchema) |
| 391 | } |
| 392 | if err != nil { |
| 393 | return err |
| 394 | } |
| 395 | if v < 7 { |
| 396 | _, err = tx.ExecContext(ctx, admissionSchema) |
| 397 | } |
| 398 | if err == nil && v < 8 { |
| 399 | _, err = tx.ExecContext(ctx, coordinatorSchema) |
| 400 | } |
| 401 | return err |
| 402 | }) |
| 403 | } |
| 404 | |
| 405 | // start bumps the incarnation, pauses admission and decides quarantine |
| 406 | // from the marker outside the database. |
| 407 | func (s *Store) start(ctx context.Context) error { |
| 408 | var next int64 |
| 409 | err := s.transaction(ctx, false, true, func(tx *sql.Tx) error { |
| 410 | var high string |
| 411 | if err := tx.QueryRowContext(ctx, "SELECT clock_high_water FROM service WHERE id=1").Scan(&high); err != nil { |
| 412 | return err |
| 413 | } |
| 414 | s.clock.(*storeClock).remember(parseTS(high)) |
| 415 | var inc, revision int64 |
| 416 | var previousRestore, previousQuarantine int |
| 417 | var previousWhy string |
| 418 | if err := tx.QueryRowContext(ctx, `SELECT incarnation, revision, restore_uncertain, quarantine, quarantine_why FROM service WHERE id=1`).Scan(&inc, &revision, &previousRestore, &previousQuarantine, &previousWhy); err != nil { |
| 419 | return err |
| 420 | } |
| 421 | why, restore := "", previousRestore |
| 422 | if previousQuarantine != 0 { |
| 423 | why = previousWhy |
| 424 | } |
| 425 | mInc, mRevision, clean, markerErr := readMarker(s.marker) |
| 426 | if inc == 0 { |
| 427 | // Establish an empty predecessor before the first commit. A |
| 428 | // crash during the first Open then has the same one-step gap. |
| 429 | if errors.Is(markerErr, os.ErrNotExist) && revision == 0 { |
| 430 | if err := writeMarker(s.marker, 0, 0, false); err != nil { |
| 431 | return err |
| 432 | } |
| 433 | mInc, mRevision, markerErr = 0, 0, nil |
| 434 | } |
| 435 | if markerErr != nil || mInc != 0 || mRevision != 0 || revision != 0 { |
| 436 | return fail(CodeStaleStore, "empty database has no matching empty witness") |
| 437 | } |
| 438 | } else { |
| 439 | switch { |
| 440 | case markerErr != nil: |
| 441 | why, restore = "marker missing or unreadable: "+markerErr.Error(), 1 |
| 442 | case revision > 0 && mRevision == revision-1 && (mInc == inc || (inc > 0 && mInc == inc-1)): |
| 443 | // SQL committed but its witness did not. Repair the witness |
| 444 | // before another commit, so repeated crashes never widen the gap. |
| 445 | if err := writeMarker(s.marker, inc, revision, false); err != nil { |
| 446 | return err |
| 447 | } |
| 448 | why = "unclean shutdown after database commit" |
| 449 | case mInc != inc || mRevision != revision: |
| 450 | why, restore = fmt.Sprintf("marker position %d/%d, database %d/%d: restored snapshot", mInc, mRevision, inc, revision), 1 |
| 451 | case !clean: |
| 452 | why = "unclean shutdown" |
| 453 | } |
| 454 | } |
| 455 | if restore != 0 && why == "" { |
| 456 | why = "restored history requires operator recovery" |
| 457 | } |
| 458 | var err error |
| 459 | next, err = addChecked(max(inc, mInc), 1) |
| 460 | if err != nil { |
| 461 | return err |
| 462 | } |
| 463 | if restore != 0 { |
| 464 | if _, err := tx.ExecContext(ctx, `UPDATE actions SET state='uncertain', last_error='restored intent may have executed after snapshot' WHERE state='intent'`); err != nil { |
| 465 | return err |
| 466 | } |
| 467 | } |
| 468 | if err := settleRecoveredUnknown(ctx, tx, s.clock.Now()); err != nil { |
| 469 | return err |
| 470 | } |
| 471 | // Classify restored intents before clock rollback can revoke live intents. |
| 472 | if err := s.observeClock(ctx, tx); err != nil { |
| 473 | return err |
| 474 | } |
| 475 | var clockQuarantine int |
| 476 | var clockWhy string |
| 477 | if err := tx.QueryRowContext(ctx, `SELECT quarantine,quarantine_why FROM service WHERE id=1`).Scan(&clockQuarantine, &clockWhy); err != nil { |
| 478 | return err |
| 479 | } |
| 480 | if why == "" && clockQuarantine != 0 { |
| 481 | why = clockWhy |
| 482 | } |
| 483 | q := 0 |
| 484 | if why != "" { |
| 485 | q = 1 |
| 486 | } |
| 487 | _, err = tx.ExecContext(ctx, `UPDATE service SET incarnation=?, recovery_revision=recovery_revision+1, admission_paused=1, quarantine=?, quarantine_why=?, restore_uncertain=? WHERE id=1`, next, q, why, restore) |
| 488 | return err |
| 489 | }) |
| 490 | if err == nil { |
| 491 | s.incarnation = next |
| 492 | } |
| 493 | return err |
| 494 | } |
| 495 | |
| 496 | func readMarker(path string) (int64, int64, bool, error) { |
| 497 | raw, err := os.ReadFile(path) |
| 498 | if err != nil { |
| 499 | return 0, 0, false, err |
| 500 | } |
| 501 | inc, revision := int64(-1), int64(-1) |
| 502 | clean := false |
| 503 | for _, line := range strings.Split(strings.TrimSpace(string(raw)), "\n") { |
| 504 | key, value, ok := strings.Cut(line, "=") |
| 505 | if !ok { |
| 506 | return 0, 0, false, fmt.Errorf("invalid marker line") |
| 507 | } |
| 508 | switch key { |
| 509 | case "incarnation": |
| 510 | inc, err = strconv.ParseInt(value, 10, 64) |
| 511 | case "revision": |
| 512 | revision, err = strconv.ParseInt(value, 10, 64) |
| 513 | case "clean": |
| 514 | clean, err = strconv.ParseBool(value) |
| 515 | } |
| 516 | if err != nil { |
| 517 | return 0, 0, false, err |
| 518 | } |
| 519 | } |
| 520 | if inc < 0 || revision < 0 { |
| 521 | return 0, 0, false, fmt.Errorf("marker has no valid position") |
| 522 | } |
| 523 | return inc, revision, clean, nil |
| 524 | } |
| 525 | |
| 526 | func writeMarker(path string, inc, revision int64, clean bool) error { |
| 527 | tmp := path + ".tmp" |
| 528 | body := fmt.Sprintf("incarnation=%d\nclean=%t\nrevision=%d\n", inc, clean, revision) |
| 529 | if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { |
| 530 | return fail(CodeInvalid, "marker: %v", err) |
| 531 | } |
| 532 | if err := os.WriteFile(tmp, []byte(body), 0o600); err != nil { |
| 533 | return fail(CodeInvalid, "marker: %v", err) |
| 534 | } |
| 535 | if err := os.Rename(tmp, path); err != nil { |
| 536 | return fail(CodeInvalid, "marker: %v", err) |
| 537 | } |
| 538 | return nil |
| 539 | } |
| 540 | |
| 541 | // A successful operation commits SQL and then publishes the same position |
| 542 | // externally, under one process-shared guard. A failed witness write poisons |
| 543 | // this handle. Thus a crash leaves either equal positions or exactly one |
| 544 | // unpublished commit; start repairs that gap before advancing again. |
| 545 | // Reads also advance the position in this bounded prototype. |
| 546 | func (s *Store) tx(ctx context.Context, fn func(*sql.Tx) error) error { |
| 547 | if tx := s.bound(ctx); tx != nil { |
| 548 | return fn(tx) |
| 549 | } |
| 550 | return s.transact(ctx, false, func(tx *sql.Tx) error { |
| 551 | if s.incarnation != 0 { |
| 552 | if err := s.observeClock(ctx, tx); err != nil { |
| 553 | return err |
| 554 | } |
| 555 | } |
| 556 | return fn(tx) |
| 557 | }) |
| 558 | } |
| 559 | |
| 560 | func (s *Store) read(ctx context.Context, fn func(*sql.Tx) error) error { |
| 561 | if tx := s.bound(ctx); tx != nil { |
| 562 | return fn(tx) |
| 563 | } |
| 564 | return s.transact(ctx, false, fn) |
| 565 | } |
| 566 | |
| 567 | func (s *Store) transact(ctx context.Context, clean bool, fn func(*sql.Tx) error) error { |
| 568 | return s.transaction(ctx, clean, s.incarnation != 0, fn) |
| 569 | } |
| 570 | |
| 571 | func (s *Store) transaction(ctx context.Context, clean, witnessed bool, fn func(*sql.Tx) error) error { |
| 572 | var committedNotify func() |
| 573 | defer func() { |
| 574 | if committedNotify != nil { |
| 575 | committedNotify() |
| 576 | } |
| 577 | }() |
| 578 | return s.withStoreGuard(ctx, func() error { |
| 579 | if s.closed { |
| 580 | return fail(CodeStaleStore, "store is closed") |
| 581 | } |
| 582 | if clean { |
| 583 | defer func() { s.closed = true }() |
| 584 | } |
| 585 | tx, err := s.db.BeginTx(ctx, nil) |
| 586 | if err != nil { |
| 587 | return fail(CodeInvalid, "begin: %v", err) |
| 588 | } |
| 589 | defer tx.Rollback() |
| 590 | if s.incarnation != 0 { |
| 591 | var current, revision int64 |
| 592 | if err := tx.QueryRowContext(ctx, `SELECT incarnation, revision FROM service WHERE id=1`).Scan(¤t, &revision); err != nil { |
| 593 | return err |
| 594 | } |
| 595 | if current != s.incarnation { |
| 596 | return fail(CodeStaleStore, "incarnation %d replaced by %d", s.incarnation, current) |
| 597 | } |
| 598 | mInc, mRevision, _, err := readMarker(s.marker) |
| 599 | if err != nil || mInc != current || mRevision != revision { |
| 600 | s.broken = fail(CodeStaleStore, "database and witness differ; reopen for recovery") |
| 601 | return s.broken |
| 602 | } |
| 603 | } |
| 604 | var observer CommitObserver |
| 605 | if s.observeWrite != nil { |
| 606 | observer, err = s.observeWrite(ctx, tx) |
| 607 | if err != nil { |
| 608 | observer = nil |
| 609 | if s.observerFailed != nil { |
| 610 | s.observerFailed() |
| 611 | } |
| 612 | } |
| 613 | } |
| 614 | if err := fn(tx); err != nil { |
| 615 | return err |
| 616 | } |
| 617 | var notify func() |
| 618 | if observer != nil { |
| 619 | notify, err = observer(ctx, tx) |
| 620 | if err != nil { |
| 621 | notify = nil |
| 622 | if s.observerFailed != nil { |
| 623 | s.observerFailed() |
| 624 | } |
| 625 | } |
| 626 | } |
| 627 | var inc, revision int64 |
| 628 | if witnessed { |
| 629 | if err := tx.QueryRowContext(ctx, `SELECT incarnation, revision FROM service WHERE id=1`).Scan(&inc, &revision); err != nil { |
| 630 | return err |
| 631 | } |
| 632 | revision, err = addChecked(revision, 1) |
| 633 | if err != nil { |
| 634 | return err |
| 635 | } |
| 636 | if _, err := tx.ExecContext(ctx, `UPDATE service SET revision=? WHERE id=1`, revision); err != nil { |
| 637 | return err |
| 638 | } |
| 639 | } |
| 640 | if s.commitHook != nil { |
| 641 | if err := s.commitHook("before_commit"); err != nil { |
| 642 | return err |
| 643 | } |
| 644 | } |
| 645 | if err := tx.Commit(); err != nil { |
| 646 | s.broken = err // a commit error may leave its outcome unknown |
| 647 | return fail(CodeInvalid, "commit: %v", err) |
| 648 | } |
| 649 | committedNotify = notify |
| 650 | if s.commitHook != nil { |
| 651 | if err := s.commitHook("after_commit"); err != nil { |
| 652 | s.broken = err |
| 653 | return err |
| 654 | } |
| 655 | } |
| 656 | if witnessed { |
| 657 | if err := writeMarker(s.marker, inc, revision, clean); err != nil { |
| 658 | s.broken = err |
| 659 | return err |
| 660 | } |
| 661 | } |
| 662 | return nil |
| 663 | }) |
| 664 | } |
| 665 | |
| 666 | // admissionOpen fails closed while the service is paused or quarantined. |
| 667 | func admissionOpen(ctx context.Context, tx *sql.Tx) error { |
| 668 | var paused, quarantine int |
| 669 | var why string |
| 670 | if err := tx.QueryRowContext(ctx, `SELECT admission_paused, quarantine, quarantine_why FROM service WHERE id=1`).Scan(&paused, &quarantine, &why); err != nil { |
| 671 | return fail(CodeInvalid, "service row: %v", err) |
| 672 | } |
| 673 | if quarantine != 0 { |
| 674 | return fail(CodeAdmissionPaused, "quarantine: %s", why) |
| 675 | } |
| 676 | if paused != 0 { |
| 677 | return fail(CodeAdmissionPaused, "admission paused until resume") |
| 678 | } |
| 679 | return nil |
| 680 | } |
| 681 | |
| 682 | // Time columns are RFC3339Nano UTC text; the zero time is the empty string. |
| 683 | func ts(t time.Time) string { |
| 684 | if t.IsZero() { |
| 685 | return "" |
| 686 | } |
| 687 | return t.UTC().Format(time.RFC3339Nano) |
| 688 | } |
| 689 | |
| 690 | func parseTS(s string) time.Time { |
| 691 | if s == "" { |
| 692 | return time.Time{} |
| 693 | } |
| 694 | t, err := time.Parse(time.RFC3339Nano, s) |
| 695 | if err != nil { |
| 696 | return time.Time{} |
| 697 | } |
| 698 | return t |
| 699 | } |
| 700 | |
| 701 | const runnerPolicySchema = ` |
| 702 | ALTER TABLE reservations ADD COLUMN project_id INTEGER NOT NULL DEFAULT 0; |
| 703 | ALTER TABLE reservations ADD COLUMN period TEXT NOT NULL DEFAULT ""; |
| 704 | ALTER TABLE reservations ADD COLUMN cost_unavailable INTEGER NOT NULL DEFAULT 0; |
| 705 | ALTER TABLE reservations ADD COLUMN s_cached INTEGER NOT NULL DEFAULT 0; |
| 706 | ALTER TABLE period_budgets ADD COLUMN content_hash TEXT NOT NULL DEFAULT ""; |
| 707 | CREATE TABLE runner_policy_validation (valid INTEGER NOT NULL CHECK(valid=1)); |
| 708 | INSERT INTO runner_policy_validation SELECT CASE WHEN EXISTS ( |
| 709 | SELECT 1 FROM reservations r LEFT JOIN jobs j ON j.id=r.job_id |
| 710 | WHERE j.id IS NULL OR j.account!=r.account OR j.project_id<0 |
| 711 | OR length(r.created_at)<20 OR substr(r.created_at,-1)!='Z' |
| 712 | OR substr(r.created_at,1,19) NOT GLOB '[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]T[0-9][0-9]:[0-9][0-9]:[0-9][0-9]' |
| 713 | OR substr(r.created_at,12,2)>'23' OR substr(r.created_at,15,2)>'59' OR substr(r.created_at,18,2)>'59' |
| 714 | OR date(substr(r.created_at,1,10),'+0 days')!=substr(r.created_at,1,10) |
| 715 | OR (length(r.created_at)!=20 AND (length(r.created_at)<22 OR length(r.created_at)>30 |
| 716 | OR substr(r.created_at,20,1)!='.' OR substr(r.created_at,21,length(r.created_at)-21) GLOB '*[^0-9]*')) |
| 717 | OR strftime('%Y-%m',substr(r.created_at,1,19)||'Z') IS NULL |
| 718 | OR r.state NOT IN ('open','settled','settled_audited','released') |
| 719 | ) OR EXISTS ( |
| 720 | SELECT 1 FROM time_reservations r LEFT JOIN jobs j ON j.id=r.job_id |
| 721 | WHERE j.id IS NULL OR j.account!=r.account OR j.project_id!=r.project_id |
| 722 | OR r.project_id<0 OR length(r.period)!=7 OR strftime('%Y-%m',r.period||'-01') IS NULL |
| 723 | OR r.state NOT IN ('open','settled') |
| 724 | ) THEN 0 ELSE 1 END; |
| 725 | DROP TABLE runner_policy_validation; |
| 726 | UPDATE reservations SET project_id=(SELECT project_id FROM jobs WHERE id=reservations.job_id), period=substr(created_at,1,7); |
| 727 | CREATE INDEX reservations_period_account ON reservations(account,state,period); |
| 728 | CREATE INDEX reservations_period_project ON reservations(account,project_id,state,period); |
| 729 | CREATE INDEX time_period_account ON time_reservations(account,state,period); |
| 730 | CREATE INDEX time_period_project ON time_reservations(account,project_id,state,period); |
| 731 | CREATE INDEX recovery_charges_scope ON recovery_charges(account,project_id); |
| 732 | UPDATE service SET schema_version=5 WHERE id=1; |
| 733 | ` |
| 734 | |
| 735 | const jobRequestSchema = ` |
| 736 | ALTER TABLE jobs ADD COLUMN request_key TEXT NOT NULL DEFAULT ""; |
| 737 | ALTER TABLE jobs ADD COLUMN request_hash TEXT NOT NULL DEFAULT ""; |
| 738 | CREATE UNIQUE INDEX jobs_request ON jobs(account, requester, request_key) WHERE request_key <> ''; |
| 739 | UPDATE service SET schema_version=6 WHERE id=1; |
| 740 | ` |
| 741 | |