This repository has been archived by the owner on Mar 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 38
/
machines.go
231 lines (208 loc) · 6.82 KB
/
machines.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
package apiv1
import (
"errors"
"fmt"
"github.com/Khan/genqlient/graphql"
hreq "github.com/imroc/req/v3"
"net/http"
"time"
)
var NonceHeader = "fly-machine-lease-nonce"
type MachineAPI struct {
client *graphql.Client
httpClient *hreq.Client
endpoint string
}
type MachineMount struct {
Encrypted bool `json:"encrypted,omitempty"`
Path string `json:"path"`
SizeGb int `json:"size_gb,omitempty"`
Volume string `json:"volume"`
}
type Port struct {
Port int64 `json:"port"`
Handlers []string `json:"handlers"`
}
type Service struct {
Ports []Port `json:"ports"`
Protocol string `json:"protocol"`
InternalPort int64 `json:"internal_port"`
}
type InitConfig struct {
Cmd []string `json:"cmd,omitempty"`
Entrypoint []string `json:"entrypoint,omitempty"`
Exec []string `json:"exec,omitempty"`
}
type MachineConfig struct {
Image string `json:"image"`
Env map[string]string `json:"env"`
Init InitConfig `json:"init,omitempty"`
Mounts []MachineMount `json:"mounts,omitempty"`
Services []Service `json:"services"`
Guest GuestConfig `json:"guest,omitempty"`
}
type GuestConfig struct {
Cpus int `json:"cpus,omitempty"`
MemoryMb int `json:"memory_mb,omitempty"`
CpuType string `json:"cpu_kind,omitempty"`
}
type MachineCreateOrUpdateRequest struct {
Name string `json:"name"`
Region string `json:"region"`
Config MachineConfig `json:"config"`
}
type MachineResponse struct {
ID string `json:"id"`
Name string `json:"name"`
State string `json:"state"`
Region string `json:"region"`
InstanceID string `json:"instance_id"`
PrivateIP string `json:"private_ip"`
Config struct {
Env map[string]string `json:"env"`
Init struct {
Exec []string `json:"exec"`
Entrypoint []string `json:"entrypoint"`
Cmd []string `json:"cmd"`
//Tty bool `json:"tty"`
} `json:"init"`
Image string `json:"image"`
Metadata interface{} `json:"metadata"`
Restart struct {
Policy string `json:"policy"`
} `json:"restart"`
Services []Service `json:"services"`
Mounts []MachineMount `json:"mounts"`
Guest struct {
CPUKind string `json:"cpu_kind"`
Cpus int `json:"cpus"`
MemoryMb int `json:"memory_mb"`
} `json:"guest"`
} `json:"config"`
ImageRef struct {
Registry string `json:"registry"`
Repository string `json:"repository"`
Tag string `json:"tag"`
Digest string `json:"digest"`
Labels struct {
} `json:"labels"`
} `json:"image_ref"`
CreatedAt time.Time `json:"created_at"`
}
type MachineLease struct {
Status string `json:"status"`
Data struct {
Nonce string `json:"nonce"`
ExpiresAt int64 `json:"expires_at"`
Owner string `json:"owner"`
}
}
func NewMachineAPI(httpClient *hreq.Client, endpoint string) *MachineAPI {
return &MachineAPI{
httpClient: httpClient,
endpoint: endpoint,
}
}
func (a *MachineAPI) LockMachine(app string, id string, timeout int) (*MachineLease, error) {
var res MachineLease
_, err := a.httpClient.R().SetResult(&res).Post(fmt.Sprintf("http://%s/v1/apps/%s/machines/%s/lease/?ttl=%d", a.endpoint, app, id, timeout))
if err != nil {
return nil, err
}
return &res, nil
}
func (a *MachineAPI) ReleaseMachine(lease MachineLease, app string, id string) error {
_, err := a.httpClient.R().SetHeader(NonceHeader, lease.Data.Nonce).Delete(fmt.Sprintf("http://%s/v1/apps/%s/machines/%s/lease", a.endpoint, app, id))
if err != nil {
return err
}
return nil
}
func (a *MachineAPI) WaitForMachine(app string, id string, instanceID string) error {
_, err := a.httpClient.R().Get(fmt.Sprintf("http://%s/v1/apps/%s/machines/%s/wait?instance_id=%s", a.endpoint, app, id, instanceID))
return err
}
// CreateMachine takes a MachineCreateOrUpdateRequest and creates the requested machine in the given app and then writes the response into the `res` param
func (a *MachineAPI) CreateMachine(req MachineCreateOrUpdateRequest, app string, res *MachineResponse) error {
if req.Config.Guest.CpuType == "" {
req.Config.Guest.CpuType = "shared"
}
if req.Config.Guest.Cpus == 0 {
req.Config.Guest.Cpus = 1
}
if req.Config.Guest.MemoryMb == 0 {
req.Config.Guest.MemoryMb = 256
}
createResponse, err := a.httpClient.R().SetBody(req).SetResult(res).Post(fmt.Sprintf("http://%s/v1/apps/%s/machines", a.endpoint, app))
if err != nil {
return err
}
if createResponse.StatusCode != http.StatusCreated && createResponse.StatusCode != http.StatusOK {
return errors.New(fmt.Sprintf("Create request failed: %s, %+v", createResponse.Status, res))
}
return nil
}
func (a *MachineAPI) UpdateMachine(req MachineCreateOrUpdateRequest, app string, id string, res *MachineResponse) error {
if req.Config.Guest.CpuType == "" {
req.Config.Guest.CpuType = "shared"
}
if req.Config.Guest.Cpus == 0 {
//You can't have a machine with no cpus
req.Config.Guest.Cpus = 1
}
if req.Config.Guest.MemoryMb == 0 {
//You can't have a machine with no memory
req.Config.Guest.MemoryMb = 256
}
lease, err := a.LockMachine(app, id, 30)
if err != nil {
return err
}
reqRes, err := a.httpClient.R().SetBody(req).SetResult(res).SetHeader(NonceHeader, lease.Data.Nonce).Post(fmt.Sprintf("http://%s/v1/apps/%s/machines/%s", a.endpoint, app, id))
if err != nil {
return err
}
err = a.ReleaseMachine(*lease, app, id)
if err != nil {
return err
}
if reqRes.StatusCode != http.StatusCreated && reqRes.StatusCode != http.StatusOK {
return errors.New(fmt.Sprintf("Update request failed: %s, %+v", reqRes.Status, res))
}
return nil
}
func (a *MachineAPI) ReadMachine(app string, id string, res *MachineResponse) (*hreq.Response, error) {
return a.httpClient.R().SetResult(res).Get(fmt.Sprintf("http://%s/v1/apps/%s/machines/%s", a.endpoint, app, id))
}
func (a *MachineAPI) DeleteMachine(app string, id string, maxRetries int) error {
deleted := false
for i := 0; i < maxRetries; i++ {
var machine MachineResponse
readResponse, err := a.httpClient.R().SetResult(&machine).Get(fmt.Sprintf("http://%s/v1/apps/%s/machines/%s", a.endpoint, app, id))
if err != nil {
return err
}
if readResponse.StatusCode == 200 {
if machine.State == "started" || machine.State == "starting" || machine.State == "replacing" {
_, _ = a.httpClient.R().Post(fmt.Sprintf("http://%s/v1/apps/%s/machines/%s/stop", a.endpoint, app, id))
}
if machine.State == "stopping" || machine.State == "destroying" {
time.Sleep(5 * time.Second)
}
if machine.State == "stopped" || machine.State == "replaced" {
_, err = a.httpClient.R().Delete(fmt.Sprintf("http://%s/v1/apps/%s/machines/%s", a.endpoint, app, id))
if err != nil {
return err
}
}
if machine.State == "destroyed" {
deleted = true
break
}
}
}
if !deleted {
return errors.New("max retries exceeded")
}
return nil
}