gunk-dev/the-valley

store.go

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