diff --git a/controller/job_history.go b/controller/job_history.go new file mode 100644 index 00000000..9c144ec2 --- /dev/null +++ b/controller/job_history.go @@ -0,0 +1,604 @@ +package main + +import ( + "bytes" + "crypto/sha256" + "encoding/binary" + "encoding/json" + "errors" + "fmt" + "hash/crc32" + "io" + "math" + "os" + "path/filepath" + "strings" + + "github.com/google/uuid" + "golang.org/x/sys/unix" +) + +const ( + jobSlots = 5000 + jobSlotBytes = 4096 + jobStateSize = 8192 + jobMaxAge = 7 * 24 * 60 * 60 +) + +type jobHistoryState struct { + Version int `json:"version"` + Boot string `json:"boot"` + Controller string `json:"controller"` + ScaleSet string `json:"scale_set"` + Generation string `json:"generation"` + Epoch string `json:"activity_epoch"` + Open bool `json:"session_open"` + Dirty bool `json:"dirty"` + PollAt int64 `json:"poll_at"` + Demand *jobDemand `json:"demand,omitempty"` + Gaps map[string]uint64 `json:"gaps"` + Slots int `json:"slots"` + Records int `json:"record_count"` + RecordFile string `json:"record_file"` +} + +type jobHistory struct { + dir *os.File + file *os.File + state jobHistoryState + records []jobRecord + index map[string]int + pending map[int]struct{} + nextExpiry int64 +} + +var errUnsafeJobHistory = errors.New("unsafe job history") + +func jobHistoryAbsent(err error) bool { return errors.Is(err, unix.ENOENT) } + +func jobNoACL(fd int) error { + for _, attribute := range []string{"system.posix_acl_access", "system.posix_acl_default"} { + if _, err := unix.Fgetxattr(fd, attribute, nil); err != unix.ENODATA && err != unix.ENOTSUP { + return errUnsafeJobHistory + } + } + return nil +} + +func openJobDirectory(path string) (*os.File, error) { + if !filepath.IsAbs(path) || filepath.Clean(path) != path { + return nil, errUnsafeJobHistory + } + const flags = unix.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC | unix.O_NOFOLLOW + fd, err := unix.Open("/", flags, 0) + if err != nil { + return nil, err + } + current := "" + parts := strings.Split(strings.TrimPrefix(path, "/"), "/") + for i, name := range parts { + child, err := unix.Openat(fd, name, flags, 0) + unix.Close(fd) + if err != nil { + return nil, err + } + fd = child + current += "/" + name + var stat unix.Stat_t + if err := unix.Fstat(fd, &stat); err != nil { + unix.Close(fd) + return nil, err + } + mode := stat.Mode & 07777 + if stat.Uid != 0 || (mode&0022 != 0 && !(current == "/tmp" && mode&01000 != 0)) || + (i == len(parts)-2 && (mode != 0750 || jobNoACL(fd) != nil)) || + (i == len(parts)-1 && (mode != 0700 || jobNoACL(fd) != nil)) { + unix.Close(fd) + return nil, errUnsafeJobHistory + } + } + return os.NewFile(uintptr(fd), path), nil +} + +func openJobFile(dir *os.File, name string, flags int, limit int64) (*os.File, error) { + fd, err := unix.Openat(int(dir.Fd()), name, flags|unix.O_CLOEXEC|unix.O_NOFOLLOW|unix.O_NONBLOCK, 0600) + if err != nil { + return nil, err + } + var stat unix.Stat_t + if err := unix.Fstat(fd, &stat); err != nil || stat.Uid != 0 || stat.Nlink != 1 || + stat.Mode != unix.S_IFREG|0600 || stat.Size > limit || jobNoACL(fd) != nil { + unix.Close(fd) + return nil, errUnsafeJobHistory + } + return os.NewFile(uintptr(fd), name), nil +} + +func (h *jobHistory) validateDirectory() error { + // Use a fresh descriptor so reading the directory never changes the lock's offset. + fd, err := unix.Openat(int(h.dir.Fd()), ".", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) + if err != nil { + return err + } + scan := os.NewFile(uintptr(fd), "private") + defer scan.Close() + names, err := scan.Readdirnames(7) + if err != nil && err != io.EOF { + return err + } + for _, name := range names { + var limit int64 + switch name { + case "records": + limit = jobSlots * jobSlotBytes + case "state.json", "state.json.tmp": + limit = jobStateSize + case "attempt.json", "attempt.json.tmp": + // The publisher validates these under the export lock and can replace them concurrently. + continue + default: + return errUnsafeJobHistory + } + file, err := openJobFile(h.dir, name, unix.O_RDONLY, limit) + if err != nil { + return err + } + file.Close() + } + return nil +} + +func openJobHistory(path, controller, scaleSet string) (_ *jobHistory, err error) { + if !jobScope.MatchString(controller) || !jobScope.MatchString(scaleSet) { + return nil, errUnsafeJobHistory + } + dir, err := openJobDirectory(path) + if err != nil { + return nil, err + } + h := &jobHistory{dir: dir, index: make(map[string]int), pending: make(map[int]struct{})} + defer func() { + if err != nil { + h.close() + } + }() + if err = unix.Flock(int(dir.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { + return nil, err + } + defer unix.Flock(int(dir.Fd()), unix.LOCK_UN) + if err = h.validateDirectory(); err != nil { + return nil, err + } + h.file, err = openJobFile(dir, "records", unix.O_RDWR, jobSlots*jobSlotBytes) + if errors.Is(err, unix.ENOENT) { + h.file, err = openJobFile(dir, "records", unix.O_RDWR|unix.O_CREAT|unix.O_EXCL, jobSlots*jobSlotBytes) + } + if err != nil { + return nil, err + } + if err = unix.Flock(int(h.file.Fd()), unix.LOCK_EX|unix.LOCK_NB); err != nil { + return nil, err + } + read, readErr := openJobFile(dir, "state.json", unix.O_RDONLY, jobStateSize) + if readErr == nil { + payload, readErr := io.ReadAll(io.LimitReader(read, jobStateSize+1)) + read.Close() + if readErr != nil { + return nil, readErr + } + if err := decodeJobJSON(payload, &h.state); err != nil || h.state.Version != 1 || + h.state.Gaps == nil || h.state.Slots < 0 || h.state.Slots > jobSlots || + h.state.Records < 0 || h.state.Records > h.state.Slots { + return nil, errUnsafeJobHistory + } + } else if !errors.Is(readErr, unix.ENOENT) { + return nil, readErr + } + if h.state.Version == 1 && h.state.Controller != controller { + return nil, errUnsafeJobHistory + } + reset := h.state.Version == 0 || h.state.ScaleSet != scaleSet + if reset { + h.state = jobHistoryState{Version: 1, Controller: controller, ScaleSet: scaleSet, Gaps: map[string]uint64{"initial_unknown": 1}} + } + if h.state.Open || h.state.Dirty { + h.gap("unclean_session", 1) + } + info, err := h.file.Stat() + if err != nil { + return nil, err + } + digest, err := h.recordFile() + if err != nil { + return nil, err + } + if info.Size() != int64(h.state.Slots)*jobSlotBytes || (!reset && digest != h.state.RecordFile) { + h.gap("storage_corruption", 1) + } + bootBytes, bootErr := os.ReadFile("/proc/sys/kernel/random/boot_id") + boot := strings.TrimSpace(string(bootBytes)) + if _, parseErr := uuid.Parse(boot); bootErr != nil || parseErr != nil { + return nil, errUnsafeJobHistory + } + h.state.Boot = boot + h.state.Open, h.state.Dirty, h.state.PollAt, h.state.Demand = true, true, 0, nil + h.state.Epoch, h.state.Generation = uuid.NewString(), uuid.NewString() + if reset { + if err = h.file.Truncate(0); err != nil { + return nil, err + } + if err = h.file.Sync(); err != nil { + return nil, err + } + } + if err = h.writeState(); err != nil { + return nil, err + } + if !reset { + err = h.load(info.Size()) + if len(h.index) != h.state.Records { + h.gap("storage_corruption", 1) + } + } + if err != nil { + return nil, err + } + if err = h.flush(); err != nil { + return nil, err + } + return h, nil +} + +func (h *jobHistory) close() { + if h.file != nil { + h.file.Close() + } + h.dir.Close() +} + +func decodeJobJSON(payload []byte, target any) error { + decoder := json.NewDecoder(bytes.NewReader(payload)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(target); err != nil { + return err + } + if decoder.Decode(new(any)) != io.EOF { + return errUnsafeJobHistory + } + return nil +} + +func (h *jobHistory) load(size int64) error { + if remainder := size % jobSlotBytes; remainder != 0 { + size -= remainder + if err := h.file.Truncate(size); err != nil { + return err + } + } + frame := make([]byte, jobSlotBytes) + for offset := int64(0); offset < size; offset += jobSlotBytes { + if _, err := h.file.ReadAt(frame, offset); err != nil { + return err + } + slot := len(h.records) + var record jobRecord + length := binary.LittleEndian.Uint32(frame) + if length != 0 { + key := "" + if length <= jobSlotBytes-8 && crc32.ChecksumIEEE(frame[8:8+length]) == binary.LittleEndian.Uint32(frame[4:]) && + decodeJobJSON(frame[8:8+length], &record) == nil && record.SeenAt > 0 { + key = jobKey(record) + } + if _, duplicate := h.index[key]; key == "" || duplicate { + h.gap("storage_corruption", 1) + record = jobRecord{} + h.pending[slot] = struct{}{} + } else { + h.index[key] = slot + } + } else if !bytes.Equal(frame, make([]byte, jobSlotBytes)) { + h.gap("storage_corruption", 1) + h.pending[slot] = struct{}{} + } + h.records = append(h.records, record) + } + return nil +} + +func (h *jobHistory) recordFile() (string, error) { + var stat unix.Stat_t + if err := unix.Fstat(int(h.file.Fd()), &stat); err != nil { + return "", err + } + if stat.Nlink != 1 { + return "", errUnsafeJobHistory + } + identity := fmt.Sprintf("%d:%d:%d:%d", stat.Dev, stat.Ino, stat.Size, stat.Ctim.Nano()) + return fmt.Sprintf("%x", sha256.Sum256([]byte(identity))), nil +} + +func (h *jobHistory) writeState() error { + payload, err := json.Marshal(h.state) + if err != nil || len(payload) > jobStateSize { + return errUnsafeJobHistory + } + dir := int(h.dir.Fd()) + if err := unix.Unlinkat(dir, "state.json.tmp", 0); err != nil && !errors.Is(err, unix.ENOENT) { + return err + } + tmp, err := openJobFile(h.dir, "state.json.tmp", unix.O_WRONLY|unix.O_CREAT|unix.O_EXCL, jobStateSize) + if err != nil { + return err + } + defer tmp.Close() + if _, err := tmp.Write(payload); err != nil { + return err + } + if err := tmp.Sync(); err != nil { + return err + } + if err := unix.Renameat(dir, "state.json.tmp", dir, "state.json"); err != nil { + return err + } + return h.dir.Sync() +} + +func (h *jobHistory) flush() error { + frame := make([]byte, jobSlotBytes) + for slot := range h.pending { + clear(frame) + if record := h.records[slot]; record.SeenAt != 0 { + var buffer bytes.Buffer + encoder := json.NewEncoder(&buffer) + encoder.SetEscapeHTML(false) + if err := encoder.Encode(record); err != nil { + return err + } + payload := bytes.TrimSuffix(buffer.Bytes(), []byte("\n")) + if len(payload) > jobSlotBytes-8 { + return errUnsafeJobHistory + } + binary.LittleEndian.PutUint32(frame, uint32(len(payload))) + binary.LittleEndian.PutUint32(frame[4:], crc32.ChecksumIEEE(payload)) + copy(frame[8:], payload) + } + if _, err := h.file.WriteAt(frame, int64(slot*jobSlotBytes)); err != nil { + return err + } + } + if err := h.file.Sync(); err != nil { + return err + } + clear(h.pending) + h.state.Dirty = false + h.state.Slots, h.state.Records = len(h.records), len(h.index) + var err error + h.state.RecordFile, err = h.recordFile() + if err != nil { + return err + } + return h.writeState() +} + +func (h *jobHistory) gap(code string, count uint64) { + h.state.Gaps[code] += min(count, math.MaxInt64-h.state.Gaps[code]) +} + +func jobKey(record jobRecord) string { + if record.JobID != "" { + return "job:" + record.JobID + } + if record.RunnerName != "" { + return "runner:" + record.RunnerName + } + return "" +} + +func (h *jobHistory) set(slot int, record jobRecord) { + if oldKey := jobKey(h.records[slot]); oldKey != "" { + delete(h.index, oldKey) + } + h.records[slot] = record + h.pending[slot] = struct{}{} + if record.SeenAt != 0 { + h.index[jobKey(record)] = slot + expires := record.SeenAt + jobMaxAge + if h.nextExpiry == 0 || expires < h.nextExpiry { + h.nextExpiry = expires + } + } +} + +func (h *jobHistory) place(record jobRecord) { + for slot, old := range h.records { + if old.SeenAt == 0 { + h.set(slot, record) + return + } + } + if len(h.records) < jobSlots { + h.records = append(h.records, jobRecord{}) + h.set(len(h.records)-1, record) + return + } + oldest := 0 + for slot, candidate := range h.records { + if candidate.SeenAt < h.records[oldest].SeenAt { + oldest = slot + } + } + h.gap("retention_cap", 1) + if h.records[oldest].State != "completed" { + h.gap("retention_nonterminal", 1) + } + h.set(oldest, record) +} + +func (h *jobHistory) apply(event jobEvent) bool { + r := event.record + if event.kind == "recover" || event.kind == "exit" { + matched := false + for slot, old := range h.records { + if old.RunnerName != r.RunnerName { + continue + } + matched = true + if event.kind == "exit" && old.Gap == "recovered_association_unknown" { + old.Gap = "runner_exit_without_job" + h.set(slot, old) + } + if event.kind == "exit" && old.State == "running" { + old.State, old.Gap, old.Epoch = "unknown", "runner_exited", "" + old.SeenAt = max(old.SeenAt, r.SeenAt) + h.set(slot, old) + } + } + if !matched { + r.State, r.Gap = "unknown", "recovered_association_unknown" + if event.kind == "exit" { + r.Gap = "runner_exit_without_job" + } + h.place(r) + } + return true + } + if r.JobID == "" { + return false + } + slot, exists := h.index[jobKey(r)] + if exists { + old := h.records[slot] + if (old.Owner != "" && r.Owner != "" && (!strings.EqualFold(old.Owner, r.Owner) || !strings.EqualFold(old.Repository, r.Repository))) || + (old.RunID != "" && r.RunID != "" && old.RunID != r.RunID) || + (old.RunnerName != "" && r.RunnerName != "" && old.RunnerName != r.RunnerName) { + return false + } + } + if association, ok := h.index["runner:"+r.RunnerName]; ok { + if h.records[association].Gap == "runner_exit_without_job" && r.State == "running" { + r.State, r.Gap = "unknown", "runner_exited" + } + h.set(association, jobRecord{}) + } + if !exists { + if r.State == "running" { + r.Epoch = h.state.Epoch + } + h.place(r) + return true + } + old := h.records[slot] + updated := old + if event.kind == "complete" && (old.CompletedAt == 0 || old.Result == "" && r.Result != "") { + if updated.CompletedAt == 0 { + updated.CompletedAt = r.CompletedAt + } + updated.State, updated.Result, updated.Gap, updated.Epoch = r.State, r.Result, r.Gap, "" + } + if old.StartedAt == 0 && r.StartedAt != 0 { + updated.StartedAt = r.StartedAt + } + if event.kind == "start" && r.State == "unknown" && old.State == "running" { + updated.State, updated.Gap, updated.Epoch = r.State, r.Gap, "" + } + mergeJobMetadata(&updated, r) + if updated != old { + updated.SeenAt = max(updated.SeenAt, r.SeenAt) + h.set(slot, updated) + } + return true +} + +func mergeJobMetadata(dst *jobRecord, src jobRecord) { + if dst.Owner == "" { + dst.Owner, dst.Repository = src.Owner, src.Repository + } + if dst.DisplayName == "" { + dst.DisplayName, dst.DisplayCut = src.DisplayName, src.DisplayCut + } + if dst.RunID == "" { + dst.RunID = src.RunID + } + if dst.RunnerName == "" { + dst.RunnerName = src.RunnerName + } + if dst.RunnerID == 0 { + dst.RunnerID = src.RunnerID + } + if dst.QueuedAt == 0 { + dst.QueuedAt = src.QueuedAt + } + if dst.SetAssignedAt == 0 { + dst.SetAssignedAt = src.SetAssignedAt + } + if dst.AssignedAt == 0 { + dst.AssignedAt = src.AssignedAt + } + if dst.FinishedAt == 0 { + dst.FinishedAt = src.FinishedAt + } +} + +func (h *jobHistory) update(now, poll int64, demand *jobDemand, drops uint64, events []jobEvent, stopped, graceful bool) error { + before := h.state + if h.nextExpiry == 0 || h.nextExpiry <= now { + h.nextExpiry = 0 + for slot, record := range h.records { + if record.SeenAt == 0 { + continue + } + expires := record.SeenAt + jobMaxAge + if expires <= now { + h.set(slot, jobRecord{}) + h.gap("retention_expired", 1) + if record.State != "completed" { + h.gap("retention_nonterminal", 1) + } + } else if h.nextExpiry == 0 || expires < h.nextExpiry { + h.nextExpiry = expires + } + } + } + for _, event := range events { + if !h.apply(event) { + drops++ + } + } + if drops > 0 { + h.gap("event_loss", drops) + h.state.Epoch = uuid.NewString() + } + if stopped && graceful { + h.state.Open = false + } + h.state.PollAt, h.state.Demand = poll, demand + changed := len(h.pending) > 0 || drops > 0 || h.state.Open != before.Open + if !changed && poll == before.PollAt && demand == before.Demand { + return nil + } + if err := unix.Flock(int(h.dir.Fd()), unix.LOCK_EX); err != nil { + return err + } + defer unix.Flock(int(h.dir.Fd()), unix.LOCK_UN) + if err := h.validateDirectory(); err != nil { + return err + } + digest, err := h.recordFile() + if err != nil || digest != h.state.RecordFile { + return errUnsafeJobHistory + } + if !changed { + return h.writeState() + } + h.state.Generation = uuid.NewString() + h.state.Dirty = len(h.pending) > 0 + if err := h.writeState(); err != nil { + return err + } + if h.state.Dirty { + if err := h.flush(); err != nil { + return fmt.Errorf("flush job history: %w", err) + } + } + return nil +} diff --git a/controller/job_history_test.go b/controller/job_history_test.go new file mode 100644 index 00000000..c00550f7 --- /dev/null +++ b/controller/job_history_test.go @@ -0,0 +1,205 @@ +package main + +import ( + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/actions/scaleset" + "golang.org/x/sys/unix" +) + +func jobFixture(t *testing.T) string { + t.Helper() + if os.Geteuid() != 0 { + t.Skip("protected job store requires root ownership") + } + base := filepath.Join(t.TempDir(), "observer") + path := filepath.Join(base, "private") + if err := os.MkdirAll(path, 0700); err != nil { + t.Fatal(err) + } + if err := os.Chmod(base, 0750); err != nil { + t.Fatal(err) + } + return path +} + +func fixtureHistory(t *testing.T, path string) *jobHistory { + t.Helper() + history, err := openJobHistory(path, "example", "docker-ci-example") + if err != nil { + t.Fatal(err) + } + return history +} + +func testJob(id, name string, now int64, completed bool) jobEvent { + row := jobRecord{JobID: id, RunnerName: name, SeenAt: now, StartedAt: now, State: "running"} + if completed { + row.StartedAt = 0 + row.CompletedAt, row.State, row.Result = now, "completed", "success" + return jobEvent{kind: "complete", record: row} + } + return jobEvent{kind: "start", record: row} +} + +func persistJobs(t *testing.T, history *jobHistory, now int64, jobs ...jobEvent) { + t.Helper() + if err := history.update(now, now, nil, 0, jobs, false, false); err != nil { + t.Fatal(err) + } +} + +func TestJobHistoryRecoversTerminalAndUnknownAssociation(t *testing.T) { + path := jobFixture(t) + now := int64(1_800_000_000) + history := fixtureHistory(t, path) + if !history.state.Open || history.state.Dirty { + t.Fatal("listener marker was not committed") + } + if _, err := openJobHistory(path, "example", "docker-ci-example"); err == nil { + t.Fatal("a second writer opened the controller's history") + } + complete := testJob("opaque:176", "runner-done", now, true) + incomplete := testJob("unfinished", "runner-lost", now, false) + recovered := jobEvent{kind: "recover", record: jobRecord{RunnerName: "runner-recovered", SeenAt: now}} + persistJobs(t, history, now, complete, incomplete, recovered) + firstEpoch := history.state.Epoch + generation := history.state.Generation + persistJobs(t, history, now+1, complete) + if history.state.Generation != generation { + t.Fatal("duplicate completion changed the generation") + } + history.close() + + history = fixtureHistory(t, path) + defer history.close() + if history.state.Gaps["unclean_session"] != 1 || history.state.Epoch == firstEpoch { + t.Fatalf("restart did not retain an unknown coverage gap: %+v", history.state) + } + lateStart := testJob("opaque:176", "runner-done", now+2, false) + conflictingCompletion := complete + conflictingCompletion.record.Result = "failure" + exit := jobEvent{kind: "exit", record: jobRecord{RunnerName: "runner-lost", SeenAt: now + 2}} + persistJobs(t, history, now+2, lateStart, conflictingCompletion, exit) + done := history.records[history.index["job:opaque:176"]] + missing := history.records[history.index["job:unfinished"]] + unknown := history.records[history.index["runner:runner-recovered"]] + if done.Result != "success" || done.State != "completed" || done.StartedAt != now+2 || done.CompletedAt != now { + t.Fatalf("late and conflicting evidence changed terminal result: %+v", done) + } + if missing.State != "unknown" || missing.Result != "" || missing.Gap != "runner_exited" || + unknown.JobID != "" || unknown.Gap != "recovered_association_unknown" { + t.Fatalf("missing completion or runner association was invented: %+v %+v", missing, unknown) + } + if err := history.update(now+2, now+2, nil, 0, nil, true, true); err != nil { + t.Fatal(err) + } + if history.state.Open || history.state.Gaps["unclean_session"] != 1 { + t.Fatal("graceful shutdown lost historical gap or kept the open marker") + } +} + +func TestJobHistoryBoundsAndIdleSweep(t *testing.T) { + path := jobFixture(t) + now := int64(1_800_000_000) + history := fixtureHistory(t, path) + defer history.close() + events := make([]jobEvent, jobSlots+1) + for i := range events { + events[i] = testJob(fmt.Sprintf("job-%d", i), "", now+int64(i), i != 0) + events[i].record.DisplayName = strings.Repeat("あ", 170) + } + started := time.Now() + persistJobs(t, history, now+jobSlots, events...) + elapsed := time.Since(started) + var allocated int64 + entries, err := os.ReadDir(path) + if err != nil { + t.Fatal(err) + } + for _, entry := range entries { + var info unix.Stat_t + if err := unix.Stat(filepath.Join(path, entry.Name()), &info); err != nil { + t.Fatal(err) + } + allocated += info.Blocks * 512 + } + t.Logf("private store at capacity: %d records, %d allocated bytes across %d files, fixture write %s", + len(history.index), allocated, len(entries), elapsed) + if len(history.index) != jobSlots || history.state.Gaps["retention_cap"] != 1 || history.state.Gaps["retention_nonterminal"] != 1 || allocated > 32<<20 { + t.Fatalf("private history exceeded its bounds: %+v", history.state) + } + persistJobs(t, history, now+jobSlots+jobMaxAge) + if len(history.index) != 0 || history.state.Gaps["retention_expired"] != jobSlots { + t.Fatalf("records remained after an idle sweep: %+v", history.state) + } + frame := make([]byte, jobSlotBytes) + if _, err := history.file.ReadAt(frame, 0); err != nil || strings.Trim(string(frame), "\x00") != "" { + t.Fatalf("expired payload remains on disk: %v", err) + } +} + +func TestJobHistoryRecoversTruncatedSlotWithoutInventingResults(t *testing.T) { + path := jobFixture(t) + now := int64(1_800_000_000) + history := fixtureHistory(t, path) + persistJobs(t, history, now, testJob("first", "runner-1", now, true), testJob("last", "runner-2", now, false)) + if err := history.file.Truncate(jobSlotBytes + 7); err != nil { + t.Fatal(err) + } + history.close() + history = fixtureHistory(t, path) + defer history.close() + if history.state.Gaps["storage_corruption"] == 0 || history.state.Gaps["unclean_session"] == 0 || + len(history.index) != 1 || history.records[0].Result != "success" { + t.Fatalf("recovery lost intact terminal evidence or did not expose loss: %+v", history.state) + } +} + +func TestJobHistoryDetectsZeroedSlotWithoutLosingOtherResults(t *testing.T) { + path := jobFixture(t) + now := int64(1_800_000_000) + history := fixtureHistory(t, path) + persistJobs(t, history, now, testJob("first", "runner-1", now, true), testJob("last", "runner-2", now, false)) + if _, err := history.file.WriteAt(make([]byte, jobSlotBytes), jobSlotBytes); err != nil { + t.Fatal(err) + } + if err := history.update(now+1, now+1, nil, 0, nil, false, false); err == nil { + t.Fatal("writer accepted an externally changed records file") + } + history.close() + history = fixtureHistory(t, path) + defer history.close() + if history.state.Gaps["storage_corruption"] == 0 || history.state.Records != 1 || + history.records[0].Result != "success" { + t.Fatalf("valid historical result or corruption evidence lost: %+v", history.state) + } +} + +func TestJobObserverBoundsAndAllowlistsListenerMetadata(t *testing.T) { + now := int64(1_800_000_000) + o := &jobObserver{batches: make(chan jobBatch, 1)} + base := scaleset.JobMessageBase{JobID: "opaque/job:abc", OwnerName: "owner", RepositoryName: "../unsafe", + WorkflowRunID: 9007199254740993, JobDisplayName: strings.Repeat("😀", 130), JobWorkflowRef: "private-ref", + QueueTime: time.Unix(now-10, 0), RunnerAssignTime: time.Unix(now+500, 0)} + o.batch(&scaleset.RunnerScaleSetMessage{ + JobStartedMessages: []*scaleset.JobStarted{{JobMessageBase: base, RunnerName: "runner-1"}, {JobMessageBase: base}}, + Statistics: &scaleset.RunnerScaleSetStatistic{TotalAvailableJobs: 2, TotalAssignedJobs: 3}, + }, now, now, func(name string) bool { return name == "runner-1" }) + o.batch(&scaleset.RunnerScaleSetMessage{JobStartedMessages: []*scaleset.JobStarted{{JobMessageBase: base}}}, now, now, nil) + batch := <-o.batches + if len(batch.events) != 2 || batch.pollAt != now || batch.demand.Assigned != 3 { + t.Fatalf("listener events and liveness were split: %+v", batch) + } + r := batch.events[0].record + if r.Owner != "" || r.Repository != "" || r.RunID != "9007199254740993" || r.JobID != base.JobID || + len(r.DisplayName) != 512 || !r.DisplayCut || r.QueuedAt != now-10 || r.AssignedAt != 0 || + o.drops.Load() != 1 || batch.events[1].record.State != "unknown" { + t.Fatalf("wrong listener projection: %+v, dropped %d", r, o.drops.Load()) + } +} diff --git a/controller/job_observer.go b/controller/job_observer.go new file mode 100644 index 00000000..4c2a24b3 --- /dev/null +++ b/controller/job_observer.go @@ -0,0 +1,281 @@ +package main + +import ( + "context" + "log/slog" + "regexp" + "strconv" + "strings" + "sync/atomic" + "time" + "unicode" + "unicode/utf8" + + "github.com/actions/scaleset" +) + +const ( + jobPrivateDirectory = "/var/lib/ci-fleet-observer/private" + jobQueueSize = 16 + jobBatchSize = 256 + jobPeriod = 30 * time.Second + jobStartupBudget = 100 * time.Millisecond +) + +var ( + jobOwner = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9-]{0,38}$`) + jobRepo = regexp.MustCompile(`^[A-Za-z0-9_.-]{1,100}$`) + jobRunner = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$`) + jobScope = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`) +) + +type jobRecord struct { + JobID string `json:"job_id,omitempty"` + Owner string `json:"owner,omitempty"` + Repository string `json:"repository,omitempty"` + DisplayName string `json:"display_name,omitempty"` + DisplayCut bool `json:"display_truncated,omitempty"` + RunID string `json:"run_id,omitempty"` + RunnerName string `json:"runner_name,omitempty"` + RunnerID int `json:"runner_id,omitempty"` + QueuedAt int64 `json:"queued_at,omitempty"` + SetAssignedAt int64 `json:"scale_set_assigned_at,omitempty"` + AssignedAt int64 `json:"runner_assigned_at,omitempty"` + FinishedAt int64 `json:"finished_at,omitempty"` + StartedAt int64 `json:"start_observed_at,omitempty"` + CompletedAt int64 `json:"completion_observed_at,omitempty"` + SeenAt int64 `json:"last_observed_at"` + State string `json:"state"` + Result string `json:"result,omitempty"` + Gap string `json:"gap,omitempty"` + Epoch string `json:"activity_epoch,omitempty"` +} + +type jobEvent struct { + record jobRecord + kind string +} + +type jobDemand struct { + ObservedAt int64 `json:"observed_at"` + Available int `json:"available"` + Assigned int `json:"assigned"` +} + +type jobBatch struct { + events []jobEvent + drops uint64 + pollAt int64 + demand *jobDemand +} + +type jobObserver struct { + batches chan jobBatch + finish chan bool + done chan struct{} + drops atomic.Uint64 + stopping atomic.Bool +} + +func startJobObserver(parent context.Context, path, controller, scaleSet string, logger *slog.Logger) *jobObserver { + ctx, cancel := context.WithTimeout(parent, jobStartupBudget) + defer cancel() + observer := &jobObserver{batches: make(chan jobBatch, jobQueueSize), finish: make(chan bool, 1), done: make(chan struct{})} + ready := make(chan bool) + go func() { + defer close(observer.done) + store, err := openJobHistory(path, controller, scaleSet) + if err != nil { + if !jobHistoryAbsent(err) { + logger.Warn("job history unavailable") + } + } else { + defer store.close() + } + select { + case ready <- err == nil: + case <-ctx.Done(): + return + } + if err == nil && observer.run(store) != nil { + logger.Warn("job history unavailable") + } + }() + select { + case available := <-ready: + if available { + return observer + } + case <-ctx.Done(): + logger.Warn("job history startup deadline elapsed") + } + return nil +} + +func (o *jobObserver) stop(graceful bool) { + if o == nil { + return + } + o.stopping.Store(true) + o.finish <- graceful + timer := time.NewTimer(jobStartupBudget) + defer timer.Stop() + select { + case <-o.done: + case <-timer.C: + } +} + +func (o *jobObserver) run(store *jobHistory) error { + ticker := time.NewTicker(jobPeriod) + defer ticker.Stop() + var poll int64 + var demand *jobDemand + for { + var events []jobEvent + var drops uint64 + collect := func(batch jobBatch) { + events = append(events, batch.events...) + drops += batch.drops + poll = max(poll, batch.pollAt) + if batch.demand != nil { + demand = batch.demand + } + } + var stopped, graceful bool + select { + case first := <-o.batches: + collect(first) + case <-ticker.C: + case graceful = <-o.finish: + stopped = true + } + // A dropped batch follows everything already queued when its loss is recorded. + lost := o.drops.Swap(0) + count := len(o.batches) + for i := 0; i < count; i++ { + collect(<-o.batches) + } + if err := store.update(time.Now().Unix(), poll, demand, drops+lost, events, stopped, graceful); err != nil { + return err + } + if stopped { + return nil + } + } +} + +func (o *jobObserver) submit(batch jobBatch) { + select { + case o.batches <- batch: + default: + o.drops.Add(batch.drops + uint64(len(batch.events))) + } +} + +func (o *jobObserver) batch(message *scaleset.RunnerScaleSetMessage, now, pollAt int64, active func(string) bool) { + batch := jobBatch{pollAt: pollAt} + if message == nil { + o.submit(batch) + return + } + if stats := message.Statistics; stats != nil && stats.TotalAvailableJobs >= 0 && stats.TotalAssignedJobs >= 0 { + batch.demand = &jobDemand{ObservedAt: now, Available: stats.TotalAvailableJobs, Assigned: stats.TotalAssignedJobs} + } + if len(o.batches) == cap(o.batches) { + o.drops.Add(uint64(len(message.JobStartedMessages)) + uint64(len(message.JobCompletedMessages))) + return + } + // Preserve terminal evidence first if the upstream batch exceeds the observer budget. + completions := min(len(message.JobCompletedMessages), jobBatchSize) + starts := min(len(message.JobStartedMessages), jobBatchSize-completions) + batch.drops = uint64(len(message.JobCompletedMessages)-completions) + uint64(len(message.JobStartedMessages)-starts) + for _, job := range message.JobStartedMessages[:starts] { + if job == nil { + batch.drops++ + continue + } + r := projectJob(job.JobMessageBase, job.RunnerName, job.RunnerID, now) + r.StartedAt, r.State = now, "running" + if !active(r.RunnerName) { + r.State, r.Gap = "unknown", "runner_activity_unverified" + } + batch.events = append(batch.events, jobEvent{record: r, kind: "start"}) + } + for _, job := range message.JobCompletedMessages[:completions] { + if job == nil { + batch.drops++ + continue + } + r := projectJob(job.JobMessageBase, job.RunnerName, job.RunnerID, now) + r.CompletedAt, r.State = now, "completed" + result := "" + if len(job.Result) <= 32 { + result = strings.ToLower(job.Result) + } + switch result { + case "succeeded", "success": + r.Result = "success" + case "failed", "failure": + r.Result = "failure" + case "canceled", "cancelled": + r.Result = "cancelled" + case "skipped", "timed_out", "neutral", "action_required", "stale", "startup_failure": + r.Result = result + default: + r.Gap = "result_unknown" + } + batch.events = append(batch.events, jobEvent{record: r, kind: "complete"}) + } + o.submit(batch) +} + +func (o *jobObserver) runner(name, kind string) { + if o != nil && !o.stopping.Load() && jobRunner.MatchString(name) { + event := jobEvent{record: jobRecord{RunnerName: name, SeenAt: time.Now().Unix()}, kind: kind} + o.submit(jobBatch{events: []jobEvent{event}}) + } +} + +func projectJob(job scaleset.JobMessageBase, runner string, runnerID int, now int64) jobRecord { + record := jobRecord{SeenAt: now} + if len(job.JobID) <= 256 && utf8.ValidString(job.JobID) && strings.IndexFunc(job.JobID, unicode.IsControl) < 0 { + record.JobID = strings.Clone(job.JobID) + } + if jobOwner.MatchString(job.OwnerName) && jobRepo.MatchString(job.RepositoryName) && job.RepositoryName != "." && job.RepositoryName != ".." { + record.Owner, record.Repository = strings.Clone(job.OwnerName), strings.Clone(job.RepositoryName) + } + if job.WorkflowRunID > 0 { + record.RunID = strconv.FormatInt(job.WorkflowRunID, 10) + } + if jobRunner.MatchString(runner) { + record.RunnerName = strings.Clone(runner) + } + if runnerID > 0 { + record.RunnerID = runnerID + } + var name strings.Builder + for _, r := range job.JobDisplayName { + if unicode.IsControl(r) { + r = ' ' + } + if name.Len()+utf8.RuneLen(r) > 512 { + record.DisplayCut = true + break + } + name.WriteRune(r) + } + record.DisplayName = name.String() + record.QueuedAt = jobSourceTime(job.QueueTime, now) + record.SetAssignedAt = jobSourceTime(job.ScaleSetAssignTime, now) + record.AssignedAt = jobSourceTime(job.RunnerAssignTime, now) + record.FinishedAt = jobSourceTime(job.FinishTime, now) + return record +} + +func jobSourceTime(source time.Time, now int64) int64 { + if seconds := source.Unix(); seconds > 0 && seconds <= now+300 { + return seconds + } + return 0 +} diff --git a/controller/lifecycle_test.go b/controller/lifecycle_test.go index d19e0876..12c17c4b 100644 --- a/controller/lifecycle_test.go +++ b/controller/lifecycle_test.go @@ -68,7 +68,10 @@ func TestLateEventsAfterRestartDoNotDiscardTheRestOfTheSDKBatch(t *testing.T) { const live = "ci-fleet-example-89abcdef" client := &lifecycleBatchClient{message: &scaleset.RunnerScaleSetMessage{ MessageID: 7, Statistics: &scaleset.RunnerScaleSetStatistic{}, - JobStartedMessages: []*scaleset.JobStarted{{RunnerName: gone}, {RunnerName: live}}, + JobStartedMessages: []*scaleset.JobStarted{ + {RunnerName: gone, JobMessageBase: scaleset.JobMessageBase{JobID: "opaque-gone"}}, + {RunnerName: live, JobMessageBase: scaleset.JobMessageBase{JobID: "opaque-live"}}, + }, JobCompletedMessages: []*scaleset.JobCompleted{{RunnerName: gone}, {RunnerName: gone}, {RunnerName: live}, {RunnerName: live}}, }} var removed atomic.Bool @@ -129,6 +132,7 @@ func TestLateEventsAfterRestartDoNotDiscardTheRestOfTheSDKBatch(t *testing.T) { defer docker.Close() scaler := &Scaler{runners: newRunnerState(), dockerClient: docker, logger: slog.New(slog.DiscardHandler), config: Config{FleetInstance: "example", ScaleSetName: "docker-ci-example", MaxRunners: 1, StatusFile: t.TempDir() + "/status.json"}} + scaler.jobs = &jobObserver{batches: make(chan jobBatch, jobQueueSize)} if err := scaler.recoverRunners(context.Background()); err != nil { t.Fatal(err) } @@ -148,6 +152,22 @@ func TestLateEventsAfterRestartDoNotDiscardTheRestOfTheSDKBatch(t *testing.T) { if !removed.Load() || removals.Load() != 1 || scaler.runners.count() != 0 { t.Fatalf("later completion or duplicate was mishandled: removed=%v removals=%d runners=%d", removed.Load(), removals.Load(), scaler.runners.count()) } + var observed bool + for len(scaler.jobs.batches) > 0 { + batch := <-scaler.jobs.batches + for _, event := range batch.events { + if event.record.JobID == "opaque-gone" { + observed = true + if event.record.State != "unknown" || event.record.Gap != "runner_activity_unverified" || + len(batch.events) != len(client.message.JobStartedMessages)+len(client.message.JobCompletedMessages) { + t.Fatalf("late start acquired current activity or split its SDK batch: %+v", batch) + } + } + } + } + if !observed { + t.Fatal("observer discarded a valid late start") + } } func TestUntrackedRunnerEventsRetainUnrelatedAndDockerErrors(t *testing.T) { diff --git a/controller/main.go b/controller/main.go index b1eaddd6..400b1b23 100644 --- a/controller/main.go +++ b/controller/main.go @@ -110,7 +110,9 @@ func run(ctx context.Context) error { if err != nil { return fmt.Errorf("create listener: %w", err) } + scaler.jobs = startJobObserver(ctx, jobPrivateDirectory, cfg.FleetInstance, set.Name, logger) if err := scaler.recoverRunners(ctx); err != nil { + scaler.jobs.stop(false) return err } disk.check() @@ -119,7 +121,9 @@ func run(ctx context.Context) error { defer statusTicker.Stop() go scaler.publishStatus(ctx, statusTicker.C) logger.Info("controller ready", "scaleSet", cfg.ScaleSetName, "minRunners", cfg.MinRunners, "maxRunners", cfg.MaxRunners) - if err := l.Run(ctx, scaler); err != nil && !errors.Is(err, context.Canceled) { + err = l.Run(ctx, scaler) + scaler.jobs.stop(ctx.Err() != nil && (err == nil || errors.Is(err, context.Canceled))) + if err != nil && !errors.Is(err, context.Canceled) { return fmt.Errorf("listener: %w", err) } scaler.shutdown(context.WithoutCancel(ctx)) diff --git a/controller/messages.go b/controller/messages.go index 6d1d4852..4dab5084 100644 --- a/controller/messages.go +++ b/controller/messages.go @@ -31,6 +31,9 @@ func (s *Scaler) Scale(ctx context.Context, message *scaleset.RunnerScaleSetMess if err := ctx.Err(); err != nil { return err } + if s.jobs != nil { + defer s.jobs.batch(message, time.Now().Unix(), s.listenerPollAt.Load(), s.runners.isBusy) + } if message != nil { if message.Statistics == nil { return fmt.Errorf("scale-set message has no statistics") diff --git a/controller/scaler.go b/controller/scaler.go index 5bc21db0..9313de43 100644 --- a/controller/scaler.go +++ b/controller/scaler.go @@ -27,6 +27,7 @@ type Scaler struct { disk *diskAdmission enrollment *controllerEnrollment listenerPollAt atomic.Int64 + jobs *jobObserver runners runnerState dockerClient *dockerclient.Client scalesetClient interface { @@ -230,7 +231,8 @@ func (s *Scaler) watchRunner(ctx context.Context, name, id string) { // Docker can wake a not-running waiter while the container is restarting. current, err := s.dockerClient.ContainerInspect(ctx, id) // A not-found inspection already proves this exact container is retired. - if !errdefs.IsNotFound(err) { + gone := errdefs.IsNotFound(err) + if !gone { if err != nil || current.State == nil { s.logger.Warn("inspect exited runner", "runner", name, "error", err) time.Sleep(time.Minute) @@ -239,6 +241,9 @@ func (s *Scaler) watchRunner(ctx context.Context, name, id string) { if current.State.Running || current.State.Restarting || current.State.Paused { continue } + } + s.jobs.runner(name, "exit") + if !gone { if err := s.logAndRemove(ctx, name, id, false); err != nil { s.logger.Warn("retry exited runner cleanup", "runner", name, "error", err) time.Sleep(time.Minute) @@ -289,6 +294,7 @@ func (s *Scaler) recoverRunners(ctx context.Context) error { } // A surviving runner may already have a job whose start event was acknowledged. s.runners.addBusy(name, c.ID) + s.jobs.runner(name, "recover") go s.watchRunner(context.WithoutCancel(ctx), name, c.ID) s.logger.Info("recovered active runner", "runner", name, "containerID", c.ID) continue diff --git a/controller/state.go b/controller/state.go index 44fd76c6..9d9b90d4 100644 --- a/controller/state.go +++ b/controller/state.go @@ -58,6 +58,13 @@ func (r *runnerState) markBusy(name string) bool { return true } +func (r *runnerState) isBusy(name string) bool { + r.mu.Lock() + defer r.mu.Unlock() + _, ok := r.busy[name] + return ok +} + func (r *runnerState) contains(name, expectedID string) bool { r.mu.Lock() defer r.mu.Unlock() diff --git a/docs/ENDPOINT-SNAPSHOTS.md b/docs/ENDPOINT-SNAPSHOTS.md index 1c68e3e9..6273fb6e 100644 --- a/docs/ENDPOINT-SNAPSHOTS.md +++ b/docs/ENDPOINT-SNAPSHOTS.md @@ -56,7 +56,7 @@ The authenticated read response adds derived `freshness` to each source and `pub | Capacity | Uses the active pool's valid anonymous samples from the last seven days. Exports the latest included sample time, sample and runner-observation counts, and p50/p95 for approved CPU, memory, swap, root/Docker disk and inode metrics. An idle, empty or unreadable history supplies no current measurement. Individual samples and job associations stay private. | | Transaction | Uses the controlled pre-transaction rejection phase/reason, terminal verified rollback, or installer outcome preserved by reconciliation. The record must identify the controller and match the applied configuration. Convergence, legacy records without controller identity, and free-text messages alone supply no transaction proof. | -Job history and `jobs.json` remain in #119. The installation engine field records applied policy. The controller's reported software revision, selected filesystem release, desired engine and verified image bindings each have their own source. +The jobs source carries the generation, pending status, and listener and coverage evidence described below. The installation engine field records applied policy. The controller's reported software revision, selected filesystem release, desired engine and verified image bindings each have their own source. Health helpers can substitute zero counts or a configured engine revision after failed reads. The snapshot excludes those fallback values and uses existing health reports and capacity samples without rerunning their probes. The Docker status read has a 64 KiB output cap and a five-second deadline. Image verification has a separate five-second budget. The capacity history read is capped at 128 MiB and the sampler's 26,000-record limit. Its aggregation has a 15-second processing budget. The snapshot reports unavailable when the history exceeds those bounds. @@ -77,12 +77,72 @@ The export directory permits only `endpoint.json`, `jobs.json`, and their fixed The producer exclusively creates `endpoint.json.tmp` at mode `0600`, assigns its observer GID before setting mode `0640`, flushes the complete bounded payload, atomically replaces the final file, and flushes the directory. Failure before replacement preserves the incumbent export. Reads authenticate first, close descriptors after bounded reads, and cannot access private source stores through the consumer API. +## Worker job history + +The existing authenticated scale-set listener feeds a bounded, nonblocking +queue that admits up to 16 batches of up to 256 events each. The controller writes to an already prepared, +root-owned `/var/lib/ci-fleet-observer/private` directory at mode `0700`. +It keeps `records` and its small state files at mode `0600`. Each record +occupies a checksummed 4 KiB slot. Changes rewrite individual slots. The +5,000 slots and four capped state and staging names use less than 20 MiB of +logical file space. A background sweep clears retained payloads after seven +days even when the listener is idle. This directory is independent of the +controller status file and anonymous capacity history. + +Before polling, the controller attempts to commit an open-session marker +within its startup budget. A failed or delayed observer startup leaves CI +available and the observation source unavailable. A verified listener +shutdown clears the marker after the queue flushes. An interrupted session, +invalid slot, full event queue, or retention cap leaves controlled evidence +of the gap. Each restart ends the previous session's claim of current +activity. A later session can prove jobs it observes directly. It cannot +recover missing events. Runner exit leaves an unknown result, and a +recovered runner can have an unknown job association. + +The privileged publication command uses the existing export lock. Run it on +the observer's 30-second cadence when #122 prepares the service. The jobs +source reports the listener's successful poll time and separately timestamps +the publisher's check. The publisher verifies the private records file and +the controller's lifetime writer lock before accepting listener liveness. +The publisher checks the records file against the committed file identity and +checks the populated-slot count when building a new projection. Counts report only `TotalAvailableJobs` and +`TotalAssignedJobs` in statistics from this scale-set session, with the time +the controller observed them. The scopes and counts have no effect on +scheduling. The covered time range uses local observations. Queue, +scale-set assignment, runner assignment and finish times come from the +source when supplied. Start and completion observation times are local to +the listener. Run URLs use the configured GitHub origin, currently +`https://github.com`, and validated owner, repository and workflow run ID. +The opaque job ID has no verified REST correlation. + +`jobs.json` caps the projection at 4 MiB. It orders nonterminal records +first, then terminal records by source finish time when available or local +completion time. It reports retained, exported and omitted counts, including +omitted nonterminal records. The generation changes when records or coverage +change. A boot-bound monotonic allowance and durable in-flight reservation +enforce at least 60 seconds between full-write attempts. An uncertain +allowance requires a fresh 60-second cooldown. Liveness-only publication keeps +the previous job file. + +`SnapshotReader.read_job_history(headers)` authenticates before reading either +export. It caches only the validated current generation. Running activity +requires a matching generation, a clear pending flag, fresh publisher and +listener evidence, and sufficient projection coverage. Otherwise the +authenticated read shows unknown current activity while preserving terminal +results and original observation times. The aggregate activity flag also +accounts for retained coverage gaps and loss of nonterminal records. A +directly observed running job can remain current while aggregate coverage is +unknown. Missing summary evidence defaults +to unknown activity. The API accepts only the fixed job file. + ## Verification ```bash python3 scripts/test_endpoint_snapshot.py python3 scripts/test_endpoint_snapshot_sources.py python3 scripts/test_endpoint_snapshot_store.py +python3 scripts/test_endpoint_jobs.py +(cd controller && go test -v -run 'TestJob(History|Observer)') ``` -The focused tests cover source identity, timestamp provenance, missing or invalid evidence, redaction, unknown and stale states, authentication before file access, protected permissions and paths, interrupted publication, and bounded subprocess and file reads. The repository's [full validation](LOCAL-VALIDATION.md) records test durations and stage logs. Live runner and reconciliation continuity during observation failures still require #122 acceptance on an approved host. +The job fixtures report allocated and logical bytes and elapsed write times in the test output. The focused tests cover source identity, timestamp provenance, missing or invalid evidence, redaction, unknown and stale states, authentication before file access, protected permissions and paths, interrupted publication, and bounded subprocess and file reads. The repository's [full validation](LOCAL-VALIDATION.md) records test durations and stage logs. Private-directory provisioning, the controller mount, publisher activation, and live runner and reconciliation continuity during observation failures require #122 acceptance on an approved host. diff --git a/docs/ENDPOINT-UI-DESIGN.md b/docs/ENDPOINT-UI-DESIGN.md index 4cd6baca..0f0a9851 100644 --- a/docs/ENDPOINT-UI-DESIGN.md +++ b/docs/ENDPOINT-UI-DESIGN.md @@ -104,7 +104,7 @@ Publisher and listener liveness are separate. The existing controller status hea The small endpoint export must flag pending job or coverage changes during coalescing or a failed publication. While changes are pending, retained running records show unknown current activity even if listener liveness is fresh. Historical terminal results remain visible. Clear the pending flag only after the matching validated job generation contains the coalesced changes or explicit loss evidence. Missing pending-state evidence defaults to unknown activity. -[Issue #119](https://github.com/RandomDevelopment/ci-fleet/issues/119) records an allowlisted history through the existing authenticated scale-set listener. Observation does not change scaling, message acknowledgement, or runner cleanup and creates no competing message consumer. The pinned listener acknowledges batches before callbacks. Persist a protected unclean-session marker before listener polling begins. Missing, unreadable, or inconsistent durable coverage state defaults to unknown, including on first startup and after restart. If marker or observation persistence fails, ordinary CI continues, but observation cannot claim complete coverage. Clear the session marker only after a verified graceful listener shutdown and observation flush; this does not clear retained coverage gaps. +[Issue #119](https://github.com/RandomDevelopment/ci-fleet/issues/119) records an allowlisted history through the existing authenticated scale-set listener. Observation does not change scaling, message acknowledgement, or runner cleanup and creates no competing message consumer. The original v0.4.0 listener acknowledged batches before callbacks. The pinned v0.5.0 listener acknowledges a batch after the scaler callback succeeds. The observer queue and its disk writes have their own failure boundary. Persist a protected unclean-session marker before listener polling begins. Missing, unreadable, or inconsistent durable coverage state defaults to unknown, including on first startup and after restart. If marker or observation persistence fails, ordinary CI continues, but observation cannot claim complete coverage. Clear the session marker only after a verified graceful listener shutdown and observation flush; this does not clear retained coverage gaps. After an unclean restart, retain a coverage gap until a separately approved reconciliation source independently inventories the affected jobs or recovers the missing batch. #119 must define and verify any such source before using it. The initial listener-only implementation has no reconciliation source and leaves the gap unknown. Optional GitHub Actions-read enrichment does not by itself establish completeness. A healthy heartbeat, a new event, or successful later persistence cannot clear a retained gap or turn missing durable state into complete coverage. @@ -171,5 +171,5 @@ Risks remain explicit. Trusted job code with Docker access is host-root-equivale - [Current fleet architecture](ARCHITECTURE.md), [secrets model](SECRETS.md), [host enrollment](ADDING-A-HOST.md), and [project boundaries](PROJECT-STANDARD.md). - [Health monitoring](HEALTH-MONITORING.md), [capacity telemetry](CAPACITY-TELEMETRY.md), and [authenticated status reporting](STATUS-REPORTING.md). -- [Pinned scale-set metadata](https://github.com/actions/scaleset/blob/v0.4.0/types.go) and [GitHub workflow jobs API](https://docs.github.com/en/rest/actions/workflow-jobs). +- [Pinned scale-set metadata](https://github.com/actions/scaleset/blob/v0.5.0/types.go) and [GitHub workflow jobs API](https://docs.github.com/en/rest/actions/workflow-jobs). - [GitHub ephemeral runner guidance](https://docs.github.com/en/actions/reference/runners/self-hosted-runners) and [Docker socket access limits](https://dozzle.dev/guide/authentication). diff --git a/docs/STATUS-REPORTING.md b/docs/STATUS-REPORTING.md index 042ebf2e..e9ecdadc 100644 --- a/docs/STATUS-REPORTING.md +++ b/docs/STATUS-REPORTING.md @@ -140,3 +140,7 @@ The local full health result remains available for recovery, but only the status For dedicated-host packaging, one-time secret boundaries, activation, verification, upgrade, and rollback, see [Status receiver deployment](STATUS-RECEIVER-DEPLOYMENT.md). + +The [worker job history](ENDPOINT-SNAPSHOTS.md#worker-job-history) stays in the +protected local observer store. Status-report v1 and anonymous capacity +samples exclude job metadata. diff --git a/scripts/endpoint_jobs.py b/scripts/endpoint_jobs.py new file mode 100644 index 00000000..ce93977c --- /dev/null +++ b/scripts/endpoint_jobs.py @@ -0,0 +1,454 @@ +"""The worker's protected job projection and export allowance.""" + +from contextlib import contextmanager +import fcntl +import hashlib +import os +import re +import stat +import struct +import time +import unicodedata +import zlib + +from endpoint_snapshot_store import ( + DIRECTORY_FLAGS, MAX_JOB_BYTES, READ_FLAGS, StoreError, _no_acl, _open_directory, + _os_error, _read_at, _regular, _require, decode_json, encode_json, jobs_identity, publish_jobs, read_jobs, +) + +SLOTS = 5000 +FRAME = 4096 +STATE_BYTES = 8192 +AGE = 7 * 86400 +MIN_INTERVAL_NS = 60 * 10**9 +SCOPE = re.compile(r"[a-z0-9][a-z0-9-]{0,62}") +UUID = re.compile(r"[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}") +OWNER = re.compile(r"[A-Za-z0-9][A-Za-z0-9-]{0,38}") +REPOSITORY = re.compile(r"[A-Za-z0-9_.-]{1,100}") +FINGERPRINT = re.compile(r"[0-9a-f]{64}") +RUN_ID = re.compile(r"[1-9][0-9]{0,18}") +RUNNER = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,127}") +RESULTS = {"success", "failure", "cancelled", "skipped", "timed_out", "neutral", + "action_required", "stale", "startup_failure"} +COVERAGE_GAPS = {"initial_unknown", "unclean_session", "storage_corruption", + "event_loss", "retention_cap", "retention_expired", "retention_nonterminal"} +CURRENT_COVERAGE_GAPS = COVERAGE_GAPS - {"retention_expired", "retention_cap"} +SOURCE_TIMES = {"queued_at", "scale_set_assigned_at", "runner_assigned_at", "finished_at"} +LOCAL_TIMES = {"start_observed_at", "completion_observed_at", "last_observed_at"} +FIELDS = SOURCE_TIMES | LOCAL_TIMES | { + "job_id", "owner", "repository", "display_name", "display_truncated", "run_id", + "runner_name", "runner_id", "state", "result", "gap", +} +PRIVATE_NAMES = {"state.json", "state.json.tmp", "records", "attempt.json", "attempt.json.tmp"} + + +def match(pattern, value): + return isinstance(value, str) and pattern.fullmatch(value) is not None + + +def uint(value): + return type(value) is int and 0 <= value <= 2**63 - 1 + + +def valid_gaps(value): + return (isinstance(value, dict) and value.keys() <= COVERAGE_GAPS + and all(uint(count) and count > 0 for count in value.values())) + + +def valid_demand(demand, now): + return (isinstance(demand, dict) and set(demand) == {"observed_at", "available", "assigned"} + and all(uint(value) for value in demand.values()) and 0 < demand["observed_at"] <= now) + + +def text(value, limit): + return (isinstance(value, str) and len(value.encode("utf-8")) <= limit + and all(unicodedata.category(char) != "Cc" for char in value)) + + +def run_link(record): + repo = record.get("repository") + run = record.get("run_id") + if (match(OWNER, record.get("owner")) and match(REPOSITORY, repo) and repo not in {".", ".."} + and match(RUN_ID, run) and uint(int(run))): + return f"https://github.com/{record['owner']}/{repo}/actions/runs/{run}" + return None + + +def record_key(record): + return ("job", record["job_id"]) if "job_id" in record else ("runner", record["runner_name"]) + + +def validate_record(record, now, *, private=False): + extra = {"activity_epoch"} if private else {"run_url"} + _require(isinstance(record, dict) and {"last_observed_at", "state"} <= record.keys() <= FIELDS | extra, + "invalid_jobs") + for name, pattern in (("owner", OWNER), ("repository", REPOSITORY), ("runner_name", RUNNER), ("run_id", RUN_ID), + ("activity_epoch", UUID)): + _require(name not in record or match(pattern, record[name]), "invalid_jobs") + _require(("owner" in record) == ("repository" in record) and record.get("repository") not in {".", ".."} + and ("run_id" not in record or uint(int(record["run_id"]))) + and ("runner_id" not in record or uint(record["runner_id"]) and record["runner_id"] > 0) + and ("display_truncated" not in record or record["display_truncated"] is True + and bool(record.get("display_name"))), "invalid_jobs") + for field, limit in (("job_id", 256), ("display_name", 512)): + _require(field not in record or text(record[field], limit) and bool(record[field]), "invalid_jobs") + for field in SOURCE_TIMES | LOCAL_TIMES: + _require(field not in record or uint(record[field]) and 0 < record[field] <= now + 300, "invalid_jobs") + seen = record["last_observed_at"] + _require(all(record.get(field, 0) <= seen for field in LOCAL_TIMES), "invalid_jobs") + state, gap = record["state"], record.get("gap") + if state == "completed": + _require("job_id" in record and "completion_observed_at" in record and "activity_epoch" not in record + and ((gap is None and record.get("result") in RESULTS) + or (gap == "result_unknown" and "result" not in record)), "invalid_jobs") + elif state == "running": + _require({"job_id", "start_observed_at"} <= record.keys() + and ("activity_epoch" in record) == private and gap is None + and not {"completion_observed_at", "result"} & record.keys(), "invalid_jobs") + elif state == "unknown": + _require(not {"completion_observed_at", "result", "activity_epoch"} & record.keys(), "invalid_jobs") + if gap in {"recovered_association_unknown", "runner_exit_without_job"}: + _require(set(record) == {"runner_name", "last_observed_at", "state", "gap"}, "invalid_jobs") + else: + _require(gap in {"runner_exited", "coverage_unknown", "runner_activity_unverified"} and "job_id" in record + and "start_observed_at" in record, "invalid_jobs") + else: + raise StoreError("invalid_jobs") + _require(private or record.get("run_url") == run_link(record), "invalid_jobs") + _require(len(encode_json(record)) - 1 <= FRAME, "invalid_jobs") + + +@contextmanager +def private_directory(base, observer_gid): + base_fd = fd = None + try: + base_fd = _open_directory(base) + metadata = os.fstat(base_fd) + _require(metadata.st_uid == 0 and metadata.st_gid == observer_gid + and stat.S_IMODE(metadata.st_mode) == 0o750, "unsafe_path") + _no_acl(base_fd, "unsafe_path") + fd = os.open("private", DIRECTORY_FLAGS, dir_fd=base_fd) + metadata = os.fstat(fd) + _require(metadata.st_uid == 0 and stat.S_IMODE(metadata.st_mode) == 0o700, "unsafe_path") + _no_acl(fd, "unsafe_path") + yield fd + except OSError as error: + raise _os_error(error) from None + finally: + if fd is not None: + os.close(fd) + if base_fd is not None: + os.close(base_fd) + + +def check_private_file(fd, name, limit): + _regular(os.stat(name, dir_fd=fd, follow_symlinks=False), modes=(0o600,), max_bytes=limit) + handle = os.open(name, READ_FLAGS, dir_fd=fd) + try: + _regular(os.fstat(handle), modes=(0o600,), max_bytes=limit) + _no_acl(handle, "unsafe_file") + finally: + os.close(handle) + + +@contextmanager +def private_lock(base, observer_gid): + with private_directory(base, observer_gid) as fd: + try: + fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + raise StoreError("busy") from None + with os.scandir(fd) as entries: + for entry in entries: + _require(entry.name in PRIVATE_NAMES, "unsafe_file") + limit = SLOTS * FRAME if entry.name == "records" else STATE_BYTES + check_private_file(fd, entry.name, limit) + yield fd + + +def read_private(fd, name, limit=STATE_BYTES): + try: + return _read_at(fd, name, modes=(0o600,), max_bytes=limit) + except OSError as error: + raise _os_error(error) from None + + +def load_state(fd, controller, scale_set, now): + state = decode_json(read_private(fd, "state.json"), max_bytes=STATE_BYTES) + fields = {"version", "boot", "controller", "scale_set", "generation", "activity_epoch", + "session_open", "dirty", "poll_at", "gaps", "slots", "record_count", "record_file"} + _require(fields <= state.keys() <= fields | {"demand"} and type(state["version"]) is int + and state["version"] == 1 and state["controller"] == controller and state["scale_set"] == scale_set + and match(UUID, state["generation"]) and match(UUID, state["activity_epoch"]) and match(UUID, state["boot"]) + and type(state["session_open"]) is bool and type(state["dirty"]) is bool + and uint(state["poll_at"]) and state["poll_at"] <= now and valid_gaps(state["gaps"]) + and uint(state["slots"]) and state["slots"] <= SLOTS + and uint(state["record_count"]) and state["record_count"] <= state["slots"] + and match(FINGERPRINT, state["record_file"]) + and ("demand" not in state or valid_demand(state["demand"], now)), "invalid_jobs") + return state + + +def allowance_clock(root): + try: + boot = (root / "proc/sys/kernel/random/boot_id").read_text(encoding="ascii").strip() + ticks = time.clock_gettime_ns(time.CLOCK_BOOTTIME) + except (OSError, UnicodeError, AttributeError): + return None + return (boot, ticks) if match(UUID, boot) else None + + +def allowance_ready(fd, clock): + try: + check_private_file(fd, "attempt.json", STATE_BYTES) + prior = decode_json(read_private(fd, "attempt.json"), max_bytes=STATE_BYTES) + except FileNotFoundError: + prior = {} + except StoreError as error: + if error.code not in {"not_found", "invalid_json"}: + raise + prior = {} + if clock is None: + if prior != {"uncertain": True}: + write_attempt(fd, None, in_flight=False) + return False + boot, ticks = clock + valid = (set(prior) == {"boot", "ticks", "in_flight"} and prior["boot"] == boot + and prior["in_flight"] is False and uint(prior["ticks"]) and prior["ticks"] <= ticks) + if not valid: + write_attempt(fd, clock, in_flight=False) + return False + return ticks - prior["ticks"] >= MIN_INTERVAL_NS + + +def invalidate_allowance(base, observer_gid): + try: + with private_directory(base, observer_gid) as fd: + allowance_ready(fd, None) + except StoreError: + pass + + +def write_attempt(fd, clock, *, in_flight): + value = {"uncertain": True} if clock is None else {"boot": clock[0], "ticks": clock[1], "in_flight": in_flight} + try: + check_private_file(fd, "attempt.json.tmp", STATE_BYTES) + os.unlink("attempt.json.tmp", dir_fd=fd) + except FileNotFoundError: + pass + handle = os.open("attempt.json.tmp", os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_CLOEXEC, + 0o600, dir_fd=fd) + with os.fdopen(handle, "wb") as temporary: + temporary.write(encode_json(value)) + temporary.flush() + os.fsync(temporary.fileno()) + os.replace("attempt.json.tmp", "attempt.json", src_dir_fd=fd, dst_dir_fd=fd) + os.fsync(fd) + + +def record_order(record): + if record["state"] == "completed": + return (1, -record.get("finished_at", record["completion_observed_at"]), record_key(record)) + return (0, -record["last_observed_at"], record_key(record)) + + +def projection(state, payload, now): + records = {} + seen_keys = set() + gaps = dict(state["gaps"]) + corrupt = int(len(payload) != state["slots"] * FRAME) + for offset in range(0, len(payload) - FRAME + 1, FRAME): + frame = payload[offset:offset + FRAME] + if not any(frame): + continue + length, checksum = struct.unpack_from(" MAX_JOB_BYTES: + break + exported.append(record) + times = [record["last_observed_at"] for record in ordered] + return { + "schema_version": 1, "role": "worker", "controller": state["controller"], + "scale_set": state["scale_set"], "generation": state["generation"], "published_at": now, + "observation_source": "scale_set_listener", "gaps": gaps, + "retained": len(ordered), "exported": len(exported), "omitted": len(ordered) - len(exported), + "omitted_nonterminal": sum(record["state"] != "completed" for record in ordered[len(exported):]), + "covered_from": min(times, default=None), "covered_through": max(times, default=None), + "records": exported, + } + + +def validate_projection(value, controller): + fields = {"schema_version", "role", "controller", "scale_set", "generation", "published_at", + "observation_source", "gaps", "retained", "exported", "omitted", "omitted_nonterminal", + "covered_from", "covered_through", "records"} + try: + now = value["published_at"] + rows = value["records"] + _require(set(value) == fields and type(value["schema_version"]) is int and value["schema_version"] == 1 + and value["role"] == "worker" and value["controller"] == controller + and match(SCOPE, value["scale_set"]) and match(UUID, value["generation"]) + and uint(now) and value["observation_source"] == "scale_set_listener" + and valid_gaps(value["gaps"]) and isinstance(rows, list) + and all(uint(value[field]) for field in ("retained", "exported", "omitted", "omitted_nonterminal")) + and value["retained"] == value["exported"] + value["omitted"] <= SLOTS + and len(rows) == value["exported"] and value["omitted_nonterminal"] <= value["omitted"], "invalid_jobs") + lo, hi = value["covered_from"], value["covered_through"] + _require((uint(lo) and uint(hi) and now - AGE < lo <= hi <= now + 300) if value["retained"] + else lo is None and hi is None, "invalid_jobs") + for record in rows: + validate_record(record, now) + _require(lo <= record["last_observed_at"] <= hi, "invalid_jobs") + _require(len({record_key(record) for record in rows}) == len(rows) + and rows == sorted(rows, key=record_order) + and (not value["omitted_nonterminal"] or not any(row["state"] == "completed" for row in rows)), + "invalid_jobs") + except (TypeError, ValueError, KeyError, UnicodeError) as error: + if isinstance(error, StoreError): + raise + raise StoreError("invalid_jobs") from None + + +def valid_summary(value, now): + fields = {"scale_set", "pending", "source_available", "last_poll_at", "generation", "export_fingerprint", "gaps"} + return (isinstance(value, dict) and fields <= value.keys() <= fields | {"demand"} + and match(SCOPE, value["scale_set"]) and type(value["pending"]) is bool + and type(value["source_available"]) is bool and uint(value["last_poll_at"]) + and value["last_poll_at"] <= now and valid_gaps(value["gaps"]) + and (match(UUID, value["generation"]) and match(FINGERPRINT, value["export_fingerprint"]) + or value["pending"] and value["generation"] is value["export_fingerprint"] is None) + and ("demand" not in value or valid_demand(value["demand"], now))) + + +def fingerprint(identity): + return hashlib.sha256(repr(identity).encode("ascii")).hexdigest() + + +def record_file_digest(metadata): + identity = f"{metadata.st_dev}:{metadata.st_ino}:{metadata.st_size}:{metadata.st_ctime_ns}" + return hashlib.sha256(identity.encode("ascii")).hexdigest() + + +def records_health(private_fd, state): + try: + fd = os.open("records", READ_FLAGS, dir_fd=private_fd) + except FileNotFoundError: + return False, False + try: + metadata = os.fstat(fd) + _regular(metadata, modes=(0o600,), max_bytes=SLOTS * FRAME) + _no_acl(fd, "unsafe_file") + intact = (metadata.st_size == state["slots"] * FRAME + and record_file_digest(metadata) == state["record_file"]) + try: + fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB) + except BlockingIOError: + return intact, True + return intact, False + finally: + os.close(fd) + + +def job_summary(state, incumbent, now, clock, intact, writer): + generation = incumbent.get("generation") + summary = { + "scale_set": state["scale_set"], "pending": not intact or state["dirty"] or state["generation"] != generation, + "generation": generation, "export_fingerprint": incumbent.get("export_fingerprint"), + "gaps": dict(state["gaps"]), "last_poll_at": state["poll_at"], + "source_available": (intact and writer and clock is not None and clock[0] == state["boot"] + and state["session_open"] and not state["dirty"] and 0 < state["poll_at"] <= now), + } + if not intact: + summary["gaps"]["storage_corruption"] = max(1, summary["gaps"].get("storage_corruption", 0)) + if "demand" in state: + summary["demand"] = state["demand"] + return summary + + +def incumbent_summary(base, observer_gid, directory_fd, controller, scale_set, previous): + try: + identity = jobs_identity(directory_fd, observer_gid) + if (previous.get("scale_set") == scale_set and previous.get("pending") is False + and previous.get("export_fingerprint") == fingerprint(identity)): + return previous + identity, current = read_jobs(base, observer_gid, directory_fd=directory_fd) + validate_projection(current, controller) + if current["scale_set"] == scale_set: + return {"generation": current["generation"], "export_fingerprint": fingerprint(identity), + "gaps": current["gaps"]} + except StoreError: + pass + return {} + + +def publish_history(base, observer_gid, directory_fd, controller, scale_set, now, clock, previous, save_summary): + incumbent = incumbent_summary(base, observer_gid, directory_fd, controller, scale_set, previous) + with private_directory(base, observer_gid) as private_fd: + sampled = clock() + allowed = allowance_ready(private_fd, sampled) + with private_lock(base, observer_gid) as private_fd: + state = load_state(private_fd, controller, scale_set, now) + intact, writer = records_health(private_fd, state) + summary = job_summary(state, incumbent, now, sampled, intact, writer) + if not summary["pending"]: + summary["gaps"] = incumbent["gaps"] + save_summary(summary) + return + if state["dirty"] or not intact or not allowed: + save_summary(summary) + return + payload = read_private(private_fd, "records", SLOTS * FRAME) + save_summary(summary) + value = projection(state, payload, now) + validate_projection(value, controller) + with private_directory(base, observer_gid) as private_fd: + reservation = clock() + if not allowance_ready(private_fd, reservation): + return + write_attempt(private_fd, reservation, in_flight=True) + try: + publish_jobs(base, value, observer_gid, directory_fd=directory_fd) + finally: + with private_directory(base, observer_gid) as private_fd: + write_attempt(private_fd, clock(), in_flight=False) + identity, written = read_jobs(base, observer_gid, directory_fd=directory_fd) + validate_projection(written, controller) + _require(written == value, "invalid_jobs") + with private_lock(base, observer_gid) as private_fd: + latest = load_state(private_fd, controller, scale_set, now) + intact, writer = records_health(private_fd, latest) + summary = job_summary(latest, {"generation": written["generation"], "export_fingerprint": fingerprint(identity)}, + now, clock(), intact, writer) + if not summary["pending"]: + summary["gaps"] = written["gaps"] + save_summary(summary) diff --git a/scripts/endpoint_snapshot.py b/scripts/endpoint_snapshot.py index e8fce836..1f8f1bd0 100644 --- a/scripts/endpoint_snapshot.py +++ b/scripts/endpoint_snapshot.py @@ -14,8 +14,11 @@ from pathlib import Path from typing import Any, Mapping +from endpoint_jobs import AGE as JOB_MAX_AGE +from endpoint_jobs import CURRENT_COVERAGE_GAPS +from endpoint_jobs import allowance_clock, fingerprint, invalidate_allowance, publish_history, valid_summary, validate_projection from endpoint_snapshot_sources import CAPACITY_METRICS, CAPACITY_PERIOD, SourceError, capacity_aggregate, collect_documents -from endpoint_snapshot_store import StoreError, publication_lock, publish_endpoint, read_endpoint +from endpoint_snapshot_store import StoreError, publication_lock, publish_endpoint, read_endpoint, read_jobs MAX_BYTES = 65_536 CONTROLLER_ID = re.compile(r"[a-z0-9][a-z0-9-]{0,62}") @@ -46,8 +49,8 @@ STALE_AFTER = {"controller": 120, "enrollment_identity": 120, "enrollment_listener": 120, "runtime_revision": 120, "manager_revision": 120, "staged_manager_revision": 900, "image_verification": 120, "capacity": 120, "health": 900, "reconciliation": 900, - "enrollment_reporting": 900, "desired_engine_revision": 900, "transaction": 900} -UNSUPPORTED_SOURCES = {"enrollment_owner_confirmation", "jobs"} + "enrollment_reporting": 900, "desired_engine_revision": 900, "transaction": 900, "jobs": 120} +UNSUPPORTED_SOURCES = {"enrollment_owner_confirmation"} CONTROLLER_ENROLLMENT = { "enrollment_authentication": ("session_opened_at", "authenticated"), "enrollment_scale_set": ("matched_at", "matched"), @@ -162,6 +165,11 @@ def capacity_metrics(value: Any) -> bool: "transaction": {"outcome": choice("rejected", "rollback_verified", "applied", "rollback_unverified"), "phase": choice("pre_transaction"), "reason": choice(*TRANSACTION_REASONS)}, + "jobs": {"scale_set": token, "pending": lambda v: type(v) is bool, + "source_available": lambda v: type(v) is bool, "last_poll_at": integer, + "generation": lambda v: v is None or isinstance(v, str), + "export_fingerprint": lambda v: v is None or isinstance(v, str), "gaps": lambda v: isinstance(v, dict), + "demand": lambda v: isinstance(v, dict)}, **{name: {} for name in UNSUPPORTED_SOURCES}, } SOURCE_NAMES = set(DATA_FIELDS) @@ -206,6 +214,7 @@ def validate_data(name: str, value: dict) -> None: "health": {"status", "checks", "desired_state"}, "reconciliation": {"state"}, "transaction": {"outcome"}, + "jobs": set(DATA_FIELDS["jobs"]) - {"demand"}, }.get(name, set(DATA_FIELDS[name])) if name == "installation": if value.get("record_state") == "absent": @@ -660,6 +669,8 @@ def _validate_snapshot(value: Any, *, controller: str) -> None: raise SnapshotError("invalid_snapshot") if name not in FOUNDATION_SOURCES and source["data"] and source["availability"] != "available": raise SnapshotError("invalid_snapshot") + if name == "jobs" and source["availability"] == "available" and not valid_summary(source["data"], source["observed_at"]): + raise SnapshotError("invalid_snapshot") if name == "installation" and "installed_at" in source["data"]: timestamp(source["data"]["installed_at"], source["last_success_at"]) if name == "reconciliation" and "last_success_at" in source["data"]: @@ -700,6 +711,12 @@ def _validate_snapshot(value: Any, *, controller: str) -> None: if (health["data"]["desired_state"] != policy["data"]["policy_state"] or health["last_success_at"] < policy["data"]["installed_at"]): raise SnapshotError("invalid_snapshot") + jobs = value["sources"]["jobs"] + if jobs["availability"] == "available" and ( + policy["availability"] != "available" or policy["data"].get("record_state") != "installed" + or jobs["data"]["scale_set"] != policy["data"]["scale_set_name"] + ): + raise SnapshotError("invalid_snapshot") validate_new_sources(value["sources"]) try: encoded = (json.dumps(value, separators=(",", ":"), sort_keys=True, ensure_ascii=False, allow_nan=False) + "\n").encode() @@ -788,14 +805,18 @@ def __init__(self, base: Path, *, observer_gid: int, controller: str, backend_be if not isinstance(controller, str) or not CONTROLLER_ID.fullmatch(controller) or not isinstance(backend_bearer, str) or not BEARER.fullmatch(backend_bearer): raise SnapshotError("invalid_reader_configuration") self.base, self.observer_gid, self.controller, self._bearer = base, observer_gid, controller, backend_bearer + self._job_cache = None - def read(self, headers: Mapping[str, str], *, now: int | None = None) -> dict: + def _authenticate(self, headers: Mapping[str, str]) -> None: if not isinstance(headers, Mapping): raise SnapshotError("authentication_failed") authorization = [value for key, value in headers.items() if isinstance(key, str) and key.lower() == "authorization"] if (len(authorization) != 1 or not isinstance(authorization[0], str) or len(authorization[0]) != 50 or not authorization[0].isascii() or not hmac.compare_digest(authorization[0], "Bearer " + self._bearer)): raise SnapshotError("authentication_failed") + + def read(self, headers: Mapping[str, str], *, now: int | None = None) -> dict: + self._authenticate(headers) value = read_endpoint(self.base, self.observer_gid) validate_snapshot(value, controller=self.controller) for name in SOURCE_NAMES - value["sources"].keys(): @@ -818,6 +839,36 @@ def read(self, headers: Mapping[str, str], *, now: int | None = None) -> dict: value["publisher_freshness"] = "unknown" if uncertain else "stale" if now - value["published_at"] > 120 else "current" return value + def read_job_history(self, headers: Mapping[str, str], *, now: int | None = None) -> dict: + self._authenticate(headers) + now = int(time.time()) if now is None else now + if not integer(now): + raise SnapshotError("invalid_argument") + cached = self._job_cache + try: + identity, history = read_jobs(self.base, self.observer_gid, cached=cached) + if cached is None or cached[0] != identity: + validate_projection(history, self.controller) + except StoreError: + self._job_cache = None + raise + self._job_cache = (identity, history) + try: + endpoint = self.read(headers, now=now) + source = endpoint["sources"]["jobs"] + data = source["data"] + current = (endpoint["publisher_freshness"] == source["freshness"] == "current" + and data["generation"] == history["generation"] and data["scale_set"] == history["scale_set"] + and data["export_fingerprint"] == fingerprint(identity) + and not data["pending"] and data["source_available"] + and 0 <= now - data["last_poll_at"] <= 120 and history["omitted_nonterminal"] == 0) + except (KeyError, StoreError, SnapshotError): + current = False + rows = [{**row, "current_activity": "unknown" if row["state"] == "running" and not current else row["state"]} + for row in history["records"] if row["last_observed_at"] > now - JOB_MAX_AGE] + return {**history, "gaps": dict(history["gaps"]), "records": rows, + "current_activity_verified": current and not (CURRENT_COVERAGE_GAPS & history["gaps"].keys())} + def publish(controller: str, *, observer_gid: int, root: Path = Path("/"), now: int | None = None) -> dict: base = root / "var/lib/ci-fleet-observer" @@ -835,7 +886,37 @@ def publish(controller: str, *, observer_gid: int, root: Path = Path("/"), now: raise previous = None documents, errors = collect_documents(controller, root=root) - value = build_snapshot(controller, documents, errors, now=int(time.time()) if now is None else now, previous=previous) + try: + value = build_snapshot(controller, documents, errors, now=int(time.time()) if now is None else now, + previous=previous) + except SnapshotError as error: + if error.code == "clock_uncertain": + invalidate_allowance(base, observer_gid) + raise + install = value["sources"]["installation"]["data"] + if install.get("record_state") == "installed": + def save_jobs_summary(summary: dict) -> None: + prior = value["sources"]["jobs"] + value["sources"]["jobs"] = evidence(summary, observed_at=value["published_at"]) + try: + validate_snapshot(value, controller=controller) + publish_endpoint(base, value, observer_gid, _directory_fd=directory_fd) + except (StoreError, SnapshotError, OSError): + value["sources"]["jobs"] = prior + raise + + try: + publish_history( + base, observer_gid, directory_fd, controller, install["scale_set_name"], value["published_at"], + lambda: allowance_clock(root) if value["clock_state"] != "uncertain" else None, + (previous or {}).get("sources", {}).get("jobs", {}).get("data", {}), save_jobs_summary, + ) + return value + except (StoreError, SnapshotError, OSError) as error: + if value["sources"]["jobs"]["data"].get("pending"): + return value + value["sources"]["jobs"] = failure("unsupported" if getattr(error, "code", None) == "not_found" + else "source_unavailable") publish_endpoint(base, value, observer_gid, _directory_fd=directory_fd) return value diff --git a/scripts/endpoint_snapshot_store.py b/scripts/endpoint_snapshot_store.py index 8586e5b7..e709a762 100644 --- a/scripts/endpoint_snapshot_store.py +++ b/scripts/endpoint_snapshot_store.py @@ -279,13 +279,26 @@ def _validate_exports(directory_fd: int, observer_gid: int) -> tuple[list[str], def publish_endpoint(base: Path, snapshot: dict[str, Any], observer_gid: int, *, _directory_fd: int | None = None) -> None: + _publish_export(base, snapshot, observer_gid, "endpoint.json", MAX_ENDPOINT_BYTES, _directory_fd) + + +def publish_jobs(base: Path, snapshot: dict[str, Any], observer_gid: int, *, directory_fd: int) -> None: + _publish_export(base, snapshot, observer_gid, "jobs.json", MAX_JOB_BYTES, directory_fd) + + +def encode_json(value: dict[str, Any]) -> bytes: + return (json.dumps(value, separators=(",", ":"), sort_keys=True, ensure_ascii=False, + allow_nan=False) + "\n").encode("utf-8") + + +def _publish_export(base: Path, snapshot: dict[str, Any], observer_gid: int, name: str, + limit: int, _directory_fd: int | None) -> None: _require(isinstance(snapshot, dict), "invalid_json") try: - value = (json.dumps(snapshot, separators=(",", ":"), sort_keys=True, ensure_ascii=False, - allow_nan=False) + "\n").encode("utf-8") + value = encode_json(snapshot) except (UnicodeError, TypeError, ValueError, RecursionError): raise StoreError("invalid_json") from None - _require(len(value) <= MAX_ENDPOINT_BYTES, "too_large") + _require(len(value) <= limit, "too_large") directory_fd = _directory_fd temporary_fd = None try: @@ -296,15 +309,16 @@ def publish_endpoint(base: Path, snapshot: dict[str, Any], observer_gid: int, *, except BlockingIOError: raise StoreError("busy") from None temporary, _ = _validate_exports(directory_fd, observer_gid) - for name in temporary: - os.unlink(name, dir_fd=directory_fd) + for abandoned in temporary: + os.unlink(abandoned, dir_fd=directory_fd) _, total = _validate_exports(directory_fd, observer_gid) _require(total + len(value) <= MAX_EXPORT_BYTES, "too_large") - temporary_fd = os.open("endpoint.json.tmp", os.O_CREAT | os.O_EXCL | os.O_WRONLY + temporary_name = name + ".tmp" + temporary_fd = os.open(temporary_name, os.O_CREAT | os.O_EXCL | os.O_WRONLY | os.O_NOFOLLOW | os.O_NONBLOCK | os.O_CLOEXEC, 0o600, dir_fd=directory_fd) os.fchmod(temporary_fd, 0o600) metadata = os.fstat(temporary_fd) - _regular(metadata, modes=(0o600,), max_bytes=MAX_ENDPOINT_BYTES, gid=INITIAL_GID) + _regular(metadata, modes=(0o600,), max_bytes=limit, gid=INITIAL_GID) _no_acl(temporary_fd, "unsafe_file") offset = 0 while offset < len(value): @@ -316,7 +330,7 @@ def publish_endpoint(base: Path, snapshot: dict[str, Any], observer_gid: int, *, os.fsync(temporary_fd) os.close(temporary_fd) temporary_fd = None - os.replace("endpoint.json.tmp", "endpoint.json", src_dir_fd=directory_fd, dst_dir_fd=directory_fd) + os.replace(temporary_name, name, src_dir_fd=directory_fd, dst_dir_fd=directory_fd) os.fsync(directory_fd) except OSError as error: raise _os_error(error) from None @@ -340,3 +354,29 @@ def read_endpoint(base: Path, observer_gid: int, *, _directory_fd: int | None = finally: if _directory_fd is None and directory_fd is not None: os.close(directory_fd) + + +def read_jobs(base: Path, observer_gid: int, *, directory_fd: int | None = None, + cached: tuple | None = None) -> tuple[tuple, dict]: + fd = _open_exports(base, observer_gid) if directory_fd is None else directory_fd + try: + identity = jobs_identity(fd, observer_gid) + if cached is not None and cached[0] == identity: + return cached + value = _read_at(fd, "jobs.json", modes=(0o640,), max_bytes=MAX_JOB_BYTES, gid=observer_gid) + return identity, decode_json(value, max_bytes=MAX_JOB_BYTES) + except OSError as error: + raise _os_error(error) from None + finally: + if directory_fd is None: + os.close(fd) + + +def jobs_identity(directory_fd: int, observer_gid: int) -> tuple: + try: + _validate_exports(directory_fd, observer_gid) + metadata = os.stat("jobs.json", dir_fd=directory_fd, follow_symlinks=False) + _regular(metadata, modes=(0o640,), max_bytes=MAX_JOB_BYTES, gid=observer_gid) + return metadata.st_dev, metadata.st_ino, metadata.st_size, metadata.st_ctime_ns + except OSError as error: + raise _os_error(error) from None diff --git a/scripts/test_endpoint_jobs.py b/scripts/test_endpoint_jobs.py new file mode 100644 index 00000000..b126de87 --- /dev/null +++ b/scripts/test_endpoint_jobs.py @@ -0,0 +1,250 @@ +"""Fixture-only coverage for protected job collection and publication.""" +import fcntl +import os +from pathlib import Path +import struct +import tempfile +import time +import unittest +from unittest.mock import patch +import zlib + +import endpoint_jobs as jobs +import endpoint_snapshot as snapshot +import endpoint_snapshot_store as store +from test_endpoint_snapshot import BEARER, CONTROLLER, NOW, documents + +SCALE = "example-ci-01-scale-set" +BOOT = "b0000000-0000-4000-8000-000000000001" +EPOCH = "e0000000-0000-4000-8000-000000000001" +GEN = "a0000000-0000-4000-8000-000000000001" +GEN2 = "a0000000-0000-4000-8000-000000000002" +HEADERS = {"Authorization": "Bearer " + BEARER} + + +def frame(record): + payload = store.encode_json(record).rstrip(b"\n") + return (struct.pack("