diff --git a/.github/workflows/safety-ci.yml b/.github/workflows/safety-ci.yml index 3319765..99cacc5 100644 --- a/.github/workflows/safety-ci.yml +++ b/.github/workflows/safety-ci.yml @@ -183,6 +183,49 @@ jobs: if-no-files-found: warn retention-days: 14 + prune_acceptance: + name: Filesystem pruning — real container acceptance + runs-on: ubuntu-24.04 + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ env.CHECKPOINT_SHA }} + persist-credentials: false + - name: Refresh Ubuntu package indexes + timeout-minutes: 5 + run: bash .github/scripts/ci-media-apt.sh update + - name: Install media test tools + timeout-minutes: 8 + run: bash .github/scripts/ci-media-apt.sh install ffmpeg python3-venv openssl + - name: Build the exact checkout runtime image + timeout-minutes: 8 + run: docker build -t simplenvr-safety-test . + - name: Install pinned browser acceptance tooling + timeout-minutes: 8 + shell: bash + run: | + set -euo pipefail + python3 -m venv "$RUNNER_TEMP/simplenvr-browser-venv" + . "$RUNNER_TEMP/simplenvr-browser-venv/bin/activate" + python -m pip install 'playwright==1.56.0' + python -m playwright install --with-deps chrome + - name: Real container ceiling pruning on a loopback ext4 volume, with Chrome + timeout-minutes: 12 + shell: bash + run: | + set -euo pipefail + . "$RUNNER_TEMP/simplenvr-browser-venv/bin/activate" + GITHUB_SHA="$CHECKPOINT_SHA" bash tests/acceptance/filesystem-prune-acceptance.sh simplenvr-safety-test "$RUNNER_TEMP/simplenvr-prune-evidence" + - name: Retain pruning acceptance evidence + if: always() + uses: actions/upload-artifact@v4 + with: + name: filesystem-prune-acceptance-${{ env.CHECKPOINT_SHA }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/simplenvr-prune-evidence + if-no-files-found: warn + retention-days: 14 + correspondence_resources: name: Ordered content — bounded synthetic resource measurements runs-on: ubuntu-24.04 @@ -263,18 +306,20 @@ jobs: verify: name: Required checks — all must pass if: always() - needs: [core, browser, correspondence_resources] + needs: [core, browser, prune_acceptance, correspondence_resources] runs-on: ubuntu-24.04 timeout-minutes: 2 steps: - - name: Require core, both browser attempts and resource measurements + - name: Require core, both browser attempts, pruning acceptance and resource measurements env: CORE_RESULT: ${{ needs.core.result }} BROWSER_RESULT: ${{ needs.browser.result }} + PRUNE_RESULT: ${{ needs.prune_acceptance.result }} RESOURCE_RESULT: ${{ needs.correspondence_resources.result }} run: | set -euo pipefail - printf 'core=%s browser=%s resources=%s\n' "$CORE_RESULT" "$BROWSER_RESULT" "$RESOURCE_RESULT" + printf 'core=%s browser=%s prune=%s resources=%s\n' "$CORE_RESULT" "$BROWSER_RESULT" "$PRUNE_RESULT" "$RESOURCE_RESULT" test "$CORE_RESULT" = success test "$BROWSER_RESULT" = success + test "$PRUNE_RESULT" = success test "$RESOURCE_RESULT" = success diff --git a/cmd/simplenvr/auth.go b/cmd/simplenvr/auth.go index 793c736..dd55ed9 100644 --- a/cmd/simplenvr/auth.go +++ b/cmd/simplenvr/auth.go @@ -228,6 +228,25 @@ var mutationPaths = map[string]bool{ "/api/events/clear-all":true, "/api/events/clear-camera":true, } +// readWriteMutationPaths are mutation paths that also serve GET and HEAD reads. They +// stay in mutationPaths, so the shutdown gate still tracks their POST, and cross-origin +// protection and the session check still apply to every method. +var readWriteMutationPaths = map[string]bool{} + +// methodPolicy says which methods a path accepts once the caller is authenticated. +// Paths outside mutationPaths accept only GET and HEAD, mutation paths only POST, and +// read-write mutation paths all three. +func methodPolicy(path, method string) (allow string, ok bool) { + switch { + case readWriteMutationPaths[path]: + return "GET, HEAD, POST", method == http.MethodGet || method == http.MethodHead || method == http.MethodPost + case mutationPaths[path]: + return "POST", method == http.MethodPost + default: + return "GET, HEAD", method == http.MethodGet || method == http.MethodHead + } +} + func (a *authManager) Handler(next http.Handler) http.Handler { protected := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Header().Set("X-Content-Type-Options", "nosniff") @@ -247,10 +266,8 @@ func (a *authManager) Handler(next http.Handler) http.Handler { } if r.URL.Path == "/api/settings/session" { a.sessionSettingsHandler(w,r); return } if r.URL.Path == "/api/settings/restart" { a.restartHandler(w,r); return } - if mutationPaths[r.URL.Path] { - if r.Method != http.MethodPost { w.Header().Set("Allow","POST"); http.Error(w,"Method not allowed",http.StatusMethodNotAllowed); return } - } else if r.Method != http.MethodGet && r.Method != http.MethodHead { - w.Header().Set("Allow","GET, HEAD"); http.Error(w,"Method not allowed",http.StatusMethodNotAllowed); return + if allow, ok := methodPolicy(r.URL.Path, r.Method); !ok { + w.Header().Set("Allow",allow); http.Error(w,"Method not allowed",http.StatusMethodNotAllowed); return } if strings.HasPrefix(r.URL.Path,"/recordings/") { servePrivateRecording(w,r); return } clean := r.Clone(r.Context()) diff --git a/cmd/simplenvr/cleanup.go b/cmd/simplenvr/cleanup.go index 3455c49..847f65d 100644 --- a/cmd/simplenvr/cleanup.go +++ b/cmd/simplenvr/cleanup.go @@ -19,9 +19,13 @@ func cleanupEventsForWithSave(ctx context.Context,n *NVR,persist func() error) { if ctx.Err()!=nil {n.mu.Unlock();return} retentionMap:=make(map[string]time.Duration) invalidRetention:=make(map[string]bool) + ageOff:=make(map[string]bool) for _,cam:=range n.cameras { retention,err:=cameraRetentionDuration(cam.RetentionDays) if err!=nil {invalidRetention[cam.Name]=true;log.Printf("Skipping invalid retention policy for camera %s",cam.ID);continue} + // Retention 0 means no age limit. Events lack camera IDs, so any camera with that + // name and no age limit keeps the name's events from expiring by age. + if cam.RetentionDays==0 {ageOff[cam.Name]=true;continue} // Events lack camera IDs. Do not choose a shorter policy based on map // iteration order when several registered cameras share the same name. if retention>retentionMap[cam.Name] {retentionMap[cam.Name]=retention} @@ -34,6 +38,7 @@ func cleanupEventsForWithSave(ctx context.Context,n *NVR,persist func() error) { // An invalid policy is not equivalent to a missing camera. Preserve its // events, including ambiguous names shared with another camera. if invalidRetention[event.CameraName] {validEvents=append(validEvents,event);continue} + if ageOff[event.CameraName] {validEvents=append(validEvents,event);continue} retention,exists:=retentionMap[event.CameraName] if !exists || event.StartTime.Before(now.Add(-retention)) {deletedCount++;continue} validEvents=append(validEvents,event) diff --git a/cmd/simplenvr/filesystem_ceiling.go b/cmd/simplenvr/filesystem_ceiling.go new file mode 100644 index 0000000..a985a37 --- /dev/null +++ b/cmd/simplenvr/filesystem_ceiling.go @@ -0,0 +1,149 @@ +package main + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "log" + "math" + "net/http" + "strconv" + "sync" + "time" +) + +// The ceiling is the highest filesystem-used percentage the owner accepts. The prune +// job (filesystem_prune.go) reads it; a successful change asks that job for a pass. +const ( + defaultMaxFilesystemUsedPercent=80 + minMaxFilesystemUsedPercent=10 + maxMaxFilesystemUsedPercent=95 + filesystemPruneMarginPercent=2 + maxFilesystemCeilingRequestBytes=1024 +) + +var errFilesystemCeiling=errors.New("max_filesystem_used_percent must be a whole number from 10 to 95") + +type filesystemCeilingSetting struct { + mu sync.RWMutex + percent int +} + +func (s *filesystemCeilingSetting) get() int {s.mu.RLock();defer s.mu.RUnlock();return s.percent} +func (s *filesystemCeilingSetting) set(percent int) {s.mu.Lock();s.percent=percent;s.mu.Unlock()} + +var recordingFilesystemCeiling=&filesystemCeilingSetting{percent:defaultMaxFilesystemUsedPercent} + +// filesystemCeilingUpdateMu serializes updates so a failed save restores the value +// that was current before that update. +var filesystemCeilingUpdateMu sync.Mutex + +func validateFilesystemCeiling(percent int) error { + if percentmaxMaxFilesystemUsedPercent {return errFilesystemCeiling} + return nil +} + +// filesystemPruneTrigger is derived from the ceiling and never stored. +func filesystemPruneTrigger(ceiling int) int {return ceiling-filesystemPruneMarginPercent} + +// parseFilesystemCeilingValue accepts only a JSON integer literal in range. A +// string, fraction, exponent, null or boolean is refused. +func parseFilesystemCeilingValue(raw []byte) (int,error) { + percent,err:=strconv.Atoi(string(bytes.TrimSpace(raw))) + if err!=nil {return 0,errFilesystemCeiling} + if err=validateFilesystemCeiling(percent);err!=nil {return 0,err} + return percent,nil +} + +// storedFilesystemCeiling reads the top-level key from configuration. A missing key +// is the default; a present but invalid value is an error. +func storedFilesystemCeiling(raw []byte) (int,error) { + var doc struct {Value json.RawMessage `json:"max_filesystem_used_percent"`} + if err:=json.Unmarshal(raw,&doc);err!=nil {return 0,err} + if doc.Value==nil {return defaultMaxFilesystemUsedPercent,nil} + return parseFilesystemCeilingValue(doc.Value) +} + +// persistedDocument is what is written to cameras.json. persistedState stays a +// three-field struct so existing positional literals keep compiling; the embedded +// fields are written at the top level beside the ceiling. +type persistedDocument struct { + persistedState + MaxFilesystemUsedPercent int `json:"max_filesystem_used_percent"` +} + +type filesystemCeilingResponse struct { + Ceiling int `json:"max_filesystem_used_percent"` + Trigger int `json:"filesystem_prune_trigger_percent"` + Used *float64 `json:"filesystem_used_percent"` + ObservedAt *time.Time `json:"filesystem_observed_at"` +} + +type filesystemCeilingDeps struct { + setting *filesystemCeilingSetting + read func(string) (filesystemUsage,error) + save func() error + // onChange, when set, runs after a successful save so a changed ceiling can be + // acted on without waiting for the next scheduled pass. + onChange func() +} + +func filesystemCeilingSnapshot(deps filesystemCeilingDeps) filesystemCeilingResponse { + ceiling:=deps.setting.get() + resp:=filesystemCeilingResponse{Ceiling:ceiling,Trigger:filesystemPruneTrigger(ceiling)} + usage,err:=deps.read(recordingsRoot) + if err==nil && !math.IsNaN(usage.UsedPercent) && !math.IsInf(usage.UsedPercent,0) { + used:=math.Round(usage.UsedPercent*10)/10 + observed:=usage.ObservedAt + resp.Used=&used;resp.ObservedAt=&observed + } + return resp +} + +func writeFilesystemCeiling(w http.ResponseWriter,deps filesystemCeilingDeps) { + w.Header().Set("Content-Type","application/json") + w.Header().Set("X-Content-Type-Options","nosniff") + json.NewEncoder(w).Encode(filesystemCeilingSnapshot(deps)) +} + +func updateFilesystemCeiling(w http.ResponseWriter,r *http.Request,deps filesystemCeilingDeps) { + r.Body=http.MaxBytesReader(w,r.Body,maxFilesystemCeilingRequestBytes) + dec:=json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + var req struct {Value json.RawMessage `json:"max_filesystem_used_percent"`} + if err:=dec.Decode(&req);err!=nil || req.Value==nil {http.Error(w,errFilesystemCeiling.Error(),400);return} + var extra interface{} + if err:=dec.Decode(&extra);err!=io.EOF {http.Error(w,errFilesystemCeiling.Error(),400);return} + percent,err:=parseFilesystemCeilingValue(req.Value) + if err!=nil {http.Error(w,err.Error(),400);return} + filesystemCeilingUpdateMu.Lock() + defer filesystemCeilingUpdateMu.Unlock() + previous:=deps.setting.get() + deps.setting.set(percent) + if err=deps.save();err!=nil { + deps.setting.set(previous) + log.Printf("Saving filesystem usage ceiling failed: %v",err) + http.Error(w,"Failed to save filesystem usage ceiling",500) + return + } + if deps.onChange!=nil {deps.onChange()} + writeFilesystemCeiling(w,deps) +} + +func serveFilesystemCeiling(w http.ResponseWriter,r *http.Request,deps filesystemCeilingDeps) { + w.Header().Set("Cache-Control","no-store") + switch r.Method { + case http.MethodGet: + writeFilesystemCeiling(w,deps) + case http.MethodPost: + updateFilesystemCeiling(w,r,deps) + default: + w.Header().Set("Allow","GET, POST") + http.Error(w,"Method not allowed",405) + } +} + +func filesystemCeilingHandler(w http.ResponseWriter,r *http.Request) { + serveFilesystemCeiling(w,r,filesystemCeilingDeps{setting:recordingFilesystemCeiling,read:readFilesystemUsage,save:nvr.save,onChange:recordingFilesystemPruner.requestPass}) +} diff --git a/cmd/simplenvr/filesystem_ceiling_frontend_test.go b/cmd/simplenvr/filesystem_ceiling_frontend_test.go new file mode 100644 index 0000000..f633e58 --- /dev/null +++ b/cmd/simplenvr/filesystem_ceiling_frontend_test.go @@ -0,0 +1,7 @@ +package main + +import "testing" + +func TestFrontendFilesystemCeiling(t *testing.T) { + runFrontendRegression(t, "tests/frontend/filesystem-ceiling.cjs", "UTC") +} diff --git a/cmd/simplenvr/filesystem_ceiling_routes.go b/cmd/simplenvr/filesystem_ceiling_routes.go new file mode 100644 index 0000000..ad22c1e --- /dev/null +++ b/cmd/simplenvr/filesystem_ceiling_routes.go @@ -0,0 +1,11 @@ +package main + +const filesystemCeilingPath="/api/storage/ceiling" + +// The ceiling route serves GET (read) and POST (change). Registering it as a tracked +// mutation makes the shutdown gate wait for an in-flight save, and registering it as +// read-write lets the auth layer accept its GET as well as its POST. +func init() { + mutationPaths[filesystemCeilingPath]=true + readWriteMutationPaths[filesystemCeilingPath]=true +} diff --git a/cmd/simplenvr/filesystem_ceiling_routes_test.go b/cmd/simplenvr/filesystem_ceiling_routes_test.go new file mode 100644 index 0000000..2ec99e3 --- /dev/null +++ b/cmd/simplenvr/filesystem_ceiling_routes_test.go @@ -0,0 +1,77 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "net/url" + "strings" + "testing" +) + +func httpHandlerRecording(reached *[]string) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter,r *http.Request) { + *reached=append(*reached,r.Method+" "+r.URL.Path) + w.WriteHeader(204) + }) +} + +func TestMethodPolicy(t *testing.T) { + for _,c:=range []struct{path,method,allow string;ok bool}{ + {"/api/storage/ceiling","GET","GET, HEAD, POST",true}, + {"/api/storage/ceiling","HEAD","GET, HEAD, POST",true}, + {"/api/storage/ceiling","POST","GET, HEAD, POST",true}, + {"/api/storage/ceiling","PUT","GET, HEAD, POST",false}, + {"/api/storage/ceiling","DELETE","GET, HEAD, POST",false}, + {"/api/cameras/delete-all","POST","POST",true}, + {"/api/cameras/delete-all","GET","POST",false}, + {"/api/cameras/update-retention","GET","POST",false}, + {"/api/cameras","GET","GET, HEAD",true}, + {"/api/cameras","POST","GET, HEAD",false}, + {"/api/storage/status","POST","GET, HEAD",false}, + } { + allow,ok:=methodPolicy(c.path,c.method) + if allow!=c.allow || ok!=c.ok {t.Fatalf("%s %s = %q, %v; want %q, %v",c.method,c.path,allow,ok,c.allow,c.ok)} + } +} + +func TestFilesystemCeilingPathIsATrackedMutation(t *testing.T) { + if !mutationPaths[filesystemCeilingPath] {t.Fatal("the shutdown gate would not wait for an in-flight ceiling save")} + if !readWriteMutationPaths[filesystemCeilingPath] {t.Fatal("the auth layer would reject the ceiling read")} + for path:=range readWriteMutationPaths { + if !mutationPaths[path] {t.Fatalf("%s is read-write but not a tracked mutation",path)} + } +} + +// The CP3 handler tests called the handler directly and never saw the auth layer, which +// rejected every POST with 405. This sends the route through the real auth handler. +func TestFilesystemCeilingRouteThroughRealAuth(t *testing.T) { + a,_:=authFixture(t) + var reached []string + handler:=a.Handler(httpHandlerRecording(&reached)) + form:=url.Values{"username":{"admin"},"password":{"correct horse battery staple"}} + login:=httptest.NewRequest("POST","https://nvr.test/auth/login",strings.NewReader(form.Encode())) + login.Header.Set("Content-Type","application/x-www-form-urlencoded") + loginResponse:=httptest.NewRecorder();handler.ServeHTTP(loginResponse,login) + if loginResponse.Code!=303 {t.Fatalf("login: %d",loginResponse.Code)} + cookies:=loginResponse.Result().Cookies() + if len(cookies)==0 {t.Fatal("no session cookie")} + request:=func(method,origin string,withCookie bool) *httptest.ResponseRecorder { + r:=httptest.NewRequest(method,"https://nvr.test"+filesystemCeilingPath,strings.NewReader(`{"max_filesystem_used_percent":90}`)) + if withCookie {r.AddCookie(cookies[0])} + if origin!="" {r.Header.Set("Origin",origin)} + w:=httptest.NewRecorder();handler.ServeHTTP(w,r);return w + } + for _,method:=range []string{"GET","HEAD"} { + if w:=request(method,"",true);w.Code!=204 {t.Fatalf("%s with a session: %d",method,w.Code)} + } + if w:=request("POST","https://nvr.test",true);w.Code!=204 {t.Fatalf("POST with a session: %d",w.Code)} + for _,method:=range []string{"PUT","DELETE","PATCH"} { + w:=request(method,"https://nvr.test",true) + if w.Code!=405 || w.Header().Get("Allow")!="GET, HEAD, POST" {t.Fatalf("%s: %d allow %q",method,w.Code,w.Header().Get("Allow"))} + } + if w:=request("POST","https://evil.invalid",true);w.Code!=403 {t.Fatalf("cross-origin POST: %d",w.Code)} + if w:=request("GET","",false);w.Code!=401 {t.Fatalf("unauthenticated GET: %d",w.Code)} + if w:=request("POST","https://nvr.test",false);w.Code!=401 {t.Fatalf("unauthenticated POST: %d",w.Code)} + want:="GET /api/storage/ceiling,HEAD /api/storage/ceiling,POST /api/storage/ceiling" + if got:=strings.Join(reached,",");got!=want {t.Fatalf("requests that reached the handler = %q; want %q",got,want)} +} diff --git a/cmd/simplenvr/filesystem_ceiling_test.go b/cmd/simplenvr/filesystem_ceiling_test.go new file mode 100644 index 0000000..650869f --- /dev/null +++ b/cmd/simplenvr/filesystem_ceiling_test.go @@ -0,0 +1,179 @@ +package main + +import ( + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" +) + +func resetFilesystemCeiling(t *testing.T,value int) { + t.Helper() + previous:=recordingFilesystemCeiling.get() + recordingFilesystemCeiling.set(value) + t.Cleanup(func(){recordingFilesystemCeiling.set(previous)}) +} + +func newCeilingNVR() *NVR { + return &NVR{cameras:map[string]*Camera{},cameraOrder:[]string{},events:[]Event{}} +} + +func TestValidateFilesystemCeilingRange(t *testing.T) { + for _,value:=range []int{10,11,80,94,95} { + if err:=validateFilesystemCeiling(value);err!=nil {t.Fatalf("%d refused: %v",value,err)} + } + for _,value:=range []int{-1,0,9,96,100,1000000} { + if err:=validateFilesystemCeiling(value);err==nil {t.Fatalf("%d accepted",value)} + } + if got:=filesystemPruneTrigger(80);got!=78 {t.Fatalf("trigger for 80 = %d",got)} + if got:=filesystemPruneTrigger(10);got!=8 {t.Fatalf("trigger for 10 = %d",got)} +} + +func TestStoredFilesystemCeiling(t *testing.T) { + valid:=map[string]int{`{}`:80,`{"max_filesystem_used_percent":10}`:10,`{"max_filesystem_used_percent":80}`:80,`{"max_filesystem_used_percent":95}`:95} + for raw,want:=range valid { + got,err:=storedFilesystemCeiling([]byte(raw)) + if err!=nil || got!=want {t.Fatalf("%s = %d, %v; want %d",raw,got,err,want)} + } + for _,value:=range []string{`9`,`96`,`-5`,`0`,`80.5`,`"80"`,`null`,`1e1`,`true`,`[]`,`{}`} { + raw:=`{"max_filesystem_used_percent":`+value+`}` + if got,err:=storedFilesystemCeiling([]byte(raw));err==nil {t.Fatalf("%s accepted as %d",raw,got)} + } +} + +func TestDecodeStateChecksFilesystemCeiling(t *testing.T) { + for _,raw:=range []string{`{"cameras":{}}`,`{"cameras":{},"max_filesystem_used_percent":55}`} { + if _,err:=decodeState([]byte(raw));err!=nil {t.Fatalf("%s refused: %v",raw,err)} + } + for _,raw:=range []string{`{"cameras":{},"max_filesystem_used_percent":96}`,`{"cameras":{},"max_filesystem_used_percent":"80"}`,`{"cameras":{},"max_filesystem_used_percent":null}`} { + if _,err:=decodeState([]byte(raw));err==nil {t.Fatalf("%s accepted",raw)} + } +} + +func TestSaveWritesFilesystemCeilingExplicitly(t *testing.T) { + for _,value:=range []int{80,55} { + resetFilesystemCeiling(t,value) + path:=filepath.Join(t.TempDir(),"cameras.json") + var written []byte + err:=newCeilingNVR().saveAtWithWriter(path,func(target string,raw []byte) error {if target==path {written=raw};return nil}) + if err!=nil {t.Fatal(err)} + var doc map[string]json.RawMessage + if err=json.Unmarshal(written,&doc);err!=nil {t.Fatal(err)} + if string(doc["max_filesystem_used_percent"])!=fmt.Sprint(value) {t.Fatalf("saved ceiling = %s; want %d",doc["max_filesystem_used_percent"],value)} + for _,key:=range []string{"cameras","camera_order","events"} { + if _,ok:=doc[key];!ok {t.Fatalf("top-level key %q missing",key)} + } + } +} + +func TestFilesystemCeilingSurvivesSaveAndLoad(t *testing.T) { + resetFilesystemCeiling(t,55) + path:=filepath.Join(t.TempDir(),"cameras.json") + var written []byte + if err:=newCeilingNVR().saveAtWithWriter(path,func(target string,raw []byte) error {if target==path {written=raw};return nil});err!=nil {t.Fatal(err)} + if err:=os.WriteFile(path,written,0600);err!=nil {t.Fatal(err)} + recordingFilesystemCeiling.set(80) + if err:=newCeilingNVR().loadAt(path);err!=nil {t.Fatal(err)} + if got:=recordingFilesystemCeiling.get();got!=55 {t.Fatalf("loaded ceiling = %d; want 55",got)} +} + +func TestLoadRefusesInvalidFilesystemCeiling(t *testing.T) { + resetFilesystemCeiling(t,70) + path:=filepath.Join(t.TempDir(),"cameras.json") + if err:=os.WriteFile(path,[]byte(`{"cameras":{},"max_filesystem_used_percent":96}`),0600);err!=nil {t.Fatal(err)} + if err:=newCeilingNVR().loadAt(path);err==nil {t.Fatal("invalid ceiling loaded")} + if got:=recordingFilesystemCeiling.get();got!=70 {t.Fatalf("ceiling changed to %d after refused load",got)} +} + +func ceilingTestDeps(saveErr error,saves *int) filesystemCeilingDeps { + return filesystemCeilingDeps{ + setting:recordingFilesystemCeiling, + read:func(string) (filesystemUsage,error) {return filesystemUsage{UsedPercent:61.26,ObservedAt:time.Date(2026,11,29,12,0,0,0,time.UTC)},nil}, + save:func() error {*saves++;return saveErr}, + } +} + +func doCeilingRequest(deps filesystemCeilingDeps,method,body string) *httptest.ResponseRecorder { + req:=httptest.NewRequest(method,"/api/storage/ceiling",strings.NewReader(body)) + w:=httptest.NewRecorder() + serveFilesystemCeiling(w,req,deps) + return w +} + +func TestFilesystemCeilingGet(t *testing.T) { + resetFilesystemCeiling(t,80) + saves:=0 + w:=doCeilingRequest(ceilingTestDeps(nil,&saves),http.MethodGet,"") + if w.Code!=200 || saves!=0 {t.Fatalf("status %d saves %d",w.Code,saves)} + if w.Header().Get("Cache-Control")!="no-store" {t.Fatal("response is cacheable")} + var got filesystemCeilingResponse + if err:=json.Unmarshal(w.Body.Bytes(),&got);err!=nil {t.Fatal(err)} + if got.Ceiling!=80 || got.Trigger!=78 || got.Used==nil || *got.Used!=61.3 || got.ObservedAt==nil {t.Fatalf("unexpected response %s",w.Body.String())} +} + +func TestFilesystemCeilingGetUnknownUsage(t *testing.T) { + resetFilesystemCeiling(t,80) + saves:=0 + deps:=ceilingTestDeps(nil,&saves) + deps.read=func(string) (filesystemUsage,error) {return filesystemUsage{},errFilesystemUsage} + w:=doCeilingRequest(deps,http.MethodGet,"") + if w.Code!=200 {t.Fatalf("status %d; unknown usage must not hide the ceiling",w.Code)} + var raw map[string]interface{} + if err:=json.Unmarshal(w.Body.Bytes(),&raw);err!=nil {t.Fatal(err)} + for _,key:=range []string{"filesystem_used_percent","filesystem_observed_at"} { + if value,ok:=raw[key];!ok || value!=nil {t.Fatalf("%s = %v; want null",key,value)} + } + if raw["max_filesystem_used_percent"]!=float64(80) {t.Fatalf("ceiling missing: %s",w.Body.String())} +} + +func TestFilesystemCeilingPostSavesAndReturnsStoredValue(t *testing.T) { + for _,value:=range []int{10,80,90,95} { + resetFilesystemCeiling(t,50) + saves:=0 + w:=doCeilingRequest(ceilingTestDeps(nil,&saves),http.MethodPost,fmt.Sprintf(`{"max_filesystem_used_percent":%d}`,value)) + if w.Code!=200 || saves!=1 {t.Fatalf("%d: status %d saves %d",value,w.Code,saves)} + if got:=recordingFilesystemCeiling.get();got!=value {t.Fatalf("stored %d; want %d",got,value)} + var got filesystemCeilingResponse + if err:=json.Unmarshal(w.Body.Bytes(),&got);err!=nil {t.Fatal(err)} + if got.Ceiling!=value || got.Trigger!=value-2 {t.Fatalf("response %s",w.Body.String())} + } +} + +func TestFilesystemCeilingPostRefusesInvalidRequests(t *testing.T) { + bodies:=[]string{ + `{"max_filesystem_used_percent":9}`,`{"max_filesystem_used_percent":96}`,`{"max_filesystem_used_percent":80.5}`, + `{"max_filesystem_used_percent":"80"}`,`{"max_filesystem_used_percent":null}`,`{"max_filesystem_used_percent":1e1}`, + `{}`,`{"max_filesystem_used_percent":80,"extra":1}`,`{"max_filesystem_used_percent":80} {}`,`not json`,``, + `{"max_filesystem_used_percent":80,"pad":"`+strings.Repeat("x",2000)+`"}`, + } + for _,body:=range bodies { + resetFilesystemCeiling(t,70) + saves:=0 + w:=doCeilingRequest(ceilingTestDeps(nil,&saves),http.MethodPost,body) + if w.Code!=400 {t.Fatalf("%.60q: status %d",body,w.Code)} + if saves!=0 || recordingFilesystemCeiling.get()!=70 {t.Fatalf("%.60q changed state: saves %d ceiling %d",body,saves,recordingFilesystemCeiling.get())} + } +} + +func TestFilesystemCeilingPostRestoresValueWhenSaveFails(t *testing.T) { + resetFilesystemCeiling(t,80) + saves:=0 + w:=doCeilingRequest(ceilingTestDeps(errors.New("disk failure"),&saves),http.MethodPost,`{"max_filesystem_used_percent":90}`) + if w.Code!=500 || saves!=1 {t.Fatalf("status %d saves %d",w.Code,saves)} + if got:=recordingFilesystemCeiling.get();got!=80 {t.Fatalf("ceiling = %d after failed save; want 80",got)} + if strings.Contains(w.Body.String(),"disk failure") {t.Fatal("internal error text returned to client")} +} + +func TestFilesystemCeilingRefusesOtherMethods(t *testing.T) { + for _,method:=range []string{http.MethodPut,http.MethodDelete,http.MethodPatch} { + saves:=0 + w:=doCeilingRequest(ceilingTestDeps(nil,&saves),method,`{"max_filesystem_used_percent":90}`) + if w.Code!=405 || w.Header().Get("Allow")!="GET, POST" || saves!=0 {t.Fatalf("%s: status %d allow %q saves %d",method,w.Code,w.Header().Get("Allow"),saves)} + } +} diff --git a/cmd/simplenvr/filesystem_prune.go b/cmd/simplenvr/filesystem_prune.go new file mode 100644 index 0000000..a7f47f8 --- /dev/null +++ b/cmd/simplenvr/filesystem_prune.go @@ -0,0 +1,309 @@ +package main + +import ( + "context" + "errors" + "io" + "log" + "os" + "path/filepath" + "sort" + "sync" + "time" + + "golang.org/x/sys/unix" +) + +// Filesystem pruning (issue #14, CP4). A separate job, not part of retention cleanup. +// When the recordings filesystem is at or above the ceiling minus 2 points it removes +// the oldest day that still has published MP4 files from each camera, one day per +// camera per pass, never the newest day folder. Deletion runs under the shared media +// lease and the published deletion engine, in the lock order media ownership, +// retentionPolicyMu, NVR.mu. Footage deleted here is not recoverable. + +// An increase of available bytes smaller than this is treated as no effect. +const pruneMinGainBytes uint64 = 1<<20 + +// The first pass is one interval after startup, like the usage monitor. +const filesystemPruneInterval = 5*time.Minute + +type pruneTarget struct { + id,name,dir string + camera *Camera +} + +type pruneDayResult struct { + cameraID,cameraName,day string + result publishedDeleteResult + err error +} + +type pruneDayKey struct{name,day string} + +type filesystemPruner struct { + n *NVR + root string + ceiling *filesystemCeilingSetting + read func(string) (filesystemUsage,error) + persist func() error + unlink func(int,string,int) error + interval time.Duration + requests chan struct{} + + passMu sync.Mutex + + mu sync.Mutex + guardActive bool + guardBaseline uint64 + notMet bool + notMetCeiling int +} + +func newFilesystemPruner(n *NVR,ceiling *filesystemCeilingSetting,read func(string) (filesystemUsage,error),persist func() error) *filesystemPruner { + return &filesystemPruner{n:n,root:recordingsRoot,ceiling:ceiling,read:read,persist:persist,unlink:unix.Unlinkat,interval:filesystemPruneInterval,requests:make(chan struct{},1)} +} + +var recordingFilesystemPruner=newFilesystemPruner(nvr,recordingFilesystemCeiling,readFilesystemUsage,func() error {return nvr.save()}) + +// requestPass asks the running job for a pass soon, for example after the ceiling +// changed. It never blocks and never deletes by itself. It does not re-arm the +// ceiling-not-met message: that message is logged once per ceiling value. +func (p *filesystemPruner) requestPass() { + select {case p.requests<-struct{}{}:default:} +} + +// Run blocks until ctx is canceled. Start it with shutdownGate.startBackgroundJob so +// shutdown cancels and joins it before final persistence. +func (p *filesystemPruner) Run(ctx context.Context) { + ticker:=time.NewTicker(p.interval) + defer ticker.Stop() + log.Println("Filesystem pruner started") + p.run(ctx,ticker.C) +} + +func (p *filesystemPruner) run(ctx context.Context,ticks <-chan time.Time) { + for { + select { + case <-ctx.Done(): + return + case _,ok:=<-ticks: + if !ok || ctx.Err()!=nil {return} + p.runPass(ctx) + case <-p.requests: + if ctx.Err()!=nil {return} + p.runPass(ctx) + } + } +} + +func (p *filesystemPruner) snapshot() []pruneTarget { + p.n.mu.RLock();defer p.n.mu.RUnlock() + targets:=make([]pruneTarget,0,len(p.n.cameras)) + for id,cam:=range p.n.cameras { + if cam!=nil {targets=append(targets,pruneTarget{id:id,name:cam.Name,dir:cam.RecordDir,camera:cam})} + } + sort.Slice(targets,func(i,j int) bool {return targets[i].idp.guardBaseline && usage.AvailableBytes-p.guardBaseline>=pruneMinGainBytes { + p.guardActive=false + log.Println("Filesystem pruning resumed: available space rose by at least 1 MiB") + return false + } + return true +} + +func (p *filesystemPruner) setGuard(baseline uint64) { + p.mu.Lock();already:=p.guardActive;p.guardActive=true;p.guardBaseline=baseline;p.mu.Unlock() + if !already {log.Println("Filesystem pruning paused: deleting did not raise available space by at least 1 MiB")} +} + +// runPass is one prune pass. Passes never overlap each other, and each takes the +// shared media lease, so a pass never overlaps retention cleanup either. +func (p *filesystemPruner) runPass(ctx context.Context) { + p.passMu.Lock();defer p.passMu.Unlock() + if ctx.Err()!=nil || p.n.shuttingDown.Load() {return} + ceiling:=p.ceiling.get() + trigger:=float64(filesystemPruneTrigger(ceiling)) + usage,err:=p.read(p.root) + if err!=nil {log.Println("Filesystem pruning skipped: recording filesystem usage is unknown");return} + if usage.UsedPercent=float64(ceiling) {p.enterNotMet(before.UsedPercent,ceiling)} + return + } + p.setNotMet(false) + if deleted==0 {return} + after,err:=p.read(p.root) + if err!=nil { + log.Println("Filesystem pruning could not measure usage after deleting") + p.setGuard(before.AvailableBytes) + return + } + if after.AvailableBytes>before.AvailableBytes && after.AvailableBytes-before.AvailableBytes>=pruneMinGainBytes {return} + p.setGuard(after.AvailableBytes) +} + +// pruneUnderLease acquires the media lease, then the policy read lock, then measures +// again so the before-reading belongs to the same moment as the deletion. +func (p *filesystemPruner) pruneUnderLease(ctx context.Context,trigger float64) (results []pruneDayResult,before filesystemUsage,inspectFailed bool,ok bool) { + targets:=p.snapshot() + lease,err:=recordingMediaOwnership.acquire(ctx) + if err!=nil {return} + defer lease.release() + retentionPolicyMu.RLock() + defer retentionPolicyMu.RUnlock() + before,err=p.read(p.root) + if err!=nil {log.Println("Filesystem pruning skipped: recording filesystem usage is unknown");return} + if before.UsedPercent0: + log.Printf("Filesystem pruning incomplete for camera %s day %s: removed %d recording(s), %d could not be removed; inspect media",t.id,day,res.Count,res.Failures) + default: + log.Printf("Filesystem pruning removed %d recording(s), %d bytes, from camera %s day %s",res.Count,res.Bytes,t.id,day) + } + } + return +} + +// Event records for a pruned day are removed by camera name and UTC start day, so +// cameras that share a name share the match. A day that was only partly removed keeps +// its event records, because footage for them may remain. +func (p *filesystemPruner) removePrunedEvents(results []pruneDayResult) { + pruned:=map[pruneDayKey]bool{} + blocked:=map[pruneDayKey]bool{} + for _,r:=range results { + key:=pruneDayKey{name:r.cameraName,day:r.day} + if r.err!=nil || r.result.Failures>0 || r.result.Count==0 {blocked[key]=true;continue} + pruned[key]=true + } + for key:=range blocked {delete(pruned,key)} + if len(pruned)==0 {return} + p.n.mu.Lock() + kept:=make([]Event,0,len(p.n.events)) + for _,event:=range p.n.events { + if pruned[pruneDayKey{name:event.CameraName,day:event.StartTime.UTC().Format(stampDayLayout)}] {continue} + kept=append(kept,event) + } + removed:=len(p.n.events)-len(kept) + if removed>0 {p.n.events=kept} + p.n.mu.Unlock() + if removed==0 {return} + log.Printf("Filesystem pruning removed %d event record(s) for pruned days",removed) + if err:=p.persist();err!=nil {log.Printf("Failed to save events after pruning: %v",err)} +} + +// oldestPrunableDay returns the oldest stamped day folder, other than the newest one, +// that contains at least one regular .mp4 file, or "" when there is none. Folders +// with only other files are skipped without a log. The newest day folder is the floor +// and is never returned. Directories are opened without following symlinks. +func oldestPrunableDay(dir string) (string,error) { + dir=filepath.Clean(dir) + if !filepath.IsAbs(dir) || dir==string(filepath.Separator) {return "",errPublishedDeletionRefused} + parent,err:=openCameraDeleteDirectory(unix.AT_FDCWD,filepath.Dir(dir)) + if err!=nil {return "",err} + defer parent.Close() + root,err:=openCameraDeleteDirectory(int(parent.Fd()),filepath.Base(dir)) + if err!=nil {return "",err} + defer root.Close() + names,err:=readDirNamesLimited(root) + if err!=nil {return "",err} + var days []string + for _,name:=range names { + if !isStampedDayName(name) {continue} + var st unix.Stat_t + if err:=unix.Fstatat(int(root.Fd()),name,&st,unix.AT_SYMLINK_NOFOLLOW);err!=nil {return "",err} + if st.Mode&unix.S_IFMT!=unix.S_IFDIR {continue} + days=append(days,name) + } + if len(days)>maxStampedScanDays {return "",errPublishedDeletionRefused} + sort.Strings(days) + var firstErr error + for i:=0;i+1publishedDeletionEntryLimit {return nil,errPublishedDeletionRefused} + if err==io.EOF {return all,nil} + if err!=nil {return nil,err} + } +} diff --git a/cmd/simplenvr/filesystem_prune_notmet_test.go b/cmd/simplenvr/filesystem_prune_notmet_test.go new file mode 100644 index 0000000..66031d1 --- /dev/null +++ b/cmd/simplenvr/filesystem_prune_notmet_test.go @@ -0,0 +1,31 @@ +package main + +import ( + "context" + "strings" + "testing" +) + +// The ceiling-not-met line is logged once per ceiling value. Saving the same ceiling +// again must not repeat it; a different ceiling logs it again once. +func TestPruneCeilingNotMetLogsOncePerCeilingValue(t *testing.T) { + f:=newPruneFixture(t,"a") + logs:=captureLog(t) + f.file("a","20991231/floor.mp4") + ctx:=context.Background() + count:=func() int {return strings.Count(logs(),"cannot meet the ceiling")} + f.p.runPass(ctx) + if got:=count();got!=1 {t.Fatalf("first pass logged %d times",got)} + for i:=0;i<3;i++ { + f.p.requestPass() + f.p.runPass(ctx) + } + if got:=count();got!=1 {t.Fatalf("same ceiling logged %d times after repeated requests",got)} + f.ceiling.set(70) + f.p.requestPass() + f.p.runPass(ctx) + if got:=count();got!=2 {t.Fatalf("a different ceiling logged %d times; want 2",got)} + f.p.requestPass() + f.p.runPass(ctx) + if got:=count();got!=2 {t.Fatalf("the new ceiling repeated: %d",got)} +} diff --git a/cmd/simplenvr/filesystem_prune_test.go b/cmd/simplenvr/filesystem_prune_test.go new file mode 100644 index 0000000..d728df0 --- /dev/null +++ b/cmd/simplenvr/filesystem_prune_test.go @@ -0,0 +1,398 @@ +package main + +import ( + "bytes" + "context" + "errors" + "log" + "net/http" + "os" + "path/filepath" + "strings" + "sync" + "sync/atomic" + "testing" + "time" + + "golang.org/x/sys/unix" +) + +type fakeUsage struct { + mu sync.Mutex + used float64 + available uint64 + err error +} + +func (f *fakeUsage) read(string) (filesystemUsage,error) { + f.mu.Lock();defer f.mu.Unlock() + if f.err!=nil {return filesystemUsage{},f.err} + return filesystemUsage{UsedPercent:f.used,AvailableBytes:f.available,ObservedAt:time.Now().UTC()},nil +} +func (f *fakeUsage) add(bytes uint64) {f.mu.Lock();f.available+=bytes;f.mu.Unlock()} +func (f *fakeUsage) setAvailable(bytes uint64) {f.mu.Lock();f.available=bytes;f.mu.Unlock()} +func (f *fakeUsage) setUsed(percent float64) {f.mu.Lock();f.used=percent;f.mu.Unlock()} +func (f *fakeUsage) setErr(err error) {f.mu.Lock();f.err=err;f.mu.Unlock()} + +type syncBuffer struct { + mu sync.Mutex + b bytes.Buffer +} + +func (s *syncBuffer) Write(p []byte) (int,error) {s.mu.Lock();defer s.mu.Unlock();return s.b.Write(p)} +func (s *syncBuffer) String() string {s.mu.Lock();defer s.mu.Unlock();return s.b.String()} + +func captureLog(t *testing.T) func() string { + t.Helper() + buf:=&syncBuffer{} + previous:=log.Writer() + log.SetOutput(buf) + t.Cleanup(func(){log.SetOutput(previous)}) + return buf.String +} + +func waitFor(t *testing.T,cond func() bool,what string) { + t.Helper() + deadline:=time.Now().Add(3*time.Second) + for time.Now().Before(deadline) { + if cond() {return} + time.Sleep(5*time.Millisecond) + } + t.Fatalf("timed out waiting for %s",what) +} + +type pruneFixture struct { + t *testing.T + n *NVR + p *filesystemPruner + fs *fakeUsage + ceiling *filesystemCeilingSetting + base string + persists atomic.Int32 + freePerUnlink uint64 + fail map[string]error + hook func(name string) +} + +func newPruneFixture(t *testing.T,ids ...string) *pruneFixture { + t.Helper() + f:=&pruneFixture{t:t,base:t.TempDir(),fs:&fakeUsage{used:85,available:100<<20},ceiling:&filesystemCeilingSetting{percent:80},fail:map[string]error{}} + f.n=&NVR{cameras:map[string]*Camera{},cameraOrder:[]string{},events:[]Event{}} + for _,id:=range ids { + dir:=filepath.Join(f.base,id) + if err:=os.MkdirAll(dir,0755);err!=nil {t.Fatal(err)} + f.n.cameras[id]=&Camera{ID:id,Name:id,RecordDir:dir,RecordingMode:ModeContinuous,RetentionDays:7} + f.n.cameraOrder=append(f.n.cameraOrder,id) + } + f.p=newFilesystemPruner(f.n,f.ceiling,f.fs.read,func() error {f.persists.Add(1);return nil}) + f.p.unlink=func(fd int,name string,flags int) error { + if f.hook!=nil && flags==0 {f.hook(name)} + if err,bad:=f.fail[name];bad && flags==0 {return err} + err:=unix.Unlinkat(fd,name,flags) + if err==nil && flags==0 && strings.HasSuffix(name,".mp4") {f.fs.add(f.freePerUnlink)} + return err + } + return f +} + +func (f *pruneFixture) path(id,rel string) string {return filepath.Join(f.base,id,filepath.FromSlash(rel))} + +func (f *pruneFixture) file(id,rel string) { + f.t.Helper() + path:=f.path(id,rel) + if err:=os.MkdirAll(filepath.Dir(path),0755);err!=nil {f.t.Fatal(err)} + if err:=os.WriteFile(path,[]byte("x"),0600);err!=nil {f.t.Fatal(err)} +} + +func (f *pruneFixture) exists(id,rel string) bool { + _,err:=os.Lstat(f.path(id,rel)) + return err==nil +} + +func (f *pruneFixture) mustExist(id,rel string) { + f.t.Helper() + if !f.exists(id,rel) {f.t.Fatalf("%s/%s was removed",id,rel)} +} + +func (f *pruneFixture) mustBeGone(id,rel string) { + f.t.Helper() + if f.exists(id,rel) {f.t.Fatalf("%s/%s still exists",id,rel)} +} + +func (f *pruneFixture) threeDays(id string) { + for _,day:=range []string{"20261101","20261102","20261103"} { + f.file(id,day+"/seg1.mp4") + f.file(id,day+"/seg2.mp4") + } +} + +func TestPruneBelowTriggerDeletesNothing(t *testing.T) { + f:=newPruneFixture(t,"a") + f.threeDays("a") + f.fs.setUsed(77.9) + f.p.runPass(context.Background()) + for _,day:=range []string{"20261101","20261102","20261103"} {f.mustExist("a",day+"/seg1.mp4")} + if f.persists.Load()!=0 {t.Fatal("saved configuration without pruning")} +} + +func TestPruneAtOrAboveTriggerRemovesOneOldestDayPerCamera(t *testing.T) { + for _,used:=range []float64{78.0,79.5,91.5} { + f:=newPruneFixture(t,"a","b") + f.threeDays("a") + f.threeDays("b") + f.fs.setUsed(used) + f.p.runPass(context.Background()) + for _,id:=range []string{"a","b"} { + f.mustBeGone(id,"20261101") + f.mustExist(id,"20261102/seg1.mp4") + f.mustExist(id,"20261102/seg2.mp4") + f.mustExist(id,"20261103/seg1.mp4") + } + } +} + +func TestPruneUsesTheCeilingMinusTwo(t *testing.T) { + f:=newPruneFixture(t,"a") + f.threeDays("a") + f.ceiling.set(60) + f.fs.setUsed(57.9) + f.p.runPass(context.Background()) + f.mustExist("a","20261101/seg1.mp4") + f.fs.setUsed(58) + f.p.runPass(context.Background()) + f.mustBeGone("a","20261101") +} + +func TestPruneNeverRemovesTheNewestDay(t *testing.T) { + f:=newPruneFixture(t,"a","single") + f.threeDays("a") + f.file("single","20261105/only.mp4") + f.freePerUnlink=2<<20 + for i:=0;i<6;i++ {f.p.runPass(context.Background())} + f.mustBeGone("a","20261101") + f.mustBeGone("a","20261102") + f.mustExist("a","20261103/seg1.mp4") + f.mustExist("a","20261103/seg2.mp4") + f.mustExist("single","20261105/only.mp4") +} + +func TestPruneNoEffectGuardPausesAndResumes(t *testing.T) { + f:=newPruneFixture(t,"a") + logs:=captureLog(t) + for _,day:=range []string{"20261101","20261102","20261103","20261104"} {f.file("a",day+"/s.mp4")} + ctx:=context.Background() + const mib=uint64(1<<20) + f.p.runPass(ctx) + f.mustBeGone("a","20261101") + f.p.runPass(ctx) + f.mustExist("a","20261102/s.mp4") + f.fs.setAvailable(100<<20+mib-1) + f.p.runPass(ctx) + f.mustExist("a","20261102/s.mp4") + f.fs.setAvailable(100<<20+mib) + f.p.runPass(ctx) + f.mustBeGone("a","20261102") + f.mustExist("a","20261103/s.mp4") + if strings.Count(logs(),"resumed")!=1 {t.Fatalf("expected one resume line: %s",logs())} +} + +func TestPruneGuardThresholdIsOneMiB(t *testing.T) { + for _,tc:=range []struct{name string;freed uint64;prunesNext bool}{ + {"one byte under",1<<20-1,false}, + {"exactly one MiB",1<<20,true}, + {"more than one MiB",3<<20,true}, + {"nothing",0,false}, + } { + t.Run(tc.name,func(t *testing.T) { + f:=newPruneFixture(t,"a") + for _,day:=range []string{"20261101","20261102","20261103"} {f.file("a",day+"/s.mp4")} + f.freePerUnlink=tc.freed + f.p.runPass(context.Background()) + f.mustBeGone("a","20261101") + f.p.runPass(context.Background()) + if tc.prunesNext {f.mustBeGone("a","20261102")} else {f.mustExist("a","20261102/s.mp4")} + }) + } +} + +func TestPruneUnknownMeasurementDeletesNothingAndLogs(t *testing.T) { + f:=newPruneFixture(t,"a") + logs:=captureLog(t) + f.threeDays("a") + f.fs.setErr(errors.New("statfs failed")) + f.p.runPass(context.Background()) + f.mustExist("a","20261101/seg1.mp4") + if !strings.Contains(logs(),"usage is unknown") {t.Fatalf("unknown measurement was not logged: %q",logs())} +} + +func TestPrunePartialFailureContinues(t *testing.T) { + f:=newPruneFixture(t,"a","b") + logs:=captureLog(t) + for _,name:=range []string{"f1.mp4","f2.mp4","f3.mp4"} {f.file("a","20261101/"+name)} + f.file("a","20261102/n.mp4") + f.file("b","20261101/g1.mp4") + f.file("b","20261102/n.mp4") + f.fail["f2.mp4"]=unix.EACCES + day:=time.Date(2026,11,1,10,0,0,0,time.UTC) + f.n.events=[]Event{{CameraName:"a",StartTime:day},{CameraName:"b",StartTime:day}} + f.p.runPass(context.Background()) + f.mustBeGone("a","20261101/f1.mp4") + f.mustBeGone("a","20261101/f3.mp4") + f.mustExist("a","20261101/f2.mp4") + f.mustBeGone("b","20261101") + f.mustExist("a","20261102/n.mp4") + f.mustExist("b","20261102/n.mp4") + if !strings.Contains(logs(),"incomplete for camera a") {t.Fatalf("partial failure was not logged: %q",logs())} + if len(f.n.events)!=1 || f.n.events[0].CameraName!="a" {t.Fatalf("events after partial failure: %+v",f.n.events)} +} + +func TestPruneSkipsLeftoverOnlyDaysSilently(t *testing.T) { + f:=newPruneFixture(t,"a") + logs:=captureLog(t) + f.file("a","20261101/leftover.tmp") + f.file("a","20261102/s.mp4") + f.file("a","20261103/n.mp4") + f.freePerUnlink=2<<20 + for i:=0;i<5;i++ {f.p.runPass(context.Background())} + f.mustBeGone("a","20261102") + f.mustExist("a","20261101/leftover.tmp") + f.mustExist("a","20261103/n.mp4") + if strings.Contains(logs(),"20261101") {t.Fatalf("leftover-only day was logged: %q",logs())} + if got:=strings.Count(logs(),"cannot meet the ceiling");got!=1 {t.Fatalf("ceiling-not-met logged %d times: %q",got,logs())} +} + +func TestPruneCeilingNotMetStateResets(t *testing.T) { + f:=newPruneFixture(t,"a") + logs:=captureLog(t) + f.file("a","20261103/n.mp4") + ctx:=context.Background() + f.p.runPass(ctx) + f.p.runPass(ctx) + if got:=strings.Count(logs(),"cannot meet the ceiling");got!=1 {t.Fatalf("logged %d times",got)} + f.fs.setUsed(50) + f.p.runPass(ctx) + f.fs.setUsed(85) + f.p.runPass(ctx) + if got:=strings.Count(logs(),"cannot meet the ceiling");got!=2 {t.Fatalf("after recovery logged %d times",got)} +} + +func TestPruneLeavesEverythingElseAlone(t *testing.T) { + f:=newPruneFixture(t,"a") + f.file("a","20261101/old.mp4") + f.file("a","20261101/keep.tmp") + f.file("a","20261103/new.mp4") + for _,rel:=range []string{"buffer/b.mp4","temp/t.mp4","staging/s.mp4","loose.mp4","loose.tmp","20261101_loose.mp4"} {f.file("a",rel)} + f.p.runPass(context.Background()) + f.mustBeGone("a","20261101/old.mp4") + f.mustExist("a","20261101/keep.tmp") + f.mustExist("a","20261103/new.mp4") + for _,rel:=range []string{"buffer/b.mp4","temp/t.mp4","staging/s.mp4","loose.mp4","loose.tmp","20261101_loose.mp4"} {f.mustExist("a",rel)} +} + +func TestPruneRemovesEventsForThePrunedDay(t *testing.T) { + f:=newPruneFixture(t,"a","b","c") + f.n.cameras["a"].Name="Front" + f.n.cameras["b"].Name="Front" + f.n.cameras["c"].Name="Back" + f.file("a","20261101/s.mp4") + f.file("a","20261102/s.mp4") + f.file("b","20261101/s.mp4") + f.file("c","20261101/s.mp4") + mk:=func(name string,day int,hour int) Event {return Event{CameraName:name,Label:"x",StartTime:time.Date(2026,11,day,hour,0,0,0,time.UTC)}} + f.n.events=[]Event{mk("Front",1,0),mk("Front",1,23),mk("Front",2,10),mk("Back",1,10),mk("Gone",1,10)} + f.p.runPass(context.Background()) + f.mustBeGone("a","20261101") + f.mustExist("b","20261101/s.mp4") + f.mustExist("c","20261101/s.mp4") + names:=[]string{} + for _,event:=range f.n.events {names=append(names,event.CameraName+"@"+event.StartTime.Format("02"))} + want:="Front@02 Back@01 Gone@01" + if got:=strings.Join(names," ");got!=want {t.Fatalf("events = %q; want %q",got,want)} + if f.persists.Load()!=1 {t.Fatalf("saved %d times; want 1",f.persists.Load())} +} + +func TestPruneRunsOnCeilingChange(t *testing.T) { + f:=newPruneFixture(t,"a") + f.fs.setUsed(60) + f.freePerUnlink=2<<20 + f.file("a","20261101/s.mp4") + f.file("a","20261102/s.mp4") + ctx,cancel:=context.WithCancel(context.Background()) + done:=make(chan struct{}) + go func(){defer close(done);f.p.run(ctx,nil)}() + t.Cleanup(func(){cancel();<-done}) + f.mustExist("a","20261101/s.mp4") + deps:=filesystemCeilingDeps{setting:f.ceiling,read:f.fs.read,save:func() error {return nil},onChange:f.p.requestPass} + if w:=doCeilingRequest(deps,http.MethodPost,`{"max_filesystem_used_percent":50}`);w.Code!=200 {t.Fatalf("status %d",w.Code)} + waitFor(t,func() bool {return !f.exists("a","20261101")},"oldest day pruned after the ceiling change") + f.mustExist("a","20261102/s.mp4") +} + +func TestPruneNeverStopsRecording(t *testing.T) { + f:=newPruneFixture(t,"a") + stopped:=atomic.Bool{} + cam:=f.n.cameras["a"] + cam.IsRecording=true + cam.recordCancel=func(){stopped.Store(true)} + f.threeDays("a") + f.freePerUnlink=2<<20 + for i:=0;i<4;i++ {f.p.runPass(context.Background())} + if !cam.IsRecording || stopped.Load() {t.Fatal("pruning stopped or changed a recorder")} + if f.n.cameras["a"]!=cam {t.Fatal("camera registry changed")} +} + +func TestPruneAndRetentionNeverDeleteConcurrently(t *testing.T) { + t.Run("retention holds the lease first",func(t *testing.T) { + f:=newPruneFixture(t,"a") + f.file("a","20261101/s.mp4") + f.file("a","20261102/s.mp4") + target:=snapshotRetentionCleanup(f.n)[0] + entered:=make(chan struct{}) + release:=make(chan struct{}) + retentionDone:=make(chan struct{}) + go func(){ + defer close(retentionDone) + admitRetentionDeletion(context.Background(),f.n,target,recordingMediaOwnership,func(context.Context,*mediaMutationLease,string,time.Duration,func() error) error {close(entered);<-release;return nil}) + }() + <-entered + passDone:=make(chan struct{}) + go func(){defer close(passDone);f.p.runPass(context.Background())}() + waitFor(t,func() bool {return recordingMediaOwnership.waiting.Load()==1},"the prune pass to wait for the lease") + f.mustExist("a","20261101/s.mp4") + close(release) + <-retentionDone + <-passDone + f.mustBeGone("a","20261101") + }) + t.Run("prune holds the lease first",func(t *testing.T) { + f:=newPruneFixture(t,"a") + f.file("a","20261101/s.mp4") + f.file("a","20261102/s.mp4") + target:=snapshotRetentionCleanup(f.n)[0] + inUnlink:=make(chan struct{}) + proceed:=make(chan struct{}) + var once sync.Once + f.hook=func(string){once.Do(func(){close(inUnlink);<-proceed})} + passDone:=make(chan struct{}) + go func(){defer close(passDone);f.p.runPass(context.Background())}() + <-inUnlink + var entered atomic.Bool + retentionDone:=make(chan struct{}) + go func(){ + defer close(retentionDone) + admitRetentionDeletion(context.Background(),f.n,target,recordingMediaOwnership,func(context.Context,*mediaMutationLease,string,time.Duration,func() error) error {entered.Store(true);return nil}) + }() + waitFor(t,func() bool {return recordingMediaOwnership.waiting.Load()==1},"retention cleanup to wait for the lease") + if entered.Load() {t.Fatal("retention cleanup ran while pruning held the lease")} + close(proceed) + <-passDone + <-retentionDone + if !entered.Load() {t.Fatal("retention cleanup never ran after pruning finished")} + }) +} + +func TestPruneJobTiming(t *testing.T) { + if filesystemPruneInterval!=5*time.Minute {t.Fatalf("interval = %v",filesystemPruneInterval)} + p:=newFilesystemPruner(&NVR{cameras:map[string]*Camera{}},&filesystemCeilingSetting{percent:80},(&fakeUsage{}).read,func() error {return nil}) + if p.interval!=filesystemPruneInterval {t.Fatalf("job interval = %v",p.interval)} +} diff --git a/cmd/simplenvr/handlers.go b/cmd/simplenvr/handlers.go index db1fdbd..532ef65 100644 --- a/cmd/simplenvr/handlers.go +++ b/cmd/simplenvr/handlers.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "errors" "fmt" "net/http" ) @@ -22,11 +23,26 @@ func deleteAllCamerasHandler(w http.ResponseWriter,r *http.Request) { camerasHandler(w,r) } +var ( + errRetentionRequestInvalid=errors.New("Invalid request") + errRetentionDaysRequired=errors.New("retention_days is required") + errRetentionDaysRange=errors.New("Retention days must be between 0 and 365") +) + +// decodeRetentionRequest requires retention_days, so a body that omits it cannot be +// read as 0 and silently turn age cleanup off. 0 (no age limit) must be sent explicitly. +func decodeRetentionRequest(r *http.Request) (string,int,error) { + var data struct {ID string `json:"id"`;RetentionDays *int `json:"retention_days"`} + if err:=json.NewDecoder(r.Body).Decode(&data);err!=nil {return "",0,errRetentionRequestInvalid} + if data.RetentionDays==nil {return "",0,errRetentionDaysRequired} + if *data.RetentionDays<0 || *data.RetentionDays>maxCameraRetentionDays {return "",0,errRetentionDaysRange} + return data.ID,*data.RetentionDays,nil +} + func updateRetentionHandler(w http.ResponseWriter,r *http.Request) { - var data struct {ID string `json:"id"`;RetentionDays int `json:"retention_days"`} - if err:=json.NewDecoder(r.Body).Decode(&data);err!=nil {http.Error(w,"Invalid request",400);return} - if data.RetentionDays<1 || data.RetentionDays>maxCameraRetentionDays {http.Error(w,"Retention days must be between 1 and 365",400);return} - if err:=setCameraRetention(nvr,data.ID,data.RetentionDays);err!=nil { + id,days,err:=decodeRetentionRequest(r) + if err!=nil {http.Error(w,err.Error(),400);return} + if err:=setCameraRetention(nvr,id,days);err!=nil { status:=400;if err==errCameraMissing {status=404} http.Error(w,err.Error(),status);return } @@ -34,10 +50,9 @@ func updateRetentionHandler(w http.ResponseWriter,r *http.Request) { } func updateRetentionAllHandler(w http.ResponseWriter,r *http.Request) { - var data struct {RetentionDays int `json:"retention_days"`} - if err:=json.NewDecoder(r.Body).Decode(&data);err!=nil {http.Error(w,"Invalid request",400);return} - if data.RetentionDays<1 || data.RetentionDays>maxCameraRetentionDays {http.Error(w,"Retention days must be between 1 and 365",400);return} - if err:=setAllCameraRetention(nvr,data.RetentionDays);err!=nil {http.Error(w,err.Error(),400);return} + _,days,err:=decodeRetentionRequest(r) + if err!=nil {http.Error(w,err.Error(),400);return} + if err:=setAllCameraRetention(nvr,days);err!=nil {http.Error(w,err.Error(),400);return} finishCameraUpdate(w,r) } @@ -95,7 +110,7 @@ func camerasHandler(w http.ResponseWriter,r *http.Request) { for _,id:=range nvr.cameraOrder { cam:=nvr.cameras[id] if cam==nil {continue} - days:=cam.RetentionDays;if days==0 {days=7} + days:=cam.RetentionDays mode:="Continuous";if cam.RecordingMode==ModeEventBased {mode="Event Based"} else if cam.RecordingMode==ModeNoRecording {mode="No Recording"} health:=continuousRecordingNotice{} if cam.IsRecording && cam.RecordingMode==ModeContinuous {health=snapshotContinuousHealth(cam)} diff --git a/cmd/simplenvr/main.go b/cmd/simplenvr/main.go index ae1b76b..dbafb51 100644 --- a/cmd/simplenvr/main.go +++ b/cmd/simplenvr/main.go @@ -127,6 +127,7 @@ func main() { http.HandleFunc("/api/stream/",streamProxyHandler) http.HandleFunc("/api/recordings/list",listRecordingsHandler) http.HandleFunc("/api/storage/status",storageStatusHandler) + http.HandleFunc("/api/storage/ceiling",filesystemCeilingHandler) http.HandleFunc("/api/recovery/status",recoveryStatusHandler) http.HandleFunc("/api/timeline/recordings",timelineRecordingsHandler) http.HandleFunc("/api/recordings/delete-all",deleteAllRecordingsHandler) @@ -145,6 +146,8 @@ func main() { server:=&http.Server{Addr:":443",Handler:gate,ReadHeaderTimeout:10*time.Second,ReadTimeout:30*time.Second,IdleTimeout:60*time.Second,MaxHeaderBytes:32768} autoStartRecordings() gate.startBackgroundJob(func(ctx context.Context){cleanupRoutine(ctx,nvr)}) + gate.startBackgroundJob(recordingFilesystemUsage.Run) + gate.startBackgroundJob(recordingFilesystemPruner.Run) log.Println("SimpleNVR starting authenticated HTTPS server on :443...") serveErr:=runAuthenticatedServer(appCtx,nvr,gate,server,certPath,keyPath) cleanupCtx,cancel:=context.WithTimeout(context.Background(),5*time.Second);defer cancel() diff --git a/cmd/simplenvr/persistence.go b/cmd/simplenvr/persistence.go index 8c66ccf..091b07a 100644 --- a/cmd/simplenvr/persistence.go +++ b/cmd/simplenvr/persistence.go @@ -48,6 +48,7 @@ func decodeState(raw []byte) (persistedState, error) { } if cam.RecordingMode == ModeNoRecording { cam.IsRecording = false } } + if _, err := storedFilesystemCeiling(raw); err != nil { return s, fmt.Errorf("invalid filesystem usage ceiling: %w", err) } seen := make(map[string]bool) order := make([]string, 0, len(s.Cameras)) for _, id := range s.CameraOrder { @@ -73,7 +74,7 @@ func (n *NVR) saveAtWithWriter(path string,write func(string,[]byte)error) error persistenceMu.Lock() defer persistenceMu.Unlock() n.mu.RLock() - raw, err := json.MarshalIndent(persistedState{n.cameras, n.cameraOrder, n.events}, "", " ") + raw, err := json.MarshalIndent(persistedDocument{persistedState{n.cameras, n.cameraOrder, n.events}, recordingFilesystemCeiling.get()}, "", " ") n.mu.RUnlock() if err != nil { return err } raw = append(raw, '\n') @@ -106,8 +107,10 @@ func (n *NVR) loadAt(path string) error { if err != nil { return err } s, err := decodeState(raw) if err != nil { return fmt.Errorf("invalid configuration %s; backup if present: %s.bak: %w", path, path, err) } + ceiling, _ := storedFilesystemCeiling(raw) n.mu.Lock() n.cameras, n.cameraOrder, n.events = s.Cameras, s.CameraOrder, s.Events n.mu.Unlock() + recordingFilesystemCeiling.set(ceiling) return nil } diff --git a/cmd/simplenvr/published_deletion_engine.go b/cmd/simplenvr/published_deletion_engine.go index 6a5e9c7..9bdbf74 100644 --- a/cmd/simplenvr/published_deletion_engine.go +++ b/cmd/simplenvr/published_deletion_engine.go @@ -40,6 +40,10 @@ func deletePublishedLeasedWithUnlink(ctx context.Context,lease *mediaMutationLea // is removed only by an atomic empty-directory rmdir after its files were deleted, // so a late entry keeps the folder. There is no recursive sweep. A retention-only // work policy may skip newer-day contents; generic/delete-all callers pass none. +// A work policy may also scope the pass to one day (onlyDay) and tolerate failures of +// single candidates (continueOnEntryError); then Failures counts those candidates and +// the pass still returns a nil error. Directory identity and guard failures always +// end the pass. func deletePublishedLeasedWithWork(ctx context.Context,lease *mediaMutationLease,dir string,selectFile func(string,time.Time) bool,guard func() error,unlink func(int,string,int) error,work *publishedDeletionWork) (result publishedDeleteResult,resultErr error) { if work==nil {work=newPublishedDeletionWork()} defer func(){if resultErr!=nil {result.Failures=1}}() @@ -92,6 +96,7 @@ func deletePublishedLeasedWithWork(ctx context.Context,lease *mediaMutationLease if listed.Mode&unix.S_IFMT!=unix.S_IFDIR {continue} work.Stats.DayFolders++ if work.Stats.DayFolders>maxStampedScanDays {return result,errPublishedDeletionRefused} + if work.onlyDay!="" && name!=work.onlyDay {work.Stats.DaysSkipped++;continue} if work.cutoff!=nil && classifyRetentionDay(name,*work.cutoff)==retentionRetainedDay {work.Stats.DaysSkipped++;continue} file,err:=openCameraDeleteDirectory(int(root.Fd()),name);if err!=nil {return result,err} work.Stats.DaysOpened++ @@ -100,7 +105,7 @@ func deletePublishedLeasedWithWork(ctx context.Context,lease *mediaMutationLease if day.id.Dev!=listed.Dev || day.id.Ino!=listed.Ino {return result,errPublishedDeletionRefused} continue } - if filepath.Ext(name)!=".mp4" {continue} + if work.onlyDay!="" || filepath.Ext(name)!=".mp4" {continue} if err:=rootCheck();err!=nil {return result,err} entry:=publishedDeletionEntry{name:name} if err:=work.statat(int(root.Fd()),name,&entry.stat,unix.AT_SYMLINK_NOFOLLOW);err!=nil {return result,err} @@ -134,19 +139,36 @@ func deletePublishedLeasedWithWork(ctx context.Context,lease *mediaMutationLease return plan[i].name0 {digits=string(rune('0'+value%10))+digits;value/=10} + return digits +} + +func TestAgeOffAndCeilingEachActOnlyUnderTheirOwnRule(t *testing.T) { + // Age cleanup acts on a camera with a limit and never on one without, whatever the + // filesystem ceiling says; ceiling pruning acts on usage alone, whatever the age limit. + // Retention keeps names shorter than 15 characters, so the old recording needs a + // full stamped name to be due for age cleanup. + const oldFile="20000101_000000_old.mp4" + f:=newPruneFixture(t,"limited","unlimited") + f.n.cameras["limited"].RetentionDays=1 + f.n.cameras["unlimited"].RetentionDays=0 + f.fs.setUsed(10) + oldDay:="20000101" + for _,id:=range []string{"limited","unlimited"} { + f.file(id,oldDay+"/"+oldFile) + f.file(id,"20300101/new.mp4") + } + // Below the trigger, ceiling pruning does nothing. + f.p.runPass(context.Background()) + for _,id:=range []string{"limited","unlimited"} {f.mustExist(id,oldDay+"/"+oldFile)} + // Age cleanup removes only the limited camera's expired day. + ticks:=make(chan time.Time,1);ticks<-time.Now();close(ticks) + runCleanupTicks(context.Background(),f.n,ticks) + f.mustBeGone("limited",oldDay) + f.mustExist("unlimited",oldDay+"/"+oldFile) + f.mustExist("limited","20300101/new.mp4") + // At the trigger, ceiling pruning removes the unlimited camera's oldest day. + f.fs.setUsed(85) + f.p.runPass(context.Background()) + f.mustBeGone("unlimited",oldDay) + f.mustExist("unlimited","20300101/new.mp4") +} diff --git a/cmd/simplenvr/retention_days_frontend_test.go b/cmd/simplenvr/retention_days_frontend_test.go new file mode 100644 index 0000000..0db41e1 --- /dev/null +++ b/cmd/simplenvr/retention_days_frontend_test.go @@ -0,0 +1,7 @@ +package main + +import "testing" + +func TestFrontendRetentionDays(t *testing.T) { + runFrontendRegression(t, "tests/frontend/retention-days.cjs", "UTC") +} diff --git a/cmd/simplenvr/retention_policy.go b/cmd/simplenvr/retention_policy.go index 1056fc0..f6a0004 100644 --- a/cmd/simplenvr/retention_policy.go +++ b/cmd/simplenvr/retention_policy.go @@ -6,11 +6,14 @@ import ( ) const maxCameraRetentionDays=365 -var errCameraRetention=errors.New("retention days must be 1 to 365, or legacy 0 for the seven-day default") +var errCameraRetention=errors.New("retention days must be 0 (no age limit) or 1 to 365") +// cameraRetentionDuration validates a camera's maximum age. 0 means no age limit and +// returns a zero duration without an error; callers must check for 0 before using the +// duration as a cutoff. cleanupExpiredPublishedLeased refuses a nonpositive duration, +// so a missed check cannot delete media. func cameraRetentionDuration(days int) (time.Duration,error) { - if days==0 {days=7} - if days<1 || days>maxCameraRetentionDays {return 0,errCameraRetention} + if days<0 || days>maxCameraRetentionDays {return 0,errCameraRetention} // Validation must precede conversion and multiplication. return time.Duration(days)*24*time.Hour,nil } diff --git a/cmd/simplenvr/retention_policy_test.go b/cmd/simplenvr/retention_policy_test.go index 3d71085..4b9c908 100644 --- a/cmd/simplenvr/retention_policy_test.go +++ b/cmd/simplenvr/retention_policy_test.go @@ -14,9 +14,10 @@ import ( ) func TestCameraRetentionConversionIsBounded(t *testing.T) { - for _,item:=range []struct{days,want int}{{0,7},{1,1},{7,7},{365,365}} { + // 0 is valid and means no age limit; it converts to a zero duration, never to a default. + for _,item:=range []struct{days,want int}{{0,0},{1,1},{7,7},{365,365}} { duration,err:=cameraRetentionDuration(item.days) - if err!=nil || duration!=time.Duration(item.want)*24*time.Hour || duration<=0 {t.Fatalf("retention %d: %v %v",item.days,duration,err)} + if err!=nil || duration!=time.Duration(item.want)*24*time.Hour {t.Fatalf("retention %d: %v %v",item.days,duration,err)} } for _,days:=range []int{-1,366,106752,200000,int(^uint(0)>>1)} { duration,err:=cameraRetentionDuration(days) @@ -28,7 +29,7 @@ func TestRetentionAPIRejectsInvalidValuesBeforeMutation(t *testing.T) { old:=nvr nvr=&NVR{cameras:map[string]*Camera{"a":{ID:"a",RetentionDays:7},"b":{ID:"b",RetentionDays:14}}} t.Cleanup(func(){nvr=old}) - for _,days:=range []int{-1,0,366,106752,int(^uint(0)>>1)} { + for _,days:=range []int{-1,366,106752,int(^uint(0)>>1)} { raw,err:=json.Marshal(map[string]interface{}{"id":"a","retention_days":days});if err!=nil {t.Fatal(err)} for _,handler:=range []http.HandlerFunc{updateRetentionHandler,updateRetentionAllHandler} { w:=httptest.NewRecorder();handler(w,httptest.NewRequest("POST","/retention",bytes.NewReader(raw))) diff --git a/cmd/simplenvr/retention_snapshot.go b/cmd/simplenvr/retention_snapshot.go index 6243cdd..51aa864 100644 --- a/cmd/simplenvr/retention_snapshot.go +++ b/cmd/simplenvr/retention_snapshot.go @@ -13,7 +13,7 @@ import ( var retentionPolicyMu sync.RWMutex func setCameraRetention(n *NVR,id string,days int) error { - if days<1 || days>maxCameraRetentionDays {return errCameraRetention} + if days<0 || days>maxCameraRetentionDays {return errCameraRetention} retentionPolicyMu.Lock();defer retentionPolicyMu.Unlock() n.mu.Lock();defer n.mu.Unlock() cam:=n.cameras[id];if cam==nil {return errCameraMissing} @@ -22,7 +22,7 @@ func setCameraRetention(n *NVR,id string,days int) error { } func setAllCameraRetention(n *NVR,days int) error { - if days<1 || days>maxCameraRetentionDays {return errCameraRetention} + if days<0 || days>maxCameraRetentionDays {return errCameraRetention} retentionPolicyMu.Lock();defer retentionPolicyMu.Unlock() n.mu.Lock();defer n.mu.Unlock() for _,cam:=range n.cameras {if cam!=nil {cam.RetentionDays=days}} @@ -37,11 +37,12 @@ type retentionCleanupSnapshot struct { duration time.Duration } +// A camera with retention 0 has no age limit, so it is never a cleanup target. func snapshotRetentionCleanup(n *NVR) []retentionCleanupSnapshot { n.mu.RLock();defer n.mu.RUnlock() targets:=make([]retentionCleanupSnapshot,0,len(n.cameras)) for id,cam:=range n.cameras { - if cam==nil {continue} + if cam==nil || cam.RetentionDays==0 {continue} duration,err:=cameraRetentionDuration(cam.RetentionDays);if err!=nil {continue} targets=append(targets,retentionCleanupSnapshot{id,cam,cam.RecordDir,cam.RetentionDays,duration}) } diff --git a/cmd/simplenvr/storage_status.go b/cmd/simplenvr/storage_status.go index 2bc02a1..f0394d1 100644 --- a/cmd/simplenvr/storage_status.go +++ b/cmd/simplenvr/storage_status.go @@ -50,15 +50,31 @@ func availableStorageBytes(blocks uint64,size int64) (uint64,error) { return blocks*uint64(size),nil } -func readRecordingStorageCapacity(dir string) (*recordingStorageCapacity,error) { +// recordingFilesystemStats are the raw counts the kernel reports for the filesystem +// holding one directory. Every capacity or usage figure is derived from these. +type recordingFilesystemStats struct { + Blocks,Free,Available uint64 + BlockSize int64 + Files,FreeInodes uint64 +} + +// readRecordingFilesystemStats opens the directory itself without following symlinks +// and reads its filesystem with Fstatfs, so a missing, replaced or non-directory +// path is an error rather than another filesystem. +func readRecordingFilesystemStats(dir string) (recordingFilesystemStats,error) { fd,err:=unix.Open(dir,unix.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW|unix.O_CLOEXEC,0) - if err!=nil {return nil,errStorageUnavailable} + if err!=nil {return recordingFilesystemStats{},errStorageUnavailable} defer unix.Close(fd) var stat unix.Statfs_t - if err:=unix.Fstatfs(fd,&stat);err!=nil {return nil,errStorageUnavailable} - available,err:=availableStorageBytes(uint64(stat.Bavail),int64(stat.Bsize));if err!=nil {return nil,err} + if err:=unix.Fstatfs(fd,&stat);err!=nil {return recordingFilesystemStats{},errStorageUnavailable} + return recordingFilesystemStats{Blocks:uint64(stat.Blocks),Free:uint64(stat.Bfree),Available:uint64(stat.Bavail),BlockSize:int64(stat.Bsize),Files:uint64(stat.Files),FreeInodes:uint64(stat.Ffree)},nil +} + +func readRecordingStorageCapacity(dir string) (*recordingStorageCapacity,error) { + stats,err:=readRecordingFilesystemStats(dir);if err!=nil {return nil,err} + available,err:=availableStorageBytes(stats.Available,stats.BlockSize);if err!=nil {return nil,err} capacity:=&recordingStorageCapacity{AvailableBytes:available} - if stat.Files>0 {free:=uint64(stat.Ffree);capacity.FreeInodes=&free} + if stats.Files>0 {free:=stats.FreeInodes;capacity.FreeInodes=&free} return capacity,nil } diff --git a/cmd/simplenvr/storage_usage.go b/cmd/simplenvr/storage_usage.go new file mode 100644 index 0000000..f4a0d43 --- /dev/null +++ b/cmd/simplenvr/storage_usage.go @@ -0,0 +1,121 @@ +package main + +import ( + "context" + "errors" + "log" + "sync" + "time" +) + +// recordingsRoot is the one filesystem whose usage is measured. Every camera +// directory is /recordings/ (see validateCameraPath). +const recordingsRoot = "/recordings" + +// The first measurement is taken one interval after startup, not immediately. +const filesystemUsageInterval = 5 * time.Minute + +var errFilesystemUsage = errors.New("unable to measure recording filesystem usage") + +// filesystemUsage is a filesystem-wide observation. It includes data that does not +// belong to SimpleNVR and is not a count of camera media bytes. +type filesystemUsage struct { + UsedPercent float64 + AvailableBytes uint64 + ObservedAt time.Time +} + +// filesystemUsedPercent uses the df convention: used / (used + available), where +// used is total minus free blocks and available is the blocks a non-privileged +// process may use. Blocks reserved for privileged users therefore count as used. +// Block counts are converted to floating point so no integer arithmetic can +// overflow. Inconsistent counts are an error, never a guessed percentage. +func filesystemUsedPercent(blocks, free, available uint64) (float64, error) { + if blocks == 0 || free > blocks || available > free { + return 0, errFilesystemUsage + } + used := float64(blocks - free) + total := used + float64(available) + if total == 0 { + return 0, errFilesystemUsage + } + return used * 100 / total, nil +} + +// readFilesystemUsage derives usage from the shared raw reader, so a missing, +// replaced or non-directory path is an error rather than a different filesystem. +func readFilesystemUsage(dir string) (filesystemUsage, error) { + stats, err := readRecordingFilesystemStats(dir) + if err != nil { + return filesystemUsage{}, errFilesystemUsage + } + percent, err := filesystemUsedPercent(stats.Blocks, stats.Free, stats.Available) + if err != nil { + return filesystemUsage{}, err + } + available, err := availableStorageBytes(stats.Available, stats.BlockSize) + if err != nil { + return filesystemUsage{}, errFilesystemUsage + } + return filesystemUsage{UsedPercent: percent, AvailableBytes: available, ObservedAt: time.Now().UTC()}, nil +} + +// filesystemUsageMonitor keeps the latest observation. A failed measurement makes +// usage unknown (it never keeps an old value) and is logged. It deletes nothing. +type filesystemUsageMonitor struct { + dir string + interval time.Duration + read func(string) (filesystemUsage, error) + + mu sync.RWMutex + latest filesystemUsage + known bool +} + +func newFilesystemUsageMonitor(dir string, read func(string) (filesystemUsage, error)) *filesystemUsageMonitor { + return &filesystemUsageMonitor{dir: dir, interval: filesystemUsageInterval, read: read} +} + +var recordingFilesystemUsage = newFilesystemUsageMonitor(recordingsRoot, readFilesystemUsage) + +// Latest returns the last successful observation, or false while usage is unknown. +func (m *filesystemUsageMonitor) Latest() (filesystemUsage, bool) { + m.mu.RLock() + defer m.mu.RUnlock() + return m.latest, m.known +} + +func (m *filesystemUsageMonitor) sample() { + usage, err := m.read(m.dir) + m.mu.Lock() + defer m.mu.Unlock() + if err != nil { + m.latest, m.known = filesystemUsage{}, false + log.Printf("Recording filesystem usage unavailable: %v", err) + return + } + m.latest, m.known = usage, true +} + +func (m *filesystemUsageMonitor) run(ctx context.Context, ticks <-chan time.Time) { + for { + select { + case <-ctx.Done(): + return + case _, ok := <-ticks: + if !ok || ctx.Err() != nil { + return + } + m.sample() + } + } +} + +// Run blocks until ctx is canceled. Start it with shutdownGate.startBackgroundJob so +// shutdown cancels and joins it before final persistence. +func (m *filesystemUsageMonitor) Run(ctx context.Context) { + ticker := time.NewTicker(m.interval) + defer ticker.Stop() + log.Println("Filesystem usage monitor started") + m.run(ctx, ticker.C) +} diff --git a/cmd/simplenvr/storage_usage_test.go b/cmd/simplenvr/storage_usage_test.go new file mode 100644 index 0000000..5bc563f --- /dev/null +++ b/cmd/simplenvr/storage_usage_test.go @@ -0,0 +1,202 @@ +package main + +import ( + "bytes" + "context" + "errors" + "log" + "math" + "net/http" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" +) + +func TestFilesystemUsedPercent(t *testing.T) { + cases := []struct { + name string + blocks, free, avail uint64 + want float64 + fail bool + }{ + {"half used", 100, 50, 50, 50, false}, + {"reserved blocks count as used", 100, 20, 10, 8000.0 / 90.0, false}, + {"empty", 100, 100, 100, 0, false}, + {"full", 100, 0, 0, 100, false}, + {"huge counts do not overflow", math.MaxUint64, math.MaxUint64 / 2, math.MaxUint64 / 2, 50, false}, + {"zero blocks", 0, 0, 0, 0, true}, + {"free above total", 10, 11, 5, 0, true}, + {"available above free", 100, 10, 20, 0, true}, + {"nothing used and nothing available", 100, 100, 0, 0, true}, + } + for _, item := range cases { + got, err := filesystemUsedPercent(item.blocks, item.free, item.avail) + if item.fail { + if !errors.Is(err, errFilesystemUsage) || got != 0 { + t.Fatalf("%s: expected failure, got %v %v", item.name, got, err) + } + continue + } + if err != nil || math.Abs(got-item.want) > 1e-9 { + t.Fatalf("%s: got %v %v, want %v", item.name, got, err, item.want) + } + } +} + +func TestReadFilesystemUsageRefusesUnsafeDirectories(t *testing.T) { + dir := t.TempDir() + link := filepath.Join(dir, "link") + if err := os.Symlink(dir, link); err != nil { + t.Fatal(err) + } + file := filepath.Join(dir, "file") + if err := os.WriteFile(file, []byte("x"), 0600); err != nil { + t.Fatal(err) + } + for _, path := range []string{filepath.Join(dir, "missing"), link, file} { + if _, err := readFilesystemUsage(path); !errors.Is(err, errFilesystemUsage) { + t.Fatalf("%s: expected measurement failure, got %v", filepath.Base(path), err) + } + } +} + +func TestReadFilesystemUsageRealDirectory(t *testing.T) { + usage, err := readFilesystemUsage(t.TempDir()) + if err != nil { + t.Skipf("test filesystem does not report usable block counts: %v", err) + } + if usage.UsedPercent < 0 || usage.UsedPercent > 100 || usage.ObservedAt.IsZero() { + t.Fatalf("implausible observation: %+v", usage) + } +} + +func newTestUsageMonitor(read func(string) (filesystemUsage, error)) *filesystemUsageMonitor { + return newFilesystemUsageMonitor("/unused", read) +} + +func TestFilesystemUsageMonitorUsesFiveMinutesAndNoImmediateRead(t *testing.T) { + if filesystemUsageInterval != 5*time.Minute { + t.Fatalf("interval changed: %v", filesystemUsageInterval) + } + var reads atomic.Int32 + m := newTestUsageMonitor(func(string) (filesystemUsage, error) { + reads.Add(1) + return filesystemUsage{UsedPercent: 10}, nil + }) + if m.interval != filesystemUsageInterval || m.dir != "/unused" { + t.Fatalf("unexpected monitor configuration: %v %q", m.interval, m.dir) + } + if _, ok := m.Latest(); ok || reads.Load() != 0 { + t.Fatal("usage must be unknown and unread before the first tick") + } + if recordingFilesystemUsage.dir != recordingsRoot || recordingsRoot != "/recordings" { + t.Fatal("production monitor must measure /recordings") + } +} + +func TestFilesystemUsageMonitorSamplesPerTickAndLogsFailure(t *testing.T) { + var logs bytes.Buffer + old := log.Writer() + log.SetOutput(&logs) + t.Cleanup(func() { log.SetOutput(old) }) + var fail atomic.Bool + var reads atomic.Int32 + m := newTestUsageMonitor(func(string) (filesystemUsage, error) { + reads.Add(1) + if fail.Load() { + return filesystemUsage{}, errFilesystemUsage + } + return filesystemUsage{UsedPercent: 42, AvailableBytes: 7}, nil + }) + runTicks := func(n int) { + ticks := make(chan time.Time, n) + for i := 0; i < n; i++ { + ticks <- time.Now() + } + close(ticks) + done := make(chan struct{}) + go func() { + defer close(done) + m.run(context.Background(), ticks) + }() + select { + case <-done: + case <-time.After(5 * time.Second): + t.Fatal("monitor did not stop") + } + } + runTicks(2) + if reads.Load() != 2 { + t.Fatalf("expected one read per tick, got %d", reads.Load()) + } + if usage, ok := m.Latest(); !ok || usage.UsedPercent != 42 || usage.AvailableBytes != 7 { + t.Fatalf("unexpected observation: %+v %v", usage, ok) + } + fail.Store(true) + runTicks(1) + if _, ok := m.Latest(); ok { + t.Fatal("failed measurement must make usage unknown") + } + if !strings.Contains(logs.String(), "Recording filesystem usage unavailable") || strings.Contains(logs.String(), "/recordings") { + t.Fatalf("failure was not logged safely: %q", logs.String()) + } + fail.Store(false) + runTicks(1) + if _, ok := m.Latest(); !ok { + t.Fatal("usage did not recover after a successful measurement") + } +} + +func TestCanceledFilesystemUsageTickDoesNotRead(t *testing.T) { + var reads atomic.Int32 + m := newTestUsageMonitor(func(string) (filesystemUsage, error) { + reads.Add(1) + return filesystemUsage{}, nil + }) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + ticks := make(chan time.Time, 1) + ticks <- time.Now() + done := make(chan struct{}) + go func() { + defer close(done) + m.run(ctx, ticks) + }() + awaitShutdownStep(t, done, "canceled monitor did not exit") + if reads.Load() != 0 { + t.Fatal("canceled monitor still read the filesystem") + } +} + +func TestFilesystemUsageMonitorIsCanceledAndJoinedOnShutdown(t *testing.T) { + n := &NVR{cameras: map[string]*Camera{}} + gate := newShutdownGate(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})) + m := newTestUsageMonitor(func(string) (filesystemUsage, error) { + t.Error("monitor read before its first interval") + return filesystemUsage{}, nil + }) + started, exited := make(chan struct{}), make(chan struct{}) + if !gate.startBackgroundJob(func(ctx context.Context) { + close(started) + m.Run(ctx) + close(exited) + }) { + t.Fatal("monitor job rejected before shutdown") + } + awaitShutdownStep(t, started, "monitor job not started") + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if err := shutdownApplication(ctx, n, gate, nil, func() error { return nil }); err != nil { + t.Fatal(err) + } + awaitShutdownStep(t, exited, "shutdown did not cancel and join the monitor") + gate.mu.Lock() + remaining := len(gate.jobs) + gate.mu.Unlock() + if remaining != 0 { + t.Fatalf("background job registration leaked: %d", remaining) + } +} diff --git a/docs/FILESYSTEM_ACCEPTANCE.md b/docs/FILESYSTEM_ACCEPTANCE.md new file mode 100644 index 0000000..ce00230 --- /dev/null +++ b/docs/FILESYSTEM_ACCEPTANCE.md @@ -0,0 +1,63 @@ +# Filesystem ceiling acceptance (issue #14, CP6) + +This describes what the CI acceptance proves, what it cannot, and the steps the owner +runs on a real ZFS volume. + +## What CI runs + +`tests/acceptance/filesystem-prune-acceptance.sh` runs the real runtime image on a +real 64 MiB ext4 volume (a loopback mount), with headless Chrome and the real HTTP API. +Only the camera capture input is a file fixture. `filesystem_prune_acceptance.py` checks: + +- The Filesystem Usage row shows the server's used %, ceiling and trigger level; a valid + ceiling saves and survives a reload; an invalid one sends nothing. +- Retention `0` is saved through the real UI (per camera and for all cameras) and persists. +- A ceiling above usage deletes nothing. +- Lowering the ceiling prunes the oldest day with `.mp4` files from each camera, one day + per pass, removes that day's events, and stops when usage falls below the trigger. +- Evidence the pruner must not touch (`.tmp`, `temp/`, `buffer/`, a leftover-only day, the + newest day, files in the camera folder) is byte-identical at the end. The recorder keeps + running throughout. +- The 1 MiB guard: hard links on the same volume stand in for a snapshot, so deleting the + names frees no space. Pruning pauses, then resumes once the links are removed. +- A partial failure (one file made immutable with `chattr +i`): the rest of the day is + removed, the incomplete day is logged, and its events are kept. +- Ceiling-not-met is logged exactly once. +- A clean shutdown persists the ceiling (`cameras.json`, mode 0600) and a restart keeps it. + +Each `POST /api/storage/ceiling` asks for one pass, so CI does not wait for the 5-minute +timer. + +## What CI does not prove + +Live RTSP cameras; ZFS or any snapshotting filesystem; the 5-minute timer and age cleanup +on that timer (unit tests cover age cleanup); unknown-usage handling inside the container +(unit-tested); performance with very large trees. + +## Owner runbook: a real ZFS volume + +**Use a throwaway dataset and a throwaway test instance. Pruning deletes recordings and +deleted footage is not recoverable. Do not point this at your real recordings.** + +1. Create a small dataset with a quota, for example `zfs create -o quota=2G pool/simplenvr-test`, + and mount it as the instance's `/recordings`. +2. Seed a few cameras with several day folders of `.mp4` files plus a newest day. Real or + dummy files are fine. Note which files are evidence you expect to survive. +3. Take a snapshot: `zfs snapshot pool/simplenvr-test@before`. +4. Record `df -h` and `zfs list -o name,used,avail,refer` for the dataset. +5. Start the instance. Open camera settings and compare the Filesystem Usage row with `df`. +6. Set the ceiling a few points below the current usage. Read the instance log for each + pass (`docker logs `). Because a snapshot holds the deleted blocks, expect + `Filesystem pruning paused: deleting did not raise available space by at least 1 MiB` + after the first pass, and no further days removed. +7. Destroy the snapshot (`zfs destroy pool/simplenvr-test@before`) and set the ceiling + again. Expect `Filesystem pruning resumed` and further days removed, one per camera + per pass. +8. Leave the instance running through at least one 5-minute interval and confirm the + scheduled pass and (for a camera with a retention limit) age cleanup happen. +9. Confirm the newest day folder and the evidence files from step 2 are untouched, and + the recorders (if any are active) kept recording. + +Record what you saw: the log lines, `df` and `zfs list` before and after, and anything that +differed from the expectations above. CP6 is not complete without this, or without an +explicit owner waiver. diff --git a/docs/FILESYSTEM_PRUNING.md b/docs/FILESYSTEM_PRUNING.md new file mode 100644 index 0000000..6ad3dad --- /dev/null +++ b/docs/FILESYSTEM_PRUNING.md @@ -0,0 +1,85 @@ +# Filesystem pruning (issue #14, CP4) + +When the recordings filesystem fills up to the configured ceiling, SimpleNVR deletes +the oldest recordings to make room. **Deleted footage is not recoverable.** There is +no recycle bin, no preview and no undo. + +Settings and measurement are described in [FILESYSTEM_USAGE.md](FILESYSTEM_USAGE.md). + +## When a pass runs + +- Every 5 minutes, starting 5 minutes after startup. This is a separate job from + retention cleanup. +- Soon after the ceiling is changed and saved, so lowering it below current usage + prunes without waiting for the next tick. Opening settings never prunes. + +A pass does nothing unless usage is at or above the trigger level, which is the +ceiling minus 2 percentage points (78% for the default ceiling of 80%). A pass +measures usage itself, again after it has the media lease, and does nothing if the +measurement fails. A failed measurement is logged. + +## What a pass removes + +One day per camera per pass: the oldest day folder (a UTC date folder such as +`20261101`) that contains at least one regular `.mp4` file. + +- **The newest day folder is never removed.** It is the floor, even if it holds only + a few minutes of recording just after UTC midnight, or if the camera stopped days + ago. +- A day folder with no `.mp4` files (only leftovers) is skipped without a log line, + and the pass moves on to the next older day that has footage. +- Only the `.mp4` files in that day are deleted, each one individually. The folder is + removed only if it is then empty, so leftovers keep it. +- Never touched: `.tmp` files, `temp/`, `buffer/`, staging folders, recovery + evidence, files directly in the camera folder, symlinks, and any other day. + +If one file cannot be deleted, the rest of that day is still deleted. The camera is +logged as incomplete, by camera ID, and the pass continues with the other cameras. + +## Safety model + +Pruning uses the same deletion engine as retention cleanup: directories are opened +without following symlinks and pinned by identity, files are unlinked one at a time, +there is no recursive delete, and a folder is removed only with an atomic empty-folder +removal. The engine gained an opt-in day-scoped mode and an opt-in mode that continues +after a single file fails; retention and the other deletion paths do not use either. + +Pruning takes the media lease like retention cleanup, in the same lock order: media +ownership, then the retention policy lock, then the camera registry. Because the +lease is exclusive, pruning and retention cleanup never delete at the same time. Camera +deletion and recovery that already use the lease are serialized the same way. + +## The 1 MiB guard + +Available bytes are read right before and right after the deletion. If they rose by +less than 1 MiB, the pass had no effect (for example, snapshots still hold the space) +and pruning pauses. It resumes once available bytes are at least 1 MiB above the +reading taken after that pass. If the reading after a pass fails, the pause baseline +is the reading from before it. This stops a filesystem that does not free space from +being emptied day by day. + +## Ceiling not met + +If usage is at or above the ceiling and no day can be pruned (only each camera's +newest day remains, or other days hold no footage), pruning logs once that it cannot +meet the ceiling. It does not log again until usage has fallen below the trigger, +something was pruned, or the ceiling was changed. This state is in the log only. + +## Events + +When every `.mp4` in a pruned day was removed, event records whose camera name +matches and whose start time falls on that UTC day are removed, and the configuration +is saved. Cameras that share a name share the match. If any file of that day could not +be removed, its event records are kept. + +## What it never does + +- Stop, start or change a recorder, or reject a recording. +- Change `SIMPLENVR_MIN_FREE_BYTES` handling. +- Estimate days remaining or preview what will be deleted. + +## Retention days + +Age-based retention is separate: each camera's `retention_days` is an optional maximum +age, where 0 means no age limit (see [RETENTION_MAX_AGE.md](RETENTION_MAX_AGE.md)). +Whichever rule reaches a recording first removes it. diff --git a/docs/FILESYSTEM_USAGE.md b/docs/FILESYSTEM_USAGE.md new file mode 100644 index 0000000..040be1d --- /dev/null +++ b/docs/FILESYSTEM_USAGE.md @@ -0,0 +1,94 @@ +# Recording filesystem usage and ceiling (issue #14, CP2 and CP3) + +SimpleNVR measures how full the recordings filesystem is and stores the highest +used percentage the owner accepts (the ceiling). These checkpoints only measure, +store and display; they add no deletion. + +## What is measured + +The used percentage of the filesystem that holds `/recordings`. Every camera +directory is `/recordings/`, so one filesystem is measured. The value is +filesystem-wide: it includes anything else stored on that filesystem and is not a +count of camera media bytes. The per-camera Disk Usage figure in the camera list +is a different number and is unchanged (see [DISK_USAGE.md](DISK_USAGE.md)). + +## Formula + +From `fstatfs` block counts, the same convention as `df`: + + used = total blocks - free blocks + percent = used / (used + available blocks) * 100 + +"Available" is the blocks a non-privileged process may use, so blocks reserved +for privileged users count as used. Counts are converted to floating point so +large filesystems cannot overflow. Zero total blocks, free blocks above total, +available blocks above free, or nothing used and nothing available are treated +as a failed measurement, not as a percentage. + +The directory is opened without following symlinks and must be a directory, so +a missing or replaced directory is an error rather than another filesystem. + +## When it runs + +A background job started through the shutdown gate measures every 5 minutes. The +first measurement is 5 minutes after startup, so the job's own value is unknown +until then. Shutdown cancels and joins the job before final persistence. + +Opening camera settings does not use the job's value. It asks the server for a +fresh reading, so the settings row is accurate even in the first 5 minutes. + +## When measurement fails + +Usage becomes unknown (an earlier value is not kept), and a log line says that +recording filesystem usage is unavailable. The log does not include the path. +Later checkpoints must not delete anything while usage is unknown. + +## The ceiling setting (CP3) + +- **Stored as** the top-level key `max_filesystem_used_percent` in + `cameras.json`, beside `cameras`, `camera_order` and `events`. +- **Default** is 80. A file without the key reads as 80. Every save writes the + value out explicitly, including when it is still the default. +- **Valid values** are whole numbers from 10 to 95. A stored value outside that + range, or one that is not an integer (a string, fraction, exponent or null), + makes the configuration invalid: startup is refused, and saves are refused until + it is fixed, the same as invalid retention. +- **Trigger level** is the ceiling minus 2 percentage points (78 for the default). + It is derived and never stored. Nothing uses it yet. + +## API + +`GET /api/storage/ceiling` returns: + + { + "max_filesystem_used_percent": 80, + "filesystem_prune_trigger_percent": 78, + "filesystem_used_percent": 61.3, + "filesystem_observed_at": "2026-11-29T12:00:00Z" + } + +It takes a fresh reading on each request. If the reading fails, the last two +fields are `null` and the status is still 200, so the ceiling stays visible. + +`POST /api/storage/ceiling` takes `{"max_filesystem_used_percent": }`, +validates it, saves it, and returns the same body as GET. Anything invalid is +refused with 400 and changes nothing. If the save fails, the previous value is +restored and the response is a generic 500. Other methods get 405. + +The per-camera `/api/storage/status` endpoint is unchanged. + +## Settings display + +Camera settings has a "Filesystem Usage" row showing the used percentage (or +"unknown"), the ceiling and the trigger level, with a number input and a Set +Ceiling button. It refreshes each time settings open. + +## Limits + +- Quotas, ZFS datasets and snapshots, and other volume features decide what the + filesystem reports. The percentage is whatever `fstatfs` reports for that + directory. +- It is not a quota, a reservation, or proof that recording can continue. +- `SIMPLENVR_MIN_FREE_BYTES` is unchanged and independent. +- Verified only by unit tests and CI. It has not been run on the deployment + filesystem. diff --git a/docs/RETENTION_MAX_AGE.md b/docs/RETENTION_MAX_AGE.md new file mode 100644 index 0000000..01ce1bf --- /dev/null +++ b/docs/RETENTION_MAX_AGE.md @@ -0,0 +1,41 @@ +# Retention days as an optional maximum age (issue #14, CP5) + +`retention_days` is each camera's maximum recording age. + +- **1 to 365:** recordings older than that many days are removed by the periodic + retention cleanup, as before. +- **0:** no age limit. Age cleanup never deletes this camera's recordings, and events + for the camera's name are not expired by age. + +The previous meaning of 0 ("use the seven-day default") is gone. There is no +migration: every install is new, and new cameras are registered with 7. A +`cameras.json` that still has `retention_days: 0` from before this change would now +mean no age limit, so check such a file before upgrading. + +## Setting it + +The per-camera box, the bulk control and the camera settings dialog accept 0 to 365 +and say that 0 means no age limit. The API endpoints `/api/cameras/update-retention` +and `/api/cameras/update-retention-all` accept 0 to 365 and **require** +`retention_days`. A body that omits it, sends `null`, a string or a fraction, is +refused with 400 and changes nothing, so only an explicit `0` turns age cleanup off. +Values below 0 or above 365 are refused as before. + +## Events + +Event records carry a camera name, not an ID. Events for a name are not expired by +age if any camera with that name has no age limit. An invalid policy on any camera +with that name still preserves the name's events (fail closed). Events whose camera no +longer exists are still removed as orphans. + +## With the filesystem ceiling + +Age cleanup and ceiling pruning are independent. A recording is removed by whichever +rule reaches it first: age cleanup when it is older than the camera's limit, ceiling +pruning when the filesystem is at or above the trigger (see +[FILESYSTEM_PRUNING.md](FILESYSTEM_PRUNING.md)). They run as separate jobs behind the +same exclusive media lease, so they never delete at the same time. A camera with no age +limit is still subject to ceiling pruning, apart from its newest day folder. + +The audit notes in `docs/audit/RETENTION_POLICY.md` and `docs/audit/EVENT_RETENTION.md` +still describe 0 as the seven-day default; this document replaces that rule. diff --git a/tests/acceptance/filesystem-prune-acceptance.sh b/tests/acceptance/filesystem-prune-acceptance.sh new file mode 100644 index 0000000..565b73b --- /dev/null +++ b/tests/acceptance/filesystem-prune-acceptance.sh @@ -0,0 +1,138 @@ +#!/usr/bin/env bash +set -euo pipefail +image=${1:?usage: bash tests/acceptance/filesystem-prune-acceptance.sh IMAGE EVIDENCE_DIR} +evidence=${2:?evidence directory required} +work=$(mktemp -d "${RUNNER_TEMP:-/tmp}/simplenvr-prune.XXXXXX") +state=$work/state +bin=$work/bin +fixture=$work/fixture +disk=$work/volume.img +name=simplenvr-prune-$$ +mkdir -p "$evidence" "$state" "$bin" "$fixture" +chmod 755 "$work" "$bin" "$fixture" +cleanup() { + docker logs "$name" > "$evidence/runtime-container.log" 2>&1 || true + docker rm -f "$name" >/dev/null 2>&1 || true + sudo chattr -R -i "$state" >/dev/null 2>&1 || true + sudo umount "$state" >/dev/null 2>&1 || true + sudo rm -rf -- "$work" +} +trap cleanup EXIT + +# A real, small ext4 volume: fstatfs reports a real used percentage and available bytes. +truncate -s 64M "$disk" +sudo mkfs.ext4 -q -F -m 0 -O '^has_journal' "$disk" +sudo mount -o loop "$disk" "$state" +sudo chown "$(id -u):$(id -g)" "$state" +python3 - "$state" <<'PY' +import json,os,sys +root=sys.argv[1] +MIB=1024*1024 +def put(path,size=0,text=None): + os.makedirs(os.path.dirname(path),exist_ok=True) + with open(path,'wb') as f: + f.write(text.encode() if text is not None else b'\0'*size) +days=['20200101','20200102','20200103','20200104','20200105'] +for cam in ('id_a','id_b'): + base=os.path.join(root,cam) + for day in days: + for n in (1,2,3): + put(f'{base}/{day}/seg{n}.mp4',MIB) + put(f'{base}/20991231/floor.mp4',MIB) + put(f'{base}/20190101/leftover.tmp',text='leftover evidence\n') + put(f'{base}/loose.mp4',text='loose published-looking file\n') +put(root+'/id_a/temp/retained-evidence/event.mp4',text='synthetic retained event input\n') +put(root+'/id_a/temp/retained-evidence/recovery.json',text='synthetic checkpoint evidence, not a valid recovery authorization\n') +put(root+'/id_a/buffer/retained-unreported.mp4',text='synthetic unreported prebuffer evidence\n') +put(root+'/id_a/buffer/retained-big.mp4',8*MIB) +os.makedirs(root+'/id_live',exist_ok=True) +cameras={} +for ident,name,recording,mode in [('id_a','Alpha',False,'no_recording'),('id_b','Bravo',False,'no_recording'),('id_live','Live',True,'continuous')]: + cameras[ident]={'id':ident,'name':name,'rtsp_url':'rtsp://synthetic-fixture/'+ident,'record_dir':'/recordings/'+ident,'is_recording':recording,'retention_days':7,'recording_mode':mode} +events=[] +for name in ('Alpha','Bravo'): + for day in days: + stamp=f'{day[:4]}-{day[4:6]}-{day[6:]}T10:00:00Z' + events.append({'id':name+'-'+day,'camera_name':name,'label':'fixture','start_time':stamp,'duration_seconds':5,'created_at':stamp}) +events.append({'id':'Live-20200101','camera_name':'Live','label':'fixture','start_time':'2020-01-01T10:00:00Z','duration_seconds':5,'created_at':'2020-01-01T10:00:00Z'}) +with open(root+'/cameras.json','w') as f: + json.dump({'cameras':cameras,'camera_order':list(cameras),'events':events},f) +PY + +docker run --rm --network none --entrypoint /usr/bin/ffmpeg \ + --mount "type=bind,src=$fixture,dst=/fixture" "$image" \ + -nostdin -v error -f lavfi -i testsrc2=size=256x144:rate=10 \ + -t 2 -c:v mpeg4 -threads 1 -an -y /fixture/source.mp4 +# Substitute only the capture input. This is real FFmpeg in the runtime image, +# but it is deliberately NOT live RTSP acceptance. +cat > "$bin/ffmpeg" <<'SH' +#!/bin/sh +segment=0 +last= +for arg do + test "$arg" != '-segment_list' || segment=1 + last=$arg +done +if test "$segment" -eq 1; then + exec /usr/bin/ffmpeg -nostdin -v error -re -stream_loop -1 -i /fixture/source.mp4 -c copy -f segment -segment_time 5 -segment_format mp4 -reset_timestamps 1 -strftime 1 -segment_list pipe:1 -segment_list_type csv -segment_list_size 0 "$last" +fi +exec /usr/bin/ffmpeg -nostdin -v error -re -stream_loop -1 -i /fixture/source.mp4 -t 600 -c copy -f mp4 -movflags faststart -y "$last" +SH +chmod 755 "$bin/ffmpeg" +SIMPLENVR_E2E_PASSWORD=$(python3 -c 'import secrets; print(secrets.token_urlsafe(32))') +export SIMPLENVR_E2E_PASSWORD +printf '%s\n' "$SIMPLENVR_E2E_PASSWORD" | docker run --rm -i \ + --mount "type=bind,src=$state,dst=/recordings" "$image" auth set-password ci-prune +sudo chown -R 0:0 "$state" +sudo chmod 700 "$state" +docker run -d --name "$name" --read-only --cap-drop ALL --cap-add NET_BIND_SERVICE \ + --security-opt no-new-privileges --tmpfs /certs:rw,nosuid,nodev,noexec \ + --tmpfs /tmp:rw,nosuid,nodev,noexec,size=64m \ + -p 127.0.0.1::443 \ + --env PATH=/fixture-bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + --mount "type=bind,src=$state,dst=/recordings" \ + --mount "type=bind,src=$fixture,dst=/fixture,readonly" \ + --mount "type=bind,src=$bin,dst=/fixture-bin,readonly" "$image" >/dev/null +image_id=$(docker image inspect -f '{{.Id}}' "$image") + +wait_ready() { + for attempt in $(seq 1 60); do + if docker exec "$name" wget --no-check-certificate -q -O /dev/null https://127.0.0.1/auth/login; then return 0; fi + sleep 0.5 + done + docker logs "$name" + return 1 +} +drive() { + local phase=$1 port ifindex + port=$(docker inspect -f '{{(index (index .NetworkSettings.Ports "443/tcp") 0).HostPort}}' "$name") + ifindex=$(docker exec "$name" cat /sys/class/net/eth0/iflink) + [[ "$ifindex" =~ ^[1-9][0-9]*$ ]] + timeout --kill-after=10 400 python3 tests/acceptance/browser_network_ready.py \ + --ifindex "$ifindex" --evidence "$evidence" -- \ + python3 tests/acceptance/filesystem_prune_acceptance.py --phase "$phase" \ + --origin "https://127.0.0.1:$port" --container "$name" --state "$state" \ + --evidence "$evidence" --commit "${GITHUB_SHA:-$(git rev-parse HEAD)}" --image-id "$image_id" +} + +wait_ready +drive main +docker stop --timeout 75 "$name" >/dev/null +test "$(docker inspect -f '{{.State.ExitCode}}' "$name")" -eq 0 +docker logs "$name" 2>&1 | grep -F 'Shutdown complete; recording intent persisted' +sudo python3 - "$state/cameras.json" <<'PY' +import json,os,stat,sys +p=sys.argv[1] +mode=stat.S_IMODE(os.stat(p).st_mode) +assert mode==0o600, oct(mode) +with open(p) as f: d=json.load(f) +assert d['max_filesystem_used_percent']==10, d.get('max_filesystem_used_percent') +assert d['cameras']['id_live']['is_recording'] is True +assert all(c['retention_days']==0 for c in d['cameras'].values()), d['cameras'] +PY +docker start "$name" >/dev/null +wait_ready +drive restart +docker stop --timeout 75 "$name" >/dev/null +test "$(docker inspect -f '{{.State.ExitCode}}' "$name")" -eq 0 +printf 'FILESYSTEM_PRUNE_VERIFIED image_id=%s filesystem=ext4_loop restart=checked live_rtsp=not_tested zfs=not_tested age_cleanup_tick=not_tested\n' "$image_id" diff --git a/tests/acceptance/filesystem_prune_acceptance.py b/tests/acceptance/filesystem_prune_acceptance.py new file mode 100644 index 0000000..d9d25f9 --- /dev/null +++ b/tests/acceptance/filesystem_prune_acceptance.py @@ -0,0 +1,315 @@ +"""Real runtime-container acceptance for the filesystem ceiling and pruning (issue #14, CP6). + +Real HTTPS server in the runtime image, a real ext4 loopback volume and headless Chrome. +Only the camera capture input is a file fixture. Not covered: live RTSP, ZFS or any +snapshotting filesystem, the 5-minute tick, age cleanup on that tick. +""" +import argparse +import asyncio +import json +import os +import re +import subprocess +import time +from pathlib import Path +from urllib.parse import urlsplit + +from playwright.async_api import async_playwright + +CAMERAS = ("id_a", "id_b") +NAMES = {"id_a": "Alpha", "id_b": "Bravo"} +DAYS = ("20200101", "20200102", "20200103", "20200104", "20200105") +FLOOR, LEFTOVER = "20991231", "20190101" +PROTECTED = { + "id_a": [FLOOR + "/floor.mp4", LEFTOVER + "/leftover.tmp", "temp/retained-evidence/event.mp4", "temp/retained-evidence/recovery.json", "buffer/retained-unreported.mp4", "buffer/retained-big.mp4", "loose.mp4"], + "id_b": [FLOOR + "/floor.mp4", LEFTOVER + "/leftover.tmp", "loose.mp4"], +} + + +def sudo(*command, check=True): + return subprocess.run(["sudo", "-n", *command], check=check, capture_output=True, timeout=120) + + +def exists(path): + return sudo("test", "-e", str(path), check=False).returncode == 0 + + +def digest(path): + return sudo("sha256sum", str(path)).stdout.split()[0].decode() + + +def read_json(path): + return json.loads(sudo("cat", str(path)).stdout) + + +def container_log(container): + result = subprocess.run(["docker", "logs", container], capture_output=True, text=True, timeout=60) + return result.stdout + result.stderr + + +def ffmpeg_pids(container): + result = subprocess.run(["docker", "exec", container, "pidof", "ffmpeg"], capture_output=True, text=True, timeout=10) + return result.stdout.split() if result.returncode == 0 else [] + + +def seeded_events(): + events = {(NAMES[camera], "2020-01-0" + day[-1]) for camera in CAMERAS for day in DAYS} + events.add(("Live", "2020-01-01")) + return events + + +class Volume: + def __init__(self, state): + self.state = Path(state) + + def day(self, camera, day): + return self.state / camera / day + + def days_present(self, days, cameras=CAMERAS): + return all(exists(self.day(camera, day)) for camera in cameras for day in days) + + def days_absent(self, days, cameras=CAMERAS): + return not any(exists(self.day(camera, day)) for camera in cameras for day in days) + + def digests(self): + return {camera + "/" + rel: digest(self.state / camera / rel) for camera, items in PROTECTED.items() for rel in items} + + def config(self): + return read_json(self.state / "cameras.json") + + def events(self): + return sorted(set((event["camera_name"], event["start_time"][:10]) for event in self.config()["events"])) + + def hold(self, day): + # Hard links on the same volume stand in for a snapshot: deleting the names frees no space. + holds = self.state / ".holds" + sudo("mkdir", "-p", str(holds)) + for camera in CAMERAS: + listing = sudo("find", str(self.day(camera, day)), "-type", "f").stdout.decode().split("\n") + for source in filter(None, listing): + sudo("ln", source, str(holds / (camera + "-" + Path(source).name))) + + def release(self): + sudo("rm", "-rf", str(self.state / ".holds")) + + +async def wait_for(condition, what, timeout=30): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if await asyncio.to_thread(condition): + return + await asyncio.sleep(0.25) + raise AssertionError("timed out waiting for " + what) + + +async def stays(condition, what, seconds=3): + end = time.monotonic() + seconds + while time.monotonic() < end: + assert await asyncio.to_thread(condition), what + " changed" + await asyncio.sleep(0.25) + + +async def get_ceiling(request, origin): + response = await request.get(origin + "/api/storage/ceiling") + assert response.status == 200, (response.status, (await response.text())[:300]) + return await response.json() + + +async def post_ceiling(request, origin, value): + response = await request.post(origin + "/api/storage/ceiling", data={"max_filesystem_used_percent": value}) + assert response.status == 200, (response.status, (await response.text())[:300]) + return await response.json() + + +async def login(page, origin): + await page.goto(origin + "/auth/login") + await page.locator('[name="username"]').fill("ci-prune") + await page.locator('[name="password"]').fill(os.environ["SIMPLENVR_E2E_PASSWORD"]) + await page.get_by_role("button", name="Sign in", exact=True).click() + await page.wait_for_url(origin + "/", wait_until="load") + + +async def open_settings(page): + await page.evaluate("openCameraSettings()") + await page.wait_for_function("(() => { const t = document.getElementById('filesystem-usage-text'); return !!t && t.textContent.startsWith('Filesystem used:'); })()") + + +def log_count(container, pattern): + return len(re.findall(pattern, container_log(container))) + + +async def expect_ok(pending, what): + response = await pending.value + assert response.status == 200, (what, response.status, (await response.text())[:300]) + return response + + +async def main_phase(args, page, context, report): + request, volume, checks = context.request, Volume(args.state), report["checks_passed"] + protected = await asyncio.to_thread(volume.digests) + (args.evidence / "protected-digests.json").write_text(json.dumps(protected, indent=2) + "\n") + await login(page, args.origin) + checks.append("real-login") + await wait_for(lambda: ffmpeg_pids(args.container), "the live recorder's FFmpeg", 90) + + posts = [] + page.on("request", lambda r: posts.append(r.url) if r.method == "POST" and urlsplit(r.url).path == "/api/storage/ceiling" else None) + await open_settings(page) + api = await get_ceiling(request, args.origin) + assert api["max_filesystem_used_percent"] == 80 and api["filesystem_prune_trigger_percent"] == 78, api + used = api["filesystem_used_percent"] + assert used is not None and 40 < used < 75, api + shown = re.fullmatch(r"Filesystem used: ([0-9.]+)%\. Ceiling: ([0-9]+)%\. Trigger level: ([0-9]+)%\.", await page.locator("#filesystem-usage-text").inner_text()) + assert shown and abs(float(shown.group(1)) - used) < 1.5 and shown.group(2) == "80" and shown.group(3) == "78", shown + checks.append("settings-row-shows-server-usage-ceiling-and-trigger") + + assert await page.locator("#filesystem-ceiling-input").input_value() == "80" + await page.locator("#filesystem-ceiling-input").fill("90") + async with page.expect_response(lambda r: urlsplit(r.url).path == "/api/storage/ceiling" and r.request.method == "POST") as pending: + await page.locator("#filesystem-ceiling-button").click() + await expect_ok(pending, "saving the ceiling from the settings row") + assert (await get_ceiling(request, args.origin))["max_filesystem_used_percent"] == 90 + await stays(lambda: volume.days_present(DAYS), "seeded days after a ceiling above usage") + await page.reload(wait_until="load") + await open_settings(page) + assert await page.locator("#filesystem-ceiling-input").input_value() == "90" + sent = len(posts) + await page.locator("#filesystem-ceiling-input").fill("9") + await page.locator("#filesystem-ceiling-button").click() + await asyncio.sleep(1) + assert len(posts) == sent and (await get_ceiling(request, args.origin))["max_filesystem_used_percent"] == 90 + checks.append("settings-row-saves-valid-ceiling-persists-and-refuses-invalid") + + box = page.locator('#modal-camera-list .camera-box[data-camera-id="id_a"]') + await box.locator("#retention-id_a").fill("0") + async with page.expect_response(lambda r: urlsplit(r.url).path == "/api/cameras/update-retention") as pending: + await box.locator(".btn-update").click() + response = await expect_ok(pending, "saving retention 0 for one camera") + assert json.loads(response.request.post_data) == {"id": "id_a", "retention_days": 0} + await page.locator("#modal-retention-all").fill("0") + async with page.expect_response(lambda r: urlsplit(r.url).path == "/api/cameras/update-retention-all") as pending: + await page.locator('#camera-settings-modal button:has-text("Set Retention")').click() + response = await expect_ok(pending, "saving retention 0 for all cameras") + assert json.loads(response.request.post_data) == {"retention_days": 0} + cameras = (await asyncio.to_thread(volume.config))["cameras"] + assert {c: cameras[c]["retention_days"] for c in cameras} == {"id_a": 0, "id_b": 0, "id_live": 0}, cameras + assert await page.locator("#modal-camera-list #retention-id_b").input_value() == "0" + checks.append("retention-zero-saved-through-the-real-ui-and-persisted") + + await post_ceiling(request, args.origin, 80) + await stays(lambda: volume.days_present(DAYS), "seeded days below the trigger") + checks.append("below-trigger-deletes-nothing") + + used = (await get_ceiling(request, args.origin))["filesystem_used_percent"] + ceiling = int(used - 12) + 2 + assert 10 <= ceiling <= 95, (used, ceiling) + await post_ceiling(request, args.origin, ceiling) + await wait_for(lambda: volume.days_absent(DAYS[:1]), "the oldest day of both cameras to be pruned") + assert await asyncio.to_thread(volume.days_present, DAYS[1:]) + expected = seeded_events() - {("Alpha", "2020-01-01"), ("Bravo", "2020-01-01")} + await wait_for(lambda: set(volume.events()) == expected, "events of the pruned day to be removed") + assert await asyncio.to_thread(volume.digests) == protected + for camera in CAMERAS: + assert log_count(args.container, r"removed 3 recording\(s\), \d+ bytes, from camera " + camera + r" day 20200101") == 1 + assert ffmpeg_pids(args.container) and (await asyncio.to_thread(volume.config))["cameras"]["id_live"]["is_recording"] is True + checks.append("one-oldest-day-per-camera-events-removed-evidence-untouched-recorder-running") + + await post_ceiling(request, args.origin, ceiling) + await wait_for(lambda: volume.days_absent(DAYS[1:2]), "the second day to be pruned") + assert await asyncio.to_thread(volume.days_present, DAYS[2:]) + await post_ceiling(request, args.origin, ceiling) + await stays(lambda: volume.days_present(DAYS[2:]), "days after usage fell below the trigger") + checks.append("repeated-passes-prune-one-day-each-and-stop-below-the-trigger") + + before = (await get_ceiling(request, args.origin))["filesystem_used_percent"] + await asyncio.to_thread(volume.hold, DAYS[2]) + await post_ceiling(request, args.origin, 10) + await wait_for(lambda: volume.days_absent(DAYS[2:3]), "the held day's names to be removed") + await wait_for(lambda: "Filesystem pruning paused" in container_log(args.container), "the no-effect pause") + held = (await get_ceiling(request, args.origin))["filesystem_used_percent"] + assert abs(held - before) < 1.0, (before, held) + await post_ceiling(request, args.origin, 10) + await stays(lambda: volume.days_present(DAYS[3:]), "days while pruning is paused") + await asyncio.to_thread(volume.release) + await post_ceiling(request, args.origin, 10) + await wait_for(lambda: volume.days_absent(DAYS[3:4]), "pruning to resume after space was freed") + assert "Filesystem pruning resumed" in container_log(args.container) + checks.append("no-effect-guard-pauses-and-resumes-with-hard-link-stand-in-for-a-snapshot") + + immutable = Path(args.state) / "id_a" / DAYS[4] / "seg2.mp4" + await asyncio.to_thread(sudo, "chattr", "+i", str(immutable)) + await post_ceiling(request, args.origin, 10) + await wait_for(lambda: volume.days_absent(DAYS[4:], ["id_b"]), "the other camera's day to be pruned") + await wait_for(lambda: log_count(args.container, r"incomplete for camera id_a day 20200105: removed 2 recording\(s\), 1 could not be removed") >= 1, "the partial failure log") + assert await asyncio.to_thread(exists, immutable) + assert not await asyncio.to_thread(exists, Path(args.state) / "id_a" / DAYS[4] / "seg1.mp4") + kept = set(await asyncio.to_thread(volume.events)) + assert ("Alpha", "2020-01-05") in kept and ("Bravo", "2020-01-05") not in kept, kept + checks.append("partial-failure-continues-logs-and-keeps-events-of-that-day") + + await asyncio.to_thread(sudo, "chattr", "-i", str(immutable)) + await post_ceiling(request, args.origin, 10) + await wait_for(lambda: volume.days_absent(DAYS), "every prunable day to be gone") + await wait_for(lambda: volume.events() == [("Live", "2020-01-01")], "all pruned days' events to be gone") + assert await asyncio.to_thread(volume.digests) == protected + for camera in CAMERAS: + assert await asyncio.to_thread(exists, volume.day(camera, FLOOR)) + final = (await get_ceiling(request, args.origin))["filesystem_used_percent"] + assert final >= 10, "the volume is too empty to show the ceiling-not-met state: %s" % final + await post_ceiling(request, args.origin, 10) + await wait_for(lambda: log_count(args.container, "cannot meet the ceiling") == 1, "the ceiling-not-met log") + await post_ceiling(request, args.origin, 10) + await stays(lambda: log_count(args.container, "cannot meet the ceiling") == 1, "the ceiling-not-met log count") + checks.append("newest-day-and-evidence-kept-ceiling-not-met-logged-once") + assert ffmpeg_pids(args.container) + checks.append("recorder-ran-throughout") + + +async def restart_phase(args, page, context, report): + volume = Volume(args.state) + expected = json.loads((args.evidence / "protected-digests.json").read_text()) + await login(page, args.origin) + api = await get_ceiling(context.request, args.origin) + assert api["max_filesystem_used_percent"] == 10 and api["filesystem_prune_trigger_percent"] == 8, api + await stays(lambda: volume.digests() == expected, "protected files after restart") + report["checks_passed"].append("restart-keeps-the-saved-ceiling-and-protected-files") + + +async def run(args): + args.evidence.mkdir(parents=True, exist_ok=True) + report = {"phase": args.phase, "commit": args.commit, "image_id": args.image_id, "backend": "real HTTPS runtime container on a loopback ext4 volume", "checks_passed": [], "status": "failed", "limits": "File-fed FFmpeg capture input; no live RTSP; no ZFS or snapshots (hard links stand in); the 5-minute tick and age cleanup on it are not exercised."} + async with async_playwright() as p: + browser = await p.chromium.launch(channel="chrome", headless=True) + context = await browser.new_context(ignore_https_errors=True, timezone_id="UTC") + context.set_default_timeout(30000) + errors = [] + try: + page = await context.new_page() + page.on("pageerror", lambda e: errors.append(str(e)[:500])) + if args.phase == "main": + await main_phase(args, page, context, report) + else: + await restart_phase(args, page, context, report) + assert not errors, errors + report["status"] = "passed" + except BaseException as error: + report["failure"] = type(error).__name__ + ": " + str(error)[:2000] + report["container_log_tail"] = container_log(args.container)[-4000:] + raise + finally: + (args.evidence / ("filesystem-prune-" + args.phase + "-report.json")).write_text(json.dumps(report, indent=2) + "\n") + print(json.dumps(report, indent=2), flush=True) + await context.close() + await browser.close() + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--phase", choices=("main", "restart"), required=True) + parser.add_argument("--origin", required=True) + parser.add_argument("--container", required=True) + parser.add_argument("--state", required=True) + parser.add_argument("--evidence", type=Path, required=True) + parser.add_argument("--commit", required=True) + parser.add_argument("--image-id", required=True) + asyncio.run(run(parser.parse_args())) diff --git a/tests/frontend/filesystem-ceiling.cjs b/tests/frontend/filesystem-ceiling.cjs new file mode 100644 index 0000000..26820a9 --- /dev/null +++ b/tests/frontend/filesystem-ceiling.cjs @@ -0,0 +1,277 @@ +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); + +const root = path.join(__dirname, '..', '..'); +const script = fs.readFileSync(path.join(root, 'web', 'static', 'js', 'filesystem-ceiling.js'), 'utf8'); +const indexHtml = fs.readFileSync(path.join(root, 'web', 'templates', 'index.html'), 'utf8'); +const ENDPOINT = '/api/storage/ceiling'; +const SECTION = 'filesystem-ceiling-section'; +const LOADED_TEXT = 'Filesystem used: 61.3%. Ceiling: 80%. Trigger level: 78%.'; +const body80 = { + max_filesystem_used_percent: 80, + filesystem_prune_trigger_percent: 78, + filesystem_used_percent: 61.3, + filesystem_observed_at: '2026-11-29T12:00:00Z' +}; +const body90 = Object.assign({}, body80, {max_filesystem_used_percent: 90, filesystem_prune_trigger_percent: 88}); + +class El { + constructor(tag) { + this.tagName = tag; + this.children = []; + this.parentNode = null; + this.style = {}; + this.listeners = {}; + this.id = ''; + this.className = ''; + this.textContent = ''; + this.value = ''; + this.disabled = false; + } + append(...nodes) { + for (const node of nodes) { node.parentNode = this; this.children.push(node); } + } + insertBefore(node, ref) { + const index = this.children.indexOf(ref); + assert.ok(index >= 0, 'reference node must be a child'); + node.parentNode = this; + this.children.splice(index, 0, node); + } + closest(selector) { + assert.equal(selector, '.config-subsection'); + for (let node = this; node; node = node.parentNode) if (node.className === 'config-subsection') return node; + return null; + } + addEventListener(type, fn) { this.listeners[type] = fn; } + find(id) { + if (this.id === id) return this; + for (const child of this.children) { const found = child.find(id); if (found) return found; } + return null; + } +} + +function jsonResponse(data, options) { + const status = (options && options.status) || 200; + const type = (options && options.type) || 'application/json; charset=utf-8'; + return Promise.resolve({ + ok: status >= 200 && status < 300, + status, + headers: {get: name => name.toLowerCase() === 'content-type' ? type : null}, + json: () => Promise.resolve(data) + }); +} + +const isPost = options => !!options && options.method === 'POST'; +const settle = async () => { for (let i = 0; i < 10; i++) await new Promise(resolve => setImmediate(resolve)); }; + +function makeEnv(respond) { + const body = new El('body'); + const modal = new El('div'); + modal.id = 'camera-settings-modal'; + const bulk = new El('div'); + bulk.className = 'config-subsection'; + const cameras = new El('div'); + cameras.className = 'config-subsection'; + const list = new El('div'); + list.id = 'modal-camera-list'; + cameras.append(list); + modal.append(bulk, cameras); + body.append(modal); + const requests = [], successes = [], errors = []; + let baseCalls = 0; + const window = { + openCameraSettings() { baseCalls++; }, + showSuccess(message) { successes.push(message); }, + showError(message) { errors.push(message); } + }; + const context = vm.createContext({ + console: {error() {}, warn() {}, log() {}}, + window, + document: {getElementById: id => body.find(id), createElement: tag => new El(tag)}, + fetch(url, options) { requests.push({url, options}); return respond(url, options); } + }); + vm.runInContext(script, context, {filename: 'filesystem-ceiling.js'}); + return {body, modal, cameras, window, requests, successes, errors, baseCalls: () => baseCalls}; +} + +const usageText = env => env.body.find('filesystem-usage-text').textContent; +const input = env => env.body.find('filesystem-ceiling-input'); +const button = env => env.body.find('filesystem-ceiling-button'); + +async function openAddsOneRowAndRefreshes() { + const env = makeEnv(() => jsonResponse(body80)); + env.window.openCameraSettings(); + await settle(); + assert.equal(env.baseCalls(), 1, 'the original openCameraSettings must still run'); + const section = env.body.find(SECTION); + assert.ok(section, 'row is added'); + assert.equal(env.modal.children.indexOf(section), env.modal.children.indexOf(env.cameras) - 1, 'row sits directly before the camera list'); + assert.equal(input(env).min, '10'); + assert.equal(input(env).max, '95'); + assert.equal(env.requests.length, 1); + assert.equal(env.requests[0].url, ENDPOINT); + assert.equal(env.requests[0].options.cache, 'no-store'); + assert.notEqual(env.requests[0].options.method, 'POST'); + assert.equal(usageText(env), LOADED_TEXT); + assert.equal(input(env).value, '80'); + env.window.openCameraSettings(); + await settle(); + assert.equal(env.baseCalls(), 2); + assert.equal(env.modal.children.filter(child => child.id === SECTION).length, 1, 'reopening must not duplicate the row'); + assert.equal(env.requests.length, 2, 'every open refreshes usage'); + assert.deepEqual(env.errors, []); + assert.deepEqual(env.successes, []); +} + +async function unknownUsageIsShownPlainly() { + const env = makeEnv(() => jsonResponse(Object.assign({}, body80, {filesystem_used_percent: null, filesystem_observed_at: null}))); + env.window.openCameraSettings(); + await settle(); + assert.equal(usageText(env), 'Filesystem used: unknown. Ceiling: 80%. Trigger level: 78%.'); +} + +async function failedLoadsAreShownPlainly() { + const variants = [ + () => jsonResponse(body80, {status: 500}), + () => jsonResponse(body80, {type: 'text/html'}), + () => jsonResponse({}), + () => jsonResponse(Object.assign({}, body80, {max_filesystem_used_percent: '80'})), + () => Promise.reject(new Error('network unavailable')) + ]; + for (const variant of variants) { + const env = makeEnv(variant); + env.window.openCameraSettings(); + await settle(); + assert.equal(usageText(env), 'Filesystem usage could not be loaded.'); + assert.equal(env.requests.length, 1, 'no retries'); + assert.deepEqual(env.successes, []); + } +} + +async function validSaveSendsOneRequestAndShowsStoredValue() { + const env = makeEnv((url, options) => jsonResponse(isPost(options) ? body90 : body80)); + env.window.openCameraSettings(); + await settle(); + input(env).value = ' 90 '; + button(env).listeners.click(); + await settle(); + assert.equal(env.requests.length, 2); + const post = env.requests[1]; + assert.equal(post.url, ENDPOINT); + assert.equal(post.options.method, 'POST'); + assert.equal(post.options.headers['Content-Type'], 'application/json'); + assert.deepEqual(JSON.parse(post.options.body), {max_filesystem_used_percent: 90}); + assert.equal(usageText(env), 'Filesystem used: 61.3%. Ceiling: 90%. Trigger level: 88%.'); + assert.equal(input(env).value, '90'); + assert.deepEqual(env.successes, ['Filesystem usage ceiling updated']); + assert.deepEqual(env.errors, []); + assert.equal(button(env).disabled, false); + for (const edge of ['10', '95']) { + input(env).value = edge; + button(env).listeners.click(); + await settle(); + assert.equal(JSON.parse(env.requests[env.requests.length - 1].options.body).max_filesystem_used_percent, Number(edge)); + } +} + +async function invalidInputIsNeverSent() { + for (const value of ['', ' ', '9', '96', '0', '100', '80.5', 'abc', '1e1', '-5', '+80', '0950']) { + const env = makeEnv(() => jsonResponse(body80)); + env.window.openCameraSettings(); + await settle(); + input(env).value = value; + button(env).listeners.click(); + await settle(); + assert.equal(env.requests.length, 1, 'no request for ' + JSON.stringify(value)); + assert.equal(env.errors.length, 1, 'one error for ' + JSON.stringify(value)); + assert.deepEqual(env.successes, []); + assert.equal(button(env).disabled, false); + } +} + +async function failedSaveNeverAnnouncesSuccess() { + const variants = [ + () => jsonResponse('bad request', {status: 400, type: 'text/plain'}), + () => jsonResponse('server error', {status: 500, type: 'text/plain'}), + () => jsonResponse(body90, {type: 'text/html'}), + () => jsonResponse({}), + () => Promise.reject(new Error('network unavailable')) + ]; + for (const variant of variants) { + const env = makeEnv((url, options) => isPost(options) ? variant() : jsonResponse(body80)); + env.window.openCameraSettings(); + await settle(); + input(env).value = '90'; + button(env).listeners.click(); + await settle(); + assert.equal(env.requests.length, 2, 'exactly one save request; no retries'); + assert.deepEqual(env.successes, [], 'failure must not announce success'); + assert.deepEqual(env.errors, ['Failed to update filesystem usage ceiling']); + assert.equal(usageText(env), LOADED_TEXT, 'failure must not change the displayed values'); + assert.equal(button(env).disabled, false, 'button must be usable again'); + } +} + +async function pendingSaveBlocksASecondRequest() { + let release; + const pending = new Promise(resolve => { release = resolve; }); + const env = makeEnv((url, options) => isPost(options) ? pending.then(() => jsonResponse(body90)) : jsonResponse(body80)); + env.window.openCameraSettings(); + await settle(); + input(env).value = '90'; + button(env).listeners.click(); + button(env).listeners.click(); + await settle(); + assert.equal(env.requests.filter(request => isPost(request.options)).length, 1, 'second click must not send another request'); + assert.equal(button(env).disabled, true); + release(); + await settle(); + assert.equal(button(env).disabled, false); + assert.equal(env.requests.filter(request => isPost(request.options)).length, 1); + assert.deepEqual(env.successes, ['Filesystem usage ceiling updated']); +} + +function scriptLoadsOnceAfterModals() { + const tags = Array.from(indexHtml.matchAll(/ + +