github.com/scaleway/scaleway-cli@v1.11.1/pkg/commands/restart.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 "sync" 10 "time" 11 12 "github.com/Sirupsen/logrus" 13 "github.com/scaleway/scaleway-cli/pkg/api" 14 ) 15 16 // RestartArgs are flags for the `RunRestart` function 17 type RestartArgs struct { 18 Wait bool 19 Timeout float64 20 Servers []string 21 } 22 23 // restartIdentifiers resolves server IDs, restarts, and waits for them to be ready (-w) 24 func restartIdentifiers(ctx CommandContext, wait bool, servers []string, cr chan string) { 25 var wg sync.WaitGroup 26 for _, needle := range servers { 27 wg.Add(1) 28 go func(needle string) { 29 res := "" 30 31 defer wg.Done() 32 server, err := ctx.API.GetServerID(needle) 33 if err != nil { 34 logrus.Error(err) 35 } else { 36 res = server 37 err := ctx.API.PostServerAction(server, "reboot") 38 if err != nil { 39 if err.Error() != "server is being stopped or rebooted" { 40 logrus.Errorf("failed to restart server %s: %s", server, err) 41 } 42 res = "" 43 } else { 44 if wait { 45 // FIXME: handle gateway 46 api.WaitForServerReady(ctx.API, server, "") 47 } 48 } 49 } 50 cr <- res 51 }(needle) 52 } 53 wg.Wait() 54 close(cr) 55 } 56 57 // RunRestart is the handler for 'scw restart' 58 func RunRestart(ctx CommandContext, args RestartArgs) error { 59 if args.Wait && args.Timeout > 0 { 60 go func() { 61 time.Sleep(time.Duration(args.Timeout*1000) * time.Millisecond) 62 // FIXME: avoid use of fatalf 63 logrus.Fatalf("Operation timed out") 64 }() 65 } 66 67 cr := make(chan string) 68 go restartIdentifiers(ctx, args.Wait, args.Servers, cr) 69 hasError := false 70 71 for { 72 uuid, more := <-cr 73 if !more { 74 break 75 } 76 if len(uuid) > 0 { 77 fmt.Fprintln(ctx.Stdout, uuid) 78 } else { 79 hasError = true 80 } 81 } 82 83 if hasError { 84 return fmt.Errorf("at least 1 server failed to restart") 85 } 86 return nil 87 }