gunk-dev/the-valley

store.go

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