| 1 | package export |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/rand" |
| 6 | "encoding/hex" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "sort" |
| 12 | "strconv" |
| 13 | "strings" |
| 14 | "sync" |
| 15 | "syscall" |
| 16 | ) |
| 17 | |
| 18 | // ErrNoExport is Open's error when the receiver has activated no export. |
| 19 | var ErrNoExport = errors.New("no export has been activated") |
| 20 | |
| 21 | // Store is a receiver's state directory. Its layout is: |
| 22 | // |
| 23 | // <state>/lock serialises activations |
| 24 | // <state>/high-water the greatest sequence accepted |
| 25 | // <state>/active symlink to exports/<sequence> |
| 26 | // <state>/exports/<sequence>/ one generation, immutable once active |
| 27 | // export.json |
| 28 | // repos/<project>.git |
| 29 | // <state>/staging/<sequence>/ one upload, until it is committed |
| 30 | // bodies/<sha256> |
| 31 | // <state>/trash/ generations being deleted |
| 32 | // |
| 33 | // A generation is activated by renaming its staging directory into |
| 34 | // exports/, writing high-water durably, and then swapping active |
| 35 | // atomically. A reader resolves active once per request with Open and |
| 36 | // keeps that generation, locked against deletion, until it releases it. |
| 37 | // An old generation is deleted only once no reader holds it. |
| 38 | // |
| 39 | // The locks are flock(2) locks, so readers and activations in different |
| 40 | // processes on one host are held to the same rule as goroutines are. |
| 41 | type Store struct { |
| 42 | dir string |
| 43 | } |
| 44 | |
| 45 | // Generation is one activated export: its sequence and its directory. |
| 46 | type Generation struct { |
| 47 | Sequence int64 |
| 48 | Dir string |
| 49 | } |
| 50 | |
| 51 | // ExportPath is the generation's export.json. |
| 52 | func (g Generation) ExportPath() string { return filepath.Join(g.Dir, ExportFile) } |
| 53 | |
| 54 | // Repo is the bare repository of the generation's project called name. ok |
| 55 | // is false for a name that is not a project name. |
| 56 | func (g Generation) Repo(name string) (path string, ok bool) { |
| 57 | if !ValidName(name) { |
| 58 | return "", false |
| 59 | } |
| 60 | return filepath.Join(g.Dir, "repos", name+".git"), true |
| 61 | } |
| 62 | |
| 63 | // Export reads and validates the generation's export.json. |
| 64 | func (g Generation) Export() (*Export, error) { |
| 65 | data, err := os.ReadFile(g.ExportPath()) |
| 66 | if err != nil { |
| 67 | return nil, err |
| 68 | } |
| 69 | return Decode(data) |
| 70 | } |
| 71 | |
| 72 | // Staging is one upload being received: its manifest and its directory. |
| 73 | type Staging struct { |
| 74 | Manifest *Manifest |
| 75 | Dir string |
| 76 | } |
| 77 | |
| 78 | // Bodies is the directory StageBody writes the upload's bodies to. |
| 79 | func (st Staging) Bodies() string { return filepath.Join(st.Dir, "bodies") } |
| 80 | |
| 81 | // Body is where the body b is staged once it verified. |
| 82 | func (st Staging) Body(b Body) string { return filepath.Join(st.Bodies(), b.SHA256) } |
| 83 | |
| 84 | // Repo is where the staged repository of the project called name goes. |
| 85 | func (st Staging) Repo(name string) string { |
| 86 | return filepath.Join(st.Dir, "repos", name+".git") |
| 87 | } |
| 88 | |
| 89 | // OpenStore opens the state directory at dir, creating its layout. It |
| 90 | // finishes an activation a crash interrupted after high-water was written, |
| 91 | // and deletes what no activation can use. |
| 92 | func OpenStore(dir string) (*Store, error) { |
| 93 | abs, err := filepath.Abs(dir) |
| 94 | if err != nil { |
| 95 | return nil, err |
| 96 | } |
| 97 | s := &Store{dir: abs} |
| 98 | for _, d := range []string{abs, s.path("exports"), s.path("staging"), s.path("trash")} { |
| 99 | if err := os.MkdirAll(d, 0o755); err != nil { |
| 100 | return nil, err |
| 101 | } |
| 102 | } |
| 103 | unlock, err := s.lock() |
| 104 | if err != nil { |
| 105 | return nil, err |
| 106 | } |
| 107 | defer unlock() |
| 108 | if err := s.recover(); err != nil { |
| 109 | return nil, err |
| 110 | } |
| 111 | return s, s.sweep() |
| 112 | } |
| 113 | |
| 114 | // Dir is the state directory. |
| 115 | func (s *Store) Dir() string { return s.dir } |
| 116 | |
| 117 | func (s *Store) path(parts ...string) string { |
| 118 | return filepath.Join(append([]string{s.dir}, parts...)...) |
| 119 | } |
| 120 | |
| 121 | func (s *Store) exportDir(sequence int64) string { |
| 122 | return s.path("exports", strconv.FormatInt(sequence, 10)) |
| 123 | } |
| 124 | |
| 125 | // HighWater is the greatest sequence the store has accepted, 0 for none. |
| 126 | func (s *Store) HighWater() (int64, error) { |
| 127 | data, err := os.ReadFile(s.path("high-water")) |
| 128 | if errors.Is(err, os.ErrNotExist) { |
| 129 | return 0, nil |
| 130 | } |
| 131 | if err != nil { |
| 132 | return 0, err |
| 133 | } |
| 134 | n, ok := decimal(strings.TrimSuffix(string(data), "\n")) |
| 135 | if !ok { |
| 136 | return 0, fmt.Errorf("%s holds %q, which is not a sequence", s.path("high-water"), data) |
| 137 | } |
| 138 | return n, nil |
| 139 | } |
| 140 | |
| 141 | // active is the sequence active points at, and false when there is none. |
| 142 | func (s *Store) active() (int64, bool, error) { |
| 143 | target, err := os.Readlink(s.path("active")) |
| 144 | if errors.Is(err, os.ErrNotExist) { |
| 145 | return 0, false, nil |
| 146 | } |
| 147 | if err != nil { |
| 148 | return 0, false, err |
| 149 | } |
| 150 | name, ok := strings.CutPrefix(target, "exports/") |
| 151 | n, valid := decimal(name) |
| 152 | if !ok || !valid { |
| 153 | return 0, false, fmt.Errorf("%s points at %q, which is no generation", s.path("active"), target) |
| 154 | } |
| 155 | return n, true, nil |
| 156 | } |
| 157 | |
| 158 | // Open resolves active once and returns that generation, held against |
| 159 | // deletion until release is called. A request serves everything from the |
| 160 | // one generation it opened, so an activation during the request never |
| 161 | // mixes two exports in one response. release may be called more than |
| 162 | // once. Open's error is ErrNoExport before the first activation. |
| 163 | func (s *Store) Open() (Generation, func(), error) { |
| 164 | for range 16 { |
| 165 | seq, ok, err := s.active() |
| 166 | if err != nil { |
| 167 | return Generation{}, func() {}, err |
| 168 | } |
| 169 | if !ok { |
| 170 | return Generation{}, func() {}, ErrNoExport |
| 171 | } |
| 172 | dir := s.exportDir(seq) |
| 173 | f, err := os.Open(dir) |
| 174 | if errors.Is(err, os.ErrNotExist) { |
| 175 | continue // active moved on and the generation was deleted |
| 176 | } |
| 177 | if err != nil { |
| 178 | return Generation{}, func() {}, err |
| 179 | } |
| 180 | if err := flock(f, syscall.LOCK_SH); err != nil { |
| 181 | f.Close() |
| 182 | return Generation{}, func() {}, err |
| 183 | } |
| 184 | // A deletion renames the generation away while it holds the lock |
| 185 | // exclusively, so a generation still at its path once this holds |
| 186 | // the lock is one no deletion will touch. |
| 187 | held, errHeld := f.Stat() |
| 188 | there, errThere := os.Stat(dir) |
| 189 | if errHeld != nil || errThere != nil || !os.SameFile(held, there) { |
| 190 | f.Close() |
| 191 | continue |
| 192 | } |
| 193 | var once sync.Once |
| 194 | release := func() { once.Do(func() { f.Close() }) } |
| 195 | return Generation{Sequence: seq, Dir: dir}, release, nil |
| 196 | } |
| 197 | return Generation{}, func() {}, errors.New("active moved on every time it was resolved") |
| 198 | } |
| 199 | |
| 200 | // Stage is the staging directory for an upload whose manifest |
| 201 | // VerifyManifest admitted. A manifest posted again finds its directory and |
| 202 | // the bodies already staged in it. Staging a manifest discards the staging |
| 203 | // directories of older ones. A manifest not newer than the high-water mark |
| 204 | // is refused as replayed, and one older than another staged upload as |
| 205 | // superseded. |
| 206 | func (s *Store) Stage(m *Manifest) (Staging, error) { |
| 207 | unlock, err := s.lock() |
| 208 | if err != nil { |
| 209 | return Staging{}, err |
| 210 | } |
| 211 | defer unlock() |
| 212 | if err := s.checkNewer(m); err != nil { |
| 213 | return Staging{}, err |
| 214 | } |
| 215 | staged, err := s.staged() |
| 216 | if err != nil { |
| 217 | return Staging{}, err |
| 218 | } |
| 219 | for _, seq := range staged { |
| 220 | if seq > m.Sequence { |
| 221 | return Staging{}, refuse(CodeSuperseded, "the upload with sequence %d supersedes this one, %d", seq, m.Sequence) |
| 222 | } |
| 223 | if seq < m.Sequence { |
| 224 | if err := os.RemoveAll(s.path("staging", strconv.FormatInt(seq, 10))); err != nil { |
| 225 | return Staging{}, err |
| 226 | } |
| 227 | } |
| 228 | } |
| 229 | st := Staging{Manifest: m, Dir: s.path("staging", strconv.FormatInt(m.Sequence, 10))} |
| 230 | for _, d := range []string{st.Bodies(), filepath.Join(st.Dir, "repos")} { |
| 231 | if err := os.MkdirAll(d, 0o755); err != nil { |
| 232 | return Staging{}, err |
| 233 | } |
| 234 | } |
| 235 | return st, nil |
| 236 | } |
| 237 | |
| 238 | // Inventory is the reply to the staged upload's manifest: the export the |
| 239 | // store serves, the projects it holds, and the bodies still to be sent. |
| 240 | // export.json is needed until it is staged. A bundle is needed until it is |
| 241 | // staged or its repository is, unless the active generation holds its |
| 242 | // project at the declared source tip, from which Activate carries it. |
| 243 | func (s *Store) Inventory(st Staging) (Inventory, error) { |
| 244 | inv := Inventory{Schema: InventorySchema, Sequence: st.Manifest.Sequence, Holds: []Held{}, Needs: []Need{}} |
| 245 | held := map[string]string{} |
| 246 | g, release, err := s.Open() |
| 247 | defer release() |
| 248 | switch { |
| 249 | case errors.Is(err, ErrNoExport): |
| 250 | case err != nil: |
| 251 | return Inventory{}, err |
| 252 | default: |
| 253 | e, err := g.Export() |
| 254 | if err != nil { |
| 255 | return Inventory{}, err |
| 256 | } |
| 257 | digest, err := e.Digest() |
| 258 | if err != nil { |
| 259 | return Inventory{}, err |
| 260 | } |
| 261 | inv.Active = &Active{Sequence: g.Sequence, Digest: digest} |
| 262 | for _, p := range e.Projects { |
| 263 | inv.Holds = append(inv.Holds, Held{Project: p.Name, SourceTip: p.SourceTip}) |
| 264 | held[p.Name] = p.SourceTip |
| 265 | } |
| 266 | } |
| 267 | needed := map[string]bool{} |
| 268 | need := func(b Body) { |
| 269 | if !needed[b.SHA256] && !exists(st.Body(b)) { |
| 270 | needed[b.SHA256] = true |
| 271 | inv.Needs = append(inv.Needs, Need{Name: b.Name, SHA256: b.SHA256, Size: b.Size}) |
| 272 | } |
| 273 | } |
| 274 | if !exists(filepath.Join(st.Dir, ExportFile)) { |
| 275 | need(st.Manifest.File) |
| 276 | } |
| 277 | for _, p := range st.Manifest.Projects { |
| 278 | if !exists(st.Repo(p.Name)) && held[p.Name] != p.SourceTip { |
| 279 | need(p.Bundle) |
| 280 | } |
| 281 | } |
| 282 | return inv, nil |
| 283 | } |
| 284 | |
| 285 | // Activate commits a staged upload: it makes it the active generation, or |
| 286 | // refuses it and leaves the active one as it was. It holds the store's |
| 287 | // lock throughout, so activations are serialised. In order, it: |
| 288 | // |
| 289 | // 1. refuses the upload unless its sequence is still greater than the |
| 290 | // high-water mark and nothing newer is staged, and as incomplete, |
| 291 | // with the bodies still needed, unless Inventory needs none; |
| 292 | // 2. moves the staged export.json into place and holds it to the |
| 293 | // manifest with CheckExport; |
| 294 | // 3. gives every project its repository: one already staged, the staged |
| 295 | // bundle through AcceptBundle, or the active generation's repository |
| 296 | // at the same source tip through CarryRepo; |
| 297 | // 4. checks that the staging directory holds export.json and exactly |
| 298 | // those repositories, each at its source tip, and removes the bodies; |
| 299 | // 5. renames the staging directory into exports/; |
| 300 | // 6. writes high-water durably; |
| 301 | // 7. swaps active to the new generation; |
| 302 | // 8. deletes the generations no reader holds and the stale staging |
| 303 | // directories. |
| 304 | // |
| 305 | // A crash before step 6 leaves the old generation active, and the next |
| 306 | // OpenStore deletes the new one. A crash between 6 and 7 is finished by |
| 307 | // the next OpenStore, which swaps active to the generation high-water |
| 308 | // names. |
| 309 | func (s *Store) Activate(ctx context.Context, st Staging) (Generation, error) { |
| 310 | unlock, err := s.lock() |
| 311 | if err != nil { |
| 312 | return Generation{}, err |
| 313 | } |
| 314 | defer unlock() |
| 315 | m := st.Manifest |
| 316 | if want := s.path("staging", strconv.FormatInt(m.Sequence, 10)); st.Dir != want { |
| 317 | return Generation{}, fmt.Errorf("the staging directory of sequence %d is %s, not %s", m.Sequence, want, st.Dir) |
| 318 | } |
| 319 | if err := s.checkNewer(m); err != nil { |
| 320 | return Generation{}, err |
| 321 | } |
| 322 | staged, err := s.staged() |
| 323 | if err != nil { |
| 324 | return Generation{}, err |
| 325 | } |
| 326 | if len(staged) == 0 || staged[len(staged)-1] != m.Sequence { |
| 327 | return Generation{}, refuse(CodeSuperseded, "the upload with sequence %d is not the newest staged", m.Sequence) |
| 328 | } |
| 329 | |
| 330 | inv, err := s.Inventory(st) |
| 331 | if err != nil { |
| 332 | return Generation{}, err |
| 333 | } |
| 334 | if len(inv.Needs) > 0 { |
| 335 | e := refuse(CodeIncomplete, "the upload with sequence %d still needs %d bodies", m.Sequence, len(inv.Needs)) |
| 336 | e.Needs = inv.Needs |
| 337 | return Generation{}, e |
| 338 | } |
| 339 | |
| 340 | // A staged body that fails here is removed, so the inventory names it |
| 341 | // as needed again rather than keep a body that cannot be activated. |
| 342 | exportPath := filepath.Join(st.Dir, ExportFile) |
| 343 | if !exists(exportPath) { |
| 344 | if err := os.Rename(st.Body(m.File), exportPath); err != nil { |
| 345 | return Generation{}, err |
| 346 | } |
| 347 | } |
| 348 | data, err := os.ReadFile(exportPath) |
| 349 | if err != nil { |
| 350 | return Generation{}, err |
| 351 | } |
| 352 | if _, err := m.CheckExport(data); err != nil { |
| 353 | os.Remove(exportPath) |
| 354 | return Generation{}, err |
| 355 | } |
| 356 | |
| 357 | for _, p := range m.Projects { |
| 358 | repo := st.Repo(p.Name) |
| 359 | if exists(repo) { |
| 360 | continue |
| 361 | } |
| 362 | if bundle := st.Body(p.Bundle); exists(bundle) { |
| 363 | if err := AcceptBundle(ctx, bundle, repo, p.SourceTip); err != nil { |
| 364 | os.Remove(bundle) |
| 365 | return Generation{}, err |
| 366 | } |
| 367 | continue |
| 368 | } |
| 369 | if err := s.carry(ctx, p, repo); err != nil { |
| 370 | return Generation{}, err |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | if err := os.RemoveAll(st.Bodies()); err != nil { |
| 375 | return Generation{}, err |
| 376 | } |
| 377 | if err := checkStaged(ctx, st); err != nil { |
| 378 | return Generation{}, err |
| 379 | } |
| 380 | for _, d := range []string{filepath.Join(st.Dir, "repos"), st.Dir} { |
| 381 | if err := syncDir(d); err != nil { |
| 382 | return Generation{}, err |
| 383 | } |
| 384 | } |
| 385 | dir := s.exportDir(m.Sequence) |
| 386 | if err := os.Rename(st.Dir, dir); err != nil { |
| 387 | return Generation{}, err |
| 388 | } |
| 389 | for _, d := range []string{s.path("exports"), s.path("staging")} { |
| 390 | if err := syncDir(d); err != nil { |
| 391 | return Generation{}, err |
| 392 | } |
| 393 | } |
| 394 | if err := writeDurably(s.path("high-water"), []byte(strconv.FormatInt(m.Sequence, 10)+"\n")); err != nil { |
| 395 | return Generation{}, err |
| 396 | } |
| 397 | if err := s.swap(m.Sequence); err != nil { |
| 398 | return Generation{}, err |
| 399 | } |
| 400 | return Generation{Sequence: m.Sequence, Dir: dir}, s.sweep() |
| 401 | } |
| 402 | |
| 403 | // carry gives a project the active generation's repository, when that |
| 404 | // generation holds the project at the manifest's source tip. |
| 405 | func (s *Store) carry(ctx context.Context, p ManifestProject, repo string) error { |
| 406 | g, release, err := s.Open() |
| 407 | defer release() |
| 408 | if err != nil && !errors.Is(err, ErrNoExport) { |
| 409 | return err |
| 410 | } |
| 411 | if err == nil { |
| 412 | e, err := g.Export() |
| 413 | if err != nil { |
| 414 | return err |
| 415 | } |
| 416 | for _, held := range e.Projects { |
| 417 | if held.Name == p.Name && held.SourceTip == p.SourceTip { |
| 418 | from, _ := g.Repo(p.Name) |
| 419 | return CarryRepo(ctx, from, repo, p.SourceTip) |
| 420 | } |
| 421 | } |
| 422 | } |
| 423 | return refuse(CodeIncomplete, "project %s has no staged bundle, and the receiver holds no repository of it at %s", p.Name, p.SourceTip) |
| 424 | } |
| 425 | |
| 426 | // checkStaged holds the staging directory to step 4 of Activate. |
| 427 | func checkStaged(ctx context.Context, st Staging) error { |
| 428 | entries, err := os.ReadDir(st.Dir) |
| 429 | if err != nil { |
| 430 | return err |
| 431 | } |
| 432 | var names []string |
| 433 | for _, e := range entries { |
| 434 | names = append(names, e.Name()) |
| 435 | } |
| 436 | if strings.Join(names, " ") != ExportFile+" repos" { |
| 437 | return fmt.Errorf("the staging directory %s holds %q, not export.json and repos", st.Dir, names) |
| 438 | } |
| 439 | repos, err := os.ReadDir(filepath.Join(st.Dir, "repos")) |
| 440 | if err != nil { |
| 441 | return err |
| 442 | } |
| 443 | if len(repos) != len(st.Manifest.Projects) { |
| 444 | return fmt.Errorf("the staging directory holds %d repositories for %d projects", len(repos), len(st.Manifest.Projects)) |
| 445 | } |
| 446 | for _, p := range st.Manifest.Projects { |
| 447 | refs, err := git(ctx, st.Repo(p.Name), "for-each-ref", "--format=%(objectname) %(refname)") |
| 448 | if err != nil { |
| 449 | return err |
| 450 | } |
| 451 | if got, want := strings.TrimSuffix(string(refs), "\n"), p.SourceTip+" "+MainRef; got != want { |
| 452 | return refuse(CodeBadBundle, "the staged repository of %s holds %q, not %q", p.Name, got, want) |
| 453 | } |
| 454 | } |
| 455 | return nil |
| 456 | } |
| 457 | |
| 458 | // checkNewer refuses a manifest whose sequence is not greater than the |
| 459 | // high-water mark. |
| 460 | func (s *Store) checkNewer(m *Manifest) error { |
| 461 | hw, err := s.HighWater() |
| 462 | if err != nil { |
| 463 | return err |
| 464 | } |
| 465 | return checkSequence(m, hw) |
| 466 | } |
| 467 | |
| 468 | // staged are the sequences with a staging directory, in ascending order. |
| 469 | func (s *Store) staged() ([]int64, error) { |
| 470 | entries, err := os.ReadDir(s.path("staging")) |
| 471 | if err != nil { |
| 472 | return nil, err |
| 473 | } |
| 474 | var seqs []int64 |
| 475 | for _, e := range entries { |
| 476 | if n, ok := decimal(e.Name()); ok { |
| 477 | seqs = append(seqs, n) |
| 478 | } |
| 479 | } |
| 480 | sort.Slice(seqs, func(i, j int) bool { return seqs[i] < seqs[j] }) |
| 481 | return seqs, nil |
| 482 | } |
| 483 | |
| 484 | // swap points active at the generation with sequence, atomically. |
| 485 | func (s *Store) swap(sequence int64) error { |
| 486 | tmp := s.path("active." + random()) |
| 487 | if err := os.Symlink("exports/"+strconv.FormatInt(sequence, 10), tmp); err != nil { |
| 488 | return err |
| 489 | } |
| 490 | if err := os.Rename(tmp, s.path("active")); err != nil { |
| 491 | os.Remove(tmp) |
| 492 | return err |
| 493 | } |
| 494 | return syncDir(s.dir) |
| 495 | } |
| 496 | |
| 497 | // recover finishes an activation interrupted between writing high-water |
| 498 | // and swapping active: the generation high-water names is complete, since |
| 499 | // it was renamed into exports/ before high-water was written. |
| 500 | func (s *Store) recover() error { |
| 501 | hw, err := s.HighWater() |
| 502 | if err != nil || hw == 0 { |
| 503 | return err |
| 504 | } |
| 505 | seq, ok, err := s.active() |
| 506 | if err != nil { |
| 507 | return err |
| 508 | } |
| 509 | if ok && seq == hw { |
| 510 | return nil |
| 511 | } |
| 512 | if !exists(s.exportDir(hw)) { |
| 513 | return nil |
| 514 | } |
| 515 | return s.swap(hw) |
| 516 | } |
| 517 | |
| 518 | // sweep deletes every generation but the active one that no reader holds, |
| 519 | // every staging directory not newer than the high-water mark, and the |
| 520 | // trash. A generation a reader holds is left for a later sweep. |
| 521 | func (s *Store) sweep() error { |
| 522 | active, ok, err := s.active() |
| 523 | if err != nil { |
| 524 | return err |
| 525 | } |
| 526 | hw, err := s.HighWater() |
| 527 | if err != nil { |
| 528 | return err |
| 529 | } |
| 530 | exports, err := os.ReadDir(s.path("exports")) |
| 531 | if err != nil { |
| 532 | return err |
| 533 | } |
| 534 | for _, e := range exports { |
| 535 | if n, valid := decimal(e.Name()); valid && ok && n == active { |
| 536 | continue |
| 537 | } |
| 538 | if err := s.delete(s.path("exports", e.Name())); err != nil { |
| 539 | return err |
| 540 | } |
| 541 | } |
| 542 | staging, err := os.ReadDir(s.path("staging")) |
| 543 | if err != nil { |
| 544 | return err |
| 545 | } |
| 546 | for _, e := range staging { |
| 547 | if n, valid := decimal(e.Name()); !valid || n <= hw { |
| 548 | if err := os.RemoveAll(s.path("staging", e.Name())); err != nil { |
| 549 | return err |
| 550 | } |
| 551 | } |
| 552 | } |
| 553 | trash, err := os.ReadDir(s.path("trash")) |
| 554 | if err != nil { |
| 555 | return err |
| 556 | } |
| 557 | for _, e := range trash { |
| 558 | if err := os.RemoveAll(s.path("trash", e.Name())); err != nil { |
| 559 | return err |
| 560 | } |
| 561 | } |
| 562 | return nil |
| 563 | } |
| 564 | |
| 565 | // delete removes the generation at dir unless a reader holds it. Holding |
| 566 | // the generation's lock exclusively, it renames the generation into the |
| 567 | // trash, so a reader that locks it afterwards finds it gone from its path. |
| 568 | func (s *Store) delete(dir string) error { |
| 569 | f, err := os.Open(dir) |
| 570 | if errors.Is(err, os.ErrNotExist) { |
| 571 | return nil |
| 572 | } |
| 573 | if err != nil { |
| 574 | return err |
| 575 | } |
| 576 | defer f.Close() |
| 577 | if err := flock(f, syscall.LOCK_EX|syscall.LOCK_NB); errors.Is(err, syscall.EWOULDBLOCK) { |
| 578 | return nil |
| 579 | } else if err != nil { |
| 580 | return err |
| 581 | } |
| 582 | trash := s.path("trash", filepath.Base(dir)+"-"+random()) |
| 583 | if err := os.Rename(dir, trash); err != nil { |
| 584 | return err |
| 585 | } |
| 586 | f.Close() |
| 587 | return os.RemoveAll(trash) |
| 588 | } |
| 589 | |
| 590 | // lock takes the store's activation lock, waiting for it. |
| 591 | func (s *Store) lock() (unlock func(), err error) { |
| 592 | f, err := os.OpenFile(s.path("lock"), os.O_RDWR|os.O_CREATE, 0o644) |
| 593 | if err != nil { |
| 594 | return nil, err |
| 595 | } |
| 596 | if err := flock(f, syscall.LOCK_EX); err != nil { |
| 597 | f.Close() |
| 598 | return nil, err |
| 599 | } |
| 600 | return func() { f.Close() }, nil |
| 601 | } |
| 602 | |
| 603 | // flock takes a lock on f's open file description, which closing f |
| 604 | // releases. |
| 605 | func flock(f *os.File, how int) error { |
| 606 | for { |
| 607 | err := syscall.Flock(int(f.Fd()), how) |
| 608 | if !errors.Is(err, syscall.EINTR) { |
| 609 | return err |
| 610 | } |
| 611 | } |
| 612 | } |
| 613 | |
| 614 | // writeDurably replaces the file at path with data: a temporary file |
| 615 | // beside it, synced, renamed over it, and the directory synced. |
| 616 | func writeDurably(path string, data []byte) error { |
| 617 | tmp := path + "." + random() |
| 618 | f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644) |
| 619 | if err != nil { |
| 620 | return err |
| 621 | } |
| 622 | _, err = f.Write(data) |
| 623 | if err == nil { |
| 624 | err = f.Sync() |
| 625 | } |
| 626 | if cerr := f.Close(); err == nil { |
| 627 | err = cerr |
| 628 | } |
| 629 | if err == nil { |
| 630 | err = os.Rename(tmp, path) |
| 631 | } |
| 632 | if err != nil { |
| 633 | os.Remove(tmp) |
| 634 | return err |
| 635 | } |
| 636 | return syncDir(filepath.Dir(path)) |
| 637 | } |
| 638 | |
| 639 | func syncDir(dir string) error { |
| 640 | f, err := os.Open(dir) |
| 641 | if err != nil { |
| 642 | return err |
| 643 | } |
| 644 | defer f.Close() |
| 645 | return f.Sync() |
| 646 | } |
| 647 | |
| 648 | func exists(path string) bool { |
| 649 | _, err := os.Lstat(path) |
| 650 | return err == nil |
| 651 | } |
| 652 | |
| 653 | func random() string { |
| 654 | b := make([]byte, 8) |
| 655 | rand.Read(b) |
| 656 | return hex.EncodeToString(b) |
| 657 | } |