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