Skip to content

Database governance built for humans and agents — controlling changes and access across every major database.

chore(action): cancel rollout on SIGINT (#15994)

p0nyfc23320e207b
diff --git a/action/api.go b/action/api.go
index 5c0d4a1067..8f596e7d14 100644
--- a/action/api.go
+++ b/action/api.go
@@ -315,3 +315,60 @@ func (c *Client) batchRunTasks(r *v1pb.BatchRunTasksRequest) (*v1pb.BatchRunTask
}
return resp, nil
}
+
+func (c *Client) listTaskRuns(r *v1pb.ListTaskRunsRequest) (*v1pb.ListTaskRunsResponse, error) {
+ req, err := http.NewRequest("GET", fmt.Sprintf("%s/v1/%s/taskRuns", c.url, r.Parent), nil)
+ if err != nil {
+ return nil, err
+ }
+ body, err := c.doRequest(req)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to list task runs")
+ }
+ resp := &v1pb.ListTaskRunsResponse{}
+ if err := protojsonUnmarshaler.Unmarshal(body, resp); err != nil {
+ return nil, err
+ }
+ return resp, nil
+}
+
+func (c *Client) listAllTaskRuns(rolloutName string) (*v1pb.ListTaskRunsResponse, error) {
+ resp := &v1pb.ListTaskRunsResponse{}
+ request := &v1pb.ListTaskRunsRequest{
+ Parent: rolloutName + "/stages/-/tasks/-",
+ PageSize: 1000,
+ PageToken: "",
+ }
+ for {
+ listResp, err := c.listTaskRuns(request)
+ if err != nil {
+ return nil, err
+ }
+ resp.TaskRuns = append(resp.TaskRuns, listResp.TaskRuns...)
+ if listResp.NextPageToken == "" {
+ break
+ }
+ request.PageToken = listResp.NextPageToken
+ }
+ return resp, nil
+}
+
+func (c *Client) batchCancelTaskRuns(r *v1pb.BatchCancelTaskRunsRequest) (*v1pb.BatchCancelTaskRunsResponse, error) {
+ rb, err := protojson.Marshal(r)
+ if err != nil {
+ return nil, err
+ }
+ req, err := http.NewRequest("POST", fmt.Sprintf("%s/v1/%s/taskRuns:batchCancel", c.url, r.Parent), bytes.NewReader(rb))
+ if err != nil {
+ return nil, err
+ }
+ body, err := c.doRequest(req)
+ if err != nil {
+ return nil, errors.Wrapf(err, "failed to batch cancel task runs")
+ }
+ resp := &v1pb.BatchCancelTaskRunsResponse{}
+ if err := protojsonUnmarshaler.Unmarshal(body, resp); err != nil {
+ return nil, err
+ }
+ return resp, nil
+}
diff --git a/action/main.go b/action/main.go
index 34a2c34d44..73447a2ccd 100644
--- a/action/main.go
+++ b/action/main.go
@@ -6,12 +6,15 @@ import (
"log/slog"
"net/url"
"os"
+ "os/signal"
"slices"
"strings"
+ "syscall"
"time"
"github.com/pkg/errors"
"github.com/spf13/cobra"
+ "go.uber.org/multierr"
"github.com/bytebase/bytebase/action/github"
"github.com/bytebase/bytebase/backend/common/log"
@@ -82,12 +85,6 @@ func init() {
cmd.AddCommand(cmdRollout)
}
-func Execute() error {
- // TODO(p0ny): on sigint handling cancel rollout if any
- ctx := context.Background()
- return cmd.ExecuteContext(ctx)
-}
-
func validateSharedFlags(*cobra.Command, []string) error {
if Config.ServiceAccount == "" {
return errors.Errorf("service-account is required and cannot be empty")
@@ -199,11 +196,22 @@ func runRollout(command *cobra.Command, _ []string) error {
return errors.Wrapf(err, "failed to preview plan")
}
+ specCount := 0
+ for _, step := range planPreview.GetPlan().GetSteps() {
+ specCount += len(step.GetSpecs())
+ }
+ if specCount == 0 {
+ slog.Info("no change required. exiting...")
+ return nil
+ }
+
planCreated, err := client.createPlan(Config.Project, planPreview.Plan)
if err != nil {
return errors.Wrapf(err, "failed to create plan")
}
+ slog.Info("plan created", "url", fmt.Sprintf("%s/%s", client.url, planCreated.Name))
+
if err := runAndWaitForPlanChecks(ctx, client, planCreated.Name); err != nil {
return errors.Wrapf(err, "failed to run and wait for plan checks")
}
@@ -219,7 +227,7 @@ func runAndWaitForPlanChecks(ctx context.Context, client *Client, planName strin
if Config.CheckPlan == "SKIP" {
return nil
}
-
+ slog.Info("running plan checks")
_, err := client.runPlanChecks(&v1pb.RunPlanChecksRequest{
Name: planName,
})
@@ -271,6 +279,7 @@ func runAndWaitForPlanChecks(ctx context.Context, client *Client, planName strin
if runningCount == 0 {
break
}
+ slog.Info("waiting for plan checks to complete", "runningCount", runningCount)
time.Sleep(5 * time.Second)
}
@@ -334,6 +343,40 @@ func waitForRollout(ctx context.Context, client *Client, rolloutPreview *v1pb.Ro
}
}))
+ defer func() {
+ if ctx.Err() == nil {
+ return
+ }
+ slog.Info("context cancelled, canceling the rollout")
+ // cancel rollout
+ if err := func() error {
+ taskRuns, err := client.listAllTaskRuns(rolloutName)
+ if err != nil {
+ return errors.Wrapf(err, "failed to list task runs")
+ }
+ taskRunsToCancelByStage := map[string][]string{}
+ for _, taskRun := range taskRuns.TaskRuns {
+ if taskRun.Status == v1pb.TaskRun_RUNNING || taskRun.Status == v1pb.TaskRun_PENDING {
+ stage := strings.Split(taskRun.Name, "/tasks")[0]
+ taskRunsToCancelByStage[stage] = append(taskRunsToCancelByStage[stage], taskRun.Name)
+ }
+ }
+ var errs error
+ for stage, taskRuns := range taskRunsToCancelByStage {
+ _, err := client.batchCancelTaskRuns(&v1pb.BatchCancelTaskRunsRequest{
+ Parent: stage + "/tasks/-",
+ TaskRuns: taskRuns,
+ })
+ if err != nil {
+ err = errors.Wrapf(err, "failed to cancel task runs for stage %v", stage)
+ errs = multierr.Append(errs, err)
+ }
+ }
+ return errs
+ }(); err != nil {
+ slog.Error("failed to cancel rollout", "error", err)
+ }
+ }()
i := 0
for {
if ctx.Err() != nil {
@@ -404,13 +447,15 @@ func waitForRollout(ctx context.Context, client *Client, rolloutPreview *v1pb.Ro
}
// run stage tasks
- if _, err := client.batchRunTasks(&v1pb.BatchRunTasksRequest{
- Parent: stage.Name,
- Tasks: notStartedTasks,
- }); err != nil {
- // ignore retryable error.
- if !strings.Contains(err.Error(), "cannot create pending task runs because there are pending/running/done task runs") {
- return errors.Wrapf(err, "failed to batch create tasks")
+ if len(notStartedTasks) > 0 {
+ if _, err := client.batchRunTasks(&v1pb.BatchRunTasksRequest{
+ Parent: stage.Name,
+ Tasks: notStartedTasks,
+ }); err != nil {
+ // ignore retryable error.
+ if !strings.Contains(err.Error(), "cannot create pending task runs because there are pending/running/done task runs") {
+ return errors.Wrapf(err, "failed to batch create tasks")
+ }
}
}
time.Sleep(5 * time.Second)
@@ -419,7 +464,19 @@ func waitForRollout(ctx context.Context, client *Client, rolloutPreview *v1pb.Ro
}
func main() {
- if err := cmd.Execute(); err != nil {
+ ctx, cancel := context.WithCancel(context.Background())
+ c := make(chan os.Signal, 1)
+ // Trigger graceful shutdown on SIGINT or SIGTERM.
+ // The default signal sent by the `kill` command is SIGTERM,
+ // which is taken as the graceful shutdown signal for many systems, eg., Kubernetes, Gunicorn.
+ signal.Notify(c, os.Interrupt, syscall.SIGTERM)
+ go func() {
+ sig := <-c
+ slog.Info(fmt.Sprintf("%s received.", sig.String()))
+ cancel()
+ }()
+
+ if err := cmd.ExecuteContext(ctx); err != nil {
slog.Error("failed to execute command", log.BBError(err))
os.Exit(1)
}