gunk-dev/the-valley

store.go

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