This repository has been archived by the owner on Mar 6, 2023. It is now read-only.
forked from NetApp/trident
/
solidfire_san.go
1315 lines (1134 loc) · 39.4 KB
/
solidfire_san.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 NetApp, Inc. All Rights Reserved.
package solidfire
import (
"encoding/json"
"errors"
"fmt"
"regexp"
"strconv"
"strings"
"github.com/RoaringBitmap/roaring"
log "github.com/sirupsen/logrus"
tridentconfig "github.com/netapp/trident/config"
"github.com/netapp/trident/storage"
sa "github.com/netapp/trident/storage_attribute"
drivers "github.com/netapp/trident/storage_drivers"
"github.com/netapp/trident/storage_drivers/solidfire/api"
"github.com/netapp/trident/utils"
)
const (
sfDefaultVolTypeName = "SolidFire-default"
sfDefaultMinIOPS = 1000
sfDefaultMaxIOPS = 10000
sfMinimumAPIVersion = "8.0"
)
const MinimumVolumeSizeBytes = 1000000000 // 1 GB
// SANStorageDriver is for iSCSI storage provisioning
type SANStorageDriver struct {
initialized bool
Config drivers.SolidfireStorageDriverConfig
Client *api.Client
AccountID int64
AccessGroups []int64
LegacyNamePrefix string
InitiatorIFace string
}
type StorageDriverConfigExternal struct {
*drivers.CommonStorageDriverConfigExternal
TenantName string
EndPoint string
SVIP string
InitiatorIFace string //iface to use of iSCSI initiator
Types *[]api.VolType
AccessGroups []int64
UseCHAP bool
}
type Telemetry struct {
tridentconfig.Telemetry
Plugin string `json:"plugin"`
}
func parseQOS(qosOpt string) (qos api.QoS, err error) {
iops := strings.Split(qosOpt, ",")
if len(iops) != 3 {
return qos, errors.New("qos parameter must have 3 constituents (min/max/burst)")
}
qos.MinIOPS, err = strconv.ParseInt(iops[0], 10, 64)
qos.MaxIOPS, err = strconv.ParseInt(iops[1], 10, 64)
qos.BurstIOPS, err = strconv.ParseInt(iops[2], 10, 64)
return qos, err
}
func parseType(vTypes []api.VolType, typeName string) (qos api.QoS, err error) {
foundType := false
for _, t := range vTypes {
if strings.EqualFold(t.Type, typeName) {
qos = t.QOS
log.Debugf("Received Type opts in Create and set QoS: %+v", qos)
foundType = true
break
}
}
if foundType == false {
log.Errorf("Specified type label not found: %v", typeName)
err = errors.New("specified type not found")
}
return qos, err
}
func (d SANStorageDriver) getTelemetry() *Telemetry {
return &Telemetry{
Telemetry: tridentconfig.OrchestratorTelemetry,
Plugin: d.Name(),
}
}
// Name is for returning the name of this driver
func (d SANStorageDriver) Name() string {
return drivers.SolidfireSANStorageDriverName
}
// Initialize from the provided config
func (d *SANStorageDriver) Initialize(
context tridentconfig.DriverContext, configJSON string, commonConfig *drivers.CommonStorageDriverConfig,
) error {
if commonConfig.DebugTraceFlags["method"] {
fields := log.Fields{"Method": "Initialize", "Type": "SANStorageDriver"}
log.WithFields(fields).Debug(">>>> Initialize")
defer log.WithFields(fields).Debug("<<<< Initialize")
}
commonConfig.DriverContext = context
config := &drivers.SolidfireStorageDriverConfig{}
config.CommonStorageDriverConfig = commonConfig
// Decode supplied configJSON string into SolidfireStorageDriverConfig object
err := json.Unmarshal([]byte(configJSON), &config)
if err != nil {
return fmt.Errorf("could not decode JSON configuration: %v", err)
}
// Apply config defaults
err = d.populateConfigurationDefaults(config)
if err != nil {
return fmt.Errorf("could not populate configuration defaults: %v", err)
}
log.WithFields(log.Fields{
"Version": config.Version,
"StorageDriverName": config.StorageDriverName,
"DisableDelete": config.DisableDelete,
}).Debugf("Parsed into solidfireConfig")
log.Debugf("Decoded to %+v", config)
d.Config = *config
var accountID int64
var defaultBlockSize int64
defaultBlockSize = 512
if config.DefaultBlockSize == 4096 {
defaultBlockSize = 4096
}
log.WithField("defaultBlockSize", defaultBlockSize).Debug("Set default block size.")
// Ensure we use at least the minimum supported version of the API
endpoint, err := d.getEndpoint(config)
if err != nil {
return err
}
// Create a new api.Config object from the JSON config file
svip := config.SVIP
cfg := api.Config{
TenantName: config.TenantName,
EndPoint: endpoint,
SVIP: config.SVIP,
InitiatorIFace: config.InitiatorIFace,
Types: config.Types,
LegacyNamePrefix: config.LegacyNamePrefix,
AccessGroups: config.AccessGroups,
DefaultBlockSize: defaultBlockSize,
DebugTraceFlags: config.DebugTraceFlags,
}
log.WithFields(log.Fields{
"endpoint": endpoint,
"svip": svip,
"cfg": cfg,
}).Debug("Initializing SolidFire API client.")
// Create a new api.Client object for interacting with the SolidFire storage system
client, _ := api.NewFromParameters(endpoint, svip, cfg)
// Lookup the specified account; if not found, dynamically create it
req := api.GetAccountByNameRequest{
Name: config.TenantName,
}
account, err := client.GetAccountByName(&req)
if err != nil {
log.WithFields(log.Fields{
"tenantName": config.TenantName,
"error": err,
}).Debug("Account not found, creating.")
req := api.AddAccountRequest{
Username: config.TenantName,
}
accountID, err = client.AddAccount(&req)
if err != nil {
log.WithFields(log.Fields{
"tenantName": config.TenantName,
"error": err,
}).Error("Failed to initialize SolidFire driver while creating account.")
return err
} else {
log.WithFields(log.Fields{
"tenantName": config.TenantName,
"accountID": account.AccountID,
}).Debug("Created account.")
}
} else {
log.WithFields(log.Fields{
"tenantName": config.TenantName,
"accountID": account.AccountID,
}).Debug("Using existing account.")
accountID = account.AccountID
}
legacyNamePrefix := "netappdvp-"
if config.LegacyNamePrefix != "" {
legacyNamePrefix = config.LegacyNamePrefix
}
iscsiInterface := "default"
if config.InitiatorIFace != "" {
iscsiInterface = config.InitiatorIFace
}
if config.Types != nil {
client.VolumeTypes = config.Types
}
if config.AccessGroups != nil {
client.AccessGroups = config.AccessGroups
}
d.AccountID = accountID
client.AccountID = accountID
d.Client = client
d.InitiatorIFace = iscsiInterface
d.LegacyNamePrefix = legacyNamePrefix
log.WithFields(log.Fields{
"AccountID": accountID,
"InitiatorIFace": iscsiInterface,
}).Debug("SolidFire driver initialized.")
validationErr := d.validate()
if validationErr != nil {
log.Errorf("Problem validating SANStorageDriver error: %+v", validationErr)
return errors.New("error encountered validating SolidFire driver on init")
}
// log cluster node serial numbers asynchronously since the API can take a long time
go d.getNodeSerialNumbers(config.CommonStorageDriverConfig)
d.initialized = true
return nil
}
func (d *SANStorageDriver) Initialized() bool {
return d.initialized
}
func (d *SANStorageDriver) Terminate() {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{"Method": "Terminate", "Type": "SANStorageDriver"}
log.WithFields(fields).Debug(">>>> Terminate")
defer log.WithFields(fields).Debug("<<<< Terminate")
}
d.initialized = false
}
// getEndpoint takes the SVIP from the config file (i.e. "https://admin:password@10.0.0.1/json-rpc/7.0")
// and replaces the version portion (i.e. "7.0") with the new minimum required by Trident ("8.0") *if* it is below
// the minimum. If the config file has a newer version (i.e. "9.0"), the version is honored as is.
func (d *SANStorageDriver) getEndpoint(config *drivers.SolidfireStorageDriverConfig) (string, error) {
var endpointRegex = regexp.MustCompile(`(?P<endpoint>.+/json-rpc/)(?P<version>[\d.]+)$`)
endpointMatch := endpointRegex.FindStringSubmatch(config.EndPoint)
paramsMap := make(map[string]string)
for i, name := range endpointRegex.SubexpNames() {
if i > 0 && i <= len(endpointMatch) {
paramsMap[name] = endpointMatch[i]
}
}
if paramsMap["endpoint"] == "" || paramsMap["version"] == "" {
return "", errors.New("invalid endpoint in config file")
}
endpointVersion, err := utils.ParseGeneric(paramsMap["version"])
if err != nil {
return "", errors.New("invalid endpoint version in config file")
}
minimumVersion := utils.MustParseGeneric(sfMinimumAPIVersion)
if !endpointVersion.AtLeast(minimumVersion) {
log.WithField("minVersion", sfMinimumAPIVersion).Warn("Overriding config file with minimum SF API version.")
return paramsMap["endpoint"] + sfMinimumAPIVersion, nil
} else {
log.WithField("version", paramsMap["version"]).Debug("Using SF API version from config file.")
return paramsMap["endpoint"] + paramsMap["version"], nil
}
}
func (d *SANStorageDriver) getNodeSerialNumbers(c *drivers.CommonStorageDriverConfig) {
c.SerialNumbers = make([]string, 0, 0)
hwInfo, err := d.Client.GetClusterHardwareInfo()
if err != nil {
log.Errorf("Unable to determine controller serial numbers: %+v ", err)
} else {
if nodes, ok := hwInfo.Nodes.(map[string]interface{}); ok {
for _, node := range nodes {
serialNumber, ok := node.(map[string]interface{})["serial"].(string)
if ok && serialNumber != "" {
c.SerialNumbers = append(c.SerialNumbers, serialNumber)
}
}
}
}
log.WithFields(log.Fields{
"serialNumbers": strings.Join(c.SerialNumbers, ","),
}).Info("Controller serial numbers.")
}
// PopulateConfigurationDefaults fills in default values for configuration settings if not supplied in the config file
func (d *SANStorageDriver) populateConfigurationDefaults(config *drivers.SolidfireStorageDriverConfig) error {
if config.DebugTraceFlags["method"] {
fields := log.Fields{"Method": "populateConfigurationDefaults", "Type": "SANStorageDriver"}
log.WithFields(fields).Debug(">>>> populateConfigurationDefaults")
defer log.WithFields(fields).Debug("<<<< populateConfigurationDefaults")
}
// SF prefix is always empty
prefix := ""
config.StoragePrefix = &prefix
// Ensure the default volume size is valid, using a "default default" of 1G if not set
if config.Size == "" {
config.Size = drivers.DefaultVolumeSize
} else {
_, err := utils.ConvertSizeToBytes(config.Size)
if err != nil {
return fmt.Errorf("invalid config value for default volume size: %v", err)
}
}
// Force CHAP for Docker & CSI
switch config.DriverContext {
case tridentconfig.ContextDocker:
if !config.UseCHAP {
log.Info("Enabling CHAP for Docker volumes.")
config.UseCHAP = true
}
case tridentconfig.ContextCSI:
if !config.UseCHAP {
log.Info("Enabling CHAP for CSI volumes.")
config.UseCHAP = true
}
}
log.WithFields(log.Fields{
"StoragePrefix": *config.StoragePrefix,
"UseCHAP": config.UseCHAP,
"Size": config.Size,
}).Debugf("Configuration defaults")
return nil
}
// Validate the driver configuration and execution environment
func (d *SANStorageDriver) validate() error {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{"Method": "validate", "Type": "SANStorageDriver"}
log.WithFields(fields).Debug(">>>> validate")
defer log.WithFields(fields).Debug("<<<< validate")
}
var err error
// We want to verify we have everything we need to run the Docker driver
if d.Config.TenantName == "" {
return errors.New("missing required TenantName in config")
}
if d.Config.EndPoint == "" {
return errors.New("missing required EndPoint in config")
}
if d.Config.SVIP == "" {
return errors.New("missing required SVIP in config")
}
if d.Config.DriverContext == tridentconfig.ContextDocker {
// Validate the environment
isIscsiSupported := utils.ISCSISupported()
if !isIscsiSupported {
log.Error("Host doesn't appear to support iSCSI.")
return errors.New("no iSCSI support on this host")
}
}
if !d.Config.UseCHAP {
// VolumeAccessGroup logic
// If zero AccessGroups are specified it could be that this is an upgrade where we
// just utilize the default 'trident' group automatically. Or, perhaps the deployment
// doesn't need more than one set of 64 initiators, so we'll just use the old way of
// doing it here, and look for/set the default group.
if len(d.Config.AccessGroups) == 0 {
// We're going to do some hacky stuff here and make sure that if this is an upgrade
// that we verify that one of the AccessGroups in the list is the default Trident VAG ID
listVAGReq := &api.ListVolumeAccessGroupsRequest{
StartVAGID: 0,
Limit: 0,
}
vags, vagErr := d.Client.ListVolumeAccessGroups(listVAGReq)
if vagErr != nil {
err = fmt.Errorf("could not list VAGs for backend %s: %s", d.Config.SVIP, vagErr.Error())
return err
}
foundVAG := false
initiators := ""
for _, vag := range vags {
if vag.Name == tridentconfig.DefaultSolidFireVAG {
d.Config.AccessGroups = append(d.Config.AccessGroups, vag.VAGID)
foundVAG = true
for _, initiator := range vag.Initiators {
initiators = initiators + initiator + ","
}
initiators = strings.TrimSuffix(initiators, ",")
log.WithFields(log.Fields{
"group": vag.Name,
"initiators": initiators,
}).Info("No AccessGroup ID's configured. Using the default group with listed initiators.")
break
}
}
if !foundVAG {
// UseCHAP was not specified in the config and no VAG was found.
if tridentconfig.PlatformAtLeast("kubernetes", "v1.7.0") {
// Found a version of Kubernetes that can support CHAP
log.WithFields(log.Fields{
"platform": tridentconfig.OrchestratorTelemetry.Platform,
"platform version": tridentconfig.OrchestratorTelemetry.PlatformVersion,
}).Info("Volume Access Group use not detected. Defaulting to using CHAP.")
d.Config.UseCHAP = true
} else {
err = fmt.Errorf("volume Access Group %v doesn't exist at %v and must be manually "+
"created; please also ensure all relevant hosts are added to the VAG",
tridentconfig.DefaultSolidFireVAG, d.Config.SVIP)
return err
}
}
} else if len(d.Config.AccessGroups) > 4 {
err = fmt.Errorf("the maximum number of allowed Volume Access Groups per config is 4 but your "+
"config has specified %d", len(d.Config.AccessGroups))
return err
} else {
// We only need this in the case that AccessGroups were specified, if it was zero and we
// used the default we already verified it in that step so we're good here.
var missingVags []int64
missingVags, err = d.VerifyVags(d.Config.AccessGroups)
if err != nil {
return err
}
if len(missingVags) != 0 {
return fmt.Errorf("failed to discover the following specified VAG ID's: %+v", missingVags)
}
}
// Deal with upgrades for versions prior to handling multiple VAG ID's
var vIDs []int64
var req api.ListVolumesForAccountRequest
req.AccountID = d.AccountID
volumes, _ := d.Client.ListVolumesForAccount(&req)
for _, v := range volumes {
if v.Status != "deleted" {
vIDs = append(vIDs, v.VolumeID)
}
}
for _, vag := range d.Config.AccessGroups {
addAGErr := d.AddMissingVolumesToVag(vag, vIDs)
if addAGErr != nil {
err = fmt.Errorf("failed to update AccessGroup membership of volume %+v", addAGErr)
return err
}
}
}
fields := log.Fields{
"driver": drivers.SolidfireSANStorageDriverName,
"SVIP": d.Config.SVIP,
"AccessGroups": d.Config.AccessGroups,
"UseCHAP": d.Config.UseCHAP,
}
if d.Config.UseCHAP {
log.WithFields(fields).Debug("Using CHAP, skipped Volume Access Group logic.")
} else {
log.WithFields(fields).Info("Please ensure all relevant hosts are added to one of the specified Volume Access Groups.")
}
return nil
}
// Make SolidFire name
func MakeSolidFireName(name string) string {
return strings.Replace(name, "_", "-", -1)
}
// Create a SolidFire volume
func (d *SANStorageDriver) Create(name string, sizeBytes uint64, opts map[string]string) error {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "Create",
"Type": "SANStorageDriver",
"name": name,
"sizeBytes": sizeBytes,
"opts": opts,
}
log.WithFields(fields).Debug(">>>> Create")
defer log.WithFields(fields).Debug("<<<< Create")
}
var req api.CreateVolumeRequest
var qos api.QoS
telemetry, _ := json.Marshal(d.getTelemetry())
var meta = map[string]string{
"trident": string(telemetry),
"docker-name": name,
}
v, err := d.GetVolume(name)
if err == nil && v.VolumeID != 0 {
log.WithField("volume", name).Warning("Found existing volume.")
return errors.New("volume with requested name already exists")
}
if sizeBytes == 0 {
defaultSize, _ := utils.ConvertSizeToBytes(d.Config.Size)
sizeBytes, _ = strconv.ParseUint(defaultSize, 10, 64)
}
if sizeBytes < MinimumVolumeSizeBytes {
return fmt.Errorf("requested volume size (%d bytes) is too small; the minimum volume size is %d bytes",
sizeBytes, MinimumVolumeSizeBytes)
}
if _, _, checkVolumeSizeLimitsError := drivers.CheckVolumeSizeLimits(sizeBytes, d.Config.CommonStorageDriverConfig); checkVolumeSizeLimitsError != nil {
return checkVolumeSizeLimitsError
}
qosOpt := utils.GetV(opts, "qos", "")
if qosOpt != "" {
qos, err = parseQOS(qosOpt)
if err != nil {
return err
}
}
typeOpt := utils.GetV(opts, "type", "")
if typeOpt != "" {
if qos.MinIOPS != 0 {
log.Warning("QoS values appear to have been set using -o qos, but " +
"type is set as well, overriding with type option.")
}
qos, err = parseType(*d.Client.VolumeTypes, typeOpt)
if err != nil {
return err
}
}
// Use whatever is set in the config as default
if d.Client.DefaultBlockSize == 4096 {
req.Enable512e = false
} else {
req.Enable512e = true
}
// Now check if they specified a block size and use it if they did
blockSizeOpt := utils.GetV(opts, "blocksize", "")
if blockSizeOpt != "" {
if blockSizeOpt == "4096" {
req.Enable512e = false
} else {
req.Enable512e = true
}
}
log.WithFields(log.Fields{
"blocksize": blockSizeOpt,
"enable512e": req.Enable512e,
}).Debug("Parsed blocksize option.")
// Check for a supported file system type
fstype := strings.ToLower(utils.GetV(opts, "fstype|fileSystemType", "ext4"))
switch fstype {
case "xfs", "ext3", "ext4":
log.WithFields(log.Fields{"fileSystemType": fstype, "name": name}).Debug("Filesystem format.")
meta["fstype"] = fstype
default:
return fmt.Errorf("unsupported fileSystemType option: %s", fstype)
}
req.Qos = qos
req.TotalSize = int64(sizeBytes)
req.AccountID = d.AccountID
req.Name = MakeSolidFireName(name)
req.Attributes = meta
_, err = d.Client.CreateVolume(&req)
if err != nil {
return err
}
return nil
}
// Create a volume clone
func (d *SANStorageDriver) CreateClone(name, sourceName, snapshotName string, opts map[string]string) error {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "CreateClone",
"Type": "SANStorageDriver",
"name": name,
"source": sourceName,
"snapshot": snapshotName,
"opts": opts,
}
log.WithFields(fields).Debug(">>>> CreateClone")
defer log.WithFields(fields).Debug("<<<< CreateClone")
}
var err error
var qos api.QoS
doModify := false
qosOpt := utils.GetV(opts, "qos", "")
if qosOpt != "" {
doModify = true
qos, err = parseQOS(qosOpt)
if err != nil {
return err
}
}
typeOpt := utils.GetV(opts, "type", "")
if typeOpt != "" {
doModify = true
if qos.MinIOPS != 0 {
log.Warning("qos values appear to have been set using -o qos, but type is set as well, " +
"overriding with type option")
}
qos, err = parseType(*d.Client.VolumeTypes, typeOpt)
if err != nil {
return err
}
}
var req api.CloneVolumeRequest
telemetry, _ := json.Marshal(d.getTelemetry())
var meta = map[string]string{
"trident": string(telemetry),
"docker-name": name,
}
// Check to see if the clone already exists
checkVolume, err := d.GetVolume(name)
if err == nil && checkVolume.VolumeID != 0 {
log.Warningf("Found existing volume %s, aborting clone operation.", name)
return errors.New("volume with requested name already exists")
}
// Get the volume ID for the source volume
sourceVolume, err := d.GetVolume(sourceName)
if err != nil || sourceVolume.VolumeID == 0 {
log.Errorf("Unable to locate requested source volume: %v", err)
return errors.New("error performing clone operation, source volume not found")
}
// If a snapshot was specified, use that
if snapshotName != "" {
s, err := d.Client.GetSnapshot(0, sourceVolume.VolumeID, snapshotName)
if err != nil || s.SnapshotID == 0 {
log.Errorf("Unable to locate requested source snapshot: %v", err)
return errors.New("error performing clone operation, source snapshot not found")
}
req.SnapshotID = s.SnapshotID
}
// Create the clone of the source volume with the name specified
req.VolumeID = sourceVolume.VolumeID
req.Name = MakeSolidFireName(name)
req.Attributes = meta
cloneVolume, err := d.Client.CloneVolume(&req)
if err != nil {
log.Errorf("Failed to create clone: %v", err)
return errors.New("error performing clone operation")
}
// If any QoS settings were specified, modify the clone
var modifyReq api.ModifyVolumeRequest
modifyReq.VolumeID = cloneVolume.VolumeID
if doModify {
modifyReq.Qos = qos
err = d.Client.ModifyVolume(&modifyReq)
if err != nil {
log.Errorf("Failed to update QoS on clone: %v", err)
return errors.New("error performing clone operation")
}
}
return nil
}
// Destroy the requested docker volume
func (d *SANStorageDriver) Destroy(name string) error {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "Destroy",
"Type": "SANStorageDriver",
"name": name,
}
log.WithFields(fields).Debug(">>>> Destroy")
defer log.WithFields(fields).Debug("<<<< Destroy")
}
v, err := d.GetVolume(name)
if err != nil && err.Error() != "volume not found" {
log.Errorf("Unable to locate volume for delete operation: %v", err)
return err
} else if err != nil {
// Volume wasn't found. No action needs to be taken.
log.Warnf("Volume %s doesn't exist.", name)
return nil
}
if d.Config.DriverContext == tridentconfig.ContextDocker {
// Inform the host about the device removal
utils.PrepareDeviceForRemoval(0, v.Iqn)
// Logout from the session
err = d.Client.DetachVolume(v)
if err != nil {
log.Warningf("Unable to detach volume, deleting anyway: %v", err)
}
}
err = d.Client.DeleteVolume(v.VolumeID)
if err != nil {
log.Errorf("Error during delete operation: %v", err)
return err
}
return nil
}
// Publish the volume to the host specified in publishInfo. This method may or may not be running on the host
// where the volume will be mounted, so it should limit itself to updating access rules, initiator groups, etc.
// that require some host identity (but not locality) as well as storage controller API access.
func (d *SANStorageDriver) Publish(name string, publishInfo *utils.VolumePublishInfo) error {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "Publish",
"Type": "SANStorageDriver",
"name": name,
}
log.WithFields(fields).Debug(">>>> Publish")
defer log.WithFields(fields).Debug("<<<< Publish")
}
v, err := d.GetVolume(name)
if err != nil {
log.Errorf("Unable to locate volume for mount operation: %+v", err)
return errors.New("volume not found")
}
// Get the fstype
attrs, _ := v.Attributes.(map[string]interface{})
fstype := "ext4"
if str, ok := attrs["fstype"].(string); ok {
fstype = str
}
// Get the account, which contains the iSCSI login credentials
var req api.GetAccountByIDRequest
req.AccountID = v.AccountID
account, err := d.Client.GetAccountByID(&req)
if err != nil {
log.Errorf("Failed to get account %v: %+v ", v.AccountID, err)
return errors.New("volume attach failure")
}
// Add fields needed by Attach
publishInfo.IscsiLunNumber = 0
publishInfo.IscsiTargetPortal = d.Config.SVIP
publishInfo.IscsiTargetIQN = v.Iqn
publishInfo.IscsiUsername = account.Username
publishInfo.IscsiInitiatorSecret = account.InitiatorSecret
publishInfo.IscsiInterface = d.InitiatorIFace
publishInfo.FilesystemType = fstype
publishInfo.UseCHAP = true
publishInfo.SharedTarget = false
return nil
}
// SnapshotList returns the list of snapshots associated with the named volume
func (d *SANStorageDriver) SnapshotList(name string) ([]storage.Snapshot, error) {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "SnapshotList",
"Type": "SANStorageDriver",
"name": name,
}
log.WithFields(fields).Debug(">>>> SnapshotList")
defer log.WithFields(fields).Debug("<<<< SnapshotList")
}
v, err := d.GetVolume(name)
if err != nil {
log.Errorf("Unable to locate parent volume in snapshot list: %+v", err)
return nil, errors.New("volume not found")
}
var req api.ListSnapshotsRequest
req.VolumeID = v.VolumeID
s, err := d.Client.ListSnapshots(&req)
if err != nil {
log.Errorf("Unable to locate snapshot: %+v", err)
return nil, errors.New("snapshot not found")
}
log.Debugf("Returned %d snapshots", len(s))
var snapshots []storage.Snapshot
for _, snap := range s {
log.Debugf("Snapshot name: %s, date: %s", snap.Name, snap.CreateTime)
snapshots = append(snapshots, storage.Snapshot{Name: snap.Name, Created: snap.CreateTime})
}
return snapshots, nil
}
// Get tests for the existence of a volume
func (d *SANStorageDriver) Get(name string) error {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{"Method": "Get", "Type": "SANStorageDriver"}
log.WithFields(fields).Debug(">>>> Get")
defer log.WithFields(fields).Debug("<<<< Get")
}
_, err := d.GetVolume(name)
return err
}
// getVolumes returns all volumes for the configured tenant. The
// keys are the volume names as reported to Docker.
func (d *SANStorageDriver) getVolumes() (map[string]api.Volume, error) {
var req api.ListVolumesForAccountRequest
req.AccountID = d.AccountID
volumes, err := d.Client.ListVolumesForAccount(&req)
if err != nil {
return nil, err
}
volMap := make(map[string]api.Volume)
for _, volume := range volumes {
if volume.Status != "deleted" {
attrs, _ := volume.Attributes.(map[string]interface{})
dName := strings.Replace(volume.Name, d.LegacyNamePrefix, "", -1)
if str, ok := attrs["docker-name"].(string); ok {
dName = strings.Replace(str, d.LegacyNamePrefix, "", -1)
}
volMap[dName] = volume
}
}
return volMap, nil
}
func (d *SANStorageDriver) GetVolume(name string) (api.Volume, error) {
var vols []api.Volume
var req api.ListVolumesForAccountRequest
// I know, I know... just use V8 of the API and let the Cluster filter on
// things like Name; trouble is we completely screwed up Name usage so we
// can't trust it. We now have a few possibilities including Name,
// Name-With-Prefix and Attributes. It could be any of the 3. At some
// point let's fix that and just use something efficient like Name and be
// done with it. Otherwise, we just get all for the account and iterate
// which isn't terrible.
req.AccountID = d.AccountID
volumes, err := d.Client.ListVolumesForAccount(&req)
if err != nil {
log.Errorf("Error encountered requesting volumes in SolidFire:getVolume: %+v", err)
return api.Volume{}, errors.New("device reported API error")
}
legacyName := MakeSolidFireName(d.LegacyNamePrefix + name)
baseSFName := MakeSolidFireName(name)
for _, v := range volumes {
attrs, _ := v.Attributes.(map[string]interface{})
// We prefer attributes, so check that first, then pick up legacy
// volumes using Volume Name
if attrs["docker-name"] == name && v.Status == "active" {
log.Debugf("Found volume by attributes: %+v", v)
vols = append(vols, v)
} else if (v.Name == legacyName || v.Name == baseSFName) && v.Status == "active" {
log.Warningf("Found volume by name using deprecated Volume.Name mapping: %+v", v)
vols = append(vols, v)
}
}
if len(vols) == 0 {
return api.Volume{}, errors.New("volume not found")
}
return vols[0], nil
}
// GetStorageBackendSpecs retrieves storage backend capabilities
func (d *SANStorageDriver) GetStorageBackendSpecs(backend *storage.Backend) error {
if d.Config.BackendName == "" {
// Use the old naming scheme if no name is specified
backend.Name = "solidfire_" + strings.Split(d.Config.SVIP, ":")[0]
} else {
backend.Name = d.Config.BackendName
}
volTypes := *d.Client.VolumeTypes
if len(volTypes) == 0 {
volTypes = []api.VolType{
{
Type: sfDefaultVolTypeName,
QOS: api.QoS{
MinIOPS: sfDefaultMinIOPS,
MaxIOPS: sfDefaultMaxIOPS,
// Leave burst IOPS blank, since we don't do anything with
// it for storage classes.
},
},
}
}
for _, volType := range volTypes {
pool := storage.NewStoragePool(backend, volType.Type)
pool.Attributes[sa.Media] = sa.NewStringOffer(sa.SSD)
pool.Attributes[sa.IOPS] = sa.NewIntOffer(int(volType.QOS.MinIOPS),
int(volType.QOS.MaxIOPS))
pool.Attributes[sa.Snapshots] = sa.NewBoolOffer(true)
pool.Attributes[sa.Clones] = sa.NewBoolOffer(true)
pool.Attributes[sa.Encryption] = sa.NewBoolOffer(false)
pool.Attributes[sa.ProvisioningType] = sa.NewStringOffer("thin")
pool.Attributes[sa.BackendType] = sa.NewStringOffer(d.Name())
backend.AddStoragePool(pool)
log.WithFields(log.Fields{
"attributes": fmt.Sprintf("%+v", pool.Attributes),
"pool": pool.Name,
"backend": backend.Name,
}).Debug("Added pool for SolidFire backend.")
}
return nil
}
func (d *SANStorageDriver) GetInternalVolumeName(name string) string {
if tridentconfig.UsingPassthroughStore {
return strings.Replace(name, "_", "-", -1)
} else {
internal := drivers.GetCommonInternalVolumeName(d.Config.CommonStorageDriverConfig, name)
internal = strings.Replace(internal, "_", "-", -1)
internal = strings.Replace(internal, ".", "-", -1)
internal = strings.Replace(internal, "--", "-", -1) // Remove any double hyphens
return internal
}
}
func (d *SANStorageDriver) CreatePrepare(volConfig *storage.VolumeConfig) bool {
// 1. Sanitize the volume name
volConfig.InternalName = d.GetInternalVolumeName(volConfig.Name)
if volConfig.CloneSourceVolume != "" {
volConfig.CloneSourceVolumeInternal =
d.GetInternalVolumeName(volConfig.CloneSourceVolume)
}
return true
}
func (d *SANStorageDriver) CreateFollowup(volConfig *storage.VolumeConfig) error {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "CreateFollowup",
"Type": "SANStorageDriver",
"name": volConfig.Name,
"internalName": volConfig.InternalName,
}
log.WithFields(fields).Debug(">>>> CreateFollowup")
defer log.WithFields(fields).Debug("<<<< CreateFollowup")
}