@@ -6,32 +6,80 @@ package commands
66
77import (
88 "fmt"
9+ "sync"
10+ "time"
911
12+ "github.com/scaleway/scaleway-cli/pkg/api"
1013 "github.com/scaleway/scaleway-cli/vendor/github.com/Sirupsen/logrus"
1114)
1215
1316// RestartArgs are flags for the `RunRestart` function
1417type RestartArgs struct {
18+ Wait bool
19+ Timeout float64
1520 Servers []string
1621}
1722
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+ defer wg .Done ()
30+ server := ctx .API .GetServerID (needle )
31+ res := server
32+ err := ctx .API .PostServerAction (server , "reboot" )
33+ if err != nil {
34+ if err .Error () != "server is being stopped or rebooted" {
35+ logrus .Errorf ("failed to restart server %s: %s" , server , err )
36+ }
37+ res = ""
38+ } else {
39+ if wait {
40+ // FIXME: handle gateway
41+ api .WaitForServerReady (ctx .API , server , "" )
42+ }
43+ }
44+ cr <- res
45+ }(needle )
46+ }
47+ wg .Wait ()
48+ close (cr )
49+ }
50+
1851// RunRestart is the handler for 'scw restart'
1952func RunRestart (ctx CommandContext , args RestartArgs ) error {
53+ if args .Wait && args .Timeout > 0 {
54+ go func () {
55+ time .Sleep (time .Duration (args .Timeout * 1000 ) * time .Millisecond )
56+ // FIXME: avoid use of fatalf
57+ logrus .Fatalf ("Operation timed out" )
58+ }()
59+ }
60+
61+ cr := make (chan string )
62+ go restartIdentifiers (ctx , args .Wait , args .Servers , cr )
63+ done := false
2064 hasError := false
21- for _ , needle := range args .Servers {
22- server := ctx .API .GetServerID (needle )
23- err := ctx .API .PostServerAction (server , "reboot" )
24- if err != nil {
25- if err .Error () != "server is being stopped or rebooted" {
26- logrus .Errorf ("failed to restart server %s: %s" , server , err )
65+
66+ for ! done {
67+ select {
68+ case uuid , more := <- cr :
69+ if ! more {
70+ done = true
71+ break
72+ }
73+ if len (uuid ) > 0 {
74+ fmt .Fprintln (ctx .Stdout , uuid )
75+ } else {
2776 hasError = true
2877 }
29- } else {
30- fmt .Fprintln (ctx .Stdout , needle )
31- }
32- if hasError {
33- return fmt .Errorf ("at least 1 server failed to restart" )
3478 }
3579 }
80+
81+ if hasError {
82+ return fmt .Errorf ("at least 1 server failed to restart" )
83+ }
3684 return nil
3785}
0 commit comments