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