Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions cmd/buildingblock/abort_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,28 +19,36 @@ func newAbortRun() *cobra.Command {
var (
output internal.OutputFlag
buildingBlockUuid uuid.UUID
runUuid uuid.UUID
)

cmd := &cobra.Command{
Use: "abort-run <building-block-uuid>",
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 <building-block-uuid>' 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
}
Expand Down Expand Up @@ -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)
}
Expand Down
82 changes: 82 additions & 0 deletions cmd/buildingblock/abort_run_internal_test.go
Original file line number Diff line number Diff line change
@@ -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)
})
}
91 changes: 66 additions & 25 deletions cmd/buildingblock/approve_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ func newApproveRun() *cobra.Command {
var (
output internal.OutputFlag
buildingBlockUuid uuid.UUID
runUuid uuid.UUID
detectRun uuid.UUID
)

cmd := &cobra.Command{
Expand All @@ -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 <run-uuid>' 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 {
Expand All @@ -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
}
Loading
Loading