gunk-dev/the-valley

store.go

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