gunk-dev/the-valley

store.go

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