-
Notifications
You must be signed in to change notification settings - Fork 224
/
machines.go
305 lines (241 loc) · 7.47 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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
package deploy
import (
"context"
"fmt"
"math"
"strings"
"time"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/client"
"github.com/superfly/flyctl/flaps"
"github.com/superfly/flyctl/internal/app"
"github.com/superfly/flyctl/internal/build/imgsrc"
"github.com/superfly/flyctl/internal/spinner"
"github.com/superfly/flyctl/iostreams"
)
// Deploy ta machines app directly from flyctl, applying the desired config to running machines,
// or launching new ones
func createMachinesRelease(ctx context.Context, config *app.Config, img *imgsrc.DeploymentImage, strategy string) (err error) {
client := client.FromContext(ctx).API()
app, err := client.GetAppCompact(ctx, config.AppName)
if err != nil {
return
}
machineConfig := api.MachineConfig{
Image: img.Tag,
}
// Convert the new, slimmer http service config to standard services
if config.HttpService != nil {
concurrency := config.HttpService.Concurrency
if concurrency != nil {
if concurrency.Type == "" {
concurrency.Type = "requests"
}
if concurrency.HardLimit == 0 {
concurrency.HardLimit = 25
}
if concurrency.SoftLimit == 0 {
concurrency.SoftLimit = int(math.Ceil(float64(concurrency.HardLimit) * 0.8))
}
}
httpService := api.MachineService{
Protocol: "tcp",
InternalPort: config.HttpService.InternalPort,
Concurrency: concurrency,
Ports: []api.MachinePort{
{
Port: 80,
Handlers: []string{"http"},
ForceHttps: config.HttpService.ForceHttps,
},
{
Port: 443,
Handlers: []string{"http", "tls"},
},
},
}
machineConfig.Services = append(machineConfig.Services, httpService)
}
// Copy standard services to the machine vonfig
if config.Services != nil {
machineConfig.Services = append(machineConfig.Services, config.Services...)
}
if config.Env != nil {
machineConfig.Env = config.Env
}
if config.Metrics != nil {
machineConfig.Metrics = config.Metrics
}
if config.Checks != nil {
machineConfig.Checks = config.Checks
}
// Run validations against struct types and their JSON tags
err = config.Validate()
if err != nil {
return err
}
if err := RunReleaseCommand(ctx, app, config, machineConfig); err != nil {
return fmt.Errorf("release command failed - aborting deployment. %w", err)
}
return DeployMachinesApp(ctx, app, strategy, machineConfig, config)
}
func RunReleaseCommand(ctx context.Context, app *api.AppCompact, appConfig *app.Config, machineConfig api.MachineConfig) (err error) {
if appConfig.Deploy == nil || appConfig.Deploy.ReleaseCommand == "" {
return nil
}
io := iostreams.FromContext(ctx)
flapsClient, err := flaps.New(ctx, app)
msg := fmt.Sprintf("Running release command: %s", appConfig.Deploy.ReleaseCommand)
spin := spinner.Run(io, msg)
defer spin.StopWithSuccess()
machineConf := machineConfig
machineConf.Metadata = map[string]string{
"process_group": "release_command",
}
// Override the machine default command to run the release command
machineConf.Init.Cmd = strings.Split(appConfig.Deploy.ReleaseCommand, " ")
launchMachineInput := api.LaunchMachineInput{
AppID: app.ID,
OrgSlug: app.Organization.ID,
Config: &machineConf,
}
// Ensure release commands run in the primary region
if appConfig.PrimaryRegion != "" {
launchMachineInput.Region = appConfig.PrimaryRegion
}
// We don't want temporary release command VMs to serve traffic, so kill the services
machineConf.Services = nil
machine, err := flapsClient.Launch(ctx, launchMachineInput)
if err != nil {
return err
}
removeInput := api.RemoveMachineInput{
AppID: app.Name,
ID: machine.ID,
}
// Make sure we clean up the release command VM
defer flapsClient.Destroy(ctx, removeInput)
// Ensure the command starts running
err = flapsClient.Wait(ctx, machine, "started")
if err != nil {
return err
}
// Wait for the release command VM to stop before moving on
err = flapsClient.Wait(ctx, machine, "stopped")
if err != nil {
return fmt.Errorf("failed determining whether the release command finished. %w", err)
}
var lastExitEvent *api.MachineEvent
var pollMaxAttempts int = 10
var pollAttempts int = 0
// Poll until the 'stopped' event arrives, so we can determine the release command exit status
for {
if pollAttempts >= pollMaxAttempts {
return fmt.Errorf("could not determine whether the release command succeeded, so aborting the deployment")
}
machine, err = flapsClient.Get(ctx, machine.ID)
for _, event := range machine.Events {
if event.Type != "exit" {
continue
}
if lastExitEvent == nil || event.Timestamp > lastExitEvent.Timestamp {
lastExitEvent = event
}
}
if lastExitEvent != nil {
break
}
time.Sleep(1 * time.Second)
pollAttempts += 1
}
exitCode := lastExitEvent.Request.ExitEvent.ExitCode
if exitCode != 0 {
return fmt.Errorf("release command exited with non-zero status of %d", exitCode)
}
return
}
func DeployMachinesApp(ctx context.Context, app *api.AppCompact, strategy string, machineConfig api.MachineConfig, appConfig *app.Config) (err error) {
io := iostreams.FromContext(ctx)
flapsClient, err := flaps.New(ctx, app)
if err != nil {
return
}
if strategy == "" {
strategy = "rolling"
}
var regionCode string
if appConfig != nil {
regionCode = appConfig.PrimaryRegion
}
msg := fmt.Sprintf("Deploying with %s strategy", strategy)
spin := spinner.Run(io, msg)
defer spin.StopWithSuccess()
machineConfig.Metadata = map[string]string{"process_group": "app"}
machineConfig.Init.Cmd = nil
launchInput := api.LaunchMachineInput{
AppID: app.Name,
OrgSlug: app.Organization.ID,
Config: &machineConfig,
Region: regionCode,
}
machines, err := flapsClient.ListActive(ctx)
if err != nil {
return
}
if len(machines) > 0 {
for _, machine := range machines {
leaseTTL := api.IntPointer(30)
lease, err := flapsClient.GetLease(ctx, machine.ID, leaseTTL)
if err != nil {
return err
}
machine.LeaseNonce = lease.Data.Nonce
defer releaseLease(ctx, flapsClient, machine)
}
for _, machine := range machines {
launchInput.ID = machine.ID
// We assume a config with no image specificed means the deploy should recreate machines
// with the existing config. For example, for applying recently set secrets.
if launchInput.Config.Image == "" {
freshMachine, err := flapsClient.Get(ctx, machine.ID)
if err != nil {
return err
}
launchInput.Config = freshMachine.Config
launchInput.Region = machine.Region
}
// Until mounts are supported in fly.toml, ensure deployments
// maintain any existing volume attachments
if machine.Config.Mounts != nil {
launchInput.Config.Mounts = machine.Config.Mounts
}
updateResult, err := flapsClient.Update(ctx, launchInput, machine.LeaseNonce)
if err != nil {
if strategy != "immediate" {
return err
} else {
fmt.Printf("Continuing after error: %s\n", err)
}
}
if strategy != "immediate" {
err = flapsClient.Wait(ctx, updateResult, "started")
if err != nil {
return err
}
}
}
} else {
fmt.Fprintf(io.Out, "Launching VM with image %s\n", launchInput.Config.Image)
_, err = flapsClient.Launch(ctx, launchInput)
if err != nil {
return err
}
}
return
}
func releaseLease(ctx context.Context, client *flaps.Client, machine *api.Machine) {
io := iostreams.FromContext(ctx)
if err := client.ReleaseLease(ctx, machine.ID, machine.LeaseNonce); err != nil {
fmt.Println(io.Out, fmt.Errorf("could not release lease on %s (%w)", machine.ID, err))
}
}