gunk-dev/the-valley

store.go

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