github.com/kolanos/fargate@v0.2.3/cmd/service_scale.go (about) 1 package cmd 2 3 import ( 4 "fmt" 5 "regexp" 6 "strconv" 7 8 "github.com/jpignata/fargate/console" 9 ECS "github.com/jpignata/fargate/ecs" 10 "github.com/spf13/cobra" 11 ) 12 13 const validScalePattern = "[-\\+]?[0-9]+" 14 15 type ScaleServiceOperation struct { 16 ServiceName string 17 DesiredCount int64 18 } 19 20 func (o *ScaleServiceOperation) SetScale(scaleExpression string) { 21 ecs := ECS.New(sess, clusterName) 22 validScale := regexp.MustCompile(validScalePattern) 23 24 if !validScale.MatchString(scaleExpression) { 25 console.ErrorExit(fmt.Errorf("Invalid scale expression %s", scaleExpression), "Invalid command line argument") 26 } 27 28 if scaleExpression[0] == '+' || scaleExpression[0] == '-' { 29 if s, err := strconv.ParseInt(scaleExpression[1:len(scaleExpression)], 10, 64); err == nil { 30 currentDesiredCount := ecs.GetDesiredCount(o.ServiceName) 31 if scaleExpression[0] == '+' { 32 o.DesiredCount = currentDesiredCount + s 33 } else if scaleExpression[0] == '-' { 34 o.DesiredCount = currentDesiredCount - s 35 } 36 } 37 } else if s, err := strconv.ParseInt(scaleExpression, 10, 64); err == nil { 38 o.DesiredCount = s 39 } else { 40 console.ErrorExit(fmt.Errorf("Invalid scale expression %s", scaleExpression), "Invalid command line argument") 41 } 42 43 if o.DesiredCount < 0 { 44 console.ErrorExit(fmt.Errorf("requested scale %d < 0", o.DesiredCount), "Invalid command line argument") 45 } 46 } 47 48 var serviceScaleCmd = &cobra.Command{ 49 Use: "scale <service-name> <scale-expression>", 50 Short: "Changes the number of tasks running for the service", 51 Long: `Scale number of tasks in a service 52 53 Changes the number of desired tasks to be run in a service by the given scale 54 expression. A scale expression can either be an absolute number or a delta 55 specified with a sign such as +5 or -2.`, 56 Args: cobra.ExactArgs(2), 57 Run: func(cmd *cobra.Command, args []string) { 58 operation := &ScaleServiceOperation{ 59 ServiceName: args[0], 60 } 61 62 operation.SetScale(args[1]) 63 64 scaleService(operation) 65 }, 66 } 67 68 func init() { 69 serviceCmd.AddCommand(serviceScaleCmd) 70 } 71 72 func scaleService(operation *ScaleServiceOperation) { 73 ecs := ECS.New(sess, clusterName) 74 75 ecs.SetDesiredCount(operation.ServiceName, operation.DesiredCount) 76 console.Info("Scaled service %s to %d", operation.ServiceName, operation.DesiredCount) 77 }