diff --git a/controller/disk_admission.go b/controller/disk_admission.go new file mode 100644 index 00000000..bc259a60 --- /dev/null +++ b/controller/disk_admission.go @@ -0,0 +1,356 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "fmt" + "io" + "os" + "strings" + "sync" + "time" + + "golang.org/x/sys/unix" +) + +const ( + diskMeasurementDirectory = "/run/ci-fleet-disk-admission" + diskStopPercent = 90 + diskResumePercent = 85 + diskStopBytes int64 = 10 * 1024 * 1024 * 1024 + diskResumeBytes int64 = 15 * 1024 * 1024 * 1024 + diskMaxAge int64 = 75 +) + +var invalidDiskJSON = errors.New("invalid disk measurement JSON") + +type diskFilesystem struct { + Roles []string `json:"roles"` + ObservedAt *int64 `json:"observed_at"` + CapacityBytes *int64 `json:"capacity_bytes"` + AvailableBytes *int64 `json:"available_bytes"` + TotalInodes *int64 `json:"total_inodes"` + FreeInodes *int64 `json:"free_inodes"` + State string `json:"state"` + Reason string `json:"reason"` +} + +type diskMeasurement struct { + SchemaVersion int `json:"schema_version"` + BootID string `json:"boot_id"` + Controller string `json:"controller"` + Filesystems []diskFilesystem `json:"filesystems"` +} + +type diskRecovery struct { + StopUsedPercent int `json:"stop_used_percent"` + ResumeUsedPercent int `json:"resume_used_percent"` + StopAvailableBytes int64 `json:"stop_available_bytes"` + ResumeAvailableBytes int64 `json:"resume_available_bytes"` + StopInodePercent int `json:"stop_inode_percent"` + ResumeInodePercent int `json:"resume_inode_percent"` + MaxAgeSeconds int64 `json:"max_age_seconds"` +} + +type diskAdmissionStatus struct { + SchemaVersion int `json:"schema_version"` + State string `json:"state"` + Reason string `json:"reason"` + ObservedAt *int64 `json:"observed_at"` + BlockedSince *int64 `json:"blocked_since"` + RecoveredAt *int64 `json:"recovered_at"` + Filesystems []diskFilesystem `json:"filesystems"` + Recovery diskRecovery `json:"recovery"` +} + +// The latch is deliberately process-local. A restart requires the recovery +// thresholds, never a persisted "ready" decision or reconstructed transition time. +type diskAdmission struct { + mu sync.Mutex + read func() (diskMeasurement, error) + now func() time.Time + bootID string + controller string + ready bool + lastNow int64 + status diskAdmissionStatus +} + +func newDiskAdmission(controller string) *diskAdmission { + boot, _ := os.ReadFile("/proc/sys/kernel/random/boot_id") + return &diskAdmission{controller: controller, bootID: strings.TrimSpace(string(boot)), now: time.Now, + read: func() (diskMeasurement, error) { return readDiskMeasurement(diskMeasurementDirectory) }} +} + +func unknownFilesystems(reason string) []diskFilesystem { + result := make([]diskFilesystem, 0, 3) + for _, role := range []string{"workspace", "docker", "spool"} { + result = append(result, diskFilesystem{Roles: []string{role}, State: "unknown", Reason: reason}) + } + return result +} + +func diskPolicy() diskRecovery { + return diskRecovery{diskStopPercent, diskResumePercent, diskStopBytes, diskResumeBytes, diskStopPercent, diskResumePercent, diskMaxAge} +} + +func (d *diskAdmission) check() bool { + if d == nil { + return false + } + d.mu.Lock() + defer d.mu.Unlock() + value, err := d.read() + now := d.now().Unix() + reason := "" + if err != nil { + reason = "measurement_unavailable" + if errors.Is(err, invalidDiskJSON) { + reason = "measurement_invalid" + } + } else if d.bootID == "" || value.BootID != d.bootID || value.Controller != d.controller || !validDiskMeasurement(value) || now < d.lastNow { + reason = "measurement_invalid" + } + d.lastNow = now + filesystems := append([]diskFilesystem(nil), value.Filesystems...) + if reason != "" { + filesystems = unknownFilesystems(reason) + } + var observed *int64 + blocked, unknown, recovering := "", "", false + for i := range filesystems { + fs := &filesystems[i] + if fs.State == "unknown" { + unknown = fs.Reason + continue + } + if *fs.ObservedAt > now { + *fs = diskFilesystem{Roles: fs.Roles, State: "unknown", Reason: "measurement_invalid"} + unknown = fs.Reason + continue + } + if now-*fs.ObservedAt > diskMaxAge { + fs.State, fs.Reason = "unknown", "measurement_stale" + unknown = fs.Reason + continue + } + if observed == nil || *fs.ObservedAt < *observed { + stamp := *fs.ObservedAt + observed = &stamp + } + fs.State, fs.Reason = "ready", "ready" + switch { + case percentAtLeast(*fs.CapacityBytes-*fs.AvailableBytes, *fs.CapacityBytes, diskStopPercent): + fs.State, fs.Reason = "blocked", "usage_percent" + case *fs.AvailableBytes < diskStopBytes: + fs.State, fs.Reason = "blocked", "available_bytes" + case percentAtLeast(*fs.TotalInodes-*fs.FreeInodes, *fs.TotalInodes, diskStopPercent): + fs.State, fs.Reason = "blocked", "inodes" + case !d.ready && (percentAbove(*fs.CapacityBytes-*fs.AvailableBytes, *fs.CapacityBytes, diskResumePercent) || + *fs.AvailableBytes < diskResumeBytes || percentAbove(*fs.TotalInodes-*fs.FreeInodes, *fs.TotalInodes, diskResumePercent)): + fs.State, fs.Reason = "blocked", "recovering" + recovering = true + } + if fs.State == "blocked" && fs.Reason != "recovering" && blocked == "" { + blocked = fs.Reason + } + } + state, reason := "ready", "ready" + // A proven blocker wins over uncertainty; every per-filesystem failure is + // still visible. Unknown is never permission to admit. + switch { + case blocked != "": + state, reason = "low_disk", blocked + case unknown != "": + state, reason = "unknown", unknown + case recovering: + state, reason = "blocked", "recovering" + } + if unknown != "" { + observed = nil + } + previous := d.ready + d.ready = state == "ready" + blockedSince, recoveredAt := d.status.BlockedSince, d.status.RecoveredAt + if previous && !d.ready { + stamp := now + blockedSince = &stamp + } + if !previous && d.ready && d.status.State != "" { + stamp := now + recoveredAt = &stamp + } + if d.ready { + blockedSince = nil + } + d.status = diskAdmissionStatus{1, state, reason, observed, blockedSince, recoveredAt, filesystems, diskPolicy()} + return d.ready +} + +// Integer quotient/remainder comparisons avoid float rounding and int64 overflow. +func percentAtLeast(used, total int64, percent int64) bool { + threshold := total/100*percent + (total%100*percent+99)/100 + return used >= threshold +} +func percentAbove(used, total int64, percent int64) bool { + threshold := total/100*percent + total%100*percent/100 + return used > threshold +} + +func validDiskMeasurement(value diskMeasurement) bool { + if value.SchemaVersion != 1 || len(value.Filesystems) < 1 || len(value.Filesystems) > 3 { + return false + } + seen := map[string]bool{} + for _, fs := range value.Filesystems { + if len(fs.Roles) == 0 { + return false + } + for _, role := range fs.Roles { + if seen[role] || (role != "workspace" && role != "docker" && role != "spool") { + return false + } + seen[role] = true + } + if fs.State == "unknown" { + if fs.Reason != "measurement_unavailable" || fs.ObservedAt != nil || fs.CapacityBytes != nil || fs.AvailableBytes != nil || fs.TotalInodes != nil || fs.FreeInodes != nil { + return false + } + continue + } + if fs.State != "measured" || fs.Reason != "measured" || fs.ObservedAt == nil || *fs.ObservedAt <= 0 || fs.CapacityBytes == nil || fs.AvailableBytes == nil || fs.TotalInodes == nil || fs.FreeInodes == nil { + return false + } + if *fs.CapacityBytes <= 0 || *fs.AvailableBytes < 0 || *fs.AvailableBytes > *fs.CapacityBytes || *fs.TotalInodes <= 0 || *fs.FreeInodes < 0 || *fs.FreeInodes > *fs.TotalInodes { + return false + } + } + return len(seen) == 3 +} + +func (d *diskAdmission) snapshot() diskAdmissionStatus { + if d == nil { + return diskAdmissionStatus{SchemaVersion: 1, State: "unknown", Reason: "starting", Filesystems: unknownFilesystems("starting"), Recovery: diskPolicy()} + } + d.mu.Lock() + defer d.mu.Unlock() + if d.status.State == "" { + return (*diskAdmission)(nil).snapshot() + } + result := d.status + result.Filesystems = append([]diskFilesystem(nil), d.status.Filesystems...) + return result +} + +func readDiskMeasurement(directory string) (diskMeasurement, error) { + var result diskMeasurement + // Open every ancestor without following symlinks. Only the dedicated export + // is mounted; no host root, Docker storage or private installation tree. + fd, err := unix.Open("/", unix.O_RDONLY|unix.O_DIRECTORY|unix.O_CLOEXEC, 0) + if err != nil { + return result, err + } + defer func() { unix.Close(fd) }() + for _, part := range strings.Split(strings.TrimPrefix(directory, "/"), "/") { + if part == "" || part == "." || part == ".." { + return result, fmt.Errorf("invalid export path") + } + next, err := unix.Openat(fd, part, unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC, 0) + if err != nil { + return result, err + } + unix.Close(fd) + fd = next + var st unix.Stat_t + if err := unix.Fstat(fd, &st); err != nil || st.Uid != 0 || st.Mode&0022 != 0 { + return result, fmt.Errorf("untrusted export ancestry") + } + } + var st unix.Stat_t + if err := unix.Fstat(fd, &st); err != nil || st.Mode&0777 != 0700 || !diskNoACL(fd) { + return result, fmt.Errorf("untrusted export directory") + } + fileFD, err := unix.Openat(fd, "measurement.json", unix.O_RDONLY|unix.O_NOFOLLOW|unix.O_NONBLOCK|unix.O_CLOEXEC, 0) + if err != nil { + return result, err + } + file := os.NewFile(uintptr(fileFD), "measurement.json") + defer file.Close() + if err := unix.Fstat(fileFD, &st); err != nil || st.Uid != 0 || st.Mode&unix.S_IFMT != unix.S_IFREG || st.Mode&0777 != 0600 || st.Nlink != 1 || st.Size > 16384 || !diskNoACL(fileFD) { + return result, fmt.Errorf("untrusted export file") + } + data, err := io.ReadAll(io.LimitReader(file, 16385)) + if err != nil || len(data) > 16384 { + return result, fmt.Errorf("invalid export size") + } + return decodeDiskMeasurement(data) +} + +func decodeDiskMeasurement(data []byte) (diskMeasurement, error) { + var result diskMeasurement + if !uniqueDiskJSON(json.NewDecoder(bytes.NewReader(data)), 0) { + return result, invalidDiskJSON + } + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + if err := decoder.Decode(&result); err != nil { + return result, invalidDiskJSON + } + if decoder.Decode(new(any)) != io.EOF { + return result, invalidDiskJSON + } + return result, nil +} + +func uniqueDiskJSON(decoder *json.Decoder, depth int) bool { + if depth > 16 { + return false + } + token, err := decoder.Token() + if err != nil { + return false + } + switch token { + case json.Delim('{'): + seen := map[string]bool{} + for decoder.More() { + key, err := decoder.Token() + if err != nil { + return false + } + name, ok := key.(string) + name = strings.ToLower(name) // encoding/json matches struct keys case-insensitively. + if !ok || seen[name] { + return false + } + seen[name] = true + if !uniqueDiskJSON(decoder, depth+1) { + return false + } + } + end, err := decoder.Token() + return err == nil && end == json.Delim('}') + case json.Delim('['): + for decoder.More() { + if !uniqueDiskJSON(decoder, depth+1) { + return false + } + } + end, err := decoder.Token() + return err == nil && end == json.Delim(']') + default: + _, delimiter := token.(json.Delim) + return !delimiter + } +} + +func diskNoACL(fd int) bool { + for _, name := range []string{"system.posix_acl_access", "system.posix_acl_default"} { + _, err := unix.Fgetxattr(fd, name, nil) + if err != unix.ENODATA && err != unix.ENOTSUP { + return false + } + } + return true +} diff --git a/controller/disk_admission_test.go b/controller/disk_admission_test.go new file mode 100644 index 00000000..7d2d3edb --- /dev/null +++ b/controller/disk_admission_test.go @@ -0,0 +1,209 @@ +package main + +import ( + "encoding/json" + "errors" + "log/slog" + "os" + "path/filepath" + "syscall" + "testing" + "time" +) + +func diskInt(value int64) *int64 { return &value } +func healthyDiskMeasurement() diskMeasurement { + return diskMeasurement{1, "test-boot", "example", []diskFilesystem{{ + Roles: []string{"workspace", "docker", "spool"}, ObservedAt: diskInt(1000), + CapacityBytes: diskInt(1000 << 30), AvailableBytes: diskInt(500 << 30), + TotalInodes: diskInt(1000000), FreeInodes: diskInt(500000), State: "measured", Reason: "measured", + }}} +} +func admittedDisk() *diskAdmission { + return &diskAdmission{bootID: "test-boot", controller: "example", now: func() time.Time { return time.Unix(1000, 0) }, + read: func() (diskMeasurement, error) { return healthyDiskMeasurement(), nil }} +} + +func TestDiskIndependentTripsAndRecovery(t *testing.T) { + for _, tc := range []struct { + name, reason string + change func(*diskFilesystem) + }{ + {"percentage", "usage_percent", func(f *diskFilesystem) { f.AvailableBytes = diskInt(100 << 30) }}, + {"bytes", "available_bytes", func(f *diskFilesystem) { f.CapacityBytes = diskInt(20 << 30); f.AvailableBytes = diskInt(9 << 30) }}, + {"inodes", "inodes", func(f *diskFilesystem) { f.FreeInodes = diskInt(100000) }}, + {"zero available", "usage_percent", func(f *diskFilesystem) { f.AvailableBytes = diskInt(0) }}, + } { + t.Run(tc.name, func(t *testing.T) { + d := admittedDisk() + m := healthyDiskMeasurement() + d.read = func() (diskMeasurement, error) { + data, _ := json.Marshal(m) + var clone diskMeasurement + _ = json.Unmarshal(data, &clone) + return clone, nil + } + if !d.check() { + t.Fatal("healthy initial sample rejected") + } + tc.change(&m.Filesystems[0]) + if d.check() || d.snapshot().Reason != tc.reason { + t.Fatalf("trip: %+v", d.snapshot()) + } + m = healthyDiskMeasurement() + m.Filesystems[0].AvailableBytes = diskInt(140 << 30) + if d.check() || d.snapshot().Reason != "recovering" { + t.Fatal("resumed above85%") + } + m.Filesystems[0].AvailableBytes = diskInt(150 << 30) + if !d.check() || d.snapshot().RecoveredAt == nil { + t.Fatal("failed recovery at85%") + } + m.Filesystems[0].CapacityBytes = diskInt(20 << 30) + m.Filesystems[0].AvailableBytes = diskInt(diskStopBytes) + if !d.check() { + t.Fatal("stop floor is strictly below10GiB") + } + m.Filesystems[0].AvailableBytes = diskInt(diskStopBytes - 1) + if d.check() { + t.Fatal("bytes floor ignored") + } + m.Filesystems[0].AvailableBytes = diskInt(diskResumeBytes - 1) + if d.check() { + t.Fatal("resume floor ignored") + } + m.Filesystems[0].AvailableBytes = diskInt(diskResumeBytes) + if !d.check() { + t.Fatal("resume floor boundary failed") + } + }) + } +} + +func TestDiskUnknownEvidenceRestartAndClock(t *testing.T) { + for _, tc := range []struct { + name, reason string + change func(*diskMeasurement) + }{ + {"stale", "measurement_stale", func(m *diskMeasurement) { m.Filesystems[0].ObservedAt = diskInt(924) }}, + {"future", "measurement_invalid", func(m *diskMeasurement) { m.Filesystems[0].ObservedAt = diskInt(1001) }}, + {"boot", "measurement_invalid", func(m *diskMeasurement) { m.BootID = "other" }}, + {"identity", "measurement_invalid", func(m *diskMeasurement) { m.Controller = "other" }}, + {"zero total", "measurement_invalid", func(m *diskMeasurement) { m.Filesystems[0].CapacityBytes = diskInt(0) }}, + {"invalid available", "measurement_invalid", func(m *diskMeasurement) { m.Filesystems[0].AvailableBytes = diskInt(1001 << 30) }}, + {"no inode support", "measurement_invalid", func(m *diskMeasurement) { m.Filesystems[0].TotalInodes = diskInt(0) }}, + {"missing role", "measurement_invalid", func(m *diskMeasurement) { m.Filesystems[0].Roles = []string{"docker"} }}, + {"duplicate role", "measurement_invalid", func(m *diskMeasurement) { m.Filesystems[0].Roles = append(m.Filesystems[0].Roles, "docker") }}, + } { + t.Run(tc.name, func(t *testing.T) { + d := admittedDisk() + m := healthyDiskMeasurement() + tc.change(&m) + d.read = func() (diskMeasurement, error) { return m, nil } + if d.check() || d.snapshot().State != "unknown" || d.snapshot().Reason != tc.reason { + t.Fatalf("bad unknown: %+v", d.snapshot()) + } + if d.snapshot().ObservedAt != nil || d.snapshot().BlockedSince != nil { + t.Fatal("invented timestamp") + } + }) + } + d := admittedDisk() + if !d.check() { + t.Fatal("initial") + } + d.now = func() time.Time { return time.Unix(999, 0) } + if d.check() { + t.Fatal("backward clock admitted") + } + d = admittedDisk() + d.read = func() (diskMeasurement, error) { return diskMeasurement{}, errors.New("missing") } + if d.check() || d.snapshot().Reason != "measurement_unavailable" { + t.Fatal("missing admitted") + } + d = admittedDisk() + m := healthyDiskMeasurement() + m.Filesystems[0].AvailableBytes = diskInt(140 << 30) + d.read = func() (diskMeasurement, error) { return m, nil } + if d.check() || d.snapshot().Reason != "recovering" || d.snapshot().BlockedSince != nil { + t.Fatal("restart bypassed recovery or invented prior transition") + } +} + +func TestDiskMultipleFilesystemsPreserveKnownBlockerAndUnknown(t *testing.T) { + d := admittedDisk() + m := healthyDiskMeasurement() + m.Filesystems[0].Roles = []string{"workspace", "spool"} + m.Filesystems[0].AvailableBytes = diskInt(0) + m.Filesystems = append(m.Filesystems, unknownFilesystems("measurement_unavailable")[1]) + d.read = func() (diskMeasurement, error) { return m, nil } + if d.check() || d.snapshot().State != "low_disk" || d.snapshot().ObservedAt != nil { + t.Fatalf("known blocker hidden: %+v", d.snapshot()) + } + if d.snapshot().Filesystems[1].State != "unknown" || d.snapshot().Filesystems[1].AvailableBytes != nil { + t.Fatal("unknown converted to zero") + } +} + +func TestDiskStatusPublicationDoesNotRefreshMeasurement(t *testing.T) { + d := admittedDisk() + d.check() + before := *d.snapshot().ObservedAt + s := &Scaler{disk: d, runners: newRunnerState(), logger: slog.New(slog.DiscardHandler), config: Config{StatusFile: t.TempDir() + "/status.json"}} + s.writeStatus() + s.writeStatus() + if *d.snapshot().ObservedAt != before { + t.Fatal("publication refreshed probe") + } +} + +func TestDiskProtectedRead(t *testing.T) { + // Use the repository's protected parent rather than /tmp's intentionally + // world-writable ancestry; this performs no privileged system mutation. + dir, err := os.MkdirTemp(".", ".disk-read-test-") + if err != nil { + t.Fatal(err) + } + defer os.RemoveAll(dir) + dir, err = filepath.Abs(dir) + if err != nil { + t.Fatal(err) + } + data, _ := json.Marshal(healthyDiskMeasurement()) + path := filepath.Join(dir, "measurement.json") + if err := os.WriteFile(path, data, 0600); err != nil { + t.Fatal(err) + } + if os.Getuid() == 0 { + if _, err := readDiskMeasurement(dir); err != nil { + t.Fatal(err) + } + } else { + if _, err := readDiskMeasurement(dir); err == nil { + t.Fatal("non-root writer admitted") + } + return + } + for _, mode := range []os.FileMode{0644, 0666} { + _ = os.Chmod(path, mode) + if _, err := readDiskMeasurement(dir); err == nil { + t.Fatal("unsafe mode") + } + } + _ = os.Chmod(path, 0600) + _ = os.Link(path, path+".link") + if _, err := readDiskMeasurement(dir); err == nil { + t.Fatal("hardlink") + } + _ = os.Remove(path + ".link") + _ = os.Remove(path) + _ = os.Symlink("missing", path) + if _, err := readDiskMeasurement(dir); err == nil { + t.Fatal("symlink") + } + _ = os.Remove(path) + _ = syscall.Mkfifo(path, 0600) + if _, err := readDiskMeasurement(dir); err == nil { + t.Fatal("fifo") + } +} diff --git a/controller/disk_json_test.go b/controller/disk_json_test.go new file mode 100644 index 00000000..0aaf5814 --- /dev/null +++ b/controller/disk_json_test.go @@ -0,0 +1,81 @@ +package main + +import ( + "encoding/json" + "errors" + "strings" + "testing" +) + +func TestDiskJSONRejectsAmbiguousMalformedAndTrailingData(t *testing.T) { + data, err := json.Marshal(healthyDiskMeasurement()) + if err != nil { + t.Fatal(err) + } + if value, err := decodeDiskMeasurement(data); err != nil || !validDiskMeasurement(value) { + t.Fatalf("valid measurement: %v", err) + } + for _, text := range []string{ + "", "{", string(data) + "{}", string(data) + " trailing", + strings.Replace(string(data), `"schema_version":1`, `"schema_version":1,"schema_version":1`, 1), + strings.Replace(string(data), `"available_bytes":`, `"available_bytes":0,"available_bytes":`, 1), + strings.Replace(string(data), `"available_bytes":`, `"Available_Bytes":0,"available_bytes":`, 1), + strings.Replace(string(data), `"schema_version":1`, `"unexpected":true,"schema_version":1`, 1), + strings.Replace(string(data), `"schema_version":1`, `"schema_version":1.5`, 1), + strings.Repeat("[", 18) + "0" + strings.Repeat("]", 18), + } { + if _, err := decodeDiskMeasurement([]byte(text)); !errors.Is(err, invalidDiskJSON) { + t.Errorf("accepted invalid JSON: %q (%v)", text, err) + } + } + d := admittedDisk() + d.read = func() (diskMeasurement, error) { return decodeDiskMeasurement([]byte("{")) } + if d.check() || d.snapshot().Reason != "measurement_invalid" { + t.Fatal("malformed evidence not classified invalid") + } +} + +func TestDiskJSONRejectsNullMalformedRolesAndState(t *testing.T) { + data, err := json.Marshal(healthyDiskMeasurement()) + if err != nil { + t.Fatal(err) + } + for _, field := range []string{"roles", "state", "reason"} { + for _, value := range []any{nil, true, 1, map[string]any{}, []any{nil}, "invalid"} { + var raw map[string]any + if err := json.Unmarshal(data, &raw); err != nil { + t.Fatal(err) + } + fs := raw["filesystems"].([]any)[0].(map[string]any) + fs[field] = value + changed, err := json.Marshal(raw) + if err != nil { + t.Fatal(err) + } + d := admittedDisk() + d.read = func() (diskMeasurement, error) { return decodeDiskMeasurement(changed) } + if d.check() || d.snapshot().Reason != "measurement_invalid" { + t.Errorf("accepted %s=%v", field, value) + } + } + } +} + +func TestDiskColdMissingEvidenceAndExactFreshnessBoundary(t *testing.T) { + d := admittedDisk() + d.ready = false + d.read = func() (diskMeasurement, error) { return diskMeasurement{}, errors.New("missing") } + if d.check() || d.snapshot().Reason != "measurement_unavailable" || d.snapshot().ObservedAt != nil { + t.Fatal("cold missing sample admitted") + } + for _, age := range []int64{75, 76} { + d.read = func() (diskMeasurement, error) { + m := healthyDiskMeasurement() + m.Filesystems[0].ObservedAt = diskInt(1000 - age) + return m, nil + } + if got := d.check(); got != (age == 75) { + t.Fatalf("age %d admitted=%v", age, got) + } + } +} diff --git a/controller/disk_messages_test.go b/controller/disk_messages_test.go new file mode 100644 index 00000000..eb756a84 --- /dev/null +++ b/controller/disk_messages_test.go @@ -0,0 +1,144 @@ +package main + +import ( + "context" + "encoding/json" + "errors" + "log/slog" + "net/http" + "net/http/httptest" + "os" + "slices" + "strings" + "sync/atomic" + "testing" + + "github.com/actions/scaleset" + "github.com/actions/scaleset/listener" + dockerclient "github.com/docker/docker/client" +) + +func TestDiskBlockedPinnedListenerAcknowledgesOfferAndCompletesActiveJob(t *testing.T) { + var acquisitions, removals atomic.Int32 + client := &lifecycleBatchClient{message: &scaleset.RunnerScaleSetMessage{ + MessageID: 20, Statistics: &scaleset.RunnerScaleSetStatistic{}, + JobAvailableMessages: []*scaleset.JobAvailable{{JobMessageBase: scaleset.JobMessageBase{RunnerRequestID: 99}}}, + JobStartedMessages: []*scaleset.JobStarted{{RunnerName: "prior-assignment"}}, + JobCompletedMessages: []*scaleset.JobCompleted{{RunnerName: "prior-assignment", Result: "success"}}, + }, acquireJobs: func(context.Context, []int64) ([]int64, error) { acquisitions.Add(1); return nil, nil }} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if client.acknowledged.Load() { + t.Error("batch acknowledged before completion") + } + switch { + case strings.HasSuffix(r.URL.Path, "/logs"): + w.WriteHeader(200) + case r.Method == http.MethodDelete: + removals.Add(1) + w.WriteHeader(204) + default: + t.Errorf("unexpected mutation %s", r.URL.Path) + w.WriteHeader(500) + } + })) + defer server.Close() + docker, err := dockerclient.NewClientWithOpts(dockerclient.WithHost(server.URL), dockerclient.WithHTTPClient(server.Client()), dockerclient.WithVersion("1.48")) + if err != nil { + t.Fatal(err) + } + defer docker.Close() + disk := admittedDisk() + disk.read = func() (diskMeasurement, error) { + m := healthyDiskMeasurement() + m.Filesystems[0].AvailableBytes = diskInt(0) + return m, nil + } + scaler := &Scaler{disk: disk, runners: newRunnerState(), dockerClient: docker, messageClient: client, logger: slog.New(slog.DiscardHandler), config: Config{MaxRunners: 2, StatusFile: t.TempDir() + "/status.json"}} + scaler.runners.addIdle("prior-assignment", "active-id") + scaler.runners.addIdle("prewarm", "idle-id") + l, err := listener.New(diskAwareSession{Client: client, disk: disk}, listener.Config{ScaleSetID: 42, MaxRunners: 2}) + if err != nil { + t.Fatal(err) + } + if err := l.Run(context.Background(), scaler); !errors.Is(err, context.Canceled) { + t.Fatal(err) + } + if !client.acknowledged.Load() || acquisitions.Load() != 0 || removals.Load() != 1 || !scaler.runners.contains("prewarm", "idle-id") { + t.Fatal("disk block acquired an offer, interrupted cleanup, or stopped a prewarmed runner") + } + if !slices.Equal(client.pollCapacity, []int{0, 0}) { + t.Fatalf("listener advertised capacity during pressure: %v", client.pollCapacity) + } + data, err := os.ReadFile(scaler.config.StatusFile) + if err != nil { + t.Fatal(err) + } + var status controllerStatus + if err := json.Unmarshal(data, &status); err != nil { + t.Fatal(err) + } + if status.DiskAdmission.State != "low_disk" || status.DiskAdmission.Reason != "usage_percent" { + t.Fatalf("missing low-disk status: %+v", status.DiskAdmission) + } + fs := status.DiskAdmission.Filesystems[0] + if fs.CapacityBytes == nil || *fs.CapacityBytes != 1000<<30 || fs.AvailableBytes == nil || *fs.AvailableBytes != 0 { + t.Fatalf("missing disk capacity or available bytes: %+v", fs) + } + t.Logf("admission=%s reason=%s capacity_bytes=%d available_bytes=%d acquisitions=%d completed=%d", + status.DiskAdmission.State, status.DiskAdmission.Reason, *fs.CapacityBytes, *fs.AvailableBytes, acquisitions.Load(), removals.Load()) +} + +// This proves local handling of a subsequently offered ID, NOT that GitHub +// re-offers an acknowledged but unacquired job. Server liveness is a separate gate. +func TestDiskRecoveryAcquiresOnlyWhenServiceOffersAgain(t *testing.T) { + available := int64(100 << 30) + d := admittedDisk() + d.read = func() (diskMeasurement, error) { + m := healthyDiskMeasurement() + m.Filesystems[0].AvailableBytes = diskInt(available) + return m, nil + } + var calls int + client := &lifecycleBatchClient{acquireJobs: func(_ context.Context, ids []int64) ([]int64, error) { + calls++ + if len(ids) != 1 || ids[0] != 99 { + t.Fatalf("unexpected IDs %v", ids) + } + return ids, nil + }} + jit := &unavailableJitClient{} + s := &Scaler{disk: d, runners: newRunnerState(), messageClient: client, scalesetClient: jit, + logger: slog.New(slog.DiscardHandler), maintenanceLockPath: t.TempDir() + "/lock", + config: Config{MaxRunners: 1, StatusFile: t.TempDir() + "/status.json"}} + message := &scaleset.RunnerScaleSetMessage{ + Statistics: &scaleset.RunnerScaleSetStatistic{TotalAssignedJobs: 1}, + JobAvailableMessages: []*scaleset.JobAvailable{{JobMessageBase: scaleset.JobMessageBase{RunnerRequestID: 99}}}, + JobAssignedMessages: []*scaleset.JobAssigned{{}}, + } + ctx := context.Background() + if err := s.Scale(ctx, message); err != nil { + t.Fatal(err) + } + if calls != 0 || jit.calls != 0 { + t.Fatal("acquired an offer or created a runner under pressure") + } + available = 140 << 30 + if err := s.Scale(ctx, nil); err != nil { + t.Fatal(err) + } + if calls != 0 || jit.calls != 0 { + t.Fatal("admission resumed before reaching the recovery threshold") + } + available = 150 << 30 + session := diskAwareSession{Client: client, disk: d} + if _, err := session.GetMessage(ctx, 0, 1); err != nil || !slices.Equal(client.pollCapacity, []int{1}) { + t.Fatalf("configured capacity did not resume: %v, %v", client.pollCapacity, err) + } + if err := s.Scale(ctx, nil); err == nil || !strings.Contains(err.Error(), "JIT temporarily unavailable") || calls != 0 || jit.calls != 1 { + t.Fatalf("recovery failed to reconcile existing demand: acquired=%d JIT=%d error=%v", calls, jit.calls, err) + } + s.runners.addIdle("warm", "id") + if err := s.Scale(ctx, message); err != nil || calls != 1 { + t.Fatalf("re-offered job was not acquired after recovery: acquired=%d error=%v", calls, err) + } +} diff --git a/controller/lifecycle_test.go b/controller/lifecycle_test.go index d0bbca21..d19e0876 100644 --- a/controller/lifecycle_test.go +++ b/controller/lifecycle_test.go @@ -23,6 +23,7 @@ import ( type lifecycleBatchClient struct { message *scaleset.RunnerScaleSetMessage polls int + pollCapacity []int acknowledged atomic.Bool acquireJobs func(context.Context, []int64) ([]int64, error) deleteError error @@ -32,8 +33,9 @@ func (c *lifecycleBatchClient) Session() scaleset.RunnerScaleSetSession { return scaleset.RunnerScaleSetSession{SessionID: uuid.New(), Statistics: &scaleset.RunnerScaleSetStatistic{}} } -func (c *lifecycleBatchClient) GetMessage(context.Context, int, int) (*scaleset.RunnerScaleSetMessage, error) { +func (c *lifecycleBatchClient) GetMessage(_ context.Context, _, capacity int) (*scaleset.RunnerScaleSetMessage, error) { c.polls++ + c.pollCapacity = append(c.pollCapacity, capacity) if c.polls == 1 { return c.message, nil } diff --git a/controller/main.go b/controller/main.go index 9d39e024..76cd0308 100644 --- a/controller/main.go +++ b/controller/main.go @@ -89,7 +89,8 @@ func run(ctx context.Context) error { return err } - scaler := &Scaler{runners: newRunnerState(), dockerClient: docker, scalesetClient: client, logger: logger, config: cfg, scaleSetID: set.ID} + disk := newDiskAdmission(cfg.FleetInstance) + scaler := &Scaler{disk: disk, runners: newRunnerState(), dockerClient: docker, scalesetClient: client, logger: logger, config: cfg, scaleSetID: set.ID} hostname, err := os.Hostname() if err != nil { return fmt.Errorf("get hostname: %w", err) @@ -100,13 +101,14 @@ func run(ctx context.Context) error { } defer session.Close(context.Background()) scaler.messageClient = session - l, err := listener.New(session, listener.Config{ScaleSetID: set.ID, MaxRunners: cfg.MaxRunners, Logger: logger.WithGroup("listener")}) + l, err := listener.New(diskAwareSession{Client: session, disk: disk}, listener.Config{ScaleSetID: set.ID, MaxRunners: cfg.MaxRunners, Logger: logger.WithGroup("listener")}) if err != nil { return fmt.Errorf("create listener: %w", err) } if err := scaler.recoverRunners(ctx); err != nil { return err } + disk.check() scaler.writeStatus() statusTicker := time.NewTicker(time.Minute) defer statusTicker.Stop() diff --git a/controller/messages.go b/controller/messages.go index 6b5fedc5..8453f0d0 100644 --- a/controller/messages.go +++ b/controller/messages.go @@ -8,6 +8,18 @@ import ( "github.com/actions/scaleset/listener" ) +type diskAwareSession struct { + listener.Client + disk *diskAdmission +} + +func (s diskAwareSession) GetMessage(ctx context.Context, lastMessageID, maxCapacity int) (*scaleset.RunnerScaleSetMessage, error) { + if !s.disk.check() { + maxCapacity = 0 + } + return s.Client.GetMessage(ctx, lastMessageID, maxCapacity) +} + func (s *Scaler) Scale(ctx context.Context, message *scaleset.RunnerScaleSetMessage) error { if err := ctx.Err(); err != nil { return err @@ -21,7 +33,7 @@ func (s *Scaler) Scale(ctx context.Context, message *scaleset.RunnerScaleSetMess // Finish an admitted batch through cleanup, as with the previous listener. ctx = context.WithoutCancel(ctx) } - if len(message.JobAvailableMessages) > 0 { + if len(message.JobAvailableMessages) > 0 && (s.disk == nil || s.disk.check()) { if s.messageClient == nil { return fmt.Errorf("job acquisition requires a message session") } diff --git a/controller/scaler.go b/controller/scaler.go index b98f072e..6e2c2793 100644 --- a/controller/scaler.go +++ b/controller/scaler.go @@ -23,6 +23,7 @@ import ( const labelPrefix = "io.randomdevelopment.ci-fleet." type Scaler struct { + disk *diskAdmission runners runnerState dockerClient *dockerclient.Client scalesetClient interface { @@ -42,6 +43,9 @@ func (s *Scaler) HandleDesiredRunnerCount(ctx context.Context, count int) (int, defer s.writeStatus() current := s.runners.count() target := min(s.config.MaxRunners, s.config.MinRunners+count) + if target > current && s.disk != nil && !s.disk.check() { + return current, nil + } if target > current && s.config.DockerNetworksPerRunner > 0 { available, err := s.availableNetworkRunnerSlots(ctx) if err != nil { @@ -66,6 +70,9 @@ func (s *Scaler) HandleDesiredRunnerCount(ctx context.Context, count int) (int, defer lock.Close() } for i := current; i < target; i++ { + if s.disk != nil && !s.disk.check() { + break + } if _, err := s.startRunner(ctx); err != nil { return s.runners.count(), fmt.Errorf("start runner: %w", err) } diff --git a/controller/status.go b/controller/status.go index bbc268b6..10688ec6 100644 --- a/controller/status.go +++ b/controller/status.go @@ -15,12 +15,13 @@ var encodeControllerStatus = func(file *os.File, value controllerStatus) error { } type controllerStatus struct { - Controller string `json:"controller"` - SoftwareVersion string `json:"software_version"` - Current int `json:"current"` - Busy int `json:"busy"` - Maximum int `json:"maximum"` - GeneratedAt int64 `json:"generated_at"` + Controller string `json:"controller"` + SoftwareVersion string `json:"software_version"` + Current int `json:"current"` + Busy int `json:"busy"` + Maximum int `json:"maximum"` + GeneratedAt int64 `json:"generated_at"` + DiskAdmission diskAdmissionStatus `json:"disk_admission"` } func (s *Scaler) writeStatus() { @@ -28,10 +29,13 @@ func (s *Scaler) writeStatus() { defer statusWriteMu.Unlock() current, busy := s.runners.counts() softwareVersion := commitSHA - if softwareVersion == "unknown" { softwareVersion = version } + if softwareVersion == "unknown" { + softwareVersion = version + } value := controllerStatus{ Controller: s.config.FleetInstance, SoftwareVersion: softwareVersion, Current: current, Busy: busy, Maximum: s.config.MaxRunners, GeneratedAt: time.Now().Unix(), + DiskAdmission: s.disk.snapshot(), } directory := filepath.Dir(s.config.StatusFile) if err := os.MkdirAll(directory, 0o755); err != nil { @@ -48,9 +52,15 @@ func (s *Scaler) writeStatus() { if err = temporary.Chmod(0o644); err == nil { err = encodeControllerStatus(temporary, value) } - if closeErr := temporary.Close(); err == nil { err = closeErr } - if err == nil { err = os.Rename(name, s.config.StatusFile) } - if err != nil { s.logger.Warn("write controller status", "error", err) } + if closeErr := temporary.Close(); err == nil { + err = closeErr + } + if err == nil { + err = os.Rename(name, s.config.StatusFile) + } + if err != nil { + s.logger.Warn("write controller status", "error", err) + } } func (s *Scaler) publishStatus(ctx context.Context, ticks <-chan time.Time) { @@ -59,6 +69,7 @@ func (s *Scaler) publishStatus(ctx context.Context, ticks <-chan time.Time) { case <-ctx.Done(): return case <-ticks: + s.disk.check() s.writeStatus() } } diff --git a/deploy/compose.yaml b/deploy/compose.yaml index ef875a1d..447d0e04 100644 --- a/deploy/compose.yaml +++ b/deploy/compose.yaml @@ -87,6 +87,12 @@ services: - github_app_private_key volumes: - ${CI_FLEET_ROOT_PREFIX:-}/run/lock/ci-fleet:/run/ci-fleet/locks + - type: bind + source: ${CI_FLEET_ROOT_PREFIX:-}/var/lib/ci-fleet/disk-admission + target: /run/ci-fleet-disk-admission + read_only: true + bind: + create_host_path: false security_opt: - no-new-privileges:true deploy: diff --git a/docs/ADDING-A-HOST.md b/docs/ADDING-A-HOST.md index 8567f93e..e1ec3f45 100644 --- a/docs/ADDING-A-HOST.md +++ b/docs/ADDING-A-HOST.md @@ -110,6 +110,11 @@ The configuration repository credential, when required, must be read-only and ho ## 7. Prove one job +For an engine with [disk admission](DISK-ADMISSION.md), select a supporting +manager before runtime activation. After convergence, check that the capacity +timer has produced a current disk sample and that admission is ready before +dispatching the proof job. + Hosts with an existing apt-cacher-ng server may opt into [APT cache support](APT-CACHE.md) after selecting a compatible engine and manager. Keep the endpoint in root-owned host configuration. Support is disabled by default and leaves host APT settings unchanged. Confirm no runner exists while idle. Dispatch one manual, read-only job from an authorized private project and verify: diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index eea067dd..4ad9eca8 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -207,6 +207,11 @@ restarts. Raw host-root clients outside this gate and asynchronous orchestrators are outside the ordinary fleet contract. See [Network reclamation](HOST-MAINTENANCE.md#network-reclamation). +The host capacity service measures the Docker data root, runner workspace, and +upload spool. The controller reads only the protected measurement export and +uses it for [disk-pressure job admission](DISK-ADMISSION.md). Runner and project +containers have no mount for that export. + ## Update layers - Project runtime versions are controlled by project Dockerfiles. diff --git a/docs/CONTROLLER-DESIGN.md b/docs/CONTROLLER-DESIGN.md index 32e29edd..872a1e2f 100644 --- a/docs/CONTROLLER-DESIGN.md +++ b/docs/CONTROLLER-DESIGN.md @@ -50,9 +50,11 @@ Before handling a completion, the controller logs its result, runner name and ID The pinned `actions/scaleset` 0.5.0 listener calls the controller's `Scale` handler for initial statistics, each message batch, and empty polls. The handler retains the latest assigned-job count so empty polls can replace exited runners -while demand remains. It acquires available jobs before processing starts and -completions, then reconciles capacity against the reported statistics. Reacquiring -an already acquired job is a service no-op. +while demand remains. With sufficient disk headroom, it acquires available +jobs before processing starts and completions, then reconciles capacity against +the reported statistics. Reacquiring an already acquired job is a service no-op. +During a [disk admission block](DISK-ADMISSION.md), it advertises zero capacity, +skips acquisition and runner creation, and continues processing callbacks. The listener acknowledges a batch only after the handler succeeds. An acquisition, callback, cleanup or acknowledgment failure stops the listener and leaves the diff --git a/docs/DISK-ADMISSION.md b/docs/DISK-ADMISSION.md new file mode 100644 index 00000000..33092832 --- /dev/null +++ b/docs/DISK-ADMISSION.md @@ -0,0 +1,112 @@ +# Disk-pressure job admission + +The controller checks disk headroom before advertising capacity to GitHub, +acquiring a job offer, and creating a runner. While blocked, it polls with a +maximum capacity of zero and continues processing job starts, completions, +and cleanup. It leaves existing runners alone. The configured maximum takes +effect again after the disk check recovers. See [issue #166](https://github.com/RandomDevelopment/ci-fleet/issues/166). + +## Limits and recovery + +A stop condition on any monitored filesystem blocks admission. Recovery +requires all three recovery limits on every monitored filesystem. + +| Measurement | Stop | Resume | +| --- | --- | --- | +| Unavailable bytes as a share of capacity | At least 90% | At most 85% | +| Available bytes | Below 10 GiB | At least 15 GiB | +| Inode use | At least 90% | At most 85% | + +Missing, invalid, or stale evidence also blocks admission. A controller restart +requires the recovery limits. After recovery, a worker stays eligible until it +hits a stop condition or loses valid evidence. + +Capacity uses `f_blocks * f_frsize`. Available bytes use `f_bavail * f_frsize`, +which excludes space reserved for root. The percentage is +`(capacity - available) / capacity`. Inode use is +`(f_files - f_ffree) / f_files`. The 10 GiB floor allows for two 1 GiB Docker +build-context uploads with 8 GiB left for other activity. The 5 GiB and +five-percentage-point recovery margins reduce repeated stop and resume cycles. +These are initial reserves. Measure concurrent workspace and build growth +before treating them as sufficient for a particular worker. The guard reserves +no bytes per job. Running jobs can continue consuming space. + +The [storage retention policy](HOST-MAINTENANCE.md#docker-storage-retention) and +the installer's below-80% upgrade check have their own thresholds. A disk +admission block leaves both policies in effect. + +## Local status + +On a managed worker, use the controller's existing local status file. + +```bash +sudo docker exec ci-fleet-controller-1 cat /run/ci-fleet/status.json | + jq -e '.disk_admission' +``` + +`low_disk` gives the triggering threshold. Check each entry in `filesystems` for +its roles, capacity, available bytes, and inode counts. Roles that share a +filesystem share one entry. `blocked` with reason `recovering` means at least +one recovery limit still fails. `unknown` means the evidence cannot establish +headroom. Unknown counters use null. A stale sample can retain historical +counters with reason `measurement_stale`; publishing status leaves the +measurement timestamp intact. `ready` means disk admission is open. Existing +runner capacity, network and maintenance controls still apply. + +The status is local to the controller. [Endpoint snapshots](ENDPOINT-SNAPSHOTS.md) +and [outbound status reports](STATUS-REPORTING.md) use their existing schemas. + +## Measurement and installation + +The existing capacity timer attempts a disk sample every 30 seconds, including +when the worker has no runners. Capacity history still records active-runner +samples. The host sampler reads Docker's data root and the backing filesystems +for the standard runner workspace and Docker proxy upload spool. It supports +the local `overlay2` driver and the containerd `overlayfs` snapshotter, including +a snapshotter on a separate filesystem. An unsupported driver, an unexpected +mount, or a failed inspection yields unknown evidence for affected roles. + +The manager prepares a root-owned export. Compose mounts only that directory, +read-only, into the controller. The export includes the controller identity and +kernel boot ID to reject evidence from another controller or boot. Controller +status contains neither the boot ID nor host paths. The controller rejects +measurements over 75 seconds old or dated in the future. Sample timing depends +on the host and sampler completion. An in-flight poll or acquisition can race +a change in headroom. + +Use a manager that supports the disk export before selecting a runtime that +requires it. Initial health and timer startup can succeed before the first +measurement allows jobs. Check the local admission status after convergence. +A successful rollback to an older engine restores that engine's admission +behavior. Updated managers remove their export after a successful downgrade +or uninstall. + +## GitHub service behavior to verify before rollout + +The pinned [scale-set listener](https://github.com/actions/scaleset/blob/v0.5.0/listener/listener.go) +allows zero advertised capacity and acknowledges a batch after its handler +succeeds. The controller skips `AcquireJobs` during a disk block, including +when an offer arrives in a poll that started before the block. The listener +can still acknowledge that batch after completing its other work. GitHub's +[SDK documentation](https://github.com/actions/scaleset/blob/v0.5.0/README.md#message-acknowledgment) +describes replay of unacknowledged messages. Whether GitHub re-offers an +acknowledged, unacquired job after recovery remains an +[open upstream question](https://github.com/actions/scaleset/issues/107#issuecomment-6759846997). + +GitHub can also send `JobAssigned` directly and dispatch work to a registered +runner. The controller blocks new runner creation during pressure, but cannot +recall a job GitHub has already assigned. Verify that zero-capacity polling +prevents new direct assignments to a prewarmed worker. Also verify that work +queued across a pressure transition runs after recovery, including the case +where an offer arrives in an in-flight poll. A fake service can verify local +polling, completion, and recovery behavior. The GitHub routing and re-offer +cases need service evidence before rollout. + +Use [exact-source and base validation](LOCAL-VALIDATION.md) for engine checks. +A disposable worker used to prove admission also needs at least 15 GiB +available on each monitored filesystem at startup, with enough additional +headroom to meet the 85% limits and run the workload. Cover cold startup with +zero runners, prewarmed runners, both supported storage layouts, and recovery +after active-job completion. Verify scoped cleanup for success, failure, +cancellation, and timeout. [Template issue #49](https://github.com/RandomDevelopment/ci-fleet-config-template/issues/49) +tracks adoption guidance pending the engine change. diff --git a/docs/DISK-PRESSURE-OBSERVATION.md b/docs/DISK-PRESSURE-OBSERVATION.md index f8d6cbfa..e42159bc 100644 --- a/docs/DISK-PRESSURE-OBSERVATION.md +++ b/docs/DISK-PRESSURE-OBSERVATION.md @@ -5,8 +5,9 @@ engine `a56fad2c47bf6b3f80e839af69615a2b42fc1461`. This document adds no produce snapshot field, collector, UI, threshold, or host authorization. The proposed [#166](https://github.com/RandomDevelopment/ci-fleet/issues/166) admission producer and its enforcement guarantees require separate implementation and review. -Update or supersede this base-pinned inventory when #166 is integrated; approval -to implement a candidate does not establish acceptance or deployment. +For the #166 implementation, see [disk-pressure job admission](DISK-ADMISSION.md). +This base-pinned inventory records the earlier evidence and the boundaries of the +existing snapshot and outbound report contracts. ## Reuse the existing evidence diff --git a/docs/HEALTH-MONITORING.md b/docs/HEALTH-MONITORING.md index ed2a489a..d8bc13fd 100644 --- a/docs/HEALTH-MONITORING.md +++ b/docs/HEALTH-MONITORING.md @@ -56,6 +56,14 @@ remove networks, cancel jobs, or change capacity in desired state. Frequent orphan reconciliation and consumer-label migrations remain later issue #81 work. Cleanup stays label-scoped and never uses blind Docker prune. +## Disk admission + +Use the controller's local [disk admission status](DISK-ADMISSION.md#local-status) +to see why it has stopped accepting work. The capacity timer measures the +workspace, Docker storage, and upload spool while the controller is idle or +busy. The admission thresholds are fixed in the engine. The health warning +thresholds below still control host alerts. + ## Threshold overrides and hooks Defaults are intentionally conservative: disk and inode warning/critical at 80/90%, available memory warning/critical at 15/8%, sustained swap use under five-minute memory pressure warning/critical at 25/50%, per-CPU fifteen-minute load warning/critical at 1.0/1.5, and controller restart warning at 3. diff --git a/scripts/capacity-sample.sh b/scripts/capacity-sample.sh index a8e1461c..7753be53 100755 --- a/scripts/capacity-sample.sh +++ b/scripts/capacity-sample.sh @@ -13,4 +13,15 @@ set -a # shellcheck disable=SC1090 . "$environment" set +a -exec python3 "$script_dir/health.py" "${args[@]}" +# Admission measurements also run while idle. Keep the existing capacity history +# independent: a failed/terminated disk probe must not suppress its collection. +disk_args=() +if [[ ${CI_FLEET_TESTING:-0} == 1 && -n ${CI_FLEET_ROOT_PREFIX:-} ]]; then + disk_args+=(--output "$CI_FLEET_ROOT_PREFIX/var/lib/ci-fleet/disk-admission") +fi +disk_result=0 +history_result=0 +timeout --kill-after=1s 15s python3 "$script_dir/disk_admission_sample.py" "${disk_args[@]}" || disk_result=$? +python3 "$script_dir/health.py" "${args[@]}" || history_result=$? +((history_result == 0)) || exit "$history_result" +exit "$disk_result" diff --git a/scripts/disk_admission_sample.py b/scripts/disk_admission_sample.py new file mode 100644 index 00000000..8d013631 --- /dev/null +++ b/scripts/disk_admission_sample.py @@ -0,0 +1,320 @@ +#!/usr/bin/env python3 +"""Narrow host-only disk measurement export; never performs Docker mutations.""" +from __future__ import annotations + +import argparse +import fcntl +import json +import os +from pathlib import Path +import re +import stat +import subprocess +import sys +import time + +sys.dont_write_bytecode = True + +import endpoint_snapshot_store as store + +OUTPUT = Path("/var/lib/ci-fleet/disk-admission") +BUDGET_SECONDS = 12 +MAX_BYTES = 16384 +ROLES = ("workspace", "docker", "spool") +INSTANCE_PATTERN = re.compile(r"^[a-z0-9][a-z0-9-]{0,62}$") + + +def require(condition: bool) -> None: + if not condition: + raise ValueError("disk_measurement_unavailable") + + +def prepare(path: Path, *, create: bool = True) -> int: + """Pin ancestry; only installer preparation may create the private directory.""" + parent = store._open_directory(path.parent) + try: + if create: + try: + os.mkdir(path.name, 0o700, dir_fd=parent) + except FileExistsError: + pass + descriptor = os.open(path.name, store.DIRECTORY_FLAGS, dir_fd=parent) + finally: + os.close(parent) + try: + meta = os.fstat(descriptor) + require(meta.st_uid == store.OWNER_UID and stat.S_IMODE(meta.st_mode) == 0o700) + store._no_acl(descriptor, "unsafe_path") + return descriptor + except BaseException: + os.close(descriptor) + raise + + +def lock_export(directory: int, *, removing: bool = False) -> None: + # Sampling never overlaps. Removal may need the already-running old sampler + # to finish after a successful downgrade; retain a bounded failure outcome. + deadline = time.monotonic() + (20 if removing else 0) + while True: + try: + fcntl.flock(directory, fcntl.LOCK_EX | fcntl.LOCK_NB) + return + except BlockingIOError: + remaining = deadline - time.monotonic() + if remaining <= 0: + raise + time.sleep(min(0.1, remaining)) + + +def validate_entries(directory: int) -> None: + for name in os.listdir(directory): + require(name in {"measurement.json", "measurement.json.tmp"}) + meta = os.stat(name, dir_fd=directory, follow_symlinks=False) + store._regular(meta, modes=(0o600,), max_bytes=MAX_BYTES, gid=0) + fd = os.open(name, store.READ_FLAGS, dir_fd=directory) + try: + store._no_acl(fd, "unsafe_file") + finally: + os.close(fd) + + +def publish(directory: int, value: dict) -> None: + data = (json.dumps(value, separators=(",", ":"), allow_nan=False) + "\n").encode() + require(len(data) <= MAX_BYTES) + validate_entries(directory) + try: + os.unlink("measurement.json.tmp", dir_fd=directory) + except FileNotFoundError: + pass + fd = os.open("measurement.json.tmp", os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600, dir_fd=directory) + try: + with os.fdopen(fd, "wb") as handle: + handle.write(data) + handle.flush() + os.fsync(handle.fileno()) + os.replace("measurement.json.tmp", "measurement.json", src_dir_fd=directory, dst_dir_fd=directory) + os.fsync(directory) + finally: + try: + os.unlink("measurement.json.tmp", dir_fd=directory) + except FileNotFoundError: + pass + + +def unknown(role: str) -> dict: + return dict(roles=[role], observed_at=None, capacity_bytes=None, available_bytes=None, + total_inodes=None, free_inodes=None, state="unknown", reason="measurement_unavailable") + + +def read_small(path: Path, limit: int = 1024 * 1024) -> str: + with path.open("rb") as handle: + value = handle.read(limit + 1) + require(len(value) <= limit) + return value.decode("utf-8") + + +def unescape_mount(value: str) -> str: + return re.sub(r"\\([0-7]{3})", lambda match: chr(int(match[1], 8)), value) + + +def backing_path(mountinfo: str, driver: str, docker_root: str, role_path: str) -> tuple[Path, Path]: + """Only standard local overlay stores are admitted; never guess a root.""" + mounts = [] + for line in mountinfo.splitlines(): + left, right = line.split(" - ", 1) + fields, details = left.split(), right.split() + require(len(fields) >= 6 and len(details) >= 3) + mountpoint = unescape_mount(fields[4]) + if role_path == mountpoint or role_path.startswith(mountpoint.rstrip("/") + "/"): + mounts.append((mountpoint, details)) + require(bool(mounts)) + mountpoint, details = max(mounts, key=lambda item: len(item[0])) + require(mountpoint == "/" and details[0] == "overlay") + options = dict(option.split("=", 1) for option in details[2].split(",") if "=" in option) + upper = Path(unescape_mount(options.get("upperdir", ""))) + require(upper.is_absolute() and ".." not in upper.parts) + if driver == "overlay2": + base = Path(docker_root) / "overlay2" + relative = upper.relative_to(base) + require(len(relative.parts) == 2 and relative.parts[-1] == "diff") + elif driver == "overlayfs": + # Docker's containerd snapshotter may live outside DockerRootDir. Obtain + # its actual tree from kernel evidence, not a /var/lib/containerd guess. + marker = "io.containerd.snapshotter.v1.overlayfs" + require(upper.parts.count(marker) == 1) + index = upper.parts.index(marker) + require(upper.parts[index + 1] == "snapshots" and len(upper.parts[index:]) == 4 + and upper.parts[-1] == "fs" and upper.parts[-2].isdigit()) + base = Path(*upper.parts[:index + 2]) + else: + raise ValueError("unsupported_storage_driver") + return upper, base + + +def validate_host_mounts(mountinfo: str, driver: str, base: Path) -> None: + """Allow normal overlay2 merged views, never overrides of writable backing.""" + for line in mountinfo.splitlines(): + left, right = line.split(" - ", 1) + fields, details = left.split(), right.split() + require(len(fields) >= 6 and len(details) >= 3) + target = Path(unescape_mount(fields[4])) + if base not in target.parents: + continue + relative = target.relative_to(base) + require(driver == "overlay2" and len(relative.parts) == 2 + and relative.parts[1] == "merged" and fields[3] == "/" + and details[0] == "overlay") + options = dict(option.split("=", 1) for option in details[2].split(",") if "=" in option) + require(unescape_mount(options.get("upperdir", "")) == str(base / relative.parts[0] / "diff")) + + +class Collector: + def __init__(self) -> None: + self.deadline = time.monotonic() + BUDGET_SECONDS + + def remaining(self) -> float: + remaining = self.deadline - time.monotonic() + require(remaining > 0) + return remaining + + def docker(self, *arguments: str): + # Fixed local socket, not an inherited remote Docker context. All errors + # remain local and are reduced to controlled unknown values on export. + result = subprocess.run(["docker", "--host", "unix:///var/run/docker.sock", *arguments], + capture_output=True, timeout=self.remaining(), check=False) + require(result.returncode == 0 and len(result.stdout) <= 1024 * 1024) + return json.loads(result.stdout) + + def inspect(self, service: str) -> dict: + value = self.docker("inspect", "--format", + '{"id":{{json .Id}},"pid":{{json .State.Pid}},"running":{{json .State.Running}},' + '"started":{{json .State.StartedAt}},"labels":{{json .Config.Labels}},"mounts":{{json .Mounts}}}', + "ci-fleet-" + service + "-1") + require(isinstance(value, dict) and isinstance(value.get("labels"), dict) + and isinstance(value.get("mounts"), list)) + require(isinstance(value.get("id"), str) and bool(value["id"]) + and isinstance(value.get("started"), str) and bool(value["started"])) + require(value["running"] is True and type(value["pid"]) is int and value["pid"] > 0) + for mount in value["mounts"]: + require(isinstance(mount, dict) and isinstance(mount.get("Destination"), str)) + require(value["labels"].get("com.docker.compose.project") == "ci-fleet" + and value["labels"].get("com.docker.compose.service") == service) + return value + + def backing(self, service: str, driver: str, docker_root: str, role_path: str) -> tuple[Path, Path]: + before = self.inspect(service) + process = Path("/proc") / str(before["pid"]) + first = read_small(process / "stat", 4096) + mounts = read_small(process / "mountinfo") + path, base = backing_path(mounts, driver, docker_root, role_path) + # The standard runner and proxy images use their writable layers, with + # no workspace/spool volume. Refuse an unexpected mounted role instead. + for mount in before["mounts"]: + destination = mount["Destination"].rstrip("/") + require(not (role_path == destination or role_path.startswith(destination + "/"))) + last = read_small(process / "stat", 4096) + require(first.rsplit(")", 1)[1].split()[19] == last.rsplit(")", 1)[1].split()[19]) + after = self.inspect(service) + require((before["id"], before["pid"], before["started"]) == (after["id"], after["pid"], after["started"])) + # Reject per-snapshot mount overrides: the standard global store must + # place future runner writable layers on this same backing filesystem. + host_mounts = read_small(Path("/proc/self/mountinfo")) + validate_host_mounts(host_mounts, driver, base) + require(os.stat(path).st_dev == os.stat(base).st_dev) + self.remaining() + return path, base + + def collect(self, instance: str) -> dict: + boot = read_small(Path("/proc/sys/kernel/random/boot_id"), 128).strip() + require(bool(re.fullmatch(r"[0-9a-f-]{36}", boot))) + values = {role: unknown(role) for role in ROLES} + paths = {} + try: + info = self.docker("info", "--format", '{"root":{{json .DockerRootDir}},"driver":{{json .Driver}}}') + root, driver = info["root"], info["driver"] + require(isinstance(root, str) and root.startswith("/") and ".." not in Path(root).parts) + paths["docker"] = Path(root) + # No runner is required at MIN=0. The controller demonstrates the + # daemon's global writable-layer store; Scaler creates runner work + # in that store without workspace mounts or image-declared volumes. + volumes = self.docker("image", "inspect", "--format", "{{json .Config.Volumes}}", os.environ["CI_FLEET_RUNNER_RUNTIME_IMAGE_ID"]) + require(volumes in (None, {})) + workspace, base = self.backing("controller", driver, root, "/home/runner/_work") + spool, spool_base = self.backing("docker-socket-proxy", driver, root, "/tmp") + require(base == spool_base) + paths.update(workspace=workspace, spool=spool) + except (OSError, ValueError, KeyError, TypeError, IndexError, subprocess.SubprocessError): + pass + groups = {} + for role in ROLES: + try: + path = paths[role] + self.remaining() + descriptor = os.open(path, os.O_RDONLY | os.O_DIRECTORY | os.O_CLOEXEC) + try: + fs, meta = os.fstatvfs(descriptor), os.fstat(descriptor) + finally: + os.close(descriptor) + capacity, available = fs.f_blocks * fs.f_frsize, fs.f_bavail * fs.f_frsize + require(0 < capacity < 2**63 and 0 <= available <= capacity + and 0 < fs.f_files < 2**63 and 0 <= fs.f_ffree <= fs.f_files) + self.remaining() + if meta.st_dev in groups: + groups[meta.st_dev]["roles"].append(role) + else: + groups[meta.st_dev] = dict(roles=[role], observed_at=int(time.time()), + capacity_bytes=capacity, available_bytes=available, total_inodes=fs.f_files, + free_inodes=fs.f_ffree, state="measured", reason="measured") + del values[role] + except (OSError, ValueError, KeyError): + pass + return dict(schema_version=1, boot_id=boot, controller=instance, + filesystems=[*groups.values(), *values.values()]) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, default=OUTPUT) + lifecycle = parser.add_mutually_exclusive_group() + lifecycle.add_argument("--prepare", action="store_true") + lifecycle.add_argument("--remove", action="store_true") + args = parser.parse_args() + descriptor = None + try: + if args.remove and not args.output.exists() and not args.output.is_symlink(): + return 0 + descriptor = prepare(args.output, create=args.prepare) + # Existing directory preparation only validates protected metadata. It + # neither changes entries nor needs the sampler's publication lock. + if args.prepare and not args.remove: + return 0 + lock_export(descriptor, removing=args.remove) + if args.remove: + # Validate the entire allowlist before removing either owned entry. + validate_entries(descriptor) + for name in ("measurement.json.tmp", "measurement.json"): + try: + os.unlink(name, dir_fd=descriptor) + except FileNotFoundError: + pass + args.output.rmdir() + elif not args.prepare: + instance = os.environ.get("CI_FLEET_INSTANCE", "") + require(bool(INSTANCE_PATTERN.fullmatch(instance))) + value = Collector().collect(instance) + publish(descriptor, value) + if any(fs["state"] == "unknown" for fs in value["filesystems"]): + print("DISK_ADMISSION_SAMPLE unknown") + return 1 + print("DISK_ADMISSION_SAMPLE measured") + return 0 + except (OSError, ValueError, KeyError, TypeError, subprocess.SubprocessError): + print("DISK_ADMISSION_SAMPLE unavailable") + return 1 + finally: + if descriptor is not None: + os.close(descriptor) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/scripts/install-worker-controller.sh b/scripts/install-worker-controller.sh index 35e4da2c..3cff005e 100755 --- a/scripts/install-worker-controller.sh +++ b/scripts/install-worker-controller.sh @@ -2008,6 +2008,21 @@ else: PY } +prepare_disk_admission_export() { + local source=$1 + if [[ -f "$source/scripts/disk_admission_sample.py" ]]; then + python3 "$source/scripts/disk_admission_sample.py" --prepare --output "$state_root/disk-admission" + fi +} + +remove_disk_admission_export() { + # This manager's helper removes only its protected, allowlisted export. Never + # delete capacity history merely because an engine predates disk admission. + if [[ -f "$repo_root/scripts/disk_admission_sample.py" ]]; then + python3 "$repo_root/scripts/disk_admission_sample.py" --remove --output "$state_root/disk-admission" + fi +} + activate_candidate() { local check_health=${1:-true} staged_state restore_reviewed_image_tags "$candidate_env" || die 'verified candidate image publication failed' @@ -2034,6 +2049,7 @@ PY chmod 0600 "$staged_state" mv -f "$staged_state" "$state_file" if [[ "$target_state" == active ]]; then + prepare_disk_admission_export "$release_dir" || die 'disk admission export preparation failed' compose "$release_dir" "$rendered_env" up -d --remove-orphans controller sleep "${CI_FLEET_STARTUP_WAIT_SECONDS:-2}" runtime_matches active || die 'controller did not remain running after activation' @@ -2581,7 +2597,8 @@ PY if [[ $(managed_runner_count) != 0 ]]; then failed=1 else - compose "$release_dir" "$rendered_env" up -d --remove-orphans controller || failed=1 + prepare_disk_admission_export "$release_dir" || failed=1 + if ((failed == 0)); then compose "$release_dir" "$rendered_env" up -d --remove-orphans controller || failed=1; fi if ((failed == 0)); then run_health_check "$release_dir" "$rendered_env" true || failed=1; fi fi fi @@ -2968,6 +2985,7 @@ perform_converge() { transaction_active=false trap on_term TERM if ((policy_status == 0)); then + if [[ ! -f "$release_dir/scripts/disk_admission_sample.py" ]]; then remove_disk_admission_export; fi note "CONVERGED mode=$mode controller=$controller_id config_ref=$config_ref engine_ref=$engine_ref state=$target_state" return fi @@ -2997,6 +3015,7 @@ perform_converge() { activate_candidate transaction_active=false if [[ ! -x "$release_dir/scripts/capacity-sample.sh" ]]; then remove_capacity_history; fi + if [[ ! -f "$release_dir/scripts/disk_admission_sample.py" ]]; then remove_disk_admission_export; fi note "CONVERGED mode=$mode controller=$controller_id config_ref=$config_ref engine_ref=$engine_ref state=$target_state" } @@ -3021,6 +3040,7 @@ perform_rollback() { transaction_started=true restore_checkpoint || die 'checkpoint restoration failed' if [[ ! -x "$release_dir/scripts/capacity-sample.sh" ]]; then remove_capacity_history; fi + if [[ ! -f "$release_dir/scripts/disk_admission_sample.py" ]]; then remove_disk_admission_export; fi note "ROLLBACK_OK checkpoint=$checkpoint_dir" } @@ -3081,6 +3101,7 @@ perform_uninstall() { rm -f "$manager_current" transaction_active=false remove_capacity_history + remove_disk_admission_export note "UNINSTALL_OK host_config_preserved=$host_config secrets_preserved=$etc_dir/secrets" } @@ -3142,6 +3163,7 @@ case "$mode" in transaction_started=true restore_checkpoint || die 'last-known-good checkpoint restoration failed' if [[ ! -x "$release_dir/scripts/capacity-sample.sh" ]]; then remove_capacity_history; fi + if [[ ! -f "$release_dir/scripts/disk_admission_sample.py" ]]; then remove_disk_admission_export; fi note "ROLLBACK_OK checkpoint=$checkpoint_dir" write_transaction_result applied exit 0 diff --git a/scripts/test-capacity-unit-stop.sh b/scripts/test-capacity-unit-stop.sh index 338dc5fc..cf746f20 100755 --- a/scripts/test-capacity-unit-stop.sh +++ b/scripts/test-capacity-unit-stop.sh @@ -34,9 +34,11 @@ printf 'CAPACITY_UNIT_STOP_TESTS_OK\n' { printf 'set -Eeuo pipefail\n' sed -n '/^remove_capacity_history() {/,/^}/p' "$repo_root/scripts/install-worker-controller.sh" + sed -n '/^remove_disk_admission_export() {/,/^}/p' "$repo_root/scripts/install-worker-controller.sh" sed -n '/^perform_uninstall() {/,/^}/p' "$repo_root/scripts/install-worker-controller.sh" cat <<'TEST' state_root=$1/state +repo_root=$2 current_link=$1/current manager_current=$1/manager-current rendered_env=$1/env @@ -46,6 +48,7 @@ host_config=fixture etc_dir=$1/etc mkdir -p "$state_root/capacity" "$state_root/health" printf 'retained observations\n' >"$state_root/capacity/samples.jsonl" +python3 "$repo_root/scripts/disk_admission_sample.py" --prepare --output "$state_root/disk-admission" load_installed_controller_identity() { :; } controller_status() { :; } manager_release_from_raw_pointer() { :; } @@ -62,16 +65,17 @@ rm() { } transaction_active=false fail_manager_removal=true -trap '[[ $transaction_active == true && -f $state_root/capacity/samples.jsonl ]] || exit 99; exit 7' ERR +trap '[[ $transaction_active == true && -f $state_root/capacity/samples.jsonl && -d $state_root/disk-admission ]] || exit 99; exit 7' ERR perform_uninstall TEST } >"$temporary/uninstall.sh" status=0 -bash "$temporary/uninstall.sh" "$temporary" || status=$? +bash "$temporary/uninstall.sh" "$temporary" "$repo_root" || status=$? [[ $status == 7 ]] || { printf 'FAIL: uninstall removed capacity history before commit, status=%s\n' "$status" >&2; exit 1; } sed -i 's/fail_manager_removal=true/fail_manager_removal=false/' "$temporary/uninstall.sh" -bash "$temporary/uninstall.sh" "$temporary" +bash "$temporary/uninstall.sh" "$temporary" "$repo_root" [[ ! -e $temporary/state/capacity ]] || { printf 'FAIL: committed uninstall retained capacity history\n' >&2; exit 1; } +[[ ! -e $temporary/state/disk-admission ]] || { printf 'FAIL: committed uninstall retained disk admission export\n' >&2; exit 1; } printf 'CAPACITY_UNINSTALL_TRANSACTION_TESTS_OK\n' mkdir -p "$temporary/outside/capacity" diff --git a/scripts/test-install-worker-controller.sh b/scripts/test-install-worker-controller.sh index e2417320..ebfea8cd 100755 --- a/scripts/test-install-worker-controller.sh +++ b/scripts/test-install-worker-controller.sh @@ -59,8 +59,9 @@ git -C "$fixture_repo" add -A git -C "$fixture_repo" -c user.name=fixture -c user.email=fixture@invalid.example commit -qm 'test: model opaque runtime sources' fake_bin=$tmp/bin mkdir -p "$fake_bin" -export REAL_STAT -REAL_STAT=$(command -v stat) +# The installer passes only FAKE_* fixture variables into Compose. +export FAKE_REAL_STAT +FAKE_REAL_STAT=$(command -v stat) export REAL_TAR REAL_TAR=$(command -v tar) export REAL_GIT @@ -327,6 +328,13 @@ case "${1:-}" in fi case "$command" in up) + if grep -Fq 'target: /run/ci-fleet-disk-admission' "$compose_file"; then + export_dir=${CI_FLEET_ROOT_PREFIX:?}/var/lib/ci-fleet/disk-admission + if [[ -L "$export_dir" || ! -d "$export_dir" || $(stat -c '%u:%a' "$export_dir") != 0:700 ]]; then + printf 'disk admission export was not prepared before Compose startup\n' >&2 + exit 49 + fi + fi [[ -z ${FAKE_PROXY_STATE:-} ]] || : >"$FAKE_PROXY_STATE" controller_image=$(awk -F= '$1 == "CI_FLEET_CONTROLLER_IMAGE" {print substr($0, index($0, "=") + 1)}' "$env_file") "$0" image inspect --format '{{.Id}}' "$controller_image" >/dev/null 2>&1 || { @@ -496,7 +504,7 @@ if [[ -n "${FAKE_WRONG_SOURCE_INSTALLER_OWNER:-}" && "${1:-}" == -c && "${2:-}" printf '99999\n' exit 0 fi -exec "$REAL_STAT" "$@" +exec "$FAKE_REAL_STAT" "$@" EOF chmod 700 "$fake_bin/docker" "$fake_bin/systemctl" "$fake_bin/stat" diff --git a/scripts/test_disk_admission_sample.py b/scripts/test_disk_admission_sample.py new file mode 100644 index 00000000..750bc2d2 --- /dev/null +++ b/scripts/test_disk_admission_sample.py @@ -0,0 +1,344 @@ +#!/usr/bin/env python3 +"""Unprivileged fixtures: no daemon, host proc probing, services or mounts.""" +import json +import os +from pathlib import Path +import subprocess +import tempfile +import threading +import types +import unittest +from unittest.mock import patch + +import disk_admission_sample as sample + + +def mounts(upper, extra=""): + return f"10 1 0:10 / / rw - overlay overlay rw,lowerdir=/lower,upperdir={upper},workdir=/work\n" + extra + + +class MappingTests(unittest.TestCase): + def test_instance_pattern_matches_managed_controller_keys(self): + schema = json.loads((Path(__file__).resolve().parent.parent / "templates/config-repository/fleet.schema.json").read_text()) + self.assertEqual(schema["properties"]["controllers"]["propertyNames"], {"$ref": "#/$defs/slug"}) + self.assertEqual(sample.INSTANCE_PATTERN.pattern, schema["$defs"]["slug"]["pattern"]) + for value in ("example", "1", "a" * 63, "example-2"): + self.assertIsNotNone(sample.INSTANCE_PATTERN.fullmatch(value)) + for value in ("", "A", "a_b", "a.b", "-example", "a" * 64, "example\n"): + self.assertIsNone(sample.INSTANCE_PATTERN.fullmatch(value)) + + def test_classic_store_and_split_containerd_store_without_runner(self): + upper, base = sample.backing_path(mounts("/docker/overlay2/id/diff"), "overlay2", "/docker", "/home/runner/_work") + self.assertEqual((str(upper), str(base)), ("/docker/overlay2/id/diff", "/docker/overlay2")) + upper, base = sample.backing_path(mounts("/snapshots/io.containerd.snapshotter.v1.overlayfs/snapshots/12/fs"), "overlayfs", "/separate/docker", "/tmp") + self.assertEqual(str(base), "/snapshots/io.containerd.snapshotter.v1.overlayfs/snapshots") + self.assertNotIn("/separate/docker", str(upper)) + + def test_uncertain_mappings_never_fall_back_to_root(self): + for text, driver in [(mounts("/elsewhere/diff"), "overlay2"), + (mounts("/docker/overlay2/id/diff"), "vfs"), + (mounts("/docker/overlay2/id/diff", "11 10 0:11 / /tmp rw - tmpfs tmpfs rw\n"), "overlay2"), + ("10 1 8:1 / / rw - ext4 /dev/test rw\n", "overlay2"), + (mounts("/docker/overlay2/../diff"), "overlay2")]: + with self.subTest(text=text), self.assertRaises((ValueError, IndexError)): + sample.backing_path(text, driver, "/docker", "/tmp") + + def test_roles_same_device_grouped_and_failures_remain_null(self): + class FakeCollector(sample.Collector): + def docker(self, *args): + if args[0] == "info": + return {"root": "/docker", "driver": "overlay2"} + if args[0] == "image": + assert args[-1] == "sha256:" + "a" * 64 + return None + raise AssertionError(args) + def backing(self, service, *args): + return Path("/fixture"), Path("/same-store") + statfs = types.SimpleNamespace(f_blocks=100, f_frsize=1024**3, f_bavail=40, f_files=1000, f_ffree=800) + with patch.dict(os.environ, CI_FLEET_RUNNER_IMAGE="different-tag", CI_FLEET_RUNNER_RUNTIME_IMAGE_ID="sha256:" + "a" * 64), patch.object(sample, "read_small", return_value="11111111-1111-4111-8111-111111111111"), patch.object(sample.os, "open", return_value=123), patch.object(sample.os, "close"), patch.object(sample.os, "fstat", return_value=types.SimpleNamespace(st_dev=9)), patch.object(sample.os, "fstatvfs", return_value=statfs): + result = FakeCollector().collect("example") + self.assertEqual(len(result["filesystems"]), 1) + self.assertEqual(result["filesystems"][0]["roles"], list(sample.ROLES)) + self.assertEqual(result["filesystems"][0]["available_bytes"], 40 * 1024**3) + self.assertNotIn("fixture", json.dumps(result)) + with patch.object(FakeCollector, "backing", side_effect=ValueError): + result = FakeCollector().collect("example") + by_role = {role: fs for fs in result["filesystems"] for role in fs["roles"]} + self.assertEqual(by_role["docker"]["state"], "measured") + for role in ("workspace", "spool"): + self.assertEqual(by_role[role]["state"], "unknown") + self.assertIsNone(by_role[role]["capacity_bytes"]) + self.assertIsNone(by_role[role]["observed_at"]) + + def test_pid_recreation_reuse_and_override_refused(self): + before = dict(id="id", pid=1, started="start", running=True, mounts=[]) + # /proc stat starttime is field22 (index19 after the comm closing ')'). + process = "1 (fixture) " + " ".join(["0"] * 19 + ["10"]) + def reads(path, *args): + if path.name == "stat": + return process + return mounts("/docker/overlay2/id/diff") + collector = sample.Collector() + for changed in ({**before, "id": "other"}, {**before, "pid": 2}, {**before, "started": "new"}): + with patch.object(collector, "inspect", side_effect=[before, changed]), patch.object(sample, "read_small", side_effect=reads), self.assertRaises(ValueError): + collector.backing("controller", "overlay2", "/docker", "/home/runner/_work") + with patch.object(collector, "inspect", return_value=before), patch.object(sample, "read_small", side_effect=[process, mounts("/docker/overlay2/id/diff"), process[:-2]+"20", process[:-2]+"20"]), self.assertRaises(ValueError): + collector.backing("controller", "overlay2", "/docker", "/home/runner/_work") + with patch.object(collector, "inspect", return_value={**before, "mounts": [{"Destination": "/tmp"}]}), patch.object(sample, "read_small", side_effect=reads), self.assertRaises(ValueError): + collector.backing("docker-socket-proxy", "overlay2", "/docker", "/tmp") + + def test_complete_classic_mapping_accepts_merged_views_not_backing_overrides(self): + identities = {"controller": (101, "controller-id"), "docker-socket-proxy": (102, "proxy-id")} + class FakeDaemon(sample.Collector): + def docker(self, *args): + if args[0] == "info": + return {"root": "/docker", "driver": "overlay2"} + if args[0] == "image": + return None + service = "controller" if args[-1] == "ci-fleet-controller-1" else "docker-socket-proxy" + pid, identifier = identities[service] + return dict(id=identifier, pid=pid, started="start", running=True, mounts=[], + labels={"com.docker.compose.project": "ci-fleet", "com.docker.compose.service": service}) + host = "1 0 8:1 / / rw - ext4 /dev/fixture rw\n" + for identifier in ("controller-id", "proxy-id", "existing-job"): + host += f"10 1 0:10 / /docker/overlay2/{identifier}/merged rw - overlay overlay rw,upperdir=/docker/overlay2/{identifier}/diff\n" + process = "101 (fixture) " + " ".join(["0"] * 19 + ["10"]) + def reads(path, *args): + if path.name == "boot_id": + return "11111111-1111-4111-8111-111111111111" + if str(path) == "/proc/self/mountinfo": + return host + if path.name == "stat": + return process + identifier = "controller-id" if path.parent.name == "101" else "proxy-id" + return mounts(f"/docker/overlay2/{identifier}/diff") + statfs = types.SimpleNamespace(f_blocks=100, f_frsize=1024**3, f_bavail=40, f_files=1000, f_ffree=800) + with patch.dict(os.environ, CI_FLEET_RUNNER_RUNTIME_IMAGE_ID="sha256:" + "a" * 64), patch.object(sample, "read_small", side_effect=reads), patch.object(sample.os, "stat", return_value=types.SimpleNamespace(st_dev=9)), patch.object(sample.os, "open", return_value=123), patch.object(sample.os, "close"), patch.object(sample.os, "fstat", return_value=types.SimpleNamespace(st_dev=9)), patch.object(sample.os, "fstatvfs", return_value=statfs): + result = FakeDaemon().collect("example") + self.assertEqual(len(result["filesystems"]), 1) + self.assertEqual(result["filesystems"][0]["roles"], list(sample.ROLES)) + self.assertEqual(result["filesystems"][0]["state"], "measured") + normal_host = host + for override in ("/docker/overlay2/controller-id/diff", "/docker/overlay2/other", "/docker/overlay2/controller-id/merged/subdir"): + host = normal_host + f"11 1 8:2 / {override} rw - ext4 /dev/other rw\n" + result = FakeDaemon().collect("example") + self.assertEqual({role for fs in result["filesystems"] if fs["state"] == "unknown" for role in fs["roles"]}, {"workspace", "spool"}) + host = normal_host.replace("upperdir=/docker/overlay2/controller-id/diff", "upperdir=/elsewhere/diff") + result = FakeDaemon().collect("example") + self.assertTrue(any(fs["state"] == "unknown" for fs in result["filesystems"])) + + def test_malformed_inspect_is_controlled_unknown(self): + valid = dict(id="id", pid=101, started="start", running=True, mounts=[], + labels={"com.docker.compose.project": "ci-fleet", "com.docker.compose.service": "controller"}) + statfs = types.SimpleNamespace(f_blocks=100, f_frsize=1024**3, f_bavail=40, f_files=1000, f_ffree=800) + for value in (None, [], {**valid, "labels": None}, {**valid, "mounts": None}, + {**valid, "mounts": [None]}, {**valid, "mounts": [{"Destination": None}]}, + {**valid, "id": None}, {**valid, "pid": True}, {**valid, "running": None}): + with self.subTest(value=value), patch.dict(os.environ, CI_FLEET_RUNNER_RUNTIME_IMAGE_ID="fixture"), patch.object(sample, "read_small", return_value="11111111-1111-4111-8111-111111111111"), patch.object(sample.Collector, "docker", side_effect=[{"root": "/docker", "driver": "overlay2"}, None, value]), patch.object(sample.os, "open", return_value=123), patch.object(sample.os, "close"), patch.object(sample.os, "fstat", return_value=types.SimpleNamespace(st_dev=9)), patch.object(sample.os, "fstatvfs", return_value=statfs): + result = sample.Collector().collect("example") + unknown = [fs for fs in result["filesystems"] if fs["state"] == "unknown"] + self.assertEqual({role for fs in unknown for role in fs["roles"]}, {"workspace", "spool"}) + self.assertTrue(all(fs["observed_at"] is None and fs["available_bytes"] is None for fs in unknown)) + + def test_deadline_prevents_another_daemon_call(self): + collector = sample.Collector() + collector.deadline = 0 + with patch.object(sample.subprocess, "run") as run, self.assertRaises(ValueError): + collector.docker("info") + run.assert_not_called() + + +class ExportTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.root = Path(self.temp.name) + self.owner = patch.object(sample.store, "OWNER_UID", os.getuid()) + self.owner.start() + def tearDown(self): + self.owner.stop() + self.temp.cleanup() + + def test_atomic_protected_publication_and_bad_entries(self): + path = self.root / "export" + fd = sample.prepare(path) + try: + # Root-group check is the production contract. Unit publication can + # use the local primary group without requiring chown privileges. + original = sample.store._regular + def local_regular(meta, **kwargs): + kwargs["gid"] = os.getgid() + return original(meta, **kwargs) + with patch.object(sample.store, "_regular", side_effect=local_regular): + sample.publish(fd, {"schema_version": 1}) + self.assertEqual((path / "measurement.json").stat().st_mode & 0o777, 0o600) + previous = (path / "measurement.json").read_bytes() + with patch.object(sample.os, "replace", side_effect=OSError), self.assertRaises(OSError): + sample.publish(fd, {"new": True}) + self.assertEqual((path / "measurement.json").read_bytes(), previous) + (path / "stranger").write_text("preserve") + with self.assertRaises(ValueError): + sample.publish(fd, {}) + self.assertEqual((path / "stranger").read_text(), "preserve") + finally: + os.close(fd) + + def test_symlink_directory_modes_hardlinks_fifo_and_acl(self): + target = self.root / "target" + target.mkdir(mode=0o700) + link = self.root / "link" + link.symlink_to(target) + with self.assertRaises(OSError): + sample.prepare(link) + target.chmod(0o755) + with self.assertRaises(ValueError): + sample.prepare(target) + target.chmod(0o700) + with patch.object(sample.store, "_no_acl", side_effect=ValueError), self.assertRaises(ValueError): + sample.prepare(target) + for kind in ("symlink", "hardlink", "fifo"): + with self.subTest(kind=kind): + fd = sample.prepare(target) + file = target / "measurement.json" + if kind == "symlink": + file.symlink_to(self.root / "missing") + elif kind == "hardlink": + source = self.root / "source" + source.write_text("{}") + source.chmod(0o600) + file.hardlink_to(source) + else: + os.mkfifo(file, 0o600) + try: + with self.assertRaises(ValueError): + sample.publish(fd, {}) + finally: + os.close(fd) + file.unlink() + + def test_prepare_and_scoped_remove_preserve_history_and_unknown_files(self): + path = self.root / "export" + history = self.root / "capacity" + history.mkdir() + (history / "samples.jsonl").write_text("preserve history") + original = sample.store._regular + def local_regular(meta, **kwargs): + kwargs["gid"] = os.getgid() + return original(meta, **kwargs) + with patch.object(sample.store, "_regular", side_effect=local_regular): + for _ in range(2): + with patch("sys.argv", ["sample", "--output", str(path), "--prepare"]): + self.assertEqual(sample.main(), 0) + self.assertFalse((path / "measurement.json").exists()) + fd = sample.prepare(path) + try: + sample.publish(fd, {"schema_version": 1}) + finally: + os.close(fd) + previous = (path / "measurement.json").read_bytes() + (path / "stranger").write_text("keep") + with patch("sys.argv", ["sample", "--output", str(path), "--remove"]): + self.assertEqual(sample.main(), 1) + self.assertEqual((path / "measurement.json").read_bytes(), previous) + self.assertEqual((path / "stranger").read_text(), "keep") + (path / "stranger").unlink() + for _ in range(2): + with patch("sys.argv", ["sample", "--output", str(path), "--remove"]): + self.assertEqual(sample.main(), 0) + self.assertFalse(path.exists()) + self.assertEqual((history / "samples.jsonl").read_text(), "preserve history") + path.symlink_to(self.root / "absent") + with patch("sys.argv", ["sample", "--output", str(path), "--remove"]): + self.assertEqual(sample.main(), 1) + self.assertTrue(path.is_symlink()) + + def test_concurrent_prepare_sample_remove_and_no_late_republication(self): + path = self.root / "export" + fd = sample.prepare(path) + late = None + original = sample.store._regular + def local_regular(meta, **kwargs): + kwargs["gid"] = os.getgid() + return original(meta, **kwargs) + with patch.object(sample.store, "_regular", side_effect=local_regular): + try: + sample.publish(fd, {"schema_version": 1}) + original_bytes = (path / "measurement.json").read_bytes() + original_inode = path.stat().st_ino + sample.lock_export(fd) + with patch("sys.argv", ["sample", "--output", str(path), "--prepare"]): + self.assertEqual(sample.main(), 0) + self.assertEqual(path.stat().st_ino, original_inode) + self.assertEqual((path / "measurement.json").read_bytes(), original_bytes) + with patch("sys.argv", ["sample", "--output", str(path)]), patch.object(sample, "Collector") as collector: + self.assertEqual(sample.main(), 1) + collector.assert_not_called() + late = sample.prepare(path, create=False) + release = threading.Timer(0.05, sample.fcntl.flock, args=(fd, sample.fcntl.LOCK_UN)) + release.start() + try: + with patch("sys.argv", ["sample", "--output", str(path), "--remove"]): + self.assertEqual(sample.main(), 0) + finally: + release.join() + self.assertFalse(path.exists()) + sample.lock_export(late) + with self.assertRaises(FileNotFoundError): + sample.publish(late, {"late": True}) + with patch("sys.argv", ["sample", "--output", str(path)]), patch.object(sample, "Collector") as collector: + self.assertEqual(sample.main(), 1) + collector.assert_not_called() + self.assertFalse(path.exists()) + finally: + os.close(fd) + if late is not None: + os.close(late) + + def test_remove_lock_wait_is_bounded_and_preserves_entries(self): + path = self.root / "export" + fd = sample.prepare(path) + try: + sample.publish(fd, {"preserve": True}) + before = (path / "measurement.json").read_bytes() + with patch.object(sample.fcntl, "flock", side_effect=BlockingIOError), patch.object(sample.time, "monotonic", side_effect=[0, 21]), patch("sys.argv", ["sample", "--output", str(path), "--remove"]): + self.assertEqual(sample.main(), 1) + self.assertEqual((path / "measurement.json").read_bytes(), before) + finally: + os.close(fd) + + def test_policy_downgrade_removes_only_after_success(self): + source = Path(__file__).with_name("install-worker-controller.sh").read_text() + converge = source.split("perform_converge() {", 1)[1].split("\n}\n", 1)[0] + selection = " if ((policy_status == 0)); then" + converge.split(" if ((policy_status == 0)); then", 1)[1].split(" if docker_network_policy_matches; then", 1)[0] + old = self.root / "old" + old.mkdir() + new = self.root / "new" + (new / "scripts").mkdir(parents=True) + (new / "scripts/disk_admission_sample.py").write_text("fixture") + for status, release, removed in ((0, old, True), (0, new, False), (20, old, False)): + script = ('set -eu\nremove_disk_admission_export() { printf "REMOVED\\n"; }\nnote() { :; }\n' + 'finish_policy() {\n' + selection + '\n}\nfinish_policy\n') + environment = {**os.environ, "policy_status": str(status), "release_dir": str(release), + "mode": "upgrade", "controller_id": "example", "config_ref": "fixture", + "engine_ref": "fixture", "target_state": "active", "checkpoint_dir": "fixture"} + result = subprocess.run(["bash", "-c", script], env=environment, capture_output=True, text=True) + self.assertEqual(result.returncode, status, result.stderr) + self.assertEqual("REMOVED" in result.stdout, removed) + + def test_sampler_failure_does_not_suppress_existing_history(self): + scripts = self.root / "scripts" + scripts.mkdir() + original = Path(__file__).with_name("capacity-sample.sh").read_text() + (scripts / "capacity-sample.sh").write_text(original) + (scripts / "disk_admission_sample.py").write_text("raise SystemExit(1)\n") + (scripts / "health.py").write_text("print('HISTORY_EXECUTED')\n") + config = self.root / "etc/ci-fleet" + config.mkdir(parents=True) + (config / "ci-fleet.env").write_text("CI_FLEET_INSTANCE=example\n") + result = subprocess.run(["bash", str(scripts / "capacity-sample.sh")], env={**os.environ, "CI_FLEET_TESTING": "1", "CI_FLEET_ROOT_PREFIX": str(self.root)}, capture_output=True, text=True) + self.assertEqual(result.returncode, 1) + self.assertIn("HISTORY_EXECUTED", result.stdout) + + +if __name__ == "__main__": + from validation_diagnostics import TimedTestRunner + unittest.main(testRunner=TimedTestRunner) diff --git a/scripts/test_portable_image_lifecycle.py b/scripts/test_portable_image_lifecycle.py index 55907cb7..1b879010 100644 --- a/scripts/test_portable_image_lifecycle.py +++ b/scripts/test_portable_image_lifecycle.py @@ -173,7 +173,7 @@ def test_opaque_manual_capture_preflight_drain_and_restoration_use_incumbent_sou "portable_managed_images", "capture_legacy_image_ids", "load_checkpoint_images", "make_checkpoint", "checkpoint_images_reproducible", "preflight_checkpoint_images", "managed_image_objects_match", "try_drain_current", "retag_checkpoint_image", "restore_reviewed_image_tags", - "managed_images_match", "restore_checkpoint"), r""" + "managed_images_match", "prepare_disk_admission_export", "restore_checkpoint"), r""" install_root=$temporary/opt/ci-fleet releases_dir=$install_root/releases mkdir -p "$releases_dir" @@ -1038,7 +1038,7 @@ def test_no_release_fixture_reestablishes_absence_after_each_rollback(self): "make_checkpoint", "latest_checkpoint", "canonical_release_target", "raw_pointer_target_exists", "raw_link_target_path", "portable_managed_images", "preflight_checkpoint_images", "checkpoint_images_reproducible", "managed_image_objects_match", "restore_reviewed_image_tags", - "retag_checkpoint_image", "managed_images_match", "restore_checkpoint", "try_drain_current", + "retag_checkpoint_image", "managed_images_match", "prepare_disk_admission_export", "restore_checkpoint", "try_drain_current", "drain_current", "managed_runner_count", "remove_inactive_managed_runners"), "uninstall_preparation() {\n" + preparation + "}\n" + r""" root=$temporary/host diff --git a/scripts/validate.sh b/scripts/validate.sh index 3df80c60..09118671 100755 --- a/scripts/validate.sh +++ b/scripts/validate.sh @@ -43,6 +43,8 @@ validation_command python-compile python3 -m py_compile \ scripts/test_cleanup_storage.py \ scripts/test_proxy_memory.py \ scripts/health.py \ + scripts/disk_admission_sample.py \ + scripts/test_disk_admission_sample.py \ scripts/endpoint_snapshot.py \ scripts/endpoint_snapshot_sources.py \ scripts/endpoint_snapshot_store.py \ diff --git a/scripts/validation_tasks.py b/scripts/validation_tasks.py index e2dd6378..2da8b9f6 100755 --- a/scripts/validation_tasks.py +++ b/scripts/validation_tasks.py @@ -43,6 +43,7 @@ ('remote-reconcile', ['python3', 'scripts/test_remote_reconcile.py'], False), ('explicit-recovery', ['python3', '-I', '-B', 'scripts/test_explicit_recovery.py'], False), ('health', ['python3', 'scripts/test_health.py'], False), + ('disk-admission', ['python3', 'scripts/test_disk_admission_sample.py'], False), ('endpoint-snapshot', ['python3', 'scripts/test_endpoint_snapshot.py'], False), ('snapshot-sources', ['python3', 'scripts/test_endpoint_snapshot_sources.py'], False), ('snapshot-store', ['python3', 'scripts/test_endpoint_snapshot_store.py'], False),