-
Notifications
You must be signed in to change notification settings - Fork 221
/
barman.go
551 lines (451 loc) · 13 KB
/
barman.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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
package postgres
import (
"context"
"fmt"
"log"
"time"
"github.com/pkg/errors"
"github.com/samber/lo"
"github.com/spf13/cobra"
fly "github.com/superfly/fly-go"
"github.com/superfly/fly-go/flaps"
"github.com/superfly/flyctl/agent"
"github.com/superfly/flyctl/internal/appconfig"
"github.com/superfly/flyctl/internal/buildinfo"
"github.com/superfly/flyctl/internal/command"
"github.com/superfly/flyctl/internal/command/apps"
"github.com/superfly/flyctl/internal/command/ssh"
"github.com/superfly/flyctl/internal/flag"
"github.com/superfly/flyctl/internal/flapsutil"
"github.com/superfly/flyctl/internal/flyutil"
mach "github.com/superfly/flyctl/internal/machine"
"github.com/superfly/flyctl/internal/prompt"
"github.com/superfly/flyctl/internal/sentry"
"github.com/superfly/flyctl/iostreams"
"github.com/superfly/flyctl/ip"
)
var (
volumeName = "barman_data"
volumePath = "/data"
Duration10s, _ = time.ParseDuration("10s")
Duration15s, _ = time.ParseDuration("15s")
CheckPathConnection = "/flycheck/connection"
CheckPathRole = "/flycheck/role"
CheckPathVm = "/flycheck/vm"
)
func newBarman() *cobra.Command {
const (
short = "Manage databases in a cluster"
long = short + "\n"
)
cmd := command.New("barman", short, long, nil)
cmd.AddCommand(
newCreateBarman(),
newCheckBarman(),
newBarmanListBackup(),
newBarmanShowBackup(),
newBarmanBackup(),
newBarmanSwitchWal(),
newBarmanRecover(),
)
flag.Add(cmd, flag.JSONOutput())
return cmd
}
func newCreateBarman() *cobra.Command {
const (
short = "create barman machine"
long = short + "\n"
usage = "create"
)
cmd := command.New(usage, short, long, runBarmanCreate,
command.RequireSession,
command.RequireAppName,
)
flag.Add(
cmd,
flag.Region(),
flag.App(),
flag.AppConfig(),
flag.String{
Name: "vm-size",
Description: "the size of the VM",
},
flag.Int{
Name: "volume-size",
Description: "The volume size in GB",
},
)
return cmd
}
func runBarmanCreate(ctx context.Context) error {
var (
io = iostreams.FromContext(ctx)
client = flyutil.ClientFromContext(ctx)
appName = appconfig.NameFromContext(ctx)
)
flapsClient, err := flapsutil.NewClientWithOptions(ctx, flaps.NewClientOpts{
AppName: appName,
})
if err != nil {
return err
}
ctx = flapsutil.NewContextWithClient(ctx, flapsClient)
// pre-fetch platform regions for later use
prompt.PlatformRegions(ctx)
app, err := client.GetAppCompact(ctx, appName)
if err != nil {
return fmt.Errorf("failed retrieving app %s: %w", appName, err)
}
if !app.IsPostgresApp() {
return fmt.Errorf("app %s is not a postgres app", appName)
}
ctx, err = apps.BuildContext(ctx, app)
if err != nil {
return err
}
var region *fly.Region
region, err = prompt.Region(ctx, !app.Organization.PaidPlan, prompt.RegionParams{
Message: "Select a region. Prefer closer to the primary",
})
if err != nil {
return err
}
machineConfig := fly.MachineConfig{}
machineConfig.Env = map[string]string{
"IS_BARMAN": "true",
"PRIMARY_REGION": region.Code,
}
// Set VM resources
vmSizeString := flag.GetString(ctx, "vm-size")
vmSize, err := resolveVMSize(ctx, vmSizeString)
if err != nil {
return err
}
machineConfig.Guest = &fly.MachineGuest{
CPUKind: vmSize.CPUClass,
CPUs: int(vmSize.CPUCores),
MemoryMB: vmSize.MemoryMB,
}
// Metrics
machineConfig.Metrics = &fly.MachineMetrics{
Path: "/metrics",
Port: 9187,
}
machineConfig.Checks = map[string]fly.MachineCheck{
"connection": {
Port: fly.Pointer(5500),
Type: fly.Pointer("http"),
HTTPPath: &CheckPathConnection,
Interval: &fly.Duration{Duration: Duration15s},
Timeout: &fly.Duration{Duration: Duration10s},
},
"role": {
Port: fly.Pointer(5500),
Type: fly.Pointer("http"),
HTTPPath: &CheckPathRole,
Interval: &fly.Duration{Duration: Duration15s},
Timeout: &fly.Duration{Duration: Duration10s},
},
"vm": {
Port: fly.Pointer(5500),
Type: fly.Pointer("http"),
HTTPPath: &CheckPathVm,
Interval: &fly.Duration{Duration: Duration15s},
Timeout: &fly.Duration{Duration: Duration10s},
},
}
// Metadata
machineConfig.Metadata = map[string]string{
fly.MachineConfigMetadataKeyFlyctlVersion: buildinfo.Version().String(),
fly.MachineConfigMetadataKeyFlyPlatformVersion: fly.MachineFlyPlatformVersion2,
fly.MachineConfigMetadataKeyFlyManagedPostgres: "true",
"managed-by-fly-deploy": "true",
"fly-barman": "true",
}
// Restart policy
machineConfig.Restart = &fly.MachineRestart{
Policy: fly.MachineRestartPolicyAlways,
}
imageRepo := "flyio/postgres-flex"
imageRef, err := client.GetLatestImageTag(ctx, imageRepo, nil)
if err != nil {
return err
}
machineConfig.Image = imageRef
var vol *fly.Volume
volInput := fly.CreateVolumeRequest{
Name: volumeName,
Region: region.Code,
SizeGb: fly.Pointer(flag.GetInt(ctx, "volume-size")),
Encrypted: fly.Pointer(true),
RequireUniqueZone: fly.Pointer(true),
ComputeRequirements: machineConfig.Guest,
ComputeImage: machineConfig.Image,
}
if *volInput.SizeGb == 0 {
otherVolumes, err := flapsClient.GetVolumes(ctx)
if err != nil {
return err
}
suggestedSize := 1
for _, volume := range otherVolumes {
if volume.Name == "pg_data" {
suggestedSize = volume.SizeGb
}
}
if err = prompt.Int(ctx, volInput.SizeGb, "Volume size (should be at least the size of the other volumes)", suggestedSize, false); err != nil {
return err
}
}
fmt.Fprintf(io.Out, "Provisioning volume with %dGB\n", volInput.SizeGb)
vol, err = flapsClient.CreateVolume(ctx, volInput)
if err != nil {
return fmt.Errorf("failed to create volume: %w", err)
}
machineConfig.Mounts = append(machineConfig.Mounts, fly.MachineMount{
Volume: vol.ID,
Path: volumePath,
})
launchInput := fly.LaunchMachineInput{
Name: "barman",
Region: volInput.Region,
Config: &machineConfig,
}
fmt.Fprintf(io.Out, "Provisioning barman machine with image %s\n", machineConfig.Image)
machine, err := flapsClient.Launch(ctx, launchInput)
if err != nil {
return err
}
fmt.Fprintf(io.Out, "Waiting for machine to start...\n")
waitTimeout := time.Minute * 5
err = mach.WaitForStartOrStop(ctx, machine, "start", waitTimeout)
if err != nil {
return err
}
fmt.Fprintf(io.Out, "Machine %s is %s\n", machine.ID, machine.State)
return nil
}
func newCheckBarman() *cobra.Command {
const (
long = `Check your barman connection`
short = long
usage = "check"
)
cmd := command.New(usage, short, long, runBarmanCheck, command.RequireSession, command.LoadAppNameIfPresent)
flag.Add(cmd,
flag.App(),
flag.AppConfig(),
)
return cmd
}
func newBarmanListBackup() *cobra.Command {
const (
long = `List your barman backups`
short = long
usage = "list-backup"
)
cmd := command.New(usage, short, long, runBarmanListBackup, command.RequireSession, command.LoadAppNameIfPresent)
flag.Add(cmd,
flag.App(),
flag.AppConfig(),
)
return cmd
}
func newBarmanShowBackup() *cobra.Command {
const (
long = `Show a single barman backup`
short = long
usage = "show-backup <backup-id>"
)
cmd := command.New(usage, short, long, runBarmanShowBackup, command.RequireSession, command.LoadAppNameIfPresent)
cmd.Args = cobra.ExactArgs(1)
flag.Add(cmd,
flag.App(),
flag.AppConfig(),
)
return cmd
}
func newBarmanBackup() *cobra.Command {
const (
long = `Backup your database on barman`
short = long
usage = "backup"
)
cmd := command.New(usage, short, long, runBarmanBackup, command.RequireSession, command.LoadAppNameIfPresent)
flag.Add(cmd,
flag.App(),
flag.AppConfig(),
)
return cmd
}
func newBarmanSwitchWal() *cobra.Command {
const (
long = `Switch WAL to sync barman`
short = long
usage = "switch-wal"
)
cmd := command.New(usage, short, long, runBarmanSwitchWal, command.RequireSession, command.LoadAppNameIfPresent)
flag.Add(cmd,
flag.App(),
flag.AppConfig(),
)
return cmd
}
func newBarmanRecover() *cobra.Command {
const (
long = `Recover primary database with a barman backup`
short = long
usage = "recover <primary machine ID>"
)
cmd := command.New(usage, short, long, runBarmanRecover, command.RequireSession, command.LoadAppNameIfPresent)
cmd.Args = cobra.ExactArgs(1)
flag.Add(cmd,
flag.App(),
flag.AppConfig(),
flag.String{
Name: "backup-id",
Shorthand: "b",
Default: "latest",
Description: "choose one backup ID. Default: latest",
},
flag.String{
Name: "target-time",
Shorthand: "T",
Description: "choose a target time for PITR. Example: \"2023-05-16 20:55:05.958774+00:00\". Default: last WAL file on barman",
},
)
return cmd
}
func captureError(ctx context.Context, err error, app *fly.AppCompact) {
// ignore cancelled errors
if errors.Is(err, context.Canceled) {
return
}
sentry.CaptureException(err,
sentry.WithTraceID(ctx),
sentry.WithTag("feature", "ssh-console"),
sentry.WithContexts(map[string]sentry.Context{
"app": map[string]interface{}{
"name": app.Name,
},
"organization": map[string]interface{}{
"name": app.Organization.Slug,
},
}),
)
}
func runBarmanCheck(ctx context.Context) error {
return runConsole(ctx, "barman check pg")
}
func runBarmanListBackup(ctx context.Context) error {
return runConsole(ctx, "barman list-backup pg")
}
func runBarmanShowBackup(ctx context.Context) error {
io := iostreams.FromContext(ctx)
backupId := flag.FirstArg(ctx)
fmt.Printf("barman show-backup pg %s", backupId)
fmt.Fprintf(io.Out, "barman show-backup pg %s", backupId)
return runConsole(ctx, fmt.Sprintf("barman show-backup pg %s", backupId))
}
func runBarmanBackup(ctx context.Context) error {
return runConsole(ctx, "barman backup pg")
}
func runBarmanSwitchWal(ctx context.Context) error {
return runConsole(ctx, "barman switch-wal pg --force --archive")
}
func runBarmanRecover(ctx context.Context) error {
appName := appconfig.NameFromContext(ctx)
backupId := flag.GetString(ctx, "backup-id")
targetTime := flag.GetString(ctx, "target-time")
primaryMachineId := flag.FirstArg(ctx)
remoteSshCommand := fmt.Sprintf("--remote-ssh-command \"ssh root@%s.vm.%s.internal -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null\" ", primaryMachineId, appName)
if targetTime != "" {
remoteSshCommand += fmt.Sprintf("--target-time \"%s\"", targetTime)
}
cmd := fmt.Sprintf("barman recover pg --get-wal %s /data/postgresql %s", backupId, remoteSshCommand)
log.Printf("Barman server will run the following command: %s", cmd)
return runConsole(ctx, cmd)
}
func runConsole(ctx context.Context, cmd string) error {
client := flyutil.ClientFromContext(ctx)
appName := appconfig.NameFromContext(ctx)
app, err := client.GetAppCompact(ctx, appName)
if err != nil {
return fmt.Errorf("get app: %w", err)
}
agentclient, dialer, err := ssh.BringUpAgent(ctx, client, app, "", false)
if err != nil {
return err
}
addr, err := lookupAddress(ctx, agentclient, dialer, app, true)
if err != nil {
return err
}
params := &ssh.ConnectParams{
Ctx: ctx,
Org: app.Organization,
Dialer: dialer,
Username: "root",
DisableSpinner: false,
AppNames: []string{app.Name},
}
sshc, err := ssh.Connect(params, addr)
if err != nil {
captureError(ctx, err, app)
return err
}
if err := ssh.Console(ctx, sshc, cmd, false); err != nil {
captureError(ctx, err, app)
return err
}
return nil
}
func lookupAddress(ctx context.Context, cli *agent.Client, dialer agent.Dialer, app *fly.AppCompact, console bool) (addr string, err error) {
addr, err = addrForMachines(ctx, app, console)
if err != nil {
return
}
// wait for the addr to be resolved in dns unless it's an ip address
if !ip.IsV6(addr) {
if err := cli.WaitForDNS(ctx, dialer, app.Organization.Slug, addr, ""); err != nil {
captureError(ctx, err, app)
return "", errors.Wrapf(err, "host unavailable at %s", addr)
}
}
return
}
func addrForMachines(ctx context.Context, app *fly.AppCompact, console bool) (addr string, err error) {
// out := iostreams.FromContext(ctx).Out
flapsClient, err := flapsutil.NewClientWithOptions(ctx, flaps.NewClientOpts{
AppCompact: app,
AppName: app.Name,
})
if err != nil {
return "", err
}
machines, err := flapsClient.ListActive(ctx)
if err != nil {
return "", err
}
machines = lo.Filter(machines, func(m *fly.Machine, _ int) bool {
return m.State == "started"
})
if len(machines) < 1 {
return "", fmt.Errorf("app %s has no started VMs", app.Name)
}
if err != nil {
return "", err
}
var selectedMachine *fly.Machine
for _, machine := range machines {
if machine.Config.Env["IS_BARMAN"] != "" {
selectedMachine = machine
}
}
if selectedMachine == nil {
return "", fmt.Errorf("no barman machine found")
}
// No VM was selected or passed as an argument, so just pick the first one for now
// Later, we might want to use 'nearest.of' but also resolve the machine IP to be able to start it
return selectedMachine.PrivateIP, nil
}