This repository has been archived by the owner on Apr 25, 2023. It is now read-only.
/
azure_anf.go
1407 lines (1143 loc) · 41.8 KB
/
azure_anf.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 2019 NetApp, Inc. All Rights Reserved.
package azure
import (
"encoding/json"
"errors"
"fmt"
"net"
"regexp"
"strconv"
"strings"
"time"
"github.com/RoaringBitmap/roaring"
"github.com/google/uuid"
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/azure/sdk"
"github.com/netapp/trident/utils"
)
const (
MinimumVolumeSizeBytes = 1000000000 // 1 GB
MinimumANFVolumeSizeBytes = 107374182400 // 100 GiB
defaultNfsMountOptions = "-o nfsvers=3"
defaultLimitVolumeSize = ""
defaultExportRule = "0.0.0.0/0"
defaultVolumeSizeStr = "107374182400"
// Constants for internal pool attributes
Cookie = "cookie"
Size = "size"
ServiceLevel = "serviceLevel"
ExportRule = "exportRule"
Location = "location"
VirtualNetwork = "virtualNetwork"
Subnet = "subnet"
)
// NFSStorageDriver is for storage provisioning using Azure NetApp Files service in Azure
type NFSStorageDriver struct {
initialized bool
Config drivers.AzureNFSStorageDriverConfig
SDK *sdk.Client
tokenRegexp *regexp.Regexp
pools map[string]*storage.Pool
}
type Telemetry struct {
tridentconfig.Telemetry
Plugin string `json:"plugin"`
}
func (d *NFSStorageDriver) GetConfig() *drivers.AzureNFSStorageDriverConfig {
return &d.Config
}
func (d *NFSStorageDriver) GetSDK() *sdk.Client {
return d.SDK
}
func (d *NFSStorageDriver) getTelemetry() *Telemetry {
return &Telemetry{
Telemetry: tridentconfig.OrchestratorTelemetry,
Plugin: d.Name(),
}
}
// Name returns the name of this driver
func (d *NFSStorageDriver) Name() string {
return drivers.AzureNFSStorageDriverName
}
// defaultBackendName returns the default name of the backend managed by this driver instance
func (d *NFSStorageDriver) defaultBackendName() string {
id := utils.RandomString(6)
if len(d.Config.ClientID) > 5 {
id = d.Config.ClientID[0:5]
}
return fmt.Sprintf("%s_%s", strings.Replace(d.Name(), "-", "", -1), id)
}
// backendName returns the name of the backend managed by this driver instance
func (d *NFSStorageDriver) backendName() string {
if d.Config.BackendName != "" {
return d.Config.BackendName
} else {
// Use the old naming scheme if no name is specified
return d.defaultBackendName()
}
}
// poolName constructs the name of the pool reported by this driver instance
func (d *NFSStorageDriver) poolName(name string) string {
return fmt.Sprintf("%s_%s", d.backendName(), strings.Replace(name, "-", "", -1))
}
// validateName checks that the name of a new volume matches the requirements of a creation token
func (d *NFSStorageDriver) validateName(name string) error {
if !d.tokenRegexp.MatchString(name) {
return fmt.Errorf("volume name '%s' is not allowed; it must be 16-36 characters long, "+
"begin with a character, and contain only characters, digits, and hyphens", name)
}
return nil
}
// Initialize initializes this driver from the provided config
func (d *NFSStorageDriver) Initialize(
context tridentconfig.DriverContext, configJSON string, commonConfig *drivers.CommonStorageDriverConfig,
) error {
if commonConfig.DebugTraceFlags["method"] {
fields := log.Fields{"Method": "Initialize", "Type": "NFSStorageDriver"}
log.WithFields(fields).Debug(">>>> Initialize")
defer log.WithFields(fields).Debug("<<<< Initialize")
}
commonConfig.DriverContext = context
d.tokenRegexp = regexp.MustCompile(`^[a-zA-Z][a-zA-Z0-9-]{15,35}$`)
// Parse the config
config, err := d.initializeAzureConfig(configJSON, commonConfig)
if err != nil {
return fmt.Errorf("error initializing %s driver. %v", d.Name(), err)
}
d.Config = *config
if err = d.populateConfigurationDefaults(&d.Config); err != nil {
return fmt.Errorf("could not populate configuration defaults: %v", err)
}
if err = d.initializeStoragePools(); err != nil {
return fmt.Errorf("could not configure storage pools: %v", err)
}
if d.SDK, err = d.initializeAzureSDKClient(&d.Config); err != nil {
return fmt.Errorf("error initializing %s SDK client. %v", d.Name(), err)
}
if err = d.validate(); err != nil {
return fmt.Errorf("error validating %s driver. %v", d.Name(), err)
}
d.initialized = true
return nil
}
// Initialized returns whether this driver has been initialized (and not terminated)
func (d *NFSStorageDriver) Initialized() bool {
return d.initialized
}
// Terminate stops the driver prior to its being unloaded
func (d *NFSStorageDriver) Terminate() {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{"Method": "Terminate", "Type": "NFSStorageDriver"}
log.WithFields(fields).Debug(">>>> Terminate")
defer log.WithFields(fields).Debug("<<<< Terminate")
}
d.SDK.Terminate()
d.initialized = false
}
// populateConfigurationDefaults fills in default values for configuration settings if not supplied in the config file
func (d *NFSStorageDriver) populateConfigurationDefaults(config *drivers.AzureNFSStorageDriverConfig) error {
if config.DebugTraceFlags["method"] {
fields := log.Fields{"Method": "populateConfigurationDefaults", "Type": "NFSStorageDriver"}
log.WithFields(fields).Debug(">>>> populateConfigurationDefaults")
defer log.WithFields(fields).Debug("<<<< populateConfigurationDefaults")
}
if config.StoragePrefix == nil {
defaultPrefix := drivers.GetDefaultStoragePrefix(config.DriverContext)
defaultPrefix = strings.Replace(defaultPrefix, "_", "-", -1)
config.StoragePrefix = &defaultPrefix
}
if config.Size == "" {
config.Size = defaultVolumeSizeStr
}
if config.NfsMountOptions == "" {
config.NfsMountOptions = defaultNfsMountOptions
}
if config.LimitVolumeSize == "" {
config.LimitVolumeSize = defaultLimitVolumeSize
}
if config.ExportRule == "" {
config.ExportRule = defaultExportRule
}
log.WithFields(log.Fields{
"StoragePrefix": *config.StoragePrefix,
"Size": config.Size,
"ServiceLevel": config.ServiceLevel,
"NfsMountOptions": config.NfsMountOptions,
"LimitVolumeSize": config.LimitVolumeSize,
"ExportRule": config.ExportRule,
}).Debugf("Configuration defaults")
return nil
}
// initializeStoragePools defines the pools reported to Trident, whether physical or virtual.
func (d *NFSStorageDriver) initializeStoragePools() error {
d.pools = make(map[string]*storage.Pool)
if len(d.Config.Storage) == 0 {
log.Debug("No vpools defined, reporting single pool.")
// No vpools defined, so report region/zone as a single pool
pool := storage.NewStoragePool(nil, d.poolName("pool"))
pool.Attributes[sa.BackendType] = sa.NewStringOffer(d.Name())
pool.Attributes[sa.Snapshots] = sa.NewBoolOffer(true)
pool.Attributes[sa.Clones] = sa.NewBoolOffer(true)
pool.Attributes[sa.Encryption] = sa.NewBoolOffer(false)
pool.Attributes[sa.Labels] = sa.NewLabelOffer(d.Config.Labels)
if d.Config.Region != "" {
pool.Attributes[sa.Region] = sa.NewStringOffer(d.Config.Region)
}
if d.Config.Zone != "" {
pool.Attributes[sa.Zone] = sa.NewStringOffer(d.Config.Zone)
}
pool.InternalAttributes[Size] = d.Config.Size
pool.InternalAttributes[ServiceLevel] = d.Config.ServiceLevel
pool.InternalAttributes[ExportRule] = d.Config.ExportRule
pool.InternalAttributes[Location] = d.Config.Location
pool.InternalAttributes[VirtualNetwork] = d.Config.VirtualNetwork
pool.InternalAttributes[Subnet] = d.Config.Subnet
d.pools[pool.Name] = pool
} else {
log.Debug("One or more vpools defined.")
// Report a pool for each virtual pool in the config
for index, vpool := range d.Config.Storage {
region := d.Config.Region
if vpool.Region != "" {
region = vpool.Region
}
zone := d.Config.Zone
if vpool.Zone != "" {
zone = vpool.Zone
}
location := d.Config.Location
if vpool.Location != "" {
location = vpool.Location
}
size := d.Config.Size
if vpool.Size != "" {
size = vpool.Size
}
serviceLevel := d.Config.ServiceLevel
if vpool.ServiceLevel != "" {
serviceLevel = vpool.ServiceLevel
}
exportRule := d.Config.ExportRule
if vpool.ExportRule != "" {
exportRule = vpool.ExportRule
}
vnet := d.Config.VirtualNetwork
if vpool.VirtualNetwork != "" {
vnet = vpool.VirtualNetwork
}
subnet := d.Config.Subnet
if vpool.Subnet != "" {
subnet = vpool.Subnet
}
pool := storage.NewStoragePool(nil, d.poolName(fmt.Sprintf("pool_%d", index)))
pool.Attributes[sa.BackendType] = sa.NewStringOffer(d.Name())
pool.Attributes[sa.Snapshots] = sa.NewBoolOffer(true)
pool.Attributes[sa.Clones] = sa.NewBoolOffer(true)
pool.Attributes[sa.Encryption] = sa.NewBoolOffer(false)
pool.Attributes[sa.Labels] = sa.NewLabelOffer(d.Config.Labels, vpool.Labels)
if region != "" {
pool.Attributes[sa.Region] = sa.NewStringOffer(region)
}
if zone != "" {
pool.Attributes[sa.Zone] = sa.NewStringOffer(zone)
}
pool.InternalAttributes[Size] = size
pool.InternalAttributes[ServiceLevel] = serviceLevel
pool.InternalAttributes[ExportRule] = exportRule
pool.InternalAttributes[Location] = location
pool.InternalAttributes[VirtualNetwork] = vnet
pool.InternalAttributes[Subnet] = subnet
d.pools[pool.Name] = pool
}
}
return nil
}
// initializeAzureConfig parses the Azure config, mixing in the specified common config.
func (d *NFSStorageDriver) initializeAzureConfig(
configJSON string, commonConfig *drivers.CommonStorageDriverConfig,
) (*drivers.AzureNFSStorageDriverConfig, error) {
if commonConfig.DebugTraceFlags["method"] {
fields := log.Fields{"Method": "initializeAzureConfig", "Type": "NFSStorageDriver"}
log.WithFields(fields).Debug(">>>> initializeAzureConfig")
defer log.WithFields(fields).Debug("<<<< initializeAzureConfig")
}
config := &drivers.AzureNFSStorageDriverConfig{}
config.CommonStorageDriverConfig = commonConfig
// decode configJSON into AzureNFSStorageDriverConfig object
if err := json.Unmarshal([]byte(configJSON), &config); err != nil {
return nil, fmt.Errorf("could not decode JSON configuration. %v", err)
}
return config, nil
}
// initializeAzureSDKClient returns an Azure SDK client.
func (d *NFSStorageDriver) initializeAzureSDKClient(
config *drivers.AzureNFSStorageDriverConfig,
) (*sdk.Client, error) {
if config.DebugTraceFlags["method"] {
fields := log.Fields{"Method": "initializeAzureSDKClient", "Type": "NFSStorageDriver"}
log.WithFields(fields).Debug(">>>> initializeAzureSDKClient")
defer log.WithFields(fields).Debug("<<<< initializeAzureSDKClient")
}
client := sdk.NewDriver(sdk.ClientConfig{
SubscriptionID: config.SubscriptionID,
TenantID: config.TenantID,
ClientID: config.ClientID,
ClientSecret: config.ClientSecret,
DebugTraceFlags: config.DebugTraceFlags,
})
if err := client.SDKClient.Authenticate(); err != nil {
return nil, err
}
// Vpools should already be set up by now
if err := client.Init(d.pools); err != nil {
return nil, err
}
return client, nil
}
// validate ensures the driver configuration and execution environment are valid and working
func (d *NFSStorageDriver) validate() error {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{"Method": "validate", "Type": "NFSStorageDriver"}
log.WithFields(fields).Debug(">>>> validate")
defer log.WithFields(fields).Debug("<<<< validate")
}
var err error
// Ensure storage prefix is compatible with cloud service
matched, err := regexp.MatchString(`[^a-zA-Z-]+`, *d.Config.StoragePrefix)
if err != nil {
return fmt.Errorf("could not check storage prefix; %v", err)
} else if matched {
return fmt.Errorf("storage prefix may only contain letters and hyphens")
}
// Validate pool-level attributes
for poolName, pool := range d.pools {
// Validate service level (it is allowed to be blank)
switch pool.InternalAttributes[ServiceLevel] {
case sdk.ServiceLevelStandard, sdk.ServiceLevelPremium, sdk.ServiceLevelUltra, "":
break
default:
return fmt.Errorf("invalid service level in pool %s: %s",
poolName, pool.InternalAttributes[ServiceLevel])
}
// Validate export rules
for _, rule := range strings.Split(pool.InternalAttributes[ExportRule], ",") {
ipAddr := net.ParseIP(rule)
_, netAddr, _ := net.ParseCIDR(rule)
if ipAddr == nil && netAddr == nil {
return fmt.Errorf("invalid address/CIDR for exportRule in pool %s: %s", poolName, rule)
}
}
// Validate default size
if _, err = utils.ConvertSizeToBytes(pool.InternalAttributes[Size]); err != nil {
return fmt.Errorf("invalid value for default volume size in pool %s: %v", poolName, err)
}
}
return nil
}
// Create a volume with the specified options
func (d *NFSStorageDriver) Create(
volConfig *storage.VolumeConfig, storagePool *storage.Pool, volAttributes map[string]sa.Request,
) error {
name := volConfig.InternalName
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "Create",
"Type": "NFSStorageDriver",
"name": name,
"attrs": volAttributes,
}
log.WithFields(fields).Debug(">>>> Create")
defer log.WithFields(fields).Debug("<<<< Create")
}
// Make sure we got a valid name
if err := d.validateName(name); err != nil {
return err
}
// Get the pool since most default values are pool-specific
if storagePool == nil {
return errors.New("pool not specified")
}
pool, ok := d.pools[storagePool.Name]
if !ok {
return fmt.Errorf("pool %s does not exist", storagePool.Name)
}
// If the volume already exists, bail out
volumeExists, _, err := d.SDK.VolumeExistsByCreationToken(name)
if err != nil {
return fmt.Errorf("error checking for existing volume: %v", err)
}
if volumeExists {
return drivers.NewVolumeExistsError(name)
}
// Determine volume size in bytes
requestedSize, err := utils.ConvertSizeToBytes(volConfig.Size)
if err != nil {
return fmt.Errorf("could not convert volume size %s: %v", volConfig.Size, err)
}
sizeBytes, err := strconv.ParseUint(requestedSize, 10, 64)
if err != nil {
return fmt.Errorf("%v is an invalid volume size: %v", volConfig.Size, err)
}
if sizeBytes == 0 {
defaultSize, _ := utils.ConvertSizeToBytes(pool.InternalAttributes[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)
}
// TODO: remove this code once ANF can handle smaller volumes
if sizeBytes < MinimumANFVolumeSizeBytes {
log.WithFields(log.Fields{
"name": name,
"size": sizeBytes,
}).Warningf("Requested size is too small. Setting volume size to the minimum allowable (100 GB).")
sizeBytes = MinimumANFVolumeSizeBytes
volConfig.Size = fmt.Sprintf("%d", sizeBytes)
}
if _, _, err := drivers.CheckVolumeSizeLimits(sizeBytes, d.Config.CommonStorageDriverConfig); err != nil {
return err
}
// Take service level from volume config first (handles Docker case), then from pool
serviceLevel := volConfig.ServiceLevel
if serviceLevel == "" {
serviceLevel = pool.InternalAttributes[ServiceLevel]
}
log.WithFields(log.Fields{
"creationToken": name,
"size": sizeBytes,
"serviceLevel": serviceLevel,
}).Debug("Creating volume.")
apiExportRule := sdk.ExportRule{
AllowedClients: pool.InternalAttributes[ExportRule],
Cifs: false,
Nfsv3: true,
Nfsv4: false,
RuleIndex: 1,
UnixReadOnly: false,
UnixReadWrite: true,
}
exportPolicy := sdk.ExportPolicy{
Rules: []sdk.ExportRule{apiExportRule},
}
createRequest := &sdk.FilesystemCreateRequest{
Name: volConfig.Name,
Location: pool.InternalAttributes[Location],
VirtualNetwork: pool.InternalAttributes[VirtualNetwork],
Subnet: pool.InternalAttributes[Subnet],
CreationToken: name,
ExportPolicy: exportPolicy,
Labels: d.getTelemetryLabels(),
ProtocolTypes: []string{sdk.ProtocolTypeNFSv3},
QuotaInBytes: int64(sizeBytes),
ServiceLevel: serviceLevel,
PoolID: storagePool.Name,
}
// Create the volume
volume, err := d.SDK.CreateVolume(createRequest)
if err != nil {
return err
}
// Wait for creation to complete so that the mount targets are available
return d.waitForVolumeCreate(volume, name)
}
// CreateClone clones an existing volume. If a snapshot is not specified, one is created.
func (d *NFSStorageDriver) CreateClone(volConfig *storage.VolumeConfig) error {
name := volConfig.InternalName
source := volConfig.CloneSourceVolumeInternal
snapshot := volConfig.CloneSourceSnapshot
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "CreateClone",
"Type": "NFSStorageDriver",
"name": name,
"source": source,
"snapshot": snapshot,
}
log.WithFields(fields).Debug(">>>> CreateClone")
defer log.WithFields(fields).Debug("<<<< CreateClone")
}
// ensure new volume doesn't exist, fail if so
// get source volume, fail if nonexistent or if wrong region
// if snapshot specified, read snapshots from source, fail if nonexistent
// if no snap specified, create one, fail if error
// create volume from snapshot
// Make sure we got a valid name
if err := d.validateName(name); err != nil {
return err
}
// If the volume already exists, bail out
volumeExists, _, err := d.SDK.VolumeExistsByCreationToken(name)
if err != nil {
return fmt.Errorf("error checking for existing volume: %v", err)
}
if volumeExists {
return drivers.NewVolumeExistsError(name)
}
// Get the source volume
sourceVolume, err := d.SDK.GetVolumeByCreationToken(source)
if err != nil {
return fmt.Errorf("could not find source volume: %v", err)
}
var sourceSnapshot *sdk.Snapshot
if snapshot != "" {
// Get the source snapshot
sourceSnapshot, err = d.SDK.GetSnapshotForVolume(sourceVolume, snapshot)
if err != nil {
return fmt.Errorf("could not find source snapshot: %v", err)
}
// Ensure snapshot is in a usable state
if sourceSnapshot.ProvisioningState != sdk.StateAvailable {
return fmt.Errorf("source snapshot state is '%s', it must be '%s'",
sourceSnapshot.ProvisioningState, sdk.StateAvailable)
}
} else {
// No source snapshot specified, so create one
snapName := time.Now().UTC().Format(storage.SnapshotNameFormat)
snapshotCreateRequest := &sdk.SnapshotCreateRequest{
FileSystemID: sourceVolume.FileSystemID,
Volume: sourceVolume,
Name: snapName,
Location: sourceVolume.Location,
}
sourceSnapshot, err = d.SDK.CreateSnapshot(snapshotCreateRequest)
if err != nil {
return fmt.Errorf("could not create source snapshot: %v", err)
}
// Wait for snapshot creation to complete
if err = d.SDK.WaitForSnapshotState(sourceSnapshot, sourceVolume, sdk.StateAvailable, []string{sdk.StateError}); err != nil {
return err
}
// Re-fetch the snapshot to populate the properties after create has completed
sourceSnapshot, err = d.SDK.GetSnapshotForVolume(sourceVolume, snapName)
if err != nil {
return fmt.Errorf("could not retrieve newly-created snapshot")
}
}
log.WithFields(log.Fields{
"creationToken": name,
"sourceVolume": sourceVolume.CreationToken,
"sourceSnapshot": sourceSnapshot.Name,
}).Debug("Cloning volume.")
cookie, err := d.SDK.GetCookieByCapacityPoolName(sourceVolume.CapacityPoolName)
if err != nil {
return fmt.Errorf("Couldn't find cookie for volume %v", name)
}
createRequest := &sdk.FilesystemCreateRequest{
Name: volConfig.Name,
Location: sourceVolume.Location,
CapacityPool: sourceVolume.CapacityPoolName, // critical value for clone path
CreationToken: name,
ExportPolicy: sourceVolume.ExportPolicy,
Labels: d.getTelemetryLabels(),
ProtocolTypes: sourceVolume.ProtocolTypes,
QuotaInBytes: sourceVolume.QuotaInBytes,
ServiceLevel: sourceVolume.ServiceLevel,
SnapshotID: sourceSnapshot.SnapshotID,
PoolID: *cookie.StoragePoolName,
Subnet: sourceVolume.Subnet,
}
// Clone the volume
clone, err := d.SDK.CreateVolume(createRequest)
if err != nil {
return err
}
// Wait for creation to complete so that the mount targets are available
return d.waitForVolumeCreate(clone, name)
}
func (d *NFSStorageDriver) Import(volConfig *storage.VolumeConfig, originalName string) error {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "Import",
"Type": "NFSStorageDriver",
"originalName": originalName,
"newName": volConfig.InternalName,
}
log.WithFields(fields).Debug(">>>> Import")
defer log.WithFields(fields).Debug("<<<< Import")
}
// Get the volume
creationToken := originalName
volume, err := d.SDK.GetVolumeByCreationToken(creationToken)
if err != nil {
return fmt.Errorf("could not find volume %s: %v", creationToken, err)
}
// Get the volume size
volConfig.Size = strconv.FormatInt(int64(volume.QuotaInBytes), 10)
// Update the volume labels if Trident will manage its lifecycle
if !volConfig.ImportNotManaged {
if _, err := d.SDK.RelabelVolume(volume, d.updateTelemetryLabels(volume)); err != nil {
log.WithField("originalName", originalName).Errorf("Could not import volume, relabel failed: %v", err)
return fmt.Errorf("could not import volume %s, relabel failed: %v", originalName, err)
}
if err := d.SDK.WaitForVolumeState(volume, sdk.StateAvailable, []string{sdk.StateError}); err != nil {
return fmt.Errorf("could not import volume %s: %v", originalName, err)
}
}
// The ANF creation token cannot be changed, so use it as the internal name
volConfig.InternalName = creationToken
return nil
}
func (d *NFSStorageDriver) Rename(name string, newName string) error {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "Rename",
"Type": "NFSStorageDriver",
"name": name,
"newName": newName,
}
log.WithFields(fields).Debug(">>>> Rename")
defer log.WithFields(fields).Debug("<<<< Rename")
}
// Rename is only needed for the import workflow, and we aren't currently renaming the
// ANF volume when importing, so do nothing here lest we set the volume name incorrectly
// during an import failure cleanup.
return nil
}
// getTelemetryLabels builds the labels that are set on each volume.
func (d *NFSStorageDriver) getTelemetryLabels() []string {
telemetry := map[string]Telemetry{"trident": *d.getTelemetry()}
telemetryLabel := ""
telemetryJSON, err := json.Marshal(telemetry)
if err != nil {
log.Errorf("Failed to marshal telemetry: %+v", telemetryLabel)
} else {
telemetryLabel = strings.Replace(string(telemetryJSON), " ", "", -1)
}
return []string{telemetryLabel}
}
func (d *NFSStorageDriver) isTelemetryLabel(label string) bool {
var telemetry map[string]Telemetry
if err := json.Unmarshal([]byte(label), &telemetry); err != nil {
return false
}
if _, ok := telemetry["trident"]; !ok {
return false
}
return true
}
// getTelemetryLabels builds the labels that are set on each volume.
func (d *NFSStorageDriver) updateTelemetryLabels(volume *sdk.FileSystem) []string {
newLabels := d.getTelemetryLabels()
for _, label := range volume.Labels {
if !d.isTelemetryLabel(label) {
newLabels = append(newLabels, label)
}
}
return newLabels
}
// waitForVolumeCreate waits for volume creation to complete by reaching the Available state. If the
// volume reaches a terminal state (Error), or if the wait operation times out, the volume is deleted.
// This method is used by both Create & CreateClone.
func (d *NFSStorageDriver) waitForVolumeCreate(volume *sdk.FileSystem, volumeName string) error {
if err := d.SDK.WaitForVolumeState(volume, sdk.StateAvailable, []string{sdk.StateError}); err != nil {
// Don't leave a ANF volume laying around in error state
errDelete := d.SDK.DeleteVolume(volume)
if errDelete != nil {
log.WithFields(log.Fields{
"volume": volumeName,
}).Warnf("Volume could not be cleaned up and must be manually deleted: %v.", errDelete)
} else {
// Wait for deletion to complete
errDeleteWait := d.SDK.WaitForVolumeState(volume, sdk.StateDeleted, []string{sdk.StateError})
if errDeleteWait != nil {
log.WithFields(log.Fields{
"volume": volumeName,
}).Warnf("Volume could not be cleaned up and must be manually deleted: %v.", errDeleteWait)
}
}
return err
}
return nil
}
// Destroy deletes a volume.
func (d *NFSStorageDriver) Destroy(name string) error {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "Destroy",
"Type": "NFSStorageDriver",
"name": name,
}
log.WithFields(fields).Debug(">>>> Destroy")
defer log.WithFields(fields).Debug("<<<< Destroy")
}
// If volume doesn't exist, return success
// 'name' is in fact 'creationToken' here.
volumeExists, volume, err := d.SDK.VolumeExistsByCreationToken(name)
if err != nil {
return err
}
if !volumeExists {
log.WithField("volume", name).Warn("Volume already deleted.")
return nil
}
// Delete the volume
if err = d.SDK.DeleteVolume(volume); err != nil {
return err
}
// Wait for deletion to complete
return d.SDK.WaitForVolumeState(volume, sdk.StateDeleted, []string{sdk.StateError})
}
// 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 *NFSStorageDriver) Publish(name string, publishInfo *utils.VolumePublishInfo) error {
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "Publish",
"Type": "NFSStorageDriver",
"name": name,
}
log.WithFields(fields).Debug(">>>> Publish")
defer log.WithFields(fields).Debug("<<<< Publish")
}
// Get the volume
creationToken := name
volume, err := d.SDK.GetVolumeByCreationToken(creationToken)
if err != nil {
return fmt.Errorf("could not find volume %s: %v", creationToken, err)
}
mountTargets, err := d.SDK.GetMountTargetsForVolume(volume)
if err != nil {
return fmt.Errorf("could not read mount targets for volume %s: %v", name, err)
}
if len(*mountTargets) == 0 {
return fmt.Errorf("volume %s has no mount targets", name)
}
// Add fields needed by Attach
publishInfo.NfsPath = "/" + volume.CreationToken
publishInfo.NfsServerIP = (*mountTargets)[0].IPAddress
publishInfo.FilesystemType = "nfs"
publishInfo.MountOptions = d.Config.NfsMountOptions
return nil
}
// GetSnapshot returns a snapshot of a volume, or an error if it does not exist.
func (d *NFSStorageDriver) GetSnapshot(snapConfig *storage.SnapshotConfig) (*storage.Snapshot, error) {
internalSnapName := snapConfig.InternalName
internalVolName := snapConfig.VolumeInternalName
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "GetSnapshot",
"Type": "NFSStorageDriver",
"snapshotName": internalSnapName,
"volumeName": internalVolName,
}
log.WithFields(fields).Debug(">>>> GetSnapshot")
defer log.WithFields(fields).Debug("<<<< GetSnapshot")
}
// Get the volume
creationToken := internalVolName
volume, err := d.SDK.GetVolumeByCreationToken(creationToken)
if err != nil {
return nil, fmt.Errorf("could not find volume %s: %v", creationToken, err)
}
snapshots, err := d.SDK.GetSnapshotsForVolume(volume)
if err != nil {
return nil, err
}
for _, snapshot := range *snapshots {
if snapshot.Name == internalSnapName {
created := snapshot.Created.UTC().Format(storage.SnapshotTimestampFormat)
log.WithFields(log.Fields{
"snapshotName": internalSnapName,
"volumeName": internalVolName,
"created": created,
}).Debug("Found snapshot.")
return &storage.Snapshot{
Config: snapConfig,
Created: created,
SizeBytes: volume.QuotaInBytes,
}, nil
}
}
log.WithFields(log.Fields{
"snapshotName": internalSnapName,
"volumeName": internalVolName,
}).Warning("Snapshot not found.")
return nil, nil
}
// Return the list of snapshots associated with the specified volume
func (d *NFSStorageDriver) GetSnapshots(volConfig *storage.VolumeConfig) ([]*storage.Snapshot, error) {
internalVolName := volConfig.InternalName
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "GetSnapshots",
"Type": "NFSStorageDriver",
"volumeName": internalVolName,
}
log.WithFields(fields).Debug(">>>> GetSnapshots")
defer log.WithFields(fields).Debug("<<<< GetSnapshots")
}
// Get the volume
creationToken := internalVolName
volume, err := d.SDK.GetVolumeByCreationToken(creationToken)
if err != nil {
return nil, fmt.Errorf("could not find volume %s: %v", creationToken, err)
}
snapshots, err := d.SDK.GetSnapshotsForVolume(volume)
if err != nil {
return nil, err
}
snapshotList := make([]*storage.Snapshot, 0)
for _, snapshot := range *snapshots {
// Filter out snapshots in an unavailable state
if snapshot.ProvisioningState != sdk.StateAvailable {
continue
}
snapshotList = append(snapshotList, &storage.Snapshot{
Config: &storage.SnapshotConfig{
Version: tridentconfig.OrchestratorAPIVersion,
Name: snapshot.Name,
InternalName: snapshot.Name,
VolumeName: volConfig.Name,
VolumeInternalName: volConfig.InternalName,
},
Created: snapshot.Created.UTC().Format(storage.SnapshotTimestampFormat),
SizeBytes: volume.QuotaInBytes,
})
}
return snapshotList, nil
}
// CreateSnapshot creates a snapshot for the given volume
func (d *NFSStorageDriver) CreateSnapshot(snapConfig *storage.SnapshotConfig) (*storage.Snapshot, error) {
internalSnapName := snapConfig.InternalName
internalVolName := snapConfig.VolumeInternalName
if d.Config.DebugTraceFlags["method"] {
fields := log.Fields{
"Method": "CreateSnapshot",
"Type": "NFSStorageDriver",
"snapshotName": internalSnapName,
"volumeName": internalVolName,
}
log.WithFields(fields).Debug(">>>> CreateSnapshot")
defer log.WithFields(fields).Debug("<<<< CreateSnapshot")
}