gunk-dev/the-valley

main.go

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