| 1 | package mirror |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/hex" |
| 7 | "encoding/json" |
| 8 | "errors" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "io/fs" |
| 12 | "os" |
| 13 | "path/filepath" |
| 14 | "sort" |
| 15 | "strings" |
| 16 | "time" |
| 17 | |
| 18 | "git.timfalken.com/timfa/bluegit-backup/internal/protocol" |
| 19 | ) |
| 20 | |
| 21 | // Mirror is de draaiende kopie: Dir bevat de logische paden (state/…, |
| 22 | // data/…). Index onthoudt per bestand grootte en mtime zoals BlueGit ze |
| 23 | // meldde, zodat een volgende sync alleen wijzigingen ophaalt. |
| 24 | type Mirror struct { |
| 25 | Dir string |
| 26 | Index string |
| 27 | } |
| 28 | |
| 29 | // Stats zegt wat een sync deed. |
| 30 | type Stats struct { |
| 31 | Files int `json:"files"` |
| 32 | Downloaded int `json:"downloaded"` |
| 33 | Bytes int64 `json:"bytes"` |
| 34 | Deleted int `json:"deleted"` |
| 35 | Skipped int `json:"skipped"` |
| 36 | } |
| 37 | |
| 38 | // LoadIndex leest de index. Geen bestand: leeg. |
| 39 | func (m *Mirror) LoadIndex() (map[string]protocol.Entry, error) { |
| 40 | idx := map[string]protocol.Entry{} |
| 41 | b, err := os.ReadFile(m.Index) |
| 42 | if errors.Is(err, os.ErrNotExist) { |
| 43 | return idx, nil |
| 44 | } |
| 45 | if err != nil { |
| 46 | return idx, err |
| 47 | } |
| 48 | return idx, json.Unmarshal(b, &idx) |
| 49 | } |
| 50 | |
| 51 | func (m *Mirror) saveIndex(idx map[string]protocol.Entry) error { |
| 52 | b, err := json.Marshal(idx) |
| 53 | if err != nil { |
| 54 | return err |
| 55 | } |
| 56 | tmp := m.Index + ".tmp" |
| 57 | if err := os.WriteFile(tmp, b, 0o600); err != nil { |
| 58 | return err |
| 59 | } |
| 60 | return os.Rename(tmp, m.Index) |
| 61 | } |
| 62 | |
| 63 | // Empty zegt of de kopie nog niets bevat. |
| 64 | func (m *Mirror) Empty() bool { |
| 65 | idx, err := m.LoadIndex() |
| 66 | return err != nil || len(idx) == 0 |
| 67 | } |
| 68 | |
| 69 | // Size is de totale grootte volgens de index. |
| 70 | func (m *Mirror) Size() int64 { |
| 71 | idx, _ := m.LoadIndex() |
| 72 | var n int64 |
| 73 | for _, e := range idx { |
| 74 | n += e.Size |
| 75 | } |
| 76 | return n |
| 77 | } |
| 78 | |
| 79 | // Wipe verwijdert de kopie en de index. |
| 80 | func (m *Mirror) Wipe() error { |
| 81 | if err := os.RemoveAll(m.Dir); err != nil { |
| 82 | return err |
| 83 | } |
| 84 | err := os.Remove(m.Index) |
| 85 | if errors.Is(err, os.ErrNotExist) { |
| 86 | return nil |
| 87 | } |
| 88 | return err |
| 89 | } |
| 90 | |
| 91 | func (m *Mirror) real(logical string) string { |
| 92 | return filepath.Join(m.Dir, filepath.FromSlash(logical)) |
| 93 | } |
| 94 | |
| 95 | func same(a, b protocol.Entry) bool { |
| 96 | if a.Path == protocol.DBPath || b.Path == protocol.DBPath { |
| 97 | return a.SHA256 != "" && a.SHA256 == b.SHA256 && a.Size == b.Size |
| 98 | } |
| 99 | return a.Size == b.Size && a.MTime == b.MTime |
| 100 | } |
| 101 | |
| 102 | // Sync haalt het manifest op en brengt de kopie gelijk: nieuwe en |
| 103 | // gewijzigde bestanden downloaden (begrensd), verdwenen bestanden weg. |
| 104 | func (m *Mirror) Sync(ctx context.Context, r *Remote) (Stats, error) { |
| 105 | var st Stats |
| 106 | man, err := r.Manifest(ctx) |
| 107 | if err != nil { |
| 108 | return st, err |
| 109 | } |
| 110 | idx, err := m.LoadIndex() |
| 111 | if err != nil { |
| 112 | idx = map[string]protocol.Entry{} |
| 113 | } |
| 114 | if err := os.MkdirAll(m.Dir, 0o750); err != nil { |
| 115 | return st, err |
| 116 | } |
| 117 | tmpDir := filepath.Join(filepath.Dir(m.Dir), "tmp") |
| 118 | if err := os.MkdirAll(tmpDir, 0o750); err != nil { |
| 119 | return st, err |
| 120 | } |
| 121 | want := map[string]bool{} |
| 122 | dirty := 0 |
| 123 | for _, e := range man.Files { |
| 124 | logical, ok := protocol.CleanLogical(e.Path) |
| 125 | if !ok { |
| 126 | continue |
| 127 | } |
| 128 | want[logical] = true |
| 129 | st.Files++ |
| 130 | if old, ok := idx[logical]; ok && same(old, e) { |
| 131 | if _, err := os.Stat(m.real(logical)); err == nil { |
| 132 | continue |
| 133 | } |
| 134 | } |
| 135 | n, err := m.download(ctx, r, tmpDir, e) |
| 136 | if errors.Is(err, ErrGone) { |
| 137 | st.Skipped++ |
| 138 | want[logical] = false |
| 139 | continue |
| 140 | } |
| 141 | if err != nil { |
| 142 | _ = m.saveIndex(idx) |
| 143 | return st, fmt.Errorf("%s: %w", logical, err) |
| 144 | } |
| 145 | idx[logical] = e |
| 146 | st.Downloaded++ |
| 147 | st.Bytes += n |
| 148 | dirty++ |
| 149 | if dirty >= 200 { |
| 150 | _ = m.saveIndex(idx) |
| 151 | dirty = 0 |
| 152 | } |
| 153 | } |
| 154 | for p := range idx { |
| 155 | if !want[p] { |
| 156 | _ = os.Remove(m.real(p)) |
| 157 | delete(idx, p) |
| 158 | st.Deleted++ |
| 159 | } |
| 160 | } |
| 161 | // Ook bestanden die niet in de index stonden (een afgebroken download). |
| 162 | _ = filepath.WalkDir(m.Dir, func(p string, d fs.DirEntry, err error) error { |
| 163 | if err != nil || d.IsDir() { |
| 164 | return nil |
| 165 | } |
| 166 | rel, _ := filepath.Rel(m.Dir, p) |
| 167 | if _, ok := idx[filepath.ToSlash(rel)]; !ok { |
| 168 | _ = os.Remove(p) |
| 169 | } |
| 170 | return nil |
| 171 | }) |
| 172 | removeEmptyDirs(m.Dir) |
| 173 | return st, m.saveIndex(idx) |
| 174 | } |
| 175 | |
| 176 | func (m *Mirror) download(ctx context.Context, r *Remote, tmpDir string, e protocol.Entry) (int64, error) { |
| 177 | rc, err := r.Fetch(ctx, e.Path) |
| 178 | if err != nil { |
| 179 | return 0, err |
| 180 | } |
| 181 | defer rc.Close() |
| 182 | f, err := os.CreateTemp(tmpDir, "dl-*") |
| 183 | if err != nil { |
| 184 | return 0, err |
| 185 | } |
| 186 | tmp := f.Name() |
| 187 | defer os.Remove(tmp) |
| 188 | h := sha256.New() |
| 189 | n, err := io.Copy(io.MultiWriter(f, h), rc) |
| 190 | if cerr := f.Close(); err == nil { |
| 191 | err = cerr |
| 192 | } |
| 193 | if err != nil { |
| 194 | return n, err |
| 195 | } |
| 196 | if e.SHA256 != "" && hex.EncodeToString(h.Sum(nil)) != e.SHA256 { |
| 197 | return n, errors.New("sha256 klopt niet") |
| 198 | } |
| 199 | mode := os.FileMode(e.Mode).Perm() |
| 200 | if mode == 0 { |
| 201 | mode = 0o640 |
| 202 | } |
| 203 | _ = os.Chmod(tmp, mode|0o600) |
| 204 | dst := m.real(e.Path) |
| 205 | if err := os.MkdirAll(filepath.Dir(dst), 0o750); err != nil { |
| 206 | return n, err |
| 207 | } |
| 208 | if err := os.Rename(tmp, dst); err != nil { |
| 209 | return n, err |
| 210 | } |
| 211 | mt := time.UnixMilli(e.MTime) |
| 212 | _ = os.Chtimes(dst, mt, mt) |
| 213 | return n, nil |
| 214 | } |
| 215 | |
| 216 | func removeEmptyDirs(root string) { |
| 217 | var dirs []string |
| 218 | _ = filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { |
| 219 | if err == nil && d.IsDir() && p != root { |
| 220 | dirs = append(dirs, p) |
| 221 | } |
| 222 | return nil |
| 223 | }) |
| 224 | sort.Slice(dirs, func(i, j int) bool { return len(dirs[i]) > len(dirs[j]) }) |
| 225 | for _, d := range dirs { |
| 226 | _ = os.Remove(d) // faalt als hij niet leeg is |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | // RebuildIndex maakt de index opnieuw uit de bestanden zelf, na het |
| 231 | // uitpakken van een archief. De mtimes komen uit het archief en zijn |
| 232 | // dezelfde die BlueGit na het terugzetten heeft. |
| 233 | func (m *Mirror) RebuildIndex() error { |
| 234 | idx := map[string]protocol.Entry{} |
| 235 | err := filepath.WalkDir(m.Dir, func(p string, d fs.DirEntry, err error) error { |
| 236 | if err != nil { |
| 237 | return err |
| 238 | } |
| 239 | if d.IsDir() || !d.Type().IsRegular() { |
| 240 | return nil |
| 241 | } |
| 242 | rel, _ := filepath.Rel(m.Dir, p) |
| 243 | logical := filepath.ToSlash(rel) |
| 244 | if _, ok := protocol.CleanLogical(logical); !ok { |
| 245 | return nil |
| 246 | } |
| 247 | fi, err := d.Info() |
| 248 | if err != nil { |
| 249 | return err |
| 250 | } |
| 251 | e := protocol.Entry{Path: logical, Size: fi.Size(), MTime: fi.ModTime().UnixMilli(), Mode: uint32(fi.Mode().Perm())} |
| 252 | if logical == protocol.DBPath { |
| 253 | f, err := os.Open(p) |
| 254 | if err != nil { |
| 255 | return err |
| 256 | } |
| 257 | h := sha256.New() |
| 258 | _, err = io.Copy(h, f) |
| 259 | f.Close() |
| 260 | if err != nil { |
| 261 | return err |
| 262 | } |
| 263 | e.SHA256 = hex.EncodeToString(h.Sum(nil)) |
| 264 | } |
| 265 | idx[logical] = e |
| 266 | return nil |
| 267 | }) |
| 268 | if err != nil && !errors.Is(err, fs.ErrNotExist) { |
| 269 | return err |
| 270 | } |
| 271 | return m.saveIndex(idx) |
| 272 | } |
| 273 | |
| 274 | // HasPath zegt of een logisch pad in de kopie staat (voor tests en status). |
| 275 | func (m *Mirror) HasPath(prefix string) bool { |
| 276 | idx, _ := m.LoadIndex() |
| 277 | for p := range idx { |
| 278 | if strings.HasPrefix(p, prefix) { |
| 279 | return true |
| 280 | } |
| 281 | } |
| 282 | return false |
| 283 | } |