gunk-dev/the-valley

main.go

source9f64ac954238main's published tip history
39.9 KiB
1// valley-restacker rebases ready changes onto main when main moves under
2// them, as its own principal, so their evidence stays fresh without their
3// owners rebasing and approving again by hand.
4//
5// `valley-restacker run` reconciles at its start and then every
6// --interval, 15 seconds by default, until it is stopped. Each
7// reconciliation is one write pass. `valley-restacker once` is one write
8// pass on its own.
9//
10// A write pass first finishes the journal of earlier operations, if the
11// state directory holds one (publish.go). It then reads one snapshot of
12// origin, plans every family, builds the writes it would make for each
13// family it would restack or hold (build.go), adds them to the journal,
14// and makes them the way recovery would after a crash: the branch push,
15// then the versions, then the reports, reading a full snapshot of origin
16// again before each phase (recover.go). A family the journal still holds,
17// such as one whose versions a request has paused, stays there, and each
18// family that shares a change or a branch with it waits: the pass builds
19// nothing for it. So does each family the pass would otherwise restack or
20// hold that shares a change or a branch with another such family, as two
21// separate captured families that name one branch do (overlapping). Every
22// other family is planned as usual.
23//
24// `valley-restacker once --report-only` reads one snapshot of origin and
25// says which families it would restack, which it would hold and why, and
26// what capacity allows. For each family it would restack or hold, it
27// builds every write a pass would make, in its scratch repository, and
28// shows them: the one branch push, each change's next version and each
29// recorded change's report. It decides the journal of earlier
30// operations, if the state directory holds one, as recovery would. It
31// pushes nothing, and writes no journal.
32//
33// It talks to origin only over git, as a client, from a scratch repository
34// under its state directory. Hooks and external filters are off there:
35// the scratch repository's hooks path is /dev/null, and git reads neither
36// the system's nor the user's configuration, nor any the environment
37// injects, so no filter driver is defined. No git variable that points git
38// at another repository, program or configuration reaches anything a pass
39// runs (passes). A service that needs ssh settings passes them in
40// GIT_SSH_COMMAND. The scratch repository commits under the identity its
41// flags give, and never under one inherited from the environment, whether
42// as an identity variable or as configuration.
43//
44// A pass holds a lock on its state directory from start to end, so a
45// second pass on the same directory fails while one runs; run holds it
46// for as long as it runs. The directory belongs to one repository, target
47// and principal, the first a pass used it for, and a pass for any other
48// is refused. Every git, cue and attest a pass runs is killed, with what
49// it started, once the pass's --timeout passes. A pass whose output
50// nobody reads ends then too. once then lets go of the lock; run keeps
51// it, and starts its next pass after the wait. A message of its
52// own that nobody reads, such as the error it ends with, is given up on
53// after a few seconds.
54package main
55
56import (
57 "bytes"
58 "context"
59 "encoding/json"
60 "errors"
61 "flag"
62 "fmt"
63 "io"
64 "os"
65 "os/exec"
66 "os/signal"
67 "path/filepath"
68 "sort"
69 "strings"
70 "syscall"
71 "time"
72
73 "the-valley/change"
74 "the-valley/composed"
75 "the-valley/note"
76 "the-valley/rebase"
77)
78
79const usage = `valley-restacker: rebase ready changes onto main when main moves.
80
81usage: valley-restacker run [--interval DURATION] [flags]
82 valley-restacker once [--report-only] [flags]
83
84 run reconcile at once and then every --interval until stopped: each
85 reconciliation is one write pass. When a pass fails, write the
86 error to stderr and double the wait before the next pass, up to
87 5 minutes, until a pass succeeds
88 once one write pass: settle any open journal in the state directory,
89 then plan every family, append the writes for each family to
90 restack or hold to the journal, and push them in order: the
91 branch push, each change's next version, and each change's
92 report, reading a full snapshot of origin again before each
93 phase. Any family still in the journal stays there, and any
94 family that shares a change or branch with it waits. A family
95 the pass would otherwise restack or hold also waits when it
96 shares a change or branch with another such family
97 once --report-only
98 read one snapshot of origin and print what a pass would do: each
99 family, restack or hold with the reason, its capacity, the
100 integration requests it considered, and the writes a pass would
101 make for it, built in the scratch repository without pushing: the
102 branch push, each change's next version, and each change's
103 report. If the state directory holds a journal, print what
104 recovery decides for each write it names.
105 Pushes nothing, and writes no journal.
106
107flags:
108 --repo URL origin: the repository the restacker serves (required)
109 --target NAME the target changes are rebased onto (only main)
110 --state DIR where the scratch repository lives (required). A pass
111 locks it, and it belongs to the first repository,
112 target and principal a pass used it for
113 --principal NAME the principal the restacker pushes as (required)
114 --commit-name NAME the name the restacker commits under (default: the
115 principal)
116 --commit-email EMAIL the email it commits under
117 (default: restacker@the-valley.invalid)
118 --interval DURATION run: how long to wait after one pass before the next
119 (default 15s)
120 --timeout DURATION the longest a pass may run, writing its output
121 included; what it runs is killed then (default 10m)
122 --known-signers FILE verifier keys, for landings proved by integrator evidence
123 --integrator-name N the name the integrator signs under
124 --signer-projects F the signer projects file the integrator reads; while
125 it names the --integrator-name, no landing is proved
126 by integrator evidence. A file that does not read
127 stops the pass
128 --attest PATH the attest helper that checks a note (default: attest on PATH)
129 --instance-repo URL the repository carrying the group's floor
130 --instance-ref REF the ref whose tip carries the floor, a full ref name
131 read by that exact name (refs/heads/main)
132 --instance-policy DIR the floor's directory in that tip (policy/instance)
133 --instance DIR a materialized floor, for a host that serves none
134 --project-policy DIR the project layer, in the target tip (policy/project)
135 --schema FILE the verification schema (VALLEY_VERIFICATION_SCHEMA)
136 --json print each pass as JSON
137`
138
139func main() {
140 if len(os.Args) < 2 {
141 say(os.Stderr, usage)
142 os.Exit(2)
143 }
144 switch os.Args[1] {
145 case "once", "run":
146 // An interrupt or a stop ends the pass as its timeout does, killing
147 // what it runs, and then ends the command, which lets go of the lock
148 // on its state. It ends run between passes too.
149 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
150 command := once
151 if os.Args[1] == "run" {
152 command = loop
153 }
154 err := command(ctx, os.Args[2:], os.Stdout, os.Stderr)
155 stop()
156 if err != nil {
157 say(os.Stderr, fmt.Sprintf("valley-restacker: %v\n", err))
158 os.Exit(1)
159 }
160 case "help", "-h", "--help":
161 say(os.Stdout, usage)
162 default:
163 say(os.Stderr, fmt.Sprintf("valley-restacker: unknown command %q\n\n%s", os.Args[1], usage))
164 os.Exit(2)
165 }
166}
167
168// sayBound is the longest the process waits to write a message of its
169// own, such as the error it ends with.
170const sayBound = 5 * time.Second
171
172// say writes a message of the process's own, and gives up after sayBound.
173// A stderr nobody reads would otherwise hold the process after its pass
174// has ended and let go of its lock. The write given up on ends with the
175// process.
176func say(w io.Writer, message string) {
177 ctx, cancel := context.WithTimeout(context.Background(), sayBound)
178 defer cancel()
179 _ = writeOut(ctx, w, []byte(message))
180}
181
182// config is a pass's configuration, from flags.
183type config struct {
184 repo, target, state, principal string
185 commitName, commitEmail string
186 timeout, interval time.Duration
187 verify rebase.Verifier
188 floor composed.Floor
189 instanceRepo, projectPolicy string
190 schema, cue string
191 json bool
192}
193
194// defaultEmail is the email the restacker commits under unless
195// --commit-email names another. The .invalid domain is reserved, so the
196// address names no mailbox, as the integrator's does not.
197const defaultEmail = "restacker@the-valley.invalid"
198
199// maxBackoff is the longest run waits after a pass that failed.
200const maxBackoff = 5 * time.Minute
201
202// parse reads a command's flags into a configuration. --report-only is
203// once's, and --interval is run's.
204func parse(name string, args []string, errOut io.Writer) (c config, reportOnly bool, err error) {
205 fs := flag.NewFlagSet("valley-restacker "+name, flag.ContinueOnError)
206 fs.SetOutput(io.Discard)
207 fs.Usage = func() { say(errOut, usage) }
208 var only *bool
209 if name == "once" {
210 only = fs.Bool("report-only", false, "")
211 } else {
212 fs.DurationVar(&c.interval, "interval", 15*time.Second, "")
213 }
214 fs.StringVar(&c.repo, "repo", "", "")
215 fs.StringVar(&c.target, "target", rebase.Target, "")
216 fs.StringVar(&c.state, "state", "", "")
217 fs.StringVar(&c.principal, "principal", "", "")
218 fs.StringVar(&c.commitName, "commit-name", "", "")
219 fs.StringVar(&c.commitEmail, "commit-email", defaultEmail, "")
220 fs.DurationVar(&c.timeout, "timeout", 10*time.Minute, "")
221 fs.StringVar(&c.verify.Keys, "known-signers", "", "")
222 fs.StringVar(&c.verify.Signer, "integrator-name", "", "")
223 fs.StringVar(&c.verify.Attest, "attest", "", "")
224 signerProjects := fs.String("signer-projects", "", "")
225 fs.StringVar(&c.instanceRepo, "instance-repo", "", "")
226 fs.StringVar(&c.floor.Ref, "instance-ref", "refs/heads/main", "")
227 fs.StringVar(&c.floor.Dir, "instance-policy", "policy/instance", "")
228 fs.StringVar(&c.floor.Path, "instance", "", "")
229 fs.StringVar(&c.projectPolicy, "project-policy", "policy/project", "")
230 fs.StringVar(&c.schema, "schema", os.Getenv("VALLEY_VERIFICATION_SCHEMA"), "")
231 fs.BoolVar(&c.json, "json", false, "")
232 if err := fs.Parse(args); err != nil {
233 return c, false, err
234 }
235 if only != nil {
236 reportOnly = *only
237 }
238 switch {
239 case fs.NArg() > 0:
240 return c, false, fmt.Errorf("unexpected argument %q", fs.Arg(0))
241 case c.target != rebase.Target:
242 return c, false, fmt.Errorf("--target %s: a change may name only %s as its target", c.target, rebase.Target)
243 case name == "run" && c.interval <= 0:
244 return c, false, fmt.Errorf("--interval %v: run waits some time between passes", c.interval)
245 }
246 for _, f := range []struct{ flag, value string }{
247 {"--repo", c.repo}, {"--state", c.state}, {"--principal", c.principal}, {"--schema", c.schema},
248 } {
249 if f.value == "" {
250 return c, false, fmt.Errorf("%s is required", f.flag)
251 }
252 }
253 if !change.ValidPrincipal(c.principal) {
254 return c, false, fmt.Errorf("--principal %q is not a principal", c.principal)
255 }
256 if c.commitName == "" {
257 c.commitName = c.principal
258 }
259 if err := checkIdentity(c.commitName, c.commitEmail); err != nil {
260 return c, false, err
261 }
262 if c.timeout <= 0 {
263 return c, false, fmt.Errorf("--timeout %v: a pass needs some time to run", c.timeout)
264 }
265 // The floor comes from the instance repository's tip, or from a
266 // directory on disk, and never from both, as for the integrator.
267 if (c.instanceRepo == "") == (c.floor.Path == "") {
268 return c, false, errors.New("exactly one of --instance-repo and --instance is required: the floor is read from the instance repository's tip, or from a materialized directory")
269 }
270 if c.instanceRepo != "" && !strings.HasPrefix(c.floor.Ref, "refs/") {
271 return c, false, fmt.Errorf("--instance-ref %s is not a full ref name; name it whole, as refs/heads/main", c.floor.Ref)
272 }
273 if c.verify.Attest == "" {
274 c.verify.Attest, _ = exec.LookPath("attest")
275 }
276 if *signerProjects != "" {
277 data, err := os.ReadFile(*signerProjects)
278 if err != nil {
279 return c, false, fmt.Errorf("--signer-projects: %w", err)
280 }
281 if c.verify.SignerProjects, err = note.ParseSignerProjects(data); err != nil {
282 return c, false, fmt.Errorf("--signer-projects %s does not read: %w", *signerProjects, err)
283 }
284 }
285 if c.cue, err = exec.LookPath("cue"); err != nil {
286 return c, false, errors.New("cue is not on the path; the restacker composes the policy with it")
287 }
288 return c, reportOnly, nil
289}
290
291// once is one pass, a write pass unless --report-only says otherwise.
292func once(ctx context.Context, args []string, out, errOut io.Writer) error {
293 // What the pass runs inherits no git variable that points git
294 // elsewhere or gives it configuration (passes).
295 controlEnvironment()
296 c, reportOnly, err := parse("once", args, errOut)
297 if err != nil {
298 return err
299 }
300 release, err := lockState(c.state)
301 if err != nil {
302 return err
303 }
304 defer release()
305 if err := bindState(c.state, c.binding()); err != nil {
306 return err
307 }
308 _, err = pass(ctx, c, reportOnly, out, errOut, false)
309 return err
310}
311
312// loop is run: a write pass at once, and another every interval after
313// the last one ended, until ctx is done. It holds the lock on its state
314// for as long as it runs, past a pass that ends at its timeout. A pass
315// that fails is said, and the wait before the next doubles, up to
316// maxBackoff, until a pass succeeds. A pass that tried no write and
317// leaves no journal open prints nothing.
318func loop(ctx context.Context, args []string, out, errOut io.Writer) error {
319 controlEnvironment()
320 c, _, err := parse("run", args, errOut)
321 if err != nil {
322 return err
323 }
324 release, err := lockState(c.state)
325 if err != nil {
326 return err
327 }
328 defer release()
329 if err := bindState(c.state, c.binding()); err != nil {
330 return err
331 }
332 failures := 0
333 for {
334 _, err := pass(ctx, c, false, out, errOut, true)
335 if ctx.Err() != nil {
336 return nil
337 }
338 wait := c.interval
339 if err != nil {
340 failures++
341 wait = backoff(c.interval, failures)
342 say(errOut, fmt.Sprintf("valley-restacker: the pass failed, and the next starts in %v: %v\n", wait, err))
343 } else {
344 failures = 0
345 }
346 select {
347 case <-ctx.Done():
348 return nil
349 case <-time.After(wait):
350 }
351 }
352}
353
354// backoff is how long run waits after the given number of passes in a row
355// have failed: twice as long for each, from the interval, up to
356// maxBackoff.
357func backoff(interval time.Duration, failures int) time.Duration {
358 wait := interval
359 for i := 0; i < failures && wait < maxBackoff; i++ {
360 wait *= 2
361 }
362 return min(wait, maxBackoff)
363}
364
365// pass runs one pass under its timeout and prints it: the plan and each
366// write it tried, or, when quiet, only the writes it tried and a journal
367// it leaves open. A write it tried may have been refused, or not pushed
368// at all.
369func pass(ctx context.Context, c config, reportOnly bool, out, errOut io.Writer, quiet bool) (*Plan, error) {
370 ctx, cancel := context.WithTimeout(ctx, c.timeout)
371 defer cancel()
372 g, err := scratchRepo(ctx, c)
373 if err != nil {
374 return nil, timedOut(ctx, c, err)
375 }
376 g.Stderr = errOut
377 var p *Plan
378 if reportOnly {
379 p, err = planOnce(ctx, g, c)
380 } else {
381 p, err = writeOnce(ctx, g, c)
382 }
383 if err != nil {
384 return p, timedOut(ctx, c, err)
385 }
386 if quiet && len(p.Actions) == 0 && p.Pending == nil {
387 return p, nil
388 }
389 var text bytes.Buffer
390 switch {
391 case c.json:
392 enc := json.NewEncoder(&text)
393 enc.SetIndent("", " ")
394 if err := enc.Encode(p); err != nil {
395 return p, err
396 }
397 case quiet:
398 printPublished(&text, p)
399 default:
400 printPlan(&text, p)
401 }
402 if err := writeOut(ctx, out, text.Bytes()); err != nil {
403 return p, timedOut(ctx, c, err)
404 }
405 return p, nil
406}
407
408// writeOut writes data to out, and gives up once ctx is done. A reader
409// that stops reading holds the write, and would otherwise hold the pass,
410// and the lock on its state, past its --timeout. The write given up on
411// ends with the process.
412func writeOut(ctx context.Context, out io.Writer, data []byte) error {
413 done := make(chan error, 1)
414 go func() {
415 _, err := out.Write(data)
416 done <- err
417 }()
418 select {
419 case err := <-done:
420 return err
421 case <-ctx.Done():
422 return fmt.Errorf("the plan was not written: %w", ctx.Err())
423 }
424}
425
426// timedOut says so when a pass failed because it ran past its timeout.
427func timedOut(ctx context.Context, c config, err error) error {
428 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
429 return fmt.Errorf("the pass ran past its --timeout of %v: %w", c.timeout, err)
430 }
431 return err
432}
433
434// checkIdentity refuses a name or an email git cannot commit under: an
435// empty one, or one with a control character or an angle bracket, which
436// would end the name or the email early in a commit's header.
437func checkIdentity(name, email string) error {
438 for _, f := range []struct{ flag, value string }{{"--commit-name", name}, {"--commit-email", email}} {
439 if strings.TrimSpace(f.value) == "" || strings.ContainsAny(f.value, "<>") ||
440 strings.ContainsFunc(f.value, func(r rune) bool { return r < 0x20 || r == 0x7f }) {
441 return fmt.Errorf("%s %q: a commit's name and email are not empty and hold no angle bracket or control character", f.flag, f.value)
442 }
443 }
444 return nil
445}
446
447// What a pass passes on to the programs it runs. A git variable can point
448// git at another repository (GIT_DIR, GIT_WORK_TREE, GIT_COMMON_DIR,
449// GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY, GIT_ALTERNATE_OBJECT_DIRECTORIES,
450// GIT_NAMESPACE, GIT_GRAFT_FILE, GIT_REPLACE_REF_BASE), at other programs
451// (GIT_EXEC_PATH, GIT_TEMPLATE_DIR), at other attributes (GIT_ATTR_SOURCE)
452// or at another format (GIT_DEFAULT_HASH). It can inject configuration
453// that beats the repository's own: GIT_CONFIG_COUNT with GIT_CONFIG_KEY_<n>
454// and GIT_CONFIG_VALUE_<n>, and GIT_CONFIG_PARAMETERS, so an inherited
455// author.name would beat user.name and an inherited core.hooksPath would
456// turn hooks back on. The other GIT_CONFIG* variables name configuration
457// files. And GIT_AUTHOR_*, GIT_COMMITTER_* and EMAIL give an identity
458// ahead of the configuration. So a pass passes on no GIT_* variable but
459// the ones that say how to reach origin over ssh, and no EMAIL. It drops
460// them from its own environment as it starts (controlEnvironment), so
461// cue, attest and the git that composes the policy run without them too.
462var passedOn = map[string]bool{"GIT_SSH": true, "GIT_SSH_COMMAND": true, "GIT_SSH_VARIANT": true}
463
464// passes reports whether a pass passes on the environment variable named.
465func passes(name string) bool {
466 switch {
467 case name == "EMAIL":
468 return false
469 case strings.HasPrefix(name, "GIT_"):
470 return passedOn[name]
471 }
472 return true
473}
474
475// gitSettings are what a pass sets for every git it runs, scratch
476// repository or not: no system or user configuration, no system
477// attributes, and no question asked at a terminal.
478var gitSettings = [][2]string{
479 {"GIT_CONFIG_NOSYSTEM", "1"},
480 {"GIT_CONFIG_GLOBAL", "/dev/null"},
481 {"GIT_ATTR_NOSYSTEM", "1"},
482 {"GIT_TERMINAL_PROMPT", "0"},
483}
484
485// controlEnvironment leaves the process's own environment holding only
486// what a pass passes on, and gitSettings.
487func controlEnvironment() {
488 for _, kv := range os.Environ() {
489 if name, _, _ := strings.Cut(kv, "="); !passes(name) {
490 os.Unsetenv(name)
491 }
492 }
493 for _, kv := range gitSettings {
494 os.Setenv(kv[0], kv[1])
495 }
496}
497
498// scratchRepo makes, or reuses, the repository a pass reads origin into,
499// and returns git run in it with hooks and configured filters off,
500// committing under the restacker's identity. git there reads no
501// configuration but the repository's, and is given its author and
502// committer explicitly. A commit it rebases keeps its own author: a
503// rebase takes the author from the commit it picks. git there is
504// unattended: it never asks a question, and every git it runs is killed
505// whole once ctx is done.
506//
507// The repository has a work tree, though nothing is ever checked out in
508// it: attest, which digests a version's tree and verifies the
509// integrator's transfer statements, reads only a repository with a work
510// tree.
511func scratchRepo(ctx context.Context, c config) (rebase.Git, error) {
512 dir := filepath.Join(c.state, "scratch")
513 var env []string
514 for _, kv := range os.Environ() {
515 if name, _, _ := strings.Cut(kv, "="); passes(name) {
516 env = append(env, kv)
517 }
518 }
519 for _, kv := range gitSettings {
520 env = append(env, kv[0]+"="+kv[1])
521 }
522 env = append(env,
523 "GIT_AUTHOR_NAME="+c.commitName,
524 "GIT_AUTHOR_EMAIL="+c.commitEmail,
525 "GIT_COMMITTER_NAME="+c.commitName,
526 "GIT_COMMITTER_EMAIL="+c.commitEmail,
527 )
528 g := rebase.Git{Dir: dir, Env: env, Stderr: os.Stderr, Unattended: true}
529 if _, err := os.Stat(filepath.Join(dir, ".git", "HEAD")); err != nil {
530 if err := os.MkdirAll(dir, 0o700); err != nil {
531 return g, err
532 }
533 if err := run(ctx, g, "init", "--quiet"); err != nil {
534 return g, err
535 }
536 }
537 // user.useConfigOnly stops git guessing an identity from the host's
538 // name and the user's account. core.attributesFile is set, since git
539 // otherwise reads the user's own attributes file under
540 // XDG_CONFIG_HOME or HOME whatever configuration it reads, and an
541 // attribute such as merge=union there would change how a rebase
542 // merges. core.fsync makes each object and ref a pass writes durable
543 // before git reports it written, as a journal of writes relies on. The
544 // state directory is bound to one repository (bindState), so origin's
545 // URL is the same every pass.
546 for _, kv := range [][2]string{
547 {"core.hooksPath", "/dev/null"},
548 {"core.fsmonitor", "false"},
549 {"core.attributesFile", "/dev/null"},
550 {"core.fsync", "objects,reference"},
551 {"user.name", c.commitName},
552 {"user.email", c.commitEmail},
553 {"user.useConfigOnly", "true"},
554 {"remote.origin.url", c.repo},
555 } {
556 if err := run(ctx, g, "config", kv[0], kv[1]); err != nil {
557 return g, err
558 }
559 }
560 return g, nil
561}
562
563func run(ctx context.Context, g rebase.Git, args ...string) error {
564 _, err := gitOut(ctx, g, args...)
565 return err
566}
567
568// gitOut runs git as the rebase engine runs it (rebase.Git.Command): killed
569// with what it started once ctx is done, and with the wait for its output
570// bounded.
571func gitOut(ctx context.Context, g rebase.Git, args ...string) (string, error) {
572 cmd := g.Command(ctx, args...)
573 var stderr strings.Builder
574 cmd.Stderr = &stderr
575 b, err := cmd.Output()
576 switch {
577 case ctx.Err() != nil:
578 return "", fmt.Errorf("git %s did not finish: %w", strings.Join(args, " "), ctx.Err())
579 case err != nil && !errors.Is(err, exec.ErrWaitDelay):
580 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))
581 }
582 return string(b), nil
583}
584
585// ancestry is merge-base --is-ancestor, telling "no" (exit 1) apart from a
586// question git could not answer.
587func ancestry(ctx context.Context, g rebase.Git) Ancestry {
588 return func(a, b string) (bool, error) {
589 err := g.Command(ctx, "merge-base", "--is-ancestor", a, b).Run()
590 var exit *exec.ExitError
591 switch {
592 case err == nil || errors.Is(err, exec.ErrWaitDelay):
593 return true, nil
594 case errors.As(err, &exit) && exit.ExitCode() == 1:
595 return false, nil
596 }
597 return false, fmt.Errorf("could not tell whether %s is in %s", short(a), short(b))
598 }
599}
600
601// incoming reads, once for each head asked about, the commits it reaches
602// that tip does not. A head that is not a commit, or is missing, is an
603// error, asked about again as the same error.
604func incoming(ctx context.Context, g rebase.Git, tip string) Incoming {
605 type read struct {
606 commits map[string]bool
607 err error
608 }
609 seen := map[string]read{}
610 return func(head string) (map[string]bool, error) {
611 if r, ok := seen[head]; ok {
612 return r.commits, r.err
613 }
614 var r read
615 out, err := gitOut(ctx, g, "rev-list", head+"^{commit}", "--not", tip)
616 if err != nil {
617 r.err = fmt.Errorf("could not read the commits %s would bring to %s", short(head), rebase.Target)
618 } else {
619 r.commits = map[string]bool{}
620 for _, c := range strings.Fields(out) {
621 r.commits[c] = true
622 }
623 }
624 if ctx.Err() == nil {
625 seen[head] = r
626 }
627 return r.commits, r.err
628 }
629}
630
631// policyCap composes the policy at the target tip and reads the cap on
632// automatic versions: the floor from the instance repository's tip, read
633// over git into the scratch repository, or from --instance; the project
634// layer from the tip.
635func policyCap(ctx context.Context, g rebase.Git, c config, tip string) (int, error) {
636 floor := c.floor
637 if c.instanceRepo != "" {
638 out, err := gitOut(ctx, g, "ls-remote", c.instanceRepo, floor.Ref)
639 if ctx.Err() != nil {
640 return 0, err
641 }
642 // ls-remote matches its pattern against the tail of each name,
643 // so it lists refs/heads/refs/heads/main for refs/heads/main, a
644 // branch a pusher can make. Only the ref of that exact name counts.
645 var oid string
646 for _, line := range strings.Split(out, "\n") {
647 if id, name, ok := strings.Cut(line, "\t"); ok && name == floor.Ref {
648 oid = id
649 }
650 }
651 if err != nil || !rebase.IsObjectID(oid) {
652 return 0, fmt.Errorf("no instance policy layer: %s has no %s: %s", c.instanceRepo, floor.Ref, composed.Floorless)
653 }
654 if err := run(ctx, g, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", c.instanceRepo, oid); err != nil {
655 return 0, err
656 }
657 floor.Repo, floor.Ref = g.Dir, oid
658 }
659 instance, done, err := floor.Open(ctx, "valley-restacker-floor")
660 if err != nil {
661 return 0, err
662 }
663 defer done()
664 project, _, doneProject, err := composed.Project(ctx, g.Dir, tip, c.projectPolicy, "valley-restacker-project")
665 if err != nil {
666 return 0, err
667 }
668 defer doneProject()
669 pol, err := composed.Compose(ctx, c.cue, c.schema, instance, project)
670 if err != nil {
671 return 0, err
672 }
673 return CapOf(pol.MaxAutomaticVersions)
674}
675
676// planOnce reads one snapshot and the cap at its tip, decides the journal
677// in the state directory if there is one, plans every family, and builds
678// the writes a pass would make. It pushes nothing, writes no journal, and
679// lets go of what it prepared.
680func planOnce(ctx context.Context, g rebase.Git, c config) (*Plan, error) {
681 s, p, err := planned(ctx, g, c)
682 if err != nil {
683 return nil, err
684 }
685 // --report-only: what is built is shown, and neither kept nor pushed.
686 out, err := build(ctx, g, s, p, c.binding(), p.Operation)
687 if err != nil {
688 return nil, err
689 }
690 out.releasePrepared(ctx, g)
691 return p, nil
692}
693
694// planned reads one snapshot and the cap at its tip, and plans it.
695func planned(ctx context.Context, g rebase.Git, c config) (*rebase.Snapshot, *Plan, error) {
696 s, err := rebase.ReadSnapshot(ctx, g, c.verify)
697 if err != nil {
698 return nil, nil, err
699 }
700 if s.Tip == "" {
701 return nil, nil, fmt.Errorf("origin has no %s", rebase.Target)
702 }
703 cap, err := policyCap(ctx, g, c, s.Tip)
704 if err != nil {
705 return nil, nil, err
706 }
707 p, err := plan(ctx, g, c, s, cap)
708 if err != nil {
709 return nil, nil, err
710 }
711 return s, p, nil
712}
713
714// writeOnce is a write pass. It settles the journal of earlier
715// operations first, if the state directory holds one. It then plans, with
716// each family that shares a change or a branch with a family the journal
717// still holds waiting for it, builds the pass's writes, adds them to the
718// journal, keeps it, and settles it (publish.go). A journal that does not
719// read, or is another's, stops the pass: the pass would otherwise write
720// its own in its place, and lose what that one names.
721func writeOnce(ctx context.Context, g rebase.Git, c config) (*Plan, error) {
722 path := filepath.Join(c.state, journalFile)
723 j, err := loadJournal(c.state, c.binding())
724 if err != nil {
725 return nil, fmt.Errorf("%w. A write pass refuses to run while this journal is in place: check origin by hand and move the journal file aside", err)
726 }
727 actions := []Action{}
728 var found *Recovery
729 if j != nil {
730 st, err := settle(ctx, g, c, j)
731 if err != nil {
732 return nil, err
733 }
734 actions, found = st.actions, st.last
735 found.Journal = path
736 if st.closed {
737 j = nil
738 }
739 }
740 // The planner reads the journal settle left in the state directory.
741 s, p, err := planned(ctx, g, c)
742 if err != nil {
743 return nil, err
744 }
745 p.Recovery, p.Actions = found, actions
746 out, err := build(ctx, g, s, p, c.binding(), p.Operation)
747 if err != nil {
748 return nil, err
749 }
750 defer out.releasePrepared(ctx, g)
751 if len(out.journal.Families) == 0 {
752 if j != nil {
753 p.Pending = found
754 }
755 return p, nil
756 }
757 if j != nil {
758 out.journal.Families = append(j.Families, out.journal.Families...)
759 }
760 if err := keep(ctx, g, c.state, out.journal); err != nil {
761 return nil, err
762 }
763 // The journal keeps every object its writes push reachable now.
764 out.releasePrepared(ctx, g)
765 st, err := settle(ctx, g, c, out.journal)
766 p.Actions = append(p.Actions, st.actions...)
767 if err != nil {
768 return nil, err
769 }
770 if !st.closed {
771 p.Pending = st.last
772 p.Pending.Journal = path
773 }
774 return p, nil
775}
776
777// binding is what a pass's state directory and journal belong to.
778func (c config) binding() binding {
779 return binding{Repository: c.repo, Target: c.target, Principal: c.principal}
780}
781
782// requestsOf is every integration request the snapshot lists, in name
783// order, and the evidence fingerprint of every attestation ref. The refs
784// are a map, read in no fixed order, so the requests are put in name
785// order before anything judges them: their reasons and notes, and the
786// reports that carry them, are then the same for the same snapshot.
787//
788// The snapshot lists request heads and does not fetch them. They are
789// fetched here, before any ancestry is read, all at once and then one by
790// one when that fails, so one head origin cannot serve leaves the others
791// readable.
792func requestsOf(ctx context.Context, g rebase.Git, s *rebase.Snapshot) ([]Request, string) {
793 var attestations []string
794 var requests []Request
795 for ref, oid := range s.Refs {
796 switch {
797 case strings.HasPrefix(ref, rebase.AttestationRefs):
798 attestations = append(attestations, ref+" "+oid)
799 case strings.HasPrefix(ref, rebase.RequestPrefix):
800 requests = append(requests, Request{Name: strings.TrimPrefix(ref, rebase.RequestPrefix), Head: oid})
801 }
802 }
803 sort.Slice(requests, func(i, j int) bool { return requests[i].Name < requests[j].Name })
804 var heads []string
805 for _, r := range requests {
806 heads = append(heads, r.Head)
807 }
808 if rebase.Fetch(ctx, g, heads...) != nil {
809 for _, h := range heads {
810 _ = rebase.Fetch(ctx, g, h)
811 }
812 }
813 return requests, change.EvidenceFingerprint(attestations)
814}
815
816// plan decides the journal in the state directory, if there is one, and
817// plans every family in the snapshot, with the cap given.
818func plan(ctx context.Context, g rebase.Git, c config, s *rebase.Snapshot, cap int) (*Plan, error) {
819 requests, evidence := requestsOf(ctx, g, s)
820 p := &Plan{
821 Target: rebase.Target, Tip: s.Tip, Evidence: evidence, Cap: cap,
822 Operation: newOperation(time.Now()), Actions: []Action{},
823 }
824 in := incoming(ctx, g, s.Tip)
825
826 j, err := loadJournal(c.state, c.binding())
827 switch {
828 case err != nil:
829 p.Recovery = &Recovery{Journal: filepath.Join(c.state, journalFile), Error: err.Error(), Decisions: []Decision{}}
830 case j != nil:
831 p.Recovery = decide(j, reading{
832 s: s, requests: requests, evidence: p.Evidence, in: in, is: ancestry(ctx, g),
833 have: func(oid string) bool { return run(ctx, g, "cat-file", "-e", oid) == nil },
834 landed: s.IsLanded,
835 })
836 p.Recovery.Journal = filepath.Join(c.state, journalFile)
837 }
838 journaled := journaledLayers(j)
839
840 seen := map[string]bool{}
841 for _, n := range s.Changes {
842 if seen[n.ID] || !s.Unlanded(n) {
843 continue
844 }
845 f, err := rebase.Capture(s, rebase.Selection{ID: n.ID, Whole: true})
846 if err != nil {
847 return nil, err
848 }
849 for _, l := range f.Layers {
850 if l.ID != "" {
851 seen[l.ID] = true
852 }
853 }
854 fp := judge(f, s, c.principal, p, requests, in)
855 if why := waits(f, journaled); why != "" {
856 fp.Action, fp.Reasons = wait, []string{why}
857 }
858 p.Families = append(p.Families, fp)
859 p.families = append(p.families, f)
860 }
861 overlapping(p)
862 return p, nil
863}
864
865// overlapping has each family the pass would build writes for wait when
866// it shares a change or a branch with another such family. Two changes
867// that name one branch are two captured families when neither's head
868// descends from the other's and no shared lower layer joins them, and
869// the journal takes no two families that share a branch, since their
870// writes would race. So neither is built while both name it, and every
871// other family is planned as usual.
872func overlapping(p *Plan) {
873 type holder struct {
874 family int
875 name string
876 }
877 whose := map[string][]holder{} // the families that would be written, by each change and branch
878 for i, fp := range p.Families {
879 if fp.Action != restack && fp.Action != hold {
880 continue
881 }
882 for _, l := range p.families[i].Layers {
883 for _, key := range layerKeys(l.ID, l.Branch) {
884 if hs := whose[key]; len(hs) == 0 || hs[len(hs)-1].family != i {
885 whose[key] = append(whose[key], holder{i, l.Name})
886 }
887 }
888 }
889 }
890 for i := range p.Families {
891 fp := &p.Families[i]
892 if fp.Action != restack && fp.Action != hold {
893 continue
894 }
895 why := ""
896 for _, l := range p.families[i].Layers {
897 for _, key := range layerKeys(l.ID, l.Branch) {
898 for _, h := range whose[key] {
899 if h.family != i && why == "" {
900 why = fmt.Sprintf("%s shares the %s with %s in another family, so both families wait while both name it", l.Name, key, h.name)
901 }
902 }
903 }
904 }
905 if why != "" {
906 fp.Action, fp.Reasons = wait, []string{why}
907 }
908 }
909}
910
911// journaledLayers is the operation of each family the journal holds, by
912// each of the family's changes and branches (layerKeys).
913func journaledLayers(j *Journal) map[string]string {
914 held := map[string]string{}
915 if j == nil {
916 return held
917 }
918 for _, f := range j.Families {
919 for _, l := range f.Observed.Layers {
920 for _, key := range layerKeys(l.ID, l.Branch) {
921 held[key] = f.Operation
922 }
923 }
924 }
925 return held
926}
927
928// waits says why a family waits for a family the journal holds: it
929// shares a change or a branch with it, and writes built for it would race
930// that family's. "" is a family that shares neither.
931func waits(f *rebase.Family, journaled map[string]string) string {
932 for _, l := range f.Layers {
933 for _, key := range layerKeys(l.ID, l.Branch) {
934 if op, found := journaled[key]; found {
935 return fmt.Sprintf("%s is in a family of operation %s, which the journal still holds, so this family waits for it", l.Name, op)
936 }
937 }
938 }
939 return ""
940}
941
942// judge decides what a pass would do with one family. It judges requests
943// in the order given, which plan makes name order, so the family's
944// requests, reasons and notes come in that order too.
945func judge(f *rebase.Family, s *rebase.Snapshot, principal string, p *Plan, requests []Request, in Incoming) FamilyPlan {
946 fp := FamilyPlan{Reasons: []string{}, Notes: []string{}, Requests: []RequestPlan{}}
947 ready := false
948 for _, l := range f.Layers {
949 lp := LayerPlan{Name: l.Name, ID: l.ID, Branch: l.Branch, Head: l.Head, State: string(l.State())}
950 if l.Below != nil {
951 lp.Below = l.Below.Name
952 }
953 if l.State() == rebase.Ready {
954 ready = true
955 } else {
956 fp.Reasons = append(fp.Reasons, stateLine(l))
957 }
958 fp.Layers = append(fp.Layers, lp)
959 }
960 switch {
961 case !ready:
962 fp.Action = leave
963 return fp
964 case f.FastForwards():
965 fp.Action, fp.Reasons = current, []string{"it already descends from " + rebase.Target + "'s tip"}
966 return fp
967 }
968 if err := f.Check(); err != nil {
969 fp.Reasons = append(fp.Reasons, err.Error())
970 }
971
972 m := membersOf(f)
973 for _, r := range requests {
974 by, err := Relate(r, m, in)
975 if err != nil {
976 fp.Requests = append(fp.Requests, RequestPlan{Name: r.Name, Head: r.Head, By: []string{}, Why: err.Error()})
977 fp.Reasons = append(fp.Reasons, fmt.Sprintf("request %s: whether it is related cannot be determined: %v", r.Name, err))
978 continue
979 }
980 if by == nil {
981 continue
982 }
983 o, found := s.OutcomeOf(r.Name)
984 rp := RequestPlan{Name: r.Name, Head: r.Head, By: by}
985 if found {
986 rp.Decision = o.Decision
987 }
988 rp.Current, rp.Releases, rp.Why = Currency(o, found, r.Head, p.Tip, p.Evidence)
989 switch {
990 case !rp.Releases:
991 fp.Reasons = append(fp.Reasons, fmt.Sprintf("request %s might still land: %s", r.Name, rp.Why))
992 case o.Decision == "reject":
993 fp.Notes = append(fp.Notes, fmt.Sprintf("request %s was rejected at this head, tip and evidence", r.Name))
994 }
995 fp.Requests = append(fp.Requests, rp)
996 }
997
998 for i, l := range f.Layers {
999 if l.ID == "" || l.Record == nil {
1000 continue
1001 }
1002 cp := CapacityOf(l.Record, principal, p.Cap, nextSize(l.Name, l.Record, principal))
1003 fp.Layers[i].Capacity = cp
1004 fp.Reasons = append(fp.Reasons, cp.Over...)
1005 }
1006 fp.Action = restack
1007 if len(fp.Reasons) > 0 {
1008 fp.Action = hold
1009 }
1010 return fp
1011}
1012
1013func printPlan(w io.Writer, p *Plan) {
1014 fmt.Fprintf(w, "%s at %s, evidence %s, at most %d versions a change uploaded by the restacker's principal\n", p.Target, short(p.Tip), p.Evidence, p.Cap)
1015 if r := p.Recovery; r != nil {
1016 printRecovery(w, r)
1017 }
1018 if len(p.Families) == 0 {
1019 fmt.Fprintln(w, "no change to restack")
1020 }
1021 for _, f := range p.Families {
1022 fmt.Fprintf(w, "\n%s: %s\n", f.Layers[0].Name, f.Action)
1023 for _, l := range f.Layers {
1024 fmt.Fprintf(w, " %-24s %-10s %s", l.Name, l.State, short(l.Head))
1025 if l.Below != "" {
1026 fmt.Fprintf(w, " on %s", l.Below)
1027 }
1028 if c := l.Capacity; c != nil {
1029 fmt.Fprintf(w, "; %d/%d automatic, %d/%d versions, update %d/%d, %d/%d bytes",
1030 c.Uploads, c.Cap, c.Versions, c.MaxVersions, c.Seq, c.MaxSeq, c.Bytes, c.MaxBytes)
1031 }
1032 fmt.Fprintln(w)
1033 }
1034 for _, r := range f.Requests {
1035 fmt.Fprintf(w, " request %s at %s, by %s: %s\n", r.Name, short(r.Head), strings.Join(r.By, ", "), r.Why)
1036 }
1037 for _, why := range f.Reasons {
1038 fmt.Fprintf(w, " - %s\n", why)
1039 }
1040 for _, n := range f.Notes {
1041 fmt.Fprintf(w, " note: %s\n", n)
1042 }
1043 if f.Writes != nil {
1044 printWrites(w, f.Writes)
1045 }
1046 }
1047 printPublished(w, p)
1048}
1049
1050// printPublished prints what a write pass pushed, and the journal it
1051// leaves open, if it leaves one.
1052func printPublished(w io.Writer, p *Plan) {
1053 for _, a := range p.Actions {
1054 what := a.Write
1055 if a.ID != "" {
1056 what += " " + a.ID
1057 }
1058 fmt.Fprintf(w, "operation %s, family %d: %s: %s", a.Operation, a.Family, what, a.Result)
1059 if a.Commit != "" {
1060 fmt.Fprintf(w, " %s", short(a.Commit))
1061 }
1062 if a.Why != "" {
1063 fmt.Fprintf(w, ": %s", a.Why)
1064 }
1065 fmt.Fprintln(w)
1066 }
1067 if r := p.Pending; r != nil {
1068 fmt.Fprintln(w, "the journal stays open; any family that shares a change or branch with an open family waits:")
1069 for _, d := range r.Decisions {
1070 if d.settled() {
1071 continue
1072 }
1073 what := d.Write
1074 if d.ID != "" {
1075 what += " " + d.ID
1076 }
1077 fmt.Fprintf(w, " operation %s, family %d %s: %s: %s\n", d.Operation, d.Family, what, d.Action, d.Why)
1078 }
1079 }
1080}
1081
1082// printWrites prints what a pass would push for a family.
1083func printWrites(w io.Writer, ws *Writes) {
1084 fmt.Fprintf(w, " would write, as %s:\n", ws.Result)
1085 for _, b := range ws.Branches {
1086 fmt.Fprintf(w, " push %s %s -> %s\n", b.Branch, short(b.Old), short(b.New))
1087 }
1088 for _, v := range ws.Versions {
1089 fmt.Fprintf(w, " add %s v%d at %s: record %s, leased on %s\n", v.ID, v.Version, short(v.Head), short(v.Record), short(v.Lease))
1090 }
1091 for _, r := range ws.Reports {
1092 switch {
1093 case r.Error != "":
1094 fmt.Fprintf(w, " report %s: none fits: %s\n", r.ID, r.Error)
1095 case r.Unchanged:
1096 fmt.Fprintf(w, " report %s %s: not written, as the current report says the same\n", r.ID, r.Result)
1097 default:
1098 lease := "none"
1099 if r.Lease != "" {
1100 lease = short(r.Lease)
1101 }
1102 fmt.Fprintf(w, " report %s %s: %s, replacing %s\n", r.ID, r.Result, short(r.Commit), lease)
1103 }
1104 if len(r.Omitted) > 0 {
1105 fmt.Fprintf(w, " leaves out %s\n", strings.Join(r.Omitted, ", "))
1106 }
1107 }
1108}
1109
1110// printRecovery prints what recovery decided of the journal.
1111func printRecovery(w io.Writer, r *Recovery) {
1112 if r.Error != "" {
1113 fmt.Fprintf(w, "recovery: %s\n", r.Error)
1114 return
1115 }
1116 state := "settled"
1117 if !r.Settled {
1118 state = "not settled"
1119 }
1120 fmt.Fprintf(w, "recovery: %s, %s\n", r.Journal, state)
1121 for _, d := range r.Decisions {
1122 what := d.Write
1123 if d.ID != "" {
1124 what += " " + d.ID
1125 }
1126 action := d.Action
1127 switch {
1128 case d.Terminal:
1129 action += " (terminal)"
1130 case d.Final:
1131 action += " (final)"
1132 }
1133 fmt.Fprintf(w, " operation %s, family %d %s: %s: %s\n", d.Operation, d.Family, what, action, d.Why)
1134 }
1135}