github.com/scaleway/scaleway-cli@v1.11.1/pkg/commands/stop.go (about) 1 // Copyright (C) 2015 Scaleway. All rights reserved. 2 // Use of this source code is governed by a MIT-style 3 // license that can be found in the LICENSE.md file. 4 5 package commands 6 7 import ( 8 "fmt" 9 "time" 10 11 "github.com/Sirupsen/logrus" 12 "github.com/scaleway/scaleway-cli/pkg/api" 13 ) 14 15 // StopArgs are flags for the `RunStop` function 16 type StopArgs struct { 17 Terminate bool 18 Wait bool 19 Servers []string 20 } 21 22 // RunStop is the handler for 'scw stop' 23 func RunStop(ctx CommandContext, args StopArgs) error { 24 // FIXME: parallelize stop when stopping multiple servers 25 hasError := false 26 for _, needle := range args.Servers { 27 serverID, err := ctx.API.GetServerID(needle) 28 if err != nil { 29 return err 30 } 31 action := "poweroff" 32 if args.Terminate { 33 action = "terminate" 34 } 35 if err = ctx.API.PostServerAction(serverID, action); err != nil { 36 if err.Error() != "server should be running" && err.Error() != "server is being stopped or rebooted" { 37 logrus.Warningf("failed to stop server %s: %s", serverID, err) 38 hasError = true 39 } 40 } else { 41 if args.Wait { 42 // We wait for 10 seconds which is the minimal amount of time needed for a server to stop 43 time.Sleep(10 * time.Second) 44 if _, err = api.WaitForServerStopped(ctx.API, serverID); err != nil { 45 logrus.Errorf("failed to wait for server %s: %v", serverID, err) 46 hasError = true 47 } 48 } 49 if args.Terminate { 50 ctx.API.Cache.RemoveServer(serverID) 51 } 52 fmt.Fprintln(ctx.Stdout, needle) 53 } 54 } 55 56 if hasError { 57 return fmt.Errorf("at least 1 server failed to be stopped") 58 } 59 return nil 60 }