gunk-dev/the-valley

main.go

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