-
Notifications
You must be signed in to change notification settings - Fork 907
/
driver_zfs_volumes.go
3515 lines (2900 loc) · 102 KB
/
driver_zfs_volumes.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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package drivers
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/google/uuid"
"golang.org/x/sys/unix"
"github.com/canonical/lxd/lxd/archive"
"github.com/canonical/lxd/lxd/backup"
"github.com/canonical/lxd/lxd/instancewriter"
"github.com/canonical/lxd/lxd/migration"
"github.com/canonical/lxd/lxd/operations"
"github.com/canonical/lxd/lxd/storage/filesystem"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
"github.com/canonical/lxd/shared/ioprogress"
"github.com/canonical/lxd/shared/logger"
"github.com/canonical/lxd/shared/revert"
"github.com/canonical/lxd/shared/units"
"github.com/canonical/lxd/shared/validate"
)
// CreateVolume creates an empty volume and can optionally fill it by executing the supplied
// filler function.
func (d *zfs) CreateVolume(vol Volume, filler *VolumeFiller, op *operations.Operation) error {
// Revert handling
revert := revert.New()
defer revert.Fail()
if vol.contentType == ContentTypeFS {
// Create mountpoint.
err := vol.EnsureMountPath()
if err != nil {
return err
}
revert.Add(func() { _ = os.Remove(vol.MountPath()) })
}
// Look for previously deleted images.
if vol.volType == VolumeTypeImage {
exists, err := d.datasetExists(d.dataset(vol, true))
if err != nil {
return err
}
if exists {
canRestore := true
if vol.IsBlockBacked() && (vol.contentType == ContentTypeBlock || d.isBlockBacked(vol)) {
// For block volumes check if the cached image volume is larger than the current pool volume.size
// setting (if so we won't be able to resize the snapshot to that the smaller size later).
volSize, err := d.getDatasetProperty(d.dataset(vol, true), "volsize")
if err != nil {
return err
}
volSizeBytes, err := strconv.ParseInt(volSize, 10, 64)
if err != nil {
return err
}
poolVolSize := DefaultBlockSize
if vol.poolConfig["volume.size"] != "" {
poolVolSize = vol.poolConfig["volume.size"]
}
poolVolSizeBytes, err := units.ParseByteSizeString(poolVolSize)
if err != nil {
return err
}
// Round to block boundary.
poolVolSizeBytes = d.roundVolumeBlockSizeBytes(poolVolSizeBytes)
// If the cached volume size is different than the pool volume size, then we can't use the
// deleted cached image volume and instead we will rename it to a random UUID so it can't
// be restored in the future and a new cached image volume will be created instead.
if volSizeBytes != poolVolSizeBytes {
d.logger.Debug("Renaming deleted cached image volume so that regeneration is used", logger.Ctx{"fingerprint": vol.Name()})
randomVol := NewVolume(d, d.name, vol.volType, vol.contentType, d.randomVolumeName(vol), vol.config, vol.poolConfig)
_, err := shared.RunCommand("/proc/self/exe", "forkzfs", "--", "rename", d.dataset(vol, true), d.dataset(randomVol, true))
if err != nil {
return err
}
if vol.IsVMBlock() {
fsVol := vol.NewVMBlockFilesystemVolume()
randomFsVol := randomVol.NewVMBlockFilesystemVolume()
_, err := shared.RunCommand("/proc/self/exe", "forkzfs", "--", "rename", d.dataset(fsVol, true), d.dataset(randomFsVol, true))
if err != nil {
return err
}
}
// We have renamed the deleted cached image volume, so we don't want to try and
// restore it.
canRestore = false
}
}
// Restore the image.
if canRestore {
d.logger.Debug("Restoring previously deleted cached image volume", logger.Ctx{"fingerprint": vol.Name()})
_, err := shared.RunCommand("/proc/self/exe", "forkzfs", "--", "rename", d.dataset(vol, true), d.dataset(vol, false))
if err != nil {
return err
}
if vol.IsVMBlock() {
fsVol := vol.NewVMBlockFilesystemVolume()
_, err := shared.RunCommand("/proc/self/exe", "forkzfs", "--", "rename", d.dataset(fsVol, true), d.dataset(fsVol, false))
if err != nil {
return err
}
}
revert.Success()
return nil
}
}
}
// After this point we'll have a volume, so setup revert.
revert.Add(func() { _ = d.DeleteVolume(vol, op) })
if vol.contentType == ContentTypeFS && !d.isBlockBacked(vol) {
// Create the filesystem dataset.
err := d.createDataset(d.dataset(vol, false), "mountpoint=legacy", "canmount=noauto")
if err != nil {
return err
}
// Apply the size limit.
err = d.SetVolumeQuota(vol, vol.ConfigSize(), false, op)
if err != nil {
return err
}
// Apply the blocksize.
err = d.setBlocksizeFromConfig(vol)
if err != nil {
return err
}
} else {
sizeBytes, err := units.ParseByteSizeString(vol.ConfigSize())
if err != nil {
return err
}
var opts []string
if vol.contentType == ContentTypeFS {
// Use volmode=dev so volume is visible as we need to run makeFSType.
opts = []string{"volmode=dev"}
} else {
// Use volmode=none so volume is invisible until mounted.
opts = []string{"volmode=none"}
}
// Add custom property lxd:content_type which allows distinguishing between regular volumes, block_mode enabled volumes, and ISO volumes.
if vol.volType == VolumeTypeCustom {
opts = append(opts, fmt.Sprintf("lxd:content_type=%s", vol.contentType))
}
// Avoid double caching in the ARC cache and in the guest OS filesystem cache.
if vol.volType == VolumeTypeVM {
opts = append(opts, "primarycache=metadata", "secondarycache=metadata")
}
loopPath := loopFilePath(d.name)
if d.config["source"] == loopPath {
// Create the volume dataset with sync disabled (to avoid kernel lockups when using a disk based pool).
opts = append(opts, "sync=disabled")
}
blockSize := vol.ExpandedConfig("zfs.blocksize")
if blockSize != "" {
// Convert to bytes.
sizeBytes, err := units.ParseByteSizeString(blockSize)
if err != nil {
return err
}
// zfs.blocksize can have value in range from 512 to 16MiB because it's used for volblocksize and recordsize
// volblocksize maximum value is 128KiB so if the value of zfs.blocksize is bigger set it to 128KiB.
if sizeBytes > zfsMaxVolBlocksize {
sizeBytes = zfsMaxVolBlocksize
}
opts = append(opts, fmt.Sprintf("volblocksize=%d", sizeBytes))
}
// Create the volume dataset.
err = d.createVolume(d.dataset(vol, false), sizeBytes, opts...)
if err != nil {
return err
}
if vol.contentType == ContentTypeFS {
// Wait half a second to give udev a chance to kick in.
time.Sleep(500 * time.Millisecond)
zfsFilesystem := vol.ConfigBlockFilesystem()
devPath, err := d.GetVolumeDiskPath(vol)
if err != nil {
return err
}
_, err = makeFSType(devPath, zfsFilesystem, nil)
if err != nil {
return err
}
err = d.setDatasetProperties(d.dataset(vol, false), "volmode=none")
if err != nil {
return err
}
}
}
// For VM images, create a filesystem volume too.
if vol.IsVMBlock() {
fsVol := vol.NewVMBlockFilesystemVolume()
err := d.CreateVolume(fsVol, nil, op)
if err != nil {
return err
}
revert.Add(func() { _ = d.DeleteVolume(fsVol, op) })
}
err := vol.MountTask(func(mountPath string, op *operations.Operation) error {
// Run the volume filler function if supplied.
if filler != nil && filler.Fill != nil {
var err error
var devPath string
if IsContentBlock(vol.contentType) {
// Get the device path.
devPath, err = d.GetVolumeDiskPath(vol)
if err != nil {
return err
}
}
allowUnsafeResize := false
if vol.volType == VolumeTypeImage {
// Allow filler to resize initial image volume as needed.
// Some storage drivers don't normally allow image volumes to be resized due to
// them having read-only snapshots that cannot be resized. However when creating
// the initial image volume and filling it before the snapshot is taken resizing
// can be allowed and is required in order to support unpacking images larger than
// the default volume size. The filler function is still expected to obey any
// volume size restrictions configured on the pool.
// Unsafe resize is also needed to disable filesystem resize safety checks.
// This is safe because if for some reason an error occurs the volume will be
// discarded rather than leaving a corrupt filesystem.
allowUnsafeResize = true
}
// Run the filler.
err = d.runFiller(vol, devPath, filler, allowUnsafeResize)
if err != nil {
return err
}
// Move the GPT alt header to end of disk if needed.
if vol.IsVMBlock() {
err = d.moveGPTAltHeader(devPath)
if err != nil {
return err
}
}
}
if vol.contentType == ContentTypeFS {
// Run EnsureMountPath again after mounting and filling to ensure the mount directory has
// the correct permissions set.
err := vol.EnsureMountPath()
if err != nil {
return err
}
}
return nil
}, op)
if err != nil {
return err
}
// Setup snapshot and unset mountpoint on image.
if vol.volType == VolumeTypeImage {
// Create snapshot of the main dataset.
_, err := shared.RunCommand("zfs", "snapshot", "-r", fmt.Sprintf("%s@readonly", d.dataset(vol, false)))
if err != nil {
return err
}
if vol.contentType == ContentTypeBlock {
// Re-create the FS config volume's readonly snapshot now that the filler function has run
// and unpacked into both config and block volumes.
fsVol := vol.NewVMBlockFilesystemVolume()
_, err := shared.RunCommand("zfs", "destroy", "-r", fmt.Sprintf("%s@readonly", d.dataset(fsVol, false)))
if err != nil {
return err
}
_, err = shared.RunCommand("zfs", "snapshot", "-r", fmt.Sprintf("%s@readonly", d.dataset(fsVol, false)))
if err != nil {
return err
}
}
}
// All done.
revert.Success()
return nil
}
// CreateVolumeFromBackup re-creates a volume from its exported state.
func (d *zfs) CreateVolumeFromBackup(vol VolumeCopy, srcBackup backup.Info, srcData io.ReadSeeker, op *operations.Operation) (VolumePostHook, revert.Hook, error) {
// Handle the non-optimized tarballs through the generic unpacker.
if !*srcBackup.OptimizedStorage {
return genericVFSBackupUnpack(d, d.state.OS, vol, srcBackup.Snapshots, srcData, op)
}
volExists, err := d.HasVolume(vol.Volume)
if err != nil {
return nil, nil, err
}
if volExists {
return nil, nil, fmt.Errorf("Cannot restore volume, already exists on target")
}
revert := revert.New()
defer revert.Fail()
// Define a revert function that will be used both to revert if an error occurs inside this
// function but also return it for use from the calling functions if no error internally.
revertHook := func() {
for _, snapName := range srcBackup.Snapshots {
fullSnapshotName := GetSnapshotVolumeName(vol.name, snapName)
snapVol := NewVolume(d, d.name, vol.volType, vol.contentType, fullSnapshotName, vol.config, vol.poolConfig)
_ = d.DeleteVolumeSnapshot(snapVol, op)
}
// And lastly the main volume.
_ = d.DeleteVolume(vol.Volume, op)
}
// Only execute the revert function if we have had an error internally.
revert.Add(revertHook)
// Define function to unpack a volume from a backup tarball file.
unpackVolume := func(v Volume, r io.ReadSeeker, unpacker []string, srcFile string, target string) error {
d.Logger().Debug("Unpacking optimized volume", logger.Ctx{"source": srcFile, "target": target})
targetPath := fmt.Sprintf("%s/storage-pools/%s", shared.VarPath(""), target)
tr, cancelFunc, err := archive.CompressedTarReader(context.Background(), r, unpacker, d.state.OS, targetPath)
if err != nil {
return err
}
defer cancelFunc()
for {
hdr, err := tr.Next()
if err == io.EOF {
break // End of archive.
}
if err != nil {
return err
}
if hdr.Name == srcFile {
// Extract the backup.
if v.ContentType() == ContentTypeBlock || d.isBlockBacked(v) {
err = shared.RunCommandWithFds(context.TODO(), tr, nil, "zfs", "receive", "-F", target)
} else {
err = shared.RunCommandWithFds(context.TODO(), tr, nil, "zfs", "receive", "-x", "mountpoint", "-F", target)
}
if err != nil {
return err
}
cancelFunc()
return nil
}
}
return fmt.Errorf("Could not find %q", srcFile)
}
var postHook VolumePostHook
// Create a list of actual volumes to unpack.
var vols []Volume
if vol.IsVMBlock() {
vols = append(vols, vol.NewVMBlockFilesystemVolume())
}
vols = append(vols, vol.Volume)
for _, v := range vols {
// Find the compression algorithm used for backup source data.
_, err := srcData.Seek(0, io.SeekStart)
if err != nil {
return nil, nil, err
}
_, _, unpacker, err := shared.DetectCompressionFile(srcData)
if err != nil {
return nil, nil, err
}
if len(srcBackup.Snapshots) > 0 {
// Create new snapshots directory.
err := createParentSnapshotDirIfMissing(d.name, v.volType, v.name)
if err != nil {
return nil, nil, err
}
}
// Restore backups from oldest to newest.
for _, snapName := range srcBackup.Snapshots {
prefix := "snapshots"
fileName := fmt.Sprintf("%s.bin", snapName)
if v.volType == VolumeTypeVM {
prefix = "virtual-machine-snapshots"
if v.contentType == ContentTypeFS {
fileName = fmt.Sprintf("%s-config.bin", snapName)
}
} else if v.volType == VolumeTypeCustom {
prefix = "volume-snapshots"
}
srcFile := fmt.Sprintf("backup/%s/%s", prefix, fileName)
dstSnapshot := fmt.Sprintf("%s@snapshot-%s", d.dataset(v, false), snapName)
err = unpackVolume(v, srcData, unpacker, srcFile, dstSnapshot)
if err != nil {
return nil, nil, err
}
}
// Extract main volume.
fileName := "container.bin"
if v.volType == VolumeTypeVM {
if v.contentType == ContentTypeFS {
fileName = "virtual-machine-config.bin"
} else {
fileName = "virtual-machine.bin"
}
} else if v.volType == VolumeTypeCustom {
fileName = "volume.bin"
}
err = unpackVolume(v, srcData, unpacker, fmt.Sprintf("backup/%s", fileName), d.dataset(v, false))
if err != nil {
return nil, nil, err
}
// Strip internal snapshots.
entries, err := d.getDatasets(d.dataset(v, false), "snapshot")
if err != nil {
return nil, nil, err
}
// Remove only the internal snapshots.
for _, entry := range entries {
if strings.Contains(entry, "@snapshot-") {
continue
}
if strings.Contains(entry, "@") {
_, err := shared.RunCommand("zfs", "destroy", fmt.Sprintf("%s%s", d.dataset(v, false), entry))
if err != nil {
return nil, nil, err
}
}
}
// Re-apply the base mount options.
if v.contentType == ContentTypeFS {
if zfsDelegate {
// Unset the zoned property so the mountpoint property can be updated.
err := d.setDatasetProperties(d.dataset(v, false), "zoned=off")
if err != nil {
return nil, nil, err
}
}
err := d.setDatasetProperties(d.dataset(v, false), "mountpoint=legacy", "canmount=noauto")
if err != nil {
return nil, nil, err
}
// Apply the blocksize.
err = d.setBlocksizeFromConfig(v)
if err != nil {
return nil, nil, err
}
}
// Only mount instance filesystem volumes for backup.yaml access.
if v.volType != VolumeTypeCustom && v.contentType != ContentTypeBlock {
// The import requires a mounted volume, so mount it and have it unmounted as a post hook.
err = d.MountVolume(v, op)
if err != nil {
return nil, nil, err
}
revert.Add(func() { _, _ = d.UnmountVolume(v, false, op) })
postHook = func(postVol Volume) error {
_, err := d.UnmountVolume(postVol, false, op)
return err
}
}
}
cleanup := revert.Clone().Fail // Clone before calling revert.Success() so we can return the Fail func.
revert.Success()
return postHook, cleanup, nil
}
// CreateVolumeFromCopy provides same-pool volume copying functionality.
func (d *zfs) CreateVolumeFromCopy(vol VolumeCopy, srcVol VolumeCopy, allowInconsistent bool, op *operations.Operation) error {
var err error
// Revert handling
revert := revert.New()
defer revert.Fail()
if vol.contentType == ContentTypeFS {
// Create mountpoint.
err = vol.EnsureMountPath()
if err != nil {
return err
}
revert.Add(func() { _ = os.Remove(vol.MountPath()) })
}
// For VMs, also copy the filesystem dataset.
if vol.IsVMBlock() {
// For VMs, also copy the filesystem volume.
// We can pass the regular volume's snapshots as only their presence is relevant.
srcFSVol := NewVolumeCopy(srcVol.NewVMBlockFilesystemVolume(), srcVol.Snapshots...)
fsVol := NewVolumeCopy(vol.NewVMBlockFilesystemVolume(), vol.Snapshots...)
err = d.CreateVolumeFromCopy(fsVol, srcFSVol, false, op)
if err != nil {
return err
}
// Delete on revert.
revert.Add(func() { _ = d.DeleteVolume(fsVol.Volume, op) })
}
// Retrieve snapshots on the source.
snapshots := []string{}
if !srcVol.IsSnapshot() && len(vol.Snapshots) > 0 {
snapshots, err = d.VolumeSnapshots(srcVol.Volume, op)
if err != nil {
return err
}
}
// When not allowing inconsistent copies and the volume has a mounted filesystem, we must ensure it is
// consistent by syncing and freezing the filesystem to ensure unwritten pages are flushed and that no
// further modifications occur while taking the source snapshot.
var unfreezeFS func() error
sourcePath := srcVol.MountPath()
if !allowInconsistent && srcVol.contentType == ContentTypeFS && srcVol.IsBlockBacked() && filesystem.IsMountPoint(sourcePath) {
unfreezeFS, err = d.filesystemFreeze(sourcePath)
if err != nil {
return err
}
revert.Add(func() { _ = unfreezeFS() })
}
var srcSnapshot string
if srcVol.volType == VolumeTypeImage {
srcSnapshot = fmt.Sprintf("%s@readonly", d.dataset(srcVol.Volume, false))
} else if srcVol.IsSnapshot() {
srcSnapshot = d.dataset(srcVol.Volume, false)
} else {
// Create a new snapshot for copy.
srcSnapshot = fmt.Sprintf("%s@copy-%s", d.dataset(srcVol.Volume, false), uuid.New().String())
_, err := shared.RunCommand("zfs", "snapshot", "-r", srcSnapshot)
if err != nil {
return err
}
// If zfs.clone_copy is disabled delete the snapshot at the end.
if shared.IsFalse(d.config["zfs.clone_copy"]) || len(snapshots) > 0 {
// Delete the snapshot at the end.
defer func() {
// Delete snapshot (or mark for deferred deletion if cannot be deleted currently).
_, err := shared.RunCommand("zfs", "destroy", "-r", "-d", srcSnapshot)
if err != nil {
d.logger.Warn("Failed deleting temporary snapshot for copy", logger.Ctx{"snapshot": srcSnapshot, "err": err})
}
}()
} else {
// Delete the snapshot on revert.
revert.Add(func() {
// Delete snapshot (or mark for deferred deletion if cannot be deleted currently).
_, err := shared.RunCommand("zfs", "destroy", "-r", "-d", srcSnapshot)
if err != nil {
d.logger.Warn("Failed deleting temporary snapshot for copy", logger.Ctx{"snapshot": srcSnapshot, "err": err})
}
})
}
}
// Now that source snapshot has been taken we can safely unfreeze the source filesystem.
if unfreezeFS != nil {
_ = unfreezeFS()
}
// Delete the volume created on failure.
revert.Add(func() { _ = d.DeleteVolume(vol.Volume, op) })
// If zfs.clone_copy is disabled or source volume has snapshots, then use full copy mode.
if shared.IsFalse(d.config["zfs.clone_copy"]) || len(snapshots) > 0 {
snapName := strings.SplitN(srcSnapshot, "@", 2)[1]
// Send/receive the snapshot.
var sender *exec.Cmd
var receiver *exec.Cmd
if vol.ContentType() == ContentTypeBlock || d.isBlockBacked(vol.Volume) {
receiver = exec.Command("zfs", "receive", d.dataset(vol.Volume, false))
} else {
receiver = exec.Command("zfs", "receive", "-x", "mountpoint", d.dataset(vol.Volume, false))
}
// Handle transferring snapshots.
if len(snapshots) > 0 {
args := []string{"send", "-R"}
// Use raw flag is supported, this is required to send/receive encrypted volumes (and enables compression).
if zfsRaw {
args = append(args, "-w")
}
args = append(args, srcSnapshot)
sender = exec.Command("zfs", args...)
} else {
args := []string{"send"}
// Check if nesting is required.
if d.needsRecursion(d.dataset(srcVol.Volume, false)) {
args = append(args, "-R")
if zfsRaw {
args = append(args, "-w")
}
}
if d.config["zfs.clone_copy"] == "rebase" {
var err error
origin := d.dataset(srcVol.Volume, false)
for {
fields := strings.SplitN(origin, "@", 2)
// If the origin is a @readonly snapshot under a /images/ path (/images or deleted/images), we're done.
if len(fields) > 1 && strings.Contains(fields[0], "/images/") && fields[1] == "readonly" {
break
}
origin, err = d.getDatasetProperty(origin, "origin")
if err != nil {
return err
}
if origin == "" || origin == "-" {
origin = ""
break
}
}
if origin != "" && origin != srcSnapshot {
args = append(args, "-i", origin)
args = append(args, srcSnapshot)
sender = exec.Command("zfs", args...)
} else {
args = append(args, srcSnapshot)
sender = exec.Command("zfs", args...)
}
} else {
args = append(args, srcSnapshot)
sender = exec.Command("zfs", args...)
}
}
// Configure the pipes.
receiver.Stdin, _ = sender.StdoutPipe()
receiver.Stdout = os.Stdout
var recvStderr bytes.Buffer
receiver.Stderr = &recvStderr
var sendStderr bytes.Buffer
sender.Stderr = &sendStderr
// Run the transfer.
err := receiver.Start()
if err != nil {
return fmt.Errorf("Failed starting ZFS receive: %w", err)
}
err = sender.Start()
if err != nil {
_ = receiver.Process.Kill()
return fmt.Errorf("Failed starting ZFS send: %w", err)
}
senderErr := make(chan error)
go func() {
err := sender.Wait()
if err != nil {
_ = receiver.Process.Kill()
// This removes any newlines in the error message.
msg := strings.ReplaceAll(strings.TrimSpace(sendStderr.String()), "\n", " ")
senderErr <- fmt.Errorf("Failed ZFS send: %w (%s)", err, msg)
return
}
senderErr <- nil
}()
err = receiver.Wait()
if err != nil {
_ = sender.Process.Kill()
// This removes any newlines in the error message.
msg := strings.ReplaceAll(strings.TrimSpace(recvStderr.String()), "\n", " ")
return fmt.Errorf("Failed ZFS receive: %w (%s)", err, msg)
}
err = <-senderErr
if err != nil {
return err
}
// Delete the snapshot.
_, err = shared.RunCommand("zfs", "destroy", "-r", fmt.Sprintf("%s@%s", d.dataset(vol.Volume, false), snapName))
if err != nil {
return err
}
// Cleanup unexpected snapshots.
if len(snapshots) > 0 {
children, err := d.getDatasets(d.dataset(vol.Volume, false), "snapshot")
if err != nil {
return err
}
for _, entry := range children {
// Check if expected snapshot.
if strings.Contains(entry, "@snapshot-") {
name := strings.Split(entry, "@snapshot-")[1]
if shared.ValueInSlice(name, snapshots) {
continue
}
}
// Delete the rest.
_, err := shared.RunCommand("zfs", "destroy", fmt.Sprintf("%s%s", d.dataset(vol.Volume, false), entry))
if err != nil {
return err
}
}
}
} else {
// Perform volume clone.
args := []string{"clone"}
if vol.contentType == ContentTypeBlock {
// Use volmode=none so volume is invisible until mounted.
args = append(args, "-o", "volmode=none")
}
args = append(args, srcSnapshot, d.dataset(vol.Volume, false))
// Clone the snapshot.
_, err := shared.RunCommand("zfs", args...)
if err != nil {
return err
}
}
// Apply the properties.
if vol.contentType == ContentTypeFS {
if !d.isBlockBacked(srcVol.Volume) {
err := d.setDatasetProperties(d.dataset(vol.Volume, false), "mountpoint=legacy", "canmount=noauto")
if err != nil {
return err
}
// Apply the blocksize.
err = d.setBlocksizeFromConfig(vol.Volume)
if err != nil {
return err
}
}
if d.isBlockBacked(srcVol.Volume) && renegerateFilesystemUUIDNeeded(vol.ConfigBlockFilesystem()) {
_, err := d.activateVolume(vol.Volume)
if err != nil {
return err
}
volPath, err := d.GetVolumeDiskPath(vol.Volume)
if err != nil {
return err
}
d.logger.Debug("Regenerating filesystem UUID", logger.Ctx{"dev": volPath, "fs": vol.ConfigBlockFilesystem()})
err = regenerateFilesystemUUID(vol.ConfigBlockFilesystem(), volPath)
if err != nil {
return err
}
}
// Mount the volume and ensure the permissions are set correctly inside the mounted volume.
err := vol.MountTask(func(_ string, _ *operations.Operation) error {
return vol.EnsureMountPath()
}, op)
if err != nil {
return err
}
}
// Pass allowUnsafeResize as true when resizing block backed filesystem volumes because we want to allow
// the filesystem to be shrunk as small as possible without needing the safety checks that would prevent
// leaving the filesystem in an inconsistent state if the resize couldn't be completed. This is because if
// the resize fails we will delete the volume anyway so don't have to worry about it being inconsistent.
var allowUnsafeResize bool
if d.isBlockBacked(vol.Volume) && vol.contentType == ContentTypeFS {
allowUnsafeResize = true
}
// Resize volume to the size specified. Only uses volume "size" property and does not use pool/defaults
// to give the caller more control over the size being used.
err = d.SetVolumeQuota(vol.Volume, vol.config["size"], allowUnsafeResize, op)
if err != nil {
return err
}
// All done.
revert.Success()
return nil
}
// CreateVolumeFromMigration creates a volume being sent via a migration.
func (d *zfs) CreateVolumeFromMigration(vol VolumeCopy, conn io.ReadWriteCloser, volTargetArgs migration.VolumeTargetArgs, preFiller *VolumeFiller, op *operations.Operation) error {
// Handle simple rsync and block_and_rsync through generic.
if volTargetArgs.MigrationType.FSType == migration.MigrationFSType_RSYNC || volTargetArgs.MigrationType.FSType == migration.MigrationFSType_BLOCK_AND_RSYNC {
_, err := genericVFSCreateVolumeFromMigration(d, nil, vol, conn, volTargetArgs, preFiller, op)
return err
} else if volTargetArgs.MigrationType.FSType != migration.MigrationFSType_ZFS {
return ErrNotSupported
}
var migrationHeader ZFSMetaDataHeader
// If no snapshots have been provided it can mean two things:
// 1) The target has no snapshots
// 2) Snapshots shouldn't be copied (--instance-only flag)
volumeOnly := len(volTargetArgs.Snapshots) == 0
if shared.ValueInSlice(migration.ZFSFeatureMigrationHeader, volTargetArgs.MigrationType.Features) {
// The source will send all of its snapshots with their respective GUID.
buf, err := io.ReadAll(conn)
if err != nil {
return fmt.Errorf("Failed reading ZFS migration header: %w", err)
}
err = json.Unmarshal(buf, &migrationHeader)
if err != nil {
return fmt.Errorf("Failed decoding ZFS migration header: %w", err)
}
}
// If we're refreshing, send back all snapshots of the target.
if volTargetArgs.Refresh && shared.ValueInSlice(migration.ZFSFeatureMigrationHeader, volTargetArgs.MigrationType.Features) {
snapshots, err := vol.Volume.Snapshots(op)
if err != nil {
return fmt.Errorf("Failed getting volume snapshots: %w", err)
}
// If there are no snapshots on the target, there's no point in doing an optimized
// refresh.
if len(snapshots) == 0 {
volTargetArgs.Refresh = false
}
var respSnapshots []ZFSDataset
var syncSnapshotNames []string
// Get the GUIDs of all target snapshots.
for _, snapVol := range snapshots {
guid, err := d.getDatasetProperty(d.dataset(snapVol, false), "guid")
if err != nil {
return err
}
_, snapName, _ := api.GetParentAndSnapshotName(snapVol.name)
respSnapshots = append(respSnapshots, ZFSDataset{Name: snapName, GUID: guid})
}
// Generate list of snapshots which need to be synced, i.e. are available on the source but not on the target.
for _, srcSnapshot := range migrationHeader.SnapshotDatasets {
found := false
for _, dstSnapshot := range respSnapshots {
if srcSnapshot.GUID == dstSnapshot.GUID {
found = true
break
}
}
if !found {
syncSnapshotNames = append(syncSnapshotNames, srcSnapshot.Name)
}
}
// The following scenario will result in a failure:
// - The source has more than one snapshot
// - The target has at least one of these snapshot, but not the very first
//
// It will fail because the source tries sending the first snapshot using `zfs send <first>`.
// Since the target does have snapshots, `zfs receive` will fail with:
// cannot receive new filesystem stream: destination has snapshots
//
// We therefore need to check the snapshots, and delete all target snapshots if the above
// scenario is true.
if !volumeOnly && len(respSnapshots) > 0 && len(migrationHeader.SnapshotDatasets) > 0 && respSnapshots[0].GUID != migrationHeader.SnapshotDatasets[0].GUID {
for _, snapVol := range snapshots {
// Delete
err = d.DeleteVolume(snapVol, op)
if err != nil {
return err
}
}
// Let the source know that we don't have any snapshots.
respSnapshots = []ZFSDataset{}
// Let the source know that we need all snapshots.
syncSnapshotNames = []string{}
for _, dataset := range migrationHeader.SnapshotDatasets {
syncSnapshotNames = append(syncSnapshotNames, dataset.Name)
}
} else {
// Delete local snapshots which exist on the target but not on the source.
for _, snapVol := range snapshots {
targetOnlySnapshot := true
_, snapName, _ := api.GetParentAndSnapshotName(snapVol.name)
for _, migrationSnap := range migrationHeader.SnapshotDatasets {
if snapName == migrationSnap.Name {
targetOnlySnapshot = false
break
}
}