-
Notifications
You must be signed in to change notification settings - Fork 937
/
Copy pathcopy.go
498 lines (416 loc) · 14 KB
/
copy.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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
package main
import (
"errors"
"fmt"
"strings"
"github.com/spf13/cobra"
"github.com/canonical/lxd/client"
"github.com/canonical/lxd/lxc/config"
"github.com/canonical/lxd/lxd/instance/instancetype"
"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 cmdCopy struct {
global *cmdGlobal
flagNoProfiles bool
flagProfile []string
flagConfig []string
flagDevice []string
flagEphemeral bool
flagInstanceOnly bool
flagMode string
flagStateless bool
flagStorage string
flagTarget string
flagTargetProject string
flagRefresh bool
flagAllowInconsistent bool
}
func (c *cmdCopy) command() *cobra.Command {
cmd := &cobra.Command{}
cmd.Use = usage("copy", i18n.G("[<remote>:]<source>[/<snapshot>] [[<remote>:]<destination>]"))
cmd.Aliases = []string{"cp"}
cmd.Short = i18n.G("Copy instances within or in between LXD servers")
cmd.Long = cli.FormatSection(i18n.G("Description"), i18n.G(
`Copy instances within or in between LXD servers
Transfer modes (--mode):
- pull: Target server pulls the data from the source server (source must listen on network)
- push: Source server pushes the data to the target server (target must listen on network)
- relay: The CLI connects to both source and server and proxies the data (both source and target must listen on network)
The pull transfer mode is the default as it is compatible with all LXD versions.
`))
cmd.RunE = c.run
cmd.Flags().StringArrayVarP(&c.flagConfig, "config", "c", nil, i18n.G("Config key/value to apply to the new instance")+"``")
cmd.Flags().StringArrayVarP(&c.flagDevice, "device", "d", nil, i18n.G("New key/value to apply to a specific device")+"``")
cmd.Flags().StringArrayVarP(&c.flagProfile, "profile", "p", nil, i18n.G("Profile to apply to the new instance")+"``")
cmd.Flags().BoolVarP(&c.flagEphemeral, "ephemeral", "e", false, i18n.G("Ephemeral instance"))
cmd.Flags().StringVar(&c.flagMode, "mode", "pull", i18n.G("Transfer mode. One of pull, push or relay")+"``")
cmd.Flags().BoolVar(&c.flagInstanceOnly, "instance-only", false, i18n.G("Copy the instance without its snapshots"))
cmd.Flags().BoolVar(&c.flagStateless, "stateless", false, i18n.G("Copy a stateful instance stateless"))
cmd.Flags().StringVarP(&c.flagStorage, "storage", "s", "", i18n.G("Storage pool name")+"``")
cmd.Flags().StringVar(&c.flagTarget, "target", "", i18n.G("Cluster member name")+"``")
cmd.Flags().StringVar(&c.flagTargetProject, "target-project", "", i18n.G("Copy to a project different from the source")+"``")
cmd.Flags().BoolVar(&c.flagNoProfiles, "no-profiles", false, i18n.G("Create the instance with no profiles applied"))
cmd.Flags().BoolVar(&c.flagRefresh, "refresh", false, i18n.G("Perform an incremental copy"))
cmd.Flags().BoolVar(&c.flagAllowInconsistent, "allow-inconsistent", false, i18n.G("Ignore copy errors for volatile files"))
cmd.ValidArgsFunction = func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
return c.global.cmpInstances(toComplete)
}
if len(args) == 1 {
return c.global.cmpRemotes(toComplete, false)
}
return nil, cobra.ShellCompDirectiveNoFileComp
}
return cmd
}
func (c *cmdCopy) copyInstance(conf *config.Config, sourceResource string, destResource string, keepVolatile bool, ephemeral int, stateful bool, instanceOnly bool, mode string, pool string, move bool) error {
// Parse the source
sourceRemote, sourceName, err := conf.ParseRemote(sourceResource)
if err != nil {
return err
}
// Parse the destination
destRemote, destName, err := conf.ParseRemote(destResource)
if err != nil {
return err
}
// Make sure we have an instance or snapshot name
if sourceName == "" {
return errors.New(i18n.G("You must specify a source instance name"))
}
// Don't allow refreshing without profiles.
if c.flagRefresh && c.flagNoProfiles {
return errors.New(i18n.G("--no-profiles cannot be used with --refresh"))
}
// If the instance is being copied to a different remote and no destination name is
// specified, use the source name with snapshot suffix trimmed (in case a new instance
// is being created from a snapshot).
if destName == "" && destResource != "" && c.flagTarget == "" {
destName = strings.SplitN(sourceName, shared.SnapshotDelimiter, 2)[0]
}
// Ensure that a destination name is provided.
if destName == "" {
return errors.New(i18n.G("You must specify a destination instance name"))
}
// Connect to the source host
source, err := conf.GetInstanceServer(sourceRemote)
if err != nil {
return err
}
// Connect to the destination host
var dest lxd.InstanceServer
if sourceRemote == destRemote {
// Source and destination are the same
dest = source
} else {
// Destination is different, connect to it
dest, err = conf.GetInstanceServer(destRemote)
if err != nil {
return err
}
}
// Project copies
if c.flagTargetProject != "" {
dest = dest.UseProject(c.flagTargetProject)
}
// Confirm that --target is only used with a cluster
if c.flagTarget != "" && !dest.IsClustered() {
return errors.New(i18n.G("To use --target, the destination remote must be a cluster"))
}
// Parse the config overrides
configMap := map[string]string{}
for _, entry := range c.flagConfig {
key, value, found := strings.Cut(entry, "=")
if !found {
return fmt.Errorf(i18n.G("Bad key=value pair: %q"), entry)
}
configMap[key] = value
}
deviceOverrides, err := parseDeviceOverrides(c.flagDevice)
if err != nil {
return err
}
var op lxd.RemoteOperation
var writable api.InstancePut
var start bool
if shared.IsSnapshot(sourceName) {
if instanceOnly {
return errors.New(i18n.G("--instance-only can't be passed when the source is a snapshot"))
}
// Prepare the instance creation request
args := lxd.InstanceSnapshotCopyArgs{
Name: destName,
Mode: mode,
Live: stateful,
}
if c.flagRefresh {
return errors.New(i18n.G("--refresh can only be used with instances"))
}
// Copy of a snapshot into a new instance
srcFields := strings.SplitN(sourceName, shared.SnapshotDelimiter, 2)
entry, _, err := source.GetInstanceSnapshot(srcFields[0], srcFields[1])
if err != nil {
return err
}
// Overwrite profiles.
if c.flagProfile != nil {
entry.Profiles = c.flagProfile
} else if c.flagNoProfiles {
entry.Profiles = []string{}
}
// Check to see if any of the overridden devices are for devices that are not yet defined in the
// local devices (and thus maybe expected to be coming from profiles).
needProfileExpansion := false
for deviceName := range deviceOverrides {
_, isLocalDevice := entry.Devices[deviceName]
if !isLocalDevice {
needProfileExpansion = true
break
}
}
profileDevices := make(map[string]map[string]string)
// If there are device overrides that are expected to be applied to profile devices then perform
// profile expansion.
if needProfileExpansion {
// If the list of profiles is empty then LXD would apply the default profile on the server side.
profileDevices, err = getProfileDevices(dest, entry.Profiles)
if err != nil {
return err
}
}
// Apply device overrides.
entry.Devices, err = shared.ApplyDeviceOverrides(profileDevices, entry.Devices, deviceOverrides)
if err != nil {
return err
}
// Allow setting additional config keys.
for key, value := range configMap {
entry.Config[key] = value
}
// Allow overriding the ephemeral status
if ephemeral == 1 {
entry.Ephemeral = true
} else if ephemeral == 0 {
entry.Ephemeral = false
}
rootDiskDeviceKey, _, _ := instancetype.GetRootDiskDevice(entry.Devices)
if rootDiskDeviceKey != "" && pool != "" {
entry.Devices[rootDiskDeviceKey]["pool"] = pool
} else if pool != "" {
entry.Devices["root"] = map[string]string{
"type": "disk",
"path": "/",
"pool": pool,
}
}
if entry.Config != nil {
// Strip the last_state.power key in all cases
delete(entry.Config, "volatile.last_state.power")
if !keepVolatile {
for k := range entry.Config {
if !instancetype.InstanceIncludeWhenCopying(k, true) {
delete(entry.Config, k)
}
}
}
}
// Do the actual copy
if c.flagTarget != "" {
dest = dest.UseTarget(c.flagTarget)
}
op, err = dest.CopyInstanceSnapshot(source, srcFields[0], *entry, &args)
if err != nil {
return err
}
} else {
// Prepare the instance creation request
args := lxd.InstanceCopyArgs{
Name: destName,
Live: stateful,
InstanceOnly: instanceOnly,
Mode: mode,
Refresh: c.flagRefresh,
AllowInconsistent: c.flagAllowInconsistent,
}
// Copy of an instance into a new instance
entry, _, err := source.GetInstance(sourceName)
if err != nil {
return err
}
// Only start the instance back up if doing a stateless migration.
// Its LXD's job to start things back up when receiving a stateful migration.
if entry.StatusCode == api.Running && move && !stateful {
start = true
}
// Overwrite profiles.
if c.flagProfile != nil {
entry.Profiles = c.flagProfile
} else if c.flagNoProfiles {
entry.Profiles = []string{}
}
// Check to see if any of the devices overrides are for devices that are not yet defined in the
// local devices and thus are expected to be coming from profiles.
needProfileExpansion := false
for deviceName := range deviceOverrides {
_, isLocalDevice := entry.Devices[deviceName]
if !isLocalDevice {
needProfileExpansion = true
break
}
}
profileDevices := make(map[string]map[string]string)
// If there are device overrides that are expected to be applied to profile devices then perform
// profile expansion.
if needProfileExpansion {
profileDevices, err = getProfileDevices(dest, entry.Profiles)
if err != nil {
return err
}
}
// Apply device overrides.
entry.Devices, err = shared.ApplyDeviceOverrides(entry.Devices, profileDevices, deviceOverrides)
if err != nil {
return err
}
// Allow setting additional config keys.
for key, value := range configMap {
entry.Config[key] = value
}
// Allow overriding the ephemeral status
if ephemeral == 1 {
entry.Ephemeral = true
} else if ephemeral == 0 {
entry.Ephemeral = false
}
rootDiskDeviceKey, _, _ := instancetype.GetRootDiskDevice(entry.Devices)
if rootDiskDeviceKey != "" && pool != "" {
entry.Devices[rootDiskDeviceKey]["pool"] = pool
} else if pool != "" {
entry.Devices["root"] = map[string]string{
"type": "disk",
"path": "/",
"pool": pool,
}
}
// Strip the volatile keys if requested
if !keepVolatile {
for k := range entry.Config {
if !instancetype.InstanceIncludeWhenCopying(k, true) {
delete(entry.Config, k)
}
}
}
if entry.Config != nil {
// Strip the last_state.power key in all cases
delete(entry.Config, "volatile.last_state.power")
}
// Do the actual copy
if c.flagTarget != "" {
dest = dest.UseTarget(c.flagTarget)
}
op, err = dest.CopyInstance(source, *entry, &args)
if err != nil {
return err
}
writable = entry.Writable()
}
// Watch the background operation
progress := cli.ProgressRenderer{
Format: i18n.G("Transferring instance: %s"),
Quiet: c.global.flagQuiet,
}
_, err = op.AddHandler(progress.UpdateOp)
if err != nil {
progress.Done("")
return err
}
// Wait for the copy to complete
err = cli.CancelableWait(op, &progress)
if err != nil {
progress.Done("")
return err
}
progress.Done("")
if c.flagRefresh {
inst, etag, err := dest.GetInstance(destName)
if err != nil {
return fmt.Errorf(i18n.G("Failed to refresh target instance '%s': %v"), destName, err)
}
// Ensure we don't change the target's volatile.idmap.next value.
if inst.Config["volatile.idmap.next"] != writable.Config["volatile.idmap.next"] {
writable.Config["volatile.idmap.next"] = inst.Config["volatile.idmap.next"]
}
// Ensure we don't change the target's root disk pool.
srcRootDiskDeviceKey, _, _ := instancetype.GetRootDiskDevice(writable.Devices)
destRootDiskDeviceKey, destRootDiskDevice, _ := instancetype.GetRootDiskDevice(inst.Devices)
if srcRootDiskDeviceKey != "" && srcRootDiskDeviceKey == destRootDiskDeviceKey {
writable.Devices[destRootDiskDeviceKey]["pool"] = destRootDiskDevice["pool"]
}
op, err := dest.UpdateInstance(destName, writable, etag)
if err != nil {
return err
}
// Watch the background operation
progress := cli.ProgressRenderer{
Format: i18n.G("Refreshing instance: %s"),
Quiet: c.global.flagQuiet,
}
_, err = op.AddHandler(progress.UpdateOp)
if err != nil {
progress.Done("")
return err
}
// Wait for the copy to complete
err = cli.CancelableWait(op, &progress)
if err != nil {
progress.Done("")
return err
}
progress.Done("")
}
// Start the instance if needed
if start {
req := api.InstanceStatePut{
Action: string(instancetype.Start),
}
op, err := dest.UpdateInstanceState(destName, req, "")
if err != nil {
return err
}
err = op.Wait()
if err != nil {
return err
}
}
return nil
}
func (c *cmdCopy) 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
}
// For copies, default to non-ephemeral and allow override (move uses -1)
ephem := 0
if c.flagEphemeral {
ephem = 1
}
// Parse the mode
mode := "pull"
if c.flagMode != "" {
mode = c.flagMode
}
stateful := !c.flagStateless && !c.flagRefresh
keepVolatile := c.flagRefresh
instanceOnly := c.flagInstanceOnly
// If not target name is specified, one will be chosed by the server
if len(args) < 2 {
return c.copyInstance(conf, args[0], "", keepVolatile, ephem, stateful, instanceOnly, mode, c.flagStorage, false)
}
// Normal copy with a pre-determined name
return c.copyInstance(conf, args[0], args[1], keepVolatile, ephem, stateful, instanceOnly, mode, c.flagStorage, false)
}