gunk-dev/the-valley

store.go

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