/
driver_ceph_volumes.go
2277 lines (1878 loc) · 68.6 KB
/
driver_ceph_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"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"strings"
"time"
"github.com/google/uuid"
"golang.org/x/sys/unix"
"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/response"
"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 *ceph) CreateVolume(vol Volume, filler *VolumeFiller, op *operations.Operation) error {
// Function to rename an RBD volume.
renameVolume := func(oldName string, newName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"mv",
oldName,
newName,
)
return err
}
// 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()) })
}
// Create a "zombie" deleted volume representation of the specified volume to look for its existence.
deletedVol := NewVolume(d, d.name, cephVolumeTypeZombieImage, vol.contentType, vol.name, vol.config, vol.poolConfig)
// Check if we have a deleted zombie image. If so, restore it otherwise create a new image volume.
if vol.volType == VolumeTypeImage {
volExists, err := d.HasVolume(deletedVol)
if err != nil {
return err
}
if volExists {
canRestore := true
// 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).
volSizeBytes, err := d.getVolumeSize(d.getRBDVolumeName(deletedVol, "", false, true))
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
}
// 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, deletedVol.volType, deletedVol.contentType, strings.Replace(uuid.New().String(), "-", "", -1), deletedVol.config, deletedVol.poolConfig)
err = renameVolume(d.getRBDVolumeName(deletedVol, "", false, true), d.getRBDVolumeName(randomVol, "", false, true))
if err != nil {
return err
}
if vol.IsVMBlock() {
fsDeletedVol := deletedVol.NewVMBlockFilesystemVolume()
fsRandomVol := randomVol.NewVMBlockFilesystemVolume()
err = renameVolume(d.getRBDVolumeName(fsDeletedVol, "", false, true), d.getRBDVolumeName(fsRandomVol, "", false, true))
if err != nil {
return err
}
}
canRestore = false
}
// Restore the image.
if canRestore {
d.logger.Debug("Restoring previously deleted cached image volume", logger.Ctx{"fingerprint": vol.Name()})
err = renameVolume(d.getRBDVolumeName(deletedVol, "", false, true), d.getRBDVolumeName(vol, "", false, true))
if err != nil {
return err
}
if vol.IsVMBlock() {
fsDeletedVol := deletedVol.NewVMBlockFilesystemVolume()
fsVol := vol.NewVMBlockFilesystemVolume()
err = renameVolume(d.getRBDVolumeName(fsDeletedVol, "", false, true), d.getRBDVolumeName(fsVol, "", false, true))
if err != nil {
return err
}
}
revert.Success()
return nil
}
}
}
// Create volume.
err := d.rbdCreateVolume(vol, vol.ConfigSize())
if err != nil {
return err
}
revert.Add(func() { _ = d.DeleteVolume(vol, op) })
devPath, err := d.rbdMapVolume(vol)
if err != nil {
return err
}
revert.Add(func() { _ = d.rbdUnmapVolume(vol, true) })
// Get filesystem.
RBDFilesystem := vol.ConfigBlockFilesystem()
if vol.contentType == ContentTypeFS {
_, err = makeFSType(devPath, RBDFilesystem, nil)
if err != nil {
return err
}
}
// For VMs, also create the filesystem volume.
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
}
// Create a readonly snapshot of the image volume which will be used a the
// clone source for future non-image volumes.
if vol.volType == VolumeTypeImage {
err = d.rbdUnmapVolume(vol, true)
if err != nil {
return err
}
err = d.rbdCreateVolumeSnapshot(vol, "readonly")
if err != nil {
return err
}
revert.Add(func() { _, _ = d.deleteVolumeSnapshot(vol, "readonly") })
err = d.rbdProtectVolumeSnapshot(vol, "readonly")
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 := NewVolume(d, d.name, vol.volType, ContentTypeFS, vol.name, vol.config, vol.poolConfig)
err := d.rbdUnprotectVolumeSnapshot(fsVol, "readonly")
if err != nil {
return err
}
_, err = d.deleteVolumeSnapshot(fsVol, "readonly")
if err != nil {
return err
}
err = d.rbdCreateVolumeSnapshot(fsVol, "readonly")
if err != nil {
return err
}
revert.Add(func() { _, _ = d.deleteVolumeSnapshot(fsVol, "readonly") })
err = d.rbdProtectVolumeSnapshot(fsVol, "readonly")
if err != nil {
return err
}
}
}
revert.Success()
return nil
}
// getVolumeSize returns the volume's size in bytes.
func (d *ceph) getVolumeSize(volumeName string) (int64, error) {
volInfo := struct {
Size int64 `json:"size"`
}{}
jsonInfo, err := shared.TryRunCommand(
"rbd",
"info",
"--format", "json",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
volumeName,
)
if err != nil {
return -1, err
}
err = json.Unmarshal([]byte(jsonInfo), &volInfo)
if err != nil {
return -1, err
}
return volInfo.Size, nil
}
// CreateVolumeFromBackup re-creates a volume from its exported state.
func (d *ceph) CreateVolumeFromBackup(vol VolumeCopy, srcBackup backup.Info, srcData io.ReadSeeker, op *operations.Operation) (VolumePostHook, revert.Hook, error) {
return genericVFSBackupUnpack(d, d.state.OS, vol, srcBackup.Snapshots, srcData, op)
}
// CreateVolumeFromCopy provides same-pool volume copying functionality.
func (d *ceph) CreateVolumeFromCopy(vol VolumeCopy, srcVol VolumeCopy, allowInconsistent bool, op *operations.Operation) error {
var err error
revert := revert.New()
defer revert.Fail()
// Function to run once the volume is created, which will regenerate the filesystem UUID (if needed),
// ensure permissions on mount path inside the volume are correct, and resize the volume to specified size.
postCreateTasks := func(v Volume) error {
// Map the RBD volume.
devPath, err := d.rbdMapVolume(v)
if err != nil {
return err
}
defer func() { _ = d.rbdUnmapVolume(v, true) }()
if vol.contentType == ContentTypeFS {
// Re-generate the UUID. Do this first as ensuring permissions and setting quota can
// rely on being able to mount the volume.
err = d.generateUUID(v.ConfigBlockFilesystem(), devPath)
if err != nil {
return err
}
// Mount the volume and ensure the permissions are set correctly inside the mounted volume.
err = v.MountTask(func(_ string, _ *operations.Operation) error {
return v.EnsureMountPath()
}, op)
if err != nil {
return err
}
}
// 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"], false, op)
if err != nil {
return err
}
return nil
}
// For VMs, also copy the filesystem volume.
if vol.IsVMBlock() {
// 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
}
}
// Copy without snapshots.
if len(vol.Snapshots) == 0 || len(snapshots) == 0 {
// If lightweight clone mode isn't enabled, perform a full copy of the volume.
if shared.IsFalse(d.config["ceph.rbd.clone_copy"]) {
_, err = shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"cp",
d.getRBDVolumeName(srcVol.Volume, "", false, true),
d.getRBDVolumeName(vol.Volume, "", false, true),
)
if err != nil {
return err
}
revert.Add(func() { _ = d.DeleteVolume(vol.Volume, op) })
_, err = d.rbdMapVolume(vol.Volume)
if err != nil {
return err
}
revert.Add(func() { _ = d.rbdUnmapVolume(vol.Volume, true) })
} else {
parentVol := srcVol
snapshotName := "readonly"
if srcVol.volType != VolumeTypeImage {
snapshotName = fmt.Sprintf("zombie_snapshot_%s", uuid.New().String())
if srcVol.IsSnapshot() {
srcParentName, srcSnapOnlyName, _ := api.GetParentAndSnapshotName(srcVol.name)
snapshotName = fmt.Sprintf("snapshot_%s", srcSnapOnlyName)
parentVol = NewVolumeCopy(NewVolume(d, d.name, srcVol.volType, srcVol.contentType, srcParentName, nil, nil))
} else {
// Create snapshot.
err := d.rbdCreateVolumeSnapshot(srcVol.Volume, snapshotName)
if err != nil {
return err
}
}
// Protect volume so we can create clones of it.
err = d.rbdProtectVolumeSnapshot(parentVol.Volume, snapshotName)
if err != nil {
return err
}
revert.Add(func() { _ = d.rbdUnprotectVolumeSnapshot(parentVol.Volume, snapshotName) })
}
err = d.rbdCreateClone(parentVol.Volume, snapshotName, vol.Volume)
if err != nil {
return err
}
revert.Add(func() { _ = d.DeleteVolume(vol.Volume, op) })
}
err = postCreateTasks(vol.Volume)
if err != nil {
return err
}
revert.Success()
return nil
}
// Copy with snapshots.
// Create empty placeholder volume
err = d.rbdCreateVolume(vol.Volume, "0")
if err != nil {
return err
}
revert.Add(func() { _ = d.rbdDeleteVolume(vol.Volume) })
// Receive over the placeholder volume we created above.
targetVolumeName := d.getRBDVolumeName(vol.Volume, "", false, true)
lastSnap := ""
if len(snapshots) > 0 {
err := createParentSnapshotDirIfMissing(d.name, vol.volType, vol.name)
if err != nil {
return err
}
}
for i, snap := range snapshots {
prev := ""
if i > 0 {
prev = fmt.Sprintf("snapshot_%s", snapshots[i-1])
}
lastSnap = fmt.Sprintf("snapshot_%s", snap)
sourceVolumeName := d.getRBDVolumeName(srcVol.Volume, lastSnap, false, true)
err = d.copyVolumeDiff(sourceVolumeName, targetVolumeName, prev)
if err != nil {
return err
}
revert.Add(func() { _ = d.rbdDeleteVolumeSnapshot(vol.Volume, snap) })
snapVol, err := vol.NewSnapshot(snap)
if err != nil {
return err
}
err = snapVol.EnsureMountPath()
if err != nil {
return err
}
}
// Copy snapshot.
sourceVolumeName := d.getRBDVolumeName(srcVol.Volume, "", false, true)
err = d.copyVolumeDiff(sourceVolumeName, targetVolumeName, lastSnap)
if err != nil {
return err
}
err = postCreateTasks(vol.Volume)
if err != nil {
return err
}
revert.Success()
return nil
}
// CreateVolumeFromMigration creates a volume being sent via a migration.
// It returns the cleanup hooks required to revert any changes made during the migration.
func (d *ceph) createVolumeFromMigration(vol VolumeCopy, conn io.ReadWriteCloser, volTargetArgs migration.VolumeTargetArgs, preFiller *VolumeFiller, op *operations.Operation) (revert.Hook, error) {
// Handle simple rsync and block_and_rsync through generic.
if shared.ValueInSlice(volTargetArgs.MigrationType.FSType, []migration.MigrationFSType{migration.MigrationFSType_RSYNC, migration.MigrationFSType_BLOCK_AND_RSYNC}) || volTargetArgs.MigrationType.FSType == migration.MigrationFSType_RBD_AND_RSYNC && vol.contentType == ContentTypeFS {
return genericVFSCreateVolumeFromMigration(d, nil, vol, conn, volTargetArgs, preFiller, op)
} else if !shared.ValueInSlice(volTargetArgs.MigrationType.FSType, []migration.MigrationFSType{migration.MigrationFSType_RBD, migration.MigrationFSType_RBD_AND_RSYNC}) {
return nil, ErrNotSupported
}
var lastCommonSnapshotName string
lastCommonSnapshotIndex := d.findLastCommonSnapshotIndex(vol.Snapshots, volTargetArgs.Snapshots)
if lastCommonSnapshotIndex >= 0 {
_, lastCommonSnapshotName, _ = api.GetParentAndSnapshotName(vol.Snapshots[lastCommonSnapshotIndex].name)
}
if lastCommonSnapshotName != "" {
// Remove all snapshots from the target that will get refreshed.
// Those are all the snapshots after the last common snapshot.
lastCommonSnapshotFound := false
for _, targetSnapshot := range vol.Snapshots {
_, targetSnapshotName, _ := api.GetParentAndSnapshotName(targetSnapshot.name)
if targetSnapshotName == lastCommonSnapshotName {
// The last common snapshot was found.
// Continue the loop and start to delete all of the following snapshots.
lastCommonSnapshotFound = true
continue
}
// Delete all of the snapshots after the last common snapshot.
if lastCommonSnapshotFound {
ok, err := d.hasVolume(d.getRBDVolumeName(vol.Volume, fmt.Sprintf("snapshot_%s", targetSnapshotName), false, false))
if err != nil {
return nil, err
}
// The snapshot does not exist on the target.
if !ok {
continue
}
// Delete the snapshot if its order is out of sync.
// This happens if not the latest snapshot on the target side gets deleted and requires refresh.
_, err = d.deleteVolumeSnapshot(vol.Volume, fmt.Sprintf("snapshot_%s", targetSnapshotName))
if err != nil {
return nil, err
}
}
}
// Before syncing the snapshots restore the target to the last common snapshot.
// This is required so that the target volume is at the exact same state as the source volume.
// We can then use the Ceph RBD export-diff/import-diff functions to create the delta
// between the latest snapshot and source volume and apply it on the target volume.
err := d.restoreVolume(vol.Volume, vol.Snapshots[lastCommonSnapshotIndex], op)
if err != nil {
return nil, err
}
} else {
// In case of refresh first delete the already existing volume.
if volTargetArgs.Refresh {
// There isn't a common snapshot on the target volume.
// Delete the volume as we will create a new sparse copy.
_, err := d.deleteVolume(vol.Volume)
if err != nil {
return nil, err
}
}
// Recreate the volume.
// A filler is not required since the source diff will be applied.
// The snapshots will get synced later using the optimized approach.
// if the volume is of type snapshot, it will get recreated later from copy.
err := d.rbdCreateVolume(vol.Volume, vol.ConfigSize())
if err != nil {
return nil, err
}
}
err := vol.Volume.EnsureMountPath()
if err != nil {
return nil, err
}
revert := revert.New()
defer revert.Fail()
targetVolumeName := d.getRBDVolumeName(vol.Volume, "", false, true)
if len(volTargetArgs.Snapshots) > 0 {
lastCommonSnapshotFound := false
for _, targetSnapshot := range vol.Snapshots {
_, targetSnapshotName, _ := api.GetParentAndSnapshotName(targetSnapshot.name)
if targetSnapshotName == lastCommonSnapshotName {
// The last common snapshot was found.
// Continue the loop and start to refresh all of the following snapshots.
lastCommonSnapshotFound = true
continue
}
// Skip this snapshot if the last common one hasn't been found.
// In case there is no last common snapshot start refreshing from the first snapshot onwards.
if !lastCommonSnapshotFound && lastCommonSnapshotName != "" {
continue
}
fullSnapshotName := d.getRBDVolumeName(vol.Volume, targetSnapshotName, false, true)
wrapper := migration.ProgressWriter(op, "fs_progress", fullSnapshotName)
err := d.receiveVolume(targetVolumeName, conn, wrapper)
if err != nil {
return nil, err
}
snapVol, err := vol.NewSnapshot(targetSnapshotName)
if err != nil {
return nil, err
}
err = snapVol.EnsureMountPath()
if err != nil {
return nil, err
}
// Ensure to cleanup the snapshot on the target volume in case of error.
// When retrying the migration there shouldn't be any left over snapshot from before.
revert.Add(func() { _, _ = d.deleteVolumeSnapshot(vol.Volume, fmt.Sprintf("snapshot_%s", targetSnapshotName)) })
}
}
defer func() {
// Delete all migration-send-* snapshots.
snaps, err := d.rbdListVolumeSnapshots(vol.Volume)
if err != nil {
return
}
for _, snap := range snaps {
if !strings.HasPrefix(snap, "migration-send") {
continue
}
_ = d.rbdDeleteVolumeSnapshot(vol.Volume, snap)
}
}()
wrapper := migration.ProgressWriter(op, "fs_progress", vol.name)
// Apply the diff.
err = d.receiveVolume(targetVolumeName, conn, wrapper)
if err != nil {
return nil, err
}
cleanup := revert.Clone().Fail
revert.Success()
return cleanup, nil
}
// CreateVolumeFromMigration creates a volume being sent via a migration.
func (d *ceph) CreateVolumeFromMigration(vol VolumeCopy, conn io.ReadWriteCloser, volTargetArgs migration.VolumeTargetArgs, preFiller *VolumeFiller, op *operations.Operation) error {
if volTargetArgs.ClusterMoveSourceName != "" {
err := vol.EnsureMountPath()
if err != nil {
return err
}
if vol.IsVMBlock() {
fsVol := NewVolumeCopy(vol.NewVMBlockFilesystemVolume())
err := d.CreateVolumeFromMigration(fsVol, conn, volTargetArgs, preFiller, op)
if err != nil {
return err
}
}
return nil
}
revert := revert.New()
defer revert.Fail()
// Migrate (receive) the VMs filesystem volume too.
// This will fall back to the generic way of refreshing.
if vol.IsVMBlock() {
// Ensure that the volume's snapshots are also replaced with their filesystem counterpart.
fsVolSnapshots := make([]Volume, 0, len(vol.Snapshots))
for _, snapshot := range vol.Snapshots {
fsVolSnapshots = append(fsVolSnapshots, snapshot.NewVMBlockFilesystemVolume())
}
fsVolCopy := NewVolumeCopy(vol.NewVMBlockFilesystemVolume(), fsVolSnapshots...)
// Migrate the VMs filesystem volume and record the cleanup hooks.
// This allows cleaning up any changes made during the generic migration.
cleanup, err := d.createVolumeFromMigration(fsVolCopy, conn, volTargetArgs, preFiller, op)
if err != nil {
return err
}
revert.Add(cleanup)
}
// Migrate the actual volume and record the cleanup hooks.
cleanup, err := d.createVolumeFromMigration(vol, conn, volTargetArgs, preFiller, op)
if err != nil {
return err
}
revert.Add(cleanup)
revert.Success()
return nil
}
// refreshVolume updates an existing volume to match the state of another.
// It returns the cleanup hooks required to revert any changes made during the refresh.
func (d *ceph) refreshVolume(vol VolumeCopy, srcVol VolumeCopy, refreshSnapshots []string, allowInconsistent bool, op *operations.Operation) (revert.Hook, error) {
// Copy volumes with content type filesystem using the generic approach.
if vol.contentType == ContentTypeFS {
return genericVFSCopyVolume(d, nil, vol, srcVol, refreshSnapshots, true, allowInconsistent, op)
}
var lastCommonSnapshotName string
lastCommonSnapshotIndex := d.findLastCommonSnapshotIndex(vol.Snapshots, refreshSnapshots)
if lastCommonSnapshotIndex >= 0 {
_, lastCommonSnapshotName, _ = api.GetParentAndSnapshotName(vol.Snapshots[lastCommonSnapshotIndex].name)
}
if lastCommonSnapshotName != "" {
// Remove all snapshots from the target that will get refreshed.
// Those are all the snapshots after the last common snapshot.
lastCommonSnapshotFound := false
for _, targetSnapshot := range vol.Snapshots {
_, targetSnapshotName, _ := api.GetParentAndSnapshotName(targetSnapshot.name)
if targetSnapshotName == lastCommonSnapshotName {
// The last common snapshot was found.
// Continue the loop and start to delete all of the following snapshots.
lastCommonSnapshotFound = true
continue
}
// Delete all of the snapshots after the last common snapshot.
if lastCommonSnapshotFound {
ok, err := d.hasVolume(d.getRBDVolumeName(vol.Volume, fmt.Sprintf("snapshot_%s", targetSnapshotName), false, false))
if err != nil {
return nil, err
}
// The snapshot does not exist on the target.
if !ok {
continue
}
// Delete the snapshot if its order is out of sync.
// This happens if not the latest snapshot on the target side gets deleted and requires refresh.
// The VMs filesystem volume snapshot will not be deleted.
// It already got refreshed using the generic approach.
_, err = d.deleteVolumeSnapshot(vol.Volume, fmt.Sprintf("snapshot_%s", targetSnapshotName))
if err != nil {
return nil, err
}
}
}
// Before syncing the snapshots restore the target to the last common snapshot.
// This is required so that the target volume is at the exact same state as the source volume.
// We can then use the Ceph RBD export-diff/import-diff functions to create the delta
// between the latest snapshot and source volume and apply it on the target volume.
// The VMs filesystem volume will not be restored.
// It already got refreshed using the generic approach.
err := d.restoreVolume(vol.Volume, vol.Snapshots[lastCommonSnapshotIndex], op)
if err != nil {
return nil, err
}
} else {
// There isn't a common snapshot on the target volume.
// Delete the volume as we will create a new sparse copy.
// The VMs filesystem volume will not be deleted.
// It already got refreshed using the generic approach.
_, err := d.deleteVolume(vol.Volume)
if err != nil {
return nil, err
}
// Recreate the volume.
// A filler is not required since the source diff will be applied.
// The snapshots will get synced at a later step.
// If the volume is of type snapshot, it will get recreated later from copy.
if !srcVol.IsSnapshot() {
// The VMs filesystem volume will not be recreated.
// It already got refreshed using the generic approach.
err := d.rbdCreateVolume(vol.Volume, vol.ConfigSize())
if err != nil {
return nil, err
}
}
}
if srcVol.IsSnapshot() {
// The target volume was just deleted in the step before
// as there isn't any common snapshot when refreshing a volume from a snapshot.
// Simply copy the source volume again to the target.
return nil, d.CreateVolumeFromCopy(vol, srcVol, allowInconsistent, op)
}
// Refreshes the targetVol by applying the sourceVol.
// sourceVol can either be a volume or snapshot.
// The optional sourceParentSnap can be provided to refresh only the diff between sourceSnap and sourceParentSnap.
refresh := func(sourceVol Volume, targetVol Volume, sourceParentSnap string) error {
// If sourceVol is a snapshot append the prefix to the snapshots name to match the name of the actual snapshot.
_, sourceSnapName, _ := api.GetParentAndSnapshotName(sourceVol.Name())
if sourceSnapName != "" {
sourceSnapName = fmt.Sprintf("snapshot_%s", sourceSnapName)
}
fullSourceSnapName := d.getRBDVolumeName(sourceVol, sourceSnapName, false, true)
fullTargetVolName := d.getRBDVolumeName(targetVol, "", false, true)
return d.copyVolumeDiff(fullSourceSnapName, fullTargetVolName, sourceParentSnap)
}
revert := revert.New()
defer revert.Fail()
var lastSnap string
// Create all missing snapshots on the target using an incremental stream.
// Iterate over the source volume's snashots to be able to use them directly for the refresh.
// If snapshots should be refreshed, the lists of source and target snapshots are equal.
if len(refreshSnapshots) > 0 {
lastCommonSnapshotFound := false
for i, sourceSnapshot := range srcVol.Snapshots {
_, sourceSnapshotName, _ := api.GetParentAndSnapshotName(sourceSnapshot.name)
if sourceSnapshotName == lastCommonSnapshotName {
// The last common snapshot was found.
// Continue the loop and start to refresh all of the following snapshots.
lastCommonSnapshotFound = true
continue
}
// Skip this snapshot if the last common one hasn't been found.
// In case there is no last common snapshot start refreshing from the first snapshot onwards.
if !lastCommonSnapshotFound && lastCommonSnapshotName != "" {
continue
}
var sourceParentSnapshotName string
// If the sourceSnap doesn't have any parent we cannot set srcParentSnapName.
// In this case the first snapshot gets transferred completely without being able to create a diff.
// This also happens if the snapshot doesn't yet exist on the target.
if i > 0 {
_, sourceParentSnapshotName, _ = api.GetParentAndSnapshotName(vol.Snapshots[i-1].name)
sourceParentSnapshotName = fmt.Sprintf("snapshot_%s", sourceParentSnapshotName)
}
lastSnap = sourceParentSnapshotName
err := refresh(sourceSnapshot, vol.Volume, sourceParentSnapshotName)
if err != nil {
return nil, err
}
// Ensure to cleanup the snapshot on the target volume in case of error.
// When retrying the refresh there shouldn't be any left over snapshot from before.
revert.Add(func() { _, _ = d.deleteVolumeSnapshot(vol.Volume, fmt.Sprintf("snapshot_%s", sourceSnapshotName)) })
}
}
// A diff to the latest snapshot can only be created if the source and target volume
// have at least one common snapshot.
// Also when refreshing only the instance, take the last common snapshot to create
// the smallest possible diff.
// After refreshing the snapshots, the last common snapshot has now been changed to the latest one present on the target.
if len(vol.Snapshots) > 0 {
_, lastCommonSnapshotName, _ := api.GetParentAndSnapshotName(vol.Snapshots[len(vol.Snapshots)-1].name)
lastSnap = fmt.Sprintf("snapshot_%s", lastCommonSnapshotName)
}
// Apply the diff on the target volume.
// If commonSnap is set only the diff from the last common snapshot gets refreshed.
err := refresh(srcVol.Volume, vol.Volume, lastSnap)
if err != nil {
return nil, err
}
cleanup := revert.Clone().Fail
revert.Success()
return cleanup, nil
}
// RefreshVolume updates an existing volume to match the state of another.
func (d *ceph) RefreshVolume(vol VolumeCopy, srcVol VolumeCopy, refreshSnapshots []string, allowInconsistent bool, op *operations.Operation) error {
revert := revert.New()
defer revert.Fail()
// Refresh the VMs filesystem volume too.
// This will fall back to the generic way of refreshing.
if srcVol.IsVMBlock() {
// Ensure that the volume's snapshots are also replaced with their filesystem counterpart.
srcFsVolSnapshots := make([]Volume, 0, len(srcVol.Snapshots))
for _, snapshot := range srcVol.Snapshots {
srcFsVolSnapshots = append(srcFsVolSnapshots, snapshot.NewVMBlockFilesystemVolume())
}
fsVolSnapshots := make([]Volume, 0, len(vol.Snapshots))
for _, snapshot := range vol.Snapshots {
fsVolSnapshots = append(fsVolSnapshots, snapshot.NewVMBlockFilesystemVolume())
}
srcFsVolCopy := NewVolumeCopy(srcVol.NewVMBlockFilesystemVolume(), srcFsVolSnapshots...)
fsVolCopy := NewVolumeCopy(vol.NewVMBlockFilesystemVolume(), fsVolSnapshots...)
// Refresh the VMs filesystem volume and record the cleanup hooks.
// This allows cleaning up any changes made during the generic refresh.
cleanup, err := d.refreshVolume(fsVolCopy, srcFsVolCopy, refreshSnapshots, allowInconsistent, op)
if err != nil {
return err
}
revert.Add(cleanup)
}
// Refresh the actual volume and record the cleanup hooks.
cleanup, err := d.refreshVolume(vol, srcVol, refreshSnapshots, allowInconsistent, op)
if err != nil {
return err
}
revert.Add(cleanup)
revert.Success()
return nil
}
// DeleteVolume deletes a volume of the storage device. If any snapshots of the volume remain then
// this function will return an error.
func (d *ceph) DeleteVolume(vol Volume, op *operations.Operation) error {
volExists, err := d.HasVolume(vol)
if err != nil {
return err
}
if !volExists {
return nil
}
if vol.volType == VolumeTypeImage {
// Unmount and unmap.
_, err := d.UnmountVolume(vol, false, op)
if err != nil {
return err
}
hasReadonlySnapshot, err := d.hasVolume(d.getRBDVolumeName(vol, "readonly", false, false))
if err != nil {
return err
}
hasDependendantSnapshots := false
if hasReadonlySnapshot {
dependantSnapshots, err := d.rbdListSnapshotClones(vol, "readonly")
if err != nil && !response.IsNotFoundError(err) {
return err
}
hasDependendantSnapshots = len(dependantSnapshots) > 0
}
if hasDependendantSnapshots {
// If the image has dependant snapshots, then we just mark it as deleted, but don't
// actually remove it yet.
err = d.rbdMarkVolumeDeleted(vol, vol.name)
if err != nil {
return err
}