-
Notifications
You must be signed in to change notification settings - Fork 336
/
controller.go
1757 lines (1564 loc) · 69.4 KB
/
controller.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 2017 The Kubernetes 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 controller
import (
"context"
"errors"
"fmt"
"os"
"strconv"
"strings"
"time"
"github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
v1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
apierrors "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/resource"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/labels"
_ "k8s.io/apimachinery/pkg/util/json"
"k8s.io/apimachinery/pkg/util/sets"
"k8s.io/apimachinery/pkg/util/validation"
coreinformers "k8s.io/client-go/informers/core/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/kubernetes/scheme"
corev1 "k8s.io/client-go/kubernetes/typed/core/v1"
corelisters "k8s.io/client-go/listers/core/v1"
storagelistersv1 "k8s.io/client-go/listers/storage/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/cache"
"k8s.io/client-go/tools/record"
"k8s.io/client-go/util/workqueue"
"k8s.io/klog/v2"
"sigs.k8s.io/sig-storage-lib-external-provisioner/v6/controller"
"sigs.k8s.io/sig-storage-lib-external-provisioner/v6/util"
"github.com/kubernetes-csi/csi-lib-utils/connection"
"github.com/kubernetes-csi/csi-lib-utils/metrics"
"github.com/kubernetes-csi/csi-lib-utils/rpc"
snapapi "github.com/kubernetes-csi/external-snapshotter/client/v3/apis/volumesnapshot/v1beta1"
snapclientset "github.com/kubernetes-csi/external-snapshotter/client/v3/clientset/versioned"
)
//secretParamsMap provides a mapping of current as well as deprecated secret keys
type secretParamsMap struct {
name string
deprecatedSecretNameKey string
deprecatedSecretNamespaceKey string
secretNameKey string
secretNamespaceKey string
}
const (
// CSI Parameters prefixed with csiParameterPrefix are not passed through
// to the driver on CreateVolumeRequest calls. Instead they are intended
// to used by the CSI external-provisioner and maybe used to populate
// fields in subsequent CSI calls or Kubernetes API objects.
csiParameterPrefix = "csi.storage.k8s.io/"
prefixedFsTypeKey = csiParameterPrefix + "fstype"
prefixedDefaultSecretNameKey = csiParameterPrefix + "secret-name"
prefixedDefaultSecretNamespaceKey = csiParameterPrefix + "secret-namespace"
prefixedProvisionerSecretNameKey = csiParameterPrefix + "provisioner-secret-name"
prefixedProvisionerSecretNamespaceKey = csiParameterPrefix + "provisioner-secret-namespace"
prefixedControllerPublishSecretNameKey = csiParameterPrefix + "controller-publish-secret-name"
prefixedControllerPublishSecretNamespaceKey = csiParameterPrefix + "controller-publish-secret-namespace"
prefixedNodeStageSecretNameKey = csiParameterPrefix + "node-stage-secret-name"
prefixedNodeStageSecretNamespaceKey = csiParameterPrefix + "node-stage-secret-namespace"
prefixedNodePublishSecretNameKey = csiParameterPrefix + "node-publish-secret-name"
prefixedNodePublishSecretNamespaceKey = csiParameterPrefix + "node-publish-secret-namespace"
prefixedControllerExpandSecretNameKey = csiParameterPrefix + "controller-expand-secret-name"
prefixedControllerExpandSecretNamespaceKey = csiParameterPrefix + "controller-expand-secret-namespace"
// [Deprecated] CSI Parameters that are put into fields but
// NOT stripped from the parameters passed to CreateVolume
provisionerSecretNameKey = "csiProvisionerSecretName"
provisionerSecretNamespaceKey = "csiProvisionerSecretNamespace"
controllerPublishSecretNameKey = "csiControllerPublishSecretName"
controllerPublishSecretNamespaceKey = "csiControllerPublishSecretNamespace"
nodeStageSecretNameKey = "csiNodeStageSecretName"
nodeStageSecretNamespaceKey = "csiNodeStageSecretNamespace"
nodePublishSecretNameKey = "csiNodePublishSecretName"
nodePublishSecretNamespaceKey = "csiNodePublishSecretNamespace"
// PV and PVC metadata, used for sending to drivers in the create requests, added as parameters, optional.
pvcNameKey = "csi.storage.k8s.io/pvc/name"
pvcNamespaceKey = "csi.storage.k8s.io/pvc/namespace"
pvNameKey = "csi.storage.k8s.io/pv/name"
// Defines parameters for ExponentialBackoff used for executing
// CSI CreateVolume API call, it gives approx 4 minutes for the CSI
// driver to complete a volume creation.
backoffDuration = time.Second * 5
backoffFactor = 1.2
backoffSteps = 10
snapshotKind = "VolumeSnapshot"
snapshotAPIGroup = snapapi.GroupName // "snapshot.storage.k8s.io"
pvcKind = "PersistentVolumeClaim" // Native types don't require an API group
tokenPVNameKey = "pv.name"
tokenPVCNameKey = "pvc.name"
tokenPVCNameSpaceKey = "pvc.namespace"
ResyncPeriodOfCsiNodeInformer = 1 * time.Hour
deleteVolumeRetryCount = 5
annMigratedTo = "pv.kubernetes.io/migrated-to"
annStorageProvisioner = "volume.beta.kubernetes.io/storage-provisioner"
annSelectedNode = "volume.kubernetes.io/selected-node"
snapshotNotBound = "snapshot %s not bound"
pvcCloneFinalizer = "provisioner.storage.kubernetes.io/cloning-protection"
)
var (
defaultSecretParams = secretParamsMap{
name: "Default",
secretNameKey: prefixedDefaultSecretNameKey,
secretNamespaceKey: prefixedDefaultSecretNamespaceKey,
}
provisionerSecretParams = secretParamsMap{
name: "Provisioner",
deprecatedSecretNameKey: provisionerSecretNameKey,
deprecatedSecretNamespaceKey: provisionerSecretNamespaceKey,
secretNameKey: prefixedProvisionerSecretNameKey,
secretNamespaceKey: prefixedProvisionerSecretNamespaceKey,
}
nodePublishSecretParams = secretParamsMap{
name: "NodePublish",
deprecatedSecretNameKey: nodePublishSecretNameKey,
deprecatedSecretNamespaceKey: nodePublishSecretNamespaceKey,
secretNameKey: prefixedNodePublishSecretNameKey,
secretNamespaceKey: prefixedNodePublishSecretNamespaceKey,
}
controllerPublishSecretParams = secretParamsMap{
name: "ControllerPublish",
deprecatedSecretNameKey: controllerPublishSecretNameKey,
deprecatedSecretNamespaceKey: controllerPublishSecretNamespaceKey,
secretNameKey: prefixedControllerPublishSecretNameKey,
secretNamespaceKey: prefixedControllerPublishSecretNamespaceKey,
}
nodeStageSecretParams = secretParamsMap{
name: "NodeStage",
deprecatedSecretNameKey: nodeStageSecretNameKey,
deprecatedSecretNamespaceKey: nodeStageSecretNamespaceKey,
secretNameKey: prefixedNodeStageSecretNameKey,
secretNamespaceKey: prefixedNodeStageSecretNamespaceKey,
}
controllerExpandSecretParams = secretParamsMap{
name: "ControllerExpand",
secretNameKey: prefixedControllerExpandSecretNameKey,
secretNamespaceKey: prefixedControllerExpandSecretNamespaceKey,
}
)
// ProvisionerCSITranslator contains the set of CSI Translation functionality
// required by the provisioner
type ProvisionerCSITranslator interface {
TranslateInTreeStorageClassToCSI(inTreePluginName string, sc *storagev1.StorageClass) (*storagev1.StorageClass, error)
TranslateCSIPVToInTree(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)
IsPVMigratable(pv *v1.PersistentVolume) bool
TranslateInTreePVToCSI(pv *v1.PersistentVolume) (*v1.PersistentVolume, error)
IsMigratedCSIDriverByName(csiPluginName string) bool
GetInTreeNameFromCSIName(pluginName string) (string, error)
}
// requiredCapabilities provides a set of extra capabilities required for special/optional features provided by a plugin
type requiredCapabilities struct {
snapshot bool
clone bool
}
// NodeDeployment contains additional parameters for running external-provisioner alongside a
// CSI driver on one or more nodes in the cluster.
type NodeDeployment struct {
// NodeName is the name of the node in Kubernetes on which the external-provisioner runs.
NodeName string
// ClaimInformer is needed to detect when some other external-provisioner
// became the owner of a PVC while the local one is still waiting before
// trying to become the owner itself.
ClaimInformer coreinformers.PersistentVolumeClaimInformer
// NodeInfo is the result of NodeGetInfo. It is need to determine which
// PVs were created for the node.
NodeInfo csi.NodeGetInfoResponse
// ImmediateBinding enables support for PVCs with immediate binding.
ImmediateBinding bool
// BaseDelay is the initial time that the external-provisioner waits
// before trying to become the owner of a PVC with immediate binding.
BaseDelay time.Duration
// MaxDelay is the maximum for the initial wait time.
MaxDelay time.Duration
}
type internalNodeDeployment struct {
NodeDeployment
rateLimiter workqueue.RateLimiter
}
type csiProvisioner struct {
client kubernetes.Interface
csiClient csi.ControllerClient
grpcClient *grpc.ClientConn
snapshotClient snapclientset.Interface
timeout time.Duration
identity string
volumeNamePrefix string
defaultFSType string
volumeNameUUIDLength int
config *rest.Config
driverName string
pluginCapabilities rpc.PluginCapabilitySet
controllerCapabilities rpc.ControllerCapabilitySet
supportsMigrationFromInTreePluginName string
strictTopology bool
immediateTopology bool
translator ProvisionerCSITranslator
scLister storagelistersv1.StorageClassLister
csiNodeLister storagelistersv1.CSINodeLister
nodeLister corelisters.NodeLister
claimLister corelisters.PersistentVolumeClaimLister
vaLister storagelistersv1.VolumeAttachmentLister
extraCreateMetadata bool
eventRecorder record.EventRecorder
nodeDeployment *internalNodeDeployment
}
var _ controller.Provisioner = &csiProvisioner{}
var _ controller.BlockProvisioner = &csiProvisioner{}
var _ controller.Qualifier = &csiProvisioner{}
var (
// Each provisioner have a identify string to distinguish with others. This
// identify string will be added in PV annoations under this key.
provisionerIDKey = "storage.kubernetes.io/csiProvisionerIdentity"
)
func Connect(address string, metricsManager metrics.CSIMetricsManager) (*grpc.ClientConn, error) {
return connection.Connect(address, metricsManager, connection.OnConnectionLoss(connection.ExitOnConnectionLoss()))
}
func Probe(conn *grpc.ClientConn, singleCallTimeout time.Duration) error {
return rpc.ProbeForever(conn, singleCallTimeout)
}
func GetDriverName(conn *grpc.ClientConn, timeout time.Duration) (string, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
return rpc.GetDriverName(ctx, conn)
}
func GetDriverCapabilities(conn *grpc.ClientConn, timeout time.Duration) (rpc.PluginCapabilitySet, rpc.ControllerCapabilitySet, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
pluginCapabilities, err := rpc.GetPluginCapabilities(ctx, conn)
if err != nil {
return nil, nil, err
}
/* Each CSI operation gets its own timeout / context */
ctx, cancel = context.WithTimeout(context.Background(), timeout)
defer cancel()
controllerCapabilities, err := rpc.GetControllerCapabilities(ctx, conn)
if err != nil {
return nil, nil, err
}
return pluginCapabilities, controllerCapabilities, nil
}
func GetNodeInfo(conn *grpc.ClientConn, timeout time.Duration) (*csi.NodeGetInfoResponse, error) {
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
client := csi.NewNodeClient(conn)
return client.NodeGetInfo(ctx, &csi.NodeGetInfoRequest{})
}
// NewCSIProvisioner creates new CSI provisioner.
//
// vaLister is optional and only needed when VolumeAttachments are
// meant to be checked before deleting a volume.
func NewCSIProvisioner(client kubernetes.Interface,
connectionTimeout time.Duration,
identity string,
volumeNamePrefix string,
volumeNameUUIDLength int,
grpcClient *grpc.ClientConn,
snapshotClient snapclientset.Interface,
driverName string,
pluginCapabilities rpc.PluginCapabilitySet,
controllerCapabilities rpc.ControllerCapabilitySet,
supportsMigrationFromInTreePluginName string,
strictTopology bool,
immediateTopology bool,
translator ProvisionerCSITranslator,
scLister storagelistersv1.StorageClassLister,
csiNodeLister storagelistersv1.CSINodeLister,
nodeLister corelisters.NodeLister,
claimLister corelisters.PersistentVolumeClaimLister,
vaLister storagelistersv1.VolumeAttachmentLister,
extraCreateMetadata bool,
defaultFSType string,
nodeDeployment *NodeDeployment,
) controller.Provisioner {
broadcaster := record.NewBroadcaster()
broadcaster.StartLogging(klog.Infof)
broadcaster.StartRecordingToSink(&corev1.EventSinkImpl{Interface: client.CoreV1().Events(v1.NamespaceAll)})
eventRecorder := broadcaster.NewRecorder(scheme.Scheme, v1.EventSource{Component: fmt.Sprintf("external-provisioner")})
csiClient := csi.NewControllerClient(grpcClient)
provisioner := &csiProvisioner{
client: client,
grpcClient: grpcClient,
csiClient: csiClient,
snapshotClient: snapshotClient,
timeout: connectionTimeout,
identity: identity,
volumeNamePrefix: volumeNamePrefix,
defaultFSType: defaultFSType,
volumeNameUUIDLength: volumeNameUUIDLength,
driverName: driverName,
pluginCapabilities: pluginCapabilities,
controllerCapabilities: controllerCapabilities,
supportsMigrationFromInTreePluginName: supportsMigrationFromInTreePluginName,
strictTopology: strictTopology,
immediateTopology: immediateTopology,
translator: translator,
scLister: scLister,
csiNodeLister: csiNodeLister,
nodeLister: nodeLister,
claimLister: claimLister,
vaLister: vaLister,
extraCreateMetadata: extraCreateMetadata,
eventRecorder: eventRecorder,
}
if nodeDeployment != nil {
provisioner.nodeDeployment = &internalNodeDeployment{
NodeDeployment: *nodeDeployment,
rateLimiter: newItemExponentialFailureRateLimiterWithJitter(nodeDeployment.BaseDelay, nodeDeployment.MaxDelay),
}
// Remove deleted PVCs from rate limiter.
claimHandler := cache.ResourceEventHandlerFuncs{
DeleteFunc: func(obj interface{}) {
if claim, ok := obj.(*v1.PersistentVolumeClaim); ok {
provisioner.nodeDeployment.rateLimiter.Forget(claim.UID)
}
},
}
provisioner.nodeDeployment.ClaimInformer.Informer().AddEventHandler(claimHandler)
}
return provisioner
}
// This function get called before any attempt to communicate with the driver.
// Before initiating Create/Delete API calls provisioner checks if Capabilities:
// PluginControllerService, ControllerCreateVolume sre supported and gets the driver name.
func (p *csiProvisioner) checkDriverCapabilities(rc *requiredCapabilities) error {
if !p.pluginCapabilities[csi.PluginCapability_Service_CONTROLLER_SERVICE] {
return fmt.Errorf("CSI driver does not support dynamic provisioning: plugin CONTROLLER_SERVICE capability is not reported")
}
if !p.controllerCapabilities[csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME] {
return fmt.Errorf("CSI driver does not support dynamic provisioning: controller CREATE_DELETE_VOLUME capability is not reported")
}
if rc.snapshot {
// Check whether plugin supports create snapshot
// If not, create volume from snapshot cannot proceed
if !p.controllerCapabilities[csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT] {
return fmt.Errorf("CSI driver does not support snapshot restore: controller CREATE_DELETE_SNAPSHOT capability is not reported")
}
}
if rc.clone {
// Check whether plugin supports clone operations
// If not, create volume from pvc cannot proceed
if !p.controllerCapabilities[csi.ControllerServiceCapability_RPC_CLONE_VOLUME] {
return fmt.Errorf("CSI driver does not support clone operations: controller CLONE_VOLUME capability is not reported")
}
}
return nil
}
func makeVolumeName(prefix, pvcUID string, volumeNameUUIDLength int) (string, error) {
// create persistent name based on a volumeNamePrefix and volumeNameUUIDLength
// of PVC's UID
if len(prefix) == 0 {
return "", fmt.Errorf("Volume name prefix cannot be of length 0")
}
if len(pvcUID) == 0 {
return "", fmt.Errorf("corrupted PVC object, it is missing UID")
}
if volumeNameUUIDLength == -1 {
// Default behavior is to not truncate or remove dashes
return fmt.Sprintf("%s-%s", prefix, pvcUID), nil
}
// Else we remove all dashes from UUID and truncate to volumeNameUUIDLength
return fmt.Sprintf("%s-%s", prefix, strings.Replace(string(pvcUID), "-", "", -1)[0:volumeNameUUIDLength]), nil
}
func getAccessTypeBlock() *csi.VolumeCapability_Block {
return &csi.VolumeCapability_Block{
Block: &csi.VolumeCapability_BlockVolume{},
}
}
func getAccessTypeMount(fsType string, mountFlags []string) *csi.VolumeCapability_Mount {
return &csi.VolumeCapability_Mount{
Mount: &csi.VolumeCapability_MountVolume{
FsType: fsType,
MountFlags: mountFlags,
},
}
}
func getAccessMode(pvcAccessMode v1.PersistentVolumeAccessMode) *csi.VolumeCapability_AccessMode {
switch pvcAccessMode {
case v1.ReadWriteOnce:
return &csi.VolumeCapability_AccessMode{
Mode: csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER,
}
case v1.ReadWriteMany:
return &csi.VolumeCapability_AccessMode{
Mode: csi.VolumeCapability_AccessMode_MULTI_NODE_MULTI_WRITER,
}
case v1.ReadOnlyMany:
return &csi.VolumeCapability_AccessMode{
Mode: csi.VolumeCapability_AccessMode_MULTI_NODE_READER_ONLY,
}
default:
return nil
}
}
func getVolumeCapability(
claim *v1.PersistentVolumeClaim,
sc *storagev1.StorageClass,
pvcAccessMode v1.PersistentVolumeAccessMode,
fsType string,
) *csi.VolumeCapability {
if util.CheckPersistentVolumeClaimModeBlock(claim) {
return &csi.VolumeCapability{
AccessType: getAccessTypeBlock(),
AccessMode: getAccessMode(pvcAccessMode),
}
}
return &csi.VolumeCapability{
AccessType: getAccessTypeMount(fsType, sc.MountOptions),
AccessMode: getAccessMode(pvcAccessMode),
}
}
type prepareProvisionResult struct {
fsType string
migratedVolume bool
req *csi.CreateVolumeRequest
csiPVSource *v1.CSIPersistentVolumeSource
}
// prepareProvision does non-destructive parameter checking and preparations for provisioning a volume.
func (p *csiProvisioner) prepareProvision(ctx context.Context, claim *v1.PersistentVolumeClaim, sc *storagev1.StorageClass, selectedNode *v1.Node) (*prepareProvisionResult, controller.ProvisioningState, error) {
if sc == nil {
return nil, controller.ProvisioningFinished, errors.New("storage class was nil")
}
migratedVolume := false
if p.supportsMigrationFromInTreePluginName != "" {
// NOTE: we cannot depend on PVC.Annotations[volume.beta.kubernetes.io/storage-provisioner] to get
// the in-tree provisioner name in case of CSI migration scenarios. The annotation will be
// set to the CSI provisioner name by PV controller for migration scenarios
// so that external provisioner can correctly pick up the PVC pointing to an in-tree plugin
if sc.Provisioner == p.supportsMigrationFromInTreePluginName {
klog.V(2).Infof("translating storage class for in-tree plugin %s to CSI", sc.Provisioner)
storageClass, err := p.translator.TranslateInTreeStorageClassToCSI(p.supportsMigrationFromInTreePluginName, sc)
if err != nil {
return nil, controller.ProvisioningFinished, fmt.Errorf("failed to translate storage class: %v", err)
}
sc = storageClass
migratedVolume = true
} else {
klog.V(4).Infof("skip translation of storage class for plugin: %s", sc.Provisioner)
}
}
// Make sure the plugin is capable of fulfilling the requested options
rc := &requiredCapabilities{}
if claim.Spec.DataSource != nil {
// PVC.Spec.DataSource.Name is the name of the VolumeSnapshot API object
if claim.Spec.DataSource.Name == "" {
return nil, controller.ProvisioningFinished, fmt.Errorf("the PVC source not found for PVC %s", claim.Name)
}
switch claim.Spec.DataSource.Kind {
case snapshotKind:
if *(claim.Spec.DataSource.APIGroup) != snapshotAPIGroup {
return nil, controller.ProvisioningFinished, fmt.Errorf("the PVC source does not belong to the right APIGroup. Expected %s, Got %s", snapshotAPIGroup, *(claim.Spec.DataSource.APIGroup))
}
rc.snapshot = true
case pvcKind:
rc.clone = true
default:
// DataSource is not VolumeSnapshot and PVC
// Assume external data populator to create the volume, and there is no more work for us to do
p.eventRecorder.Event(claim, v1.EventTypeNormal, "Provisioning", fmt.Sprintf("Assuming an external populator will provision the volume"))
return nil, controller.ProvisioningFinished, &controller.IgnoredError{
Reason: fmt.Sprintf("data source (%s) is not handled by the provisioner, assuming an external populator will provision it",
claim.Spec.DataSource.Kind),
}
}
}
if err := p.checkDriverCapabilities(rc); err != nil {
return nil, controller.ProvisioningFinished, err
}
if claim.Spec.Selector != nil {
return nil, controller.ProvisioningFinished, fmt.Errorf("claim Selector is not supported")
}
pvName, err := makeVolumeName(p.volumeNamePrefix, fmt.Sprintf("%s", claim.ObjectMeta.UID), p.volumeNameUUIDLength)
if err != nil {
return nil, controller.ProvisioningFinished, err
}
fsTypesFound := 0
fsType := ""
for k, v := range sc.Parameters {
if strings.ToLower(k) == "fstype" || k == prefixedFsTypeKey {
fsType = v
fsTypesFound++
}
if strings.ToLower(k) == "fstype" {
klog.Warningf(deprecationWarning("fstype", prefixedFsTypeKey, ""))
}
}
if fsTypesFound > 1 {
return nil, controller.ProvisioningFinished, fmt.Errorf("fstype specified in parameters with both \"fstype\" and \"%s\" keys", prefixedFsTypeKey)
}
if fsType == "" && p.defaultFSType != "" {
fsType = p.defaultFSType
}
capacity := claim.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
volSizeBytes := capacity.Value()
// Get access mode
volumeCaps := make([]*csi.VolumeCapability, 0)
for _, pvcAccessMode := range claim.Spec.AccessModes {
volumeCaps = append(volumeCaps, getVolumeCapability(claim, sc, pvcAccessMode, fsType))
}
// Create a CSI CreateVolumeRequest and Response
req := csi.CreateVolumeRequest{
Name: pvName,
Parameters: sc.Parameters,
VolumeCapabilities: volumeCaps,
CapacityRange: &csi.CapacityRange{
RequiredBytes: int64(volSizeBytes),
},
}
if claim.Spec.DataSource != nil && (rc.clone || rc.snapshot) {
volumeContentSource, err := p.getVolumeContentSource(ctx, claim, sc)
if err != nil {
return nil, controller.ProvisioningNoChange, fmt.Errorf("error getting handle for DataSource Type %s by Name %s: %v", claim.Spec.DataSource.Kind, claim.Spec.DataSource.Name, err)
}
req.VolumeContentSource = volumeContentSource
}
if claim.Spec.DataSource != nil && rc.clone {
err = p.setCloneFinalizer(ctx, claim)
if err != nil {
return nil, controller.ProvisioningNoChange, err
}
}
if p.supportsTopology() {
requirements, err := GenerateAccessibilityRequirements(
p.client,
p.driverName,
claim.Name,
sc.AllowedTopologies,
selectedNode,
p.strictTopology,
p.immediateTopology,
p.csiNodeLister,
p.nodeLister)
if err != nil {
return nil, controller.ProvisioningNoChange, fmt.Errorf("error generating accessibility requirements: %v", err)
}
req.AccessibilityRequirements = requirements
}
// Resolve provision secret credentials.
provisionerSecretRef, err := getSecretReference(provisionerSecretParams, sc.Parameters, pvName, &v1.PersistentVolumeClaim{
ObjectMeta: metav1.ObjectMeta{
Name: claim.Name,
Namespace: claim.Namespace,
},
})
if err != nil {
return nil, controller.ProvisioningNoChange, err
}
provisionerCredentials, err := getCredentials(ctx, p.client, provisionerSecretRef)
if err != nil {
return nil, controller.ProvisioningNoChange, err
}
req.Secrets = provisionerCredentials
// Resolve controller publish, node stage, node publish secret references
controllerPublishSecretRef, err := getSecretReference(controllerPublishSecretParams, sc.Parameters, pvName, claim)
if err != nil {
return nil, controller.ProvisioningNoChange, err
}
nodeStageSecretRef, err := getSecretReference(nodeStageSecretParams, sc.Parameters, pvName, claim)
if err != nil {
return nil, controller.ProvisioningNoChange, err
}
nodePublishSecretRef, err := getSecretReference(nodePublishSecretParams, sc.Parameters, pvName, claim)
if err != nil {
return nil, controller.ProvisioningNoChange, err
}
controllerExpandSecretRef, err := getSecretReference(controllerExpandSecretParams, sc.Parameters, pvName, claim)
if err != nil {
return nil, controller.ProvisioningNoChange, err
}
csiPVSource := &v1.CSIPersistentVolumeSource{
Driver: p.driverName,
// VolumeHandle and VolumeAttributes will be added after provisioning.
ControllerPublishSecretRef: controllerPublishSecretRef,
NodeStageSecretRef: nodeStageSecretRef,
NodePublishSecretRef: nodePublishSecretRef,
ControllerExpandSecretRef: controllerExpandSecretRef,
}
req.Parameters, err = removePrefixedParameters(sc.Parameters)
if err != nil {
return nil, controller.ProvisioningFinished, fmt.Errorf("failed to strip CSI Parameters of prefixed keys: %v", err)
}
if p.extraCreateMetadata {
// add pvc and pv metadata to request for use by the plugin
req.Parameters[pvcNameKey] = claim.GetName()
req.Parameters[pvcNamespaceKey] = claim.GetNamespace()
req.Parameters[pvNameKey] = pvName
}
return &prepareProvisionResult{
fsType: fsType,
migratedVolume: migratedVolume,
req: &req,
csiPVSource: csiPVSource,
}, controller.ProvisioningNoChange, nil
}
func (p *csiProvisioner) Provision(ctx context.Context, options controller.ProvisionOptions) (*v1.PersistentVolume, controller.ProvisioningState, error) {
claim := options.PVC
if claim.Annotations[annStorageProvisioner] != p.driverName && claim.Annotations[annMigratedTo] != p.driverName {
// The storage provisioner annotation may not equal driver name but the
// PVC could have annotation "migrated-to" which is the new way to
// signal a PVC is migrated (k8s v1.17+)
return nil, controller.ProvisioningFinished, &controller.IgnoredError{
Reason: fmt.Sprintf("PVC annotated with external-provisioner name %s does not match provisioner driver name %s. This could mean the PVC is not migrated",
claim.Annotations[annStorageProvisioner],
p.driverName),
}
}
// The same check already ran in ShouldProvision, but perhaps
// it couldn't complete due to some unexpected error.
owned, err := p.checkNode(ctx, claim, options.StorageClass, "provision")
if err != nil {
return nil, controller.ProvisioningNoChange,
fmt.Errorf("node check failed: %v", err)
}
if !owned {
return nil, controller.ProvisioningNoChange, &controller.IgnoredError{
Reason: fmt.Sprintf("not responsible for provisioning of PVC %s/%s because it is not assigned to node %q", claim.Namespace, claim.Name, p.nodeDeployment.NodeName),
}
}
result, state, err := p.prepareProvision(ctx, claim, options.StorageClass, options.SelectedNode)
if result == nil {
return nil, state, err
}
req := result.req
volSizeBytes := req.CapacityRange.RequiredBytes
pvName := req.Name
provisionerCredentials := req.Secrets
createCtx := markAsMigrated(ctx, result.migratedVolume)
createCtx, cancel := context.WithTimeout(createCtx, p.timeout)
defer cancel()
rep, err := p.csiClient.CreateVolume(createCtx, req)
if err != nil {
// Giving up after an error and telling the pod scheduler to retry with a different node
// only makes sense if:
// - The CSI driver supports topology: without that, the next CreateVolume call after
// rescheduling will be exactly the same.
// - We are working on a volume with late binding: only in that case will
// provisioning be retried if we give up for now.
// - The error is one where rescheduling is
// a) allowed (i.e. we don't have to keep calling CreateVolume because the operation might be running) and
// b) it makes sense (typically local resource exhausted).
// isFinalError is going to check this.
//
// We do this regardless whether the driver has asked for strict topology because
// even drivers which did not ask for it explicitly might still only look at the first
// topology entry and thus succeed after rescheduling.
mayReschedule := p.supportsTopology() &&
options.SelectedNode != nil
state := checkError(err, mayReschedule)
klog.V(5).Infof("CreateVolume failed, supports topology = %v, node selected %v => may reschedule = %v => state = %v: %v",
p.supportsTopology(),
options.SelectedNode != nil,
mayReschedule,
state,
err)
return nil, state, err
}
if rep.Volume != nil {
klog.V(3).Infof("create volume rep: %+v", *rep.Volume)
}
volumeAttributes := map[string]string{provisionerIDKey: p.identity}
for k, v := range rep.Volume.VolumeContext {
volumeAttributes[k] = v
}
respCap := rep.GetVolume().GetCapacityBytes()
//According to CSI spec CreateVolume should be able to return capacity = 0, which means it is unknown. for example NFS/FTP
if respCap == 0 {
respCap = volSizeBytes
klog.V(3).Infof("csiClient response volume with size 0, which is not supported by apiServer, will use claim size:%d", respCap)
} else if respCap < volSizeBytes {
capErr := fmt.Errorf("created volume capacity %v less than requested capacity %v", respCap, volSizeBytes)
delReq := &csi.DeleteVolumeRequest{
VolumeId: rep.GetVolume().GetVolumeId(),
}
err = cleanupVolume(ctx, p, delReq, provisionerCredentials)
if err != nil {
capErr = fmt.Errorf("%v. Cleanup of volume %s failed, volume is orphaned: %v", capErr, pvName, err)
}
// use InBackground to retry the call, hoping the volume is deleted correctly next time.
return nil, controller.ProvisioningInBackground, capErr
}
if options.PVC.Spec.DataSource != nil {
contentSource := rep.GetVolume().ContentSource
if contentSource == nil {
sourceErr := fmt.Errorf("volume content source missing")
delReq := &csi.DeleteVolumeRequest{
VolumeId: rep.GetVolume().GetVolumeId(),
}
err = cleanupVolume(ctx, p, delReq, provisionerCredentials)
if err != nil {
sourceErr = fmt.Errorf("%v. cleanup of volume %s failed, volume is orphaned: %v", sourceErr, pvName, err)
}
return nil, controller.ProvisioningInBackground, sourceErr
}
}
result.csiPVSource.VolumeHandle = p.volumeIdToHandle(rep.Volume.VolumeId)
result.csiPVSource.VolumeAttributes = volumeAttributes
pv := &v1.PersistentVolume{
ObjectMeta: metav1.ObjectMeta{
Name: pvName,
},
Spec: v1.PersistentVolumeSpec{
AccessModes: options.PVC.Spec.AccessModes,
MountOptions: options.StorageClass.MountOptions,
Capacity: v1.ResourceList{
v1.ResourceName(v1.ResourceStorage): bytesToQuantity(respCap),
},
// TODO wait for CSI VolumeSource API
PersistentVolumeSource: v1.PersistentVolumeSource{
CSI: result.csiPVSource,
},
},
}
if options.StorageClass.ReclaimPolicy != nil {
pv.Spec.PersistentVolumeReclaimPolicy = *options.StorageClass.ReclaimPolicy
}
if p.supportsTopology() {
pv.Spec.NodeAffinity = GenerateVolumeNodeAffinity(rep.Volume.AccessibleTopology)
}
// Set VolumeMode to PV if it is passed via PVC spec when Block feature is enabled
if options.PVC.Spec.VolumeMode != nil {
pv.Spec.VolumeMode = options.PVC.Spec.VolumeMode
}
// Set FSType if PV is not Block Volume
if !util.CheckPersistentVolumeClaimModeBlock(options.PVC) {
pv.Spec.PersistentVolumeSource.CSI.FSType = result.fsType
}
klog.V(2).Infof("successfully created PV %v for PVC %v and csi volume name %v", pv.Name, options.PVC.Name, pv.Spec.CSI.VolumeHandle)
if result.migratedVolume {
pv, err = p.translator.TranslateCSIPVToInTree(pv)
if err != nil {
klog.Warningf("failed to translate CSI PV to in-tree due to: %v. Deleting provisioned PV", err)
deleteErr := p.Delete(ctx, pv)
if deleteErr != nil {
klog.Warningf("failed to delete partly provisioned PV: %v", deleteErr)
// Retry the call again to clean up the orphan
return nil, controller.ProvisioningInBackground, err
}
return nil, controller.ProvisioningFinished, err
}
}
klog.V(5).Infof("successfully created PV %+v", pv.Spec.PersistentVolumeSource)
return pv, controller.ProvisioningFinished, nil
}
func (p *csiProvisioner) setCloneFinalizer(ctx context.Context, pvc *v1.PersistentVolumeClaim) error {
claim, err := p.claimLister.PersistentVolumeClaims(pvc.Namespace).Get(pvc.Spec.DataSource.Name)
if err != nil {
return err
}
if !checkFinalizer(claim, pvcCloneFinalizer) {
claim.Finalizers = append(claim.Finalizers, pvcCloneFinalizer)
_, err := p.client.CoreV1().PersistentVolumeClaims(claim.Namespace).Update(ctx, claim, metav1.UpdateOptions{})
return err
}
return nil
}
func (p *csiProvisioner) supportsTopology() bool {
return SupportsTopology(p.pluginCapabilities)
}
func removePrefixedParameters(param map[string]string) (map[string]string, error) {
newParam := map[string]string{}
for k, v := range param {
if strings.HasPrefix(k, csiParameterPrefix) {
// Check if its well known
switch k {
case prefixedFsTypeKey:
case prefixedProvisionerSecretNameKey:
case prefixedProvisionerSecretNamespaceKey:
case prefixedControllerPublishSecretNameKey:
case prefixedControllerPublishSecretNamespaceKey:
case prefixedNodeStageSecretNameKey:
case prefixedNodeStageSecretNamespaceKey:
case prefixedNodePublishSecretNameKey:
case prefixedNodePublishSecretNamespaceKey:
case prefixedControllerExpandSecretNameKey:
case prefixedControllerExpandSecretNamespaceKey:
case prefixedDefaultSecretNameKey:
case prefixedDefaultSecretNamespaceKey:
default:
return map[string]string{}, fmt.Errorf("found unknown parameter key \"%s\" with reserved namespace %s", k, csiParameterPrefix)
}
} else {
// Don't strip, add this key-value to new map
// Deprecated parameters prefixed with "csi" are not stripped to preserve backwards compatibility
newParam[k] = v
}
}
return newParam, nil
}
// getVolumeContentSource is a helper function to process provisioning requests that include a DataSource
// currently we provide Snapshot and PVC, the default case allows the provisioner to still create a volume
// so that an external controller can act upon it. Additional DataSource types can be added here with
// an appropriate implementation function
func (p *csiProvisioner) getVolumeContentSource(ctx context.Context, claim *v1.PersistentVolumeClaim, sc *storagev1.StorageClass) (*csi.VolumeContentSource, error) {
switch claim.Spec.DataSource.Kind {
case snapshotKind:
return p.getSnapshotSource(ctx, claim, sc)
case pvcKind:
return p.getPVCSource(ctx, claim, sc)
default:
// For now we shouldn't pass other things to this function, but treat it as a noop and extend as needed
return nil, nil
}
}
// getPVCSource verifies DataSource.Kind of type PersistentVolumeClaim, making sure that the requested PVC is available/ready
// returns the VolumeContentSource for the requested PVC
func (p *csiProvisioner) getPVCSource(ctx context.Context, claim *v1.PersistentVolumeClaim, sc *storagev1.StorageClass) (*csi.VolumeContentSource, error) {
sourcePVC, err := p.claimLister.PersistentVolumeClaims(claim.Namespace).Get(claim.Spec.DataSource.Name)
if err != nil {
return nil, fmt.Errorf("error getting PVC %s (namespace %q) from api server: %v", claim.Spec.DataSource.Name, claim.Namespace, err)
}
if string(sourcePVC.Status.Phase) != "Bound" {
return nil, fmt.Errorf("the PVC DataSource %s must have a status of Bound. Got %v", claim.Spec.DataSource.Name, sourcePVC.Status)
}
if sourcePVC.ObjectMeta.DeletionTimestamp != nil {
return nil, fmt.Errorf("the PVC DataSource %s is currently being deleted", claim.Spec.DataSource.Name)
}
if sourcePVC.Spec.StorageClassName == nil {
return nil, fmt.Errorf("the source PVC (%s) storageclass cannot be empty", sourcePVC.Name)
}
if claim.Spec.StorageClassName == nil {
return nil, fmt.Errorf("the requested PVC (%s) storageclass cannot be empty", claim.Name)
}
if *sourcePVC.Spec.StorageClassName != *claim.Spec.StorageClassName {
return nil, fmt.Errorf("the source PVC and destination PVCs must be in the same storage class for cloning. Source is in %v, but new PVC is in %v",
*sourcePVC.Spec.StorageClassName, *claim.Spec.StorageClassName)
}
capacity := claim.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
requestedSize := capacity.Value()
srcCapacity := sourcePVC.Spec.Resources.Requests[v1.ResourceName(v1.ResourceStorage)]
srcPVCSize := srcCapacity.Value()
if requestedSize < srcPVCSize {
return nil, fmt.Errorf("error, new PVC request must be greater than or equal in size to the specified PVC data source, requested %v but source is %v", requestedSize, srcPVCSize)
}
if sourcePVC.Spec.VolumeName == "" {
return nil, fmt.Errorf("volume name is empty in source PVC %s", sourcePVC.Name)
}
sourcePV, err := p.client.CoreV1().PersistentVolumes().Get(ctx, sourcePVC.Spec.VolumeName, metav1.GetOptions{})
if err != nil {
klog.Warningf("error getting volume %s for PVC %s/%s: %s", sourcePVC.Spec.VolumeName, sourcePVC.Namespace, sourcePVC.Name, err)
return nil, fmt.Errorf("claim in dataSource not bound or invalid")
}
if sourcePV.Spec.CSI == nil {
klog.Warningf("error getting volume source from %s for PVC %s/%s", sourcePVC.Spec.VolumeName, sourcePVC.Namespace, sourcePVC.Name)
return nil, fmt.Errorf("claim in dataSource not bound or invalid")
}
if sourcePV.Spec.CSI.Driver != sc.Provisioner {
klog.Warningf("the source volume %s for PVC %s/%s is handled by a different CSI driver than requested by StorageClass %s", sourcePVC.Spec.VolumeName, sourcePVC.Namespace, sourcePVC.Name, *claim.Spec.StorageClassName)
return nil, fmt.Errorf("claim in dataSource not bound or invalid")
}
if sourcePV.Spec.ClaimRef == nil {
klog.Warningf("the source volume %s for PVC %s/%s is not bound", sourcePVC.Spec.VolumeName, sourcePVC.Namespace, sourcePVC.Name)
return nil, fmt.Errorf("claim in dataSource not bound or invalid")
}
if sourcePV.Spec.ClaimRef.UID != sourcePVC.UID || sourcePV.Spec.ClaimRef.Namespace != sourcePVC.Namespace || sourcePV.Spec.ClaimRef.Name != sourcePVC.Name {
klog.Warningf("the source volume %s for PVC %s/%s is bound to a different PVC than requested", sourcePVC.Spec.VolumeName, sourcePVC.Namespace, sourcePVC.Name)
return nil, fmt.Errorf("claim in dataSource not bound or invalid")
}
if sourcePV.Status.Phase != v1.VolumeBound {
klog.Warningf("the source volume %s for PVC %s/%s status is \"%s\", should instead be \"%s\"", sourcePVC.Spec.VolumeName, sourcePVC.Namespace, sourcePVC.Name, sourcePV.Status.Phase, v1.VolumeBound)
return nil, fmt.Errorf("claim in dataSource not bound or invalid")
}
if claim.Spec.VolumeMode == nil || *claim.Spec.VolumeMode == v1.PersistentVolumeFilesystem {
if sourcePV.Spec.VolumeMode != nil && *sourcePV.Spec.VolumeMode != v1.PersistentVolumeFilesystem {
return nil, fmt.Errorf("the source PVC and destination PVCs must have the same volume mode for cloning. Source is Block, but new PVC requested Filesystem")
}
}