oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package hostedctl
2
3import (
4 "context"
5 "crypto/rand"
6 "crypto/sha256"
7 "database/sql"
8 "encoding/binary"
9 "encoding/hex"
10 "encoding/json"
11 "errors"
12 "fmt"
13 "math"
14 "strings"
15 "time"
16
17 "amadan.net/oficina/equipo/internal/hostedwire"
18 "amadan.net/oficina/equipo/internal/isolatedjob"
19)
20
21var (
22 // ErrDisabled: launches are off (EQUIPO_HOSTED_ENABLED is not 1).
23 ErrDisabled = errors.New("hostedctl: hosted launches are disabled")
24 // ErrForbidden: the verified key's role may not make this call.
25 ErrForbidden = errors.New("hostedctl: this key may not do that")
26 // ErrImageNotAllowed: the image digest is not in Config.Images.
27 ErrImageNotAllowed = errors.New("hostedctl: image is not in the allowlist")
28 // ErrReplacementLive: the attempt named in Replaces is unknown, belongs
29 // to another key, or has no stop proof yet.
30 ErrReplacementLive = errors.New("hostedctl: replaced attempt is not proven stopped")
31 // ErrProviderLaunch: the provider's launch call failed in a way none of
32 // the isolatedjob sentinels names. The provider's own text is dropped,
33 // as it might echo the request and with it the instance code.
34 ErrProviderLaunch = errors.New("hostedctl: provider launch failed")
35)
36
37// DrainBefore and StopBefore place a job's drain and stop times before its
38// deadline (spec §3: draining at 7 h 15 min and a forced stop at 7 h 50 min
39// of an 8 hour lifetime).
40const (
41 DrainBefore = 45 * time.Minute
42 StopBefore = 10 * time.Minute
43)
44
45// maxNameLen bounds TaskID and Account. Controller policy (ruling R16): the
46// two IDs are written into audit rows and alerts, so they are kept short and
47// printable.
48const maxNameLen = 128
49
50// launchIDLen is the length of a launch ID: 128 random bits in hex.
51const launchIDLen = 32
52
53// purposeTask is jobs.purpose for a launch that runs a task attempt.
54const purposeTask = "task"
55
56// Audit actions written by Launch and Replay.
57const (
58 actionLaunchRefused = "launch_refused"
59 actionLaunchIntent = "launch_intent"
60 actionLaunchRepeated = "launch_repeated"
61 actionLaunchDeferred = "launch_deferred"
62 actionLaunchStarted = "launch_started"
63 actionLaunchThrottled = "launch_throttled"
64 actionLaunchFailed = "launch_failed"
65 actionLaunchAbandoned = "launch_abandoned"
66 actionReplayStarted = "replay_started"
67 actionReplayThrottled = "replay_throttled"
68 actionReplayFailed = "replay_failed"
69 actionReplayAbandoned = "replay_abandoned"
70 actionVMAfterAbandon = "vm_after_abandon"
71 providerFailureReason = "provider error; intent kept for replay"
72 providerThrottleReason = "provider throttled; intent kept for replay"
73 reasonConfigChanged = "config_changed"
74)
75
76// AlertConfigChanged: a launch intent was abandoned because the provider
77// settings it was saved with changed (ruling R29).
78const AlertConfigChanged = "config_changed"
79
80// LaunchRequest asks for one VM for one task attempt. InstanceCode is a
81// secret: it goes into the VM's bootstrap and the saved spec, and nowhere
82// else.
83type LaunchRequest struct {
84 AttemptID, TaskID, Account, Replaces string
85 Image isolatedjob.ImageDigest
86 Size isolatedjob.Size
87 MaxLifetime time.Duration
88 InstanceCode string
89}
90
91// JobView is the controller's view of one attempt. The *In fields count down
92// in controller time from the moment the view was read, and are zero once
93// passed.
94type JobView struct {
95 AttemptID, LaunchID, State string
96 VMRef isolatedjob.Ref
97 Epoch int64
98 DeadlineIn, DrainIn, StopIn time.Duration
99}
100
101// Deadlines returns a job's deadline (launched plus lifetime), its drain
102// time (DrainBefore the deadline) and its stop time (StopBefore the
103// deadline). Drain and stop are never before launched; a negative lifetime
104// counts as zero and the deadline saturates rather than overflow.
105func Deadlines(launched T, lifetime time.Duration) (deadline, drain, stop T) {
106 lifetime = max(lifetime, 0)
107 deadline = launched + T(lifetime)
108 if deadline < launched {
109 deadline = T(math.MaxInt64)
110 }
111 drain = max(launched, deadline-T(DrainBefore))
112 stop = max(launched, deadline-T(StopBefore))
113 return deadline, drain, stop
114}
115
116// Launch saves a launch intent for q and then asks the provider for the VM.
117//
118// In order it refuses: launches switched off (ErrDisabled); a key without
119// RoleInstance (ErrForbidden); a malformed request (isolatedjob.ErrInvalid,
120// or ErrBootstrapTooLarge; see checkRequest for the controller's own
121// limits); an image outside Config.Images (ErrImageNotAllowed); no passing
122// network audit begun within AuditMaxAge (ErrNetworkAudit). Each refusal is
123// audited and creates nothing.
124//
125// Transaction 1 then looks up q.AttemptID. A job saved for the same request
126// by the same key is returned as it stands, with no provider call; a
127// different request, or another key, gives isolatedjob.ErrConflict. A new
128// attempt naming Replaces needs that attempt to exist, belong to by and
129// carry stop proof (ErrReplacementLive). Otherwise transaction 1 draws a
130// fresh launch ID, builds the exact LaunchSpec and saves it as a JobWaiting
131// intent with deadlines from the current controller time.
132//
133// After that commit, dispatch re-reads the intent and re-checks every gate
134// that guards VM creation, as Replay does, immediately before the provider
135// call: a stop asked for or the stop time reached abandons the intent
136// (JobAbandoned); launches off, the image dropped or no fresh passing audit
137// leaves it JobWaiting, and Launch returns that view with a nil error. Time
138// spent queueing for transaction 1 can let the audit go stale, so the check
139// before it is not enough.
140//
141// The provider call runs outside any transaction, with the attempt ID as
142// its client token. On success transaction 2 saves the Ref and JobStarting.
143// A throttle returns the JobWaiting view and a nil error: Replay launches it
144// once the provider allows. Any other provider error, a lost reply included,
145// returns a zero view and a fixed error (see providerError); the intent
146// stays JobWaiting for Replay, which re-sends the same spec, so a VM the lost
147// call created is found again rather than doubled.
148func (c *Controller) Launch(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, q LaunchRequest) (JobView, error) {
149 if !c.cfg.Enabled {
150 return c.refuse(ctx, by, q, ErrDisabled)
151 }
152 if by == "" || key.Role != hostedwire.RoleInstance {
153 return c.refuse(ctx, by, q, fmt.Errorf("%w: launch needs an instance key", ErrForbidden))
154 }
155 if err := c.checkRequest(q); err != nil {
156 return c.refuse(ctx, by, q, err)
157 }
158 if !c.cfg.Images[q.Image] {
159 return c.refuse(ctx, by, q, fmt.Errorf("%w: %s", ErrImageNotAllowed, q.Image))
160 }
161 if err := c.audit.check(c.store.Clock().Now()); err != nil {
162 return c.refuse(ctx, by, q, err)
163 }
164
165 view, created, err := c.saveIntent(ctx, by, q)
166 if err != nil || !created {
167 return view, err
168 }
169 view, gate, err := c.dispatch(ctx, by, q.AttemptID, false)
170 if gate != nil {
171 aerr := c.store.Tx(ctx, func(tx *sql.Tx) error {
172 return appendAudit(tx, Audit{Actor: by, Account: q.Account, Task: q.TaskID, Attempt: q.AttemptID,
173 Action: actionLaunchDeferred, Reason: "intent kept for replay: " + gate.Error(), At: c.store.Clock().Now()})
174 })
175 if aerr != nil {
176 return JobView{}, aerr
177 }
178 }
179 return view, err
180}
181
182// refuse audits a refusal that came before any transaction, in a short
183// transaction of its own, and returns err. The row names the request's
184// attempt, task and account, never its instance code.
185func (c *Controller) refuse(ctx context.Context, by hostedwire.KeyID, q LaunchRequest, err error) (JobView, error) {
186 aerr := c.store.Tx(ctx, func(tx *sql.Tx) error {
187 return appendAudit(tx, Audit{Actor: by, Account: q.Account, Task: q.TaskID, Attempt: q.AttemptID,
188 Action: actionLaunchRefused, Reason: err.Error(), At: c.store.Clock().Now()})
189 })
190 if aerr != nil {
191 return JobView{}, errors.Join(err, aerr)
192 }
193 return JobView{}, err
194}
195
196// checkRequest checks q's fields, then validates the spec q would give
197// against the runner's limits. That spec carries a placeholder launch ID of
198// the real length, so the bootstrap size checked is the size sent; the real
199// ID is drawn only in transaction 1, for a new intent.
200//
201// Two limits are controller policy (ruling R16), beyond what the provider
202// needs: TaskID and Account must be 1 to maxNameLen printable ASCII
203// characters, as they appear in audit rows and alerts; and MaxLifetime must
204// be more than StopBefore, since a shorter one has its stop time at launch
205// and the reaper would stop it, or Replay abandon it, at once.
206func (c *Controller) checkRequest(q LaunchRequest) error {
207 switch {
208 case !printableASCII(q.TaskID, maxNameLen):
209 return fmt.Errorf("%w: task id must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen)
210 case !printableASCII(q.Account, maxNameLen):
211 return fmt.Errorf("%w: account must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen)
212 case q.Replaces != "" && !printableASCII(q.Replaces, maxNameLen):
213 return fmt.Errorf("%w: replaced attempt id must be printable ASCII", isolatedjob.ErrInvalid)
214 case q.MaxLifetime <= StopBefore:
215 return fmt.Errorf("%w: lifetime %v must be more than %v", isolatedjob.ErrInvalid, q.MaxLifetime, StopBefore)
216 case !printableASCII(q.InstanceCode, math.MaxInt):
217 // The text never repeats the code.
218 return fmt.Errorf("%w: instance code must be one or more printable ASCII characters", isolatedjob.ErrInvalid)
219 }
220 spec, err := buildSpec(q, strings.Repeat("0", launchIDLen))
221 if err != nil {
222 return err
223 }
224 return spec.Validate(c.runner.Limits())
225}
226
227// buildSpec is the LaunchSpec for q with launchID in its bootstrap.
228func buildSpec(q LaunchRequest, launchID string) (isolatedjob.LaunchSpec, error) {
229 boot, err := json.Marshal(hostedwire.Bootstrap{Version: hostedwire.BootstrapVersion, LaunchID: launchID, InstanceCode: q.InstanceCode})
230 if err != nil {
231 return isolatedjob.LaunchSpec{}, fmt.Errorf("hostedctl: encode bootstrap: %w", err)
232 }
233 return isolatedjob.LaunchSpec{AttemptID: q.AttemptID, Image: q.Image, Size: q.Size, MaxLifetime: q.MaxLifetime, Bootstrap: boot}, nil
234}
235
236// printableASCII reports whether s is 1 to n bytes, each from ' ' to '~'.
237// The AWS adapter refuses payloads that are not ASCII.
238func printableASCII(s string, n int) bool {
239 if len(s) == 0 || len(s) > n {
240 return false
241 }
242 for i := 0; i < len(s); i++ {
243 if s[i] < 0x20 || s[i] > 0x7e {
244 return false
245 }
246 }
247 return true
248}
249
250// newLaunchID returns 128 random bits as launchIDLen lower-case hex digits.
251func newLaunchID() (string, error) {
252 var b [launchIDLen / 2]byte
253 if _, err := rand.Read(b[:]); err != nil {
254 return "", fmt.Errorf("hostedctl: launch id: %w", err)
255 }
256 return hex.EncodeToString(b[:]), nil
257}
258
259// requestHash is the SHA-256, in hex, of a canonical encoding of q and by:
260// each field as its length (uvarint) and then its bytes, in a fixed order.
261// It decides whether a repeated launch is the same request.
262func requestHash(by hostedwire.KeyID, q LaunchRequest) string {
263 h := sha256.New()
264 field := func(s string) {
265 _, _ = h.Write(binary.AppendUvarint(nil, uint64(len(s))))
266 _, _ = h.Write([]byte(s))
267 }
268 field("hostedctl launch request v1")
269 field(string(by))
270 field(q.AttemptID)
271 field(q.TaskID)
272 field(q.Account)
273 field(q.Replaces)
274 field(string(q.Image))
275 field(string(q.Size))
276 field(fmt.Sprint(int64(q.MaxLifetime)))
277 field(q.InstanceCode)
278 return hex.EncodeToString(h.Sum(nil))
279}
280
281// storedSpec is the layout of jobs.spec_json: the exact LaunchSpec sent to
282// the provider, so a replay re-sends identical bytes.
283type storedSpec struct {
284 AttemptID string `json:"attempt_id"`
285 Image isolatedjob.ImageDigest `json:"image"`
286 Size isolatedjob.Size `json:"size"`
287 MaxLifetimeNS int64 `json:"max_lifetime_ns"`
288 Bootstrap []byte `json:"bootstrap"`
289}
290
291func encodeSpec(s isolatedjob.LaunchSpec) (string, error) {
292 b, err := json.Marshal(storedSpec{AttemptID: s.AttemptID, Image: s.Image, Size: s.Size,
293 MaxLifetimeNS: int64(s.MaxLifetime), Bootstrap: s.Bootstrap})
294 if err != nil {
295 return "", fmt.Errorf("hostedctl: encode launch spec: %w", err)
296 }
297 return string(b), nil
298}
299
300// decodeSpec reads a saved spec and checks it is the one for attempt.
301func decodeSpec(text, attempt string) (isolatedjob.LaunchSpec, error) {
302 var s storedSpec
303 if err := json.Unmarshal([]byte(text), &s); err != nil {
304 return isolatedjob.LaunchSpec{}, fmt.Errorf("hostedctl: saved spec for %s is unreadable", attempt)
305 }
306 if s.AttemptID != attempt {
307 return isolatedjob.LaunchSpec{}, fmt.Errorf("hostedctl: saved spec for %s names attempt %s", attempt, s.AttemptID)
308 }
309 return isolatedjob.LaunchSpec{AttemptID: s.AttemptID, Image: s.Image, Size: s.Size,
310 MaxLifetime: time.Duration(s.MaxLifetimeNS), Bootstrap: s.Bootstrap}, nil
311}
312
313// saveIntent is transaction 1. It returns the existing job's view when the
314// same request was saved before (created false), or draws a launch ID,
315// builds the spec, saves the new intent and returns its view (created
316// true). A conflict or a live replaced attempt is audited, committed, and
317// returned as the error.
318func (c *Controller) saveIntent(ctx context.Context, by hostedwire.KeyID, q LaunchRequest) (JobView, bool, error) {
319 hash := requestHash(by, q)
320 var view JobView
321 var created bool
322 var refusal error
323 err := c.store.Tx(ctx, func(tx *sql.Tx) error {
324 view, created, refusal = JobView{}, false, nil
325 now := c.store.Clock().Now()
326 a := Audit{Actor: by, Account: q.Account, Task: q.TaskID, Attempt: q.AttemptID, At: now}
327 j, found, err := loadJob(ctx, tx, q.AttemptID)
328 if err != nil {
329 return err
330 }
331 if found {
332 if j.specSHA != hash {
333 refusal = fmt.Errorf("%w: attempt %s was asked for with a different request", isolatedjob.ErrConflict, q.AttemptID)
334 a.Action, a.Reason = actionLaunchRefused, refusal.Error()
335 return appendAudit(tx, a)
336 }
337 view = j.view(now)
338 a.Action, a.Reason = actionLaunchRepeated, "same request again; job is "+j.state
339 return appendAudit(tx, a)
340 }
341 if q.Replaces != "" {
342 if err := checkReplaces(ctx, tx, by, q.Replaces); err != nil {
343 if !errors.Is(err, ErrReplacementLive) {
344 return err // a lookup error denies and saves nothing
345 }
346 refusal = err
347 a.Action, a.Reason = actionLaunchRefused, err.Error()
348 return appendAudit(tx, a)
349 }
350 }
351 launchID, err := newLaunchID()
352 if err != nil {
353 return err
354 }
355 spec, err := buildSpec(q, launchID)
356 if err != nil {
357 return err
358 }
359 specJSON, err := encodeSpec(spec)
360 if err != nil {
361 return err
362 }
363 deadline, drain, stop := Deadlines(now, spec.MaxLifetime)
364 replaces := sql.NullString{String: q.Replaces, Valid: q.Replaces != ""}
365 if _, err := tx.ExecContext(ctx, `INSERT INTO jobs (attempt_id, launch_id, task_id, account_id, actor_key,
366 purpose, replaces_attempt, spec_json, spec_sha256, provider_fingerprint, state, launched_t, deadline_t, drain_t, stop_t)
367 VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
368 q.AttemptID, launchID, q.TaskID, q.Account, string(by), purposeTask, replaces, specJSON, hash,
369 c.cfg.ProviderFingerprint(spec.Image, spec.Size), JobWaiting, int64(now), int64(deadline), int64(drain), int64(stop)); err != nil {
370 return fmt.Errorf("hostedctl: save launch intent: %w", err)
371 }
372 a.Action = actionLaunchIntent
373 a.Reason = fmt.Sprintf("intent saved: launch %s, image %s, size %s, lifetime %v", launchID, spec.Image, spec.Size, spec.MaxLifetime)
374 if err := appendAudit(tx, a); err != nil {
375 return err
376 }
377 view = JobView{AttemptID: q.AttemptID, LaunchID: launchID, State: JobWaiting,
378 DeadlineIn: until(now, deadline), DrainIn: until(now, drain), StopIn: until(now, stop)}
379 created = true
380 return nil
381 })
382 if err != nil {
383 return JobView{}, false, err
384 }
385 if refusal != nil {
386 return JobView{}, false, refusal
387 }
388 return view, created, nil
389}
390
391// checkReplaces returns ErrReplacementLive unless attempt exists, was
392// launched by by and carries stop proof. An unknown attempt and another
393// key's attempt get the same message, so the refusal tells nobody whether
394// another key's attempt exists.
395func checkReplaces(ctx context.Context, tx *sql.Tx, by hostedwire.KeyID, attempt string) error {
396 r, found, err := loadJob(ctx, tx, attempt)
397 if err != nil {
398 return err
399 }
400 if !found || r.actor != string(by) {
401 return fmt.Errorf("%w: %s is not an attempt of this key", ErrReplacementLive, attempt)
402 }
403 if !r.stopProof.Valid {
404 return fmt.Errorf("%w: %s has no stop proof", ErrReplacementLive, attempt)
405 }
406 return nil
407}
408
409// dispatch sends attempt's saved spec to the provider if, read again just
410// now, it is still a waiting intent with no Ref and every creation gate
411// passes. Launch (actor by, replay false) and Replay (actor empty, replay
412// true) both create VMs only through it.
413//
414// In its own transaction it re-reads the row. An intent no longer waiting,
415// or holding a Ref, is returned as it stands. A stop asked for, or the stop
416// time reached, marks it JobAbandoned with an audit row; so does a provider
417// fingerprint other than the one saved with the intent (R29), which also
418// raises an AlertConfigChanged alert. Then, outside the
419// transaction and just before the call, it checks the transient gates
420// (creatable); a failure is returned as gate with the waiting view and no
421// provider call. Otherwise it records the dispatch marker (markDispatch,
422// R19), checks the stop time and the transient gates again once the marker
423// has committed, and only then calls the provider and settles the answer.
424func (c *Controller) dispatch(ctx context.Context, actor hostedwire.KeyID, attempt string, replay bool) (view JobView, gate, err error) {
425 // The attempt's lock (R18) is held from the gate check to the settled
426 // answer, so a Stop cannot land between them.
427 defer c.lockAttempt(attempt)()
428 // R23: the ownership lock, taken before the row is read and the gates
429 // are checked and held to the settled answer, so the orphan reaper's
430 // final check cannot run in between (ownershipLock, reaper.go), and a
431 // wait for it never lets a gate that passed go stale before the call.
432 defer c.ownership.rlock()()
433 var spec isolatedjob.LaunchSpec
434 var stopAt T // the intent's stop time; the attempt lock keeps it still
435 ready, changed := false, false
436 err = c.store.Tx(ctx, func(tx *sql.Tx) error {
437 ready, changed = false, false
438 j, found, err := loadJob(ctx, tx, attempt)
439 if err != nil {
440 return err
441 }
442 if !found {
443 return fmt.Errorf("hostedctl: launch intent %s is missing", attempt)
444 }
445 now := c.store.Clock().Now()
446 if j.state != JobWaiting || j.ref.Valid {
447 view = j.view(now)
448 return nil
449 }
450 if spec, err = decodeSpec(j.specJSON, attempt); err != nil {
451 return err
452 }
453 reason := abandonReason(j, now)
454 if fp := c.cfg.ProviderFingerprint(spec.Image, spec.Size); reason == "" && fp != j.fingerprint {
455 reason, changed = fmt.Sprintf("%s: the provider settings for image %s at size %s changed since the intent was saved (%q, now %q)",
456 reasonConfigChanged, spec.Image, spec.Size, j.fingerprint, fp), true
457 }
458 if reason != "" {
459 view, err = abandonIntent(ctx, tx, actor, j, replay, reason, now)
460 return err
461 }
462 view, stopAt = j.view(now), T(j.stopT)
463 ready = true
464 return nil
465 })
466 if err != nil {
467 return JobView{}, nil, err
468 }
469 if changed {
470 return view, nil, c.alertConfigChanged(ctx, attempt, view)
471 }
472 if !ready {
473 return view, nil, nil
474 }
475 if gate := c.creatable(spec.Image, c.store.Clock().Now()); gate != nil {
476 return view, gate, nil
477 }
478 if c.beforeMark != nil {
479 c.beforeMark()
480 }
481 if err := c.markDispatch(ctx, attempt); err != nil {
482 return JobView{}, nil, err
483 }
484 // The marker's transaction may have queued for the store while the stop
485 // time passed or the audit failed or went stale, so both are checked
486 // again once it commits, in memory, immediately before the call.
487 if now := c.store.Clock().Now(); now >= stopAt {
488 view, err = c.abandonDue(ctx, actor, attempt, replay)
489 return view, nil, err
490 } else if gate := c.creatable(spec.Image, now); gate != nil {
491 return view, gate, nil
492 }
493 // R21: c.runner bounds the call by ProviderLaunchTimeout, so no launch
494 // call this process makes can outlive the Ref-less proof fence
495 // (ReflessProofDelay) that starts at its dispatch.
496 ref, perr := c.runner.Launch(ctx, spec)
497 // Record the answer even if the caller has gone: a VM may now exist.
498 view, err = c.settle(context.WithoutCancel(ctx), actor, attempt, ref, perr, replay)
499 return view, nil, err
500}
501
502// providerError turns a provider launch error into a fixed error for
503// attempt. It keeps the isolatedjob sentinel the error matches, so
504// errors.Is still works, and drops the provider's own text, which might
505// echo the request and with it the instance code. An error matching none
506// becomes ErrProviderLaunch.
507func providerError(attempt string, err error) error {
508 for _, s := range []error{
509 isolatedjob.ErrThrottled, isolatedjob.ErrConflict, isolatedjob.ErrInvalid,
510 isolatedjob.ErrBootstrapTooLarge, isolatedjob.ErrNotFound, isolatedjob.ErrIncomplete,
511 context.Canceled, context.DeadlineExceeded,
512 } {
513 if errors.Is(err, s) {
514 return fmt.Errorf("hostedctl: launch %s: provider refused: %w", attempt, s)
515 }
516 }
517 return fmt.Errorf("hostedctl: launch %s: %w", attempt, ErrProviderLaunch)
518}
519
520// settle records what the provider said about a launch of attempt. actor is
521// the key that asked, or empty for Replay. A Ref is saved by transaction 2
522// (saveRef). A throttle is audited and returns the waiting view with a nil
523// error. Any other error is audited with a fixed reason and returned as
524// providerError gives it.
525func (c *Controller) settle(ctx context.Context, actor hostedwire.KeyID, attempt string, ref isolatedjob.Ref, perr error, replay bool) (JobView, error) {
526 if perr == nil && ref == "" {
527 perr = errors.New("provider returned no VM ref")
528 }
529 if perr == nil {
530 return c.saveRef(ctx, actor, attempt, ref, replay)
531 }
532 throttled := errors.Is(perr, isolatedjob.ErrThrottled)
533 fixed := providerError(attempt, perr)
534 action, reason := actionLaunchFailed, providerFailureReason
535 switch {
536 case throttled && replay:
537 action, reason = actionReplayThrottled, providerThrottleReason
538 case throttled:
539 action, reason = actionLaunchThrottled, providerThrottleReason
540 case replay:
541 action = actionReplayFailed
542 }
543 var view JobView
544 err := c.store.Tx(ctx, func(tx *sql.Tx) error {
545 now := c.store.Clock().Now()
546 j, found, err := loadJob(ctx, tx, attempt)
547 if err != nil {
548 return err
549 }
550 if !found {
551 return fmt.Errorf("hostedctl: launch intent %s is missing", attempt)
552 }
553 view = j.view(now)
554 return appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: attempt,
555 Action: action, Reason: reason, At: now})
556 })
557 if throttled && err == nil {
558 return view, nil
559 }
560 return JobView{}, errors.Join(fixed, err)
561}
562
563// saveRef is transaction 2: it saves ref for a waiting intent and moves it
564// to JobStarting. A ref already saved, by a concurrent call for the same
565// attempt, is left as it is. An intent abandoned while the call was in
566// flight keeps no ref: the VM is audited and left for the orphan reaper,
567// which finds no job owning it.
568func (c *Controller) saveRef(ctx context.Context, actor hostedwire.KeyID, attempt string, ref isolatedjob.Ref, replay bool) (JobView, error) {
569 var view JobView
570 err := c.store.Tx(ctx, func(tx *sql.Tx) error {
571 now := c.store.Clock().Now()
572 j, found, err := loadJob(ctx, tx, attempt)
573 if err != nil {
574 return err
575 }
576 if !found {
577 return fmt.Errorf("hostedctl: launch intent %s is missing", attempt)
578 }
579 a := Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: attempt, At: now}
580 switch {
581 case j.ref.Valid && j.ref.String == string(ref):
582 view = j.view(now)
583 return nil
584 case j.ref.Valid:
585 return fmt.Errorf("hostedctl: attempt %s: provider returned VM %s but the job holds %s", attempt, ref, j.ref.String)
586 case j.state == JobAbandoned:
587 a.Action = actionVMAfterAbandon
588 a.Reason = fmt.Sprintf("provider created VM %s after the intent was abandoned; left for the orphan reaper", ref)
589 view = j.view(now)
590 return appendAudit(tx, a)
591 case j.state != JobWaiting:
592 return fmt.Errorf("hostedctl: attempt %s is %s; VM %s not recorded", attempt, j.state, ref)
593 }
594 res, err := tx.ExecContext(ctx, `UPDATE jobs SET vm_ref = ?, state = ?, revision = revision + 1
595 WHERE attempt_id = ? AND vm_ref IS NULL AND state = ?`, string(ref), JobStarting, attempt, JobWaiting)
596 if err != nil {
597 return fmt.Errorf("hostedctl: save VM ref: %w", err)
598 }
599 if n, err := res.RowsAffected(); err != nil || n != 1 {
600 return fmt.Errorf("hostedctl: save VM ref for %s: %d rows (%v)", attempt, n, err)
601 }
602 a.Action, a.Reason = actionLaunchStarted, fmt.Sprintf("provider started VM %s", ref)
603 if replay {
604 a.Action = actionReplayStarted
605 }
606 if err := appendAudit(tx, a); err != nil {
607 return err
608 }
609 j.ref, j.state = sql.NullString{String: string(ref), Valid: true}, JobStarting
610 view = j.view(now)
611 return nil
612 })
613 if err != nil {
614 return JobView{}, err
615 }
616 return view, nil
617}
618
619// Replay launches every intent that has no Ref yet, in launch order, each
620// with its saved spec, through dispatch. Before each provider call the
621// gates are re-checked:
622//
623// - a stop asked for, the intent's stop time reached, or provider
624// settings changed since it was saved (config_changed, alerted): the
625// intent is marked JobAbandoned and audited, and never replayed again;
626// - launches switched off, the image no longer allowed, or no passing
627// audit begun within AuditMaxAge: the intent stays JobWaiting for a later
628// pass, with no audit row, as nothing changed.
629//
630// A gate that fails makes no provider call. A throttle leaves the intent
631// waiting and is not an error. Replay returns the other failures joined; one
632// intent's failure does not stop the others.
633func (c *Controller) Replay(ctx context.Context) error {
634 var pending []string
635 err := c.store.Tx(ctx, func(tx *sql.Tx) error {
636 pending = pending[:0]
637 rows, err := tx.QueryContext(ctx, `SELECT attempt_id FROM jobs WHERE state = ? AND vm_ref IS NULL
638 ORDER BY launched_t, attempt_id`, JobWaiting)
639 if err != nil {
640 return fmt.Errorf("hostedctl: list launch intents: %w", err)
641 }
642 defer rows.Close()
643 for rows.Next() {
644 var id string
645 if err := rows.Scan(&id); err != nil {
646 return fmt.Errorf("hostedctl: list launch intents: %w", err)
647 }
648 pending = append(pending, id)
649 }
650 return rows.Err()
651 })
652 if err != nil {
653 return err
654 }
655 var errs []error
656 for _, id := range pending {
657 if err := ctx.Err(); err != nil {
658 errs = append(errs, err)
659 break
660 }
661 if _, _, err := c.dispatch(ctx, "", id, true); err != nil {
662 errs = append(errs, err)
663 }
664 }
665 return errors.Join(errs...)
666}
667
668// abandonIntent marks waiting intent j JobAbandoned inside tx, with an audit
669// row giving reason, and returns its view. It is never launched again; a VM
670// a lost reply made for it is an orphan.
671func abandonIntent(ctx context.Context, tx *sql.Tx, actor hostedwire.KeyID, j jobRow, replay bool, reason string, now T) (JobView, error) {
672 res, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, revision = revision + 1
673 WHERE attempt_id = ? AND state = ? AND vm_ref IS NULL`, JobAbandoned, j.attempt, JobWaiting)
674 if err != nil {
675 return JobView{}, fmt.Errorf("hostedctl: abandon %s: %w", j.attempt, err)
676 }
677 if n, err := res.RowsAffected(); err != nil || n != 1 {
678 return JobView{}, fmt.Errorf("hostedctl: abandon %s: %d rows (%v)", j.attempt, n, err)
679 }
680 action := actionLaunchAbandoned
681 if replay {
682 action = actionReplayAbandoned
683 }
684 j.state = JobAbandoned
685 return j.view(now), appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: j.attempt,
686 Action: action, Reason: reason, At: now})
687}
688
689// abandonDue abandons attempt's waiting intent, in a transaction of its own,
690// once dispatch finds its stop time come after the dispatch marker. An
691// intent no longer waiting is returned as it stands.
692func (c *Controller) abandonDue(ctx context.Context, actor hostedwire.KeyID, attempt string, replay bool) (JobView, error) {
693 var view JobView
694 err := c.store.Tx(ctx, func(tx *sql.Tx) error {
695 j, found, err := loadJob(ctx, tx, attempt)
696 if err != nil {
697 return err
698 }
699 if !found {
700 return fmt.Errorf("hostedctl: launch intent %s is missing", attempt)
701 }
702 now := c.store.Clock().Now()
703 reason := abandonReason(j, now)
704 if j.state != JobWaiting || j.ref.Valid || reason == "" {
705 view = j.view(now)
706 return nil
707 }
708 view, err = abandonIntent(ctx, tx, actor, j, replay, reason+"; found after the dispatch was recorded", now)
709 return err
710 })
711 if err != nil {
712 return JobView{}, err
713 }
714 return view, nil
715}
716
717// alertConfigChanged sends the AlertConfigChanged alert for an intent
718// abandoned because the provider settings changed, even if the caller has
719// gone. The abandonment is already committed and audited.
720func (c *Controller) alertConfigChanged(ctx context.Context, attempt string, v JobView) error {
721 err := c.alerter.Alert(context.WithoutCancel(ctx), Alert{Kind: AlertConfigChanged, At: c.store.Clock().Now(), Detail: fmt.Sprintf(
722 "launch intent %s (launch %s) was abandoned: the provider settings changed since it was saved; a VM its lost reply made is reaped as an orphan",
723 attempt, v.LaunchID)})
724 if err != nil {
725 return fmt.Errorf("hostedctl: deliver %s alert for %s: %w", AlertConfigChanged, attempt, err)
726 }
727 return nil
728}
729
730// abandonReason returns why a waiting intent must never be launched, or ""
731// when nothing stops it: a stop was asked for, or its stop time has come.
732func abandonReason(j jobRow, now T) string {
733 if j.stopRequested.Valid {
734 return "stop asked for before the VM was launched"
735 }
736 if now >= T(j.stopT) {
737 return fmt.Sprintf("stop time passed before the VM was launched (%v after it)", time.Duration(now-T(j.stopT)))
738 }
739 return ""
740}
741
742// creatable checks the transient creation gates: launches on, the image
743// still allowed, and a passing audit begun within AuditMaxAge.
744func (c *Controller) creatable(img isolatedjob.ImageDigest, now T) error {
745 if !c.cfg.Enabled {
746 return ErrDisabled
747 }
748 if !c.cfg.Images[img] {
749 return fmt.Errorf("%w: %s", ErrImageNotAllowed, img)
750 }
751 return c.audit.check(now)
752}
753
754// jobRow is the part of a jobs row that launches read.
755type jobRow struct {
756 attempt, launchID, task, account, actor, state, specJSON, specSHA string
757 fingerprint string // provider_fingerprint
758 ref sql.NullString
759 launchedT, deadlineT, drainT, stopT, epoch int64
760 stopRequested sql.NullInt64
761 stopProof sql.NullString
762}
763
764// loadJob reads attempt's row inside tx. found is false when there is none.
765func loadJob(ctx context.Context, tx *sql.Tx, attempt string) (jobRow, bool, error) {
766 var j jobRow
767 err := tx.QueryRowContext(ctx, `SELECT attempt_id, launch_id, task_id, account_id, actor_key, state,
768 spec_json, spec_sha256, provider_fingerprint, vm_ref, launched_t, deadline_t, drain_t, stop_t, epoch, stop_requested_t,
769 stop_proof_json FROM jobs WHERE attempt_id = ?`, attempt).Scan(&j.attempt, &j.launchID, &j.task, &j.account, &j.actor,
770 &j.state, &j.specJSON, &j.specSHA, &j.fingerprint, &j.ref, &j.launchedT, &j.deadlineT, &j.drainT, &j.stopT, &j.epoch,
771 &j.stopRequested, &j.stopProof)
772 switch {
773 case errors.Is(err, sql.ErrNoRows):
774 return jobRow{}, false, nil
775 case err != nil:
776 return jobRow{}, false, fmt.Errorf("hostedctl: read job %s: %w", attempt, err)
777 }
778 return j, true, nil
779}
780
781// view is the JobView of j at controller time now.
782func (j jobRow) view(now T) JobView {
783 return JobView{
784 AttemptID: j.attempt, LaunchID: j.launchID, State: j.state,
785 VMRef: isolatedjob.Ref(j.ref.String), Epoch: j.epoch,
786 DeadlineIn: until(now, T(j.deadlineT)), DrainIn: until(now, T(j.drainT)), StopIn: until(now, T(j.stopT)),
787 }
788}
789
790// until is how long from now to at, or zero once at has passed.
791func until(now, at T) time.Duration {
792 if at <= now {
793 return 0
794 }
795 return time.Duration(at - now)
796}
797