diff --git a/cmd/buildingblock/abort_run.go b/cmd/buildingblock/abort_run.go index 4798b138..4c3d295a 100644 --- a/cmd/buildingblock/abort_run.go +++ b/cmd/buildingblock/abort_run.go @@ -19,6 +19,7 @@ func newAbortRun() *cobra.Command { var ( output internal.OutputFlag buildingBlockUuid uuid.UUID + runUuid uuid.UUID ) cmd := &cobra.Command{ @@ -26,21 +27,28 @@ func newAbortRun() *cobra.Command { Short: "Abort the latest run of a building block", Long: `Abort the latest run of a building block, or its dry run if the dry run is newer. -The command shows the run and asks you to confirm, so it needs a terminal. After the abort, it prints the building block.`, +The command shows the run and asks you to confirm, so it needs a terminal. After the abort, it prints the building block. + +Without a terminal, pass the uuid of the run to abort with --` + runFlagName + `; 'meshstack buildingblockrun list --building-block ' shows it. The command aborts that run of the building block without asking. The run can wait for approval or be in progress, and it does not have to be the latest run. A run that is already applying changes may leave them half done.`, Example: ` meshstack buildingblock abort-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 - meshstack bb abort-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90`, + meshstack bb abort-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 --run 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c`, Args: internal.UuidArg(&buildingBlockUuid), RunE: func(cmd *cobra.Command, _ []string) error { ctx := cmd.Context() - action, err := newRunAction(cmd, buildingBlockUuid, output.Format) + named := cmd.Flags().Changed(runFlagName) + action, err := newRunAction(cmd, buildingBlockUuid, output.Format, named) if err != nil { return err } + if named { + return action.abortNamedRun(ctx, runUuid) + } return action.abort(ctx) }, } output.RegisterForItem(cmd.Flags()) + cmd.Flags().Var((*internal.UuidFlag)(&runUuid), runFlagName, "abort the run with this uuid without asking") return cmd } @@ -74,7 +82,23 @@ func (a runAction) abort(ctx context.Context) error { slog.InfoContext(ctx, fmt.Sprintf("Did not abort run %s.", run.Metadata.Uuid)) return nil } - err = a.meshStack.BuildingBlockRunAction.AbortRun(ctx, *run.Links.Abort) + return a.sendAbort(ctx, run) +} + +func (a runAction) abortNamedRun(ctx context.Context, runUuid uuid.UUID) error { + run, err := a.readNamedRun(ctx, runUuid) + if err != nil { + return err + } + if run.Links.Abort == nil { + return fmt.Errorf("run %s of building block %s has the status %s and cannot be aborted, or you are not allowed to abort it", + runUuid, a.buildingBlockUuid, run.Status) + } + return a.sendAbort(ctx, run) +} + +func (a runAction) sendAbort(ctx context.Context, run client.MeshBuildingBlockRun) error { + err := a.meshStack.BuildingBlockRunAction.AbortRun(ctx, *run.Links.Abort) if httpErr, ok := errors.AsType[client.HttpError](err); ok && httpErr.StatusCode == gohttp.StatusConflict { return fmt.Errorf("run %s can no longer be aborted", run.Metadata.Uuid) } diff --git a/cmd/buildingblock/abort_run_internal_test.go b/cmd/buildingblock/abort_run_internal_test.go new file mode 100644 index 00000000..7b122d84 --- /dev/null +++ b/cmd/buildingblock/abort_run_internal_test.go @@ -0,0 +1,82 @@ +package buildingblock + +import ( + "io" + gohttp "net/http" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack" + "github.com/meshcloud/meshstack-cli/internal/testutil/testlogin" +) + +func TestAbortRunWithoutATerminalAbortsTheRunItIsGiven(t *testing.T) { + const ( + waitingRun = "a0000000-0000-4000-8000-000000000003" + inProgressRun = "a0000000-0000-4000-8000-000000000004" + finishedRun = "a0000000-0000-4000-8000-000000000005" + runOfOtherBlock = "a0000000-0000-4000-8000-000000000006" + otherBuildingBlock = "b1d2c3e4-0000-4000-8000-000000000009" + ) + runWithLinks := func(runUuid, ofBuildingBlock, status string, linkNames ...string) any { + var links []string + for _, name := range linkNames { + links = append(links, `"`+name+`": {"href": "`+runsPath+runUuid+`/`+name+`"}`) + } + return meshObject(t, `{"metadata": {"uuid": "`+runUuid+`"}, "status": "`+status+`", `+ + `"spec": {"buildingBlock": {"uuid": "`+ofBuildingBlock+`"}}, "_links": {`+strings.Join(links, ", ")+`}}`) + } + server := fakemeshstack.Start(t, fakemeshstack.Options{ + BuildingBlocks: []any{meshObject(t, `{"metadata": {"uuid": "`+buildingBlockUuid+`"}, "status": {"action": "APPROVE_RUN"}}`)}, + BuildingBlockRuns: []any{ + runWithLinks(waitingRun, buildingBlockUuid, "IN_PROGRESS", "approve", "abort"), + runWithLinks(inProgressRun, buildingBlockUuid, "IN_PROGRESS", "abort"), + runWithLinks(finishedRun, buildingBlockUuid, "SUCCEEDED"), + runWithLinks(runOfOtherBlock, otherBuildingBlock, "IN_PROGRESS", "abort"), + }, + }) + var aborted []string + for _, runUuid := range []string{waitingRun, inProgressRun, runOfOtherBlock} { + server.Route("POST "+runsPath+runUuid+"/abort", func(w gohttp.ResponseWriter, _ *gohttp.Request) { + aborted = append(aborted, runUuid) + w.WriteHeader(gohttp.StatusAccepted) + }) + } + testlogin.LoggedInTo(t, server.URL) + abortRun := func(stdin string, args ...string) error { + cmd := New() + cmd.SetIn(strings.NewReader(stdin)) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + cmd.SetArgs(append([]string{"abort-run", buildingBlockUuid}, args...)) + return cmd.ExecuteContext(t.Context()) + } + + t.Run("without a terminal and without --run, nothing is asked and nothing is aborted", func(t *testing.T) { + require.EqualError(t, abortRun("y\n"), "abort-run needs a terminal, because it asks you to confirm. 'buildingblock abort-run --help' shows how to run it without a terminal") + assert.Empty(t, server.TakeRequests()) + }) + + t.Run("--run aborts a run that waits for approval", func(t *testing.T) { + require.NoError(t, abortRun("", "--run", waitingRun)) + assert.Equal(t, []string{waitingRun}, aborted) + }) + + t.Run("--run aborts a run that is in progress", func(t *testing.T) { + require.NoError(t, abortRun("", "--run", inProgressRun)) + assert.Equal(t, []string{waitingRun, inProgressRun}, aborted) + }) + + t.Run("--run does not abort a run that cannot be aborted", func(t *testing.T) { + require.ErrorContains(t, abortRun("", "--run", finishedRun), "has the status SUCCEEDED and cannot be aborted") + assert.Equal(t, []string{waitingRun, inProgressRun}, aborted) + }) + + t.Run("--run does not abort a run of another building block", func(t *testing.T) { + require.ErrorContains(t, abortRun("", "--run", runOfOtherBlock), "belongs to building block "+otherBuildingBlock) + assert.Equal(t, []string{waitingRun, inProgressRun}, aborted) + }) +} diff --git a/cmd/buildingblock/approve_run.go b/cmd/buildingblock/approve_run.go index 27fe7385..cdd06400 100644 --- a/cmd/buildingblock/approve_run.go +++ b/cmd/buildingblock/approve_run.go @@ -20,6 +20,8 @@ func newApproveRun() *cobra.Command { var ( output internal.OutputFlag buildingBlockUuid uuid.UUID + runUuid uuid.UUID + detectRun uuid.UUID ) cmd := &cobra.Command{ @@ -29,25 +31,36 @@ func newApproveRun() *cobra.Command { The command shows the plan and asks you to approve it, so it needs a terminal. It approves exactly the plan it showed. If meshStack planned the run again in the meantime, the approval fails, and you can run the command again to review the new plan. +Without a terminal, review the plan with 'meshstack buildingblockrun plan ' first, and approve it only if the user allows it. Then pass the uuid of that run with --` + runFlagName + ` and the uuid of the detect run that 'meshstack buildingblockrun plan' prints with --` + detectRunFlagName + `. The command approves that plan of that run without asking. If meshStack has planned the run again since, the approval fails, and the user has to see the new plan before you approve it. + A building block whose status.action is APPROVE_RUN in 'meshstack buildingblock list' has a run that is waiting for approval. After the approval, the command prints the building block.`, Example: ` meshstack buildingblock approve-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 - meshstack bb approve-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90`, + meshstack bb approve-run 0b5c1d3e-5f1a-4c2b-9d7e-2a6f8e4b1c90 --run 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c --detect-run 2c8d1e4f-6a7b-4c3d-8e9f-0a1b2c3d4e5f`, Args: internal.UuidArg(&buildingBlockUuid), RunE: func(cmd *cobra.Command, _ []string) error { ctx := cmd.Context() - action, err := newRunAction(cmd, buildingBlockUuid, output.Format) + named := cmd.Flags().Changed(runFlagName) + action, err := newRunAction(cmd, buildingBlockUuid, output.Format, named) if err != nil { return err } + if named { + return action.approveNamedRun(ctx, runUuid, detectRun) + } return action.approve(ctx) }, } output.RegisterForItem(cmd.Flags()) + cmd.Flags().Var((*internal.UuidFlag)(&runUuid), runFlagName, "approve the run with this uuid without asking, together with --"+detectRunFlagName) + cmd.Flags().Var((*internal.UuidFlag)(&detectRun), detectRunFlagName, "approve the plan of the detect run with this uuid, together with --"+runFlagName) + cmd.MarkFlagsRequiredTogether(runFlagName, detectRunFlagName) return cmd } +const detectRunFlagName = "detect-run" + func (a runAction) approve(ctx context.Context) error { _, block, err := a.readBuildingBlock(ctx) if err != nil { @@ -64,47 +77,75 @@ func (a runAction) approve(ctx context.Context) error { return fmt.Errorf("the latest run %s of building block %s (action %s) is not waiting for approval, or you are not allowed to approve it", run.Metadata.Uuid, a.buildingBlockUuid, block.Status.Action) } - if run.Links.Predecessor == nil { - return fmt.Errorf("run %s is waiting for approval, but meshStack does not say which run created its plan", run.Metadata.Uuid) + plan, err := a.confirmPlan(ctx, run) + if err != nil || plan == "" { + return err } - plan, err := a.meshStack.BuildingBlockRunAction.ReadRun(ctx, *run.Links.Predecessor) + return a.sendApproval(ctx, run, plan, + fmt.Errorf("the plan of run %s changed after you saw it. Run the command again to review the new plan", run.Metadata.Uuid)) +} + +func (a runAction) approveNamedRun(ctx context.Context, runUuid, detectRun uuid.UUID) error { + run, err := a.readNamedRun(ctx, runUuid) if err != nil { return err } - if plan.Links.DownloadLogs == nil { - return fmt.Errorf("cannot read the logs of run %s, which created the plan for run %s", plan.Metadata.Uuid, run.Metadata.Uuid) + if run.Links.Approve == nil { + return fmt.Errorf("run %s of building block %s is not waiting for approval, or you are not allowed to approve it. 'meshstack buildingblock list' shows the run that waits as status.latestRunUuid of a building block whose status.action is APPROVE_RUN", + runUuid, a.buildingBlockUuid) + } + return a.sendApproval(ctx, run, detectRun.String(), plansDiffer(run, detectRun)) +} + +// sendApproval approves the plan of the detect run plan for run, and prints the building block. +// changed is the error for the 409 of meshStack, which it sends for any plan that is not the one +// the run waits for now. +func (a runAction) sendApproval(ctx context.Context, run client.MeshBuildingBlockRun, plan string, changed error) error { + err := a.meshStack.BuildingBlockRunAction.ApproveRun(ctx, *run.Links.Approve, plan) + if httpErr, ok := errors.AsType[client.HttpError](err); ok { + switch httpErr.StatusCode { + case gohttp.StatusConflict: + return changed + case gohttp.StatusBadRequest: + return fmt.Errorf("run %s is no longer waiting for approval", run.Metadata.Uuid) + } } - logs, err := a.meshStack.BuildingBlockRunAction.ReadLogs(ctx, *plan.Links.DownloadLogs) if err != nil { return err } + return a.report(ctx, fmt.Sprintf("Approved the plan of run %s. Follow the run with 'meshstack buildingblockrun logs %s --follow'.", run.Metadata.Uuid, run.Metadata.Uuid)) +} + +// plansDiffer is the error for the 409 of a caller that named the detect run: meshStack planned the +// run again, or the caller named a detect run that is not the one of the run. +func plansDiffer(run client.MeshBuildingBlockRun, detectRun uuid.UUID) error { + return fmt.Errorf("run %s waits for another plan than the one of detect run %s: meshStack planned the run again, or that is not its detect run. "+ + "An earlier go-ahead does not count for the new plan. Show the user the plan from 'meshstack buildingblockrun plan %s', and approve it only if the user allows it", + run.Metadata.Uuid, detectRun, run.Metadata.Uuid) +} + +// confirmPlan shows the plan that run waits to have approved, and returns its detect run if the +// user approves it. +func (a runAction) confirmPlan(ctx context.Context, run client.MeshBuildingBlockRun) (string, error) { + plan, logs, err := buildingblockrun.ReadPlan(ctx, a.meshStack, run) + if err != nil { + return "", err + } var shown bytes.Buffer if err = buildingblockrun.WriteLogs(&shown, logs); err != nil { - return err + return "", err } if err = a.prompt.Printf("Run %d of building block %q is waiting for approval of the plan from run %s:\n\n%s\n", run.Spec.RunNumber, run.Spec.BuildingBlock.Spec.DisplayName, plan.Metadata.Uuid, shown.String()); err != nil { - return err + return "", err } approved, err := a.prompt.Confirm(ctx, "Approve this plan?") if err != nil { - return err + return "", err } if !approved { slog.InfoContext(ctx, fmt.Sprintf("Did not approve run %s.", run.Metadata.Uuid)) - return nil - } - err = a.meshStack.BuildingBlockRunAction.ApproveRun(ctx, *run.Links.Approve, plan.Metadata.Uuid) - if httpErr, ok := errors.AsType[client.HttpError](err); ok { - switch httpErr.StatusCode { - case gohttp.StatusConflict: - return fmt.Errorf("the plan of run %s changed after you saw it. Run the command again to review the new plan", run.Metadata.Uuid) - case gohttp.StatusBadRequest: - return fmt.Errorf("run %s is no longer waiting for approval", run.Metadata.Uuid) - } - } - if err != nil { - return err + return "", nil } - return a.report(ctx, fmt.Sprintf("Approved the plan of run %s.", run.Metadata.Uuid)) + return plan.Metadata.Uuid, nil } diff --git a/cmd/buildingblock/approve_run_internal_test.go b/cmd/buildingblock/approve_run_internal_test.go index b4b9e60d..9c91c991 100644 --- a/cmd/buildingblock/approve_run_internal_test.go +++ b/cmd/buildingblock/approve_run_internal_test.go @@ -12,8 +12,10 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/meshcloud/meshstack-cli/cmd/buildingblockrun" "github.com/meshcloud/meshstack-cli/cmd/internal" "github.com/meshcloud/meshstack-cli/cmd/internal/prompt" + "github.com/meshcloud/meshstack-cli/internal/logs" "github.com/meshcloud/meshstack-cli/internal/testutil/fakemeshstack" "github.com/meshcloud/meshstack-cli/internal/testutil/testlogin" ) @@ -45,8 +47,12 @@ func newTestRunAction(t *testing.T, server *fakemeshstack.Server, answers string func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { const ( - waitingRun = "a0000000-0000-4000-8000-000000000002" - planRun = "a0000000-0000-4000-8000-000000000001" + waitingRun = "a0000000-0000-4000-8000-000000000002" + planRun = "a0000000-0000-4000-8000-000000000001" + otherPlan = "a0000000-0000-4000-8000-000000000009" + approvedRun = "a0000000-0000-4000-8000-000000000007" + runOfOtherBlock = "a0000000-0000-4000-8000-000000000008" + otherBuildingBlock = "b1d2c3e4-0000-4000-8000-000000000009" ) run := meshObject(t, `{"metadata": {"uuid": "`+waitingRun+`"}, "status": "IN_PROGRESS", `+ `"spec": {"runNumber": 2, "behavior": "APPLY", "buildingBlock": {"uuid": "`+buildingBlockUuid+`", "spec": {"displayName": "my-block"}}}, `+ @@ -54,8 +60,14 @@ func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { server := fakemeshstack.Start(t, fakemeshstack.Options{ BuildingBlocks: []any{meshObject(t, `{"metadata": {"uuid": "`+buildingBlockUuid+`"}, "status": {"action": "APPROVE_RUN"}, `+ `"_links": {"latestRun": {"href": "`+runsPath+waitingRun+`"}}}`)}, - BuildingBlockRuns: []any{run, meshObject(t, `{"metadata": {"uuid": "`+planRun+`"}, "status": "SUCCEEDED", `+ - `"_links": {"downloadLogs": {"href": "`+runsPath+planRun+`/logs"}}}`)}, + BuildingBlockRuns: []any{ + run, meshObject(t, `{"metadata": {"uuid": "`+planRun+`"}, "status": "SUCCEEDED", `+ + `"_links": {"downloadLogs": {"href": "`+runsPath+planRun+`/logs"}}}`), + meshObject(t, `{"metadata": {"uuid": "`+approvedRun+`"}, "status": "IN_PROGRESS", `+ + `"spec": {"buildingBlock": {"uuid": "`+buildingBlockUuid+`"}}, "_links": {}}`), + meshObject(t, `{"metadata": {"uuid": "`+runOfOtherBlock+`"}, "status": "IN_PROGRESS", `+ + `"spec": {"buildingBlock": {"uuid": "`+otherBuildingBlock+`"}}, "_links": {"approve": {"href": "`+runsPath+runOfOtherBlock+`/approve"}}}`), + }, }) server.Route("GET "+runsPath+planRun+"/logs", func(w gohttp.ResponseWriter, _ *gohttp.Request) { _, _ = io.WriteString(w, `{"steps": [{"displayName": "Plan", "status": "SUCCEEDED", "userMessage": "+ resource \"x\" will be created"}]}`) @@ -75,10 +87,24 @@ func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { cmd.SetErr(io.Discard) cmd.SetArgs([]string{"approve-run", buildingBlockUuid}) - require.EqualError(t, cmd.ExecuteContext(t.Context()), "approve-run needs a terminal, because it asks you to confirm") + require.EqualError(t, cmd.ExecuteContext(t.Context()), "approve-run needs a terminal, because it asks you to confirm. 'buildingblock approve-run --help' shows how to run it without a terminal") assert.Empty(t, server.TakeRequests()) }) + t.Run("bbrun plan prints the plan of the waiting run and names the detect run", func(t *testing.T) { + testlogin.LoggedInTo(t, server.URL) + captured := logs.Capture(t) + cmd := buildingblockrun.New() + var stdout bytes.Buffer + cmd.SetOut(&stdout) + cmd.SetArgs([]string{"plan", waitingRun}) + + require.NoError(t, cmd.ExecuteContext(t.Context())) + assert.Equal(t, "Plan: SUCCEEDED\nPlan | + resource \"x\" will be created\n", stdout.String()) + assert.Contains(t, captured.String(), "from the detect run "+planRun) + assert.Contains(t, captured.String(), "approve-run "+buildingBlockUuid+" --run "+waitingRun+" --detect-run "+planRun+"'") + }) + t.Run("a plan that is not approved stays waiting", func(t *testing.T) { action, asked := newTestRunAction(t, server, "n\n") @@ -96,6 +122,49 @@ func TestApproveRunApprovesOnlyThePlanItShowed(t *testing.T) { assert.JSONEq(t, `{"predecessorRunUuid": "`+planRun+`"}`, approvals[0]) }) + approveWithoutATerminal := func(t *testing.T, args ...string) error { + t.Helper() + testlogin.LoggedInTo(t, server.URL) + cmd := New() + cmd.SetIn(strings.NewReader("")) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + cmd.SetArgs(append([]string{"approve-run", buildingBlockUuid}, args...)) + return cmd.ExecuteContext(t.Context()) + } + + t.Run("without a terminal, --run and --detect-run approve the plan of that run without asking", func(t *testing.T) { + require.NoError(t, approveWithoutATerminal(t, "--run", waitingRun, "--detect-run", planRun)) + require.Len(t, approvals, 2) + assert.JSONEq(t, `{"predecessorRunUuid": "`+planRun+`"}`, approvals[1]) + }) + + t.Run("--run and --detect-run belong together", func(t *testing.T) { + require.ErrorContains(t, approveWithoutATerminal(t, "--run", waitingRun), "must all be set") + require.ErrorContains(t, approveWithoutATerminal(t, "--detect-run", planRun), "must all be set") + assert.Len(t, approvals, 2) + }) + + t.Run("--run of a run that does not wait for approval is refused", func(t *testing.T) { + require.ErrorContains(t, approveWithoutATerminal(t, "--run", approvedRun, "--detect-run", planRun), "is not waiting for approval") + assert.Len(t, approvals, 2) + }) + + t.Run("--run of a run of another building block is refused", func(t *testing.T) { + require.ErrorContains(t, approveWithoutATerminal(t, "--run", runOfOtherBlock, "--detect-run", planRun), "belongs to building block "+otherBuildingBlock) + assert.Len(t, approvals, 2) + }) + + t.Run("--detect-run of another plan is refused, and the user has to see the plan", func(t *testing.T) { + approveAnswer = gohttp.StatusConflict + + err := approveWithoutATerminal(t, "--run", waitingRun, "--detect-run", otherPlan) + require.ErrorContains(t, err, "run "+waitingRun+" waits for another plan than the one of detect run "+otherPlan) + require.ErrorContains(t, err, "Show the user the plan from 'meshstack buildingblockrun plan "+waitingRun+"'") + require.Len(t, approvals, 3) + assert.JSONEq(t, `{"predecessorRunUuid": "`+otherPlan+`"}`, approvals[2]) + }) + t.Run("a plan that changed after it was shown has to be reviewed again", func(t *testing.T) { approveAnswer = gohttp.StatusConflict action, _ := newTestRunAction(t, server, "y\n") diff --git a/cmd/buildingblock/buildingblock.go b/cmd/buildingblock/buildingblock.go index 084fd853..56730938 100644 --- a/cmd/buildingblock/buildingblock.go +++ b/cmd/buildingblock/buildingblock.go @@ -13,6 +13,7 @@ import ( "github.com/meshcloud/meshstack-cli/client" "github.com/meshcloud/meshstack-cli/cmd/buildingblock/tfstate" + "github.com/meshcloud/meshstack-cli/cmd/buildingblockrun" "github.com/meshcloud/meshstack-cli/cmd/internal" "github.com/meshcloud/meshstack-cli/cmd/internal/prompt" ) @@ -49,11 +50,13 @@ type runAction struct { format internal.OutputFormat } -func newRunAction(cmd *cobra.Command, buildingBlockUuid uuid.UUID, format internal.OutputFormat) (runAction, error) { +// newRunAction needs a terminal to ask for a confirmation, unless the caller names the plan to approve +// or the run to abort. A name binds the command to that plan or run, but does not show that anyone +// has reviewed it. +func newRunAction(cmd *cobra.Command, buildingBlockUuid uuid.UUID, format internal.OutputFormat, confirmed bool) (runAction, error) { p := prompt.New(cmd.InOrStdin(), cmd.ErrOrStderr()) - // A script cannot approve or abort: the decision belongs to a person who saw the run. - if !p.UsesTerminal() { - return runAction{}, fmt.Errorf("%s needs a terminal, because it asks you to confirm", cmd.Name()) + if !confirmed && !p.UsesTerminal() { + return runAction{}, fmt.Errorf("%s needs a terminal, because it asks you to confirm. '%s --help' shows how to run it without a terminal", cmd.Name(), cmd.CommandPath()) } meshStack, err := internal.ResolveClient(cmd.Context()) if err != nil { @@ -76,6 +79,20 @@ func (a runAction) readBuildingBlock(ctx context.Context) (jsontext.Value, linke return raw, block, json.Unmarshal(raw, &block) } +const runFlagName = "run" + +// readNamedRun reads the run that the caller names with --run, which has to belong to the building block. +func (a runAction) readNamedRun(ctx context.Context, runUuid uuid.UUID) (client.MeshBuildingBlockRun, error) { + run, err := buildingblockrun.ReadRun(ctx, a.meshStack, runUuid) + if err != nil { + return run, err + } + if run.Spec.BuildingBlock.Uuid != a.buildingBlockUuid.String() { + return run, fmt.Errorf("run %s belongs to building block %s, not to %s", runUuid, run.Spec.BuildingBlock.Uuid, a.buildingBlockUuid) + } + return run, nil +} + // report reads the building block again and writes it, because a run hides the actions // APPROVE_RUN and REVIEW_ABORTED_RUN that only the building block shows. func (a runAction) report(ctx context.Context, done string) error { diff --git a/cmd/buildingblock/wait_test.go b/cmd/buildingblock/wait_test.go index 2202cb49..4dda1220 100644 --- a/cmd/buildingblock/wait_test.go +++ b/cmd/buildingblock/wait_test.go @@ -57,9 +57,10 @@ func TestWaitFailsOnAnOutcomeThatNeedsSomeoneToAct(t *testing.T) { assert.Contains(t, stdout, `"action": "REVIEW_ERRORS"`, "the building block still goes to stdout") }) - t.Run("a run that waits for approval fails the wait", func(t *testing.T) { + t.Run("a run that waits for approval fails the wait with its action and points to its plan", func(t *testing.T) { current.Store(new(buildingBlockWithRun("APPROVE_RUN", "run-2"))) _, err := run(before, "wait", waitedBuildingBlock, "--before=-") require.ErrorContains(t, err, "is paused at action APPROVE_RUN") + require.ErrorContains(t, err, "meshstack buildingblockrun plan run-2") }) } diff --git a/cmd/buildingblockrun/buildingblockrun.go b/cmd/buildingblockrun/buildingblockrun.go index 38afd40b..c6b66740 100644 --- a/cmd/buildingblockrun/buildingblockrun.go +++ b/cmd/buildingblockrun/buildingblockrun.go @@ -22,6 +22,7 @@ func New() *cobra.Command { cmd.AddCommand(newList()) cmd.AddCommand(newLogs()) + cmd.AddCommand(newPlan()) return cmd } diff --git a/cmd/buildingblockrun/plan.go b/cmd/buildingblockrun/plan.go new file mode 100644 index 00000000..60c63343 --- /dev/null +++ b/cmd/buildingblockrun/plan.go @@ -0,0 +1,87 @@ +package buildingblockrun + +import ( + "context" + "encoding/json/v2" + "fmt" + "log/slog" + "uuid" + + "github.com/spf13/cobra" + + "github.com/meshcloud/meshstack-cli/client" + "github.com/meshcloud/meshstack-cli/cmd/internal" +) + +func newPlan() *cobra.Command { + var runUuid uuid.UUID + + return &cobra.Command{ + Use: "plan ", + Short: "Show the plan that a building block run is waiting to have approved", + Long: `Show the plan that a building block run is waiting to have approved, as text. + +A run that waits for approval has no logs of its own. Its plan is in the logs of the run before it, the detect run, which planned the changes. The command prints the logs of the detect run, and a line with the uuid of the detect run. Give the waiting run by its uuid; 'meshstack buildingblock list' shows it as status.latestRunUuid of a building block whose status.action is APPROVE_RUN. + +The command prints a line ': ' for each step, and the lines of a step's messages after ' |'. Filter on '|' to read only the messages. + +To approve the plan without a terminal, pass the uuid of this run and the uuid of the detect run to 'meshstack buildingblock approve-run --run --detect-run ', and approve only if the user allows it. The approval fails if meshStack has planned the run again in the meantime.`, + Example: ` meshstack buildingblockrun plan 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c + meshstack bbrun plan 7f3a2b1c-8d4e-4f6a-9b0c-1d2e3f4a5b6c | grep '| Plan:'`, + Args: internal.UuidArg(&runUuid), + RunE: func(cmd *cobra.Command, _ []string) error { + ctx := cmd.Context() + meshStack, err := internal.ResolveClient(ctx) + if err != nil { + return err + } + run, err := ReadRun(ctx, meshStack, runUuid) + if err != nil { + return err + } + detectRun, logs, err := ReadPlan(ctx, meshStack, run) + if err != nil { + return err + } + if err = WriteLogs(cmd.OutOrStdout(), logs); err != nil { + return err + } + if run.Links.Approve == nil { + slog.InfoContext(ctx, fmt.Sprintf("This is the plan from the detect run %s. Run %s is not waiting for approval, or you are not allowed to approve it.", + detectRun.Metadata.Uuid, runUuid)) + return nil + } + slog.InfoContext(ctx, fmt.Sprintf("Run %s is waiting for approval of this plan from the detect run %s. If the user allows it, approve the plan with 'meshstack buildingblock approve-run %s --run %s --detect-run %s'", + runUuid, detectRun.Metadata.Uuid, run.Spec.BuildingBlock.Uuid, runUuid, detectRun.Metadata.Uuid)) + return nil + }, + } +} + +func ReadRun(ctx context.Context, meshStack client.Client, runUuid uuid.UUID) (client.MeshBuildingBlockRun, error) { + var run client.MeshBuildingBlockRun + raw, err := meshStack.Raw.Get[client.MeshBuildingBlockRun](ctx, runUuid) + if err != nil { + return run, err + } + return run, json.Unmarshal(raw, &run) +} + +// ReadPlan reads the detect run that planned run, and its logs, which hold the plan that run is +// waiting to have approved. +func ReadPlan(ctx context.Context, meshStack client.Client, run client.MeshBuildingBlockRun) (client.MeshBuildingBlockRun, client.MeshBuildingBlockRunLogs, error) { + if run.Links.Predecessor == nil { + return client.MeshBuildingBlockRun{}, client.MeshBuildingBlockRunLogs{}, fmt.Errorf( + "run %s has no predecessor, so no plan waits for its approval. Give the run that waits for approval: the status.latestRunUuid of a building block whose status.action is APPROVE_RUN", + run.Metadata.Uuid) + } + detectRun, err := meshStack.BuildingBlockRunAction.ReadRun(ctx, *run.Links.Predecessor) + if err != nil { + return detectRun, client.MeshBuildingBlockRunLogs{}, err + } + if detectRun.Links.DownloadLogs == nil { + return detectRun, client.MeshBuildingBlockRunLogs{}, fmt.Errorf("cannot read the logs of the detect run %s, which planned run %s", detectRun.Metadata.Uuid, run.Metadata.Uuid) + } + logs, err := meshStack.BuildingBlockRunAction.ReadLogs(ctx, *detectRun.Links.DownloadLogs) + return detectRun, logs, err +} diff --git a/cmd/internal/buildingblock/run_wait.go b/cmd/internal/buildingblock/run_wait.go index 57ec7780..405c6b08 100644 --- a/cmd/internal/buildingblock/run_wait.go +++ b/cmd/internal/buildingblock/run_wait.go @@ -76,6 +76,12 @@ func (w RunWait) Outcome(block *client.MeshBuildingBlockV2) error { err = fmt.Errorf("the run of building block %s ended with action %s", w.buildingBlockUuid, status.Action) case status.IsWaitingForInput(): err = fmt.Errorf("the run of building block %s is paused at action %s and continues only after someone acts on it", w.buildingBlockUuid, status.Action) + if status.Action == client.BuildingBlockActionApproveRun { + // status.latestDryRunUuid is null here, because the waiting run is newer than its detect run. + // 'bbrun plan' finds the detect run through the waiting run's predecessor. + waiting := status.GetLatestRunUuid() + err = fmt.Errorf("%w. Run %s waits for approval: review its plan with 'meshstack buildingblockrun plan %s'", err, waiting, waiting) + } } return withMeshPanelLink(err, block) } diff --git a/skills/meshstack-cli/SKILL.md b/skills/meshstack-cli/SKILL.md index 18e40ee1..4ef32a75 100644 --- a/skills/meshstack-cli/SKILL.md +++ b/skills/meshstack-cli/SKILL.md @@ -6,8 +6,8 @@ description: > (metadata/spec/status) that makes filtering cheap, and `meshstack api` / `api-docs` for everything the other commands do not cover. Use when asked to list, inspect or debug workspaces, building blocks, building block definitions or building block runs, to report on the health of - the building blocks a platform team provides, to trigger or wait for a run, or to order a - building block. + the building blocks a platform team provides, to trigger or wait for a run, to review and approve + a run that waits for approval, to abort a run, or to order a building block. --- # meshStack CLI @@ -29,11 +29,14 @@ skill and the help disagree, trust the help. | `meshstack buildingblock list` | `bb` | building blocks (deployed instances), newest first | | `meshstack buildingblock trigger-run ` | `bb` | starts a run of one block | | `meshstack buildingblock wait --before ` | `bb` | waits until the run of one block has ended | +| `meshstack buildingblock approve-run --run --detect-run ` | `bb` | approves the plan that `bbrun plan` shows, once the user allows it | +| `meshstack buildingblock abort-run --run ` | `bb` | aborts one run of a block, also one in progress | | `meshstack buildingblock tfstate` | `bb` | reads and writes the OpenTofu state of one block | | `meshstack buildingblockdefinition list` | `bbd` | definitions — what platform teams offer | | `meshstack buildingblockdefinitionversion list --definition ` | `bbdv` | the versions of one definition | | `meshstack buildingblockrun list [--building-block ]` | `bbrun` | runs, newest first | | `meshstack buildingblockrun logs ` | `bbrun` | the steps of one run, with their output | +| `meshstack buildingblockrun plan ` | `bbrun` | the plan that a run waits to have approved | | `meshstack eventlog list` | | event logs, newest first | | `meshstack api [-X method] [--request-json file\|-]` | | any meshStack API call, with this login | | `meshstack api-docs [] [--describe ]` | | what the API docs say about a request | @@ -317,26 +320,56 @@ meshstack bb trigger-run -o ndjson | jq -r '.status.latestRunUuid' It waits until meshStack has started the run, and prints the block; `status.latestRunUuid` names the new run. It never approves: when the definition gates manual triggers (`spec.approvalPolicies.manualTriggers`), meshStack starts a preflight run, which -`status.latestDryRunUuid` names, and the run after it waits until a person approves it in meshPanel. +`status.latestDryRunUuid` names at first, and the run after it waits until a person approves it, in +meshPanel or with `bb approve-run` (see +[Approval gates and preflight runs](#approval-gates-and-preflight-runs)). Every call starts a run, so trigger once and then wait. ## Approval gates and preflight runs A definition with `approvalPolicies` does not apply a gated change straight away. meshStack first runs a **preflight**: a dry run, listed with `spec.behavior == "DETECT"`. The `APPLY` run after it -waits, with the block's action `APPROVE_RUN`, until someone approves it in meshPanel. The approver sees the -preflight's plan, so read it yourself before you ask for the approval: +waits, with the block's action `APPROVE_RUN`, until someone approves it in meshPanel or with +`bb approve-run`. The approver sees the preflight's plan, so read it yourself before you ask for the +approval. `bbrun plan` takes the waiting run, the block's `status.latestRunUuid`, and prints the plan +of the preflight before it. The command prints a line `: ` for each step and the lines +of a step's messages after ` |`, so filter on the bar: ```sh -meshstack bbrun logs -o ndjson | - jq -r '.steps[].systemMessage // ""' | - grep -E "will be (created|destroyed|updated|replaced)|must be replaced|Plan:" +meshstack bbrun plan | + grep -E '\| .*(will be (created|destroyed|updated|replaced)|must be replaced|Plan:)' ``` Report the `Plan:` line and anything unexpected, and hand the user a deep link (below). A Terraform apply that updates such a block ends with the provider warning `Building block run is waiting for input or approval` — that is the gate, not an error. +Approve the run only if the user allows it for this plan. Then pass the waiting run and the detect +run that `bbrun plan` prints. The approval fails if meshStack has planned the run again since. The +plan has changed then: show the user the new plan, and approve only if they allow it again. + +```sh +meshstack bb approve-run --run --detect-run +``` + +The command prints the block as it reads it right after the approval, which is no `--before` for +`bb wait`. To wait for the approved run, follow its logs. The command exits with status 0 if the run +succeeded: + +```sh +meshstack bbrun logs --follow +``` + +To reject a waiting run instead, if the user asks you to, abort it by its uuid. The command does not +ask, and it aborts a run in any state: if someone approved the run since you read the block, the +apply in progress stops, and its changes can stay half done. So read the block again just before, +and abort only if its `status.action` is still `APPROVE_RUN`. The same command aborts a run in +progress, if the user asks you to: + +```sh +meshstack bb abort-run --run +``` + ## Linking into meshPanel Give the user a link whenever you ask them to act in meshPanel. A building block read from a recent @@ -366,7 +399,9 @@ meshstack api -X PUT /api/meshobjects/meshbuildingblocks/ --request-json b meshstack bb wait --before=- ``` -Both fail, and name the action, when the run failed or waits for a person or a dependency. +Both fail, and name the action, when the run failed or waits for a person or a dependency. When the +run waits for approval, they also point to `bbrun plan` for the waiting run: see +[Approval gates and preflight runs](#approval-gates-and-preflight-runs). A block that deletes itself at the end of its run, like a starterkit, is gone before `bb wait` can read the outcome. Poll its runs instead: `meshstack bbrun list --building-block --workspace