-
Notifications
You must be signed in to change notification settings - Fork 223
/
machines.go
311 lines (248 loc) · 7.64 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
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/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 := getFromMetadata(m, api.MachineConfigMetadataKeyFlyProcessGroup)
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()
)
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 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 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 postgres.IsFlex(machines[0]) {
yes, note := isQuorumMet(machines)
if !yes {
fmt.Fprintf(io.Out, colorize.Yellow(note))
}
}
// 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, ""
}