gunk-dev/the-valley

store.go

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