-
Notifications
You must be signed in to change notification settings - Fork 937
/
Copy pathexport.go
194 lines (160 loc) · 4.48 KB
/
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
package main
import (
"fmt"
"io"
"net/url"
"os"
"path"
"time"
"github.com/spf13/cobra"
"github.com/canonical/lxd/client"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
cli "github.com/canonical/lxd/shared/cmd"
"github.com/canonical/lxd/shared/i18n"
)
type cmdExport struct {
global *cmdGlobal
flagInstanceOnly bool
flagOptimizedStorage bool
flagCompressionAlgorithm string
}
func (c *cmdExport) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("export", i18n.G("[<remote>:]<instance> [target] [--instance-only] [--optimized-storage]"))
cmd.Short = i18n.G("Export instance backups")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Export instances as backup tarballs.`))
cmd.Example = cli.FormatSection("", i18n.G(
`lxc export u1 backup0.tar.gz
Download a backup tarball of the u1 instance.`))
cmd.RunE = c.run
cmd.Flags().BoolVar(&c.flagInstanceOnly, "instance-only", false,
i18n.G("Whether or not to only backup the instance (without snapshots)"))
cmd.Flags().BoolVar(&c.flagOptimizedStorage, "optimized-storage", false,
i18n.G("Use storage driver optimized format (can only be restored on a similar pool)"))
cmd.Flags().StringVar(&c.flagCompressionAlgorithm, "compression", "", i18n.G("Compression algorithm to use (none for uncompressed)")+"``")
return cmd
}
func (c *cmdExport) run(cmd *cobra.Command, args []string) error {
conf := c.global.conf
// Quick checks.
exit, err := c.global.CheckArgs(cmd, args, 1, 2)
if exit {
return err
}
// Connect to LXD
remote, name, err := conf.ParseRemote(args[0])
if err != nil {
return err
}
d, err := conf.GetInstanceServer(remote)
if err != nil {
return err
}
instanceOnly := c.flagInstanceOnly
req := api.InstanceBackupsPost{
Name: "",
ExpiresAt: time.Now().Add(24 * time.Hour),
ContainerOnly: instanceOnly,
InstanceOnly: instanceOnly,
OptimizedStorage: c.flagOptimizedStorage,
CompressionAlgorithm: c.flagCompressionAlgorithm,
}
op, err := d.CreateInstanceBackup(name, req)
if err != nil {
return fmt.Errorf("Create instance backup: %w", err)
}
var targetName string
if len(args) > 1 {
targetName = args[1]
} else {
targetName = name + ".backup"
}
var target *os.File
if targetName == "-" {
target = os.Stdout
c.global.flagQuiet = true
} else {
target, err = os.Create(shared.HostPathFollow(targetName))
if err != nil {
return err
}
defer func() { _ = target.Close() }()
}
// Watch the background operation
progress := cli.ProgressRenderer{
Format: i18n.G("Backing up instance: %s"),
Quiet: c.global.flagQuiet,
}
_, err = op.AddHandler(progress.UpdateOp)
if err != nil {
progress.Done("")
return err
}
// Wait until backup is done
err = cli.CancelableWait(op, &progress)
if err != nil {
progress.Done("")
return err
}
progress.Done("")
err = op.Wait()
if err != nil {
return err
}
// Get name of backup
uStr := op.Get().Resources["backups"][0]
u, err := url.Parse(uStr)
if err != nil {
return fmt.Errorf("Invalid URL %q: %w", uStr, err)
}
backupName, err := url.PathUnescape(path.Base(u.EscapedPath()))
if err != nil {
return fmt.Errorf("Invalid backup name segment in path %q: %w", u.EscapedPath(), err)
}
defer func() {
// Delete backup after we're done
op, err = d.DeleteInstanceBackup(name, backupName)
if err == nil {
_ = op.Wait()
}
}()
// Prepare the download request
progress = cli.ProgressRenderer{
Format: i18n.G("Exporting the backup: %s"),
Quiet: c.global.flagQuiet,
}
backupFileRequest := lxd.BackupFileRequest{
BackupFile: io.WriteSeeker(target),
ProgressHandler: progress.UpdateProgress,
}
// Export tarball
_, err = d.GetInstanceBackupFile(name, backupName, &backupFileRequest)
if err != nil {
_ = os.Remove(targetName)
progress.Done("")
return fmt.Errorf("Fetch instance backup file: %w", err)
}
// Detect backup file type and rename file accordingly
if len(args) <= 1 {
_, err := target.Seek(0, io.SeekStart)
if err != nil {
return err
}
_, ext, _, err := shared.DetectCompressionFile(target)
if err != nil {
return err
}
err = os.Rename(shared.HostPathFollow(targetName), shared.HostPathFollow(name+ext))
if err != nil {
return fmt.Errorf("Failed to rename export file: %w", err)
}
}
err = target.Close()
if err != nil {
return fmt.Errorf("Failed to close export file: %w", err)
}
progress.Done(i18n.G("Backup exported successfully!"))
return nil
}