github.com/kolanos/fargate@v0.2.3/cmd/task_stop.go (about)

     1  package cmd
     2  
     3  import (
     4  	"github.com/jpignata/fargate/console"
     5  	ECS "github.com/jpignata/fargate/ecs"
     6  	"github.com/spf13/cobra"
     7  )
     8  
     9  type TaskStopOperation struct {
    10  	TaskGroupName string
    11  	TaskIds       []string
    12  }
    13  
    14  var (
    15  	flagTaskStopTasks []string
    16  )
    17  
    18  var taskStopCmd = &cobra.Command{
    19  	Use:   "stop <task group name>",
    20  	Short: "Stop tasks",
    21  	Long: `Stop tasks
    22  
    23    Stops all tasks within a task group if run with only a task group name or stops
    24    individual tasks if one or more tasks are passed via the --task flag. Specify
    25    --task with a task ID parameter multiple times to stop multiple specific tasks.`,
    26  	Args: cobra.ExactArgs(1),
    27  	Run: func(cmd *cobra.Command, args []string) {
    28  		operation := &TaskStopOperation{
    29  			TaskGroupName: args[0],
    30  			TaskIds:       flagTaskStopTasks,
    31  		}
    32  
    33  		stopTasks(operation)
    34  	},
    35  }
    36  
    37  func init() {
    38  	taskCmd.AddCommand(taskStopCmd)
    39  
    40  	taskStopCmd.Flags().StringSliceVarP(&flagTaskStopTasks, "task", "t", []string{}, "Stop specific task instances (can be specified multiple times)")
    41  }
    42  
    43  func stopTasks(operation *TaskStopOperation) {
    44  	var taskCount int
    45  
    46  	ecs := ECS.New(sess, clusterName)
    47  
    48  	if len(operation.TaskIds) > 0 {
    49  		taskCount = len(operation.TaskIds)
    50  
    51  		ecs.StopTasks(operation.TaskIds)
    52  	} else {
    53  		var taskIds []string
    54  
    55  		tasks := ecs.DescribeTasksForTaskGroup(operation.TaskGroupName)
    56  
    57  		for _, task := range tasks {
    58  			taskIds = append(taskIds, task.TaskId)
    59  		}
    60  
    61  		taskCount = len(taskIds)
    62  
    63  		ecs.StopTasks(taskIds)
    64  	}
    65  
    66  	if taskCount == 1 {
    67  		console.Info("Stopped %d task", taskCount)
    68  	} else {
    69  		console.Info("Stopped %d tasks", taskCount)
    70  	}
    71  }