-
Notifications
You must be signed in to change notification settings - Fork 20
/
snapshot_export.go
204 lines (165 loc) · 4.39 KB
/
snapshot_export.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
package cmd
import (
"crypto/md5"
"encoding/hex"
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/exoscale/cli/pkg/globalstate"
"github.com/exoscale/cli/pkg/output"
"github.com/exoscale/egoscale"
"github.com/spf13/cobra"
"github.com/vbauerster/mpb/v4"
"github.com/vbauerster/mpb/v4/decor"
)
type snapshotExportOutput struct {
URL string `json:"url"`
Checksum string `json:"checksum"`
}
func (o *snapshotExportOutput) ToJSON() { output.JSON(o) }
func (o *snapshotExportOutput) ToText() { output.Text(o) }
func (o *snapshotExportOutput) ToTable() { output.Table(o) }
var snapshotExportCmd = &cobra.Command{
Use: "export ID",
Short: "Export snapshot",
Long: fmt.Sprintf(`This command exports a volume snapshot.
Supported output template annotations: %s`,
strings.Join(output.TemplateAnnotations(&snapshotExportOutput{}), ", ")),
RunE: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return cmd.Usage()
}
filePath, err := cmd.Flags().GetString("download")
if err != nil {
return err
}
snapshot, err := exportSnapshot(args[0])
if err != nil {
return err
}
if !cmd.Flags().Changed("download") {
return printOutput(&snapshotExportOutput{
URL: snapshot.PresignedURL,
Checksum: snapshot.MD5sum,
}, nil)
}
filePath, err = downloadExportedSnapshot(filePath, snapshot.PresignedURL)
if err != nil {
return err
}
if !globalstate.Quiet {
fmt.Print("Verifying downloaded file checksum... ")
}
if err = checkExportedSnapshot(filePath, snapshot.MD5sum); err != nil {
if !globalstate.Quiet {
fmt.Println("failed")
}
return err
}
if !globalstate.Quiet {
fmt.Println("success")
}
return nil
},
}
func exportSnapshot(snapshotID string) (*egoscale.ExportSnapshotResponse, error) {
id, err := egoscale.ParseUUID(snapshotID)
if err != nil {
return nil, err
}
res, err := asyncRequest(&egoscale.ExportSnapshot{ID: id}, fmt.Sprintf("Exporting snapshot %q", id))
if err != nil {
return nil, err
}
return res.(*egoscale.ExportSnapshotResponse), nil
}
func downloadExportedSnapshot(filePath, url string) (string, error) {
filePath = filepath.ToSlash(filePath)
st, err := os.Stat(filePath)
if err != nil && !os.IsNotExist(err) {
return "", err
}
if st != nil && st.IsDir() {
return "", errors.New("download path must not be an existing directory")
}
if filepath.Ext(filePath) != ".qcow2" {
filePath = filePath + ".qcow2"
}
if _, err = os.Stat(filePath); err == nil {
return "", fmt.Errorf("file %q already exists", filePath)
}
if err = os.MkdirAll(filepath.Dir(filePath), os.ModePerm); err != nil {
return "", err
}
file, err := os.OpenFile(filePath, os.O_CREATE|os.O_WRONLY, 0o600)
if err != nil {
return "", err
}
req, err := http.NewRequestWithContext(gContext, "GET", url, nil)
if err != nil {
return "", err
}
client := http.DefaultClient
resp, err := client.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
size, err := strconv.Atoi(resp.Header.Get("Content-Length"))
if err != nil {
return "", err
}
progress := mpb.NewWithContext(gContext,
mpb.WithWidth(64),
mpb.WithRefreshRate(180*time.Millisecond),
mpb.ContainerOptOn(mpb.WithOutput(nil), func() bool { return globalstate.Quiet }),
)
bar := progress.AddBar(
int64(size),
mpb.BarRemoveOnComplete(),
mpb.PrependDecorators(
decor.Name("Downloading snapshot file... "),
decor.OnComplete(decor.CountersKibiByte("% .2f / % .2f"), "success"),
),
mpb.AppendDecorators(
decor.OnComplete(decor.EwmaETA(decor.ET_STYLE_GO, 90), ""),
decor.OnComplete(decor.Name(""), ""),
),
)
proxyReader := bar.ProxyReader(resp.Body)
defer proxyReader.Close()
if _, err = io.Copy(file, proxyReader); err != nil {
return "", err
}
progress.Wait()
if err = file.Close(); err != nil {
return "", err
}
return filePath, nil
}
func checkExportedSnapshot(filePath, md5sum string) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
hash := md5.New()
if _, err := io.Copy(hash, file); err != nil {
return err
}
h := hex.EncodeToString(hash.Sum(nil))
if h != md5sum {
return fmt.Errorf("checksum mismatch: expected %q, got %q", md5sum, h)
}
return nil
}
func init() {
snapshotCmd.AddCommand(snapshotExportCmd)
snapshotExportCmd.Flags().StringP("download", "d", "", "Path to download exported snapshot")
}