package hostops import ( "bytes" "context" "encoding/json" "errors" "os" "reflect" "time" "github.com/carlosframework/platform/internal/hostclaim" "github.com/carlosframework/platform/internal/release" ) // PurgeRequestKey is the box-written automatic purge request. The console // consumes it only through DiscardPurgeRequest or RemovePurgeJournal. func PurgeRequestKey(account, app string) (string, error) { if _, err := AdmissionKey(account, app); err != nil { return "", err } return "apps/" + account + "/" + app + "/purge-request.json", nil } func validNewJournal(j PurgeJournal) error { if j.V != 1 || j.ID == "" || j.AppID == "" || j.Phase != "reserved" || j.Hosts == nil { return ErrIdentity } if j.Tombstone.Key != release.AppTombstoneKey(j.Account, j.App) || j.Tombstone.ETag == "" || !json.Valid(j.Tombstone.Body) { return ErrIdentity } return nil } // ReservePurge registers the purge reservation, then writes the journal // create-only. The journal is the durable intent BeginPurge transfers to the // exclusive operation; losing that CAS leaves only an admitted reservation // with no teardown authority. func (w *ControlWriter) ReservePurge(ctx context.Context, j PurgeJournal, owner RegistrationOwner, now time.Time) (string, error) { if err := w.ready(); err != nil { return "", err } if !validRegistrationOwner(owner) { return "", ErrIdentity } key, err := PurgeKey(j.Account, j.App) if err != nil { return "", err } a, err := w.read(ctx, j.Account, j.App, j.AppID) if err != nil { return "", err } if j.AdmissionEpoch == 0 { j.AdmissionEpoch = a.Value.Epoch } if err = validNewJournal(j); err != nil || j.AdmissionEpoch != a.Value.Epoch { return "", ErrIdentity } if existing, tag, gerr := w.raw.Get(ctx, key); gerr == nil { var seen struct { ID string `json:"id"` AppID string `json:"app_id"` } if json.Unmarshal(existing, &seen) == nil && seen.ID == j.ID && seen.AppID == j.AppID && tag != "" { return tag, nil } // Another purge's journal (or a malformed one) holds the name. return "", ErrPending } else if !errors.Is(gerr, os.ErrNotExist) { return "", gerr } body, tag, err := w.raw.Get(ctx, j.Tombstone.Key) if err != nil { return "", err } if tag != j.Tombstone.ETag || !bytes.Equal(body, j.Tombstone.Body) { return "", ErrPending } if a.Value.State != "open" || a.Value.Op != nil { return "", ErrPending } if _, ok := a.Value.Registrations[j.ID]; !ok { reg := Registration{Kind: registrationPurge, Owner: owner, AppID: j.AppID, Epoch: a.Value.Epoch} if a, err = w.updateAdmission(ctx, a, func(v *AppAdmission) error { return registerStart(v, j.ID, reg, now) }); err != nil { return "", err } } reg := a.Value.Registrations[j.ID] if reg.Kind != registrationPurge || reg.Owner != owner || !RegistrationLive(reg, now) { return "", ErrPending } raw, err := json.Marshal(j) if err != nil { return "", err } return w.raw.Put(ctx, key, raw, "") } // BeginPurge transfers the reserved journal into the exclusive purging // operation, removing its own reservation registration in the same CAS. // Replays return a handle for the existing operation. func (w *ControlWriter) BeginPurge(ctx context.Context, account, app, appID, id string, owner RegistrationOwner) (*OperationHandle, error) { if !validRegistrationOwner(owner) { return nil, ErrIdentity } j, _, err := ReadPurgeJournal(ctx, w.raw, account, app, id, appID) if err != nil { return nil, err } a, err := w.read(ctx, account, app, appID) if err != nil { return nil, err } if op := a.Value.Op; op != nil { if a.Value.State == "closed" && op.ID == id && op.Kind == OpPurging { return &OperationHandle{w: w, account: account, app: app, appID: appID, id: id, kind: OpPurging, owner: owner}, nil } return nil, ErrPending } if j.Phase != "reserved" || j.AdmissionEpoch != a.Value.Epoch { return nil, ErrPending } if _, err = w.updateAdmission(ctx, a, func(v *AppAdmission) error { op := AppOperation{ID: id, Kind: OpPurging, AppID: appID, Phase: "draining", Intent: map[string]string{"account": account, "app": app}} if err := exclusiveAdmission(v, op); err != nil { return err } if r, ok := v.Registrations[id]; ok && r.Kind == registrationPurge { delete(v.Registrations, id) } return nil }); err != nil { return nil, err } return &OperationHandle{w: w, account: account, app: app, appID: appID, id: id, kind: OpPurging, owner: owner}, nil } // SavePurgeJournal is a validated replacement, not a generic write: // identity is immutable, the phase never moves backwards, cleanup flags only // set, host entries are never removed, and the journal's own purging // operation must still own admission. func (w *ControlWriter) SavePurgeJournal(ctx context.Context, next PurgeJournal, tag string) (string, error) { if err := w.ready(); err != nil { return "", err } if tag == "" { return "", ErrIdentity } key, err := PurgeKey(next.Account, next.App) if err != nil { return "", err } cur, curTag, err := ReadPurgeJournal(ctx, w.raw, next.Account, next.App, next.ID, next.AppID) if err != nil { return "", err } if curTag != tag { return "", release.ErrCASConflict } if next.V != cur.V || next.RequestedBy != cur.RequestedBy || next.RequestedAt != cur.RequestedAt || next.Reason != cur.Reason || !reflect.DeepEqual(next.Tombstone, cur.Tombstone) || next.AdmissionEpoch != cur.AdmissionEpoch { return "", ErrIdentity } if phaseIndex(next.Phase) < phaseIndex(cur.Phase) { return "", ErrIdentity } for id, reg := range next.IngestRegistrations { if !validIngestRegistration(id, reg, next.AppID, next.AdmissionEpoch) { return "", ErrIdentity } } for id, reg := range cur.IngestRegistrations { if next.IngestRegistrations[id] != reg { return "", ErrIdentity } } for host := range cur.Hosts { if _, ok := next.Hosts[host]; !ok { return "", ErrIdentity } } c, n := cur.Cleanup, next.Cleanup if (c.Tombstone && !n.Tombstone) || (c.AppRow && !n.AppRow) || (c.Fences && !n.Fences) || (c.Admission && !n.Admission) || (c.Sweep.Verified && !n.Sweep.Verified) || n.Sweep.Batch < c.Sweep.Batch { return "", ErrIdentity } a, err := w.read(ctx, next.Account, next.App, next.AppID) if err != nil { return "", err } if a.Value.State != "closed" || a.Value.Op == nil || a.Value.Op.ID != next.ID || a.Value.Op.Kind != OpPurging { return "", ErrPending } body, err := json.Marshal(next) if err != nil { return "", err } MarkAppMutationIssued(ctx) return w.raw.Put(ctx, key, body, tag) } // DrainPurgeRegistrations journals each saved registration into the purge // journal, fences or witnesses its host, and only then removes it. func (w *ControlWriter) DrainPurgeRegistrations(ctx context.Context, account, app, appID, id string, now time.Time, recoverCreate func(context.Context, string) error) error { a, err := w.read(ctx, account, app, appID) if err != nil { return err } if a.Value.State != "closed" || a.Value.Op == nil || a.Value.Op.ID != id || a.Value.Op.Kind != OpPurging { return ErrPending } for regID, registration := range a.Value.Registrations { if registration.Kind == RegistrationIngest { j, tag, err := ReadPurgeJournal(ctx, w.raw, account, app, id, appID) if err != nil { return err } if j.Phase != "reserved" { return ErrPending } if j.IngestRegistrations == nil { j.IngestRegistrations = map[string]Registration{} } if old, ok := j.IngestRegistrations[regID]; ok && old != registration { return ErrIdentity } j.IngestRegistrations[regID] = registration if _, err = w.SavePurgeJournal(ctx, j, tag); err != nil { return err } out, _, err := w.judgeRegistration(ctx, &a.Value, account, app, regID, registration, now, nil) if err != nil { return err } if out != drainRemove { return ErrPending } } else if registration.Kind == registrationPurge { // A different purge's reservation: drained once it lapses. if !RegistrationDrained(registration, now) { return ErrPending } } else { j, tag, err := ReadPurgeJournal(ctx, w.raw, account, app, id, appID) if err != nil { return err } if j.Phase != "reserved" { return ErrPending } h := j.Hosts[registration.Host] if h.Registrations == nil { h.Registrations = map[string]json.RawMessage{} } body, err := json.Marshal(registration) if err != nil { return err } h.Registrations[regID] = body j.Hosts[registration.Host] = h if _, err = w.SavePurgeJournal(ctx, j, tag); err != nil { return err } obs, err := hostclaim.Read(ctx, w.raw, registration.Host) if err != nil { return err } if !obs.Absent && obs.Claim.Op.ID == regID { if obs.Claim.Op.Kind == hostclaim.KindCreating && recoverCreate != nil { if err = recoverCreate(ctx, registration.Host); err != nil && !errors.Is(err, ErrPending) { return err } } return ErrPending } if !RegistrationDrained(registration, now) { return ErrPending } changed := obs.Absent != registration.Claim.Absent || (!obs.Absent && (obs.ETag != registration.Claim.ETag || obs.Claim.Gen != registration.Claim.Gen)) switch { case registration.Kind == RegistrationWakeRetryReset: case obs.Absent || obs.Claim.Free(): if obs, err = hostclaim.Update(ctx, w.raw, obs, FencePurge(id, now)); err != nil { return err } h.FenceState, h.FenceGen, h.FenceETag = "held", obs.Claim.Gen, obs.ETag case obs.Claim.Holder == nil && obs.Claim.Op.Kind == hostclaim.KindPurging && obs.Claim.Op.ID == id: h.FenceState, h.FenceGen, h.FenceETag = "held", obs.Claim.Gen, obs.ETag default: if !changed { return ErrPending } // A foreign revision proves only that the delayed CAS cannot // succeed; it grants no authority over that holder. h.FenceState, h.FenceGen, h.FenceETag = "changed", obs.Claim.Gen, obs.ETag } if j, tag, err = ReadPurgeJournal(ctx, w.raw, account, app, id, appID); err != nil { return err } if j.Phase != "reserved" { return ErrPending } j.Hosts[registration.Host] = h if _, err = w.SavePurgeJournal(ctx, j, tag); err != nil { return err } } // Retried: the mutate re-checks the op and the exact saved registration. if _, err = w.retryAdmission(ctx, account, app, appID, AdmissionObserved{}, func(v *AppAdmission) error { if v.Op == nil || v.Op.ID != id || v.Op.Kind != OpPurging || v.State != "closed" { return ErrPending } saved, ok := v.Registrations[regID] if !ok { return nil } if saved != registration || !effectsSettled(v, regID) { return ErrPending } delete(v.Registrations, regID) return nil }); err != nil { return err } } fresh, err := w.read(ctx, account, app, appID) if err != nil { return err } if len(fresh.Value.Registrations) != 0 || !effectsSettled(&fresh.Value, "") { return ErrPending } return nil } // CompletePurge closes the incarnation: last_purge is set exactly here. func (h *OperationHandle) CompletePurge(ctx context.Context) error { if h.kind != OpPurging { return ErrIdentity } j, _, err := ReadPurgeJournal(ctx, h.w.raw, h.account, h.app, h.id, h.appID) if err != nil { return err } if j.Phase != "done" || !j.Cleanup.Fences || !j.Cleanup.Tombstone || !j.Cleanup.AppRow || !j.Cleanup.Sweep.Verified { return ErrPending } a, err := h.w.read(ctx, h.account, h.app, h.appID) if err != nil { return err } if lp := a.Value.LastPurge; a.Value.Op == nil && lp != nil && lp.ID == h.id && lp.AppID == h.appID { return nil } if err = h.mine(&a.Value); err != nil { return err } _, err = h.w.retryAdmission(ctx, h.account, h.app, h.appID, a, func(v *AppAdmission) error { if err := h.mine(v); err != nil { return err } if len(v.Registrations) != 0 || !effectsSettled(v, "") { return ErrPending } v.State = "closed" v.LastPurge = &PurgeMark{ID: h.id, AppID: h.appID} v.Op = nil return nil }) return err } // RemovePurgeJournal deletes the journal last, and with it a box purge // request that named the same retired incarnation. func (w *ControlWriter) RemovePurgeJournal(ctx context.Context, account, app, id string) error { a, err := ReadCanonicalAdmission(ctx, w.raw, account, app) if err != nil { return err } if !CompletedAdmission(a.Value) || a.Value.LastPurge.ID != id { return ErrPending } j, tag, err := ReadPurgeJournal(ctx, w.raw, account, app, id, a.Value.AppID) if errors.Is(err, os.ErrNotExist) { _, err = w.DiscardPurgeRequest(ctx, account, app) return err } if err != nil { return err } if j.Phase != "done" || !j.Cleanup.Fences { return ErrPending } if _, err = w.DiscardPurgeRequest(ctx, account, app); err != nil { return err } key, err := PurgeKey(account, app) if err != nil { return err } return release.DeleteIfMatch(ctx, w.raw, key, tag) } // DiscardPurgeRequest removes a box request only when it names a retired // incarnation; a request for the live app is left for SweepRequests. func (w *ControlWriter) DiscardPurgeRequest(ctx context.Context, account, app string) (bool, error) { key, err := PurgeRequestKey(account, app) if err != nil { return false, err } body, tag, err := w.raw.Get(ctx, key) if errors.Is(err, os.ErrNotExist) { return false, nil } if err != nil { return false, err } var request release.ClaimPurgeRequest if err = json.Unmarshal(body, &request); err != nil { return false, err } if request.V != 1 || request.Account != account || request.App != app || request.AppID == "" || tag == "" { return false, ErrIdentity } a, err := ReadCanonicalAdmission(ctx, w.raw, account, app) if err != nil { return false, err } if a.Value.LastPurge == nil || a.Value.LastPurge.AppID != request.AppID { return false, nil } if err = release.DeleteIfMatch(ctx, w.raw, key, tag); err != nil { return false, err } return true, nil }