gunk-dev/the-valley

store.go

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