-
Notifications
You must be signed in to change notification settings - Fork 16
/
controller.go
4263 lines (3985 loc) · 160 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 © 2021 Dell Inc. or its subsidiaries. All Rights Reserved.
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 service
import (
"errors"
"fmt"
"math/rand"
"path"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/dell/csi-powermax/v2/pkg/file"
"github.com/dell/csi-powermax/v2/pkg/symmetrix"
pmax "github.com/dell/gopowermax/v2"
csiext "github.com/dell/dell-csi-extensions/replication"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"github.com/container-storage-interface/spec/lib/go/csi"
types "github.com/dell/gopowermax/v2/types/v100"
"github.com/golang/protobuf/ptypes"
log "github.com/sirupsen/logrus"
"google.golang.org/protobuf/types/known/wrapperspb"
)
// constants
const (
cylinderSizeInBytes = 1966080
MiBSizeInBytes = 1048576
DefaultVolumeSizeBytes = 1073741824
// MinVolumeSizeBytes - This is the minimum volume size in bytes. This is equal to
// the number of bytes to create a volume which requires 1 cylinder less than
// the number of bytes required for 50 MB
MinVolumeSizeBytes = 51118080
// MaxVolumeSizeBytes - This is the maximum volume size in bytes. This is equal to
// the minimum number of bytes required to create a 65 TB volume on PowerMax arrays
MaxVolumeSizeBytes = 70368745881600
errUnknownAccessType = "unknown access type is not Block or Mount"
errUnknownAccessMode = "access mode cannot be UNKNOWN"
errNoMultiNodeWriter = "multi-node with writer(s) only supported for block access type"
StoragePoolCacheDuration = 4 * time.Hour
MaxVolIdentifierLength = 64
MaxPortGroupIdentifierLength = 64
MaxClusterPrefixLength = 3
CSIPrefix = "csi"
DeletionPrefix = "_DEL"
CsiHostPrefix = "csi-node-"
CsiMVPrefix = "csi-mv-"
CsiNoSrpSGPrefix = "csi-no-srp-sg-"
CsiVolumePrefix = "csi-"
CsiRepSGPrefix = "csi-rep-sg-"
PublishContextDeviceWWN = "DEVICE_WWN"
RemotePublishContextDeviceWWN = "REMOTE_DEVICE_WWN"
PublishContextLUNAddress = "LUN_ADDRESS"
RemotePublishContextLUNAddress = "REMOTE_LUN_ADDRESS"
PortIdentifiers = "PORT_IDENTIFIERS"
RemotePortIdentifiers = "REMOTE_PORT_IDENTIFIERS"
PortIdentifierKeyCount = "PORT_IDENTIFIER_KEYS"
RemotePortIdentifierKeyCount = "REMOTE_PORT_IDENTIFIER_KEYS"
MaxPortIdentifierLength = 128
FCSuffix = "-FC"
PGSuffix = "PG"
notFound = "not found" // error message from s.GetVolumeByID when volume not found
cannotBeFound = "Could not find" // error message from pmax when volume not found
failedToValidateVolumeNameAndID = "Failed to validate combination of Volume Name and Volume ID"
IscsiTransportProtocol = "ISCSI"
FcTransportProtocol = "FC"
MaxSnapIdentifierLength = 32
SnapDelPrefix = "DEL"
delSrcTag = "DS"
StorageGroup = "StorageGroup"
Async = "ASYNC"
Sync = "SYNC"
Metro = "METRO"
ActiveBias = "ActiveBias"
Consistent = "Consistent"
Synchronized = "Synchronized"
FailedOver = "Failed Over"
Suspended = "Suspended"
Invalid = "Invalid"
Split = "Split"
SyncInProgress = "SyncInProg"
Vsphere = "VSPHERE"
MigrationActionCommit = "Commit"
HostLimitName = "HostLimitName"
HostLimits = "hostLimits"
HostIOLimitMBSec = "HostIOLimitMBSec"
HostIOLimitIOSec = "HostIOLimitIOSec"
DynamicDistribution = "DynamicDistribution"
NFS = "nfs"
NASServerName = "nasServer"
fileSystemID = "file_system_id"
)
// Keys for parameters to CreateVolume
const (
SymmetrixIDParam = "SYMID"
ServiceLevelParam = "ServiceLevel"
ContentSource = "VolumeContentSource"
StoragePoolParam = "SRP"
// If storage_group is set, this over-rides the generation of the Storage Group from SLO/SRP
StorageGroupParam = "StorageGroup"
ThickVolumesParam = "ThickVolumes" // "true" or "false" or "" (defaults thin)
ApplicationPrefixParam = "ApplicationPrefix"
CapacityGB = "CapacityGB"
uCode5978 = 5978
uCodeELMSR = 221
// These params will be in replication enabled storage class
RepEnabledParam = "isReplicationEnabled"
LocalRDFGroupParam = "RdfGroup"
RemoteRDFGroupParam = "RemoteRDFGroup"
RemoteSymIDParam = "RemoteSYMID"
RemoteVolumeIDParam = "RemoteVolumeID"
ReplicationModeParam = "RdfMode"
CSIPVCNamespace = "csi.storage.k8s.io/pvc/namespace"
CSIPersistentVolumeName = "csi.storage.k8s.io/pv/name"
CSIPersistentVolumeClaimName = "csi.storage.k8s.io/pvc/name"
// These map to the above fields in the form of HTTP header names.
HeaderPersistentVolumeName = "x-csi-pv-name"
HeaderPersistentVolumeClaimName = "x-csi-pv-claimname"
HeaderPersistentVolumeClaimNamespace = "x-csi-pv-namespace"
RemoteServiceLevelParam = "RemoteServiceLevel"
RemoteSRPParam = "RemoteSRP"
BiasParam = "Bias"
FsTypeParam = "csi.storage.k8s.io/fstype"
AllowRootParam = "allowRoot"
)
// Pair - structure which holds a pair
type Pair struct {
first, second interface{}
}
var nodeCache sync.Map
// Information cached about a pmax
type pmaxCachedInformation struct {
// Existence of a StoragePool discovered at indicated time
knownStoragePools map[string]time.Time
// Pair of a map containing dirPortKey to portIdentifier mapping
// and a timestamp indicating when this map was created
portIdentifiers *Pair
uCodeVersion *Pair
}
// Initializes a pmaxCachedInformation type
func (p *pmaxCachedInformation) initialize() {
p.knownStoragePools = make(map[string]time.Time)
p.portIdentifiers = nil
p.uCodeVersion = nil
}
func getPmaxCache(symID string) *pmaxCachedInformation {
if pmaxCache == nil {
pmaxCache = make(map[string]*pmaxCachedInformation)
}
if pmaxCache[symID] != nil {
return pmaxCache[symID]
}
info := &pmaxCachedInformation{}
info.initialize()
pmaxCache[symID] = info
return info
}
var (
validSLO = [...]string{"Diamond", "Platinum", "Gold", "Silver", "Bronze", "Optimized", "None"}
// A map of the symmetrixID to the pmaxCachedInformation structure for that pmax
pmaxCache map[string]*pmaxCachedInformation
// Quickly fail if there is too much load
controllerPendingState pendingState
snapshotPendingState pendingState
// Retry delay for retrying GetMaskingViewConnections
getMVConnectionsDelay = 30 * time.Second
)
func (s *service) GetPortIdentifier(ctx context.Context, symID string, dirPortKey string, pmaxClient pmax.Pmax) (string, error) {
s.cacheMutex.Lock()
defer s.cacheMutex.Unlock()
portIdentifier := ""
cache := getPmaxCache(symID)
cacheExpired := false
if cache == nil {
return "", fmt.Errorf("Internal error - cache pointer is empty")
}
if cache.portIdentifiers != nil {
portTimeStamp := cache.portIdentifiers.second.(time.Time)
if time.Now().Sub(portTimeStamp) < s.storagePoolCacheDuration {
// We have a valid cache entry
dirPortKeys := cache.portIdentifiers.first.(map[string]string)
portIdentifier, ok := dirPortKeys[dirPortKey]
if ok {
log.Debug("Cache hit for :" + dirPortKey)
return portIdentifier, nil
}
} else {
cacheExpired = true
}
}
// Example dirPortKeys: FA-1D:4 (FC), SE-1E:24 (ISCSI)
dirPortDetails := strings.Split(dirPortKey, ":")
dirID := dirPortDetails[0]
portNumber := dirPortDetails[1]
// Fetch the port details
port, err := pmaxClient.GetPort(ctx, symID, dirID, portNumber)
if err != nil {
log.Errorf("Couldn't get port details for %s. Error: %s", dirPortKey, err.Error())
return "", err
}
log.Debugf("Symmetrix ID: %s, DirPortKey: %s, Port type: %s",
symID, dirPortKey, port.SymmetrixPort.Type)
if !strings.Contains(port.SymmetrixPort.Identifier, "iqn") {
// Add "0x" to the FC Port WWN as that is used by gofsutils to differentiate between FC and ISCSI
portIdentifier = "0x"
}
portIdentifier += port.SymmetrixPort.Identifier
if cache.portIdentifiers != nil {
if cacheExpired {
// Invalidate all the values in cache for this symmetrix
log.Debug("Cache expired. Rebuilding port identifier cache with entry for : " + dirPortKey)
dirPortKeys := make(map[string]string)
dirPortKeys[dirPortKey] = portIdentifier
cache.portIdentifiers = &Pair{
first: dirPortKeys,
second: time.Now(),
}
} else {
// We are adding a new port identifier to the cache
log.Debug("Adding value to port identifier cache for :" + dirPortKey)
dirPortKeys := cache.portIdentifiers.first.(map[string]string)
dirPortKeys[dirPortKey] = portIdentifier
}
} else {
// Build the cache
dirPortKeys := make(map[string]string)
dirPortKeys[dirPortKey] = portIdentifier
cache.portIdentifiers = &Pair{
first: dirPortKeys,
second: time.Now(),
}
log.Debug("Port identifier cache created with entry for :" + dirPortKey)
}
return portIdentifier, nil
}
// GetPowerMaxClient returns a valid client based on arrays
func (s *service) GetPowerMaxClient(primarySymID string, arrayIDs ...string) (pmax.Pmax, error) {
if len(arrayIDs) > 0 && arrayIDs[0] != "" {
return symmetrix.GetPowerMaxClient(primarySymID, arrayIDs...)
}
return symmetrix.GetPowerMaxClient(primarySymID)
}
func (s *service) CreateVolume(
ctx context.Context,
req *csi.CreateVolumeRequest) (
*csi.CreateVolumeResponse, error,
) {
var reqID string
headers, ok := metadata.FromIncomingContext(ctx)
if ok {
if req, ok := headers["csi.requestid"]; ok && len(req) > 0 {
reqID = req[0]
}
}
params := req.GetParameters()
params = mergeStringMaps(params, req.GetSecrets())
symmetrixID := params[SymmetrixIDParam]
if symmetrixID == "" {
log.Error("A SYMID parameter is required")
return nil, status.Errorf(codes.InvalidArgument, "A SYMID parameter is required")
}
pmaxClient, err := s.GetPowerMaxClient(symmetrixID)
if err != nil {
log.Error(err.Error())
return nil, status.Error(codes.InvalidArgument, err.Error())
}
// Get the parameters
if err := s.requireProbe(ctx, pmaxClient); err != nil {
return nil, err
}
thick := params[ThickVolumesParam]
applicationPrefix := ""
if params[ApplicationPrefixParam] != "" {
applicationPrefix = params[ApplicationPrefixParam]
}
// Storage (resource) Pool. Validate it against exist Pools
storagePoolID := params[StoragePoolParam]
err = s.validateStoragePoolID(ctx, symmetrixID, storagePoolID, pmaxClient)
if err != nil {
log.Error(err.Error())
return nil, status.Errorf(codes.InvalidArgument, err.Error())
}
// SLO is optional
serviceLevel := "Optimized"
if params[ServiceLevelParam] != "" {
serviceLevel = params[ServiceLevelParam]
found := false
for _, val := range validSLO {
if serviceLevel == val {
found = true
}
}
if !found {
log.Error("An invalid Service Level parameter was specified")
return nil, status.Errorf(codes.InvalidArgument, "An invalid Service Level parameter was specified")
}
}
storageGroupName := ""
if params[StorageGroupParam] != "" {
storageGroupName = params[StorageGroupParam]
}
// get HostIOLimits for the storage group
hostLimitName := ""
hostMBsec := ""
hostIOsec := ""
hostDynDistribution := ""
if params[HostLimitName] != "" {
hostLimitName = params[HostLimitName]
}
if params[HostIOLimitMBSec] != "" {
hostMBsec = params[HostIOLimitMBSec]
}
if params[HostIOLimitIOSec] != "" {
hostIOsec = params[HostIOLimitIOSec]
}
if params[DynamicDistribution] != "" {
hostDynDistribution = params[DynamicDistribution]
}
// Get the namespace
namespace := ""
if params[CSIPVCNamespace] != "" {
namespace = params[CSIPVCNamespace]
}
// File related params
useNFS := false
nasServer := ""
allowRoot := ""
if params[NASServerName] != "" {
nasServer = params[NASServerName]
}
if params[AllowRootParam] != "" {
allowRoot = params[AllowRootParam]
}
// Validate volume capabilities
vcs := req.GetVolumeCapabilities()
if vcs != nil {
isBlock := accTypeIsBlock(vcs)
if isBlock && !s.opts.EnableBlock {
return nil, status.Error(codes.InvalidArgument, "Block Volume Capability is not supported")
}
useNFS = accTypeIsNFS(vcs)
if isBlock && useNFS {
return nil, status.Errorf(codes.InvalidArgument, "NFS with Block is not supported")
}
}
// Remote Replication based paramsMes
var replicationEnabled string
var remoteSymID string
var localRDFGrpNo string
var remoteRDFGrpNo string
var remoteServiceLevel string
var remoteSRPID string
var repMode string
var bias string
if params[path.Join(s.opts.ReplicationPrefix, RepEnabledParam)] == "true" {
if s.opts.IsVsphereEnabled {
return nil, status.Errorf(codes.Unavailable, "Replication on a vSphere volume is not supported")
}
if useNFS {
return nil, status.Errorf(codes.Unavailable, "Replication on a NFS volume is not supported")
}
replicationEnabled = params[path.Join(s.opts.ReplicationPrefix, RepEnabledParam)]
// remote symmetrix ID and rdf group name are mandatory params when replication is enabled
remoteSymID = params[path.Join(s.opts.ReplicationPrefix, RemoteSymIDParam)]
// check if storage class contains SRDG details
if params[path.Join(s.opts.ReplicationPrefix, LocalRDFGroupParam)] != "" {
localRDFGrpNo = params[path.Join(s.opts.ReplicationPrefix, LocalRDFGroupParam)]
}
if params[path.Join(s.opts.ReplicationPrefix, RemoteRDFGroupParam)] != "" {
remoteRDFGrpNo = params[path.Join(s.opts.ReplicationPrefix, RemoteRDFGroupParam)]
}
repMode = params[path.Join(s.opts.ReplicationPrefix, ReplicationModeParam)]
remoteServiceLevel = params[path.Join(s.opts.ReplicationPrefix, RemoteServiceLevelParam)]
remoteSRPID = params[path.Join(s.opts.ReplicationPrefix, RemoteSRPParam)]
bias = params[path.Join(s.opts.ReplicationPrefix, BiasParam)]
// Get Local and remote RDFg Numbers from a rest call
// Create RDFg for a namespace if it doens't exist?
// Create RDFg when the volume gets added first time for a replication sssn
if localRDFGrpNo == "" && remoteRDFGrpNo == "" {
localRDFGrpNo, remoteRDFGrpNo, err = s.GetOrCreateRDFGroup(ctx, symmetrixID, remoteSymID, repMode, namespace, pmaxClient)
if err != nil {
return nil, status.Errorf(codes.NotFound, "Received error get/create RDFG, err: %s", err.Error())
}
if localRDFGrpNo == "" || remoteRDFGrpNo == "" {
return nil, status.Errorf(codes.Unavailable, "Can not fetch RDF Group for volume creation get/create RDFG")
}
log.Debugf("RDF group for given array pair and RDF mode: local(%s), remote(%s)", localRDFGrpNo, remoteRDFGrpNo)
}
if repMode == Metro {
return s.createMetroVolume(ctx, req, reqID, storagePoolID, symmetrixID, storageGroupName, serviceLevel, thick, remoteSymID, localRDFGrpNo, remoteRDFGrpNo, remoteServiceLevel, remoteSRPID, namespace, applicationPrefix, bias, hostLimitName, hostMBsec, hostIOsec, hostDynDistribution)
}
if repMode != Async && repMode != Sync {
log.Errorf("Unsupported Replication Mode: (%s)", repMode)
return nil, status.Errorf(codes.InvalidArgument, "Unsupported Replication Mode: (%s)", repMode)
}
}
accessibility := req.GetAccessibilityRequirements()
// Get the required capacity
cr := req.GetCapacityRange()
requiredCylinders, err := s.validateVolSize(ctx, cr, symmetrixID, storagePoolID, pmaxClient)
if err != nil {
return nil, err
}
var srcVolID, srcSnapID string
var symID, SrcDevID, snapID string
var srcVol *types.Volume
var volContent string
// When content source is specified, the size of the new volume
// is determined based on the size of the source volume in the
// snapshot. The size of the new volume to be created should be
// greater than or equal to the size of snapshot source
contentSource := req.GetVolumeContentSource()
if contentSource != nil {
if useNFS {
return nil, status.Errorf(codes.Unavailable, "Cloning on a NFS volume is not supported")
}
switch req.GetVolumeContentSource().GetType().(type) {
case *csi.VolumeContentSource_Volume:
srcVolID = req.GetVolumeContentSource().GetVolume().GetVolumeId()
if srcVolID != "" {
_, symID, SrcDevID, _, _, err = s.parseCsiID(srcVolID)
if err != nil {
// We couldn't comprehend the identifier.
log.Error("Could not parse CSI VolumeId: " + srcVolID)
return nil, status.Error(codes.InvalidArgument, "Source volume identifier not in supported format")
}
volContent = srcVolID
}
break
case *csi.VolumeContentSource_Snapshot:
srcSnapID = req.GetVolumeContentSource().GetSnapshot().GetSnapshotId()
if srcSnapID != "" {
snapID, symID, SrcDevID, _, _, err = s.parseCsiID(srcSnapID)
if err != nil {
// We couldn't comprehend the identifier.
log.Error("Snapshot identifier not in supported format: " + srcSnapID)
return nil, status.Error(codes.InvalidArgument, "Snapshot identifier not in supported format")
}
volContent = snapID
}
break
default:
return nil, status.Error(codes.InvalidArgument, "VolumeContentSource is missing volume and snapshot source")
}
// check snapshot is licensed
if err := s.IsSnapshotLicensed(ctx, symID, pmaxClient); err != nil {
log.Error("Error - " + err.Error())
return nil, status.Error(codes.Internal, err.Error())
}
}
if SrcDevID != "" && symID != "" {
if symID != symmetrixID {
log.Error("The volume content source is in different PowerMax array")
return nil, status.Errorf(codes.InvalidArgument, "The volume content source is in different PowerMax array")
}
srcVol, err = pmaxClient.GetVolumeByID(ctx, symmetrixID, SrcDevID)
if err != nil {
log.Error("Volume content source volume couldn't be found in the array: " + err.Error())
return nil, status.Errorf(codes.InvalidArgument, "Volume content source volume couldn't be found in the array: %s", err.Error())
}
// reset the volume size to match with source
if requiredCylinders < srcVol.CapacityCYL {
log.Error("Capacity specified is smaller than the source")
return nil, status.Error(codes.InvalidArgument, "Requested capacity is smaller than the source")
}
}
// Get the volume name
volumeName := req.GetName()
if volumeName == "" {
log.Error("Name cannot be empty")
return nil, status.Error(codes.InvalidArgument,
"Name cannot be empty")
}
// Get the Volume prefix from environment
volumePrefix := s.getClusterPrefix()
maxLength := MaxVolIdentifierLength - len(volumePrefix) - len(s.getClusterPrefix()) - len(CsiVolumePrefix) - 1
// First get the short volume name
shortVolumeName := truncateString(volumeName, maxLength)
// Form the volume identifier using short volume name and namespace
var namespaceSuffix string
if namespace != "" {
namespaceSuffix = "-" + namespace
}
volumeIdentifier := fmt.Sprintf("%s%s-%s%s", CsiVolumePrefix, s.getClusterPrefix(), shortVolumeName, namespaceSuffix)
if useNFS {
// calculate size in MiB
reqSizeInMiB := cr.GetRequiredBytes() / MiBSizeInBytes
return file.CreateFileSystem(ctx, reqID, accessibility, params, symmetrixID, storagePoolID, serviceLevel, nasServer, volumeIdentifier, allowRoot, reqSizeInMiB, pmaxClient)
}
// Storage Group is required to be derived from the parameters (such as service level and storage resource pool which are supplied in parameters)
// Storage Group Name can optionally be supplied in the parameters (for testing) to over-ride the default.
if storageGroupName == "" {
if applicationPrefix == "" {
storageGroupName = fmt.Sprintf("%s-%s-%s-%s-SG", CSIPrefix, s.getClusterPrefix(),
serviceLevel, storagePoolID)
} else {
storageGroupName = fmt.Sprintf("%s-%s-%s-%s-%s-SG", CSIPrefix, s.getClusterPrefix(),
applicationPrefix, serviceLevel, storagePoolID)
}
if hostLimitName != "" {
storageGroupName = fmt.Sprintf("%s-%s", storageGroupName, hostLimitName)
}
}
// localProtectionGroupID refers to name of Storage Group which has protected local volumes
// remoteProtectionGroupID refers to name of Storage Group which has protected remote volumes
var localProtectionGroupID string
var remoteProtectionGroupID string
if replicationEnabled == "true" {
localProtectionGroupID = buildProtectionGroupID(namespace, localRDFGrpNo, repMode)
remoteProtectionGroupID = buildProtectionGroupID(namespace, remoteRDFGrpNo, repMode)
}
// log all parameters used in CreateVolume call
fields := map[string]interface{}{
"SymmetrixID": symmetrixID,
"SRP": storagePoolID,
"Accessibility": accessibility,
"ApplicationPrefix": applicationPrefix,
"volumeIdentifier": volumeIdentifier,
"requiredCylinders": requiredCylinders,
"storageGroupName": storageGroupName,
"CSIRequestID": reqID,
"SourceVolume": srcVolID,
"SourceSnapshot": srcSnapID,
"ReplicationEnabled": replicationEnabled,
"RemoteSymID": remoteSymID,
"LocalRDFGroup": localRDFGrpNo,
"RemoteRDFGroup": remoteRDFGrpNo,
"SRDFMode": repMode,
"PVCNamespace": namespace,
"LocalProtectionGroupID": localProtectionGroupID,
"RemoteProtectionGroupID": remoteProtectionGroupID,
HeaderPersistentVolumeName: params[CSIPersistentVolumeName],
HeaderPersistentVolumeClaimName: params[CSIPersistentVolumeClaimName],
HeaderPersistentVolumeClaimNamespace: params[CSIPVCNamespace],
HostIOLimitMBSec: hostMBsec,
HostIOLimitIOSec: hostIOsec,
DynamicDistribution: hostDynDistribution,
}
log.WithFields(fields).Info("Executing CreateVolume with following fields")
// isSGUnprotected is set to true only if SG has a replica, eg if the SG is new
isSGUnprotected := false
if replicationEnabled == "true" {
sg, err := s.getOrCreateProtectedStorageGroup(ctx, symmetrixID, localProtectionGroupID, namespace, localRDFGrpNo, repMode, reqID, pmaxClient)
if err != nil {
return nil, status.Errorf(codes.Internal, "Error in getOrCreateProtectedStorageGroup: (%s)", err.Error())
}
if sg != nil && sg.Rdf == true {
// Check the direction of SG
// Creation of replicated volume is allowed in an SG of type R1
err := s.VerifyProtectedGroupDirection(ctx, symmetrixID, localProtectionGroupID, localRDFGrpNo, pmaxClient)
if err != nil {
return nil, err
}
} else {
isSGUnprotected = true
}
}
// Check existence of the Storage Group and create if necessary.
sg, err := pmaxClient.GetStorageGroup(ctx, symmetrixID, storageGroupName)
log.Debug(fmt.Sprintf("Unable to find storage group: %s", storageGroupName))
if err != nil || sg == nil {
hostLimitsParam := &types.SetHostIOLimitsParam{
HostIOLimitMBSec: hostIOsec,
HostIOLimitIOSec: hostMBsec,
DynamicDistribution: hostDynDistribution,
}
optionalPayload := make(map[string]interface{})
optionalPayload[HostLimits] = hostLimitsParam
if *hostLimitsParam == (types.SetHostIOLimitsParam{}) {
optionalPayload = nil
}
_, err := pmaxClient.CreateStorageGroup(ctx, symmetrixID, storageGroupName, storagePoolID,
serviceLevel, thick == "true", optionalPayload)
if err != nil {
log.Error("Error creating storage group: " + err.Error())
return nil, status.Errorf(codes.Internal, "Error creating storage group: %s", err.Error())
}
}
var vol *types.Volume
// Idempotency test. We will read the volume and check for:
// 1. Existence of a volume with matching volume name
// 2. Matching cylinderSize
// 3. Is a member of the storage group
// 4. Check if snapshot/volume target
log.Debug("Calling GetVolumeIDList for idempotency test")
// For now an exact match
volumeIDList, err := pmaxClient.GetVolumeIDList(ctx, symmetrixID, volumeIdentifier, false)
if err != nil {
log.Error("Error looking up volume for idempotence check: " + err.Error())
return nil, status.Errorf(codes.Internal, "Error looking up volume for idempotence check: %s", err.Error())
}
alreadyExists := false
// isLocalVolumePresent restrict CreateVolumeInProtectedSG call if the volume is present in local SG but not in remote SG
isLocalVolumePresent := false
// Look up the volume(s), if any, returned for the idempotency check to see if there are any matches
// We ignore any volume not in the desired storage group (even though they have the same name).
for _, volumeID := range volumeIDList {
// Fetch the volume
log.WithFields(fields).Info("Calling GetVolumeByID for idempotence check")
vol, err = pmaxClient.GetVolumeByID(ctx, symmetrixID, volumeID)
if err != nil {
log.Error("Error fetching volume for idempotence check: " + err.Error())
return nil, status.Errorf(codes.Internal, "Error fetching volume for idempotence check: %s", err.Error())
}
if len(vol.StorageGroupIDList) < 1 {
log.Error("Idempotence check: StorageGroupIDList is empty for (%s): " + volumeID)
return nil, status.Errorf(codes.Internal, "Idempotence check: StorageGroupIDList is empty for (%s): "+volumeID)
}
matchesStorageGroup := false
for _, sgid := range vol.StorageGroupIDList {
if sgid == storageGroupName {
matchesStorageGroup = true
}
}
if matchesStorageGroup && vol.VolumeIdentifier == volumeIdentifier {
if vol.CapacityCYL != requiredCylinders {
log.Error("A volume with the same name exists but has a different size than required.")
alreadyExists = true
continue
}
var remoteVolumeID string
if replicationEnabled == "true" {
remoteVolumeID, _, err = s.GetRemoteVolumeID(ctx, symmetrixID, localRDFGrpNo, vol.VolumeID, pmaxClient)
if err != nil && !strings.Contains(err.Error(), "The device must be an RDF device") {
return nil, status.Errorf(codes.Internal, "Failed to fetch rdf pair information for (%s) - Error (%s)", vol.VolumeID, err.Error())
}
if remoteVolumeID == "" {
// Missing corresponding Remote Volume Name for existing local volume
// The SG is unprotected as Local volume and Local SG exists but missing corresponding SRDF info
// If the SG was protected, there must exist a corresponding remote replica volume
log.Debugf("Local Volume already exist, skipping creation (%s)", vol.VolumeID)
isLocalVolumePresent = true
continue
}
}
if volContent != "" {
if replicationEnabled == "true" {
if srcSnapID != "" {
err = s.LinkSRDFVolToSnapshot(ctx, reqID, symID, srcVol.VolumeID, snapID, localProtectionGroupID, localRDFGrpNo, vol, bias, false, pmaxClient)
if err != nil {
return nil, err
}
} else if srcVolID != "" {
// Build the temporary snapshot identifier
snapID := fmt.Sprintf("%s%s-%d", TempSnap, s.getClusterPrefix(), time.Now().Nanosecond())
err = s.LinkSRDFVolToVolume(ctx, reqID, symID, srcVol, vol, snapID, localProtectionGroupID, localRDFGrpNo, "false", false, pmaxClient)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to create SRDF volume from volume (%s)", err.Error())
}
}
}
}
log.WithFields(fields).Info("Idempotent volume detected, returning success")
vol.VolumeID = fmt.Sprintf("%s-%s-%s", volumeIdentifier, symmetrixID, vol.VolumeID)
volResp := s.getCSIVolume(vol)
// Set the volume context
attributes := map[string]string{
ServiceLevelParam: serviceLevel,
StoragePoolParam: storagePoolID,
path.Join(s.opts.ReplicationContextPrefix, SymmetrixIDParam): symmetrixID,
CapacityGB: fmt.Sprintf("%.2f", vol.CapacityGB),
ContentSource: volContent,
StorageGroup: storageGroupName,
// Format the time output
"CreationTime": time.Now().Format("20060102150405"),
}
if replicationEnabled == "true" {
addReplicationParamsToVolumeAttributes(attributes, s.opts.ReplicationContextPrefix, remoteSymID, repMode, remoteVolumeID, localRDFGrpNo, remoteRDFGrpNo)
}
volResp.VolumeContext = attributes
csiResp := &csi.CreateVolumeResponse{
Volume: volResp,
}
volResp.ContentSource = contentSource
if accessibility != nil {
volResp.AccessibleTopology = accessibility.Preferred
}
return csiResp, nil
}
}
if alreadyExists {
log.Error("A volume with the same name " + volumeName + "exists but has a different size than requested. Use a different name.")
return nil, status.Errorf(codes.AlreadyExists, "A volume with the same name %s exists but has a different size than requested. Use a different name.", volumeName)
}
// CSI specific metada for authorization
headerMetadata := addMetaData(params)
// Let's create the volume
if !isLocalVolumePresent {
vol, err = pmaxClient.CreateVolumeInStorageGroupS(ctx, symmetrixID, storageGroupName, volumeIdentifier, requiredCylinders, nil, headerMetadata)
if err != nil {
log.Error(fmt.Sprintf("Could not create volume: %s: %s", volumeName, err.Error()))
return nil, status.Errorf(codes.Internal, "Could not create volume: %s: %s", volumeName, err.Error())
}
}
if replicationEnabled == "true" {
log.Debugf("RDF: Found Rdf enabled")
// remote storage group name is kept same as local storage group name
// Check if volume is already added in SG, else add it
protectedSGID := s.GetProtectedStorageGroupID(vol.StorageGroupIDList, localRDFGrpNo+"-"+repMode)
if protectedSGID == "" {
// Volume is not present in Protected Storage Group, Add
err = s.addVolumesToProtectedStorageGroup(ctx, reqID, symmetrixID, localProtectionGroupID, remoteSymID, remoteProtectionGroupID, false, vol.VolumeID, pmaxClient)
if err != nil {
return nil, err
}
}
if isSGUnprotected {
// If the required SG is still unprotected, protect the local SG with RDF info
// If valid RDF group is supplied this will create a remote SG, a RDF pair and add the vol in respective SG created
// Remote storage group name is kept same as local storage group name
err := s.ProtectStorageGroup(ctx, symmetrixID, remoteSymID, localProtectionGroupID, remoteProtectionGroupID, "", localRDFGrpNo, repMode, vol.VolumeID, reqID, false, pmaxClient)
if err != nil {
log.Errorf("Proceeding to remove volume from protected storage group as rollback")
// Remove volume from protected storage group as a rollback
// The device could be just a TDEV and can make RDF unmanageable due to slow u4p response
_, er := pmaxClient.RemoveVolumesFromStorageGroup(ctx, symmetrixID, localProtectionGroupID, true, vol.VolumeID)
if er != nil {
log.Errorf("Error removing volume %s from protected SG %s with error: %s", vol.VolumeID, localProtectionGroupID, er.Error())
}
return nil, err
}
}
}
// If volume content source is specified, initiate no_copy to newly created volume
if contentSource != nil {
if srcVolID != "" {
// Build the temporary snapshot identifier
snapID := fmt.Sprintf("%s%s-%d", TempSnap, s.getClusterPrefix(), time.Now().Nanosecond())
if replicationEnabled == "true" {
err = s.LinkSRDFVolToVolume(ctx, reqID, symID, srcVol, vol, snapID, localProtectionGroupID, localRDFGrpNo, "false", false, pmaxClient)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to create SRDF volume from volume (%s)", err.Error())
}
} else {
err = s.LinkVolumeToVolume(ctx, symID, srcVol, vol.VolumeID, snapID, reqID, false, pmaxClient)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to create volume from volume (%s)", err.Error())
}
}
} else if srcSnapID != "" {
if replicationEnabled == "true" {
err = s.LinkSRDFVolToSnapshot(ctx, reqID, symID, srcVol.VolumeID, snapID, localProtectionGroupID, localRDFGrpNo, vol, bias, false, pmaxClient)
if err != nil {
return nil, err
}
} else {
// Unlink all previous targets from this snapshot if the link is in defined state
err = s.UnlinkTargets(ctx, symID, SrcDevID, pmaxClient)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed unlink existing target from snapshot (%s)", err.Error())
}
err = s.LinkVolumeToSnapshot(ctx, symID, srcVol.VolumeID, vol.VolumeID, snapID, reqID, false, pmaxClient)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to create volume from snapshot (%s)", err.Error())
}
}
}
}
// Formulate the return response
volID := vol.VolumeID
vol.VolumeID = fmt.Sprintf("%s-%s-%s", volumeIdentifier, symmetrixID, vol.VolumeID)
volResp := s.getCSIVolume(vol)
volResp.ContentSource = contentSource
// Set the volume context
attributes := map[string]string{
ServiceLevelParam: serviceLevel,
StoragePoolParam: storagePoolID,
path.Join(s.opts.ReplicationContextPrefix, SymmetrixIDParam): symmetrixID,
CapacityGB: fmt.Sprintf("%.2f", vol.CapacityGB),
ContentSource: volContent,
StorageGroup: storageGroupName,
// Format the time output
"CreationTime": time.Now().Format("20060102150405"),
}
if replicationEnabled == "true" {
remoteVolumeID, _, err := s.GetRemoteVolumeID(ctx, symmetrixID, localRDFGrpNo, volID, pmaxClient)
if err != nil {
return nil, status.Errorf(codes.Internal, "Failed to fetch rdf pair information for (%s) - Error (%s)", vol.VolumeID, err.Error())
}
addReplicationParamsToVolumeAttributes(attributes, s.opts.ReplicationContextPrefix, remoteSymID, repMode, remoteVolumeID, localRDFGrpNo, remoteRDFGrpNo)
}
volResp.VolumeContext = attributes
if accessibility != nil {
volResp.AccessibleTopology = accessibility.Preferred
}
csiResp := &csi.CreateVolumeResponse{
Volume: volResp,
}
log.WithFields(fields).Infof("Created volume with ID: %s", volResp.VolumeId)
return csiResp, nil
}
func (s *service) createMetroVolume(ctx context.Context, req *csi.CreateVolumeRequest, reqID, storagePoolID, symID, storageGroupName, serviceLevel, thick, remoteSymID, localRDFGrpNo, remoteRDFGrpNo, remoteServiceLevel, remoteSRPID, namespace, applicationPrefix, bias, hostLimitName, hostMBsec, hostIOsec, hostDynDist string) (*csi.CreateVolumeResponse, error) {
repMode := Metro
accessibility := req.GetAccessibilityRequirements()
pmaxClient, err := s.GetPowerMaxClient(symID, remoteSymID)
if err != nil {
log.Error(err.Error())
return nil, status.Error(codes.InvalidArgument, err.Error())
}
// Get the required capacity
cr := req.GetCapacityRange()
// validate size on R1
requiredCylinders, err := s.validateVolSize(ctx, cr, symID, storagePoolID, pmaxClient)
if err != nil {
return nil, err
}
// validate size on R2
_, err = s.validateVolSize(ctx, cr, remoteSymID, remoteSRPID, pmaxClient)
if err != nil {
return nil, err
}
// params from snapshot request
var srcVolID, srcSnapID string
var symmID, SrcDevID, snapID string
var srcVol *types.Volume
var volContent string
// When content source is specified, the size of the new volume
// is determined based on the size of the source volume in the
// snapshot. The size of the new volume to be created should be
// greater than or equal to the size of snapshot source
contentSource := req.GetVolumeContentSource()
if contentSource != nil {
switch req.GetVolumeContentSource().GetType().(type) {
case *csi.VolumeContentSource_Volume:
srcVolID = req.GetVolumeContentSource().GetVolume().GetVolumeId()
if srcVolID != "" {
_, symmID, SrcDevID, _, _, err = s.parseCsiID(srcVolID)
if err != nil {
// We couldn't comprehend the identifier.
log.Error("Could not parse CSI VolumeId: " + srcVolID)
return nil, status.Error(codes.InvalidArgument, "Source volume identifier not in supported format")
}
volContent = srcVolID
}
break
case *csi.VolumeContentSource_Snapshot:
srcSnapID = req.GetVolumeContentSource().GetSnapshot().GetSnapshotId()
if srcSnapID != "" {
snapID, symmID, SrcDevID, _, _, err = s.parseCsiID(srcSnapID)
if err != nil {
// We couldn't comprehend the identifier.
log.Error("Snapshot identifier not in supported format: " + srcSnapID)
return nil, status.Error(codes.InvalidArgument, "Snapshot identifier not in supported format")
}
volContent = snapID
}
break
default:
return nil, status.Error(codes.InvalidArgument, "VolumeContentSource is missing volume and snapshot source")
}
// check snapshot is licensed
if err := s.IsSnapshotLicensed(ctx, symmID, pmaxClient); err != nil {
log.Error("Error - " + err.Error())
return nil, status.Error(codes.Internal, err.Error())
}
}
if SrcDevID != "" && symmID != "" {
if symmID != symID {
log.Error("The volume content source is in different PowerMax array")
return nil, status.Errorf(codes.InvalidArgument, "The volume content source is in different PowerMax array")
}
srcVol, err = pmaxClient.GetVolumeByID(ctx, symID, SrcDevID)
if err != nil {
log.Error("Volume content source volume couldn't be found in the array: " + err.Error())
return nil, status.Errorf(codes.InvalidArgument, "Volume content source volume couldn't be found in the array: %s", err.Error())
}
// reset the volume size to match with source
if requiredCylinders < srcVol.CapacityCYL {
log.Error("Capacity specified is smaller than the source")
return nil, status.Error(codes.InvalidArgument, "Requested capacity is smaller than the source")
}
}
// Validate volume capabilities
vcs := req.GetVolumeCapabilities()
if vcs != nil {
isBlock := accTypeIsBlock(vcs)
if isBlock && !s.opts.EnableBlock {
return nil, status.Error(codes.InvalidArgument, "Block Volume Capability is not supported")
}
}
// Get the volume name
volumeName := req.GetName()
if volumeName == "" {
log.Error("Name cannot be empty")
return nil, status.Error(codes.InvalidArgument,
"Name cannot be empty")
}
// Get the Volume prefix from environment
volumePrefix := s.getClusterPrefix()
maxLength := MaxVolIdentifierLength - len(volumePrefix) - len(s.getClusterPrefix()) - len(CsiVolumePrefix) - 1
// First get the short volume name
shortVolumeName := truncateString(volumeName, maxLength)
// Form the volume identifier using short volume name and namespace
var namespaceSuffix string
if namespace != "" {
namespaceSuffix = "-" + namespace
}
volumeIdentifier := fmt.Sprintf("%s%s-%s%s", CsiVolumePrefix, s.getClusterPrefix(), shortVolumeName, namespaceSuffix)
// Storage Group is required to be derived from the parameters (such as service level and storage resource pool which are supplied in parameters)
// Storage Group Name can optionally be supplied in the parameters (for testing) to over-ride the default.
var remoteStorageGroupName string
if storageGroupName == "" {
if applicationPrefix == "" {
storageGroupName = fmt.Sprintf("%s-%s-%s-%s-SG", CSIPrefix, s.getClusterPrefix(),
serviceLevel, storagePoolID)
remoteStorageGroupName = fmt.Sprintf("%s-%s-%s-%s-SG", CSIPrefix, s.getClusterPrefix(),
remoteServiceLevel, remoteSRPID)
} else {
storageGroupName = fmt.Sprintf("%s-%s-%s-%s-%s-SG", CSIPrefix, s.getClusterPrefix(),
applicationPrefix, serviceLevel, storagePoolID)
remoteStorageGroupName = fmt.Sprintf("%s-%s-%s-%s-%s-SG", CSIPrefix, s.getClusterPrefix(),
applicationPrefix, remoteServiceLevel, remoteSRPID)
}
if hostLimitName != "" {
storageGroupName = fmt.Sprintf("%s-%s", storageGroupName, hostLimitName)
remoteStorageGroupName = fmt.Sprintf("%s-%s", remoteStorageGroupName, hostLimitName)
}
}
// localProtectionGroupID refers to name of Storage Group which has protected local volumes
// remoteProtectionGroupID refers to name of Storage Group which has protected remote volumes
localProtectionGroupID := buildProtectionGroupID(namespace, localRDFGrpNo, repMode)
remoteProtectionGroupID := buildProtectionGroupID(namespace, remoteRDFGrpNo, repMode)
// log all parameters used in CreateVolume call
fields := map[string]interface{}{
"SymmetrixID": symID,
"SRP": storagePoolID,
"Accessibility": accessibility,