/
driver_ceph_utils.go
1273 lines (1083 loc) · 34.3 KB
/
driver_ceph_utils.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 (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"regexp"
"strconv"
"strings"
"time"
"github.com/pborman/uuid"
"github.com/lxc/lxd/lxd/db"
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/ioprogress"
log "github.com/lxc/lxd/shared/log15"
"github.com/lxc/lxd/shared/units"
)
// cephBlockVolSuffix suffix used for block content type volumes.
const cephBlockVolSuffix = ".block"
const cephVolumeTypeZombieImage = VolumeType("zombie_image")
// cephVolTypePrefixes maps volume type to storage volume name prefix.
var cephVolTypePrefixes = map[VolumeType]string{
VolumeTypeContainer: db.StoragePoolVolumeTypeNameContainer,
VolumeTypeVM: db.StoragePoolVolumeTypeNameVM,
VolumeTypeImage: db.StoragePoolVolumeTypeNameImage,
VolumeTypeCustom: db.StoragePoolVolumeTypeNameCustom,
}
// osdPoolExists checks whether a given OSD pool exists.
func (d *ceph) osdPoolExists() bool {
_, err := shared.RunCommand(
"ceph",
"--name", fmt.Sprintf("client.%s", d.config["ceph.user.name"]),
"--cluster", d.config["ceph.cluster_name"],
"osd",
"pool",
"get",
d.config["ceph.osd.pool_name"],
"size")
return err == nil
}
// osdDeletePool destroys an OSD pool.
// - A call to osdDeletePool will destroy a pool including any storage
// volumes that still exist in the pool.
// - In case the OSD pool that is supposed to be deleted does not exist this
// command will still exit 0. This means that if the caller wants to be sure
// that this call actually deleted an OSD pool it needs to check for the
// existence of the pool first.
func (d *ceph) osdDeletePool() error {
_, err := shared.RunCommand("ceph",
"--name", fmt.Sprintf("client.%s", d.config["ceph.user.name"]),
"--cluster", d.config["ceph.cluster_name"],
"osd",
"pool",
"delete",
d.config["ceph.osd.pool_name"],
d.config["ceph.osd.pool_name"],
"--yes-i-really-really-mean-it")
if err != nil {
return err
}
return nil
}
// rbdCreateVolume creates an RBD storage volume.
// Note that the default set of features is intentionally limited
// by passing --image-feature explicitly. This is done to ensure that
// the chances of a conflict between the features supported by the userspace
// library and the kernel module are minimized. Otherwise random panics might
// occur.
func (d *ceph) rbdCreateVolume(vol Volume, size string) error {
sizeBytes, err := units.ParseByteSizeString(size)
if err != nil {
return err
}
cmd := []string{
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
}
if d.config["ceph.rbd.features"] != "" {
for _, feature := range util.SplitNTrimSpace(d.config["ceph.rbd.features"], ",", -1, true) {
cmd = append(cmd, "--image-feature", feature)
}
} else {
cmd = append(cmd, "--image-feature", "layering")
}
if d.config["ceph.osd.data_pool_name"] != "" {
cmd = append(cmd, "--data-pool", d.config["ceph.osd.data_pool_name"])
}
cmd = append(cmd,
"--size", fmt.Sprintf("%dB", sizeBytes),
"create",
d.getRBDVolumeName(vol, "", false, false))
_, err = shared.RunCommand("rbd", cmd...)
return err
}
// rbdDeleteVolume deletes an RBD storage volume.
// - In case the RBD storage volume that is supposed to be deleted does not
// exist this command will still exit 0. This means that if the caller wants
// to be sure that this call actually deleted an RBD storage volume it needs
// to check for the existence of the pool first.
func (d *ceph) rbdDeleteVolume(vol Volume) error {
_, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
"rm",
d.getRBDVolumeName(vol, "", false, false))
if err != nil {
return err
}
return nil
}
// rbdMapVolume maps a given RBD storage volume.
// This will ensure that the RBD storage volume is accessible as a block device
// in the /dev directory and is therefore necessary in order to mount it.
func (d *ceph) rbdMapVolume(vol Volume) (string, error) {
rbdName := d.getRBDVolumeName(vol, "", false, false)
devPath, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
"map",
rbdName)
if err != nil {
return "", err
}
idx := strings.Index(devPath, "/dev/rbd")
if idx < 0 {
return "", fmt.Errorf("Failed to detect mapped device path")
}
devPath = strings.TrimSpace(devPath[idx:])
d.logger.Debug("Activated RBD volume", log.Ctx{"vol": rbdName, "dev": devPath})
return devPath, nil
}
// rbdUnmapVolume unmaps a given RBD storage volume.
// This is a precondition in order to delete an RBD storage volume can.
func (d *ceph) rbdUnmapVolume(vol Volume, unmapUntilEINVAL bool) error {
busyCount := 0
rbdVol := d.getRBDVolumeName(vol, "", false, false)
ourDeactivate := false
again:
_, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
"unmap",
rbdVol)
if err != nil {
runError, ok := err.(shared.RunError)
if ok {
exitError, ok := runError.Err.(*exec.ExitError)
if ok {
if exitError.ExitCode() == 22 {
// EINVAL (already unmapped).
if ourDeactivate {
d.logger.Debug("Deactivated RBD volume", log.Ctx{"vol": rbdVol})
}
return nil
}
if exitError.ExitCode() == 16 {
// EBUSY (currently in use).
busyCount++
if busyCount == 10 {
return err
}
// Wait a second an try again.
time.Sleep(time.Second)
goto again
}
}
}
return err
}
if unmapUntilEINVAL {
ourDeactivate = true
goto again
}
d.logger.Debug("Deactivated RBD volume", log.Ctx{"vol": rbdVol})
return nil
}
// rbdUnmapVolumeSnapshot unmaps a given RBD snapshot.
// This is a precondition in order to delete an RBD snapshot can.
func (d *ceph) rbdUnmapVolumeSnapshot(vol Volume, snapshotName string, unmapUntilEINVAL bool) error {
again:
_, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
"unmap",
d.getRBDVolumeName(vol, snapshotName, false, false))
if err != nil {
runError, ok := err.(shared.RunError)
if ok {
exitError, ok := runError.Err.(*exec.ExitError)
if ok {
if exitError.ExitCode() == 22 {
// EINVAL (already unmapped).
return nil
}
}
}
return err
}
if unmapUntilEINVAL {
goto again
}
return nil
}
// rbdCreateVolumeSnapshot creates a read-write snapshot of a given RBD storage volume.
func (d *ceph) rbdCreateVolumeSnapshot(vol Volume, snapshotName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
"snap",
"create",
"--snap", snapshotName,
d.getRBDVolumeName(vol, "", false, false))
if err != nil {
return err
}
return nil
}
// rbdProtectVolumeSnapshot protects a given snapshot from being deleted.
// This is a precondition to be able to create RBD clones from a given snapshot.
func (d *ceph) rbdProtectVolumeSnapshot(vol Volume, snapshotName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
"snap",
"protect",
"--snap", snapshotName,
d.getRBDVolumeName(vol, "", false, false))
if err != nil {
runError, ok := err.(shared.RunError)
if ok {
exitError, ok := runError.Err.(*exec.ExitError)
if ok {
if exitError.ExitCode() == 16 {
// EBUSY (snapshot already protected).
return nil
}
}
}
return err
}
return nil
}
// rbdUnprotectVolumeSnapshot unprotects a given snapshot.
// - This is a precondition to be able to delete an RBD snapshot.
// - This command will only succeed if the snapshot does not have any clones.
func (d *ceph) rbdUnprotectVolumeSnapshot(vol Volume, snapshotName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
"snap",
"unprotect",
"--snap", snapshotName,
d.getRBDVolumeName(vol, "", false, false))
if err != nil {
runError, ok := err.(shared.RunError)
if ok {
exitError, ok := runError.Err.(*exec.ExitError)
if ok {
if exitError.ExitCode() == 22 {
// EBUSY (snapshot already unprotected).
return nil
}
}
}
return err
}
return nil
}
// rbdCreateClone creates a clone from a protected RBD snapshot.
func (d *ceph) rbdCreateClone(sourceVol Volume, sourceSnapshotName string, targetVol Volume) error {
cmd := []string{
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
}
if d.config["ceph.rbd.features"] != "" {
for _, feature := range util.SplitNTrimSpace(d.config["ceph.rbd.features"], ",", -1, true) {
cmd = append(cmd, "--image-feature", feature)
}
} else {
cmd = append(cmd, "--image-feature", "layering")
}
if d.config["ceph.osd.data_pool_name"] != "" {
cmd = append(cmd, "--data-pool", d.config["ceph.osd.data_pool_name"])
}
cmd = append(cmd,
"clone",
d.getRBDVolumeName(sourceVol, sourceSnapshotName, false, true),
d.getRBDVolumeName(targetVol, "", false, true))
_, err := shared.RunCommand("rbd", cmd...)
if err != nil {
return err
}
return nil
}
// rbdListSnapshotClones list all clones of an RBD snapshot.
func (d *ceph) rbdListSnapshotClones(vol Volume, snapshotName string) ([]string, error) {
msg, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
"children",
"--image", d.getRBDVolumeName(vol, "", false, false),
"--snap", snapshotName)
if err != nil {
return nil, err
}
msg = strings.TrimSpace(msg)
clones := strings.Fields(msg)
if len(clones) == 0 {
return nil, db.ErrNoSuchObject
}
return clones, nil
}
// rbdMarkVolumeDeleted marks an RBD storage volume as being in "zombie" state.
// An RBD storage volume that is in zombie state is not tracked in LXD's
// database anymore but still needs to be kept around for the sake of any
// dependent storage entities in the storage pool. This usually happens when an
// RBD storage volume has protected snapshots; a scenario most common when
// creating a sparse copy of a container or when LXD updated an image and the
// image still has dependent container clones.
func (d *ceph) rbdMarkVolumeDeleted(vol Volume, newVolumeName string) error {
// Ensure that new volume contains the config from the source volume to maintain filesystem suffix on
// new volume name generated in getRBDVolumeName.
newVol := NewVolume(d, d.name, vol.volType, vol.contentType, newVolumeName, vol.config, vol.poolConfig)
deletedName := d.getRBDVolumeName(newVol, "", true, true)
_, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"mv",
d.getRBDVolumeName(vol, "", false, true),
deletedName,
)
if err != nil {
return err
}
return nil
}
// rbdRenameVolume renames a given RBD storage volume.
// Note that this usually requires that the image be unmapped under its original
// name, then renamed, and finally will be remapped again. If it is not unmapped
// under its original name and the callers maps it under its new name the image
// will be mapped twice. This will prevent it from being deleted.
func (d *ceph) rbdRenameVolume(vol Volume, newVolumeName string) error {
// Ensure that new volume contains the config from the source volume to maintain filesystem suffix on
// new volume name generated in getRBDVolumeName.
newVol := NewVolume(d, d.name, vol.volType, vol.contentType, newVolumeName, vol.config, vol.poolConfig)
_, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"mv",
d.getRBDVolumeName(vol, "", false, true),
d.getRBDVolumeName(newVol, "", false, true),
)
if err != nil {
return err
}
return nil
}
// rbdRenameVolumeSnapshot renames a given RBD storage volume.
// Note that if the snapshot is mapped - which it usually shouldn't be - this
// usually requires that the snapshot be unmapped under its original name, then
// renamed, and finally will be remapped again. If it is not unmapped under its
// original name and the caller maps it under its new name the snapshot will be
// mapped twice. This will prevent it from being deleted.
func (d *ceph) rbdRenameVolumeSnapshot(vol Volume, oldSnapshotName string, newSnapshotName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"snap",
"rename",
d.getRBDVolumeName(vol, oldSnapshotName, false, true),
d.getRBDVolumeName(vol, newSnapshotName, false, true))
if err != nil {
return err
}
return nil
}
// rbdGetVolumeParent will return the snapshot the RBD clone was created from:
// - If the RBD storage volume is not a clone then this function will return
// db.NoSuchObjectError.
// - The snapshot will be returned as
// <osd-pool-name>/<rbd-volume-name>@<rbd-snapshot-name>
// The caller will usually want to parse this according to its needs. This
// helper library provides two small functions to do this but see below.
func (d *ceph) rbdGetVolumeParent(vol Volume) (string, error) {
msg, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
"info",
d.getRBDVolumeName(vol, "", false, false))
if err != nil {
return "", err
}
idx := strings.Index(msg, "parent: ")
if idx == -1 {
return "", db.ErrNoSuchObject
}
msg = msg[(idx + len("parent: ")):]
msg = strings.TrimSpace(msg)
idx = strings.Index(msg, "\n")
if idx == -1 {
return "", fmt.Errorf("Unexpected parsing error")
}
msg = msg[:idx]
msg = strings.TrimSpace(msg)
return msg, nil
}
// rbdDeleteVolumeSnapshot deletes an RBD snapshot.
// This requires that the snapshot does not have any clones and is unmapped and
// unprotected.
func (d *ceph) rbdDeleteVolumeSnapshot(vol Volume, snapshotName string) error {
_, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
"snap",
"rm",
d.getRBDVolumeName(vol, snapshotName, false, false))
if err != nil {
return err
}
return nil
}
// rbdListVolumeSnapshots retrieves the snapshots of an RBD storage volume.
// The format of the snapshot names is simply the part after the @. So given a
// valid RBD path relative to a pool
// <osd-pool-name>/<rbd-storage-volume>@<rbd-snapshot-name>
// this will only return
// <rbd-snapshot-name>
func (d *ceph) rbdListVolumeSnapshots(vol Volume) ([]string, error) {
msg, err := shared.RunCommand(
"rbd",
"--id", d.config["ceph.user.name"],
"--format", "json",
"--cluster", d.config["ceph.cluster_name"],
"--pool", d.config["ceph.osd.pool_name"],
"snap",
"ls",
d.getRBDVolumeName(vol, "", false, false))
if err != nil {
return []string{}, err
}
var data []map[string]interface{}
err = json.Unmarshal([]byte(msg), &data)
if err != nil {
return []string{}, err
}
snapshots := []string{}
for _, v := range data {
_, ok := v["name"]
if !ok {
return []string{}, fmt.Errorf("No \"name\" property found")
}
name, ok := v["name"].(string)
if !ok {
return []string{}, fmt.Errorf("\"name\" property did not have string type")
}
name = strings.TrimSpace(name)
snapshots = append(snapshots, name)
}
if len(snapshots) == 0 {
return []string{}, db.ErrNoSuchObject
}
return snapshots, nil
}
// copyWithSnapshots creates a non-sparse copy of a container including its snapshots.
// This does not introduce a dependency relation between the source RBD storage
// volume and the target RBD storage volume.
func (d *ceph) copyWithSnapshots(sourceVolumeName string, targetVolumeName string, sourceParentSnapshot string) error {
args := []string{
"export-diff",
"--id", d.config["ceph.user.name"],
"--cluster", d.config["ceph.cluster_name"],
sourceVolumeName,
}
if sourceParentSnapshot != "" {
args = append(args, "--from-snap", sourceParentSnapshot)
}
// Redirect output to stdout.
args = append(args, "-")
rbdSendCmd := exec.Command("rbd", args...)
rbdRecvCmd := exec.Command(
"rbd",
"--id", d.config["ceph.user.name"],
"import-diff",
"--cluster", d.config["ceph.cluster_name"],
"-",
targetVolumeName)
rbdRecvCmd.Stdin, _ = rbdSendCmd.StdoutPipe()
rbdRecvCmd.Stdout = os.Stdout
rbdRecvCmd.Stderr = os.Stderr
err := rbdRecvCmd.Start()
if err != nil {
return err
}
err = rbdSendCmd.Run()
if err != nil {
return err
}
err = rbdRecvCmd.Wait()
if err != nil {
return err
}
return nil
}
// deleteVolume deletes the RBD storage volume of a container including any dependencies.
// - This function takes care to delete any RBD storage entities that are marked
// as zombie and whose existence is solely dependent on the RBD storage volume
// for the container to be deleted.
// - This function will mark any storage entities of the container to be deleted
// as zombies in case any RBD storage entities in the storage pool have a
// dependency relation with it.
// - This function uses a C-style convention to return error or success simply
// because it is more elegant and simple than the go way.
// The function will return
// -1 on error
// 0 if the RBD storage volume has been deleted
// 1 if the RBD storage volume has been marked as a zombie
// - deleteVolume in conjunction with deleteVolumeSnapshot
// recurses through an OSD storage pool to find and delete any storage
// entities that were kept around because of dependency relations but are not
// deletable.
func (d *ceph) deleteVolume(vol Volume) (int, error) {
snaps, err := d.rbdListVolumeSnapshots(vol)
if err == nil {
var zombies int
for _, snap := range snaps {
ret, err := d.deleteVolumeSnapshot(vol, snap)
if ret < 0 {
return -1, err
} else if ret == 1 {
zombies++
}
}
if zombies > 0 {
// Unmap.
err = d.rbdUnmapVolume(vol, true)
if err != nil {
return -1, err
}
if strings.HasPrefix(vol.name, "zombie_") || strings.HasPrefix(string(vol.volType), "zombie_") {
return 1, nil
}
newVolumeName := fmt.Sprintf("%s_%s", vol.name, uuid.New())
err := d.rbdMarkVolumeDeleted(vol, newVolumeName)
if err != nil {
return -1, err
}
return 1, nil
} else if zombies == 0 {
// Delete.
err = d.rbdDeleteVolume(vol)
if err != nil {
return -1, err
}
}
} else {
if err != db.ErrNoSuchObject {
return -1, err
}
parent, err := d.rbdGetVolumeParent(vol)
if err == nil {
parentVol, parentSnapshotName, err := d.parseParent(parent)
if err != nil {
return -1, err
}
// Unmap.
err = d.rbdUnmapVolume(vol, true)
if err != nil {
return -1, err
}
// Delete.
err = d.rbdDeleteVolume(vol)
if err != nil {
return -1, err
}
// Only delete the parent snapshot of the instance if it is a zombie.
// This includes both if the parent volume itself is a zombie, or if the just the snapshot
// is a zombie. If it is not we know that LXD is still using it.
if strings.HasPrefix(string(parentVol.volType), "zombie_") || strings.HasPrefix(parentSnapshotName, "zombie_") {
ret, err := d.deleteVolumeSnapshot(parentVol, parentSnapshotName)
if ret < 0 {
return -1, err
}
}
} else {
if err != db.ErrNoSuchObject {
return -1, err
}
// Unmap.
err = d.rbdUnmapVolume(vol, true)
if err != nil {
return -1, err
}
// Delete.
err = d.rbdDeleteVolume(vol)
if err != nil {
return -1, err
}
}
}
return 0, nil
}
// deleteVolumeSnapshot deletes an RBD snapshot of a container including any dependencies.
// - This function takes care to delete any RBD storage entities that are marked
// as zombie and whose existence is solely dependent on the RBD snapshot for
// the container to be deleted.
// - This function will mark any storage entities of the container to be deleted
// as zombies in case any RBD storage entities in the storage pool have a
// dependency relation with it.
// - This function uses a C-style convention to return error or success simply
// because it is more elegant and simple than the go way.
// The function will return
// -1 on error
// 0 if the RBD storage volume has been deleted
// 1 if the RBD storage volume has been marked as a zombie
// - deleteVolumeSnapshot in conjunction with deleteVolume
// recurses through an OSD storage pool to find and delete any storage
// entities that were kept around because of dependency relations but are not
// deletable.
func (d *ceph) deleteVolumeSnapshot(vol Volume, snapshotName string) (int, error) {
clones, err := d.rbdListSnapshotClones(vol, snapshotName)
if err != nil {
if err != db.ErrNoSuchObject {
return -1, err
}
// Unprotect.
err = d.rbdUnprotectVolumeSnapshot(vol, snapshotName)
if err != nil {
return -1, err
}
// Unmap.
err = d.rbdUnmapVolumeSnapshot(vol, snapshotName, true)
if err != nil {
return -1, err
}
// Delete.
err = d.rbdDeleteVolumeSnapshot(vol, snapshotName)
if err != nil {
return -1, err
}
// Only delete the parent image if it is a zombie. If it is not we know that LXD is still using it.
if strings.HasPrefix(string(vol.volType), "zombie_") {
ret, err := d.deleteVolume(vol)
if ret < 0 {
return -1, err
}
}
return 0, nil
}
canDelete := true
for _, clone := range clones {
_, cloneType, cloneName, err := d.parseClone(clone)
if err != nil {
return -1, err
}
if !strings.HasPrefix(cloneType, "zombie_") {
canDelete = false
continue
}
cloneVol := NewVolume(d, d.name, VolumeType(cloneType), vol.contentType, cloneName, nil, nil)
ret, err := d.deleteVolume(cloneVol)
if ret < 0 {
return -1, err
} else if ret == 1 {
// Only marked as zombie.
canDelete = false
}
}
if canDelete {
// Unprotect.
err = d.rbdUnprotectVolumeSnapshot(vol, snapshotName)
if err != nil {
return -1, err
}
// Unmap.
err = d.rbdUnmapVolumeSnapshot(vol, snapshotName, true)
if err != nil {
return -1, err
}
// Delete.
err = d.rbdDeleteVolumeSnapshot(vol, snapshotName)
if err != nil {
return -1, err
}
// Only delete the parent image if it is a zombie. If it
// is not we know that LXD is still using it.
if strings.HasPrefix(string(vol.volType), "zombie_") {
ret, err := d.deleteVolume(vol)
if ret < 0 {
return -1, err
}
}
} else {
if strings.HasPrefix(snapshotName, "zombie_") {
return 1, nil
}
err := d.rbdUnmapVolumeSnapshot(vol, snapshotName, true)
if err != nil {
return -1, err
}
newSnapshotName := fmt.Sprintf("zombie_snapshot_%s", uuid.New())
err = d.rbdRenameVolumeSnapshot(vol, snapshotName, newSnapshotName)
if err != nil {
return -1, err
}
}
return 1, nil
}
// parseParent splits a string describing a RBD storage entity into its components.
// This can be used on strings like: <osd-pool-name>/<lxd-specific-prefix>_<rbd-storage-volume>@<rbd-snapshot-name>
// and will return a Volume and snapshot name.
func (d *ceph) parseParent(parent string) (Volume, string, error) {
vol := Volume{}
idx := strings.Index(parent, "/")
if idx == -1 {
return vol, "", fmt.Errorf("Pool delimiter not found")
}
slider := parent[(idx + 1):]
poolName := parent[:idx]
// Match image volumes and extract their various parts into a Volume struct.
// Looks for volumes like:
// pool/zombie_image_9e90b7b9ccdd7a671a987fadcf07ab92363be57e7f056d18d42af452cdaf95bb_ext4.block@readonly
// pool/image_9e90b7b9ccdd7a671a987fadcf07ab92363be57e7f056d18d42af452cdaf95bb_xfs
reImage := regexp.MustCompile(`^((?:zombie_)?image)_([A-Za-z0-9]+)_([A-Za-z0-9]+)\.?(block)?@?([-\w]+)?$`)
if imageRes := reImage.FindStringSubmatch(slider); imageRes != nil {
vol.volType = VolumeType(imageRes[1])
vol.pool = poolName
vol.name = imageRes[2]
vol.config = map[string]string{
"block.filesystem": imageRes[3],
}
if imageRes[4] == "block" {
vol.contentType = ContentTypeBlock
} else {
vol.contentType = ContentTypeFS
}
return vol, imageRes[5], nil
}
// Match normal instance volumes.
// Looks for volumes like:
// pool/container_bar@zombie_snapshot_ce77e971-6c1b-45c0-b193-dba9ec5e7d82
reInst := regexp.MustCompile(`^((?:zombie_)?[a-z-]+)_([\w-]+)\.?(block)?@?([-\w]+)?$`)
if instRes := reInst.FindStringSubmatch(slider); instRes != nil {
vol.volType = VolumeType(instRes[1])
vol.pool = poolName
vol.name = instRes[2]
if instRes[3] == "block" {
vol.contentType = ContentTypeBlock
} else {
vol.contentType = ContentTypeFS
}
return vol, instRes[4], nil
}
return vol, "", fmt.Errorf("Unrecognised parent: %q", parent)
}
// parseClone splits a strings describing an RBD storage volume.
// For example a string like
// <osd-pool-name>/<lxd-specific-prefix>_<rbd-storage-volume>
// will be split into
// <osd-pool-name>, <lxd-specific-prefix>, <rbd-storage-volume>
func (d *ceph) parseClone(clone string) (string, string, string, error) {
idx := strings.Index(clone, "/")
if idx == -1 {
return "", "", "", fmt.Errorf("Unexpected parsing error")
}
slider := clone[(idx + 1):]
poolName := clone[:idx]
volumeType := slider
idx = strings.Index(slider, "zombie_")
if idx == 0 {
idx += len("zombie_")
volumeType = slider
slider = slider[idx:]
}
idxType := strings.Index(slider, "_")
if idxType == -1 {
return "", "", "", fmt.Errorf("Unexpected parsing error")
}
if idx == len("zombie_") {
idxType += idx
}
volumeType = volumeType[:idxType]
idx = strings.Index(slider, "_")
if idx == -1 {
return "", "", "", fmt.Errorf("Unexpected parsing error")
}
volumeName := slider
idx = strings.Index(volumeName, "_")
if idx == -1 {
return "", "", "", fmt.Errorf("Unexpected parsing error")
}
volumeName = volumeName[(idx + 1):]
return poolName, volumeType, volumeName, nil
}
// getRBDMappedDevPath looks at sysfs to retrieve the device path. If it doesn't find it it will map it if told to
// do so. Returns bool indicating if map was needed and device path e.g. "/dev/rbd<idx>" for an RBD image.
func (d *ceph) getRBDMappedDevPath(vol Volume, mapIfMissing bool) (bool, string, error) {
// List all RBD devices.
files, err := ioutil.ReadDir("/sys/devices/rbd")
if err != nil && !os.IsNotExist(err) {
return false, "", err
}
// Go through the existing RBD devices.
for _, f := range files {
fName := f.Name()
// Skip if not a directory.
if !f.IsDir() {
continue
}
// Skip if not a device directory.
idx, err := strconv.ParseUint(fName, 10, 64)
if err != nil {
continue
}
// Get the pool for the RBD device.
devPoolName, err := ioutil.ReadFile(fmt.Sprintf("/sys/devices/rbd/%s/pool", fName))
if err != nil {
// Skip if no pool file.
if os.IsNotExist(err) {
continue
}
return false, "", err
}
// Skip if the pools don't match.
if strings.TrimSpace(string(devPoolName)) != d.config["ceph.osd.pool_name"] {
continue
}
// Get the volume name for the RBD device.
devName, err := ioutil.ReadFile(fmt.Sprintf("/sys/devices/rbd/%s/name", fName))
if err != nil {
// Skip if no name file.
if os.IsNotExist(err) {
continue
}
return false, "", err
}