gunk-dev/the-valley

main.go

source28abc5737165main's published tip history
39.7 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 and cue a pass runs is killed, with what it
49// 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 What a pass verified is remembered in valley/transfers
124 under the user's cache directory (XDG_CACHE_HOME,
125 else ~/.cache)
126 --integrator-name N the name the integrator signs under
127 --signer-projects F the signer projects file the integrator reads; while
128 it names the --integrator-name, no landing is proved
129 by integrator evidence. A file that does not read
130 stops the pass
131 --instance-repo URL the repository carrying the group's floor
132 --instance-ref REF the ref whose tip carries the floor, a full ref name
133 read by that exact name (refs/heads/main)
134 --instance-policy DIR the floor's directory in that tip (policy/instance)
135 --instance DIR a materialized floor, for a host that serves none
136 --project-policy DIR the project layer, in the target tip (policy/project)
137 --schema FILE the verification schema (VALLEY_VERIFICATION_SCHEMA)
138 --json print each pass as JSON
139`
140
141func main() {
142 if len(os.Args) < 2 {
143 say(os.Stderr, usage)
144 os.Exit(2)
145 }
146 switch os.Args[1] {
147 case "once", "run":
148 // An interrupt or a stop ends the pass as its timeout does, killing
149 // what it runs, and then ends the command, which lets go of the lock
150 // on its state. It ends run between passes too.
151 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
152 command := once
153 if os.Args[1] == "run" {
154 command = loop
155 }
156 err := command(ctx, os.Args[2:], os.Stdout, os.Stderr)
157 stop()
158 if err != nil {
159 say(os.Stderr, fmt.Sprintf("valley-restacker: %v\n", err))
160 os.Exit(1)
161 }
162 case "help", "-h", "--help":
163 say(os.Stdout, usage)
164 default:
165 say(os.Stderr, fmt.Sprintf("valley-restacker: unknown command %q\n\n%s", os.Args[1], usage))
166 os.Exit(2)
167 }
168}
169
170// sayBound is the longest the process waits to write a message of its
171// own, such as the error it ends with.
172const sayBound = 5 * time.Second
173
174// say writes a message of the process's own, and gives up after sayBound.
175// A stderr nobody reads would otherwise hold the process after its pass
176// has ended and let go of its lock. The write given up on ends with the
177// process.
178func say(w io.Writer, message string) {
179 ctx, cancel := context.WithTimeout(context.Background(), sayBound)
180 defer cancel()
181 _ = writeOut(ctx, w, []byte(message))
182}
183
184// config is a pass's configuration, from flags.
185type config struct {
186 repo, target, state, principal string
187 commitName, commitEmail string
188 timeout, interval time.Duration
189 verify rebase.Verifier
190 floor composed.Floor
191 instanceRepo, projectPolicy string
192 schema, cue string
193 json bool
194}
195
196// defaultEmail is the email the restacker commits under unless
197// --commit-email names another. The .invalid domain is reserved, so the
198// address names no mailbox, as the integrator's does not.
199const defaultEmail = "restacker@the-valley.invalid"
200
201// maxBackoff is the longest run waits after a pass that failed.
202const maxBackoff = 5 * time.Minute
203
204// parse reads a command's flags into a configuration. --report-only is
205// once's, and --interval is run's.
206func parse(name string, args []string, errOut io.Writer) (c config, reportOnly bool, err error) {
207 fs := flag.NewFlagSet("valley-restacker "+name, flag.ContinueOnError)
208 fs.SetOutput(io.Discard)
209 fs.Usage = func() { say(errOut, usage) }
210 var only *bool
211 if name == "once" {
212 only = fs.Bool("report-only", false, "")
213 } else {
214 fs.DurationVar(&c.interval, "interval", 15*time.Second, "")
215 }
216 fs.StringVar(&c.repo, "repo", "", "")
217 fs.StringVar(&c.target, "target", rebase.Target, "")
218 fs.StringVar(&c.state, "state", "", "")
219 fs.StringVar(&c.principal, "principal", "", "")
220 fs.StringVar(&c.commitName, "commit-name", "", "")
221 fs.StringVar(&c.commitEmail, "commit-email", defaultEmail, "")
222 fs.DurationVar(&c.timeout, "timeout", 10*time.Minute, "")
223 fs.StringVar(&c.verify.Keys, "known-signers", "", "")
224 fs.StringVar(&c.verify.Signer, "integrator-name", "", "")
225 signerProjects := fs.String("signer-projects", "", "")
226 fs.StringVar(&c.instanceRepo, "instance-repo", "", "")
227 fs.StringVar(&c.floor.Ref, "instance-ref", "refs/heads/main", "")
228 fs.StringVar(&c.floor.Dir, "instance-policy", "policy/instance", "")
229 fs.StringVar(&c.floor.Path, "instance", "", "")
230 fs.StringVar(&c.projectPolicy, "project-policy", "policy/project", "")
231 fs.StringVar(&c.schema, "schema", os.Getenv("VALLEY_VERIFICATION_SCHEMA"), "")
232 fs.BoolVar(&c.json, "json", false, "")
233 if err := fs.Parse(args); err != nil {
234 return c, false, err
235 }
236 if only != nil {
237 reportOnly = *only
238 }
239 switch {
240 case fs.NArg() > 0:
241 return c, false, fmt.Errorf("unexpected argument %q", fs.Arg(0))
242 case c.target != rebase.Target:
243 return c, false, fmt.Errorf("--target %s: a change may name only %s as its target", c.target, rebase.Target)
244 case name == "run" && c.interval <= 0:
245 return c, false, fmt.Errorf("--interval %v: run waits some time between passes", c.interval)
246 }
247 for _, f := range []struct{ flag, value string }{
248 {"--repo", c.repo}, {"--state", c.state}, {"--principal", c.principal}, {"--schema", c.schema},
249 } {
250 if f.value == "" {
251 return c, false, fmt.Errorf("%s is required", f.flag)
252 }
253 }
254 if !change.ValidPrincipal(c.principal) {
255 return c, false, fmt.Errorf("--principal %q is not a principal", c.principal)
256 }
257 if c.commitName == "" {
258 c.commitName = c.principal
259 }
260 if err := checkIdentity(c.commitName, c.commitEmail); err != nil {
261 return c, false, err
262 }
263 if c.timeout <= 0 {
264 return c, false, fmt.Errorf("--timeout %v: a pass needs some time to run", c.timeout)
265 }
266 // The floor comes from the instance repository's tip, or from a
267 // directory on disk, and never from both, as for the integrator.
268 if (c.instanceRepo == "") == (c.floor.Path == "") {
269 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")
270 }
271 if c.instanceRepo != "" && !strings.HasPrefix(c.floor.Ref, "refs/") {
272 return c, false, fmt.Errorf("--instance-ref %s is not a full ref name; name it whole, as refs/heads/main", c.floor.Ref)
273 }
274 c.verify.Cache = rebase.CacheDir()
275 if *signerProjects != "" {
276 data, err := os.ReadFile(*signerProjects)
277 if err != nil {
278 return c, false, fmt.Errorf("--signer-projects: %w", err)
279 }
280 if c.verify.SignerProjects, err = note.ParseSignerProjects(data); err != nil {
281 return c, false, fmt.Errorf("--signer-projects %s does not read: %w", *signerProjects, err)
282 }
283 }
284 if c.cue, err = exec.LookPath("cue"); err != nil {
285 return c, false, errors.New("cue is not on the path; the restacker composes the policy with it")
286 }
287 return c, reportOnly, nil
288}
289
290// once is one pass, a write pass unless --report-only says otherwise.
291func once(ctx context.Context, args []string, out, errOut io.Writer) error {
292 // What the pass runs inherits no git variable that points git
293 // elsewhere or gives it configuration (passes).
294 controlEnvironment()
295 c, reportOnly, err := parse("once", args, errOut)
296 if err != nil {
297 return err
298 }
299 release, err := lockState(c.state)
300 if err != nil {
301 return err
302 }
303 defer release()
304 if err := bindState(c.state, c.binding()); err != nil {
305 return err
306 }
307 _, err = pass(ctx, c, reportOnly, out, errOut, false)
308 return err
309}
310
311// loop is run: a write pass at once, and another every interval after
312// the last one ended, until ctx is done. It holds the lock on its state
313// for as long as it runs, past a pass that ends at its timeout. A pass
314// that fails is said, and the wait before the next doubles, up to
315// maxBackoff, until a pass succeeds. A pass that tried no write and
316// leaves no journal open prints nothing.
317func loop(ctx context.Context, args []string, out, errOut io.Writer) error {
318 controlEnvironment()
319 c, _, err := parse("run", args, errOut)
320 if err != nil {
321 return err
322 }
323 release, err := lockState(c.state)
324 if err != nil {
325 return err
326 }
327 defer release()
328 if err := bindState(c.state, c.binding()); err != nil {
329 return err
330 }
331 failures := 0
332 for {
333 _, err := pass(ctx, c, false, out, errOut, true)
334 if ctx.Err() != nil {
335 return nil
336 }
337 wait := c.interval
338 if err != nil {
339 failures++
340 wait = backoff(c.interval, failures)
341 say(errOut, fmt.Sprintf("valley-restacker: the pass failed, and the next starts in %v: %v\n", wait, err))
342 } else {
343 failures = 0
344 }
345 select {
346 case <-ctx.Done():
347 return nil
348 case <-time.After(wait):
349 }
350 }
351}
352
353// backoff is how long run waits after the given number of passes in a row
354// have failed: twice as long for each, from the interval, up to
355// maxBackoff.
356func backoff(interval time.Duration, failures int) time.Duration {
357 wait := interval
358 for i := 0; i < failures && wait < maxBackoff; i++ {
359 wait *= 2
360 }
361 return min(wait, maxBackoff)
362}
363
364// pass runs one pass under its timeout and prints it: the plan and each
365// write it tried, or, when quiet, only the writes it tried and a journal
366// it leaves open. A write it tried may have been refused, or not pushed
367// at all.
368func pass(ctx context.Context, c config, reportOnly bool, out, errOut io.Writer, quiet bool) (*Plan, error) {
369 ctx, cancel := context.WithTimeout(ctx, c.timeout)
370 defer cancel()
371 g, err := scratchRepo(ctx, c)
372 if err != nil {
373 return nil, timedOut(ctx, c, err)
374 }
375 g.Stderr = errOut
376 var p *Plan
377 if reportOnly {
378 p, err = planOnce(ctx, g, c)
379 } else {
380 p, err = writeOnce(ctx, g, c)
381 }
382 if err != nil {
383 return p, timedOut(ctx, c, err)
384 }
385 if quiet && len(p.Actions) == 0 && p.Pending == nil {
386 return p, nil
387 }
388 var text bytes.Buffer
389 switch {
390 case c.json:
391 enc := json.NewEncoder(&text)
392 enc.SetIndent("", " ")
393 if err := enc.Encode(p); err != nil {
394 return p, err
395 }
396 case quiet:
397 printPublished(&text, p)
398 default:
399 printPlan(&text, p)
400 }
401 if err := writeOut(ctx, out, text.Bytes()); err != nil {
402 return p, timedOut(ctx, c, err)
403 }
404 return p, nil
405}
406
407// writeOut writes data to out, and gives up once ctx is done. A reader
408// that stops reading holds the write, and would otherwise hold the pass,
409// and the lock on its state, past its --timeout. The write given up on
410// ends with the process.
411func writeOut(ctx context.Context, out io.Writer, data []byte) error {
412 done := make(chan error, 1)
413 go func() {
414 _, err := out.Write(data)
415 done <- err
416 }()
417 select {
418 case err := <-done:
419 return err
420 case <-ctx.Done():
421 return fmt.Errorf("the plan was not written: %w", ctx.Err())
422 }
423}
424
425// timedOut says so when a pass failed because it ran past its timeout.
426func timedOut(ctx context.Context, c config, err error) error {
427 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
428 return fmt.Errorf("the pass ran past its --timeout of %v: %w", c.timeout, err)
429 }
430 return err
431}
432
433// checkIdentity refuses a name or an email git cannot commit under: an
434// empty one, or one with a control character or an angle bracket, which
435// would end the name or the email early in a commit's header.
436func checkIdentity(name, email string) error {
437 for _, f := range []struct{ flag, value string }{{"--commit-name", name}, {"--commit-email", email}} {
438 if strings.TrimSpace(f.value) == "" || strings.ContainsAny(f.value, "<>") ||
439 strings.ContainsFunc(f.value, func(r rune) bool { return r < 0x20 || r == 0x7f }) {
440 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)
441 }
442 }
443 return nil
444}
445
446// What a pass passes on to the programs it runs. A git variable can point
447// git at another repository (GIT_DIR, GIT_WORK_TREE, GIT_COMMON_DIR,
448// GIT_INDEX_FILE, GIT_OBJECT_DIRECTORY, GIT_ALTERNATE_OBJECT_DIRECTORIES,
449// GIT_NAMESPACE, GIT_GRAFT_FILE, GIT_REPLACE_REF_BASE), at other programs
450// (GIT_EXEC_PATH, GIT_TEMPLATE_DIR), at other attributes (GIT_ATTR_SOURCE)
451// or at another format (GIT_DEFAULT_HASH). It can inject configuration
452// that beats the repository's own: GIT_CONFIG_COUNT with GIT_CONFIG_KEY_<n>
453// and GIT_CONFIG_VALUE_<n>, and GIT_CONFIG_PARAMETERS, so an inherited
454// author.name would beat user.name and an inherited core.hooksPath would
455// turn hooks back on. The other GIT_CONFIG* variables name configuration
456// files. And GIT_AUTHOR_*, GIT_COMMITTER_* and EMAIL give an identity
457// ahead of the configuration. So a pass passes on no GIT_* variable but
458// the ones that say how to reach origin over ssh, and no EMAIL. It drops
459// them from its own environment as it starts (controlEnvironment), so
460// cue and the git that composes the policy run without them too.
461var passedOn = map[string]bool{"GIT_SSH": true, "GIT_SSH_COMMAND": true, "GIT_SSH_VARIANT": true}
462
463// passes reports whether a pass passes on the environment variable named.
464func passes(name string) bool {
465 switch {
466 case name == "EMAIL":
467 return false
468 case strings.HasPrefix(name, "GIT_"):
469 return passedOn[name]
470 }
471 return true
472}
473
474// gitSettings are what a pass sets for every git it runs, scratch
475// repository or not: no system or user configuration, no system
476// attributes, and no question asked at a terminal.
477var gitSettings = [][2]string{
478 {"GIT_CONFIG_NOSYSTEM", "1"},
479 {"GIT_CONFIG_GLOBAL", "/dev/null"},
480 {"GIT_ATTR_NOSYSTEM", "1"},
481 {"GIT_TERMINAL_PROMPT", "0"},
482}
483
484// controlEnvironment leaves the process's own environment holding only
485// what a pass passes on, and gitSettings.
486func controlEnvironment() {
487 for _, kv := range os.Environ() {
488 if name, _, _ := strings.Cut(kv, "="); !passes(name) {
489 os.Unsetenv(name)
490 }
491 }
492 for _, kv := range gitSettings {
493 os.Setenv(kv[0], kv[1])
494 }
495}
496
497// scratchRepo makes, or reuses, the repository a pass reads origin into,
498// and returns git run in it with hooks and configured filters off,
499// committing under the restacker's identity. git there reads no
500// configuration but the repository's, and is given its author and
501// committer explicitly. A commit it rebases keeps its own author: a
502// rebase takes the author from the commit it picks. git there is
503// unattended: it never asks a question, and every git it runs is killed
504// whole once ctx is done.
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 captured families when neither's head
862// descends from the other's and no shared lower layer joins them, and
863// the journal takes no two families that share a branch, since their
864// writes would race. So neither is built while both name it, and every
865// other family is planned as usual.
866func overlapping(p *Plan) {
867 type holder struct {
868 family int
869 name string
870 }
871 whose := map[string][]holder{} // the families that would be written, by each change and branch
872 for i, fp := range p.Families {
873 if fp.Action != restack && fp.Action != hold {
874 continue
875 }
876 for _, l := range p.families[i].Layers {
877 for _, key := range layerKeys(l.ID, l.Branch) {
878 if hs := whose[key]; len(hs) == 0 || hs[len(hs)-1].family != i {
879 whose[key] = append(whose[key], holder{i, l.Name})
880 }
881 }
882 }
883 }
884 for i := range p.Families {
885 fp := &p.Families[i]
886 if fp.Action != restack && fp.Action != hold {
887 continue
888 }
889 why := ""
890 for _, l := range p.families[i].Layers {
891 for _, key := range layerKeys(l.ID, l.Branch) {
892 for _, h := range whose[key] {
893 if h.family != i && why == "" {
894 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)
895 }
896 }
897 }
898 }
899 if why != "" {
900 fp.Action, fp.Reasons = wait, []string{why}
901 }
902 }
903}
904
905// journaledLayers is the operation of each family the journal holds, by
906// each of the family's changes and branches (layerKeys).
907func journaledLayers(j *Journal) map[string]string {
908 held := map[string]string{}
909 if j == nil {
910 return held
911 }
912 for _, f := range j.Families {
913 for _, l := range f.Observed.Layers {
914 for _, key := range layerKeys(l.ID, l.Branch) {
915 held[key] = f.Operation
916 }
917 }
918 }
919 return held
920}
921
922// waits says why a family waits for a family the journal holds: it
923// shares a change or a branch with it, and writes built for it would race
924// that family's. "" is a family that shares neither.
925func waits(f *rebase.Family, journaled map[string]string) string {
926 for _, l := range f.Layers {
927 for _, key := range layerKeys(l.ID, l.Branch) {
928 if op, found := journaled[key]; found {
929 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)
930 }
931 }
932 }
933 return ""
934}
935
936// judge decides what a pass would do with one family. It judges requests
937// in the order given, which plan makes name order, so the family's
938// requests, reasons and notes come in that order too.
939func judge(f *rebase.Family, s *rebase.Snapshot, principal string, p *Plan, requests []Request, in Incoming) FamilyPlan {
940 fp := FamilyPlan{Reasons: []string{}, Notes: []string{}, Requests: []RequestPlan{}}
941 ready := false
942 for _, l := range f.Layers {
943 lp := LayerPlan{Name: l.Name, ID: l.ID, Branch: l.Branch, Head: l.Head, State: string(l.State())}
944 if l.Below != nil {
945 lp.Below = l.Below.Name
946 }
947 if l.State() == rebase.Ready {
948 ready = true
949 } else {
950 fp.Reasons = append(fp.Reasons, stateLine(l))
951 }
952 fp.Layers = append(fp.Layers, lp)
953 }
954 switch {
955 case !ready:
956 fp.Action = leave
957 return fp
958 case f.FastForwards():
959 fp.Action, fp.Reasons = current, []string{"it already descends from " + rebase.Target + "'s tip"}
960 return fp
961 }
962 if err := f.Check(); err != nil {
963 fp.Reasons = append(fp.Reasons, err.Error())
964 }
965
966 m := membersOf(f)
967 for _, r := range requests {
968 by, err := Relate(r, m, in)
969 if err != nil {
970 fp.Requests = append(fp.Requests, RequestPlan{Name: r.Name, Head: r.Head, By: []string{}, Why: err.Error()})
971 fp.Reasons = append(fp.Reasons, fmt.Sprintf("request %s: whether it is related cannot be determined: %v", r.Name, err))
972 continue
973 }
974 if by == nil {
975 continue
976 }
977 o, found := s.OutcomeOf(r.Name)
978 rp := RequestPlan{Name: r.Name, Head: r.Head, By: by}
979 if found {
980 rp.Decision = o.Decision
981 }
982 rp.Current, rp.Releases, rp.Why = Currency(o, found, r.Head, p.Tip, p.Evidence)
983 switch {
984 case !rp.Releases:
985 fp.Reasons = append(fp.Reasons, fmt.Sprintf("request %s might still land: %s", r.Name, rp.Why))
986 case o.Decision == "reject":
987 fp.Notes = append(fp.Notes, fmt.Sprintf("request %s was rejected at this head, tip and evidence", r.Name))
988 }
989 fp.Requests = append(fp.Requests, rp)
990 }
991
992 for i, l := range f.Layers {
993 if l.ID == "" || l.Record == nil {
994 continue
995 }
996 cp := CapacityOf(l.Record, principal, p.Cap, nextSize(l.Name, l.Record, principal))
997 fp.Layers[i].Capacity = cp
998 fp.Reasons = append(fp.Reasons, cp.Over...)
999 }
1000 fp.Action = restack
1001 if len(fp.Reasons) > 0 {
1002 fp.Action = hold
1003 }
1004 return fp
1005}
1006
1007func printPlan(w io.Writer, p *Plan) {
1008 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)
1009 if r := p.Recovery; r != nil {
1010 printRecovery(w, r)
1011 }
1012 if len(p.Families) == 0 {
1013 fmt.Fprintln(w, "no change to restack")
1014 }
1015 for _, f := range p.Families {
1016 fmt.Fprintf(w, "\n%s: %s\n", f.Layers[0].Name, f.Action)
1017 for _, l := range f.Layers {
1018 fmt.Fprintf(w, " %-24s %-10s %s", l.Name, l.State, short(l.Head))
1019 if l.Below != "" {
1020 fmt.Fprintf(w, " on %s", l.Below)
1021 }
1022 if c := l.Capacity; c != nil {
1023 fmt.Fprintf(w, "; %d/%d automatic, %d/%d versions, update %d/%d, %d/%d bytes",
1024 c.Uploads, c.Cap, c.Versions, c.MaxVersions, c.Seq, c.MaxSeq, c.Bytes, c.MaxBytes)
1025 }
1026 fmt.Fprintln(w)
1027 }
1028 for _, r := range f.Requests {
1029 fmt.Fprintf(w, " request %s at %s, by %s: %s\n", r.Name, short(r.Head), strings.Join(r.By, ", "), r.Why)
1030 }
1031 for _, why := range f.Reasons {
1032 fmt.Fprintf(w, " - %s\n", why)
1033 }
1034 for _, n := range f.Notes {
1035 fmt.Fprintf(w, " note: %s\n", n)
1036 }
1037 if f.Writes != nil {
1038 printWrites(w, f.Writes)
1039 }
1040 }
1041 printPublished(w, p)
1042}
1043
1044// printPublished prints what a write pass pushed, and the journal it
1045// leaves open, if it leaves one.
1046func printPublished(w io.Writer, p *Plan) {
1047 for _, a := range p.Actions {
1048 what := a.Write
1049 if a.ID != "" {
1050 what += " " + a.ID
1051 }
1052 fmt.Fprintf(w, "operation %s, family %d: %s: %s", a.Operation, a.Family, what, a.Result)
1053 if a.Commit != "" {
1054 fmt.Fprintf(w, " %s", short(a.Commit))
1055 }
1056 if a.Why != "" {
1057 fmt.Fprintf(w, ": %s", a.Why)
1058 }
1059 fmt.Fprintln(w)
1060 }
1061 if r := p.Pending; r != nil {
1062 fmt.Fprintln(w, "the journal stays open; any family that shares a change or branch with an open family waits:")
1063 for _, d := range r.Decisions {
1064 if d.settled() {
1065 continue
1066 }
1067 what := d.Write
1068 if d.ID != "" {
1069 what += " " + d.ID
1070 }
1071 fmt.Fprintf(w, " operation %s, family %d %s: %s: %s\n", d.Operation, d.Family, what, d.Action, d.Why)
1072 }
1073 }
1074}
1075
1076// printWrites prints what a pass would push for a family.
1077func printWrites(w io.Writer, ws *Writes) {
1078 fmt.Fprintf(w, " would write, as %s:\n", ws.Result)
1079 for _, b := range ws.Branches {
1080 fmt.Fprintf(w, " push %s %s -> %s\n", b.Branch, short(b.Old), short(b.New))
1081 }
1082 for _, v := range ws.Versions {
1083 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))
1084 }
1085 for _, r := range ws.Reports {
1086 switch {
1087 case r.Error != "":
1088 fmt.Fprintf(w, " report %s: none fits: %s\n", r.ID, r.Error)
1089 case r.Unchanged:
1090 fmt.Fprintf(w, " report %s %s: not written, as the current report says the same\n", r.ID, r.Result)
1091 default:
1092 lease := "none"
1093 if r.Lease != "" {
1094 lease = short(r.Lease)
1095 }
1096 fmt.Fprintf(w, " report %s %s: %s, replacing %s\n", r.ID, r.Result, short(r.Commit), lease)
1097 }
1098 if len(r.Omitted) > 0 {
1099 fmt.Fprintf(w, " leaves out %s\n", strings.Join(r.Omitted, ", "))
1100 }
1101 }
1102}
1103
1104// printRecovery prints what recovery decided of the journal.
1105func printRecovery(w io.Writer, r *Recovery) {
1106 if r.Error != "" {
1107 fmt.Fprintf(w, "recovery: %s\n", r.Error)
1108 return
1109 }
1110 state := "settled"
1111 if !r.Settled {
1112 state = "not settled"
1113 }
1114 fmt.Fprintf(w, "recovery: %s, %s\n", r.Journal, state)
1115 for _, d := range r.Decisions {
1116 what := d.Write
1117 if d.ID != "" {
1118 what += " " + d.ID
1119 }
1120 action := d.Action
1121 switch {
1122 case d.Terminal:
1123 action += " (terminal)"
1124 case d.Final:
1125 action += " (final)"
1126 }
1127 fmt.Fprintf(w, " operation %s, family %d %s: %s: %s\n", d.Operation, d.Family, what, action, d.Why)
1128 }
1129}