-
Notifications
You must be signed in to change notification settings - Fork 221
/
machines.go
375 lines (306 loc) · 9.17 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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
package status
import (
"context"
"fmt"
"sort"
"strconv"
"strings"
"github.com/superfly/flyctl/api"
"github.com/superfly/flyctl/client"
"github.com/superfly/flyctl/flaps"
"github.com/superfly/flyctl/internal/command/postgres"
"github.com/superfly/flyctl/internal/config"
"github.com/superfly/flyctl/internal/render"
"github.com/superfly/flyctl/iostreams"
)
func getFromMetadata(m *api.Machine, key string) string {
if m.Config != nil && m.Config.Metadata != nil {
return m.Config.Metadata[key]
}
return ""
}
func getProcessgroup(m *api.Machine) string {
name := m.ProcessGroup()
if name != "" {
return name
}
return "<default>"
}
func getReleaseVersion(m *api.Machine) string {
return getFromMetadata(m, api.MachineConfigMetadataKeyFlyReleaseVersion)
}
// getImage returns the image on the most recent machine released under an app.
func getImage(machines []*api.Machine) (string, error) {
// for context, see this comment https://github.com/superfly/flyctl/pull/1709#discussion_r1110466239
versionToImage := map[int]string{}
for _, machine := range machines {
rv := getReleaseVersion(machine)
if rv == "" {
continue
}
version, err := strconv.Atoi(rv)
if err != nil {
return "", fmt.Errorf("could not parse release version (%s)", rv)
}
versionToImage[version] = machine.ImageRefWithVersion()
}
highestVersion, latestImage := 0, "-"
for version, image := range versionToImage {
if version > highestVersion {
latestImage = image
highestVersion = version
}
}
return latestImage, nil
}
func renderMachineStatus(ctx context.Context, app *api.AppCompact) error {
var (
io = iostreams.FromContext(ctx)
colorize = io.ColorScheme()
client = client.FromContext(ctx).API()
jsonOutput = config.FromContext(ctx).JSONOutput
)
flapsClient, err := flaps.New(ctx, app)
if err != nil {
return err
}
machines, err := flapsClient.ListActive(ctx)
if err != nil {
return err
}
sort.Slice(machines, func(i, j int) bool {
return machines[i].ID < machines[j].ID
})
if jsonOutput {
return renderMachineJSONStatus(ctx, app, machines)
}
if app.IsPostgresApp() {
return renderPGStatus(ctx, app, machines)
}
// Tracks latest eligible version
var latest *api.ImageVersion
var updatable []*api.Machine
for _, machine := range machines {
image := fmt.Sprintf("%s:%s", machine.ImageRef.Repository, machine.ImageRef.Tag)
latestImage, err := client.GetLatestImageDetails(ctx, image)
if err != nil && strings.Contains(err.Error(), "Unknown repository") {
continue
}
if err != nil {
return fmt.Errorf("unable to fetch latest image details for %s: %w", image, err)
}
if latest == nil {
latest = latestImage
}
// Exclude machines that are already running the latest version
if machine.ImageRef.Digest == latest.Digest {
continue
}
updatable = append(updatable, machine)
}
if len(updatable) > 0 {
msgs := []string{"Updates available:\n\n"}
for _, machine := range updatable {
latestStr := fmt.Sprintf("%s:%s (%s)", latest.Repository, latest.Tag, latest.Version)
msg := fmt.Sprintf("Machine %q %s -> %s\n", machine.ID, machine.ImageRefWithVersion(), latestStr)
msgs = append(msgs, msg)
}
fmt.Fprintln(io.Out, colorize.Yellow(strings.Join(msgs, "")))
fmt.Fprintln(io.ErrOut, colorize.Yellow("Run `flyctl image update` to migrate to the latest image version."))
}
managed, unmanaged := []*api.Machine{}, []*api.Machine{}
for _, machine := range machines {
if machine.IsAppsV2() {
managed = append(managed, machine)
} else {
unmanaged = append(unmanaged, machine)
}
}
image, err := getImage(managed)
if err != nil {
return err
}
obj := [][]string{{app.Name, app.Organization.Slug, app.Hostname, image, app.PlatformVersion}}
if err := render.VerticalTable(io.Out, "App", obj, "Name", "Owner", "Hostname", "Image", "Platform"); err != nil {
return err
}
if len(managed) > 0 {
rows := [][]string{}
for _, machine := range managed {
rows = append(rows, []string{
machine.ID,
getProcessgroup(machine),
getReleaseVersion(machine),
machine.Region,
machine.State,
render.MachineHealthChecksSummary(machine),
machine.UpdatedAt,
})
}
err := render.Table(io.Out, "Machines", rows, "ID", "Process", "Version", "Region", "State", "Health Checks", "Last Updated")
if err != nil {
return err
}
}
if len(unmanaged) > 0 {
msg := fmt.Sprintf("Found machines that aren't part of the Fly Apps Platform, run %s to see them.\n", io.ColorScheme().Yellow("fly machines list"))
fmt.Fprint(io.ErrOut, msg)
}
return nil
}
func renderMachineJSONStatus(ctx context.Context, app *api.AppCompact, machines []*api.Machine) error {
var (
out = iostreams.FromContext(ctx).Out
client = client.FromContext(ctx).API()
)
versionQuery := `
query ($appName: String!) {
app(name:$appName) {
currentRelease:currentReleaseUnprocessed {
version
}
}
}
`
req := client.NewRequest(versionQuery)
req.Var("appName", app.Name)
resp, err := client.RunWithContext(ctx, req)
if err != nil {
return fmt.Errorf("could not get current release for app '%s': %w", app.Name, err)
}
version := 0
if resp.App.CurrentRelease != nil {
version = resp.App.CurrentRelease.Version
}
machinesToShow := []*api.Machine{}
if app.IsPostgresApp() {
machinesToShow = machines
} else {
for _, machine := range machines {
if machine.IsAppsV2() {
machinesToShow = append(machinesToShow, machine)
}
}
}
status := map[string]any{
"ID": app.ID,
"Name": app.Name,
"Deployed": app.Deployed,
"Status": app.Status,
"Hostname": app.Hostname,
"Version": version,
"AppURL": app.AppURL,
"Organization": app.Organization,
"PlatformVersion": app.PlatformVersion,
"Machines": machinesToShow,
}
return render.JSON(out, status)
}
func renderPGStatus(ctx context.Context, app *api.AppCompact, machines []*api.Machine) (err error) {
var (
io = iostreams.FromContext(ctx)
colorize = io.ColorScheme()
client = client.FromContext(ctx).API()
)
if len(machines) > 0 {
if postgres.IsFlex(machines[0]) {
yes, note := isQuorumMet(machines)
if !yes {
fmt.Fprintf(io.Out, colorize.Yellow(note))
}
}
} else {
fmt.Fprintf(io.Out, "No machines are available on this app %s\n", app.Name)
return
}
// Tracks latest eligible version
var latest *api.ImageVersion
var updatable []*api.Machine
for _, machine := range machines {
image := fmt.Sprintf("%s:%s", machine.ImageRef.Repository, machine.ImageRef.Tag)
latestImage, err := client.GetLatestImageDetails(ctx, image)
if err != nil && strings.Contains(err.Error(), "Unknown repository") {
continue
}
if err != nil {
return fmt.Errorf("unable to fetch latest image details for %s: %w", image, err)
}
if latest == nil {
latest = latestImage
}
if latest.Tag != latestImage.Tag {
return fmt.Errorf("major version mismatch detected")
}
// Exclude machines that are already running the latest version
if machine.ImageRef.Digest == latest.Digest {
continue
}
updatable = append(updatable, machine)
}
if len(updatable) > 0 {
msgs := []string{"Updates available:\n\n"}
for _, machine := range updatable {
latestStr := fmt.Sprintf("%s:%s (%s)", latest.Repository, latest.Tag, latest.Version)
msg := fmt.Sprintf("Machine %q %s -> %s\n", machine.ID, machine.ImageRefWithVersion(), latestStr)
msgs = append(msgs, msg)
}
fmt.Fprintln(io.ErrOut, colorize.Yellow(strings.Join(msgs, "")))
fmt.Fprintln(io.ErrOut, colorize.Yellow("Run `flyctl image update` to migrate to the latest image version."))
}
rows := [][]string{}
for _, machine := range machines {
role := "unknown"
for _, check := range machine.Checks {
if check.Name == "role" {
if check.Status == "passing" {
role = check.Output
} else {
role = "error"
}
}
}
rows = append(rows, []string{
machine.ID,
machine.State,
role,
machine.Region,
render.MachineHealthChecksSummary(machine),
machine.ImageRefWithVersion(),
machine.CreatedAt,
machine.UpdatedAt,
})
}
return render.Table(io.Out, "", rows, "ID", "State", "Role", "Region", "Health checks", "Image", "Created", "Updated")
}
func isQuorumMet(machines []*api.Machine) (bool, string) {
primaryRegion := machines[0].Config.Env["PRIMARY_REGION"]
totalPrimary := 0
activePrimary := 0
total := 0
inactive := 0
for _, m := range machines {
isPrimaryRegion := m.Region == primaryRegion
if isPrimaryRegion {
totalPrimary++
}
if m.IsActive() {
if isPrimaryRegion {
activePrimary++
}
} else {
inactive++
}
total++
}
quorum := total/2 + 1
totalActive := (total - inactive)
// Verify that we meet basic quorum requirements.
if totalActive <= quorum {
return false, fmt.Sprintf("WARNING: Cluster size does not meet requirements for HA (expected >= 3, got %d)\n", totalActive)
}
// If quorum is met, verify that we have at least 2 active nodes within the primary region.
if totalActive > 2 && activePrimary < 2 {
return false, fmt.Sprintf("WARNING: Cluster size within the PRIMARY_REGION %q does not meet requirements for HA (expected >= 2, got %d)\n", primaryRegion, totalPrimary)
}
return true, ""
}