-
Notifications
You must be signed in to change notification settings - Fork 15
/
etcd_backup_get.go
98 lines (87 loc) · 1.96 KB
/
etcd_backup_get.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
package cmd
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"github.com/cybozu-go/cke/op"
"github.com/cybozu-go/cke"
"github.com/cybozu-go/well"
"github.com/spf13/cobra"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
func backupGet(ctx context.Context, cmd *cobra.Command, filename string) error {
cfg, err := storage.GetCluster(ctx)
if err != nil {
return err
}
if !cfg.EtcdBackup.Enabled {
return errors.New("etcd backup is disabled")
}
var controlPlane *cke.Node
for _, node := range cfg.Nodes {
if node.ControlPlane {
controlPlane = node
break
}
}
if controlPlane == nil {
return errors.New("control plane not found")
}
cs, err := inf.K8sClient(ctx, controlPlane)
if err != nil {
return err
}
svc, err := cs.CoreV1().Services("kube-system").Get(op.EtcdBackupAppName, metav1.GetOptions{})
if err != nil {
return err
}
if len(svc.Spec.Ports) == 0 {
return errors.New("service.ports is empty")
}
port := svc.Spec.Ports[0].NodePort
nodeIP := cfg.Nodes[0].Address
url := fmt.Sprintf("http://%s:%d/api/v1/backup/%s", nodeIP, port, filename)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return err
}
req = req.WithContext(ctx)
resp, err := inf.HTTPClient().Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
dir, err := os.Getwd()
if err != nil {
return err
}
f, err := os.Create(filepath.Join(dir, filename))
if err != nil {
return err
}
defer f.Close()
cmd.SetOutput(f)
_, err = io.Copy(f, resp.Body)
return err
}
var etcdBackupGetCmd = &cobra.Command{
Use: "get BACKUP_NAME",
Short: "Get an etcd backup",
Long: `Get an etcd backup.
You can find BACKUP_NAME using ckecli etcd backup list`,
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
well.Go(func(ctx context.Context) error {
return backupGet(ctx, cmd, args[0])
})
well.Stop()
return well.Wait()
},
}
func init() {
etcdBackupCmd.AddCommand(etcdBackupGetCmd)
}