gunk-dev/the-valley

store.go

source026c37612e61main's published tip history
27.4 KiB
1package export
2
3import (
4 "bytes"
5 "context"
6 "crypto/rand"
7 "encoding/hex"
8 "errors"
9 "fmt"
10 "io/fs"
11 "os"
12 "os/exec"
13 "path/filepath"
14 "sort"
15 "strconv"
16 "strings"
17 "sync"
18 "syscall"
19)
20
21// ErrNoExport is Open's error when the receiver has activated no export.
22var ErrNoExport = errors.New("no export has been activated")
23
24// Store is a receiver's state directory. Its layout is:
25//
26// <state>/lock serialises activations
27// <state>/high-water the greatest sequence accepted
28// <state>/active symlink to exports/<sequence>
29// <state>/exports/<sequence>/ one generation, immutable once active
30// export.json
31// repos/<project>.git
32// <state>/staging/<sequence>/ one upload, until it is committed
33// bodies/<sha256>
34// export.json
35// tmp/<project>.git a repository being built
36// repos/<project>.git a repository once it is accepted
37// <state>/trash/ generations being deleted
38//
39// A generation is activated by renaming its staging directory into
40// exports/, writing high-water durably, and then swapping active
41// atomically. A reader resolves active once per request with Open and
42// keeps that generation, locked against deletion, until it releases it.
43// An old generation is deleted only once no reader holds it.
44//
45// The locks are flock(2) locks, so readers and activations in different
46// processes on one host are held to the same rule as goroutines are.
47type Store struct {
48 dir string
49 report func(error)
50}
51
52// Generation is one activated export: its sequence and its directory.
53type Generation struct {
54 Sequence int64
55 Dir string
56}
57
58// ExportPath is the generation's export.json.
59func (g Generation) ExportPath() string { return filepath.Join(g.Dir, ExportFile) }
60
61// Repo is the bare repository of the generation's project called name. ok
62// is false for a name that is not a project name.
63func (g Generation) Repo(name string) (path string, ok bool) {
64 if !ValidName(name) {
65 return "", false
66 }
67 return filepath.Join(g.Dir, "repos", name+".git"), true
68}
69
70// Export reads and validates the generation's export.json.
71func (g Generation) Export() (*Export, error) {
72 data, err := os.ReadFile(g.ExportPath())
73 if err != nil {
74 return nil, err
75 }
76 return Decode(data)
77}
78
79// Staging is one upload being received: its manifest and its directory.
80type Staging struct {
81 Manifest *Manifest
82 Dir string
83}
84
85// Bodies is the directory StageBody writes the upload's bodies to.
86func (st Staging) Bodies() string { return filepath.Join(st.Dir, "bodies") }
87
88// Body is where the body b is staged once it verified.
89func (st Staging) Body(b Body) string { return filepath.Join(st.Bodies(), b.SHA256) }
90
91// Repo is where the staged repository of the project called name goes.
92func (st Staging) Repo(name string) string {
93 return filepath.Join(st.Dir, "repos", name+".git")
94}
95
96// tmp is the directory a staged repository is built in.
97func (st Staging) tmp() string { return filepath.Join(st.Dir, "tmp") }
98
99// OpenStore opens the state directory at dir, creating its layout. It
100// finishes an activation a crash interrupted after high-water was written,
101// and deletes what no activation can use. If it cannot finish checking the
102// generation that activation would make active, as when git is killed, it
103// deletes nothing and returns the error, and the receiver tries again.
104//
105// report is told of each failure the store works past rather than
106// returns: deleting what no activation can use, which the next sweep
107// tries again; syncing a swap of active to disk, which the next
108// OpenStore repeats after a crash; and a generation high-water names that
109// recovery found damaged and did not activate. None undoes an activation
110// that succeeded. A receiver logs them. A nil report drops them.
111func OpenStore(dir string, report func(error)) (*Store, error) {
112 abs, err := filepath.Abs(dir)
113 if err != nil {
114 return nil, err
115 }
116 if report == nil {
117 report = func(error) {}
118 }
119 s := &Store{dir: abs, report: report}
120 for _, d := range []string{abs, s.path("exports"), s.path("staging"), s.path("trash")} {
121 if err := os.MkdirAll(d, 0o755); err != nil {
122 return nil, err
123 }
124 }
125 unlock, err := s.lock()
126 if err != nil {
127 return nil, err
128 }
129 defer unlock()
130 if err := s.recover(); err != nil {
131 return nil, err
132 }
133 if err := s.sweep(); err != nil {
134 s.report(err)
135 }
136 return s, nil
137}
138
139// Dir is the state directory.
140func (s *Store) Dir() string { return s.dir }
141
142func (s *Store) path(parts ...string) string {
143 return filepath.Join(append([]string{s.dir}, parts...)...)
144}
145
146func (s *Store) exportDir(sequence int64) string {
147 return s.path("exports", strconv.FormatInt(sequence, 10))
148}
149
150// HighWater is the greatest sequence the store has accepted, 0 for none.
151func (s *Store) HighWater() (int64, error) {
152 data, err := os.ReadFile(s.path("high-water"))
153 if errors.Is(err, os.ErrNotExist) {
154 return 0, nil
155 }
156 if err != nil {
157 return 0, err
158 }
159 n, ok := decimal(strings.TrimSuffix(string(data), "\n"))
160 if !ok {
161 return 0, fmt.Errorf("%s holds %q, which is not a sequence", s.path("high-water"), data)
162 }
163 return n, nil
164}
165
166// active is the sequence active points at, and false when there is none.
167func (s *Store) active() (int64, bool, error) {
168 target, err := os.Readlink(s.path("active"))
169 if errors.Is(err, os.ErrNotExist) {
170 return 0, false, nil
171 }
172 if err != nil {
173 return 0, false, err
174 }
175 name, ok := strings.CutPrefix(target, "exports/")
176 n, valid := decimal(name)
177 if !ok || !valid {
178 return 0, false, fmt.Errorf("%s points at %q, which is no generation", s.path("active"), target)
179 }
180 return n, true, nil
181}
182
183// Open resolves active once and returns that generation, held against
184// deletion until release is called. A request serves everything from the
185// one generation it opened, so an activation during the request never
186// mixes two exports in one response. release may be called more than
187// once. Open's error is ErrNoExport before the first activation.
188func (s *Store) Open() (Generation, func(), error) {
189 for range 16 {
190 seq, ok, err := s.active()
191 if err != nil {
192 return Generation{}, func() {}, err
193 }
194 if !ok {
195 return Generation{}, func() {}, ErrNoExport
196 }
197 dir := s.exportDir(seq)
198 f, err := os.Open(dir)
199 if errors.Is(err, os.ErrNotExist) {
200 continue // active moved on and the generation was deleted
201 }
202 if err != nil {
203 return Generation{}, func() {}, err
204 }
205 if err := flock(f, syscall.LOCK_SH); err != nil {
206 f.Close()
207 return Generation{}, func() {}, err
208 }
209 // A deletion renames the generation away while it holds the lock
210 // exclusively, so a generation still at its path once this holds
211 // the lock is one no deletion will touch.
212 held, errHeld := f.Stat()
213 there, errThere := os.Stat(dir)
214 if errHeld != nil || errThere != nil || !os.SameFile(held, there) {
215 f.Close()
216 continue
217 }
218 var once sync.Once
219 release := func() { once.Do(func() { f.Close() }) }
220 return Generation{Sequence: seq, Dir: dir}, release, nil
221 }
222 return Generation{}, func() {}, errors.New("active moved on every time it was resolved")
223}
224
225// Stage is the staging directory for an upload whose manifest
226// VerifyManifest admitted. A manifest posted again finds its directory and
227// the bodies already staged in it. Staging a manifest discards the staging
228// directories of older ones. A manifest not newer than the high-water mark
229// is refused as replayed, and one older than another staged upload as
230// superseded.
231func (s *Store) Stage(m *Manifest) (Staging, error) {
232 unlock, err := s.lock()
233 if err != nil {
234 return Staging{}, err
235 }
236 defer unlock()
237 if err := s.checkNewer(m); err != nil {
238 return Staging{}, err
239 }
240 staged, err := s.staged()
241 if err != nil {
242 return Staging{}, err
243 }
244 for _, seq := range staged {
245 if seq > m.Sequence {
246 return Staging{}, refuse(CodeSuperseded, "the upload with sequence %d supersedes this one, %d", seq, m.Sequence)
247 }
248 if seq < m.Sequence {
249 if err := removeAll(s.path("staging", strconv.FormatInt(seq, 10))); err != nil {
250 return Staging{}, err
251 }
252 }
253 }
254 st := Staging{Manifest: m, Dir: s.path("staging", strconv.FormatInt(m.Sequence, 10))}
255 for _, d := range []string{st.Bodies(), filepath.Join(st.Dir, "repos")} {
256 if err := os.MkdirAll(d, 0o755); err != nil {
257 return Staging{}, err
258 }
259 }
260 return st, nil
261}
262
263// Inventory is the reply to the staged upload's manifest: the export the
264// store serves, the projects it holds, and the bodies still to be sent.
265// export.json is needed until it is staged. A bundle is needed until it is
266// staged or its repository is, unless the active generation holds its
267// project at the declared source tip, from which Activate carries it.
268func (s *Store) Inventory(st Staging) (Inventory, error) {
269 inv := Inventory{Schema: InventorySchema, Sequence: st.Manifest.Sequence, Holds: []Held{}, Needs: []Need{}}
270 held := map[string]string{}
271 g, release, err := s.Open()
272 defer release()
273 switch {
274 case errors.Is(err, ErrNoExport):
275 case err != nil:
276 return Inventory{}, err
277 default:
278 e, err := g.Export()
279 if err != nil {
280 return Inventory{}, err
281 }
282 digest, err := e.Digest()
283 if err != nil {
284 return Inventory{}, err
285 }
286 inv.Active = &Active{Sequence: g.Sequence, Digest: digest}
287 for _, p := range e.Projects {
288 inv.Holds = append(inv.Holds, Held{Project: p.Name, SourceTip: p.SourceTip})
289 held[p.Name] = p.SourceTip
290 }
291 }
292 needed := map[string]bool{}
293 need := func(b Body) {
294 if !needed[b.SHA256] && !exists(st.Body(b)) {
295 needed[b.SHA256] = true
296 inv.Needs = append(inv.Needs, Need{Name: b.Name, SHA256: b.SHA256, Size: b.Size})
297 }
298 }
299 if !exists(filepath.Join(st.Dir, ExportFile)) {
300 need(st.Manifest.File)
301 }
302 for _, p := range st.Manifest.Projects {
303 if !exists(st.Repo(p.Name)) && held[p.Name] != p.SourceTip {
304 need(p.Bundle)
305 }
306 }
307 return inv, nil
308}
309
310// Activate commits a staged upload: it makes it the active generation, or
311// refuses it and leaves the active one as it was. It holds the store's
312// lock throughout, so activations are serialised. In order, it:
313//
314// 1. refuses the upload unless its sequence is still greater than the
315// high-water mark and nothing newer is staged, and as incomplete,
316// with the bodies still needed, unless Inventory needs none;
317// 2. moves the staged export.json into place and holds it to the
318// manifest with CheckExport;
319// 3. gives every project its repository: one already staged, the staged
320// bundle through AcceptBundle, or the active generation's repository
321// at the same source tip through CarryRepo. A repository is built
322// under tmp/, every file and directory of it is synced to disk, and
323// only then is it renamed into repos/;
324// 4. removes the bodies and tmp/, and checks that the staging directory
325// holds export.json and exactly those repositories, each at its
326// source tip;
327// 5. syncs export.json, repos/ and the staging directory, renames the
328// staging directory into exports/, and syncs both parents;
329// 6. writes high-water durably, once every file and directory of the
330// generation is on disk;
331// 7. swaps active to the new generation;
332// 8. syncs the swap to disk, and deletes the generations no reader holds
333// and the stale staging directories.
334//
335// The activation has succeeded once step 7 is done: the new generation
336// serves, and high-water names it, so the next OpenStore restores it
337// after a crash. What fails in step 8 goes to the store's report, and
338// Activate still returns the new generation.
339//
340// A failure before step 7 is returned, and leaves the old generation
341// active. A crash before step 6 leaves the old generation active, and the
342// next OpenStore deletes the new one. After step 6 the sequence is
343// accepted: a commit retried after a failure between 6 and 7 is refused
344// as replayed. A crash between 6 and 7 is finished by the next OpenStore,
345// which swaps active to the generation high-water names.
346func (s *Store) Activate(ctx context.Context, st Staging) (Generation, error) {
347 unlock, err := s.lock()
348 if err != nil {
349 return Generation{}, err
350 }
351 defer unlock()
352 m := st.Manifest
353 if want := s.path("staging", strconv.FormatInt(m.Sequence, 10)); st.Dir != want {
354 return Generation{}, fmt.Errorf("the staging directory of sequence %d is %s, not %s", m.Sequence, want, st.Dir)
355 }
356 if err := s.checkNewer(m); err != nil {
357 return Generation{}, err
358 }
359 staged, err := s.staged()
360 if err != nil {
361 return Generation{}, err
362 }
363 if len(staged) == 0 || staged[len(staged)-1] != m.Sequence {
364 return Generation{}, refuse(CodeSuperseded, "the upload with sequence %d is not the newest staged", m.Sequence)
365 }
366
367 inv, err := s.Inventory(st)
368 if err != nil {
369 return Generation{}, err
370 }
371 if len(inv.Needs) > 0 {
372 e := refuse(CodeIncomplete, "the upload with sequence %d still needs %d bodies", m.Sequence, len(inv.Needs))
373 e.Needs = inv.Needs
374 return Generation{}, e
375 }
376
377 // A staged body that fails here is removed, so the inventory names it
378 // as needed again rather than keep a body that cannot be activated.
379 exportPath := filepath.Join(st.Dir, ExportFile)
380 if !exists(exportPath) {
381 if err := rename(st.Body(m.File), exportPath); err != nil {
382 return Generation{}, err
383 }
384 }
385 data, err := os.ReadFile(exportPath)
386 if err != nil {
387 return Generation{}, err
388 }
389 if _, err := m.CheckExport(data); err != nil {
390 os.Remove(exportPath)
391 return Generation{}, err
392 }
393
394 for _, p := range m.Projects {
395 if exists(st.Repo(p.Name)) {
396 continue
397 }
398 if err := s.build(ctx, st, p); err != nil {
399 return Generation{}, err
400 }
401 }
402
403 for _, d := range []string{st.Bodies(), st.tmp()} {
404 if err := removeAll(d); err != nil {
405 return Generation{}, err
406 }
407 }
408 if err := checkStaged(ctx, st); err != nil {
409 return Generation{}, err
410 }
411 for _, p := range []string{exportPath, filepath.Join(st.Dir, "repos"), st.Dir} {
412 if err := syncPath(p); err != nil {
413 return Generation{}, err
414 }
415 }
416 dir := s.exportDir(m.Sequence)
417 if err := rename(st.Dir, dir); err != nil {
418 return Generation{}, err
419 }
420 for _, d := range []string{s.path("exports"), s.path("staging")} {
421 if err := syncPath(d); err != nil {
422 return Generation{}, err
423 }
424 }
425 if err := writeDurably(s.path("high-water"), []byte(strconv.FormatInt(m.Sequence, 10)+"\n")); err != nil {
426 return Generation{}, err
427 }
428 if err := s.swap(m.Sequence); err != nil {
429 return Generation{}, err
430 }
431 if err := syncPath(s.dir); err != nil {
432 s.report(fmt.Errorf("the swap of active to generation %d is not on disk: %w", m.Sequence, err))
433 }
434 if err := s.sweep(); err != nil {
435 s.report(err)
436 }
437 return Generation{Sequence: m.Sequence, Dir: dir}, nil
438}
439
440// build gives the project its repository in staging, from the staged
441// bundle through AcceptBundle or from the active generation through
442// carry. It builds the repository under tmp/, syncs it to disk, and only
443// then renames it into repos/, so a repository in repos/ is always an
444// accepted one, whole on disk. A build a crash interrupted is left under
445// tmp/, where the next build of the project starts again.
446func (s *Store) build(ctx context.Context, st Staging, p ManifestProject) error {
447 tmp := filepath.Join(st.tmp(), p.Name+".git")
448 if err := removeAll(tmp); err != nil {
449 return err
450 }
451 if err := os.MkdirAll(st.tmp(), 0o755); err != nil {
452 return err
453 }
454 if bundle := st.Body(p.Bundle); exists(bundle) {
455 if err := AcceptBundle(ctx, bundle, tmp, p.SourceTip); err != nil {
456 os.Remove(bundle)
457 return err
458 }
459 } else if err := s.carry(ctx, p, tmp); err != nil {
460 return err
461 }
462 // git syncs what it fetches, but not what git init wrote before.
463 if err := syncTree(tmp); err != nil {
464 return err
465 }
466 return rename(tmp, st.Repo(p.Name))
467}
468
469// carry gives a project the active generation's repository, when that
470// generation holds the project at the manifest's source tip.
471func (s *Store) carry(ctx context.Context, p ManifestProject, repo string) error {
472 g, release, err := s.Open()
473 defer release()
474 if err != nil && !errors.Is(err, ErrNoExport) {
475 return err
476 }
477 if err == nil {
478 e, err := g.Export()
479 if err != nil {
480 return err
481 }
482 for _, held := range e.Projects {
483 if held.Name == p.Name && held.SourceTip == p.SourceTip {
484 from, _ := g.Repo(p.Name)
485 return CarryRepo(ctx, from, repo, p.SourceTip)
486 }
487 }
488 }
489 return refuse(CodeIncomplete, "project %s has no staged bundle, and the receiver holds no repository of it at %s", p.Name, p.SourceTip)
490}
491
492// checkStaged holds the staging directory to step 4 of Activate.
493func checkStaged(ctx context.Context, st Staging) error {
494 entries, err := os.ReadDir(st.Dir)
495 if err != nil {
496 return err
497 }
498 var names []string
499 for _, e := range entries {
500 names = append(names, e.Name())
501 }
502 if strings.Join(names, " ") != ExportFile+" repos" {
503 return fmt.Errorf("the staging directory %s holds %q, not export.json and repos", st.Dir, names)
504 }
505 repos, err := os.ReadDir(filepath.Join(st.Dir, "repos"))
506 if err != nil {
507 return err
508 }
509 if len(repos) != len(st.Manifest.Projects) {
510 return fmt.Errorf("the staging directory holds %d repositories for %d projects", len(repos), len(st.Manifest.Projects))
511 }
512 for _, p := range st.Manifest.Projects {
513 refs, err := git(ctx, st.Repo(p.Name), "for-each-ref", "--format=%(objectname) %(refname)")
514 if err != nil {
515 return err
516 }
517 if got, want := strings.TrimSuffix(string(refs), "\n"), p.SourceTip+" "+MainRef; got != want {
518 return refuse(CodeBadBundle, "the staged repository of %s holds %q, not %q", p.Name, got, want)
519 }
520 }
521 return nil
522}
523
524// errNotWhole is checkGeneration's finding that a generation is damaged.
525var errNotWhole = errors.New("the generation is not whole")
526
527// checkGeneration holds the activated generation at dir to what Activate
528// checked before high-water named it, and to git fsck. export.json is a
529// valid export, and each of its projects has a repository that git fsck
530// finds whole and that holds refs/heads/main at the project's source tip
531// and no other ref. A generation that fails gives an error that wraps
532// errNotWhole. Any other error says nothing about the generation: the
533// check did not finish, as when git is killed or fails to start.
534func checkGeneration(ctx context.Context, dir string) error {
535 g := Generation{Dir: dir}
536 data, err := os.ReadFile(g.ExportPath())
537 if errors.Is(err, fs.ErrNotExist) {
538 return fmt.Errorf("%w: it holds no export.json", errNotWhole)
539 }
540 if err != nil {
541 return err
542 }
543 e, err := Decode(data)
544 if err != nil {
545 return fmt.Errorf("%w: %v", errNotWhole, err)
546 }
547 for _, p := range e.Projects {
548 repo, _ := g.Repo(p.Name)
549 if _, err := os.Lstat(repo); errors.Is(err, fs.ErrNotExist) {
550 return fmt.Errorf("%w: the repository of %s is gone", errNotWhole, p.Name)
551 } else if err != nil {
552 return err
553 }
554 finding, err := fsck(ctx, repo)
555 if err != nil {
556 return fmt.Errorf("the check of the repository of %s did not finish: %w", p.Name, err)
557 }
558 if finding != "" {
559 return fmt.Errorf("%w: git fsck finds the repository of %s damaged: %s", errNotWhole, p.Name, finding)
560 }
561 refs, err := git(ctx, repo, "for-each-ref", "--format=%(objectname) %(refname)")
562 if err != nil {
563 return err
564 }
565 if got, want := strings.TrimSuffix(string(refs), "\n"), p.SourceTip+" "+MainRef; got != want {
566 return fmt.Errorf("%w: the repository of %s holds %q, not %q", errNotWhole, p.Name, got, want)
567 }
568 }
569 return nil
570}
571
572// fsck runs git fsck on the repository at repo. finding is the first
573// problem fsck names when it finds the repository damaged, and "" when it
574// finds it whole. fsck finds damage only when git exits on its own with a
575// non-zero status and names a problem. Anything else is an error, which
576// says nothing about the repository: git killed by a signal, failing to
577// start, outliving ctx, or exiting without naming a problem, as it does
578// when it runs out of memory.
579func fsck(ctx context.Context, repo string) (finding string, err error) {
580 // --git-dir, unlike -C, never lets git check a repository it finds
581 // above repo. LC_ALL=C keeps git's messages in the words fsckFinding
582 // reads.
583 cmd := command(ctx, "", "--git-dir="+repo, "fsck", "--no-progress", "--no-dangling")
584 cmd.Env = append(cmd.Env, "LC_ALL=C")
585 var out bytes.Buffer
586 cmd.Stdout, cmd.Stderr = &out, &out
587 err = cmd.Run()
588 if err == nil {
589 return "", nil
590 }
591 var exit *exec.ExitError
592 if errors.As(err, &exit) && exit.Exited() && ctx.Err() == nil {
593 if finding := fsckFinding(out.String()); finding != "" {
594 return finding, nil
595 }
596 }
597 last := strings.TrimSpace(out.String())
598 if i := strings.LastIndexByte(last, '\n'); i >= 0 {
599 last = last[i+1:]
600 }
601 if last == "" {
602 return "", fmt.Errorf("git fsck: %w", err)
603 }
604 return "", fmt.Errorf("git fsck: %w: %s", err, last)
605}
606
607// fsckFinding is the first line of git fsck's output that names a problem
608// with the repository, and "" when none does. fsck reports each problem it
609// finds on a line of its own: an error, a missing object, or a broken
610// link. git refuses a directory that holds no repository, and dies on an
611// object it finds corrupt. A failure of git's own, such as malloc failing,
612// names no problem.
613func fsckFinding(out string) string {
614 for _, line := range strings.Split(out, "\n") {
615 switch {
616 case strings.HasPrefix(line, "error: "),
617 strings.HasPrefix(line, "missing "),
618 strings.HasPrefix(line, "broken link from "),
619 strings.HasPrefix(line, "fatal: not a git repository"),
620 strings.HasPrefix(line, "fatal: ") && strings.HasSuffix(line, " is corrupt"):
621 return line
622 }
623 }
624 return ""
625}
626
627// checkNewer refuses a manifest whose sequence is not greater than the
628// high-water mark.
629func (s *Store) checkNewer(m *Manifest) error {
630 hw, err := s.HighWater()
631 if err != nil {
632 return err
633 }
634 return checkSequence(m, hw)
635}
636
637// staged are the sequences with a staging directory, in ascending order.
638func (s *Store) staged() ([]int64, error) {
639 entries, err := os.ReadDir(s.path("staging"))
640 if err != nil {
641 return nil, err
642 }
643 var seqs []int64
644 for _, e := range entries {
645 if n, ok := decimal(e.Name()); ok {
646 seqs = append(seqs, n)
647 }
648 }
649 sort.Slice(seqs, func(i, j int) bool { return seqs[i] < seqs[j] })
650 return seqs, nil
651}
652
653// swap points active at the generation with sequence, atomically. The
654// caller syncs the state directory.
655func (s *Store) swap(sequence int64) error {
656 tmp := s.path("active." + random())
657 if err := os.Symlink("exports/"+strconv.FormatInt(sequence, 10), tmp); err != nil {
658 return err
659 }
660 if err := rename(tmp, s.path("active")); err != nil {
661 os.Remove(tmp)
662 return err
663 }
664 return nil
665}
666
667// recover finishes an activation interrupted between writing high-water
668// and swapping active. The generation high-water names was on disk before
669// high-water was written, so it is whole unless the disk lost what it was
670// told to keep. recover holds it to checkGeneration before it swaps
671// active to it. A generation that fails is reported and not activated:
672// the old generation keeps serving, the sweep after recovery deletes the
673// damaged one, and the publisher's next manifest replaces it. A check
674// that did not finish says nothing about the generation, so recover
675// returns its error, and OpenStore deletes nothing and fails, to be tried
676// again.
677func (s *Store) recover() error {
678 hw, err := s.HighWater()
679 if err != nil || hw == 0 {
680 return err
681 }
682 seq, ok, err := s.active()
683 if err != nil {
684 return err
685 }
686 if ok && seq == hw {
687 return nil
688 }
689 dir := s.exportDir(hw)
690 if !exists(dir) {
691 return nil
692 }
693 if err := checkGeneration(context.Background(), dir); errors.Is(err, errNotWhole) {
694 s.report(fmt.Errorf("generation %d, which high-water names, is not activated: %w", hw, err))
695 return nil
696 } else if err != nil {
697 return fmt.Errorf("generation %d, which high-water names, is kept unchecked: %w", hw, err)
698 }
699 if err := s.swap(hw); err != nil {
700 return err
701 }
702 return syncPath(s.dir)
703}
704
705// sweep deletes every generation but the active one that no reader holds,
706// every staging directory not newer than the high-water mark, and the
707// trash. A generation a reader holds is left for a later sweep. A
708// deletion that fails does not stop the others, and the next sweep tries
709// it again.
710func (s *Store) sweep() error {
711 active, ok, err := s.active()
712 if err != nil {
713 return fmt.Errorf("sweeping %s: %w", s.dir, err)
714 }
715 hw, err := s.HighWater()
716 if err != nil {
717 return fmt.Errorf("sweeping %s: %w", s.dir, err)
718 }
719 var errs []error
720 exports, err := os.ReadDir(s.path("exports"))
721 errs = append(errs, err)
722 for _, e := range exports {
723 if n, valid := decimal(e.Name()); valid && ok && n == active {
724 continue
725 }
726 errs = append(errs, s.delete(s.path("exports", e.Name())))
727 }
728 staging, err := os.ReadDir(s.path("staging"))
729 errs = append(errs, err)
730 for _, e := range staging {
731 if n, valid := decimal(e.Name()); !valid || n <= hw {
732 errs = append(errs, removeAll(s.path("staging", e.Name())))
733 }
734 }
735 trash, err := os.ReadDir(s.path("trash"))
736 errs = append(errs, err)
737 for _, e := range trash {
738 errs = append(errs, removeAll(s.path("trash", e.Name())))
739 }
740 if err := errors.Join(errs...); err != nil {
741 return fmt.Errorf("sweeping %s: %w", s.dir, err)
742 }
743 return nil
744}
745
746// delete removes the generation at dir unless a reader holds it. Holding
747// the generation's lock exclusively, it renames the generation into the
748// trash, so a reader that locks it afterwards finds it gone from its path.
749func (s *Store) delete(dir string) error {
750 f, err := os.Open(dir)
751 if errors.Is(err, os.ErrNotExist) {
752 return nil
753 }
754 if err != nil {
755 return err
756 }
757 defer f.Close()
758 if err := flock(f, syscall.LOCK_EX|syscall.LOCK_NB); errors.Is(err, syscall.EWOULDBLOCK) {
759 return nil
760 } else if err != nil {
761 return err
762 }
763 trash := s.path("trash", filepath.Base(dir)+"-"+random())
764 if err := rename(dir, trash); err != nil {
765 return err
766 }
767 f.Close()
768 return removeAll(trash)
769}
770
771// lock takes the store's activation lock, waiting for it.
772func (s *Store) lock() (unlock func(), err error) {
773 f, err := os.OpenFile(s.path("lock"), os.O_RDWR|os.O_CREATE, 0o644)
774 if err != nil {
775 return nil, err
776 }
777 if err := flock(f, syscall.LOCK_EX); err != nil {
778 f.Close()
779 return nil, err
780 }
781 return func() { f.Close() }, nil
782}
783
784// flock takes a lock on f's open file description, which closing f
785// releases.
786func flock(f *os.File, how int) error {
787 for {
788 err := syscall.Flock(int(f.Fd()), how)
789 if !errors.Is(err, syscall.EINTR) {
790 return err
791 }
792 }
793}
794
795// writeDurably replaces the file at path with data: a temporary file
796// beside it, synced, renamed over it, and the directory synced.
797func writeDurably(path string, data []byte) error {
798 tmp := path + "." + random()
799 f, err := os.OpenFile(tmp, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o644)
800 if err != nil {
801 return err
802 }
803 _, err = f.Write(data)
804 if err == nil {
805 err = syncFile(f)
806 }
807 if cerr := f.Close(); err == nil {
808 err = cerr
809 }
810 if err == nil {
811 err = rename(tmp, path)
812 }
813 if err != nil {
814 os.Remove(tmp)
815 return err
816 }
817 return syncPath(filepath.Dir(path))
818}
819
820// syncTree syncs every file and directory in the tree at root. A symlink
821// is not followed: syncing its directory makes it durable.
822func syncTree(root string) error {
823 return filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
824 if err != nil {
825 return err
826 }
827 if !d.IsDir() && !d.Type().IsRegular() {
828 return nil
829 }
830 return syncPath(path)
831 })
832}
833
834// syncPath syncs the file or directory at path. Syncing a directory makes
835// its entries durable.
836func syncPath(path string) error {
837 f, err := os.Open(path)
838 if err != nil {
839 return err
840 }
841 defer f.Close()
842 return syncFile(f)
843}
844
845// The calls the store syncs, renames and deletes with. A test replaces
846// them to record their order or to make one fail.
847var (
848 syncFile = (*os.File).Sync
849 rename = os.Rename
850 removeAll = os.RemoveAll
851)
852
853func exists(path string) bool {
854 _, err := os.Lstat(path)
855 return err == nil
856}
857
858func random() string {
859 b := make([]byte, 8)
860 rand.Read(b)
861 return hex.EncodeToString(b)
862}