-
Notifications
You must be signed in to change notification settings - Fork 219
/
azure_anf.go
2593 lines (2199 loc) · 90.9 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 2023 NetApp, Inc. All Rights Reserved.
package azure
import (
"context"
"encoding/json"
"fmt"
"math"
"net"
"os"
"reflect"
"regexp"
"strconv"
"strings"
"time"
"github.com/RoaringBitmap/roaring"
"github.com/google/uuid"
"go.uber.org/multierr"
"sigs.k8s.io/cloud-provider-azure/pkg/azclient"
"github.com/netapp/trident/acp"
tridentconfig "github.com/netapp/trident/config"
. "github.com/netapp/trident/logging"
"github.com/netapp/trident/storage"
sa "github.com/netapp/trident/storage_attribute"
sc "github.com/netapp/trident/storage_class"
drivers "github.com/netapp/trident/storage_drivers"
"github.com/netapp/trident/storage_drivers/azure/api"
"github.com/netapp/trident/utils"
"github.com/netapp/trident/utils/errors"
"github.com/netapp/trident/utils/models"
)
const (
MinimumVolumeSizeBytes = uint64(1000000000) // 1 GB
MinimumANFVolumeSizeBytes = uint64(107374182400) // 100 GiB
defaultUnixPermissions = "" // TODO (cknight): change to "0777" when whitelisted permissions feature reaches GA
defaultNfsMountOptions = "nfsvers=3"
defaultKerberosNfsMountOptions = "nfsvers=4.1"
defaultSnapshotDir = ""
defaultLimitVolumeSize = ""
defaultExportRule = "0.0.0.0/0"
defaultVolumeSizeStr = "107374182400"
defaultNetworkFeatures = "" // Leave empty, some regions may never support this
// Constants for internal pool attributes
Size = "size"
UnixPermissions = "unixPermissions"
ServiceLevel = "serviceLevel"
SnapshotDir = "snapshotDir"
ExportRule = "exportRule"
VirtualNetwork = "virtualNetwork"
NetworkFeatures = "networkFeatures"
Subnet = "subnet"
ResourceGroups = "resourceGroups"
NetappAccounts = "netappAccounts"
CapacityPools = "capacityPools"
FilePoolVolumes = "filePoolVolumes"
Kerberos = "kerberos"
nfsVersion3 = "3"
nfsVersion4 = "4"
nfsVersion41 = "4.1"
)
var (
supportedNFSVersions = []string{nfsVersion3, nfsVersion4, nfsVersion41}
storagePrefixRegex = regexp.MustCompile(`^$|^[a-zA-Z][a-zA-Z-]*$`)
volumeNameRegex = regexp.MustCompile(`^[a-zA-Z][a-zA-Z\d-_]{0,63}$`)
volumeCreationTokenRegex = regexp.MustCompile(`^[a-zA-Z][a-zA-Z\d-]{0,79}$`)
csiRegex = regexp.MustCompile(`^pvc-[\da-fA-F]{8}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{4}-[\da-fA-F]{12}$`)
)
// NASStorageDriver is for storage provisioning using the Azure NetApp Files service.
type NASStorageDriver struct {
initialized bool
Config drivers.AzureNASStorageDriverConfig
telemetry *Telemetry
SDK api.Azure
pools map[string]storage.Pool
volumeCreateTimeout time.Duration
}
type Telemetry struct {
tridentconfig.Telemetry
Plugin string `json:"plugin"`
}
// Name returns the name of this driver.
func (d *NASStorageDriver) Name() string {
return tridentconfig.AzureNASStorageDriverName
}
// GetConfig returns the config of this driver.
func (d *NASStorageDriver) GetConfig() drivers.DriverConfig {
return &d.Config
}
// defaultBackendName returns the default name of the backend managed by this driver instance.
func (d *NASStorageDriver) 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 *NASStorageDriver) 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 *NASStorageDriver) poolName(name string) string {
return fmt.Sprintf("%s_%s", d.BackendName(), strings.Replace(name, "-", "", -1))
}
// validateVolumeName checks that the name of a new volume matches the requirements of an ANF volume name.
func (d *NASStorageDriver) validateVolumeName(name string) error {
if !volumeNameRegex.MatchString(name) {
return fmt.Errorf("volume name '%s' is not allowed; it must be 1-64 characters long, "+
"begin with a letter, and contain only letters, digits, hyphens, and underscores", name)
}
return nil
}
// validateCreationToken checks that the creation token of a new volume matches the requirements of a creation token.
func (d *NASStorageDriver) validateCreationToken(name string) error {
if !volumeCreationTokenRegex.MatchString(name) {
return fmt.Errorf("volume internal name '%s' is not allowed; it must be 1-80 characters long, "+
"begin with a letter, and contain only letters, digits, and hyphens", name)
}
return nil
}
// defaultCreateTimeout sets the driver timeout for volume create/delete operations. Docker gets more time, since
// it doesn't have a mechanism to retry.
func (d *NASStorageDriver) defaultCreateTimeout() time.Duration {
switch d.Config.DriverContext {
case tridentconfig.ContextDocker:
return tridentconfig.DockerCreateTimeout
default:
return api.VolumeCreateTimeout
}
}
// defaultTimeout controls the driver timeout for most workflows.
func (d *NASStorageDriver) defaultTimeout() time.Duration {
switch d.Config.DriverContext {
case tridentconfig.ContextDocker:
return tridentconfig.DockerDefaultTimeout
default:
return api.DefaultTimeout
}
}
// Initialize initializes this driver from the provided config.
func (d *NASStorageDriver) Initialize(
ctx context.Context, context tridentconfig.DriverContext, configJSON string,
commonConfig *drivers.CommonStorageDriverConfig, backendSecret map[string]string, backendUUID string,
) error {
fields := LogFields{"Method": "Initialize", "Type": "NASStorageDriver"}
Logd(ctx, commonConfig.StorageDriverName, commonConfig.DebugTraceFlags["method"]).WithFields(fields).
Trace(">>>> Initialize")
defer Logd(ctx, commonConfig.StorageDriverName, commonConfig.DebugTraceFlags["method"]).WithFields(fields).
Trace("<<<< Initialize")
commonConfig.DriverContext = context
// Initialize the driver's CommonStorageDriverConfig
d.Config.CommonStorageDriverConfig = commonConfig
// Parse the config
config, err := d.initializeAzureConfig(ctx, configJSON, commonConfig, backendSecret)
if err != nil {
return fmt.Errorf("error initializing %s driver; %v", d.Name(), err)
}
d.Config = *config
d.populateConfigurationDefaults(ctx, &d.Config)
d.initializeStoragePools(ctx)
d.initializeTelemetry(ctx, backendUUID)
if err = d.initializeAzureSDKClient(ctx, &d.Config); err != nil {
return fmt.Errorf("error initializing %s SDK client. %v", d.Name(), err)
}
if err = d.validate(ctx); err != nil {
return fmt.Errorf("error validating %s driver. %v", d.Name(), err)
}
// Identify non-overlapping storage backend pools on the driver backend.
pools, err := drivers.EncodeStorageBackendPools(ctx, commonConfig, d.getStorageBackendPools(ctx))
if err != nil {
return fmt.Errorf("failed to encode storage backend pools: %v", err)
}
d.Config.BackendPools = pools
volumeCreateTimeout := d.defaultCreateTimeout()
if config.VolumeCreateTimeout != "" {
if i, parseErr := strconv.ParseUint(d.Config.VolumeCreateTimeout, 10, 64); parseErr != nil {
Logc(ctx).WithField("interval", d.Config.VolumeCreateTimeout).WithError(parseErr).Error(
"Invalid volume create timeout period.")
return parseErr
} else {
volumeCreateTimeout = time.Duration(i) * time.Second
}
}
d.volumeCreateTimeout = volumeCreateTimeout
Logc(ctx).WithFields(LogFields{
"StoragePrefix": *config.StoragePrefix,
"Size": config.Size,
"ServiceLevel": config.ServiceLevel,
"NfsMountOptions": config.NfsMountOptions,
"LimitVolumeSize": config.LimitVolumeSize,
"ExportRule": config.ExportRule,
"VolumeCreateTimeoutSeconds": config.VolumeCreateTimeout,
})
d.initialized = true
return nil
}
// Initialized returns whether this driver has been initialized (and not terminated).
func (d *NASStorageDriver) Initialized() bool {
return d.initialized
}
// Terminate stops the driver prior to its being unloaded.
func (d *NASStorageDriver) Terminate(ctx context.Context, _ string) {
fields := LogFields{"Method": "Terminate", "Type": "NASStorageDriver"}
Logd(ctx, d.Name(), d.Config.DebugTraceFlags["method"]).WithFields(fields).Trace(">>>> Terminate")
defer Logd(ctx, d.Name(), d.Config.DebugTraceFlags["method"]).WithFields(fields).Trace("<<<< Terminate")
d.initialized = false
}
// populateConfigurationDefaults fills in default values for configuration settings if not supplied in the config.
func (d *NASStorageDriver) populateConfigurationDefaults(
ctx context.Context, config *drivers.AzureNASStorageDriverConfig,
) {
fields := LogFields{"Method": "populateConfigurationDefaults", "Type": "NASStorageDriver"}
Logd(ctx, config.StorageDriverName,
config.DebugTraceFlags["method"]).WithFields(fields).Trace(">>>> populateConfigurationDefaults")
defer Logd(ctx, config.StorageDriverName,
config.DebugTraceFlags["method"]).WithFields(fields).Trace("<<<< 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.UnixPermissions == "" {
config.UnixPermissions = defaultUnixPermissions
}
if config.NfsMountOptions == "" {
if config.Kerberos != "" {
config.NfsMountOptions = defaultKerberosNfsMountOptions
} else {
config.NfsMountOptions = defaultNfsMountOptions
}
}
if config.SnapshotDir != "" {
// Set the snapshotDir provided in the config
snapDirFormatted, err := utils.GetFormattedBool(config.SnapshotDir)
if err != nil {
Logc(ctx).WithError(err).Errorf("Invalid boolean value for snapshotDir: %v.", config.SnapshotDir)
}
config.SnapshotDir = snapDirFormatted
}
if config.LimitVolumeSize == "" {
config.LimitVolumeSize = defaultLimitVolumeSize
}
if config.ExportRule == "" {
config.ExportRule = defaultExportRule
}
if config.NetworkFeatures == "" {
config.NetworkFeatures = defaultNetworkFeatures
}
if config.NASType == "" {
config.NASType = sa.NFS
}
Logc(ctx).WithFields(LogFields{
"StoragePrefix": *config.StoragePrefix,
"Size": config.Size,
"UnixPermissions": config.UnixPermissions,
"ServiceLevel": config.ServiceLevel,
"NfsMountOptions": config.NfsMountOptions,
"SnapshotDir": config.SnapshotDir,
"LimitVolumeSize": config.LimitVolumeSize,
"ExportRule": config.ExportRule,
}).Debugf("Configuration defaults")
return
}
// initializeStoragePools defines the pools reported to Trident, whether physical or virtual.
func (d *NASStorageDriver) initializeStoragePools(ctx context.Context) {
d.pools = make(map[string]storage.Pool)
// If snapshotDir is provided, ensure it is lower case
if d.Config.SnapshotDir != "" {
snapDirFormatted, err := utils.GetFormattedBool(d.Config.SnapshotDir)
if err != nil {
Logc(ctx).WithError(err).Errorf("Invalid boolean value for snapshotDir: %v.", d.Config.SnapshotDir)
}
d.Config.SnapshotDir = snapDirFormatted
}
if len(d.Config.Storage) == 0 {
Logc(ctx).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.Replication] = sa.NewBoolOffer(false)
pool.Attributes()[sa.Labels] = sa.NewLabelOffer(d.Config.Labels)
pool.Attributes()[sa.NASType] = sa.NewStringOffer(d.Config.NASType)
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()[UnixPermissions] = d.Config.UnixPermissions
pool.InternalAttributes()[ServiceLevel] = utils.Title(d.Config.ServiceLevel)
pool.InternalAttributes()[SnapshotDir] = d.Config.SnapshotDir
pool.InternalAttributes()[ExportRule] = d.Config.ExportRule
pool.InternalAttributes()[VirtualNetwork] = d.Config.VirtualNetwork
pool.InternalAttributes()[NetworkFeatures] = d.Config.NetworkFeatures
pool.InternalAttributes()[Subnet] = d.Config.Subnet
pool.InternalAttributes()[ResourceGroups] = strings.Join(d.Config.ResourceGroups, ",")
pool.InternalAttributes()[NetappAccounts] = strings.Join(d.Config.NetappAccounts, ",")
pool.InternalAttributes()[CapacityPools] = strings.Join(d.Config.CapacityPools, ",")
pool.InternalAttributes()[Kerberos] = d.Config.Kerberos
pool.SetSupportedTopologies(d.Config.SupportedTopologies)
d.pools[pool.Name()] = pool
} else {
Logc(ctx).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
}
size := d.Config.Size
if vpool.Size != "" {
size = vpool.Size
}
unixPermissions := d.Config.UnixPermissions
if vpool.UnixPermissions != "" {
unixPermissions = vpool.UnixPermissions
}
supportedTopologies := d.Config.SupportedTopologies
if vpool.SupportedTopologies != nil {
supportedTopologies = vpool.SupportedTopologies
}
resourceGroups := d.Config.ResourceGroups
if vpool.ResourceGroups != nil {
resourceGroups = vpool.ResourceGroups
}
netappAccounts := d.Config.NetappAccounts
if vpool.NetappAccounts != nil {
netappAccounts = vpool.NetappAccounts
}
capacityPools := d.Config.CapacityPools
if vpool.CapacityPools != nil {
capacityPools = vpool.CapacityPools
}
serviceLevel := d.Config.ServiceLevel
if vpool.ServiceLevel != "" {
serviceLevel = vpool.ServiceLevel
}
snapshotDir := d.Config.SnapshotDir
if vpool.SnapshotDir != "" {
snapDirFormatted, err := utils.GetFormattedBool(vpool.SnapshotDir)
if err != nil {
Logc(ctx).WithError(err).Errorf("Invalid boolean value for vpool's snapshotDir: %v.",
vpool.SnapshotDir)
}
snapshotDir = snapDirFormatted
}
exportRule := d.Config.ExportRule
if vpool.ExportRule != "" {
exportRule = vpool.ExportRule
}
vnet := d.Config.VirtualNetwork
if vpool.VirtualNetwork != "" {
vnet = vpool.VirtualNetwork
}
networkFeatures := d.Config.NetworkFeatures
if vpool.NetworkFeatures != "" {
networkFeatures = vpool.NetworkFeatures
}
subnet := d.Config.Subnet
if vpool.Subnet != "" {
subnet = vpool.Subnet
}
kerberos := d.Config.Kerberos
if vpool.Kerberos != "" {
kerberos = vpool.Kerberos
}
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.Replication] = sa.NewBoolOffer(false)
pool.Attributes()[sa.Labels] = sa.NewLabelOffer(d.Config.Labels, vpool.Labels)
nasType := d.Config.NASType
if vpool.NASType != "" {
nasType = vpool.NASType
}
pool.Attributes()[sa.NASType] = sa.NewStringOffer(nasType)
if region != "" {
pool.Attributes()[sa.Region] = sa.NewStringOffer(region)
}
if zone != "" {
pool.Attributes()[sa.Zone] = sa.NewStringOffer(zone)
}
pool.InternalAttributes()[Size] = size
pool.InternalAttributes()[UnixPermissions] = unixPermissions
pool.InternalAttributes()[ServiceLevel] = utils.Title(serviceLevel)
pool.InternalAttributes()[SnapshotDir] = snapshotDir
pool.InternalAttributes()[ExportRule] = exportRule
pool.InternalAttributes()[VirtualNetwork] = vnet
pool.InternalAttributes()[NetworkFeatures] = networkFeatures
pool.InternalAttributes()[Subnet] = subnet
pool.InternalAttributes()[ResourceGroups] = strings.Join(resourceGroups, ",")
pool.InternalAttributes()[NetappAccounts] = strings.Join(netappAccounts, ",")
pool.InternalAttributes()[CapacityPools] = strings.Join(capacityPools, ",")
pool.InternalAttributes()[Kerberos] = kerberos
pool.SetSupportedTopologies(supportedTopologies)
d.pools[pool.Name()] = pool
}
}
return
}
// initializeTelemetry assembles all the telemetry data to be used as volume labels.
func (d *NASStorageDriver) initializeTelemetry(_ context.Context, backendUUID string) {
telemetry := tridentconfig.OrchestratorTelemetry
telemetry.TridentBackendUUID = backendUUID
d.telemetry = &Telemetry{
Telemetry: telemetry,
Plugin: d.Name(),
}
}
// initializeAzureConfig parses the Azure config, mixing in the specified common config.
func (d *NASStorageDriver) initializeAzureConfig(
ctx context.Context, configJSON string, commonConfig *drivers.CommonStorageDriverConfig,
backendSecret map[string]string,
) (*drivers.AzureNASStorageDriverConfig, error) {
fields := LogFields{"Method": "initializeAzureConfig", "Type": "NASStorageDriver"}
Logd(ctx, commonConfig.StorageDriverName,
commonConfig.DebugTraceFlags["method"]).WithFields(fields).Trace(">>>> initializeAzureConfig")
defer Logd(ctx, commonConfig.StorageDriverName,
commonConfig.DebugTraceFlags["method"]).WithFields(fields).Trace("<<<< initializeAzureConfig")
config := &drivers.AzureNASStorageDriverConfig{}
config.CommonStorageDriverConfig = commonConfig
// decode configJSON into AzureNASStorageDriverConfig object
if err := json.Unmarshal([]byte(configJSON), &config); err != nil {
return nil, fmt.Errorf("could not decode JSON configuration; %v", err)
}
// Inject secret if not empty
if len(backendSecret) != 0 {
err := config.InjectSecrets(backendSecret)
if err != nil {
return nil, fmt.Errorf("could not inject backend secret; %v", err)
}
}
return config, nil
}
// initializeAzureSDKClient creates and initializes an Azure SDK client.
func (d *NASStorageDriver) initializeAzureSDKClient(
ctx context.Context, config *drivers.AzureNASStorageDriverConfig,
) error {
fields := LogFields{"Method": "initializeAzureSDKClient", "Type": "NASStorageDriver"}
Logd(ctx, config.StorageDriverName,
config.DebugTraceFlags["method"]).WithFields(fields).Trace(">>>> initializeAzureSDKClient")
defer Logd(ctx, config.StorageDriverName,
config.DebugTraceFlags["method"]).WithFields(fields).Trace("<<<< initializeAzureSDKClient")
sdkTimeout := api.DefaultSDKTimeout
if config.SDKTimeout != "" {
if i, parseErr := strconv.ParseUint(d.Config.SDKTimeout, 10, 64); parseErr != nil {
Logc(ctx).WithField("interval", d.Config.SDKTimeout).WithError(parseErr).Error(
"Invalid value for SDK timeout.")
return parseErr
} else {
sdkTimeout = time.Duration(i) * time.Second
}
}
maxCacheAge := api.DefaultMaxCacheAge
if config.MaxCacheAge != "" {
if i, parseErr := strconv.ParseUint(d.Config.MaxCacheAge, 10, 64); parseErr != nil {
Logc(ctx).WithField("interval", d.Config.MaxCacheAge).WithError(parseErr).Error(
"Invalid value for max cache age.")
return parseErr
} else {
maxCacheAge = time.Duration(i) * time.Second
}
}
clientConfig := api.ClientConfig{
SubscriptionID: config.SubscriptionID,
AzureAuthConfig: azclient.AzureAuthConfig{
AADClientID: config.ClientID,
AADClientSecret: config.ClientSecret,
},
TenantID: config.TenantID,
Location: config.Location,
StorageDriverName: config.StorageDriverName,
DebugTraceFlags: config.DebugTraceFlags,
SDKTimeout: sdkTimeout,
MaxCacheAge: maxCacheAge,
}
// Try ANF driver initialization with Azure workload identity followed by Azure managed identity,
// when both are not present, default to credentials present in the backend configuration file.
// Azure workload identity
// If cloud identity is provided and cloud provider is set to 'Azure' during the installation,
// we can use AZURE_CLIENT_ID,AZURE_TENANT_ID,AZURE_FEDERATED_TOKEN_FILE and AZURE_AUTHORITY_HOST
// environment variables injected by workload identity webhook for initialization of ANF driver.
if os.Getenv("AZURE_CLIENT_ID") != "" && os.Getenv("AZURE_TENANT_ID") != "" &&
os.Getenv("AZURE_FEDERATED_TOKEN_FILE") != "" && os.Getenv("AZURE_AUTHORITY_HOST") != "" {
Logc(ctx).Info("Using Azure workload identity.")
} else {
// Azure managed identity
// If cloud provider is set to 'Azure' and cloud identity is not provided during the installation,
// we read the contents of AZURE_CREDENTIAL_FILE to initialize the ANF driver.
if config.ClientSecret == "" && config.ClientID == "" && os.Getenv("AZURE_CREDENTIAL_FILE") != "" {
credFilePath := os.Getenv("AZURE_CREDENTIAL_FILE")
Logc(ctx).WithField("credFilePath", credFilePath).Info("Using Azure credential config file.")
credFile, err := os.ReadFile(credFilePath)
if err != nil {
return errors.New("error reading from azure config file: " + err.Error())
}
if err = json.Unmarshal(credFile, &clientConfig); err != nil {
return errors.New("error parsing azureAuthConfig: " + err.Error())
}
// Set SubscriptionID and Location.
d.Config.SubscriptionID = clientConfig.SubscriptionID
d.Config.Location = clientConfig.Location
}
}
client, err := api.NewDriver(clientConfig)
if err != nil {
return err
}
// Unit tests mock the API layer, so we only use the real API interface if it doesn't already exist.
if d.SDK == nil {
d.SDK = client
}
// The storage pools should already be set up by this point. We register the pools with the
// API layer to enable matching of storage pools with discovered ANF resources.
return d.SDK.Init(ctx, d.pools)
}
// validate ensures the driver configuration and execution environment are valid and working.
func (d *NASStorageDriver) validate(ctx context.Context) error {
fields := LogFields{"Method": "validate", "Type": "NASStorageDriver"}
Logd(ctx, d.Name(), d.Config.DebugTraceFlags["method"]).WithFields(fields).Trace(">>>> validate")
defer Logd(ctx, d.Name(), d.Config.DebugTraceFlags["method"]).WithFields(fields).Trace("<<<< validate")
// Ensure storage prefix is compatible with cloud service
if err := validateStoragePrefix(*d.Config.StoragePrefix); err != nil {
return err
}
// Ensure that networkFeatures is not set to Basic when customer encryption keys are passed
if err := validateNetworkFeatures(d.Config.NetworkFeatures, d.Config.CustomerEncryptionKeys); err != nil {
return err
}
// Validate pool-level attributes
for poolName, pool := range d.pools {
// Validate service level (it is allowed to be blank)
serviceLevel := pool.InternalAttributes()[ServiceLevel]
switch serviceLevel {
case api.ServiceLevelStandard, api.ServiceLevelPremium, api.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 snapshot dir
if pool.InternalAttributes()[SnapshotDir] != "" {
_, err := strconv.ParseBool(pool.InternalAttributes()[SnapshotDir])
if err != nil {
return fmt.Errorf("invalid boolean value for snapshotDir in pool %s; %v", poolName, err)
}
}
// Validate unix permissions
if pool.InternalAttributes()[UnixPermissions] != "" {
err := utils.ValidateOctalUnixPermissions(pool.InternalAttributes()[UnixPermissions])
if err != nil {
return fmt.Errorf("invalid value for unixPermissions in pool %s; %v", poolName, err)
}
}
// 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)
}
// Validate pool labels
if _, err := pool.GetLabelsJSON(ctx, storage.ProvisioningLabelTag, api.MaxLabelLength); err != nil {
return fmt.Errorf("invalid value for label in pool %s; %v", poolName, err)
}
// Validate vnet features
switch pool.InternalAttributes()[NetworkFeatures] {
case "", api.NetworkFeaturesBasic, api.NetworkFeaturesStandard:
break
default:
return fmt.Errorf("invalid value for networkFeatures in pool %s", poolName)
}
if pool.InternalAttributes()[Kerberos] != "" {
if err := acp.API().IsFeatureEnabled(ctx, acp.FeatureInflightEncryption); err != nil {
// Log a warning to avoid putting the backend into a failed state.
Logc(ctx).WithFields(LogFields{
"attribute": Kerberos,
"value": pool.InternalAttributes()[Kerberos],
}).WithError(err).Warning("Pool attribute requires ACP; workflows using this option may fail.")
}
}
}
return nil
}
// Create creates a new volume.
func (d *NASStorageDriver) Create(
ctx context.Context, volConfig *storage.VolumeConfig, storagePool storage.Pool, volAttributes map[string]sa.Request,
) error {
name := volConfig.InternalName
fields := LogFields{
"Method": "Create",
"Type": "NASStorageDriver",
"name": name,
"attrs": volAttributes,
}
Logd(ctx, d.Name(), d.Config.DebugTraceFlags["method"]).WithFields(fields).Trace(">>>> Create")
defer Logd(ctx, d.Name(), d.Config.DebugTraceFlags["method"]).WithFields(fields).Trace("<<<< Create")
// Update resource cache as needed
if err := d.SDK.RefreshAzureResources(ctx); err != nil {
return fmt.Errorf("could not update ANF resource cache; %v", err)
}
// Make sure we got a valid name
if err := d.validateVolumeName(volConfig.Name); err != nil {
return err
}
// Make sure we got a valid creation token
if err := d.validateCreationToken(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())
}
// Check if this volume landed on a Kerberos-enabled storage pool. If so, check if ACP allows it.
if pool.InternalAttributes()[Kerberos] != "" {
if err := acp.API().IsFeatureEnabled(ctx, acp.FeatureInflightEncryption); err != nil {
Logc(ctx).WithField(
"feature", acp.FeatureInflightEncryption,
).WithError(err).Errorf("Failed to create volume.")
return fmt.Errorf("feature %s requires ACP; %w", acp.FeatureInflightEncryption, err)
}
}
// If the volume already exists, bail out
volumeExists, extantVolume, err := d.SDK.VolumeExists(ctx, volConfig)
if err != nil {
return fmt.Errorf("error checking for existing volume %s; %v", name, err)
}
if volumeExists {
if extantVolume.ProvisioningState == api.StateCreating {
// This is a retry and the volume still isn't ready, so no need to wait further.
return errors.VolumeCreatingError(
fmt.Sprintf("volume state is still %s, not %s", api.StateCreating, api.StateAvailable))
}
Logc(ctx).WithFields(LogFields{
"name": name,
"state": extantVolume.ProvisioningState,
}).Warning("Volume already exists.")
// Volume here is likely in terminal state. Get the exact error message why is it so.
if err = d.waitForVolumeCreate(ctx, extantVolume, api.Create); err != nil {
return err
}
// No specific error is returned, so return a generic volume exists error
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 || sizeBytes > math.MaxInt64 { // the azure api requires both int64 and uint64
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 err = drivers.CheckMinVolumeSize(sizeBytes, MinimumVolumeSizeBytes); err != nil {
return err
}
if sizeBytes < MinimumANFVolumeSizeBytes {
Logc(ctx).WithFields(LogFields{
"name": name,
"size": sizeBytes,
}).Warningf("Requested size is too small. Setting volume size to the minimum allowable (100 GB).")
sizeBytes = MinimumANFVolumeSizeBytes
}
if _, _, err = drivers.CheckVolumeSizeLimits(ctx, sizeBytes, d.Config.CommonStorageDriverConfig); err != nil {
return err
}
// Take service level from volume config first (handles Docker case), then from pool
serviceLevel := utils.Title(volConfig.ServiceLevel)
if serviceLevel == "" {
serviceLevel = pool.InternalAttributes()[ServiceLevel]
}
// Determine mount options (volume config wins, followed by backend config)
mountOptions := d.Config.NfsMountOptions
if volConfig.MountOptions != "" {
mountOptions = volConfig.MountOptions
}
// Take unix permissions from volume config first (handles Docker case & PVC annotations), then from pool
unixPermissions := volConfig.UnixPermissions
if unixPermissions == "" {
unixPermissions = pool.InternalAttributes()[UnixPermissions]
}
// TODO (cknight): remove when preview permissions feature reaches GA
if unixPermissions == "" && d.SDK.HasFeature(api.FeatureUnixPermissions) {
unixPermissions = "0777"
}
// Take kerberos option from pool
kerberos := pool.InternalAttributes()[Kerberos]
// Determine protocol from mount options
var protocolTypes []string
var cifsAccess, nfsV3Access, nfsV41Access, kerberosEnabled bool
var apiExportRule api.ExportRule
var exportPolicy api.ExportPolicy
switch kerberos {
case api.MountOptionKerberos5, api.MountOptionKerberos5I, api.MountOptionKerberos5P:
kerberosEnabled = true
case "":
kerberosEnabled = false
default:
return fmt.Errorf("unsupported kerberos type: %s", kerberos)
}
var nfsVersion string
if d.Config.NASType == sa.SMB {
protocolTypes = []string{api.ProtocolTypeCIFS}
} else {
nfsVersion, err = utils.GetNFSVersionFromMountOptions(mountOptions, nfsVersion3, supportedNFSVersions)
if err != nil {
return err
}
switch nfsVersion {
case nfsVersion3:
nfsV3Access = true
protocolTypes = []string{api.ProtocolTypeNFSv3}
case nfsVersion4:
fallthrough
case nfsVersion41:
nfsV41Access = true
protocolTypes = []string{api.ProtocolTypeNFSv41}
}
apiExportRule = api.ExportRule{
AllowedClients: pool.InternalAttributes()[ExportRule],
Cifs: cifsAccess,
Nfsv3: nfsV3Access,
Nfsv41: nfsV41Access,
RuleIndex: 1,
UnixReadOnly: false,
UnixReadWrite: true,
}
if kerberosEnabled {
protocolTypes = []string{api.ProtocolTypeNFSv41}
apiExportRule.Nfsv3 = false
apiExportRule.Nfsv41 = true
apiExportRule.UnixReadOnly = false
apiExportRule.UnixReadWrite = false
switch kerberos {
case api.MountOptionKerberos5:
apiExportRule.Kerberos5ReadWrite = true
case api.MountOptionKerberos5I:
apiExportRule.Kerberos5IReadWrite = true
case api.MountOptionKerberos5P:
apiExportRule.Kerberos5PReadWrite = true
}
}
exportPolicy = api.ExportPolicy{
Rules: []api.ExportRule{apiExportRule},
}
}
// Set snapshot directory from volume config first (handles Docker case), then from pool
// If none is set, set it based on mountOption by default; for nfsv3 => false, nfsv4/4.1 => true
snapshotDir := volConfig.SnapshotDir
if snapshotDir == "" {
snapshotDir = pool.InternalAttributes()[SnapshotDir]
// If snapshot directory is not set at pool level, then set default value based on mount option
if snapshotDir == "" {
if strings.HasPrefix(nfsVersion, "4") {
snapshotDir = "true"
} else {
snapshotDir = "false"
}
}
}
snapshotDirBool, err := strconv.ParseBool(snapshotDir)
if err != nil {
return fmt.Errorf("invalid value for snapshotDir; %v", err)
}
labels := make(map[string]string)
labels[drivers.TridentLabelTag] = d.getTelemetryLabels(ctx)
poolLabels, err := pool.GetLabelsJSON(ctx, storage.ProvisioningLabelTag, api.MaxLabelLength)
if err != nil {
return err
}
labels[storage.ProvisioningLabelTag] = poolLabels
networkFeatures := pool.InternalAttributes()[NetworkFeatures]
// Get topology, if any, and determine the matched Azure zone. If the pool has no zones, assume none are in use.
var region, zone string
if len(pool.SupportedTopologies()) > 0 {
if topology, topologyErr := sc.GetTopologyForVolume(ctx, volConfig, pool); topologyErr != nil {
return topologyErr
} else {
region, zone = sc.GetRegionZoneForTopology(topology)
zone, _ = strings.CutPrefix(zone, region+"-")
}
}
// Update config to reflect values used to create volume
volConfig.Size = strconv.FormatUint(sizeBytes, 10)
volConfig.ServiceLevel = serviceLevel
volConfig.SnapshotDir = strconv.FormatBool(snapshotDirBool)
volConfig.UnixPermissions = unixPermissions
volConfig.Zone = zone
// Find a subnet
subnet := d.SDK.RandomSubnetForStoragePool(ctx, pool)
if subnet == nil {
return fmt.Errorf("no subnets found for storage pool %s", pool.Name())
}
// Find matching capacity pools
cPools := d.SDK.CapacityPoolsForStoragePool(ctx, pool, serviceLevel)
if len(cPools) == 0 {
return fmt.Errorf("no capacity pools found for storage pool %s", pool.Name())
}
createErrors := multierr.Combine()
// Try each capacity pool until one works
for _, cPool := range cPools {
keyVaultEndpointID := ""
if keyVaultEndpoint, ok := d.Config.CustomerEncryptionKeys[cPool.NetAppAccount]; ok {
if networkFeatures == "" {
networkFeatures = api.NetworkFeaturesStandard
}
keyVaultEndpointID = api.CreateKeyVaultEndpoint(d.Config.SubscriptionID, cPool.ResourceGroup,
keyVaultEndpoint)
}
if d.Config.NASType == sa.SMB {
Logc(ctx).WithFields(LogFields{
"capacityPool": cPool.Name,
"creationToken": name,
"size": sizeBytes,
"serviceLevel": serviceLevel,