gunk-dev/the-valley

store.go

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