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