-
Notifications
You must be signed in to change notification settings - Fork 19
/
controller.go
1759 lines (1569 loc) · 66 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 (c) 2019 Dell EMC Corporation
All Rights Reserved
*/
package service
import (
"fmt"
"strconv"
"strings"
"github.com/dell/gounity/api"
"github.com/dell/gounity/util"
"github.com/golang/protobuf/ptypes"
"github.com/golang/protobuf/ptypes/timestamp"
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/dell/csi-unity/service/utils"
"github.com/dell/gounity"
"github.com/dell/gounity/types"
"golang.org/x/net/context"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
const (
// KeyStoragePool is the key used to get the storagePool name from the
// volume create parameters map
keyStoragePool = "storagePool"
keyThinProvisioned = "thinProvisioned"
keyDescription = "description"
keyDataReductionEnabled = "isDataReductionEnabled"
keyTieringPolicy = "tieringPolicy"
keyHostIOLimitName = "hostIOLimitName"
keyArrayId = "arrayId"
keyProtocol = "protocol"
keyNasServer = "nasServer"
keyHostIoSize = "hostIoSize"
)
const (
FC = "FC"
ISCSI = "iSCSI"
NFS = "NFS"
ProtocolUnknown = "Unknown"
ProtocolNFS = int(0)
MAX_ENTRIES_SNAPSHOT = 100
MAX_ENTRIES_VOLUME = 100
NFSShareLocalPath = "/"
NFSShareNamePrefix = "csishare-"
AdditionalFilesystemSize = 1.5 * 1024 * 1024 * 1024
)
var (
errUnknownAccessType = "unknown access type is not Block or Mount"
errUnknownAccessMode = "access mode cannot be UNKNOWN"
errIncompatibleAccessMode = "access mode should be single node reader or single node writer"
errNoMultiNodeWriter = "Multi-node with writer(s) only supported for block access type"
errNoMultiNodeReader = "Multi-node Reader access mode is only supported for block access type"
errBlockReadOnly = "Read Only Many access mode not supported for Block Volume"
errBlockNFS = "Block Volume Capability is not supported for NFS"
)
//CRParams - defines placeholder for all create volume parameters
type CRParams struct {
VolumeName string
Protocol string
StoragePool string
Desciption string
HostIOLimitName string
Thin bool
DataReduction bool
Size int64
TieringPolicy int64
HostIoSize int64
}
type resourceType string
const volumeType resourceType = "volume"
const snapshotType resourceType = "snapshot"
func (s *service) CreateVolume(ctx context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) {
ctx, log, rid := GetRunidLog(ctx)
log.Debugf("Executing CreateVolume with args: %+v", *req)
params := req.GetParameters()
arrayID := strings.ToLower(strings.TrimSpace(params[keyArrayId]))
if arrayID == "" {
return nil, status.Error(codes.InvalidArgument, utils.GetMessageWithRunID(rid, "ArrayId cannot be empty"))
}
ctx, log = setArrayIdContext(ctx, arrayID)
if err := s.requireProbe(ctx, arrayID); err != nil {
return nil, err
}
unity, err := s.getUnityClient(ctx, arrayID)
if err != nil {
return nil, err
}
protocol, storagePool, size, tieringPolicy, hostIoSize, thin, dataReduction, err := ValidateCreateVolumeRequest(ctx, req)
if err != nil {
return nil, err
}
volName := req.GetName()
accessibility := req.GetAccessibilityRequirements()
preferredAccessibility := accessibility.GetPreferred()
log.Infof("PREFERRED-->%+v", preferredAccessibility)
desc := params[keyDescription]
hostIOLimitName := strings.TrimSpace(params[keyHostIOLimitName])
crParams := CRParams{
VolumeName: volName,
Protocol: protocol,
StoragePool: storagePool,
Desciption: desc,
HostIOLimitName: hostIOLimitName,
Thin: thin,
DataReduction: dataReduction,
Size: size,
TieringPolicy: tieringPolicy,
HostIoSize: hostIoSize,
}
// Creating Volume from a volume content source
contentSource := req.GetVolumeContentSource()
if contentSource != nil {
volumeSource := contentSource.GetVolume()
if volumeSource != nil {
sourceVolID := volumeSource.VolumeId
log.Debugf("Cloning Volume: %s", sourceVolID)
resp, err := s.createVolumeClone(ctx, &crParams, sourceVolID, arrayID, contentSource, unity, preferredAccessibility)
return resp, err
}
snapshotSource := contentSource.GetSnapshot()
if snapshotSource != nil {
snapshotID := snapshotSource.SnapshotId
log.Debugf("Create Volume from Snapshot: %s", snapshotID)
resp, err := s.createVolumeFromSnap(ctx, &crParams, snapshotID, arrayID, contentSource, unity, preferredAccessibility)
return resp, err
}
}
//Create Fresh Volume
if protocol == NFS {
nasServer, ok := params[keyNasServer]
if !ok {
return nil, status.Errorf(codes.InvalidArgument, utils.GetMessageWithRunID(rid, "`%s` is a required parameter", keyNasServer))
}
//Add AdditionalFilesystemSize in size as Unity use this much size for metadata in filesystem
size += AdditionalFilesystemSize
// log all parameters used in Create File System call
fields := map[string]interface{}{
"storagePool": storagePool,
"Accessibility": accessibility,
"contentSource": contentSource,
"thin": thin,
"dataReduction": dataReduction,
"tieringPolicy": tieringPolicy,
"protocol": protocol,
"nasServer": nasServer,
"hostIoSize": hostIoSize,
}
log.WithFields(fields).Infof("Executing Create File System with following fields")
//Idempotency check
fileAPI := gounity.NewFilesystem(unity)
filesystem, _ := fileAPI.FindFilesystemByName(ctx, volName)
if filesystem != nil {
content := filesystem.FileContent
if int64(content.SizeTotal) == size && content.NASServer.Id == nasServer && content.Pool.Id == storagePool {
log.Info("Filesystem exists in the requested state with same size, NAS server and storage pool")
filesystem.FileContent.SizeTotal -= AdditionalFilesystemSize
return utils.GetVolumeResponseFromFilesystem(filesystem, arrayID, protocol, preferredAccessibility), nil
} else {
log.Info("'Filesystem name' already exists and size/NAS server/storage pool is different")
return nil, status.Error(codes.AlreadyExists, utils.GetMessageWithRunID(rid, "'Filesystem name' already exists and size/NAS server/storage pool is different."))
}
}
log.Debug("Filesystem does not exist, proceeding to create new filesystem")
//Hardcoded ProtocolNFS to 0 in order to support only NFS
resp, err := fileAPI.CreateFilesystem(ctx, volName, storagePool, desc, nasServer, uint64(size), int(tieringPolicy), int(hostIoSize), ProtocolNFS, thin, dataReduction)
//Add method to create filesystem
if err != nil {
log.Debugf("Filesystem create response:%v Error:%v", resp, err)
return nil, status.Error(codes.Unknown, utils.GetMessageWithRunID(rid, "Create Filesystem %s failed with error: %v", volName, err))
}
resp, err = fileAPI.FindFilesystemByName(ctx, volName)
if err != nil {
log.Debugf("Find Filesystem response: %v Error: %v", resp, err)
}
if resp != nil {
resp.FileContent.SizeTotal -= AdditionalFilesystemSize
filesystemResp := utils.GetVolumeResponseFromFilesystem(resp, arrayID, protocol, preferredAccessibility)
return filesystemResp, nil
}
} else {
// log all parameters used in CreateVolume call
fields := map[string]interface{}{
"storagePool": storagePool,
"Accessibility": accessibility,
"contentSource": contentSource,
"thin": thin,
"dataReduction": dataReduction,
"tieringPolicy": tieringPolicy,
"protocol": protocol,
"hostIOLimitName": hostIOLimitName,
}
log.WithFields(fields).Infof("Executing CreateVolume with following fields")
volumeAPI := gounity.NewVolume(unity)
var hostIOLimit *types.IoLimitPolicy
var hostIOLimitId string
if hostIOLimitName != "" {
hostIOLimit, err = volumeAPI.FindHostIOLimitByName(ctx, hostIOLimitName)
if err != nil {
return nil, status.Error(codes.InvalidArgument, utils.GetMessageWithRunID(rid, "HostIOLimitName %s not found. Error: %v", hostIOLimitName, err))
}
hostIOLimitId = hostIOLimit.IoLimitPolicyContent.Id
}
//Idempotency check
vol, _ := volumeAPI.FindVolumeByName(ctx, volName)
if vol != nil {
content := vol.VolumeContent
if int64(content.SizeTotal) == size {
log.Info("Volume exists in the requested state with same size")
return utils.GetVolumeResponseFromVolume(vol, arrayID, protocol, preferredAccessibility), nil
} else {
log.Info("'Volume name' already exists and size is different")
return nil, status.Error(codes.AlreadyExists, utils.GetMessageWithRunID(rid, "'Volume name' already exists and size is different."))
}
}
log.Debug("Volume does not exist, proceeding to create new volume")
resp, err := volumeAPI.CreateLun(ctx, volName, storagePool, desc, uint64(size), int(tieringPolicy), hostIOLimitId, thin, dataReduction)
if err != nil {
return nil, status.Error(codes.Unknown, utils.GetMessageWithRunID(rid, "Create Volume %s failed with error: %v", volName, err))
}
resp, err = volumeAPI.FindVolumeByName(ctx, volName)
if resp != nil {
volumeResp := utils.GetVolumeResponseFromVolume(resp, arrayID, protocol, preferredAccessibility)
log.Debugf("CreateVolume successful for volid: [%s]", volumeResp.Volume.VolumeId)
return volumeResp, nil
}
}
return nil, status.Error(codes.NotFound, utils.GetMessageWithRunID(rid, "Volume/Filesystem not found after create. %v", err))
}
func (s *service) DeleteVolume(
ctx context.Context,
req *csi.DeleteVolumeRequest) (
*csi.DeleteVolumeResponse, error) {
ctx, log, rid := GetRunidLog(ctx)
log.Debugf("Executing DeleteVolume with args: %+v", *req)
var snapErr error
volID, protocol, arrayId, unity, err := s.validateAndGetResourceDetails(ctx, req.GetVolumeId(), volumeType)
if err != nil {
return nil, err
}
ctx, log = setArrayIdContext(ctx, arrayId)
if err := s.requireProbe(ctx, arrayId); err != nil {
return nil, err
}
deleteVolumeResp := &csi.DeleteVolumeResponse{}
//Not validating protocol here to support deletion of pvcs from v1.0
if protocol != NFS {
//Delete logic for FC and iSCSI volumes
var throwErr error
err, throwErr = s.deleteBlockVolume(ctx, volID, unity)
if throwErr != nil {
return nil, throwErr
}
} else {
//Delete logic for Filesystem
var throwErr error
err, snapErr, throwErr = s.deleteFilesystem(ctx, volID, unity)
if throwErr != nil {
return nil, throwErr
}
}
//Idempotency check
if err == nil {
log.Debugf("DeleteVolume successful for volid: [%s]", req.VolumeId)
return deleteVolumeResp, nil
} else if err == gounity.FilesystemNotFoundError || err == gounity.VolumeNotFoundError || snapErr == gounity.SnapshotNotFoundError {
log.Debug("Volume not found on array")
log.Debugf("DeleteVolume successful for volid: [%s]", req.VolumeId)
return deleteVolumeResp, nil
}
return nil, status.Error(codes.FailedPrecondition, utils.GetMessageWithRunID(rid, "Delete Volume %s failed with error: %v", volID, err))
}
func (s *service) ControllerPublishVolume(
ctx context.Context,
req *csi.ControllerPublishVolumeRequest) (
*csi.ControllerPublishVolumeResponse, error) {
ctx, log, _ := GetRunidLog(ctx)
log.Debugf("Executing ControllerPublishVolume with args: %+v", *req)
volID, protocol, arrayID, unity, err := s.validateAndGetResourceDetails(ctx, req.GetVolumeId(), volumeType)
if err != nil {
return nil, err
}
ctx, log = setArrayIdContext(ctx, arrayID)
if err := s.requireProbe(ctx, arrayID); err != nil {
return nil, err
}
protocol, nodeID, err := ValidateControllerPublishRequest(ctx, req, protocol)
if err != nil {
return nil, err
}
hostNames := strings.Split(nodeID, ",")
host, err := s.getHostId(ctx, arrayID, hostNames[0], hostNames[1])
if err != nil {
return nil, err
}
hostContent := host.HostContent
hostID := hostContent.ID
pinfo := make(map[string]string)
pinfo["volumeContextId"] = req.GetVolumeId()
pinfo["arrayId"] = arrayID
pinfo["host"] = nodeID
vc := req.GetVolumeCapability()
am := vc.GetAccessMode()
if protocol == FC || protocol == ISCSI {
resp, err := s.exportVolume(ctx, protocol, volID, hostID, nodeID, arrayID, unity, pinfo, host, vc)
return resp, err
}
//Export for NFS
resp, err := s.exportFilesystem(ctx, volID, hostID, nodeID, arrayID, unity, pinfo, am)
return resp, err
}
func (s *service) ControllerUnpublishVolume(
ctx context.Context,
req *csi.ControllerUnpublishVolumeRequest) (
*csi.ControllerUnpublishVolumeResponse, error) {
ctx, log, rid := GetRunidLog(ctx)
log.Debugf("Executing ControllerUnpublishVolume with args: %+v", *req)
volID, protocol, arrayID, unity, err := s.validateAndGetResourceDetails(ctx, req.GetVolumeId(), volumeType)
if err != nil {
return nil, err
}
ctx, log = setArrayIdContext(ctx, arrayID)
if err := s.requireProbe(ctx, arrayID); err != nil {
return nil, err
}
nodeID := req.GetNodeId()
if nodeID == "" {
return nil, status.Error(codes.InvalidArgument, utils.GetMessageWithRunID(rid, "Node ID is required"))
}
hostNames := strings.Split(nodeID, ",")
host, err := s.getHostId(ctx, arrayID, hostNames[0], hostNames[1])
if err != nil {
return nil, err
}
hostContent := host.HostContent
hostID := hostContent.ID
if protocol != NFS {
volumeAPI := gounity.NewVolume(unity)
vol, err := volumeAPI.FindVolumeById(ctx, volID)
if err != nil {
// If the volume isn't found, k8s will retry Controller Unpublish forever so...
// There is no way back if volume isn't found and so considering this scenario idempotent
if err == gounity.VolumeNotFoundError {
log.Debugf("Volume %s not found on the array %s during Controller Unpublish. Hence considering the call to be idempotent", volID, arrayID)
return &csi.ControllerUnpublishVolumeResponse{}, nil
}
return nil, status.Error(codes.Internal, utils.GetMessageWithRunID(rid, "%v", err))
}
//Idempotency check
content := vol.VolumeContent
if len(content.HostAccessResponse) > 0 {
hostIDList := make([]string, 0)
//Check if the volume is published to any other node and retain it - RWX raw block
for _, hostaccess := range content.HostAccessResponse {
hostcontent := hostaccess.HostContent
hostAccessID := hostcontent.ID
if hostAccessID != hostID {
hostIDList = append(hostIDList, hostAccessID)
}
}
log.Debug("Removing Host access on Volume ", volID)
log.Debug("List of host access that will be retained on the volume: ", hostIDList)
err = volumeAPI.ModifyVolumeExport(ctx, volID, hostIDList)
if err != nil {
return nil, status.Error(codes.Unknown, utils.GetMessageWithRunID(rid, "Unexport Volume Failed. %v", err))
}
} else {
log.Info(fmt.Sprintf("The given Node %s does not have access on the given volume %s. Already in Unpublished state.", hostID, volID))
}
log.Debugf("ControllerUnpublishVolume successful for volid: [%s]", req.GetVolumeId())
return &csi.ControllerUnpublishVolumeResponse{}, nil
}
//Unexport for NFS
err = s.unexportFilesystem(ctx, volID, hostID, nodeID, req.GetVolumeId(), arrayID, unity)
if err != nil {
return nil, err
}
return &csi.ControllerUnpublishVolumeResponse{}, nil
}
func (s *service) ValidateVolumeCapabilities(ctx context.Context, req *csi.ValidateVolumeCapabilitiesRequest) (*csi.ValidateVolumeCapabilitiesResponse, error) {
ctx, log, rid := GetRunidLog(ctx)
log.Debugf("Executing ValidateVolumeCapabilities with args: %+v", *req)
volID, _, arrayId, unity, err := s.validateAndGetResourceDetails(ctx, req.GetVolumeId(), volumeType)
if err != nil {
return nil, err
}
ctx, log = setArrayIdContext(ctx, arrayId)
if err := s.requireProbe(ctx, arrayId); err != nil {
return nil, err
}
volumeAPI := gounity.NewVolume(unity)
_, err = volumeAPI.FindVolumeById(ctx, volID)
if err != nil {
return nil, status.Error(codes.NotFound, utils.GetMessageWithRunID(rid, "Volume not found. Error: %v", err))
}
params := req.GetParameters()
protocol, _ := params[keyProtocol]
if protocol == "" {
log.Errorf("Protocol is required to validate capabilities")
return nil, status.Error(codes.NotFound, utils.GetMessageWithRunID(rid, "Protocol is required to validate capabilities"))
}
vcs := req.GetVolumeCapabilities()
supported, reason := valVolumeCaps(vcs, protocol)
resp := &csi.ValidateVolumeCapabilitiesResponse{}
if supported {
// The optional fields volume_context and parameters are not passed.
confirmed := &csi.ValidateVolumeCapabilitiesResponse_Confirmed{}
confirmed.VolumeCapabilities = vcs
resp.Confirmed = confirmed
return resp, nil
} else {
resp.Message = reason
return resp, status.Error(codes.Unknown, utils.GetMessageWithRunID(rid, "Unsupported capability"))
}
}
func (s *service) ListVolumes(ctx context.Context, req *csi.ListVolumesRequest) (*csi.ListVolumesResponse, error) {
return nil, status.Error(codes.Unimplemented, "Not implemented")
}
func (s *service) GetCapacity(
ctx context.Context,
req *csi.GetCapacityRequest) (
*csi.GetCapacityResponse, error) {
return nil, status.Error(codes.Unimplemented, "Not implemented")
}
func (s *service) CreateSnapshot(ctx context.Context, req *csi.CreateSnapshotRequest) (*csi.CreateSnapshotResponse, error) {
ctx, log, rid := GetRunidLog(ctx)
log.Debugf("Executing CreateSnapshot with args: %+v", *req)
if len(req.SourceVolumeId) == 0 {
return nil, status.Error(codes.InvalidArgument, utils.GetMessageWithRunID(rid, "Storage Resource ID cannot be empty"))
}
var err error
req.Name, err = util.ValidateResourceName(req.Name, api.MaxResourceNameLength)
if err != nil {
return nil, status.Error(codes.InvalidArgument, utils.GetMessageWithRunID(rid, "invalid snapshot name [%v]", err))
}
//Source volume is for volume clone or snapshot clone
volId, protocol, arrayId, _, err := s.validateAndGetResourceDetails(ctx, req.SourceVolumeId, volumeType)
if err != nil {
return nil, err
}
ctx, log = setArrayIdContext(ctx, arrayId)
if err := s.requireProbe(ctx, arrayId); err != nil {
return nil, err
}
//Idempotency check
snap, err := s.createIdempotentSnapshot(ctx, req.Name, volId, req.Parameters["description"], req.Parameters["retentionDuration"], protocol, arrayId, false)
if err != nil {
return nil, err
}
return utils.GetSnapshotResponseFromSnapshot(snap, protocol, arrayId), nil
}
func (s *service) DeleteSnapshot(ctx context.Context, req *csi.DeleteSnapshotRequest) (*csi.DeleteSnapshotResponse, error) {
ctx, log, rid := GetRunidLog(ctx)
log.Debugf("Executing DeleteSnapshot with args: %+v", *req)
snapId, _, arrayId, unity, err := s.validateAndGetResourceDetails(ctx, req.SnapshotId, snapshotType)
if err != nil {
return nil, err
}
ctx, log = setArrayIdContext(ctx, arrayId)
if err := s.requireProbe(ctx, arrayId); err != nil {
return nil, err
}
snapApi := gounity.NewSnapshot(unity)
//Idempotency check
snap, err := snapApi.FindSnapshotById(ctx, snapId)
//snapshot exists, continue deleting the snapshot
if err != nil {
log.Info("Snapshot doesn't exists")
}
if snap != nil {
err := snapApi.DeleteSnapshot(ctx, snapId)
if err != nil {
return nil, status.Error(codes.Unknown, utils.GetMessageWithRunID(rid, "Delete Snapshot error: %v", err))
}
}
delSnapResponse := &csi.DeleteSnapshotResponse{}
log.Debugf("Delete snapshot successful [%s]", req.SnapshotId)
return delSnapResponse, nil
}
func (s *service) ListSnapshots(ctx context.Context, req *csi.ListSnapshotsRequest) (*csi.ListSnapshotsResponse, error) {
ctx, log, rid := GetRunidLog(ctx)
log.Infof("Executing ListSnapshot with args: %+v", *req)
var (
startToken int
err error
maxEntries = int(req.MaxEntries)
)
snapId, protocol, arrayId, unity, err := s.validateAndGetResourceDetails(ctx, req.SnapshotId, snapshotType)
if err != nil {
return nil, err
}
ctx, log = setArrayIdContext(ctx, arrayId)
if err := s.requireProbe(ctx, arrayId); err != nil {
return nil, err
}
snapApi := gounity.NewSnapshot(unity)
//Limiting the number of snapshots to 100 to avoid timeout issues
if maxEntries > MAX_ENTRIES_SNAPSHOT || maxEntries == 0 {
maxEntries = MAX_ENTRIES_SNAPSHOT
}
if req.StartingToken != "" {
i, err := strconv.ParseInt(req.StartingToken, 10, 64)
if err != nil {
return nil, status.Error(codes.InvalidArgument, utils.GetMessageWithRunID(rid, "Unable to parse StartingToken: %v into uint32", req.StartingToken))
}
startToken = int(i)
}
snaps, nextToken, err := snapApi.ListSnapshots(ctx, startToken, maxEntries, "", snapId)
if err != nil {
return nil, status.Error(codes.NotFound, utils.GetMessageWithRunID(rid, "Unable to get the snapshots: %v", err))
}
// Process the source snapshots and make CSI Snapshot
entries, err := s.getCSISnapshots(snaps, req.SourceVolumeId, protocol, arrayId)
if err != nil {
return nil, status.Error(codes.Unknown, utils.GetMessageWithRunID(rid, err.Error()))
}
log.Debugf("ListSnapshot successful for snapid: [%s]", req.SnapshotId)
return &csi.ListSnapshotsResponse{
Entries: entries,
NextToken: strconv.Itoa(nextToken),
}, nil
}
func (s *service) controllerProbe(ctx context.Context, arrayId string) error {
return s.probe(ctx, "Controller", arrayId)
}
// ControllerGetCapabilities implements the default GRPC callout.
// Default supports all capabilities
func (cs *service) ControllerGetCapabilities(ctx context.Context, req *csi.ControllerGetCapabilitiesRequest) (*csi.ControllerGetCapabilitiesResponse, error) {
ctx, log, _ := GetRunidLog(ctx)
log.Debugf("Executing ControllerGetCapabilities with args: %+v", *req)
return &csi.ControllerGetCapabilitiesResponse{
Capabilities: []*csi.ControllerServiceCapability{
&csi.ControllerServiceCapability{
Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME,
},
},
},
&csi.ControllerServiceCapability{
Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_PUBLISH_UNPUBLISH_VOLUME,
},
},
},
&csi.ControllerServiceCapability{
Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_LIST_VOLUMES,
},
},
},
&csi.ControllerServiceCapability{
Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_GET_CAPACITY,
},
},
},
&csi.ControllerServiceCapability{
Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT,
},
},
},
&csi.ControllerServiceCapability{
Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_LIST_SNAPSHOTS,
},
},
},
&csi.ControllerServiceCapability{
Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_EXPAND_VOLUME,
},
},
},
&csi.ControllerServiceCapability{
Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_CLONE_VOLUME,
},
},
},
&csi.ControllerServiceCapability{
Type: &csi.ControllerServiceCapability_Rpc{
Rpc: &csi.ControllerServiceCapability_RPC{
Type: csi.ControllerServiceCapability_RPC_PUBLISH_READONLY,
},
},
},
},
}, nil
}
func (s *service) ControllerExpandVolume(ctx context.Context, req *csi.ControllerExpandVolumeRequest) (*csi.ControllerExpandVolumeResponse, error) {
ctx, log, rid := GetRunidLog(ctx)
log.Debugf("Executing ControllerExpandVolume with args: %+v", *req)
if req.VolumeId == "" {
return nil, status.Error(codes.InvalidArgument, utils.GetMessageWithRunID(rid, "volumeId is mandatory parameter"))
}
volId, protocol, arrayId, unity, err := s.validateAndGetResourceDetails(ctx, req.VolumeId, volumeType)
if err != nil {
return nil, err
}
ctx, log = setArrayIdContext(ctx, arrayId)
if err := s.requireProbe(ctx, arrayId); err != nil {
return nil, err
}
var capacity int64
if cr := req.CapacityRange; cr != nil {
if rb := cr.RequiredBytes; rb > 0 {
capacity = rb
}
if lb := cr.LimitBytes; lb > 0 {
capacity = lb
}
}
if capacity <= 0 {
return nil, status.Error(codes.InvalidArgument, utils.GetMessageWithRunID(rid, "Required bytes can not be 0 or less"))
}
expandVolumeResp := &csi.ControllerExpandVolumeResponse{
CapacityBytes: capacity,
}
if protocol == NFS {
//Adding Additional size used for metadata
capacity += AdditionalFilesystemSize
filesystemApi := gounity.NewFilesystem(unity)
filesystem, err := filesystemApi.FindFilesystemById(ctx, volId)
if err != nil {
snapshotApi := gounity.NewSnapshot(unity)
_, err = snapshotApi.FindSnapshotById(ctx, volId)
if err != nil {
return nil, status.Error(codes.NotFound, utils.GetMessageWithRunID(rid, "Find filesystem %s failed with error: %v", volId, err))
}
return nil, status.Error(codes.Unimplemented, utils.GetMessageWithRunID(rid, "Expand Volume not supported for cloned filesystems(snapshot on array)"))
}
//Idempotency check
if filesystem.FileContent.SizeTotal >= uint64(capacity) {
log.Infof("New Filesystem size (%d) is same as existing Filesystem size. Ignoring expand volume operation.", filesystem.FileContent.SizeTotal)
expandVolumeResp := &csi.ControllerExpandVolumeResponse{
CapacityBytes: 0,
}
expandVolumeResp.NodeExpansionRequired = false
return expandVolumeResp, nil
}
err = filesystemApi.ExpandFilesystem(ctx, volId, uint64(capacity))
if err != nil {
return nil, status.Error(codes.Unknown, utils.GetMessageWithRunID(rid, "Expand filesystem failed with error: %v", err))
}
filesystem, err = filesystemApi.FindFilesystemById(ctx, volId)
if err != nil {
return nil, status.Error(codes.NotFound, utils.GetMessageWithRunID(rid, "Find filesystem failed with error: %v", err))
}
expandVolumeResp.CapacityBytes = int64(filesystem.FileContent.SizeTotal) - AdditionalFilesystemSize
expandVolumeResp.NodeExpansionRequired = false
return expandVolumeResp, err
} else {
volumeApi := gounity.NewVolume(unity)
//Idempotency check
volume, err := volumeApi.FindVolumeById(ctx, volId)
if err != nil {
return nil, status.Error(codes.NotFound, utils.GetMessageWithRunID(rid, "Find volume failed with error: %v", err))
}
nodeExpansionRequired := false
content := volume.VolumeContent
if len(content.HostAccessResponse) >= 1 { //If the volume has 1 or more host access then set nodeExpansionRequired as true
nodeExpansionRequired = true
}
if volume.VolumeContent.SizeTotal >= uint64(capacity) {
log.Infof("New Volume size (%d) is same as existing Volume size. Ignoring expand volume operation.", volume.VolumeContent.SizeTotal)
expandVolumeResp := &csi.ControllerExpandVolumeResponse{
CapacityBytes: 0,
}
expandVolumeResp.NodeExpansionRequired = nodeExpansionRequired
return expandVolumeResp, nil
}
err = volumeApi.ExpandVolume(ctx, volId, uint64(capacity))
if err != nil {
return nil, status.Error(codes.Unknown, utils.GetMessageWithRunID(rid, "Expand volume failed with error: %v", err))
}
volume, err = volumeApi.FindVolumeById(ctx, volId)
if err != nil {
return nil, status.Error(codes.NotFound, utils.GetMessageWithRunID(rid, "Find volume failed with error: %v", err))
}
expandVolumeResp.CapacityBytes = int64(volume.VolumeContent.SizeTotal)
expandVolumeResp.NodeExpansionRequired = nodeExpansionRequired
return expandVolumeResp, err
}
}
func (s *service) getCSIVolumes(volumes []types.Volume) ([]*csi.ListVolumesResponse_Entry, error) {
entries := make([]*csi.ListVolumesResponse_Entry, len(volumes))
for i, vol := range volumes {
// Make the additional volume attributes
attributes := map[string]string{
"Name": vol.VolumeContent.Name,
"Type": strconv.Itoa(vol.VolumeContent.Type),
"Wwn": vol.VolumeContent.Wwn,
"StoragePoolID": vol.VolumeContent.Pool.Id,
}
//Create CSI volume
vi := &csi.Volume{
VolumeId: vol.VolumeContent.ResourceId,
CapacityBytes: int64(vol.VolumeContent.SizeTotal),
VolumeContext: attributes,
}
entries[i] = &csi.ListVolumesResponse_Entry{
Volume: vi,
}
}
return entries, nil
}
func (s *service) getCSISnapshots(snaps []types.Snapshot, volId, protocol, arrayId string) ([]*csi.ListSnapshotsResponse_Entry, error) {
entries := make([]*csi.ListSnapshotsResponse_Entry, len(snaps))
for i, snap := range snaps {
isReady := false
if snap.SnapshotContent.State == 2 {
isReady = true
}
var timestamp *timestamp.Timestamp
if !snap.SnapshotContent.CreationTime.IsZero() {
timestamp, _ = ptypes.TimestampProto(snap.SnapshotContent.CreationTime)
}
snapId := fmt.Sprintf("%s-%s-%s-%s", snap.SnapshotContent.Name, protocol, arrayId, snap.SnapshotContent.ResourceId)
size := snap.SnapshotContent.Size
if protocol == NFS {
size -= AdditionalFilesystemSize
}
//Create CSI Snapshot
vi := &csi.Snapshot{
SizeBytes: size,
SnapshotId: snapId,
SourceVolumeId: volId,
CreationTime: timestamp,
ReadyToUse: isReady,
}
entries[i] = &csi.ListSnapshotsResponse_Entry{
Snapshot: vi,
}
}
return entries, nil
}
//@TODO: Check if arrayID can be changed to unity client
func (s *service) getFilesystemByResourceID(ctx context.Context, resourceID, arrayID string) (*types.Filesystem, error) {
ctx, _, rid := GetRunidLog(ctx)
unity, err := s.getUnityClient(ctx, arrayID)
if err != nil {
return nil, err
}
filesystemAPI := gounity.NewFilesystem(unity)
filesystemID, err := filesystemAPI.GetFilesystemIdFromResId(ctx, resourceID)
if err != nil {
return nil, status.Error(codes.NotFound, utils.GetMessageWithRunID(rid, "Storage resource: %s filesystem Id not found. Error: %v", resourceID, err))
}
sourceFilesystemResp, err := filesystemAPI.FindFilesystemById(ctx, filesystemID)
if err != nil {
return nil, status.Error(codes.NotFound, utils.GetMessageWithRunID(rid, "Filesystem: %s not found. Error: %v", filesystemID, err))
}
return sourceFilesystemResp, nil
}
//Create Volume from Snapshot(Copy snapshot on array)
func (s *service) createFilesystemFromSnapshot(ctx context.Context, snapID, volumeName, arrayID string) (*types.Snapshot, error) {
ctx, _, rid := GetRunidLog(ctx)
unity, err := s.getUnityClient(ctx, arrayID)
if err != nil {
return nil, err
}
snapshotAPI := gounity.NewSnapshot(unity)
snapResp, err := snapshotAPI.CopySnapshot(ctx, snapID, volumeName)
if err != nil {
return nil, status.Error(codes.Unknown, utils.GetMessageWithRunID(rid, "Create Filesystem from snapshot failed with error. Error: %v", err))
}
snapResp, err = snapshotAPI.FindSnapshotByName(ctx, volumeName)
if err != nil {
return nil, status.Error(codes.Unknown, utils.GetMessageWithRunID(rid, "Create Filesystem from snapshot failed with error. Error: %v", err))
}
return snapResp, nil
}
func (s *service) createIdempotentSnapshot(ctx context.Context, snapshotName, sourceVolID, description, retentionDuration, protocol, arrayID string, isClone bool) (*types.Snapshot, error) {
ctx, log, rid := GetRunidLog(ctx)
unity, err := s.getUnityClient(ctx, arrayID)
if err != nil {
return nil, err
}
snapshotAPI := gounity.NewSnapshot(unity)
isSnapshot := false
var snapResp *types.Snapshot
var filesystemResp *types.Filesystem
if protocol == NFS {
fileAPI := gounity.NewFilesystem(unity)
filesystemResp, err = fileAPI.FindFilesystemById(ctx, sourceVolID)
if err != nil {
snapshotApi := gounity.NewSnapshot(unity)
snapResp, err = snapshotApi.FindSnapshotById(ctx, sourceVolID)
if err != nil {
return nil, status.Error(codes.NotFound, utils.GetMessageWithRunID(rid, "Find source filesystem: %s failed with error: %v", sourceVolID, err))
}
isSnapshot = true
filesystemResp, err = s.getFilesystemByResourceID(ctx, snapResp.SnapshotContent.StorageResource.Id, arrayID)
if err != nil {
return nil, err
}
}
}
if protocol == NFS && !isSnapshot {
sourceVolID = filesystemResp.FileContent.StorageResource.Id
}
snap, _ := snapshotAPI.FindSnapshotByName(ctx, snapshotName)
if snap != nil {
if snap.SnapshotContent.StorageResource.Id == sourceVolID || (isSnapshot && snap.SnapshotContent.StorageResource.Id == filesystemResp.FileContent.StorageResource.Id) {
//Subtract AdditionalFilesystemSize for Filesystem snapshots
if protocol == NFS {
snap.SnapshotContent.Size -= AdditionalFilesystemSize
}
log.Infof("Snapshot already exists with same name %s for same storage resource %s", snapshotName, sourceVolID)
return snap, nil
}
return nil, status.Error(codes.AlreadyExists, utils.GetMessageWithRunID(rid, "Snapshot with same name %s already exists for storage resource %s", snapshotName, snap.SnapshotContent.StorageResource.Id))
}
var newSnapshot *types.Snapshot
if isSnapshot {
newSnapshot, err = snapshotAPI.CopySnapshot(ctx, sourceVolID, snapshotName)
if err != nil {
return nil, status.Error(codes.Unknown, utils.GetMessageWithRunID(rid, "Create Snapshot error: %v", err))
}
err = snapshotAPI.ModifySnapshot(ctx, newSnapshot.SnapshotContent.ResourceId, description, retentionDuration)
if err != nil {
log.Infof("Unable to modify description and retention duration in created snapshot %s. Error: %s", newSnapshot.SnapshotContent.ResourceId, err)
}
} else {
if isClone {
newSnapshot, err = snapshotAPI.CreateSnapshotWithFsAccesType(ctx, sourceVolID, snapshotName, description, retentionDuration, gounity.ProtocolAccessType)
} else {
newSnapshot, err = snapshotAPI.CreateSnapshot(ctx, sourceVolID, snapshotName, description, retentionDuration)
}
if err != nil {
return nil, status.Error(codes.Unknown, utils.GetMessageWithRunID(rid, "Create Snapshot error: %v", err))
}
}
newSnapshot, _ = snapshotAPI.FindSnapshotByName(ctx, snapshotName)
if newSnapshot != nil {
//Subtract AdditionalFilesystemSize for Filesystem snapshots{
if protocol == NFS {
newSnapshot.SnapshotContent.Size -= AdditionalFilesystemSize
}
return newSnapshot, nil
}
return nil, status.Error(codes.Unknown, utils.GetMessageWithRunID(rid, "Find Snapshot error after create. %v", err))
}
func (s *service) getHostId(ctx context.Context, arrayId, shortHostname, longHostname string) (*types.Host, error) {
ctx, _, rid := GetRunidLog(ctx)
unity, err := s.getUnityClient(ctx, arrayId)
if err != nil {
return nil, status.Error(codes.NotFound, utils.GetMessageWithRunID(rid, "Unable to get Unity client."))
}
hostAPI := gounity.NewHost(unity)
host, err := hostAPI.FindHostByName(ctx, shortHostname)
if err != nil {
if err != gounity.HostNotFoundError {
return nil, status.Error(codes.NotFound, utils.GetMessageWithRunID(rid, "Find Host Failed %v", err))
}
}
if host != nil {
for _, hostIpPort := range host.HostContent.IpPorts {
if hostIpPort.Address == longHostname {
return host, nil
}
}
}
host, err = hostAPI.FindHostByName(ctx, longHostname)
if err != nil {
return nil, status.Error(codes.NotFound, utils.GetMessageWithRunID(rid, "Find Host Failed %v", err))