-
Notifications
You must be signed in to change notification settings - Fork 220
/
wait.go
60 lines (53 loc) · 1.56 KB
/
wait.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package machine
import (
"context"
"errors"
"fmt"
"net/http"
"strings"
"time"
"github.com/jpillora/backoff"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/flaps"
)
func WaitForStartOrStop(ctx context.Context, machine *api.Machine, action string, timeout time.Duration) error {
var flapsClient = flaps.FromContext(ctx)
waitCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
var waitOnAction string
switch action {
case "start":
waitOnAction = "started"
case "stop":
waitOnAction = "stopped"
default:
return fmt.Errorf("action must be either start or stop")
}
b := &backoff.Backoff{
Min: 500 * time.Millisecond,
Max: 2 * time.Second,
Factor: 2,
Jitter: false,
}
for {
err := flapsClient.Wait(waitCtx, machine, waitOnAction, 60*time.Second)
if err == nil {
return nil
}
switch {
case errors.Is(waitCtx.Err(), context.Canceled):
return err
case errors.Is(waitCtx.Err(), context.DeadlineExceeded):
return fmt.Errorf("timeout reached waiting for machine to %s %w", waitOnAction, err)
default:
var flapsErr *flaps.FlapsError
if strings.Contains(err.Error(), "machine failed to reach desired state") && machine.Config.Restart.Policy == api.MachineRestartPolicyNo {
return fmt.Errorf("machine failed to reach desired start state, and restart policy was set to %s restart", machine.Config.Restart.Policy)
}
if errors.As(err, &flapsErr) && flapsErr.ResponseStatusCode == http.StatusBadRequest {
return fmt.Errorf("failed waiting for machine: %w", err)
}
time.Sleep(b.Duration())
}
}
}