-
Notifications
You must be signed in to change notification settings - Fork 907
/
driver_lvm_volumes.go
1426 lines (1186 loc) · 47.2 KB
/
driver_lvm_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"
"fmt"
"io"
"math"
"os"
"os/exec"
"strings"
"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/rsync"
"github.com/canonical/lxd/lxd/storage/filesystem"
"github.com/canonical/lxd/shared"
"github.com/canonical/lxd/shared/api"
"github.com/canonical/lxd/shared/logger"
"github.com/canonical/lxd/shared/revert"
"github.com/canonical/lxd/shared/validate"
)
// CreateVolume creates an empty volume and can optionally fill it by executing the supplied filler function.
func (d *lvm) CreateVolume(vol Volume, filler *VolumeFiller, op *operations.Operation) error {
revert := revert.New()
defer revert.Fail()
volPath := vol.MountPath()
err := vol.EnsureMountPath()
if err != nil {
return err
}
revert.Add(func() { _ = os.RemoveAll(volPath) })
err = d.createLogicalVolume(d.config["lvm.vg_name"], d.thinpoolName(), vol, d.usesThinpool())
if err != nil {
return fmt.Errorf("Error creating LVM logical volume: %w", err)
}
revert.Add(func() { _ = d.DeleteVolume(vol, op) })
// 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 || !d.usesThinpool() {
// Allow filler to resize initial image and non-thin volumes 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 volume and filling it unsafe 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
}
revert.Success()
return nil
}
// CreateVolumeFromBackup restores a backup tarball onto the storage device.
func (d *lvm) 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 *lvm) CreateVolumeFromCopy(vol VolumeCopy, srcVol VolumeCopy, allowInconsistent bool, op *operations.Operation) error {
var err error
var srcSnapshots []string
if len(vol.Snapshots) > 0 && !srcVol.IsSnapshot() {
// Get the list of snapshots from the source.
allSrcSnapshots, err := srcVol.Volume.Snapshots(op)
if err != nil {
return err
}
for _, srcSnapshot := range allSrcSnapshots {
_, snapshotName, _ := api.GetParentAndSnapshotName(srcSnapshot.name)
srcSnapshots = append(srcSnapshots, snapshotName)
}
}
// We can use optimised copying when the pool is backed by an LVM thinpool.
if d.usesThinpool() {
err = d.copyThinpoolVolume(vol.Volume, srcVol.Volume, srcSnapshots, false)
if err != nil {
return err
}
// For VMs, also copy the filesystem volume.
if vol.IsVMBlock() {
srcFSVol := srcVol.NewVMBlockFilesystemVolume()
fsVol := vol.NewVMBlockFilesystemVolume()
return d.copyThinpoolVolume(fsVol, srcFSVol, srcSnapshots, false)
}
return nil
}
// Otherwise run the generic copy.
_, err = genericVFSCopyVolume(d, nil, vol, srcVol, srcSnapshots, false, allowInconsistent, op)
return err
}
// CreateVolumeFromMigration creates a volume being sent via a migration.
func (d *lvm) CreateVolumeFromMigration(vol VolumeCopy, conn io.ReadWriteCloser, volTargetArgs migration.VolumeTargetArgs, preFiller *VolumeFiller, op *operations.Operation) error {
_, err := genericVFSCreateVolumeFromMigration(d, nil, vol, conn, volTargetArgs, preFiller, op)
return err
}
// RefreshVolume provides same-pool volume and specific snapshots syncing functionality.
func (d *lvm) RefreshVolume(vol VolumeCopy, srcVol VolumeCopy, refreshSnapshots []string, allowInconsistent bool, op *operations.Operation) error {
// We can use optimised copying when the pool is backed by an LVM thinpool.
if d.usesThinpool() {
return d.copyThinpoolVolume(vol.Volume, srcVol.Volume, refreshSnapshots, true)
}
// Otherwise run the generic copy.
_, err := genericVFSCopyVolume(d, nil, vol, srcVol, refreshSnapshots, true, allowInconsistent, op)
return err
}
// DeleteVolume deletes a volume of the storage device. If any snapshots of the volume remain then this function
// will return an error.
func (d *lvm) DeleteVolume(vol Volume, op *operations.Operation) error {
snapshots, err := d.VolumeSnapshots(vol, op)
if err != nil {
return err
}
if len(snapshots) > 0 {
return fmt.Errorf("Cannot remove a volume that has snapshots")
}
volDevPath := d.lvmDevPath(d.config["lvm.vg_name"], vol.volType, vol.contentType, vol.name)
lvExists, err := d.logicalVolumeExists(volDevPath)
if err != nil {
return err
}
if lvExists {
if vol.contentType == ContentTypeFS {
_, err = d.UnmountVolume(vol, false, op)
if err != nil {
return fmt.Errorf("Error unmounting LVM logical volume: %w", err)
}
}
err = d.removeLogicalVolume(d.lvmDevPath(d.config["lvm.vg_name"], vol.volType, vol.contentType, vol.name))
if err != nil {
return fmt.Errorf("Error removing LVM logical volume: %w", err)
}
}
if vol.contentType == ContentTypeFS {
// Remove the volume from the storage device.
mountPath := vol.MountPath()
err = os.RemoveAll(mountPath)
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("Error removing LVM logical volume mount path %q: %w", mountPath, err)
}
// Although the volume snapshot directory should already be removed, lets remove it here to just in
// case the top-level directory is left.
err = deleteParentSnapshotDirIfEmpty(d.name, vol.volType, vol.name)
if err != nil {
return err
}
}
// For VMs, also delete the filesystem volume.
if vol.IsVMBlock() {
fsVol := vol.NewVMBlockFilesystemVolume()
err := d.DeleteVolume(fsVol, op)
if err != nil {
return err
}
}
return nil
}
// HasVolume indicates whether a specific volume exists on the storage pool.
func (d *lvm) HasVolume(vol Volume) (bool, error) {
volDevPath := d.lvmDevPath(d.config["lvm.vg_name"], vol.volType, vol.contentType, vol.name)
return d.logicalVolumeExists(volDevPath)
}
// FillVolumeConfig populate volume with default config.
func (d *lvm) FillVolumeConfig(vol Volume) error {
// Copy volume.* configuration options from pool.
// Exclude "block.filesystem" and "block.mount_options" as they depend on volume type (handled below).
// Exclude "lvm.stripes", "lvm.stripes.size" as they only work on non-thin storage pools (handled below).
err := d.fillVolumeConfig(&vol, "block.filesystem", "block.mount_options", "lvm.stripes", "lvm.stripes.size")
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() {
// VM volumes will always use the default filesystem.
if vol.IsVMBlock() {
vol.config["block.filesystem"] = DefaultFilesystem
} else {
// 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"
}
}
// Inherit stripe settings from pool if not set and not using thin pool.
if !d.usesThinpool() {
if vol.config["lvm.stripes"] == "" {
vol.config["lvm.stripes"] = d.config["volume.lvm.stripes"]
}
if vol.config["lvm.stripes.size"] == "" {
vol.config["lvm.stripes.size"] = d.config["lvm.stripes.size"]
}
}
return nil
}
// commonVolumeRules returns validation rules which are common for pool and volume.
func (d *lvm) commonVolumeRules() map[string]func(value string) error {
return map[string]func(value string) error{
"block.mount_options": validate.IsAny,
"block.filesystem": validate.Optional(validate.IsOneOf(blockBackedAllowedFilesystems...)),
// lxdmeta:generate(entities=storage-lvm; group=volume-conf; key=lvm.stripes)
//
// ---
// type: string
// defaultdesc: same as `volume.lvm.stripes`
// shortdesc: Number of stripes to use for new volumes (or thin pool volume)
"lvm.stripes": validate.Optional(validate.IsUint32),
// lxdmeta:generate(entities=storage-lvm; group=volume-conf; key=lvm.stripes.size)
// The size must be at least 4096 bytes, and a multiple of 512 bytes.
// ---
// type: string
// defaultdesc: same as `volume.lvm.stripes.size`
// shortdesc: Size of stripes to use
"lvm.stripes.size": validate.Optional(validate.IsSize),
}
}
// ValidateVolume validates the supplied volume config.
func (d *lvm) ValidateVolume(vol Volume, removeUnknownKeys bool) error {
commonRules := d.commonVolumeRules()
// Disallow block.* settings for regular custom block volumes. These settings only make sense
// when using custom filesystem volumes. LXD will create the filesystem
// for these volumes, and use the mount options. When attaching a regular block volume to a VM,
// these are not mounted by LXD and therefore don't need these config keys.
if vol.volType == VolumeTypeCustom && vol.contentType == ContentTypeBlock {
delete(commonRules, "block.filesystem")
delete(commonRules, "block.mount_options")
}
err := d.validateVolume(vol, commonRules, removeUnknownKeys)
if err != nil {
return err
}
if d.usesThinpool() && vol.config["lvm.stripes"] != "" {
return fmt.Errorf("lvm.stripes cannot be used with thin pool volumes")
}
if d.usesThinpool() && vol.config["lvm.stripes.size"] != "" {
return fmt.Errorf("lvm.stripes.size cannot be used with thin pool volumes")
}
return nil
}
// UpdateVolume applies config changes to the volume.
func (d *lvm) 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
}
}
_, changed := changedConfig["lvm.stripes"]
if changed {
return fmt.Errorf("lvm.stripes cannot be changed")
}
_, changed = changedConfig["lvm.stripes.size"]
if changed {
return fmt.Errorf("lvm.stripes.size cannot be changed")
}
return nil
}
// GetVolumeUsage returns the disk space used by the volume (this is not currently supported).
func (d *lvm) GetVolumeUsage(vol Volume) (int64, error) {
// Snapshot usage not supported for LVM.
if vol.IsSnapshot() {
return -1, ErrNotSupported
}
// For non-snapshot filesystem volumes, we only return usage when the volume is mounted.
// This is because to get an accurate value we cannot use blocks allocated, as the filesystem will likely
// consume blocks and not free them when files are deleted in the volume. This avoids returning different
// values depending on whether the volume is mounted or not.
if 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
} else if vol.contentType == ContentTypeBlock && d.usesThinpool() {
// For non-snapshot thin pool block volumes we can calculate an approximate usage using the space
// allocated to the volume from the thin pool.
volDevPath := d.lvmDevPath(d.config["lvm.vg_name"], vol.volType, vol.contentType, vol.name)
_, usedSize, err := d.thinPoolVolumeUsage(volDevPath)
if err != nil {
return -1, err
}
return int64(usedSize), nil
}
return -1, ErrNotSupported
}
// SetVolumeQuota applies a size limit on volume.
// Does nothing if supplied with an empty/zero size.
func (d *lvm) SetVolumeQuota(vol Volume, size string, allowUnsafeResize bool, op *operations.Operation) error {
// Do nothing if size isn't specified.
if size == "" || size == "0" {
return nil
}
sizeBytes, err := d.roundedSizeBytesString(size)
if err != nil {
return err
}
// Read actual size of current volume.
volDevPath := d.lvmDevPath(d.config["lvm.vg_name"], vol.volType, vol.contentType, vol.name)
oldSizeBytes, err := d.logicalVolumeSize(volDevPath)
if err != nil {
return err
}
// Get the volume group's physical extent size, as we use this to figure out if the new and old sizes are
// going to change beyond 1 extent size, otherwise there is no point in trying to resize as LVM do it.
vgExtentSize, err := d.volumeGroupExtentSize(d.config["lvm.vg_name"])
if err != nil {
return err
}
// Round up the number of extents required for new quota size, as this is what the lvresize tool will do.
newNumExtents := math.Ceil(float64(sizeBytes) / float64(vgExtentSize))
oldNumExtents := math.Ceil(float64(oldSizeBytes) / float64(vgExtentSize))
extentDiff := int(newNumExtents - oldNumExtents)
// If old and new extents required are the same, nothing to do, as LVM won't resize them.
if extentDiff == 0 {
return nil
}
l := d.logger.AddContext(logger.Ctx{"dev": volDevPath, "size": fmt.Sprintf("%db", sizeBytes)})
// Activate volume if needed.
activated, err := d.activateVolume(vol)
if err != nil {
return err
}
if activated {
defer func() { _, _ = d.deactivateVolume(vol) }()
}
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.
// We do this as a separate step rather than passing -r to lvresize in resizeLogicalVolume
// so that we can have more control over when we trigger unsafe filesystem resize mode,
// otherwise by passing -f to lvresize (required for other reasons) this would then pass
// -f onto resize2fs as well.
err = shrinkFileSystem(fsType, volDevPath, vol, sizeBytes, allowUnsafeResize)
if err != nil {
return err
}
l.Debug("Logical volume filesystem shrunk")
// Shrink the block device.
err = d.resizeLogicalVolume(volDevPath, sizeBytes)
if err != nil {
return err
}
} else if sizeBytes > oldSizeBytes {
// Grow block device first.
err = d.resizeLogicalVolume(volDevPath, sizeBytes)
if err != nil {
return err
}
// Grow the filesystem to fill block device.
err = growFileSystem(fsType, volDevPath, vol)
if err != nil {
return err
}
l.Debug("Logical volume filesystem grown")
}
} else {
// Only perform pre-resize checks if we are not in "unsafe" mode.
// In unsafe mode we expect the caller to know what they are doing and understand the risks.
if !allowUnsafeResize {
if sizeBytes < oldSizeBytes {
return fmt.Errorf("Block volumes cannot be shrunk: %w", ErrCannotBeShrunk)
}
if inUse {
return ErrInUse // We don't allow online resizing of block volumes.
}
}
err = d.resizeLogicalVolume(volDevPath, sizeBytes)
if err != nil {
return err
}
// Move the VM GPT alt header to end of disk if needed (not needed in unsafe resize mode as it is
// expected the caller will do all necessary post resize actions themselves).
if vol.IsVMBlock() && !allowUnsafeResize {
err = d.moveGPTAltHeader(volDevPath)
if err != nil {
return err
}
}
}
return nil
}
// GetVolumeDiskPath returns the location of a disk volume.
func (d *lvm) GetVolumeDiskPath(vol Volume) (string, error) {
if vol.IsVMBlock() || (vol.volType == VolumeTypeCustom && IsContentBlock(vol.contentType)) {
volDevPath := d.lvmDevPath(d.config["lvm.vg_name"], vol.volType, vol.contentType, vol.name)
return volDevPath, nil
}
return "", ErrNotSupported
}
// ListVolumes returns a list of LXD volumes in storage pool.
func (d *lvm) ListVolumes() ([]Volume, error) {
vols := make(map[string]Volume)
cmd := exec.Command("lvs", "--noheadings", "-o", "lv_name", d.config["lvm.vg_name"])
stdout, err := cmd.StdoutPipe()
if err != nil {
return nil, err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return nil, err
}
err = cmd.Start()
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
rawName := strings.TrimSpace(scanner.Text())
var volType VolumeType
var volName string
for _, volumeType := range d.Info().VolumeTypes {
prefix := fmt.Sprintf("%s_", volumeType)
if strings.HasPrefix(rawName, prefix) {
volType = volumeType
volName = strings.TrimPrefix(rawName, prefix)
}
}
if volType == "" {
d.logger.Debug("Ignoring unrecognised volume type", logger.Ctx{"name": rawName})
continue // Ignore unrecognised volume.
}
lvSnapSepCount := strings.Count(volName, lvmSnapshotSeparator)
if lvSnapSepCount%2 != 0 {
// If snapshot separator count is odd, then this means we have a lone lvmSnapshotSeparator
// that is not part of the lvmEscapedHyphen pair, which means this volume is a snapshot.
d.logger.Debug("Ignoring snapshot volume", logger.Ctx{"name": rawName})
continue // Ignore snapshot volumes.
}
isBlock := strings.HasSuffix(volName, lvmBlockVolSuffix)
if volType == VolumeTypeVM && !isBlock {
continue // Ignore VM filesystem volumes as we will just return the VM's block volume.
}
// Unescape raw LVM name to LXD storage volume name. Safe to do now we know we are not dealing
// with snapshot volumes.
volName = strings.Replace(volName, lvmEscapedHyphen, "-", -1)
contentType := ContentTypeFS
if volType == VolumeTypeCustom && strings.HasSuffix(volName, lvmISOVolSuffix) {
contentType = ContentTypeISO
volName = strings.TrimSuffix(volName, lvmISOVolSuffix)
} else if volType == VolumeTypeVM || isBlock {
contentType = ContentTypeBlock
volName = strings.TrimSuffix(volName, lvmBlockVolSuffix)
}
// If a new volume has been found, or the volume will replace an existing image filesystem volume
// then proceed to add the volume to the map. We allow image volumes to overwrite existing
// filesystem volumes of the same name so that for VM images we only return the block content type
// volume (so that only the single "logical" volume is returned).
existingVol, foundExisting := vols[volName]
if !foundExisting || (existingVol.Type() == VolumeTypeImage && existingVol.ContentType() == ContentTypeFS) {
v := NewVolume(d, d.name, volType, contentType, volName, make(map[string]string), d.config)
if contentType == ContentTypeFS {
v.SetMountFilesystemProbe(true)
}
vols[volName] = v
continue
}
return nil, fmt.Errorf("Unexpected duplicate volume %q found", volName)
}
errMsg, err := io.ReadAll(stderr)
if err != nil {
return nil, err
}
err = cmd.Wait()
if err != nil {
return nil, fmt.Errorf("Failed getting volume list: %v: %w", strings.TrimSpace(string(errMsg)), err)
}
volList := make([]Volume, len(vols))
for _, v := range vols {
volList = append(volList, v)
}
return volList, nil
}
// MountVolume mounts a volume and increments ref counter. Please call UnmountVolume() when done with the volume.
func (d *lvm) MountVolume(vol Volume, op *operations.Operation) error {
unlock, err := vol.MountLock()
if err != nil {
return err
}
defer unlock()
revert := revert.New()
defer revert.Fail()
// Activate LVM volume if needed.
activated, err := d.activateVolume(vol)
if err != nil {
return err
}
if activated {
revert.Add(func() { _, _ = d.deactivateVolume(vol) })
}
if vol.contentType == ContentTypeFS {
// Check if already mounted.
mountPath := vol.MountPath()
if !filesystem.IsMountPoint(mountPath) {
fsType := vol.ConfigBlockFilesystem()
volDevPath := d.lvmDevPath(d.config["lvm.vg_name"], vol.volType, vol.contentType, vol.name)
if vol.mountFilesystemProbe {
fsType, err = fsProbe(volDevPath)
if err != nil {
return fmt.Errorf("Failed probing filesystem: %w", err)
}
}
err = vol.EnsureMountPath()
if err != nil {
return err
}
mountFlags, mountOptions := filesystem.ResolveMountOptions(strings.Split(vol.ConfigBlockMountOptions(), ","))
err = TryMount(volDevPath, mountPath, fsType, mountFlags, mountOptions)
if err != nil {
return fmt.Errorf("Failed to mount LVM logical volume: %w", err)
}
d.logger.Debug("Mounted logical volume", logger.Ctx{"volName": vol.name, "dev": volDevPath, "path": mountPath, "options": mountOptions})
}
} else if vol.contentType == ContentTypeBlock {
// For VMs, mount the filesystem volume.
if vol.IsVMBlock() {
fsVol := vol.NewVMBlockFilesystemVolume()
err = d.MountVolume(fsVol, op)
if err != nil {
return err
}
}
}
vol.MountRefCountIncrement() // From here on it is up to caller to call UnmountVolume() when done.
revert.Success()
return nil
}
// UnmountVolume unmounts volume if mounted and not in use. Returns true if this unmounted the volume.
// keepBlockDev indicates if backing block device should be not be deactivated when volume is unmounted.
func (d *lvm) UnmountVolume(vol Volume, keepBlockDev bool, op *operations.Operation) (bool, error) {
unlock, err := vol.MountLock()
if err != nil {
return false, err
}
defer unlock()
ourUnmount := false
mountPath := vol.MountPath()
refCount := vol.MountRefCountDecrement()
// Check if already mounted.
if vol.contentType == ContentTypeFS && filesystem.IsMountPoint(mountPath) {
if refCount > 0 {
d.logger.Debug("Skipping unmount as in use", logger.Ctx{"volName": vol.name, "refCount": refCount})
return false, ErrInUse
}
err = TryUnmount(mountPath, 0)
if err != nil {
return false, fmt.Errorf("Failed to unmount LVM logical volume: %w", err)
}
d.logger.Debug("Unmounted logical volume", logger.Ctx{"volName": vol.name, "path": mountPath, "keepBlockDev": keepBlockDev})
// We only deactivate filesystem volumes if an unmount was needed to better align with our
// unmount return value indicator.
if !keepBlockDev {
_, err = d.deactivateVolume(vol)
if err != nil {
return false, err
}
}
ourUnmount = true
} else if vol.contentType == ContentTypeBlock {
// For VMs, unmount the filesystem volume.
if vol.IsVMBlock() {
fsVol := vol.NewVMBlockFilesystemVolume()
ourUnmount, err = d.UnmountVolume(fsVol, false, op)
if err != nil {
return false, err
}
}
volDevPath := d.lvmDevPath(d.config["lvm.vg_name"], vol.volType, vol.contentType, vol.name)
if !keepBlockDev && shared.PathExists(volDevPath) {
if refCount > 0 {
d.logger.Debug("Skipping unmount as in use", logger.Ctx{"volName": vol.name, "refCount": refCount})
return false, ErrInUse
}
_, err = d.deactivateVolume(vol)
if err != nil {
return false, err
}
ourUnmount = true
}
}
return ourUnmount, nil
}
// RenameVolume renames a volume and its snapshots.
func (d *lvm) RenameVolume(vol Volume, newVolName string, op *operations.Operation) error {
volDevPath := d.lvmDevPath(d.config["lvm.vg_name"], vol.volType, vol.contentType, vol.name)
return vol.UnmountTask(func(op *operations.Operation) error {
snapNames, err := d.VolumeSnapshots(vol, op)
if err != nil {
return err
}
revert := revert.New()
defer revert.Fail()
// Rename snapshots (change volume prefix to use new parent volume name).
for _, snapName := range snapNames {
snapVolName := GetSnapshotVolumeName(vol.name, snapName)
snapVolDevPath := d.lvmDevPath(d.config["lvm.vg_name"], vol.volType, vol.contentType, snapVolName)
newSnapVolName := GetSnapshotVolumeName(newVolName, snapName)
newSnapVolDevPath := d.lvmDevPath(d.config["lvm.vg_name"], vol.volType, vol.contentType, newSnapVolName)
err = d.renameLogicalVolume(snapVolDevPath, newSnapVolDevPath)
if err != nil {
return err
}
revert.Add(func() { _ = d.renameLogicalVolume(newSnapVolDevPath, snapVolDevPath) })
}
// Rename snapshots dir if present.
if vol.contentType == ContentTypeFS {
srcSnapshotDir := GetVolumeSnapshotDir(d.name, vol.volType, vol.name)
dstSnapshotDir := GetVolumeSnapshotDir(d.name, vol.volType, newVolName)
if shared.PathExists(srcSnapshotDir) {
err = os.Rename(srcSnapshotDir, dstSnapshotDir)
if err != nil {
return fmt.Errorf("Error renaming LVM logical volume snapshot directory from %q to %q: %w", srcSnapshotDir, dstSnapshotDir, err)
}
revert.Add(func() { _ = os.Rename(dstSnapshotDir, srcSnapshotDir) })
}
}
// Rename actual volume.
newVolDevPath := d.lvmDevPath(d.config["lvm.vg_name"], vol.volType, vol.contentType, newVolName)
err = d.renameLogicalVolume(volDevPath, newVolDevPath)
if err != nil {
return err
}
revert.Add(func() { _ = d.renameLogicalVolume(newVolDevPath, volDevPath) })
// Rename volume dir.
if vol.contentType == ContentTypeFS {
srcVolumePath := GetVolumeMountPath(d.name, vol.volType, vol.name)
dstVolumePath := GetVolumeMountPath(d.name, vol.volType, newVolName)
err = os.Rename(srcVolumePath, dstVolumePath)
if err != nil {
return fmt.Errorf("Error renaming LVM logical volume mount path from %q to %q: %w", srcVolumePath, dstVolumePath, err)
}
revert.Add(func() { _ = os.Rename(dstVolumePath, srcVolumePath) })
}
// For VMs, also rename the filesystem volume.
if vol.IsVMBlock() {
fsVol := vol.NewVMBlockFilesystemVolume()
err = d.RenameVolume(fsVol, newVolName, op)
if err != nil {
return err
}
}
revert.Success()
return nil
}, false, op)
}
// MigrateVolume sends a volume for migration.
func (d *lvm) MigrateVolume(vol VolumeCopy, conn io.ReadWriteCloser, volSrcArgs *migration.VolumeSourceArgs, op *operations.Operation) error {
return genericVFSMigrateVolume(d, d.state, vol, conn, volSrcArgs, op)
}
// BackupVolume copies a volume (and optionally its snapshots) to a specified target path.
// This driver does not support optimized backups.
func (d *lvm) BackupVolume(vol VolumeCopy, tarWriter *instancewriter.InstanceTarWriter, _ bool, snapshots []string, op *operations.Operation) error {
return genericVFSBackupVolume(d, vol, tarWriter, snapshots, op)
}
// CreateVolumeSnapshot creates a snapshot of a volume.
func (d *lvm) CreateVolumeSnapshot(snapVol Volume, op *operations.Operation) error {
parentName, _, _ := api.GetParentAndSnapshotName(snapVol.name)
parentVol := NewVolume(d, d.name, snapVol.volType, snapVol.contentType, parentName, snapVol.config, snapVol.poolConfig)
snapPath := snapVol.MountPath()
// Create the parent directory.
err := createParentSnapshotDirIfMissing(d.name, snapVol.volType, parentName)
if err != nil {
return err
}
revert := revert.New()
defer revert.Fail()
// Create snapshot directory.
err = snapVol.EnsureMountPath()
if err != nil {
return err
}
revert.Add(func() { _ = os.RemoveAll(snapPath) })
_, err = d.createLogicalVolumeSnapshot(d.config["lvm.vg_name"], parentVol, snapVol, true, d.usesThinpool())
if err != nil {
return fmt.Errorf("Error creating LVM logical volume snapshot: %w", err)
}
volDevPath := d.lvmDevPath(d.config["lvm.vg_name"], snapVol.volType, snapVol.contentType, snapVol.name)
revert.Add(func() {
_ = d.removeLogicalVolume(volDevPath)
})
// For VMs, also snapshot the filesystem.
if snapVol.IsVMBlock() {
parentFSVol := parentVol.NewVMBlockFilesystemVolume()
fsVol := snapVol.NewVMBlockFilesystemVolume()
_, err = d.createLogicalVolumeSnapshot(d.config["lvm.vg_name"], parentFSVol, fsVol, true, d.usesThinpool())
if err != nil {
return fmt.Errorf("Error creating LVM logical volume snapshot: %w", err)
}
}
revert.Success()
return nil
}
// DeleteVolumeSnapshot removes a snapshot from the storage device. The volName and snapshotName
// must be bare names and should not be in the format "volume/snapshot".
func (d *lvm) DeleteVolumeSnapshot(snapVol Volume, op *operations.Operation) error {
// Remove the snapshot from the storage device.
volDevPath := d.lvmDevPath(d.config["lvm.vg_name"], snapVol.volType, snapVol.contentType, snapVol.name)
lvExists, err := d.logicalVolumeExists(volDevPath)
if err != nil {
return err
}
if lvExists {
_, err = d.UnmountVolume(snapVol, false, op)
if err != nil {
return fmt.Errorf("Error unmounting LVM logical volume: %w", err)
}
err = d.removeLogicalVolume(d.lvmDevPath(d.config["lvm.vg_name"], snapVol.volType, snapVol.contentType, snapVol.name))
if err != nil {
return fmt.Errorf("Error removing LVM logical volume: %w", err)
}
}
// For VMs, also remove the snapshot filesystem volume.
if snapVol.IsVMBlock() {
fsVol := snapVol.NewVMBlockFilesystemVolume()
err = d.DeleteVolumeSnapshot(fsVol, op)
if err != nil {
return err
}
}
// Remove the snapshot mount path from the storage device.
snapPath := snapVol.MountPath()
err = os.RemoveAll(snapPath)
if err != nil && !os.IsNotExist(err) {
return fmt.Errorf("Error removing LVM snapshot mount path %q: %w", snapPath, err)
}
// Remove the parent snapshot directory if this is the last snapshot being removed.
parentName, _, _ := api.GetParentAndSnapshotName(snapVol.name)
err = deleteParentSnapshotDirIfEmpty(d.name, snapVol.volType, parentName)
if err != nil {
return err
}
return nil
}
// MountVolumeSnapshot sets up a read-only mount on top of the snapshot to avoid accidental modifications.
func (d *lvm) MountVolumeSnapshot(snapVol Volume, op *operations.Operation) error {
unlock, err := snapVol.MountLock()
if err != nil {
return err
}
defer unlock()
revert := revert.New()
defer revert.Fail()
mountPath := snapVol.MountPath()
// Check if already mounted.
if snapVol.contentType == ContentTypeFS && !filesystem.IsMountPoint(mountPath) {
err = snapVol.EnsureMountPath()
if err != nil {
return err
}
// Default to mounting the original snapshot directly. This may be changed below if a temporary
// snapshot needs to be taken.
mountVol := snapVol
mountFlags, mountOptions := filesystem.ResolveMountOptions(strings.Split(mountVol.ConfigBlockMountOptions(), ","))
// Regenerate filesystem UUID if needed. This is because some filesystems do not allow mounting
// multiple volumes that share the same UUID. As snapshotting a volume will copy its UUID we need
// to potentially regenerate the UUID of the snapshot now that we are trying to mount it.
// This is done at mount time rather than snapshot time for 2 reasons; firstly snapshots need to be
// as fast as possible, and on some filesystems regenerating the UUID is a slow process, secondly