-
Notifications
You must be signed in to change notification settings - Fork 228
/
vm.go
70 lines (55 loc) · 1.17 KB
/
vm.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
61
62
63
64
65
66
67
68
69
70
package monitor
import (
"context"
"time"
"github.com/superfly/flyctl/api"
)
type UpdateFn func(status string)
func WaitForRunningVM(ctx context.Context, appName string, apiClient *api.Client, timeout time.Duration, update UpdateFn) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
done := make(chan error)
errorCount := 0
go func() {
for {
status, err := apiClient.GetAppStatus(appName, false)
if err != nil {
errorCount += 1
if errorCount < 3 {
continue
}
done <- err
}
isRunning := false
var currentStatus string
if len(runningVMs(status.Allocations)) > 0 {
currentStatus = "running"
isRunning = true
} else {
currentStatus = "starting"
}
update(currentStatus)
if isRunning {
done <- nil
break
}
time.Sleep(1 * time.Second)
}
}()
for {
select {
case <-ctx.Done():
return false, context.Canceled
case err := <-done:
return err == nil, err
}
}
}
func runningVMs(vms []*api.AllocationStatus) (out []*api.AllocationStatus) {
for _, vm := range vms {
if vm.DesiredStatus == "run" && !vm.Transitioning {
out = append(out, vm)
}
}
return
}