|
| 1 | +package baremetal |
| 2 | + |
| 3 | +import ( |
| 4 | + "time" |
| 5 | + |
| 6 | + "github.com/scaleway/scaleway-sdk-go/internal/async" |
| 7 | + "github.com/scaleway/scaleway-sdk-go/internal/errors" |
| 8 | + "github.com/scaleway/scaleway-sdk-go/scw" |
| 9 | +) |
| 10 | + |
| 11 | +// WaitForServerRequest is used by WaitForServer method |
| 12 | +type WaitForServerRequest struct { |
| 13 | + ServerID string |
| 14 | + Zone scw.Zone |
| 15 | + Timeout time.Duration |
| 16 | +} |
| 17 | + |
| 18 | +// WaitForServer wait for the server to be in a "terminal state" before returning. |
| 19 | +// This function can be used to wait for a server to be installed for example. |
| 20 | +func (s *API) WaitForServer(req *WaitForServerRequest) (*Server, scw.SdkError) { |
| 21 | + |
| 22 | + terminalStatus := map[ServerStatus]struct{}{ |
| 23 | + ServerStatusReady: {}, |
| 24 | + ServerStatusStopped: {}, |
| 25 | + ServerStatusError: {}, |
| 26 | + ServerStatusUnknown: {}, |
| 27 | + } |
| 28 | + |
| 29 | + installTerminalStatus := map[ServerInstallStatus]struct{}{ |
| 30 | + ServerInstallStatusCompleted: {}, |
| 31 | + ServerInstallStatusToInstall: {}, |
| 32 | + ServerInstallStatusError: {}, |
| 33 | + ServerInstallStatusUnknown: {}, |
| 34 | + } |
| 35 | + |
| 36 | + server, err := async.WaitSync(&async.WaitSyncConfig{ |
| 37 | + Get: func() (interface{}, error, bool) { |
| 38 | + res, err := s.GetServer(&GetServerRequest{ |
| 39 | + ServerID: req.ServerID, |
| 40 | + Zone: req.Zone, |
| 41 | + }) |
| 42 | + |
| 43 | + if err != nil { |
| 44 | + return nil, err, false |
| 45 | + } |
| 46 | + _, isTerminal := terminalStatus[res.Status] |
| 47 | + isTerminalInstall := true |
| 48 | + if res.Install != nil { |
| 49 | + _, isTerminalInstall = installTerminalStatus[res.Install.Status] |
| 50 | + } |
| 51 | + |
| 52 | + return res, err, isTerminal && isTerminalInstall |
| 53 | + }, |
| 54 | + Timeout: req.Timeout, |
| 55 | + IntervalStrategy: async.LinearIntervalStrategy(5 * time.Second), |
| 56 | + }) |
| 57 | + if err != nil { |
| 58 | + return nil, errors.Wrap(err, "waiting for server failed") |
| 59 | + } |
| 60 | + |
| 61 | + return server.(*Server), nil |
| 62 | +} |
0 commit comments