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