-
Notifications
You must be signed in to change notification settings - Fork 547
/
rbd_util.go
2157 lines (1829 loc) · 57.2 KB
/
rbd_util.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
/*
Copyright 2018 The Ceph-CSI Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package rbd
import (
"context"
"encoding/json"
"errors"
"fmt"
"math"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/ceph/ceph-csi/internal/util"
"github.com/ceph/ceph-csi/internal/util/log"
"github.com/ceph/go-ceph/rados"
librbd "github.com/ceph/go-ceph/rbd"
"github.com/ceph/go-ceph/rbd/admin"
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/golang/protobuf/ptypes/timestamp"
"google.golang.org/protobuf/types/known/timestamppb"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/cloud-provider/volume/helpers"
mount "k8s.io/mount-utils"
)
const (
// The following three values are used for 30 seconds timeout
// while waiting for RBD Watcher to expire.
rbdImageWatcherInitDelay = 1 * time.Second
rbdImageWatcherFactor = 1.4
rbdImageWatcherSteps = 10
rbdDefaultMounter = "rbd"
rbdNbdMounter = "rbd-nbd"
defaultLogDir = "/var/log/ceph"
defaultLogStrategy = "remove" // supports remove, compress and preserve
// Output strings returned during invocation of "ceph rbd task add remove <imagespec>" when
// command is not supported by ceph manager. Used to check errors and recover when the command
// is unsupported.
rbdTaskRemoveCmdInvalidString = "No handler found"
rbdTaskRemoveCmdAccessDeniedMessage = "access denied:"
// migration label key and value for parameters in volume context.
intreeMigrationKey = "migration"
intreeMigrationLabel = "true"
migInTreeImagePrefix = "kubernetes-dynamic-pvc-"
// migration volume handle identifiers.
// total length of fields in the migration volume handle.
migVolIDTotalLength = 4
// split boundary length of fields.
migVolIDSplitLength = 3
// separator for migration handle fields.
migVolIDFieldSep = "_"
// identifier of a migration vol handle.
migIdentifier = "mig"
// prefix of image field.
migImageNamePrefix = "image-"
// prefix in the handle for monitors field.
migMonPrefix = "mons-"
// krbd attribute file to check supported features.
krbdSupportedFeaturesFile = "/sys/bus/rbd/supported_features"
// clusterNameKey cluster Key, set on RBD image.
clusterNameKey = "csi.ceph.com/cluster/name"
)
// rbdImage contains common attributes and methods for the rbdVolume and
// rbdSnapshot types.
type rbdImage struct {
// RbdImageName is the name of the RBD image backing this rbdVolume.
// This does not have a JSON tag as it is not stashed in JSON encoded
// config maps in v1.0.0
RbdImageName string
// ImageID contains the image id of the image
ImageID string
// VolID is the volume ID that is exchanged with CSI drivers,
// identifying this rbd image
VolID string `json:"volID"`
Monitors string
// JournalPool is the ceph pool in which the CSI Journal/CSI snapshot Journal is
// stored
JournalPool string
// Pool is where the image journal/image snapshot journal and image/snapshot
// is stored, and could be the same as `JournalPool` (retained as Pool instead of
// renaming to ImagePool or such, as this is referenced in the code
// extensively)
Pool string
RadosNamespace string
ClusterID string `json:"clusterId"`
// RequestName is the CSI generated volume name for the rbdVolume.
// This does not have a JSON tag as it is not stashed in JSON encoded
// config maps in v1.0.0
RequestName string
NamePrefix string
// ParentName represents the parent image name of the image.
ParentName string
// Parent Pool is the pool that contains the parent image.
ParentPool string
// Cluster name
ClusterName string
// Owner is the creator (tenant, Kubernetes Namespace) of the volume
Owner string
// VolSize is the size of the RBD image backing this rbdImage.
VolSize int64
// image striping configurations.
StripeCount uint64
StripeUnit uint64
ObjectSize uint64
ImageFeatureSet librbd.FeatureSet
// blockEncryption provides access to optional VolumeEncryption functions (e.g LUKS)
blockEncryption *util.VolumeEncryption
// fileEncryption provides access to optional VolumeEncryption functions (e.g fscrypt)
fileEncryption *util.VolumeEncryption
CreatedAt *timestamp.Timestamp
// conn is a connection to the Ceph cluster obtained from a ConnPool
conn *util.ClusterConnection
// an opened IOContext, call .openIoctx() before using
ioctx *rados.IOContext
// Set metadata on volume
EnableMetadata bool
}
// rbdVolume represents a CSI volume and its RBD image specifics.
type rbdVolume struct {
rbdImage
// VolName and MonValueFromSecret are retained from older plugin versions (<= 1.0.0)
// for backward compatibility reasons
TopologyPools *[]util.TopologyConstrainedPool
TopologyRequirement *csi.TopologyRequirement
Topology map[string]string
// DataPool is where the data for images in `Pool` are stored, this is used as the `--data-pool`
// argument when the pool is created, and is not used anywhere else
DataPool string
AdminID string
UserID string
Mounter string
ReservedID string
MapOptions string
UnmapOptions string
LogDir string
LogStrategy string
VolName string
MonValueFromSecret string
// Network namespace file path to execute nsenter command
NetNamespaceFilePath string
// RequestedVolSize has the size of the volume requested by the user and
// this value will not be updated when doing getImageInfo() on rbdVolume.
RequestedVolSize int64
DisableInUseChecks bool
readOnly bool
}
// rbdSnapshot represents a CSI snapshot and its RBD snapshot specifics.
type rbdSnapshot struct {
rbdImage
// SourceVolumeID is the volume ID of RbdImageName, that is exchanged with CSI drivers
// RbdSnapName is the name of the RBD snapshot backing this rbdSnapshot
SourceVolumeID string
ReservedID string
RbdSnapName string
}
// imageFeature represents required image features and value.
type imageFeature struct {
// needRbdNbd indicates whether this image feature requires an rbd-nbd mounter
needRbdNbd bool
// dependsOn is the image features required for this imageFeature
dependsOn []string
}
// migrationvolID is a struct which consists of required fields of a rbd volume
// from migrated volumeID.
type migrationVolID struct {
imageName string
poolName string
clusterID string
}
var (
supportedFeatures = map[string]imageFeature{
librbd.FeatureNameLayering: {
needRbdNbd: false,
},
librbd.FeatureNameExclusiveLock: {
needRbdNbd: false,
},
librbd.FeatureNameObjectMap: {
needRbdNbd: false,
dependsOn: []string{librbd.FeatureNameExclusiveLock},
},
librbd.FeatureNameFastDiff: {
needRbdNbd: false,
dependsOn: []string{librbd.FeatureNameObjectMap},
},
librbd.FeatureNameJournaling: {
needRbdNbd: true,
dependsOn: []string{librbd.FeatureNameExclusiveLock},
},
librbd.FeatureNameDeepFlatten: {
needRbdNbd: false,
},
}
krbdLayeringSupport = []util.KernelVersion{
{
Version: 3,
PatchLevel: 8,
SubLevel: 0,
},
}
krbdStripingV2Support = []util.KernelVersion{
{
Version: 3,
PatchLevel: 10,
SubLevel: 0,
},
}
krbdExclusiveLockSupport = []util.KernelVersion{
{
Version: 4,
PatchLevel: 9,
SubLevel: 0,
},
}
krbdDataPoolSupport = []util.KernelVersion{
{
Version: 4,
PatchLevel: 11,
SubLevel: 0,
},
}
)
// prepareKrbdFeatureAttrs prepare krbd fearure set based on kernel version.
// Minimum kernel version should be 3.8, else it will return error.
func prepareKrbdFeatureAttrs() (uint64, error) {
// fetch the current running kernel info
release, err := util.GetKernelVersion()
if err != nil {
return 0, fmt.Errorf("fetching current kernel version failed: %w", err)
}
switch {
case util.CheckKernelSupport(release, krbdDataPoolSupport):
return librbd.FeatureDataPool, nil
case util.CheckKernelSupport(release, krbdExclusiveLockSupport):
return librbd.FeatureExclusiveLock, nil
case util.CheckKernelSupport(release, krbdStripingV2Support):
return librbd.FeatureStripingV2, nil
case util.CheckKernelSupport(release, krbdLayeringSupport):
return librbd.FeatureLayering, nil
}
log.ErrorLogMsg("kernel version is too old: %q", release)
return 0, os.ErrNotExist
}
// GetKrbdSupportedFeatures load the module if needed and return supported
// features attribute as a string.
func GetKrbdSupportedFeatures() (string, error) {
var stderr string
// check if the module is loaded or compiled in
_, err := os.Stat(krbdSupportedFeaturesFile)
if err != nil {
if !os.IsNotExist(err) {
log.ErrorLogMsg("stat on %q failed: %v", krbdSupportedFeaturesFile, err)
return "", err
}
// try to load the module
_, stderr, err = util.ExecCommand(context.TODO(), "modprobe", rbdDefaultMounter)
if err != nil {
log.ErrorLogMsg("modprobe failed (%v): %q", err, stderr)
return "", err
}
}
val, err := os.ReadFile(krbdSupportedFeaturesFile)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
log.ErrorLogMsg("reading file %q failed: %v", krbdSupportedFeaturesFile, err)
return "", err
}
attrs, err := prepareKrbdFeatureAttrs()
if err != nil {
log.ErrorLogMsg("preparing krbd feature attributes failed, %v", err)
return "", err
}
return strconv.FormatUint(attrs, 16), nil
}
return strings.TrimSuffix(string(val), "\n"), nil
}
// HexStringToInteger convert hex value to uint.
func HexStringToInteger(hexString string) (uint, error) {
// trim 0x prefix
numberStr := strings.TrimPrefix(strings.ToLower(hexString), "0x")
output, err := strconv.ParseUint(numberStr, 16, 64)
if err != nil {
log.ErrorLogMsg("converting string %q to integer failed: %v", numberStr, err)
return 0, err
}
return uint(output), nil
}
// isKrbdFeatureSupported checks if a given Image Feature is supported by krbd
// driver or not.
func isKrbdFeatureSupported(ctx context.Context, imageFeatures string) (bool, error) {
// return false when /sys/bus/rbd/supported_features is absent and we are
// not in a position to prepare krbd feature attributes, i.e. if kernel <= 3.8
if krbdFeatures == 0 {
return false, os.ErrNotExist
}
arr := strings.Split(imageFeatures, ",")
log.UsefulLog(ctx, "checking for ImageFeatures: %v", arr)
imageFeatureSet := librbd.FeatureSetFromNames(arr)
supported := true
for _, featureName := range imageFeatureSet.Names() {
if (uint(librbd.FeatureSetFromNames(strings.Split(featureName, " "))) & krbdFeatures) == 0 {
supported = false
log.ErrorLog(ctx, "krbd feature %q not supported", featureName)
break
}
}
return supported, nil
}
// Connect an rbdVolume to the Ceph cluster.
func (ri *rbdImage) Connect(cr *util.Credentials) error {
if ri.conn != nil {
return nil
}
conn := &util.ClusterConnection{}
if err := conn.Connect(ri.Monitors, cr); err != nil {
return err
}
ri.conn = conn
return nil
}
// Destroy cleans up the rbdVolume and closes the connection to the Ceph
// cluster in case one was setup.
func (ri *rbdImage) Destroy() {
if ri.ioctx != nil {
ri.ioctx.Destroy()
}
if ri.conn != nil {
ri.conn.Destroy()
}
if ri.isBlockEncrypted() {
ri.blockEncryption.Destroy()
}
if ri.isFileEncrypted() {
ri.fileEncryption.Destroy()
}
}
// String returns the image-spec (pool/{namespace/}image) format of the image.
func (ri *rbdImage) String() string {
if ri.RadosNamespace != "" {
return fmt.Sprintf("%s/%s/%s", ri.Pool, ri.RadosNamespace, ri.RbdImageName)
}
return fmt.Sprintf("%s/%s", ri.Pool, ri.RbdImageName)
}
// String returns the snap-spec (pool/{namespace/}image@snap) format of the snapshot.
func (rs *rbdSnapshot) String() string {
if rs.RadosNamespace != "" {
return fmt.Sprintf("%s/%s/%s@%s", rs.Pool, rs.RadosNamespace, rs.RbdImageName, rs.RbdSnapName)
}
return fmt.Sprintf("%s/%s@%s", rs.Pool, rs.RbdImageName, rs.RbdSnapName)
}
// createImage creates a new ceph image with provision and volume options.
func createImage(ctx context.Context, pOpts *rbdVolume, cr *util.Credentials) error {
volSzMiB := fmt.Sprintf("%dM", util.RoundOffVolSize(pOpts.VolSize))
log.DebugLog(ctx, "rbd: create %s size %s (features: %s) using mon %s",
pOpts, volSzMiB, pOpts.ImageFeatureSet.Names(), pOpts.Monitors)
options := librbd.NewRbdImageOptions()
defer options.Destroy()
err := pOpts.setImageOptions(ctx, options)
if err != nil {
return err
}
err = pOpts.Connect(cr)
if err != nil {
return err
}
err = pOpts.openIoctx()
if err != nil {
return fmt.Errorf("failed to get IOContext: %w", err)
}
err = librbd.CreateImage(pOpts.ioctx, pOpts.RbdImageName,
uint64(util.RoundOffVolSize(pOpts.VolSize)*helpers.MiB), options)
if err != nil {
return fmt.Errorf("failed to create rbd image: %w", err)
}
if pOpts.isBlockEncrypted() {
err = pOpts.setupBlockEncryption(ctx)
if err != nil {
return fmt.Errorf("failed to setup encryption for image %s: %w", pOpts, err)
}
}
return nil
}
func (ri *rbdImage) openIoctx() error {
if ri.ioctx != nil {
return nil
}
ioctx, err := ri.conn.GetIoctx(ri.Pool)
if err != nil {
// GetIoctx() can return util.ErrPoolNotFound
return err
}
ioctx.SetNamespace(ri.RadosNamespace)
ri.ioctx = ioctx
return nil
}
// getImageID queries rbd about the given image and stores its id, returns
// ErrImageNotFound if provided image is not found.
func (ri *rbdImage) getImageID() error {
if ri.ImageID != "" {
return nil
}
image, err := ri.open()
if err != nil {
return err
}
defer image.Close()
id, err := image.GetId()
if err != nil {
return err
}
ri.ImageID = id
return nil
}
// open the rbdImage after it has been connected.
// ErrPoolNotFound or ErrImageNotFound are returned in case the pool or image
// can not be found, other errors will contain more details about other issues
// (permission denied, ...) and are expected to relate to configuration issues.
func (ri *rbdImage) open() (*librbd.Image, error) {
err := ri.openIoctx()
if err != nil {
return nil, err
}
image, err := librbd.OpenImage(ri.ioctx, ri.RbdImageName, librbd.NoSnapshot)
if err != nil {
if errors.Is(err, librbd.ErrNotFound) {
err = util.JoinErrors(ErrImageNotFound, err)
}
return nil, err
}
return image, nil
}
// isInUse checks if there is a watcher on the image. It returns true if there
// is a watcher on the image, otherwise returns false.
// In case of mirroring, the image should be primary to check watchers if the
// image is secondary it returns an error.
// isInUse is called with exponential backoff to check the image is used by
// anyone else the returned bool value is discarded if its a RWX access.
func (ri *rbdImage) isInUse() (bool, error) {
image, err := ri.open()
if err != nil {
if errors.Is(err, ErrImageNotFound) || errors.Is(err, util.ErrPoolNotFound) {
return false, err
}
// any error should assume something else is using the image
return true, err
}
defer image.Close()
watchers, err := image.ListWatchers()
if err != nil {
return false, err
}
mirrorInfo, err := image.GetMirrorImageInfo()
if err != nil {
return false, err
}
if mirrorInfo.State == librbd.MirrorImageEnabled && !mirrorInfo.Primary {
// Mapping secondary image can cause issues.returning error as the
// bool value is discarded if it its RWX access.
return false, fmt.Errorf("cannot map image %s it is not primary", ri)
}
// because we opened the image, there is at least one watcher
defaultWatchers := 1
if mirrorInfo.Primary {
// if rbd mirror daemon is running, a watcher will be added by the rbd
// mirror daemon for mirrored images.
defaultWatchers++
}
return len(watchers) > defaultWatchers, nil
}
// checkValidImageFeatures check presence of imageFeatures parameter. It returns false when
// there imageFeatures is present and empty.
func checkValidImageFeatures(imageFeatures string, ok bool) bool {
return !(ok && imageFeatures == "")
}
// isNotMountPoint checks whether MountPoint does not exists and
// also discards error indicating mountPoint exists.
func isNotMountPoint(mounter mount.Interface, stagingTargetPath string) (bool, error) {
isMnt, err := mounter.IsMountPoint(stagingTargetPath)
if os.IsNotExist(err) {
err = nil
}
return !isMnt, err
}
// isCephMgrSupported determines if the cluster has support for MGR based operation
// depending on the error.
func isCephMgrSupported(ctx context.Context, clusterID string, err error) bool {
switch {
case err == nil:
return true
case strings.Contains(err.Error(), rbdTaskRemoveCmdInvalidString):
log.WarningLog(
ctx,
"cluster with cluster ID (%s) does not support Ceph manager based rbd commands"+
"(minimum ceph version required is v14.2.3)",
clusterID)
return false
case strings.Contains(err.Error(), rbdTaskRemoveCmdAccessDeniedMessage):
log.WarningLog(ctx, "access denied to Ceph MGR-based rbd commands on cluster ID (%s)", clusterID)
return false
}
return true
}
// ensureImageCleanup finds image in trash and if found removes it
// from trash.
func (ri *rbdImage) ensureImageCleanup(ctx context.Context) error {
trashInfoList, err := librbd.GetTrashList(ri.ioctx)
if err != nil {
log.ErrorLog(ctx, "failed to list images in trash: %v", err)
return err
}
for _, val := range trashInfoList {
if val.Name == ri.RbdImageName {
ri.ImageID = val.Id
return ri.trashRemoveImage(ctx)
}
}
return nil
}
// deleteImage deletes a ceph image with provision and volume options.
func (ri *rbdImage) deleteImage(ctx context.Context) error {
image := ri.RbdImageName
log.DebugLog(ctx, "rbd: delete %s using mon %s, pool %s", image, ri.Monitors, ri.Pool)
// Support deleting the older rbd images whose imageID is not stored in omap
err := ri.getImageID()
if err != nil {
return err
}
if ri.isBlockEncrypted() {
log.DebugLog(ctx, "rbd: going to remove DEK for %q (block encryption)", ri)
if err = ri.blockEncryption.RemoveDEK(ri.VolID); err != nil {
log.WarningLog(ctx, "failed to clean the passphrase for volume %s (block encryption): %s", ri.VolID, err)
}
}
if ri.isFileEncrypted() {
log.DebugLog(ctx, "rbd: going to remove DEK for %q (file encryption)", ri)
if err = ri.fileEncryption.RemoveDEK(ri.VolID); err != nil {
log.WarningLog(ctx, "failed to clean the passphrase for volume %s (file encryption): %s", ri.VolID, err)
}
}
err = ri.openIoctx()
if err != nil {
return err
}
rbdImage := librbd.GetImage(ri.ioctx, image)
err = rbdImage.Trash(0)
if err != nil {
log.ErrorLog(ctx, "failed to delete rbd image: %s, error: %v", ri, err)
return err
}
return ri.trashRemoveImage(ctx)
}
// trashRemoveImage adds a task to trash remove an image using ceph manager if supported,
// otherwise removes the image from trash.
func (ri *rbdImage) trashRemoveImage(ctx context.Context) error {
// attempt to use Ceph manager based deletion support if available
log.DebugLog(ctx, "rbd: adding task to remove image %q with id %q from trash", ri, ri.ImageID)
ta, err := ri.conn.GetTaskAdmin()
if err != nil {
return err
}
_, err = ta.AddTrashRemove(admin.NewImageSpec(ri.Pool, ri.RadosNamespace, ri.ImageID))
rbdCephMgrSupported := isCephMgrSupported(ctx, ri.ClusterID, err)
if rbdCephMgrSupported && err != nil {
log.ErrorLog(ctx, "failed to add task to delete rbd image: %s, %v", ri, err)
return err
}
if !rbdCephMgrSupported {
err = librbd.TrashRemove(ri.ioctx, ri.ImageID, true)
if err != nil {
log.ErrorLog(ctx, "failed to delete rbd image: %s, %v", ri, err)
return err
}
} else {
log.DebugLog(ctx, "rbd: successfully added task to move image %q with id %q to trash", ri, ri.ImageID)
}
return nil
}
func (ri *rbdImage) getCloneDepth(ctx context.Context) (uint, error) {
var depth uint
vol := rbdVolume{}
vol.Pool = ri.Pool
vol.Monitors = ri.Monitors
vol.RbdImageName = ri.RbdImageName
vol.RadosNamespace = ri.RadosNamespace
vol.conn = ri.conn.Copy()
for {
if vol.RbdImageName == "" {
return depth, nil
}
err := vol.openIoctx()
if err != nil {
return depth, err
}
err = vol.getImageInfo()
// FIXME: create and destroy the vol inside the loop.
// see https://github.com/ceph/ceph-csi/pull/1838#discussion_r598530807
vol.ioctx.Destroy()
vol.ioctx = nil
if err != nil {
// if the parent image is moved to trash the name will be present
// in rbd image info but the image will be in trash, in that case
// return the found depth
if errors.Is(err, ErrImageNotFound) {
return depth, nil
}
log.ErrorLog(ctx, "failed to check depth on image %s: %s", &vol, err)
return depth, err
}
if vol.ParentName != "" {
depth++
}
vol.RbdImageName = vol.ParentName
vol.Pool = vol.ParentPool
}
}
type trashSnapInfo struct {
origSnapName string
}
func flattenClonedRbdImages(
ctx context.Context,
snaps []librbd.SnapInfo,
pool, monitors, rbdImageName string,
cr *util.Credentials,
) error {
rv := &rbdVolume{}
rv.Monitors = monitors
rv.Pool = pool
rv.RbdImageName = rbdImageName
defer rv.Destroy()
err := rv.Connect(cr)
if err != nil {
log.ErrorLog(ctx, "failed to open connection %s; err %v", rv, err)
return err
}
var origNameList []trashSnapInfo
for _, snapInfo := range snaps {
// check if the snapshot belongs to trash namespace.
isTrash, retErr := rv.isTrashSnap(snapInfo.Id)
if retErr != nil {
return retErr
}
if isTrash {
// get original snap name for the snapshot in trash namespace
origSnapName, retErr := rv.getOrigSnapName(snapInfo.Id)
if retErr != nil {
return retErr
}
origNameList = append(origNameList, trashSnapInfo{origSnapName})
}
}
for _, snapName := range origNameList {
rv.RbdImageName = snapName.origSnapName
err = rv.flattenRbdImage(ctx, true, rbdHardMaxCloneDepth, rbdSoftMaxCloneDepth)
if err != nil {
log.ErrorLog(ctx, "failed to flatten %s; err %v", rv, err)
continue
}
}
return nil
}
func (ri *rbdImage) flattenRbdImage(
ctx context.Context,
forceFlatten bool,
hardlimit, softlimit uint,
) error {
var depth uint
var err error
// skip clone depth check if request is for force flatten
if !forceFlatten {
depth, err = ri.getCloneDepth(ctx)
if err != nil {
return err
}
log.ExtendedLog(
ctx,
"clone depth is (%d), configured softlimit (%d) and hardlimit (%d) for %s",
depth,
softlimit,
hardlimit,
ri)
}
if !forceFlatten && (depth < hardlimit) && (depth < softlimit) {
return nil
}
log.DebugLog(ctx, "rbd: adding task to flatten image %q", ri)
ta, err := ri.conn.GetTaskAdmin()
if err != nil {
return err
}
_, err = ta.AddFlatten(admin.NewImageSpec(ri.Pool, ri.RadosNamespace, ri.RbdImageName))
rbdCephMgrSupported := isCephMgrSupported(ctx, ri.ClusterID, err)
if rbdCephMgrSupported {
if err != nil {
// discard flattening error if the image does not have any parent
rbdFlattenNoParent := fmt.Sprintf("Image %s/%s does not have a parent", ri.Pool, ri.RbdImageName)
if strings.Contains(err.Error(), rbdFlattenNoParent) {
return nil
}
log.ErrorLog(ctx, "failed to add task flatten for %s : %v", ri, err)
return err
}
if forceFlatten || depth >= hardlimit {
return fmt.Errorf("%w: flatten is in progress for image %s", ErrFlattenInProgress, ri.RbdImageName)
}
log.DebugLog(ctx, "successfully added task to flatten image %q", ri)
}
if !rbdCephMgrSupported {
log.ErrorLog(
ctx,
"task manager does not support flatten,image will be flattened once hardlimit is reached: %v",
err)
if forceFlatten || depth >= hardlimit {
err := ri.flatten()
if err != nil {
log.ErrorLog(ctx, "rbd failed to flatten image %s %s: %v", ri.Pool, ri.RbdImageName, err)
return err
}
}
}
return nil
}
func (ri *rbdImage) getParentName() (string, error) {
rbdImage, err := ri.open()
if err != nil {
return "", err
}
defer rbdImage.Close()
parentInfo, err := rbdImage.GetParent()
if err != nil {
return "", err
}
return parentInfo.Image.ImageName, nil
}
func (ri *rbdImage) flatten() error {
rbdImage, err := ri.open()
if err != nil {
return err
}
defer rbdImage.Close()
err = rbdImage.Flatten()
if err != nil {
// rbd image flatten will fail if the rbd image does not have a parent
parent, pErr := ri.getParentName()
if pErr != nil {
return util.JoinErrors(err, pErr)
}
if parent == "" {
return nil
}
}
return nil
}
func (ri *rbdImage) hasFeature(feature uint64) bool {
return (uint64(ri.ImageFeatureSet) & feature) == feature
}
func (ri *rbdImage) checkImageChainHasFeature(ctx context.Context, feature uint64) (bool, error) {
rbdImg := rbdImage{}
rbdImg.Pool = ri.Pool
rbdImg.RadosNamespace = ri.RadosNamespace
rbdImg.Monitors = ri.Monitors
rbdImg.RbdImageName = ri.RbdImageName
rbdImg.conn = ri.conn.Copy()
for {
if rbdImg.RbdImageName == "" {
return false, nil
}
err := rbdImg.openIoctx()
if err != nil {
return false, err
}
err = rbdImg.getImageInfo()
// FIXME: create and destroy the vol inside the loop.
// see https://github.com/ceph/ceph-csi/pull/1838#discussion_r598530807
rbdImg.ioctx.Destroy()
rbdImg.ioctx = nil
if err != nil {
// call to getImageInfo returns the parent name even if the parent
// is in the trash, when we try to open the parent image to get its
// information it fails because it is already in trash. We should
// treat error as nil if the parent is not found.
if errors.Is(err, ErrImageNotFound) {
return false, nil
}
log.ErrorLog(ctx, "failed to get image info for %s: %s", rbdImg.String(), err)
return false, err
}
if f := rbdImg.hasFeature(feature); f {
return true, nil
}
rbdImg.RbdImageName = rbdImg.ParentName
rbdImg.Pool = rbdImg.ParentPool
}
}
// genSnapFromSnapID generates a rbdSnapshot structure from the provided identifier, updating
// the structure with elements from on-disk snapshot metadata as well.
func genSnapFromSnapID(
ctx context.Context,
rbdSnap *rbdSnapshot,
snapshotID string,
cr *util.Credentials,
secrets map[string]string,
) error {
var vi util.CSIIdentifier
rbdSnap.VolID = snapshotID
err := vi.DecomposeCSIID(rbdSnap.VolID)
if err != nil {
log.ErrorLog(ctx, "error decoding snapshot ID (%s) (%s)", err, rbdSnap.VolID)
return err
}
rbdSnap.ClusterID = vi.ClusterID
rbdSnap.Monitors, _, err = util.GetMonsAndClusterID(ctx, rbdSnap.ClusterID, false)
if err != nil {
log.ErrorLog(ctx, "failed getting mons (%s)", err)
return err
}
rbdSnap.Pool, err = util.GetPoolName(rbdSnap.Monitors, cr, vi.LocationID)
if err != nil {
return err
}
rbdSnap.JournalPool = rbdSnap.Pool
rbdSnap.RadosNamespace, err = util.GetRadosNamespace(util.CsiConfigFile, rbdSnap.ClusterID)
if err != nil {
return err
}
j, err := snapJournal.Connect(rbdSnap.Monitors, rbdSnap.RadosNamespace, cr)
if err != nil {
return err
}
defer j.Destroy()
imageAttributes, err := j.GetImageAttributes(
ctx, rbdSnap.Pool, vi.ObjectUUID, true)
if err != nil {
return err
}