gunk-dev/the-valley

main.go

source5f0229dc1066main's published tip history
18.4 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// This slice is the planner: `valley-restacker once --report-only` reads
6// one snapshot of origin and says which families it would restack, which
7// it would hold and why, and what capacity allows. It pushes nothing.
8//
9// It talks to origin only over git, as a client, from a scratch repository
10// under its state directory. Hooks and external filters are off there:
11// the scratch repository's hooks path is /dev/null, and git reads neither
12// the system's nor the user's configuration, so no filter driver is
13// defined. A service that needs ssh settings passes them in
14// GIT_SSH_COMMAND. The scratch repository commits under the identity its
15// flags give, and never under one inherited from the environment.
16//
17// A pass holds a lock on its state directory from start to end, so a
18// second pass on the same directory fails while one runs. The directory
19// belongs to one repository, target and principal, the first a pass used
20// it for, and a pass for any other is refused. Every git, cue and attest a
21// pass runs is killed, with what it started, once the pass's --timeout
22// passes.
23package main
24
25import (
26 "context"
27 "encoding/json"
28 "errors"
29 "flag"
30 "fmt"
31 "io"
32 "os"
33 "os/exec"
34 "os/signal"
35 "path/filepath"
36 "strings"
37 "syscall"
38 "time"
39
40 "the-valley/change"
41 "the-valley/composed"
42 "the-valley/rebase"
43)
44
45const usage = `valley-restacker: rebase ready changes onto main when main moves.
46
47usage: valley-restacker once --report-only [flags]
48
49 once --report-only
50 read one snapshot of origin and print what a pass would do: each
51 family, restack or hold with the reason, its capacity, and the
52 integration requests it considered. Pushes nothing.
53
54flags:
55 --repo URL origin: the repository the restacker serves (required)
56 --target NAME the target changes are rebased onto (only main)
57 --state DIR where the scratch repository lives (required). A pass
58 locks it, and it belongs to the first repository,
59 target and principal a pass used it for
60 --principal NAME the principal the restacker pushes as (required)
61 --commit-name NAME the name the restacker commits under (default: the
62 principal)
63 --commit-email EMAIL the email it commits under
64 (default: restacker@the-valley.invalid)
65 --timeout DURATION the longest a pass may run; what it runs is killed
66 then (default 10m)
67 --known-signers FILE verifier keys, for landings proved by integrator evidence
68 --integrator-name N the name the integrator signs under
69 --attest PATH the attest helper that checks a note (default: attest on PATH)
70 --instance-repo URL the repository carrying the group's floor
71 --instance-ref REF the ref whose tip carries the floor (refs/heads/main)
72 --instance-policy DIR the floor's directory in that tip (policy/instance)
73 --instance DIR a materialized floor, for a host that serves none
74 --project-policy DIR the project layer, in the target tip (policy/project)
75 --schema FILE the verification schema (VALLEY_VERIFICATION_SCHEMA)
76 --json print the plan as JSON
77`
78
79func main() {
80 if len(os.Args) < 2 {
81 fmt.Fprint(os.Stderr, usage)
82 os.Exit(2)
83 }
84 switch os.Args[1] {
85 case "once":
86 // An interrupt or a stop ends the pass as its timeout does: what it
87 // runs is killed, and the lock on its state is let go.
88 ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
89 err := once(ctx, os.Args[2:], os.Stdout)
90 stop()
91 if err != nil {
92 fmt.Fprintf(os.Stderr, "valley-restacker: %v\n", err)
93 os.Exit(1)
94 }
95 case "help", "-h", "--help":
96 fmt.Print(usage)
97 default:
98 fmt.Fprintf(os.Stderr, "valley-restacker: unknown command %q\n\n%s", os.Args[1], usage)
99 os.Exit(2)
100 }
101}
102
103// config is a pass's configuration, from flags.
104type config struct {
105 repo, target, state, principal string
106 commitName, commitEmail string
107 timeout time.Duration
108 verify rebase.Verifier
109 floor composed.Floor
110 instanceRepo, projectPolicy string
111 schema, cue string
112 json bool
113}
114
115// defaultEmail is the email the restacker commits under unless
116// --commit-email names another. The .invalid domain is reserved, so the
117// address names no mailbox, as the integrator's does not.
118const defaultEmail = "restacker@the-valley.invalid"
119
120func once(ctx context.Context, args []string, out io.Writer) error {
121 fs := flag.NewFlagSet("valley-restacker once", flag.ContinueOnError)
122 fs.Usage = func() { fmt.Fprint(os.Stderr, usage) }
123 var c config
124 reportOnly := fs.Bool("report-only", false, "")
125 fs.StringVar(&c.repo, "repo", "", "")
126 fs.StringVar(&c.target, "target", rebase.Target, "")
127 fs.StringVar(&c.state, "state", "", "")
128 fs.StringVar(&c.principal, "principal", "", "")
129 fs.StringVar(&c.commitName, "commit-name", "", "")
130 fs.StringVar(&c.commitEmail, "commit-email", defaultEmail, "")
131 fs.DurationVar(&c.timeout, "timeout", 10*time.Minute, "")
132 fs.StringVar(&c.verify.Keys, "known-signers", "", "")
133 fs.StringVar(&c.verify.Signer, "integrator-name", "", "")
134 fs.StringVar(&c.verify.Attest, "attest", "", "")
135 fs.StringVar(&c.instanceRepo, "instance-repo", "", "")
136 fs.StringVar(&c.floor.Ref, "instance-ref", "refs/heads/main", "")
137 fs.StringVar(&c.floor.Dir, "instance-policy", "policy/instance", "")
138 fs.StringVar(&c.floor.Path, "instance", "", "")
139 fs.StringVar(&c.projectPolicy, "project-policy", "policy/project", "")
140 fs.StringVar(&c.schema, "schema", os.Getenv("VALLEY_VERIFICATION_SCHEMA"), "")
141 fs.BoolVar(&c.json, "json", false, "")
142 if err := fs.Parse(args); err != nil {
143 return err
144 }
145 switch {
146 case fs.NArg() > 0:
147 return fmt.Errorf("unexpected argument %q", fs.Arg(0))
148 case !*reportOnly:
149 return errors.New("once needs --report-only: this restacker plans and does not yet push")
150 case c.target != rebase.Target:
151 return fmt.Errorf("--target %s: a change may name only %s as its target", c.target, rebase.Target)
152 }
153 for _, f := range []struct{ flag, value string }{
154 {"--repo", c.repo}, {"--state", c.state}, {"--principal", c.principal}, {"--schema", c.schema},
155 } {
156 if f.value == "" {
157 return fmt.Errorf("%s is required", f.flag)
158 }
159 }
160 if !change.ValidPrincipal(c.principal) {
161 return fmt.Errorf("--principal %q is not a principal", c.principal)
162 }
163 if c.commitName == "" {
164 c.commitName = c.principal
165 }
166 if err := checkIdentity(c.commitName, c.commitEmail); err != nil {
167 return err
168 }
169 if c.timeout <= 0 {
170 return fmt.Errorf("--timeout %v: a pass needs some time to run", c.timeout)
171 }
172 // The floor comes from the instance repository's tip, or from a
173 // directory on disk, and never from both, as for the integrator.
174 if (c.instanceRepo == "") == (c.floor.Path == "") {
175 return 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")
176 }
177 if c.verify.Attest == "" {
178 c.verify.Attest, _ = exec.LookPath("attest")
179 }
180 var err error
181 if c.cue, err = exec.LookPath("cue"); err != nil {
182 return errors.New("cue is not on the path; the restacker composes the policy with it")
183 }
184 release, err := lockState(c.state)
185 if err != nil {
186 return err
187 }
188 defer release()
189 if err := bindState(c.state, binding{Repository: c.repo, Target: c.target, Principal: c.principal}); err != nil {
190 return err
191 }
192 ctx, cancel := context.WithTimeout(ctx, c.timeout)
193 defer cancel()
194 g, err := scratchRepo(ctx, c)
195 if err != nil {
196 return timedOut(ctx, c, err)
197 }
198 p, err := planOnce(ctx, g, c)
199 if err != nil {
200 return timedOut(ctx, c, err)
201 }
202 if c.json {
203 enc := json.NewEncoder(out)
204 enc.SetIndent("", " ")
205 return enc.Encode(p)
206 }
207 printPlan(out, p)
208 return nil
209}
210
211// timedOut says so when a pass failed because it ran past its timeout.
212func timedOut(ctx context.Context, c config, err error) error {
213 if errors.Is(ctx.Err(), context.DeadlineExceeded) {
214 return fmt.Errorf("the pass ran past its --timeout of %v: %w", c.timeout, err)
215 }
216 return err
217}
218
219// checkIdentity refuses a name or an email git cannot commit under: an
220// empty one, or one with a control character or an angle bracket, which
221// would end the name or the email early in a commit's header.
222func checkIdentity(name, email string) error {
223 for _, f := range []struct{ flag, value string }{{"--commit-name", name}, {"--commit-email", email}} {
224 if strings.TrimSpace(f.value) == "" || strings.ContainsAny(f.value, "<>") ||
225 strings.ContainsFunc(f.value, func(r rune) bool { return r < 0x20 || r == 0x7f }) {
226 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)
227 }
228 }
229 return nil
230}
231
232// identityVariables are the environment variables git reads an author or a
233// committer from ahead of its configuration. The scratch repository's git
234// never inherits them, so the identity its flags give is the one it
235// commits under.
236var identityVariables = map[string]bool{
237 "GIT_AUTHOR_NAME": true, "GIT_AUTHOR_EMAIL": true, "GIT_AUTHOR_DATE": true,
238 "GIT_COMMITTER_NAME": true, "GIT_COMMITTER_EMAIL": true, "GIT_COMMITTER_DATE": true,
239 "EMAIL": true,
240}
241
242// scratchRepo makes, or reuses, the repository a pass reads origin into,
243// and returns git run in it with hooks and configured filters off,
244// committing under the restacker's identity. git there is unattended: it
245// never asks a question, and every git it runs is killed whole once ctx is
246// done.
247//
248// The repository has a work tree, though nothing is ever checked out in
249// it: attest, which digests a version's tree and verifies the
250// integrator's transfer statements, reads only a repository with a work
251// tree.
252func scratchRepo(ctx context.Context, c config) (rebase.Git, error) {
253 dir := filepath.Join(c.state, "scratch")
254 var env []string
255 for _, kv := range os.Environ() {
256 if name, _, _ := strings.Cut(kv, "="); !identityVariables[name] {
257 env = append(env, kv)
258 }
259 }
260 env = append(env,
261 "GIT_CONFIG_NOSYSTEM=1",
262 "GIT_CONFIG_GLOBAL=/dev/null",
263 "GIT_ATTR_NOSYSTEM=1",
264 "GIT_TERMINAL_PROMPT=0",
265 )
266 g := rebase.Git{Dir: dir, Env: env, Stderr: os.Stderr, Unattended: true}
267 if _, err := os.Stat(filepath.Join(dir, ".git", "HEAD")); err != nil {
268 if err := os.MkdirAll(dir, 0o700); err != nil {
269 return g, err
270 }
271 if err := run(ctx, g, "init", "--quiet"); err != nil {
272 return g, err
273 }
274 }
275 // user.useConfigOnly stops git guessing an identity from the host's
276 // name and the user's account. The state directory is bound to one
277 // repository (bindState), so origin's URL is the same every pass.
278 for _, kv := range [][2]string{
279 {"core.hooksPath", "/dev/null"},
280 {"core.fsmonitor", "false"},
281 {"user.name", c.commitName},
282 {"user.email", c.commitEmail},
283 {"user.useConfigOnly", "true"},
284 {"remote.origin.url", c.repo},
285 } {
286 if err := run(ctx, g, "config", kv[0], kv[1]); err != nil {
287 return g, err
288 }
289 }
290 return g, nil
291}
292
293func run(ctx context.Context, g rebase.Git, args ...string) error {
294 _, err := gitOut(ctx, g, args...)
295 return err
296}
297
298// gitOut runs git as the rebase engine runs it (rebase.Git.Command): killed
299// with what it started once ctx is done, and with the wait for its output
300// bounded.
301func gitOut(ctx context.Context, g rebase.Git, args ...string) (string, error) {
302 cmd := g.Command(ctx, args...)
303 var stderr strings.Builder
304 cmd.Stderr = &stderr
305 b, err := cmd.Output()
306 switch {
307 case ctx.Err() != nil:
308 return "", fmt.Errorf("git %s did not finish: %w", strings.Join(args, " "), ctx.Err())
309 case err != nil && !errors.Is(err, exec.ErrWaitDelay):
310 return "", fmt.Errorf("git %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(stderr.String()))
311 }
312 return string(b), nil
313}
314
315// ancestry is merge-base --is-ancestor, telling "no" (exit 1) apart from a
316// question git could not answer.
317func ancestry(ctx context.Context, g rebase.Git) Ancestry {
318 return func(a, b string) (bool, error) {
319 err := g.Command(ctx, "merge-base", "--is-ancestor", a, b).Run()
320 var exit *exec.ExitError
321 switch {
322 case err == nil || errors.Is(err, exec.ErrWaitDelay):
323 return true, nil
324 case errors.As(err, &exit) && exit.ExitCode() == 1:
325 return false, nil
326 }
327 return false, fmt.Errorf("could not tell whether %s is in %s", short(a), short(b))
328 }
329}
330
331// policyCap composes the policy at the target tip and reads the cap on
332// automatic versions: the floor from the instance repository's tip, read
333// over git into the scratch repository, or from --instance; the project
334// layer from the tip.
335func policyCap(ctx context.Context, g rebase.Git, c config, tip string) (int, error) {
336 floor := c.floor
337 if c.instanceRepo != "" {
338 out, err := gitOut(ctx, g, "ls-remote", c.instanceRepo, floor.Ref)
339 if ctx.Err() != nil {
340 return 0, err
341 }
342 oid, _, _ := strings.Cut(out, "\t")
343 if err != nil || !rebase.IsObjectID(oid) {
344 return 0, fmt.Errorf("no instance policy layer: %s has no %s: %s", c.instanceRepo, floor.Ref, composed.Floorless)
345 }
346 if err := run(ctx, g, "fetch", "--quiet", "--no-tags", "--no-write-fetch-head", c.instanceRepo, oid); err != nil {
347 return 0, err
348 }
349 floor.Repo, floor.Ref = g.Dir, oid
350 }
351 instance, done, err := floor.Open(ctx, "valley-restacker-floor")
352 if err != nil {
353 return 0, err
354 }
355 defer done()
356 project, _, doneProject, err := composed.Project(ctx, g.Dir, tip, c.projectPolicy, "valley-restacker-project")
357 if err != nil {
358 return 0, err
359 }
360 defer doneProject()
361 pol, err := composed.Compose(ctx, c.cue, c.schema, instance, project)
362 if err != nil {
363 return 0, err
364 }
365 return CapOf(pol.MaxAutomaticVersions)
366}
367
368// planOnce reads one snapshot and plans every family in it.
369func planOnce(ctx context.Context, g rebase.Git, c config) (*Plan, error) {
370 s, err := rebase.ReadSnapshot(ctx, g, c.verify)
371 if err != nil {
372 return nil, err
373 }
374 if s.Tip == "" {
375 return nil, fmt.Errorf("origin has no %s", rebase.Target)
376 }
377 cap, err := policyCap(ctx, g, c, s.Tip)
378 if err != nil {
379 return nil, err
380 }
381 var attestations []string
382 var requests []Request
383 for ref, oid := range s.Refs {
384 switch {
385 case strings.HasPrefix(ref, rebase.AttestationRefs):
386 attestations = append(attestations, ref+" "+oid)
387 case strings.HasPrefix(ref, rebase.RequestPrefix):
388 requests = append(requests, Request{Name: strings.TrimPrefix(ref, rebase.RequestPrefix), Head: oid})
389 }
390 }
391 p := &Plan{Target: rebase.Target, Tip: s.Tip, Evidence: change.EvidenceFingerprint(attestations), Cap: cap}
392
393 // The snapshot lists request heads and does not fetch them. They are
394 // fetched here, before any ancestry is read, all at once and then one
395 // by one when that fails, so one head origin cannot serve leaves the
396 // others readable.
397 var heads []string
398 for _, r := range requests {
399 heads = append(heads, r.Head)
400 }
401 if rebase.Fetch(ctx, g, heads...) != nil {
402 for _, h := range heads {
403 _ = rebase.Fetch(ctx, g, h)
404 }
405 }
406
407 seen := map[string]bool{}
408 for _, n := range s.Changes {
409 if seen[n.ID] || !s.Unlanded(n) {
410 continue
411 }
412 f, err := rebase.Capture(s, rebase.Selection{ID: n.ID, Whole: true})
413 if err != nil {
414 return nil, err
415 }
416 for _, l := range f.Layers {
417 if l.ID != "" {
418 seen[l.ID] = true
419 }
420 }
421 p.Families = append(p.Families, judge(f, s, c.principal, p, requests, ancestry(ctx, g)))
422 }
423 return p, nil
424}
425
426// judge decides what a pass would do with one family.
427func judge(f *rebase.Family, s *rebase.Snapshot, principal string, p *Plan, requests []Request, is Ancestry) FamilyPlan {
428 fp := FamilyPlan{Reasons: []string{}, Notes: []string{}, Requests: []RequestPlan{}}
429 ready := false
430 for _, l := range f.Layers {
431 lp := LayerPlan{Name: l.Name, ID: l.ID, Branch: l.Branch, Head: l.Head, State: string(l.State())}
432 if l.Below != nil {
433 lp.Below = l.Below.Name
434 }
435 if l.State() == rebase.Ready {
436 ready = true
437 } else {
438 fp.Reasons = append(fp.Reasons, stateLine(l))
439 }
440 fp.Layers = append(fp.Layers, lp)
441 }
442 switch {
443 case !ready:
444 fp.Action = leave
445 return fp
446 case f.FastForwards():
447 fp.Action, fp.Reasons = current, []string{"it already descends from " + rebase.Target + "'s tip"}
448 return fp
449 }
450 if err := f.Check(); err != nil {
451 fp.Reasons = append(fp.Reasons, err.Error())
452 }
453
454 m := membersOf(f)
455 for _, r := range requests {
456 by, err := Relate(r, m, p.Tip, is)
457 if err != nil {
458 fp.Requests = append(fp.Requests, RequestPlan{Name: r.Name, Head: r.Head, By: []string{}, Why: err.Error()})
459 fp.Reasons = append(fp.Reasons, fmt.Sprintf("request %s: whether it is related cannot be determined: %v", r.Name, err))
460 continue
461 }
462 if by == nil {
463 continue
464 }
465 o, found := s.OutcomeOf(r.Name)
466 rp := RequestPlan{Name: r.Name, Head: r.Head, By: by}
467 if found {
468 rp.Decision = o.Decision
469 }
470 rp.Current, rp.Releases, rp.Why = Currency(o, found, r.Head, p.Tip, p.Evidence)
471 switch {
472 case !rp.Releases:
473 fp.Reasons = append(fp.Reasons, fmt.Sprintf("request %s might still land: %s", r.Name, rp.Why))
474 case o.Decision == "reject":
475 fp.Notes = append(fp.Notes, fmt.Sprintf("request %s was rejected at this head, tip and evidence", r.Name))
476 }
477 fp.Requests = append(fp.Requests, rp)
478 }
479 sortRequests(fp.Requests)
480
481 for i, l := range f.Layers {
482 if l.ID == "" || l.Record == nil {
483 continue
484 }
485 cp := CapacityOf(l.Record, principal, p.Cap, nextSize(l.Name, l.Record, principal))
486 fp.Layers[i].Capacity = cp
487 fp.Reasons = append(fp.Reasons, cp.Over...)
488 }
489 fp.Action = restack
490 if len(fp.Reasons) > 0 {
491 fp.Action = hold
492 }
493 return fp
494}
495
496func printPlan(w io.Writer, p *Plan) {
497 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)
498 if len(p.Families) == 0 {
499 fmt.Fprintln(w, "no change to restack")
500 }
501 for _, f := range p.Families {
502 fmt.Fprintf(w, "\n%s: %s\n", f.Layers[0].Name, f.Action)
503 for _, l := range f.Layers {
504 fmt.Fprintf(w, " %-24s %-10s %s", l.Name, l.State, short(l.Head))
505 if l.Below != "" {
506 fmt.Fprintf(w, " on %s", l.Below)
507 }
508 if c := l.Capacity; c != nil {
509 fmt.Fprintf(w, "; %d/%d automatic, %d/%d versions, update %d/%d, %d/%d bytes",
510 c.Uploads, c.Cap, c.Versions, c.MaxVersions, c.Seq, c.MaxSeq, c.Bytes, c.MaxBytes)
511 }
512 fmt.Fprintln(w)
513 }
514 for _, r := range f.Requests {
515 fmt.Fprintf(w, " request %s at %s, by %s: %s\n", r.Name, short(r.Head), strings.Join(r.By, ", "), r.Why)
516 }
517 for _, why := range f.Reasons {
518 fmt.Fprintf(w, " - %s\n", why)
519 }
520 for _, n := range f.Notes {
521 fmt.Fprintf(w, " note: %s\n", n)
522 }
523 }
524}