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