forked from muesli/docker-backup
-
Notifications
You must be signed in to change notification settings - Fork 0
/
backup.go
297 lines (248 loc) · 6.18 KB
/
backup.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
package main
import (
"archive/tar"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
"syscall"
"time"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/container"
"github.com/docker/go-connections/nat"
"github.com/kennygrant/sanitize"
"github.com/spf13/cobra"
)
// Backup is used to gather all of a container's metadata, so we can encode it
// as JSON and store it
type Backup struct {
Name string
Config *container.Config
PortMap nat.PortMap
Mounts []types.MountPoint
}
var (
optLaunch = ""
optTar = false
optAll = false
optStopped = false
optVerbose = false
paths []string
tw *tar.Writer
backupCmd = &cobra.Command{
Use: "backup [container-id]",
Short: "creates a backup of a container",
RunE: func(cmd *cobra.Command, args []string) error {
if optAll {
return backupAll()
}
if len(args) < 1 {
return fmt.Errorf("backup requires the ID of a container")
}
return backup(args[0])
},
}
)
func collectFile(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if optVerbose {
fmt.Println("Adding", path)
}
paths = append(paths, path)
return nil
}
func collectFileTar(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.Mode()&os.ModeSocket != 0 {
// ignore sockets
return nil
}
if optVerbose {
fmt.Println("Adding", path)
}
th, err := tar.FileInfoHeader(info, path)
if err != nil {
return err
}
th.Name = path
if si, ok := info.Sys().(*syscall.Stat_t); ok {
th.Uid = int(si.Uid)
th.Gid = int(si.Gid)
}
if err := tw.WriteHeader(th); err != nil {
return err
}
if !info.Mode().IsRegular() {
return nil
}
if info.Mode().IsDir() {
return nil
}
file, err := os.Open(path)
if err != nil {
return err
}
_, err = io.Copy(tw, file)
return err
}
func backupTar(filename string, backup Backup) error {
b, err := json.MarshalIndent(backup, "", " ")
if err != nil {
return err
}
// fmt.Println(string(b))
tarfile, err := os.Create(filename + ".tar")
if err != nil {
return err
}
tw = tar.NewWriter(tarfile)
th := &tar.Header{
Name: "container.json",
Size: int64(len(b)),
ModTime: time.Now(),
AccessTime: time.Now(),
ChangeTime: time.Now(),
Mode: 0600,
}
if err := tw.WriteHeader(th); err != nil {
return err
}
if _, err := tw.Write(b); err != nil {
return err
}
for _, m := range backup.Mounts {
// fmt.Printf("Mount (type %s) %s -> %s\n", m.Type, m.Source, m.Destination)
err := filepath.Walk(m.Source, collectFileTar)
if err != nil {
return err
}
}
tw.Close()
fmt.Println("Created backup:", filename+".tar")
return nil
}
func getFullImageName(imageName string) (string, error) {
// If the image already specifies a tag we can safely use as-is
if strings.Contains(imageName, ":") {
return imageName, nil
}
// If the used image doesn't include tag information try to find one (if it exists).
images, err := cli.ImageList(ctx, types.ImageListOptions{})
if err != nil {
// Couldn't get image list, abort
return imageName, err
}
for _, image := range images {
if (!strings.Contains(imageName, image.ID)) || len(image.RepoTags) == 0 {
// unrelated image or image entry doesn't have any tags, move on
continue
}
for _, tag := range image.RepoTags {
// use closer matching tag if it exists
if !strings.Contains(tag, imageName) {
continue
}
return tag, nil
}
// If none of the tags matches the base image name, return the first tag
return image.RepoTags[0], nil
}
// There is no tag on the matching image, just have to go with what was provided
return imageName, nil
}
func backup(ID string) error {
conf, err := cli.ContainerInspect(ctx, ID)
if err != nil {
return err
}
fmt.Printf("Creating backup of %s (%s, %s)\n", conf.Name[1:], conf.Config.Image, conf.ID[:12])
paths = []string{}
conf.Config.Image, err = getFullImageName(conf.Config.Image)
if err != nil {
return err
}
backup := Backup{
Name: conf.Name,
PortMap: conf.HostConfig.PortBindings,
Config: conf.Config,
Mounts: conf.Mounts,
}
filename := sanitize.Path(fmt.Sprintf("%s-%s", conf.Config.Image, ID))
filename = strings.Replace(filename, "/", "_", -1)
if optTar {
return backupTar(filename, backup)
}
b, err := json.MarshalIndent(backup, "", " ")
if err != nil {
return err
}
// fmt.Println(string(b))
err = ioutil.WriteFile(filename+".backup.json", b, 0600)
if err != nil {
return err
}
for _, m := range conf.Mounts {
// fmt.Printf("Mount (type %s) %s -> %s\n", m.Type, m.Source, m.Destination)
err := filepath.Walk(m.Source, collectFile)
if err != nil {
return err
}
}
filelist, err := os.Create(filename + ".backup.files")
if err != nil {
return err
}
defer filelist.Close()
_, err = filelist.WriteString(filename + ".backup.json\n")
if err != nil {
return err
}
for _, s := range paths {
_, err := filelist.WriteString(s + "\n")
if err != nil {
return err
}
}
fmt.Println("Created backup:", filename+".backup.json")
if optLaunch != "" {
ol := strings.Replace(optLaunch, "%tag", filename, -1)
ol = strings.Replace(ol, "%list", filename+".backup.files", -1)
fmt.Println("Launching external command and waiting for it to finish:")
fmt.Println(ol)
l := strings.Split(ol, " ")
cmd := exec.Command(l[0], l[1:]...)
return cmd.Run()
}
return nil
}
func backupAll() error {
containers, err := cli.ContainerList(ctx, types.ContainerListOptions{
All: optStopped,
})
if err != nil {
panic(err)
}
for _, container := range containers {
err := backup(container.ID)
if err != nil {
return err
}
}
return nil
}
func init() {
backupCmd.Flags().StringVarP(&optLaunch, "launch", "l", "", "launch external program with file-list as argument")
backupCmd.Flags().BoolVarP(&optTar, "tar", "t", false, "create tar backups")
backupCmd.Flags().BoolVarP(&optAll, "all", "a", false, "backup all running containers")
backupCmd.Flags().BoolVarP(&optStopped, "stopped", "s", false, "in combination with --all: also backup stopped containers")
backupCmd.Flags().BoolVarP(&optVerbose, "verbose", "v", false, "print detailed backup progress")
RootCmd.AddCommand(backupCmd)
}