-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
executable file
·341 lines (300 loc) · 8.05 KB
/
Copy pathmain.go
File metadata and controls
executable file
·341 lines (300 loc) · 8.05 KB
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
// Based on Juned's work in https://github.com/junedkhatri31/docker-volume-snapshot
package main
import (
"bytes"
"context"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"
"github.com/containerd/errdefs"
"github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
"github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/client"
"github.com/spf13/cobra"
"dvs/images"
)
const (
ErrDockerSaidNuhUh string = "Ensure that the Docker daemon is up and running."
Arch string = runtime.GOARCH
)
var rootCmd = &cobra.Command{
Use: "dvs",
Short: "Docker Volume Snapshot (dvs)",
Long: "A tool to create and restore snapshots of Docker volumes.",
}
var createCmd = &cobra.Command{
Use: "create <source_volume> <destination_file>",
Short: "Create snapshot file from docker volume",
Example: "dvs create my_volume my_volume.tar.gz",
// TODO: allow skipping snapshot archive name?
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
cli, err := client.NewClientWithOpts(
client.FromEnv,
client.WithAPIVersionNegotiation(),
)
if err != nil {
fatal(fmt.Sprintf("Unable to create Docker client: %v", err))
}
createSnapshot(ctx, cli, args[0], args[1])
},
}
var restoreCmd = &cobra.Command{
Use: "restore <snapshot_file> <destination_volume>",
Short: "Restore snapshot file to docker volume",
Example: "dvs restore my_volume.tar.gz my_volume",
Args: cobra.ExactArgs(2),
Run: func(cmd *cobra.Command, args []string) {
ctx := context.Background()
cli, err := client.NewClientWithOpts(
client.FromEnv,
client.WithAPIVersionNegotiation(),
)
if err != nil {
fatal(fmt.Sprintf("Unable to create Docker client: %v", err))
}
restoreSnapshot(ctx, cli, args[0], args[1])
},
}
func init() {
rootCmd.AddCommand(createCmd)
rootCmd.AddCommand(restoreCmd)
}
func main() {
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func fatal(msg string) {
fmt.Fprintln(os.Stderr, msg)
os.Exit(1)
}
func createSnapshot(
ctx context.Context,
cli *client.Client,
volume string,
outputFile string,
) {
outputDir := resolveDir(outputFile)
ensureDir(outputDir)
filename := filepath.Base(outputFile)
vol := volumeHealthCheck(ctx, cli, volume)
err := validateArchiveFormat(filename)
if err != nil {
fatal(err.Error())
}
fmt.Println("Creating snapshot of volume:", vol)
containerConfig := &container.Config{
Cmd: []string{"tar", "cvaf", "/dest/" + filename, "-C", "/source", "."},
}
hostConfig := &container.HostConfig{
Mounts: []mount.Mount{
{
Type: mount.TypeVolume,
Source: vol,
Target: "/source",
},
{
Type: mount.TypeBind,
Source: outputDir,
Target: "/dest",
},
},
AutoRemove: false,
}
runContainer(ctx, cli, containerConfig, hostConfig)
fmt.Printf("Snapshot created at %s\n", outputFile)
}
func restoreSnapshot(
ctx context.Context,
cli *client.Client,
snapshotPath string,
volume string,
) {
inputDir := resolveDir(snapshotPath)
filename := filepath.Base(snapshotPath)
vol := volumeHealthCheck(ctx, cli, volume)
err := validateArchiveFormat(snapshotPath)
if err != nil {
fatal(err.Error())
}
fmt.Println("Restoring snapshot from:", snapshotPath)
containerConfig := &container.Config{
Cmd: []string{"tar", "xzvf", "/source/" + filename, "-C", "/dest"},
}
hostConfig := &container.HostConfig{
Mounts: []mount.Mount{
{
Type: mount.TypeBind,
Source: inputDir,
Target: "/source",
},
{
Type: mount.TypeVolume,
Source: vol,
Target: "/dest",
},
},
AutoRemove: true,
}
runContainer(ctx, cli, containerConfig, hostConfig)
fmt.Println("Snapshot restored to volume:", vol)
}
func runContainer(
ctx context.Context,
cli *client.Client,
config *container.Config,
hostConfig *container.HostConfig,
) {
if Arch == "" {
fatal("Unsupported architecture: " + Arch)
}
// TODO: add custom dvs tag to not mess with user's images
config.Image = fmt.Sprintf("busybox:%s", Arch)
_, err := cli.ImageInspect(ctx, config.Image)
if err != nil {
if client.IsErrConnectionFailed(err) {
fatal(ErrDockerSaidNuhUh)
}
if errdefs.IsNotFound(err) {
rdr := bytes.NewReader(images.Busybox)
// TODO: consider removing the image so as to not have any user complaints
_, loadErr := cli.ImageLoad(ctx, rdr)
if loadErr != nil {
// offload to docker to figure out the architecture, requires internet
// access
config.Image = "busybox:latest"
out, pullErr := cli.ImagePull(ctx, config.Image, image.PullOptions{})
if pullErr != nil {
fatal("Failed to pull busybox image")
}
defer out.Close()
// Wait for pull to complete by reading the response
_, err = io.Copy(io.Discard, out)
if err != nil {
fatal("Failed to read image pull response")
}
}
}
}
resp, err := cli.ContainerCreate(ctx, config, hostConfig, nil, nil, "")
if err != nil {
fatal("Container creation failed")
}
if err := cli.ContainerStart(ctx, resp.ID, container.StartOptions{}); err != nil {
fatal("Failed to start container")
}
// this shouldn't happen since container is set to auto-remove
statusCh, errCh := cli.ContainerWait(
ctx,
resp.ID,
container.WaitConditionNotRunning,
)
select {
case err := <-errCh:
if err != nil {
fatal(fmt.Sprintf("Container execution error: %v", err))
}
case status := <-statusCh:
// Check if the container exited with an error
if status.StatusCode != 0 {
fatal(
fmt.Sprintf("Container exited with status code: %d", status.StatusCode),
)
}
}
}
func resolveDir(path string) string {
absPath, err := filepath.Abs(path)
if err != nil {
fatal(fmt.Sprintf("Unable to resolve path: %v", path))
}
return filepath.Dir(absPath)
}
func ensureDir(dir string) {
if _, err := os.Stat(dir); os.IsNotExist(err) {
if err := os.MkdirAll(dir, 0755); err != nil {
fatal(fmt.Sprintf("Failed to create directory: %v", err))
}
}
}
// Checks if the volume exists and returns its name.
func volumeHealthCheck(ctx context.Context, cli *client.Client, volume string) string {
vol, err := cli.VolumeInspect(ctx, volume)
if err != nil {
if client.IsErrConnectionFailed(err) {
fatal(ErrDockerSaidNuhUh)
}
if errdefs.IsNotFound(err) {
fatal(fmt.Sprintf("Volume '%s' does not exist.", volume))
} else {
fatal(fmt.Sprintf("Failed to inspect volume '%s'", volume))
}
}
// prevent any data races by finding running containers using this volume
containers, err := cli.ContainerList(ctx, container.ListOptions{
Filters: filters.NewArgs(
filters.Arg("volume", vol.Name),
filters.Arg("status", "running"),
),
})
if err != nil {
fatal(fmt.Sprintf("Failed to list containers using volume '%s'", vol.Name))
}
type container struct {
Name string
ID string
}
var rwContainersPresent bool
var containersToDisplay []container
// a volume can be mounted to multiple containers, show all of them
for _, c := range containers {
var containerName string
var cont container
for _, m := range c.Mounts {
if m.Type == "volume" {
if m.RW {
rwContainersPresent = true
if len(c.Names) > 0 {
containerName = strings.TrimPrefix(
c.Names[0],
"/",
) // Remove leading slash
}
cont.Name = containerName
}
}
}
cont.ID = c.ID[:12]
containersToDisplay = append(containersToDisplay, cont)
}
if rwContainersPresent {
fmt.Printf(
"Volume '%s' is in use by the following container(s). Please stop them and try again.\n\n",
vol.Name,
)
for _, c := range containersToDisplay {
fmt.Printf("%s (%s)\n", c.Name, c.ID)
}
os.Exit(1)
}
return vol.Name
}
// Add this helper function
func validateArchiveFormat(filename string) error {
validExts := []string{".tar", ".tar.gz", ".tgz", ".tar.bz2", ".tar.xz"}
for _, validExt := range validExts {
if strings.HasSuffix(strings.ToLower(filename), validExt) {
return nil
}
}
// nolint:staticcheck // ST1005 Intended Error message for CLI
return fmt.Errorf("Invalid snapshot file format: %s", filename)
}