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 "database/sql"
6 "encoding/json"
7 "errors"
8 "fmt"
9 "time"
10
11 "amadan.net/oficina/equipo/internal/hostedwire"
12 "amadan.net/oficina/equipo/internal/isolatedjob"
13)
14
15var (
16 // ErrStopPending: the stop is recorded but the VM is not proven stopped
17 // yet: it is still live, the provider has answered not-found only once
18 // (NotFoundConfirm), or the job has no VM Ref and the provider has not
19 // yet been seen to hold no VM for it. Ask again later.
20 ErrStopPending = errors.New("hostedctl: stop asked for; the VM is not proven stopped yet")
21 // ErrStateUnknown: the provider reported a state this package does not
22 // know. It is never proof that the VM has stopped.
23 ErrStateUnknown = errors.New("hostedctl: the provider reports an unknown VM state; no stop proof")
24)
25
26// NotFoundConfirm is how far apart, in controller time, two not-found
27// answers from Runner.Get must be before they prove a VM gone. The
28// provider's Get is eventually consistent, so one not-found proves nothing
29// (ruling R17). It equals the reaper's interval (Task 13's ReapInterval).
30const NotFoundConfirm = 60 * time.Second
31
32// Stop reasons the controller writes itself.
33const (
34 // reasonElapsedUnknown: after a restart the provider gave no age for the
35 // VM, so how long it has lived is unknown and the controller stops it.
36 reasonElapsedUnknown = "elapsed_unknown"
37 // reasonEnded: the VM ended, or the provider forgot it, with no stop
38 // asked for.
39 reasonEnded = "ended"
40)
41
42// Audit actions written by Get, Stop and Refresh.
43const (
44 actionGetRefused = "get_refused"
45 actionStopRefused = "stop_refused"
46 actionStopRequested = "stop_requested"
47 actionStopRepeated = "stop_repeated"
48 actionStopFailed = "stop_failed"
49 actionStopStateUnknown = "stop_state_unknown"
50 actionStopProven = "stop_proven"
51 actionVMNotFound = "vm_not_found"
52 actionRestartRebased = "restart_rebased"
53)
54
55// StopProof says the provider reported the job's VM terminal, or answered
56// not-found twice, NotFoundConfirm apart, with the first after the stop
57// request (or, with no request, after the VM was last seen live). It gates
58// replacement attempts.
59// VMRef is empty for a job that never had a Ref, and State is then
60// isolatedjob.StateStopped. ObservedAt is controller time.
61type StopProof struct {
62 AttemptID string
63 VMRef isolatedjob.Ref
64 State isolatedjob.State
65 ObservedAt T
66}
67
68func (p StopProof) wire() hostedwire.StopProof {
69 return hostedwire.StopProof{AttemptID: p.AttemptID, VMRef: p.VMRef, State: p.State, ObservedAt: time.Duration(p.ObservedAt)}
70}
71
72// decodeProof reads a stored jobs.stop_proof_json and checks it is for attempt.
73func decodeProof(text, attempt string) (StopProof, error) {
74 var w hostedwire.StopProof
75 if err := json.Unmarshal([]byte(text), &w); err != nil {
76 return StopProof{}, fmt.Errorf("hostedctl: stored stop proof for %s is unreadable: %w", attempt, err)
77 }
78 if w.AttemptID != attempt {
79 return StopProof{}, fmt.Errorf("hostedctl: stored stop proof for %s names attempt %s", attempt, w.AttemptID)
80 }
81 return StopProof{AttemptID: w.AttemptID, VMRef: w.VMRef, State: w.State, ObservedAt: T(w.ObservedAt)}, nil
82}
83
84// notCreator is the refusal for a key that did not launch attempt. An
85// unknown attempt gets the same text, so a refusal never tells a key whether
86// another key's attempt exists.
87func notCreator(attempt string) error {
88 return fmt.Errorf("%w: %s is not an attempt of this key", ErrForbidden, attempt)
89}
90
91// Get returns attempt's job as the store holds it. Only the instance key
92// that launched it may read it; anyone else, and any unknown attempt, gets
93// ErrForbidden and an audit row. Get makes no provider call.
94func (c *Controller) Get(ctx context.Context, by hostedwire.KeyID, attemptID string) (JobView, error) {
95 var view JobView
96 var refusal error
97 err := c.store.Tx(ctx, func(tx *sql.Tx) error {
98 view, refusal = JobView{}, nil
99 now := c.store.Clock().Now()
100 a := Audit{Actor: by, Action: actionGetRefused, At: now}
101 if !printableASCII(attemptID, maxNameLen) {
102 refusal = fmt.Errorf("%w: attempt id must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen)
103 a.Reason = refusal.Error()
104 return appendAudit(tx, a)
105 }
106 a.Attempt = attemptID
107 j, found, err := loadJob(ctx, tx, attemptID)
108 if err != nil {
109 return err
110 }
111 if by == "" || !found || j.actor != string(by) {
112 refusal = notCreator(attemptID)
113 if found {
114 a.Account, a.Task = j.account, j.task
115 }
116 a.Reason = refusal.Error()
117 return appendAudit(tx, a)
118 }
119 view = j.view(now)
120 return nil
121 })
122 if err != nil {
123 return JobView{}, err
124 }
125 if refusal != nil {
126 return JobView{}, refusal
127 }
128 return view, nil
129}
130
131// Stop asks for attempt's VM to stop and returns proof once it has.
132//
133// Everything after the refusals runs under the attempt's lock (R18), so a
134// Stop waits for a launch dispatch in flight to settle.
135//
136// Only an instance key (RoleInstance) that launched attempt may stop it;
137// anyone else, an unknown attempt, or a malformed attempt ID or reason
138// (1 to 128 printable ASCII characters) gets an error and an audit row and
139// changes nothing. The controller's own stops do not come through here.
140//
141// In order: one transaction records stop_requested_t and stop_reason, unless
142// a stop was already asked for (the first reason is kept), and audits it. A
143// job that already holds proof returns it with no provider call. A job with
144// no VM Ref yet is marked JobAbandoned, so Replay never launches it, and
145// gets ErrStopPending: a lost launch reply may have made a VM the table does
146// not link, so Refresh issues its proof only once a complete List shows no
147// such VM. Otherwise, outside any transaction, Runner.Stop and then
148// Runner.Get:
149//
150// - a terminal state is proof: it is saved with state JobStopped in one
151// transaction and returned;
152// - isolatedjob.ErrNotFound from Get is proof only when an earlier
153// not-found, recorded after the stop request, is at least
154// NotFoundConfirm older than this Get; otherwise the first one is
155// recorded in notfound_since_t and the result is ErrStopPending;
156// - a live state (stopping included) gives ErrStopPending;
157// - an unknown state gives ErrStateUnknown;
158// - an error from Runner.Stop (a lost reply, a throttle) is returned. The
159// provider's Stop is idempotent, so the next Stop, or the next Refresh,
160// sends it again.
161//
162// stop_t is never changed.
163func (c *Controller) Stop(ctx context.Context, by hostedwire.KeyID, key hostedwire.VerifyKey, attemptID, reason string) (StopProof, error) {
164 switch {
165 case by == "" || key.Role != hostedwire.RoleInstance:
166 return StopProof{}, c.refuseStop(ctx, by, attemptID, fmt.Errorf("%w: stop needs the instance key that launched the attempt", ErrForbidden))
167 case !printableASCII(attemptID, maxNameLen):
168 return StopProof{}, c.refuseStop(ctx, by, "", fmt.Errorf("%w: attempt id must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen))
169 case !printableASCII(reason, maxNameLen):
170 return StopProof{}, c.refuseStop(ctx, by, attemptID, fmt.Errorf("%w: stop reason must be 1 to %d printable ASCII characters", isolatedjob.ErrInvalid, maxNameLen))
171 }
172 defer c.lockAttempt(attemptID)()
173 r, err := c.requestStop(ctx, by, attemptID, reason, true)
174 if err != nil {
175 return StopProof{}, err
176 }
177 if r.proof != nil {
178 return *r.proof, nil
179 }
180 if r.ref == "" {
181 return StopProof{}, fmt.Errorf("%w: %s has no VM ref yet; proof waits for a complete list showing no unlinked VM", ErrStopPending, attemptID)
182 }
183 return c.driveStop(ctx, by, r)
184}
185
186// refuseStop audits a refusal that came before any job was read, in a short
187// transaction of its own, and returns err.
188func (c *Controller) refuseStop(ctx context.Context, by hostedwire.KeyID, attempt string, err error) error {
189 aerr := c.store.Tx(ctx, func(tx *sql.Tx) error {
190 return appendAudit(tx, Audit{Actor: by, Attempt: attempt, Action: actionStopRefused,
191 Reason: err.Error(), At: c.store.Clock().Now()})
192 })
193 return errors.Join(err, aerr)
194}
195
196// stopReq is what requestStop read and recorded.
197type stopReq struct {
198 attempt, account, task string
199 ref isolatedjob.Ref // empty when the job has no VM Ref
200 reason string // the stored reason, sent to the provider
201 proof *StopProof // the stored proof, when there is one
202}
203
204// requestStop is Stop's first transaction, shared with the controller's own
205// stops (actor empty, creatorOnly false). It records the stop request and,
206// for a job with no Ref still waiting, abandons the intent.
207func (c *Controller) requestStop(ctx context.Context, actor hostedwire.KeyID, attempt, reason string, creatorOnly bool) (stopReq, error) {
208 var r stopReq
209 var refusal error
210 err := c.store.Tx(ctx, func(tx *sql.Tx) error {
211 r, refusal = stopReq{}, nil
212 now := c.store.Clock().Now()
213 j, found, err := loadJob(ctx, tx, attempt)
214 if err != nil {
215 return err
216 }
217 a := Audit{Actor: actor, Attempt: attempt, At: now}
218 if found {
219 a.Account, a.Task = j.account, j.task
220 }
221 switch {
222 case !found && !creatorOnly:
223 return fmt.Errorf("hostedctl: stop %s: job is missing", attempt)
224 case !found || (creatorOnly && j.actor != string(actor)):
225 refusal = notCreator(attempt)
226 a.Action, a.Reason = actionStopRefused, refusal.Error()
227 return appendAudit(tx, a)
228 }
229 r = stopReq{attempt: attempt, account: j.account, task: j.task, ref: isolatedjob.Ref(j.ref.String)}
230 if j.stopProof.Valid {
231 p, err := decodeProof(j.stopProof.String, attempt)
232 r.proof = &p
233 return err
234 }
235 var stored sql.NullString
236 if err := tx.QueryRowContext(ctx, `SELECT stop_reason FROM jobs WHERE attempt_id = ?`, attempt).Scan(&stored); err != nil {
237 return fmt.Errorf("hostedctl: read stop reason of %s: %w", attempt, err)
238 }
239 state := j.state
240 if !j.ref.Valid && state == JobWaiting {
241 state = JobAbandoned
242 }
243 r.reason = reason
244 if stored.Valid {
245 r.reason = stored.String
246 }
247 if j.stopRequested.Valid && state == j.state {
248 a.Action, a.Reason = actionStopRepeated, "stop asked for again: "+reason
249 return appendAudit(tx, a)
250 }
251 res, err := tx.ExecContext(ctx, `UPDATE jobs SET stop_requested_t = coalesce(stop_requested_t, ?),
252 stop_reason = coalesce(stop_reason, ?), state = ?, revision = revision + 1
253 WHERE attempt_id = ? AND stop_proof_json IS NULL`, int64(now), reason, state, attempt)
254 if err != nil {
255 return fmt.Errorf("hostedctl: record stop request for %s: %w", attempt, err)
256 }
257 if n, err := res.RowsAffected(); err != nil || n != 1 {
258 return fmt.Errorf("hostedctl: record stop request for %s: %d rows (%v)", attempt, n, err)
259 }
260 a.Action, a.Reason = actionStopRequested, "stop asked for: "+reason
261 if state == JobAbandoned && j.state != JobAbandoned {
262 a.Reason += "; intent abandoned before any VM ref was saved"
263 }
264 return appendAudit(tx, a)
265 })
266 if err != nil {
267 return stopReq{}, err
268 }
269 if refusal != nil {
270 return stopReq{}, refusal
271 }
272 return r, nil
273}
274
275// driveStop sends the provider stop for a recorded request and then reads
276// the VM, outside any transaction. A failed stop call is audited, with a
277// fixed reason, and returned.
278func (c *Controller) driveStop(ctx context.Context, actor hostedwire.KeyID, r stopReq) (StopProof, error) {
279 if perr := c.runner.Stop(ctx, r.ref, r.reason); perr != nil && !errors.Is(perr, isolatedjob.ErrNotFound) {
280 aerr := c.auditStop(context.WithoutCancel(ctx), actor, r, actionStopFailed,
281 "provider stop call failed; it is sent again on the next stop or refresh")
282 return StopProof{}, errors.Join(fmt.Errorf("hostedctl: stop %s: %w", r.attempt, perr), aerr)
283 }
284 before := c.store.Clock().Now()
285 job, gerr := c.runner.Get(ctx, r.ref)
286 at := c.store.Clock().Now()
287 // Record what the provider said even if the caller has gone.
288 rec := context.WithoutCancel(ctx)
289 switch {
290 case errors.Is(gerr, isolatedjob.ErrNotFound):
291 p, proven, err := c.notFound(rec, actor, r.attempt, r.ref, before, at, "provider holds no such VM after the stop request")
292 if err != nil || proven {
293 return p, err
294 }
295 return StopProof{}, fmt.Errorf("%w: VM %s not found once; proof needs a second not-found %v later", ErrStopPending, r.ref, NotFoundConfirm)
296 case gerr != nil:
297 return StopProof{}, fmt.Errorf("hostedctl: read VM %s of %s after stop: %w", r.ref, r.attempt, gerr)
298 case job.State.Terminal():
299 return c.recordProof(rec, actor, r.attempt, StopProof{AttemptID: r.attempt, VMRef: r.ref,
300 State: job.State, ObservedAt: at}, "provider reports the VM "+string(job.State))
301 case job.State.Live():
302 if err := c.mirrorState(rec, r.attempt, job.State); err != nil {
303 return StopProof{}, err
304 }
305 return StopProof{}, fmt.Errorf("%w: VM %s is %s", ErrStopPending, r.ref, job.State)
306 }
307 aerr := c.auditStop(rec, actor, r, actionStopStateUnknown, "provider state unknown; no proof")
308 return StopProof{}, errors.Join(fmt.Errorf("%w: VM %s of %s", ErrStateUnknown, r.ref, r.attempt), aerr)
309}
310
311// auditStop writes one audit row about r in a short transaction.
312func (c *Controller) auditStop(ctx context.Context, actor hostedwire.KeyID, r stopReq, action, reason string) error {
313 return c.store.Tx(ctx, func(tx *sql.Tx) error {
314 return appendAudit(tx, Audit{Actor: actor, Account: r.account, Task: r.task, Attempt: r.attempt,
315 Action: action, Reason: reason, At: c.store.Clock().Now()})
316 })
317}
318
319// notFound handles a not-found answer from Runner.Get for attempt's VM ref,
320// read between controller times before and at. The answer is proof only
321// when notfound_since_t holds an earlier not-found that came after the stop
322// request (if any) and after this process's Open (R19), and is at least
323// NotFoundConfirm before this Get began;
324// any live Get in between has cleared it (mirrorState). Otherwise, when no
325// such first not-found is held, at is recorded as the first one. proven
326// reports whether p is proof; a job that already holds proof returns it.
327func (c *Controller) notFound(ctx context.Context, actor hostedwire.KeyID, attempt string, ref isolatedjob.Ref, before, at T, why string) (StopProof, bool, error) {
328 var out StopProof
329 proven := false
330 err := c.store.Tx(ctx, func(tx *sql.Tx) error {
331 out, proven = StopProof{}, false
332 j, found, err := loadJob(ctx, tx, attempt)
333 if err != nil {
334 return err
335 }
336 switch {
337 case !found:
338 return fmt.Errorf("hostedctl: not-found for %s: job is missing", attempt)
339 case j.stopProof.Valid:
340 out, err = decodeProof(j.stopProof.String, attempt)
341 proven = err == nil
342 return err
343 case !j.ref.Valid || isolatedjob.Ref(j.ref.String) != ref:
344 return fmt.Errorf("hostedctl: not-found for %s names VM %s, the job holds %q", attempt, ref, j.ref.String)
345 }
346 var since sql.NullInt64
347 if err := tx.QueryRowContext(ctx, `SELECT notfound_since_t FROM jobs WHERE attempt_id = ?`, attempt).Scan(&since); err != nil {
348 return fmt.Errorf("hostedctl: read notfound_since_t of %s: %w", attempt, err)
349 }
350 // The first not-found must follow the stop request, if any, and this
351 // process's Open: the time across a restart is untrusted (R19).
352 first := since.Valid && (!j.stopRequested.Valid || since.Int64 >= j.stopRequested.Int64) &&
353 (!c.store.Restarted() || T(since.Int64) > c.store.OpenedAt())
354 if first && before-T(since.Int64) >= T(NotFoundConfirm) {
355 out, proven = StopProof{AttemptID: attempt, VMRef: ref, State: isolatedjob.StateStopped, ObservedAt: at}, true
356 return writeProof(ctx, tx, actor, j, out, fmt.Sprintf("%s; not found twice, %v apart",
357 why, time.Duration(before-T(since.Int64))))
358 }
359 if first {
360 return nil // waiting for the confirming not-found
361 }
362 res, err := tx.ExecContext(ctx, `UPDATE jobs SET notfound_since_t = ?, revision = revision + 1
363 WHERE attempt_id = ? AND stop_proof_json IS NULL`, int64(at), attempt)
364 if err != nil {
365 return fmt.Errorf("hostedctl: record not-found for %s: %w", attempt, err)
366 }
367 if n, err := res.RowsAffected(); err != nil || n != 1 {
368 return fmt.Errorf("hostedctl: record not-found for %s: %d rows (%v)", attempt, n, err)
369 }
370 return appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: attempt, Action: actionVMNotFound,
371 Reason: fmt.Sprintf("%s; proof waits for a second not-found %v later", why, NotFoundConfirm), At: at})
372 })
373 if err != nil {
374 return StopProof{}, false, err
375 }
376 return out, proven, nil
377}
378
379// recordProof saves p for a job with a VM Ref in one transaction, with the
380// job's state set to JobStopped, and returns it. A job that already holds
381// proof keeps it and returns that one. A job with no stop request ended on
382// its own: its stop_reason becomes reasonEnded, so replacements may go
383// ahead.
384func (c *Controller) recordProof(ctx context.Context, actor hostedwire.KeyID, attempt string, p StopProof, why string) (StopProof, error) {
385 out := p
386 err := c.store.Tx(ctx, func(tx *sql.Tx) error {
387 out = p
388 j, found, err := loadJob(ctx, tx, attempt)
389 if err != nil {
390 return err
391 }
392 switch {
393 case !found:
394 return fmt.Errorf("hostedctl: stop proof for %s: job is missing", attempt)
395 case j.stopProof.Valid:
396 out, err = decodeProof(j.stopProof.String, attempt)
397 return err
398 case !j.ref.Valid || isolatedjob.Ref(j.ref.String) != p.VMRef:
399 return fmt.Errorf("hostedctl: stop proof for %s names VM %s, the job holds %q", attempt, p.VMRef, j.ref.String)
400 }
401 return writeProof(ctx, tx, actor, j, p, why)
402 })
403 if err != nil {
404 return StopProof{}, err
405 }
406 return out, nil
407}
408
409// writeProof saves p on j's row inside tx and audits it. j holds no proof.
410func writeProof(ctx context.Context, tx *sql.Tx, actor hostedwire.KeyID, j jobRow, p StopProof, why string) error {
411 text, err := json.Marshal(p.wire())
412 if err != nil {
413 return fmt.Errorf("hostedctl: encode stop proof: %w", err)
414 }
415 ended := !j.stopRequested.Valid
416 res, err := tx.ExecContext(ctx, `UPDATE jobs SET stop_proof_json = ?, state = ?,
417 stop_reason = CASE WHEN ? THEN coalesce(stop_reason, ?) ELSE stop_reason END, revision = revision + 1
418 WHERE attempt_id = ? AND stop_proof_json IS NULL`, string(text), JobStopped, ended, reasonEnded, j.attempt)
419 if err != nil {
420 return fmt.Errorf("hostedctl: save stop proof for %s: %w", j.attempt, err)
421 }
422 if n, err := res.RowsAffected(); err != nil || n != 1 {
423 return fmt.Errorf("hostedctl: save stop proof for %s: %d rows (%v)", j.attempt, n, err)
424 }
425 if ended {
426 why += "; no stop was asked for, so it ended on its own"
427 }
428 if err := appendAudit(tx, Audit{Actor: actor, Account: j.account, Task: j.task, Attempt: j.attempt,
429 Action: actionStopProven, Reason: why, At: p.ObservedAt}); err != nil {
430 return err
431 }
432 // A resume still pending now never commits: fail it with the proof.
433 return failPendingResume(ctx, tx, j.account, j.task, j.attempt, p.ObservedAt, "stop proven before the pending resume committed")
434}
435
436// mirrorState saves a live VM state the provider reported as the job's
437// state, unless the job holds proof. A live VM was seen, so any first
438// not-found held in notfound_since_t no longer counts and is cleared.
439func (c *Controller) mirrorState(ctx context.Context, attempt string, st isolatedjob.State) error {
440 return c.store.Tx(ctx, func(tx *sql.Tx) error {
441 _, err := tx.ExecContext(ctx, `UPDATE jobs SET state = ?, notfound_since_t = NULL, revision = revision + 1
442 WHERE attempt_id = ? AND vm_ref IS NOT NULL AND stop_proof_json IS NULL
443 AND (state <> ? OR notfound_since_t IS NOT NULL)`,
444 string(st), attempt, string(st))
445 if err != nil {
446 return fmt.Errorf("hostedctl: save state of %s: %w", attempt, err)
447 }
448 return nil
449 })
450}
451