| 1 | package host |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | "path/filepath" |
| 6 | "strings" |
| 7 | "testing" |
| 8 | "time" |
| 9 | ) |
| 10 | |
| 11 | func TestSystemApplyReapsStagingBeforeLockCreation(t *testing.T) { |
| 12 | f := newApplyFixture(t, "stable", "v1") |
| 13 | roots := []string{ |
| 14 | f.a.optDir, |
| 15 | filepath.Join(f.a.optDir, "versions", "acct", "v1"), |
| 16 | f.a.stagingDir(), |
| 17 | filepath.Join(f.a.dataDir, "releases", "healthy"), |
| 18 | filepath.Join(f.a.etcDir, "carlos"), |
| 19 | filepath.Join(f.a.etcDir, "systemd", "system"), |
| 20 | filepath.Join(f.a.etcDir, "systemd", "journald.conf.d"), |
| 21 | filepath.Join(f.a.etcDir, "sysusers.d"), |
| 22 | filepath.Join(f.a.etcDir, "tmpfiles.d"), |
| 23 | } |
| 24 | var stale, retained []string |
| 25 | for _, root := range roots { |
| 26 | for _, tc := range []struct { |
| 27 | name string |
| 28 | old bool |
| 29 | }{ |
| 30 | {".carlos-write-" + strings.Repeat("a", 32), true}, |
| 31 | {".carlos-write-" + strings.Repeat("b", 32), false}, |
| 32 | {".carlos-write-unrelated", true}, |
| 33 | } { |
| 34 | path := filepath.Join(root, tc.name) |
| 35 | if err := os.MkdirAll(path, 0700); err != nil { |
| 36 | t.Fatal(err) |
| 37 | } |
| 38 | if err := os.WriteFile(filepath.Join(path, "data"), []byte("interrupted"), 0600); err != nil { |
| 39 | t.Fatal(err) |
| 40 | } |
| 41 | if tc.old { |
| 42 | old := time.Now().Add(-2 * time.Hour) |
| 43 | for _, entry := range []string{filepath.Join(path, "data"), path} { |
| 44 | if err := os.Chtimes(entry, old, old); err != nil { |
| 45 | t.Fatal(err) |
| 46 | } |
| 47 | } |
| 48 | } |
| 49 | if tc.old && strings.HasSuffix(tc.name, strings.Repeat("a", 32)) { |
| 50 | stale = append(stale, path) |
| 51 | } else { |
| 52 | retained = append(retained, path) |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | // Fail at lock creation, proving cleanup needs neither a usable lock nor |
| 57 | // a successful recovery (which independently removes system staging). |
| 58 | if err := os.Mkdir(f.a.lockPath(), 0700); err != nil { |
| 59 | t.Fatal(err) |
| 60 | } |
| 61 | if err := f.a.Run(t.Context(), false); err == nil { |
| 62 | t.Fatal("directory accepted as lock file") |
| 63 | } |
| 64 | for _, path := range stale { |
| 65 | if _, err := os.Lstat(path); !os.IsNotExist(err) { |
| 66 | t.Errorf("stale staging remains at %s: %v", path, err) |
| 67 | } |
| 68 | } |
| 69 | for _, path := range retained { |
| 70 | if _, err := os.Stat(filepath.Join(path, "data")); err != nil { |
| 71 | t.Errorf("retained staging changed at %s: %v", path, err) |
| 72 | } |
| 73 | } |
| 74 | } |
| 75 | |