/
driver_ceph_volumes.go
1844 lines (1508 loc) · 49.7 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/pborman/uuid"
"golang.org/x/sys/unix"
"github.com/lxc/lxd/lxd/backup"
"github.com/lxc/lxd/lxd/migration"
"github.com/lxc/lxd/lxd/operations"
"github.com/lxc/lxd/lxd/response"
"github.com/lxc/lxd/lxd/revert"
"github.com/lxc/lxd/lxd/storage/filesystem"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/instancewriter"
"github.com/lxc/lxd/shared/ioprogress"
"github.com/lxc/lxd/shared/logger"
"github.com/lxc/lxd/shared/units"
"github.com/lxc/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(), "-", "", -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 Volume, 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 Volume, srcVol Volume, copySnapshots bool, 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, vol.config["size"], false, op)
if err != nil {
return err
}
return nil
}
// Retrieve snapshots on the source.
snapshots := []string{}
if !srcVol.IsSnapshot() && copySnapshots {
snapshots, err = d.VolumeSnapshots(srcVol, op)
if err != nil {
return err
}
}
// Copy without snapshots.
if !copySnapshots || 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, "", false, true),
d.getRBDVolumeName(vol, "", false, true),
)
if err != nil {
return err
}
revert.Add(func() { _ = d.DeleteVolume(vol, op) })
_, err = d.rbdMapVolume(vol)
if err != nil {
return err
}
revert.Add(func() { _ = d.rbdUnmapVolume(vol, true) })
} else {
parentVol := srcVol
snapshotName := "readonly"
if srcVol.volType != VolumeTypeImage {
snapshotName = fmt.Sprintf("zombie_snapshot_%s", uuid.New())
if srcVol.IsSnapshot() {
srcParentName, srcSnapOnlyName, _ := api.GetParentAndSnapshotName(srcVol.name)
snapshotName = fmt.Sprintf("snapshot_%s", srcSnapOnlyName)
parentVol = NewVolume(d, d.name, srcVol.volType, srcVol.contentType, srcParentName, nil, nil)
} else {
// Create snapshot.
err := d.rbdCreateVolumeSnapshot(srcVol, snapshotName)
if err != nil {
return err
}
}
// Protect volume so we can create clones of it.
err = d.rbdProtectVolumeSnapshot(parentVol, snapshotName)
if err != nil {
return err
}
revert.Add(func() { _ = d.rbdUnprotectVolumeSnapshot(parentVol, snapshotName) })
}
err = d.rbdCreateClone(parentVol, snapshotName, vol)
if err != nil {
return err
}
revert.Add(func() { _ = d.DeleteVolume(vol, op) })
}
// For VMs, also copy the filesystem volume.
if vol.IsVMBlock() {
srcFSVol := srcVol.NewVMBlockFilesystemVolume()
fsVol := vol.NewVMBlockFilesystemVolume()
err := d.CreateVolumeFromCopy(fsVol, srcFSVol, false, false, op)
if err != nil {
return err
}
}
err = postCreateTasks(vol)
if err != nil {
return err
}
revert.Success()
return nil
}
// Copy with snapshots.
// Create empty placeholder volume
err = d.rbdCreateVolume(vol, "0")
if err != nil {
return err
}
revert.Add(func() { _ = d.rbdDeleteVolume(vol) })
// Receive over the placeholder volume we created above.
targetVolumeName := d.getRBDVolumeName(vol, "", 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, lastSnap, false, true)
err = d.copyWithSnapshots(sourceVolumeName, targetVolumeName, prev)
if err != nil {
return err
}
revert.Add(func() { _ = d.rbdDeleteVolumeSnapshot(vol, 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, "", false, true)
err = d.copyWithSnapshots(sourceVolumeName, targetVolumeName, lastSnap)
if err != nil {
return err
}
err = postCreateTasks(vol)
if err != nil {
return err
}
revert.Success()
return nil
}
// CreateVolumeFromMigration creates a volume being sent via a migration.
func (d *ceph) CreateVolumeFromMigration(vol Volume, 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 := vol.NewVMBlockFilesystemVolume()
err := d.CreateVolumeFromMigration(fsVol, conn, volTargetArgs, preFiller, op)
if err != nil {
return err
}
}
return nil
}
// Handle simple rsync and block_and_rsync through generic.
if volTargetArgs.MigrationType.FSType == migration.MigrationFSType_RSYNC || volTargetArgs.MigrationType.FSType == migration.MigrationFSType_BLOCK_AND_RSYNC {
return genericVFSCreateVolumeFromMigration(d, nil, vol, conn, volTargetArgs, preFiller, op)
} else if volTargetArgs.MigrationType.FSType != migration.MigrationFSType_RBD {
return ErrNotSupported
}
if vol.IsVMBlock() {
fsVol := vol.NewVMBlockFilesystemVolume()
err := d.CreateVolumeFromMigration(fsVol, conn, volTargetArgs, preFiller, op)
if err != nil {
return err
}
}
recvName := d.getRBDVolumeName(vol, "", false, true)
volExists, err := d.HasVolume(vol)
if err != nil {
return err
}
if !volExists {
err := d.rbdCreateVolume(vol, "0")
if err != nil {
return err
}
}
err = vol.EnsureMountPath()
if err != nil {
return err
}
// Handle zfs send/receive migration.
if len(volTargetArgs.Snapshots) > 0 {
// Create the parent directory.
err := createParentSnapshotDirIfMissing(d.name, vol.volType, vol.name)
if err != nil {
return err
}
// Transfer the snapshots.
for _, snapName := range volTargetArgs.Snapshots {
fullSnapshotName := d.getRBDVolumeName(vol, snapName, false, true)
wrapper := migration.ProgressWriter(op, "fs_progress", fullSnapshotName)
err = d.receiveVolume(recvName, conn, wrapper)
if err != nil {
return err
}
snapVol, err := vol.NewSnapshot(snapName)
if err != nil {
return err
}
err = snapVol.EnsureMountPath()
if err != nil {
return err
}
}
}
defer func() {
// Delete all migration-send-* snapshots.
snaps, err := d.rbdListVolumeSnapshots(vol)
if err != nil {
return
}
for _, snap := range snaps {
if !strings.HasPrefix(snap, "migration-send") {
continue
}
_ = d.rbdDeleteVolumeSnapshot(vol, snap)
}
}()
wrapper := migration.ProgressWriter(op, "fs_progress", vol.name)
err = d.receiveVolume(recvName, conn, wrapper)
if err != nil {
return err
}
// Map the RBD volume.
devPath, err := d.rbdMapVolume(vol)
if err != nil {
return err
}
defer func() { _ = d.rbdUnmapVolume(vol, true) }()
// Re-generate the UUID.
err = d.generateUUID(vol.ConfigBlockFilesystem(), devPath)
if err != nil {
return err
}
return nil
}
// RefreshVolume updates an existing volume to match the state of another.
func (d *ceph) RefreshVolume(vol Volume, srcVol Volume, srcSnapshots []Volume, allowInconsistent bool, op *operations.Operation) error {
return genericVFSCopyVolume(d, nil, vol, srcVol, srcSnapshots, true, allowInconsistent, op)
}
// 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
}
} else {
if hasReadonlySnapshot {
// Unprotect snapshot.
err := d.rbdUnprotectVolumeSnapshot(vol, "readonly")
if err != nil {
return err
}
}
// Delete snapshots.
_, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
"snap",
"purge",
d.getRBDVolumeName(vol, "", false, false))
if err != nil {
return err
}
// Delete image.
err = d.rbdDeleteVolume(vol)
if err != nil {
return err
}
}
} else {
// Unmount and unmap.
_, err := d.UnmountVolume(vol, false, op)
if err != nil {
return err
}
_, err = d.deleteVolume(vol)
if err != nil {
return fmt.Errorf("Failed to delete volume: %w", err)
}
}
if vol.IsVMBlock() {
fsVol := vol.NewVMBlockFilesystemVolume()
err := d.DeleteVolume(fsVol, op)
if err != nil {
return err
}
}
mountPath := vol.MountPath()
if vol.contentType == ContentTypeFS && shared.PathExists(mountPath) {
err := wipeDirectory(mountPath)
if err != nil {
return err
}
err = os.Remove(mountPath)
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("Failed to remove '%s': %w", mountPath, err)
}
}
return nil
}
// hasVolume indicates whether a specific RBD volume exists on the storage pool.
func (d *ceph) hasVolume(rbdVolumeName string) (bool, error) {
ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second)
defer cancel()
_, err := shared.RunCommandContext(ctx,
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
"info",
rbdVolumeName,
)
if err != nil {
runErr, ok := err.(shared.RunError)
if ok {
exitError, ok := runErr.Unwrap().(*exec.ExitError)
if ok {
if exitError.ExitCode() == 2 {
return false, nil
}
}
}
return false, err
}
return true, nil
}
// HasVolume indicates whether a specific volume exists on the storage pool.
func (d *ceph) HasVolume(vol Volume) (bool, error) {
return d.hasVolume(d.getRBDVolumeName(vol, "", false, false))
}
// FillVolumeConfig populate volume with default config.
func (d *ceph) FillVolumeConfig(vol Volume) error {
// Copy volume.* configuration options from pool.
// Exclude 'block.filesystem' and 'block.mount_options'
// as this ones are handled below in this function and depends from volume type
err := d.fillVolumeConfig(&vol, "block.filesystem", "block.mount_options")
if err != nil {
return err
}
// Only validate filesystem config keys for filesystem volumes or VM block volumes (which have an
// associated filesystem volume).
if vol.ContentType() == ContentTypeFS || vol.IsVMBlock() {
// Inherit filesystem from pool if not set.
if vol.config["block.filesystem"] == "" {
vol.config["block.filesystem"] = d.config["volume.block.filesystem"]
}
// Default filesystem if neither volume nor pool specify an override.
if vol.config["block.filesystem"] == "" {
// Unchangeable volume property: Set unconditionally.
vol.config["block.filesystem"] = DefaultFilesystem
}
// Inherit filesystem mount options from pool if not set.
if vol.config["block.mount_options"] == "" {
vol.config["block.mount_options"] = d.config["volume.block.mount_options"]
}
// Default filesystem mount options if neither volume nor pool specify an override.
if vol.config["block.mount_options"] == "" {
// Unchangeable volume property: Set unconditionally.
vol.config["block.mount_options"] = "discard"
}
}
return nil
}
// commonVolumeRules returns validation rules which are common for pool and volume.
func (d *ceph) commonVolumeRules() map[string]func(value string) error {
return map[string]func(value string) error{
"block.filesystem": validate.Optional(validate.IsOneOf(blockBackedAllowedFilesystems...)),
"block.mount_options": validate.IsAny,
}
}
// ValidateVolume validates the supplied volume config.
func (d *ceph) ValidateVolume(vol Volume, removeUnknownKeys bool) error {
return d.validateVolume(vol, d.commonVolumeRules(), removeUnknownKeys)
}
// UpdateVolume applies config changes to the volume.
func (d *ceph) UpdateVolume(vol Volume, changedConfig map[string]string) error {
newSize, sizeChanged := changedConfig["size"]
if sizeChanged {
err := d.SetVolumeQuota(vol, newSize, false, nil)
if err != nil {
return err
}
}
return nil
}
// GetVolumeUsage returns the disk space used by the volume.
func (d *ceph) GetVolumeUsage(vol Volume) (int64, error) {
isSnap := vol.IsSnapshot()
// If mounted, use the filesystem stats for pretty accurate usage information.
if !isSnap && vol.contentType == ContentTypeFS && filesystem.IsMountPoint(vol.MountPath()) {
var stat unix.Statfs_t
err := unix.Statfs(vol.MountPath(), &stat)
if err != nil {
return -1, err
}
return int64(stat.Blocks-stat.Bfree) * int64(stat.Bsize), nil
}
// Running rbd du can be resource intensive, so users may want to miss disk usage
// data for stopped instances instead of dealing with the performance hit
if shared.IsFalse(d.config["ceph.rbd.du"]) {
return -1, fmt.Errorf("Cannot get disk usage of unmounted volume when ceph.rbd.du is false")
}
// If not mounted (or not mountable), query the usage from ceph directly.
// This is rather inaccurate as there is no way to get the size of a
// volume without its snapshots. Instead we need to merge the size
// of all snapshots with the delta since last snapshot. This leads to
// volumes with lots of changes between snapshots potentially adding up far
// more usage than they actually have.
type cephDuLine struct {
Name string `json:"name"`
Snapshot string `json:"snapshot"`
ProvisionedSize int64 `json:"provisioned_size"`
UsedSize int64 `json:"used_size"`
}
type cephDuInfo struct {
Images []cephDuLine `json:"images"`
}
ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second)
defer cancel()
jsonInfo, err := shared.RunCommandContext(ctx,
"rbd",
"du",
"--format", "json",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
d.getRBDVolumeName(vol, "", false, false),
)
if err != nil {
return -1, err
}
var usedSize int64
var result cephDuInfo
err = json.Unmarshal([]byte(jsonInfo), &result)
if err != nil {
return -1, err
}
_, snapName, _ := api.GetParentAndSnapshotName(vol.Name())
snapName = fmt.Sprintf("snapshot_%s", snapName)
// rbd du gives the output of all related rbd images, snapshots included.
for _, image := range result.Images {
if isSnap {
// For snapshot volumes we only want to get the specific image used so we can
// indicate how much CoW usage that snapshot has.
if image.Snapshot == snapName {
usedSize = image.UsedSize
break
}
} else {
// For non-snapshot volumes, to get the total size of the volume we need to add up
// all of the image's usage.
usedSize += image.UsedSize
}
}
return usedSize, nil
}
// SetVolumeQuota applies a size limit on volume.
// Does nothing if supplied with an empty/zero size.
func (d *ceph) SetVolumeQuota(vol Volume, size string, allowUnsafeResize bool, op *operations.Operation) error {
// Convert to bytes.
sizeBytes, err := units.ParseByteSizeString(size)
if err != nil {
return err
}
// Do nothing if size isn't specified.
if sizeBytes <= 0 {
return nil
}
ourMap, devPath, err := d.getRBDMappedDevPath(vol, true)
if err != nil {
return err
}
if ourMap {
defer func() { _ = d.rbdUnmapVolume(vol, true) }()
}
oldSizeBytes, err := BlockDiskSizeBytes(devPath)
if err != nil {
return fmt.Errorf("Error getting current size: %w", err)
}
// Do nothing if volume is already specified size (+/- 512 bytes).
if oldSizeBytes+512 > sizeBytes && oldSizeBytes-512 < sizeBytes {
return nil
}
// Block image volumes cannot be resized because they have a readonly snapshot that doesn't get
// updated when the volume's size is changed, and this is what instances are created from.
// During initial volume fill allowUnsafeResize is enabled because snapshot hasn't been taken yet.
if !allowUnsafeResize && vol.volType == VolumeTypeImage {
return ErrNotSupported
}
inUse := vol.MountInUse()
// Resize filesystem if needed.
if vol.contentType == ContentTypeFS {
fsType := vol.ConfigBlockFilesystem()
if sizeBytes < oldSizeBytes {
if !filesystemTypeCanBeShrunk(fsType) {
return fmt.Errorf("Filesystem %q cannot be shrunk: %w", fsType, ErrCannotBeShrunk)
}
if inUse {
return ErrInUse // We don't allow online shrinking of filesytem volumes.
}
// Shrink filesystem first. Pass allowUnsafeResize to allow disabling of filesystem
// resize safety checks.
err = shrinkFileSystem(fsType, devPath, vol, sizeBytes, allowUnsafeResize)
if err != nil {
return err