forked from rancher-plugins/kontainer-engine-driver-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaks_driver.go
1641 lines (1340 loc) · 55.1 KB
/
aks_driver.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
package main
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"regexp"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/services/containerservice/mgmt/2018-03-31/containerservice"
"github.com/Azure/azure-sdk-for-go/services/preview/network/mgmt/2015-05-01-preview/network"
"github.com/Azure/azure-sdk-for-go/services/preview/operationalinsights/mgmt/2015-11-01-preview/operationalinsights"
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2017-05-10/resources"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/adal"
"github.com/Azure/go-autorest/autorest/azure"
"github.com/Azure/go-autorest/autorest/to"
"github.com/rancher/kontainer-engine/drivers/options"
"github.com/rancher/kontainer-engine/drivers/util"
"github.com/rancher/kontainer-engine/types"
"github.com/sirupsen/logrus"
yaml "gopkg.in/yaml.v2"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
)
var redactionRegex = regexp.MustCompile("\"(clientId|secret)\": \"(.*)\"")
type Driver struct {
driverCapabilities types.Capabilities
}
type state struct {
/**
Azure Kubernetes Service API URI Parameters
*/
// SubscriptionID is a credential which uniquely identify Azure subscription. [requirement]
SubscriptionID string `json:"subscriptionId"`
// ResourceGroup specifies the cluster located int which resource group. [requirement]
ResourceGroup string `json:"resourceGroup"`
// Name specifies the cluster name. [requirement]
Name string `json:"name"`
/**
Azure Kubernetes Service API Request Body
*/
// AzureADClientAppID specifies the client ID of Azure Active Directory. [optional when creating]
AzureADClientAppID string `json:"aadClientAppId,omitempty"`
// AzureADServerAppID specifies the server ID of Azure Active Directory. [optional when creating]
AzureADServerAppID string `json:"aadServerAppId,omitempty"`
// AzureADServerAppSecret specifies the server secret of Azure Active Directory. [optional when creating]
AzureADServerAppSecret string `json:"aadServerAppSecret,omitempty"`
// AzureADTenantID specifies the tenant ID of Azure Active Directory. [optional when creating]
AzureADTenantID string `json:"aadTenantId,omitempty"`
// AddonEnableHTTPApplicationRouting specifies to enable "httpApplicationRouting" addon or not. [optional]
AddonEnableHTTPApplicationRouting bool `json:"enableHttpApplicationRouting,omitempty"`
// AddonEnableMonitoring specifies to enable "monitoring" addon or not. [optional]
AddonEnableMonitoring bool `json:"enableMonitoring,omitempty"`
// LogAnalyticsWorkspaceResourceGroup specifies the Azure Log Analytics Workspace located int which resource group. [optional]
LogAnalyticsWorkspaceResourceGroup string `json:"logAnalyticsWorkspaceResourceGroup,omitempty"`
// LogAnalyticsWorkspace specifies an existing Azure Log Analytics Workspace for "monitoring" addon. [optional]
LogAnalyticsWorkspace string `json:"logAnalyticsWorkspace,omitempty"`
// AgentDNSPrefix specifies the DNS prefix of the agent pool. [optional only when creating]
AgentDNSPrefix string `json:"agentDnsPrefix,omitempty"`
// AgentCount specifies the number of machines in the agent pool. [optional only when creating]
AgentCount int64 `json:"count,omitempty"`
// AgentMaxPods specifies the maximum number of pods that can run on a node. [optional only when creating]
AgentMaxPods int64 `json:"maxPods,omitempty"`
// AgentName specifies an unique name of the agent pool in the context of the subscription and resource group. [optional only when creating]
AgentName string `json:"agentPoolName,omitempty"`
// AgentOsdiskSizeGB specifies the disk size for every machine in the agent pool. [optional only when creating]
AgentOsdiskSizeGB int64 `json:"agentOsdiskSize,omitempty"`
// AgentStorageProfile specifies the storage profile in the agent pool. [optional only when creating]
AgentStorageProfile string `json:"agentStorageProfile,omitempty"`
// AgentVMSize specifies the VM size in the agent pool. [optional only when creating]
AgentVMSize string `json:"agentVmSize,omitempty"`
// VirtualNetworkResourceGroup specifies the Azure Virtual Network located int which resource group. Composite of agent virtual network subnet ID. [optional only when creating]
VirtualNetworkResourceGroup string `json:"virtualNetworkResourceGroup,omitempty"`
// VirtualNetwork specifies an existing Azure Virtual Network. Composite of agent virtual network subnet ID. [optional only when creating]
VirtualNetwork string `json:"virtualNetwork,omitempty"`
// Subnet specifies an existing Azure Virtual Subnet. Composite of agent virtual network subnet ID. [optional only when creating]
Subnet string `json:"subnet,omitempty"`
// LinuxAdminUsername specifies the username to use for Linux VMs. [optional only when creating]
LinuxAdminUsername string `json:"adminUsername,omitempty"`
// LinuxSSHPublicKeyContents specifies the content of the SSH configuration for Linux VMs, Opposite to `LinuxSSHPublicKeyPath`. [requirement only when creating]
LinuxSSHPublicKeyContents string `json:"sshPublicKeyContents,omitempty"`
// LinuxSSHPublicKeyPath specifies the local path of the SSH configuration for Linux VMs, Opposite to `LinuxSSHPublicKeyContents`. [requirement only when creating]
LinuxSSHPublicKeyPath string `json:"sshPublicKey,omitempty"`
// NetworkDNSServiceIP specifies an IP address assigned to the Kubernetes DNS service, it must be within the Kubernetes Service address range specified in `NetworkServiceCIDR`. [optional only when creating]
NetworkDNSServiceIP string `json:"dnsServiceIp,omitempty"`
// NetworkDockerBridgeCIDR specifies a CIDR notation IP range assigned to the Docker bridge network, it must not overlap with any Azure Subnet IP ranges or the Kubernetes Service address range. [optional only when creating]
NetworkDockerBridgeCIDR string `json:"dockerBridgeCidr,omitempty"`
// NetworkPlugin specifies the plugin used for Kubernetes network. [optional only when creating]
NetworkPlugin string `json:"networkPlugin,omitempty"`
// NetworkPolicy specifies the policy used for Kubernetes network. [optional only when creating]
NetworkPolicy string `json:"networkPolicy,omitempty"`
// NetworkPodCIDR specifies a CIDR notation IP range from which to assign pod IPs when `NetworkPlugin` is using "kubenet". [optional only when creating]
NetworkPodCIDR string `json:"podCidr,omitempty"`
// NetworkServiceCIDR specifies a CIDR notation IP range from which to assign service cluster IPs, it must not overlap with any Azure Subnet IP ranges. [optional only when creating]
NetworkServiceCIDR string `json:"serviceCidr,omitempty"`
// Location specifies the cluster location. [requirement]
Location string `json:"location,omitempty"`
// DNSPrefix specifies the DNS prefix of the cluster. [optional only when creating]
DNSPrefix string `json:"masterDnsPrefix,omitempty"`
// KubernetesVersion specifies the Kubernetes version of the cluster. [optional]
KubernetesVersion string `json:"kubernetesVersion,omitempty"`
// Tags tag the cluster. [optional]
Tags map[string]string `json:"tags,omitempty"`
/**
Azure Kubernetes Service API Metadata & Authentication
*/
// BaseURL specifies the Azure Resource management endpoint, it defaults "https://management.azure.com/". [requirement]
BaseURL string `json:"baseUrl"`
// AuthBaseURL specifies the Azure OAuth 2.0 authentication endpoint, it defaults "https://login.microsoftonline.com/". [requirement]
AuthBaseURL string `json:"authBaseUrl"`
// ClientID is a user ID for the Service Principal. [requirement]
ClientID string `json:"clientId"`
// ClientSecret is a plain-text password associated with the Service Principal. [requirement]
ClientSecret string `json:"clientSecret"`
// TenantID is a tenant ID for Azure OAuth 2.0 authentication. [optional only when creating]
TenantID string `json:"tenantId,omitempty"`
/**
Rancher Parameters
*/
// DisplayName specifies cluster name displayed in Rancher UI. [optional only when creating]
DisplayName string `json:"displayName,omitempty"`
ClusterInfo types.ClusterInfo `json:"-"`
}
func NewDriver() types.Driver {
driver := &Driver{
driverCapabilities: types.Capabilities{
Capabilities: make(map[int64]bool),
},
}
driver.driverCapabilities.AddCapability(types.GetVersionCapability)
driver.driverCapabilities.AddCapability(types.SetVersionCapability)
driver.driverCapabilities.AddCapability(types.GetClusterSizeCapability)
driver.driverCapabilities.AddCapability(types.SetClusterSizeCapability)
return driver
}
// GetDriverCreateOptions implements driver interface
func (d *Driver) GetDriverCreateOptions(ctx context.Context) (*types.DriverFlags, error) {
driverFlag := types.DriverFlags{
Options: make(map[string]*types.Flag),
}
driverFlag.Options["subscription-id"] = &types.Flag{
Type: types.StringType,
Usage: "Subscription credentials which uniquely identify Microsoft Azure subscription.",
}
driverFlag.Options["resource-group"] = &types.Flag{
Type: types.StringType,
Usage: "The name of the 'Cluster' resource group.",
}
driverFlag.Options["name"] = &types.Flag{
Type: types.StringType,
Usage: "The name of the 'Cluster' resource, and the internal name of the cluster in Rancher.",
}
driverFlag.Options["aad-client-app-id"] = &types.Flag{
Type: types.StringType,
Usage: `The ID of an Azure Active Directory client application of type "Native". This application is for user login via kubectl.`,
}
driverFlag.Options["aad-server-app-id"] = &types.Flag{
Type: types.StringType,
Usage: `The ID of an Azure Active Directory server application of type "Web app/API". This application represents the managed cluster's apiserver (Server application).`,
}
driverFlag.Options["aad-server-app-secret"] = &types.Flag{
Type: types.StringType,
Password: true,
Usage: `The secret of an Azure Active Directory server application.`,
}
driverFlag.Options["aad-tenant-id"] = &types.Flag{
Type: types.StringType,
Usage: `The ID of an Azure Active Directory tenant.`,
}
driverFlag.Options["enable-http-application-routing"] = &types.Flag{
Type: types.BoolType,
Usage: `Enable the Kubernetes ingress with automatic public DNS name creation.`,
Default: &types.Default{
DefaultBool: false,
},
}
driverFlag.Options["enable-monitoring"] = &types.Flag{
Type: types.BoolType,
Usage: `Turn on Azure Log Analytics monitoring. Uses the Log Analytics "Default" workspace if it exists, else creates one. if using an existing workspace, specifies "log analytics workspace resource id".`,
Default: &types.Default{
DefaultBool: true,
},
}
driverFlag.Options["log-analytics-workspace-resource-group"] = &types.Flag{
Type: types.StringType,
Usage: `The resource group of an existing Azure Log Analytics Workspace to use for storing monitoring data. If not specified, uses the 'Cluster' resource group.`,
}
driverFlag.Options["log-analytics-workspace"] = &types.Flag{
Type: types.StringType,
Usage: `The name of an existing Azure Log Analytics Workspace to use for storing monitoring data. If not specified, uses '{resource group}-{subscription id}-{location code}'.`,
}
driverFlag.Options["agent-dns-prefix"] = &types.Flag{
Type: types.StringType,
Usage: "DNS prefix to be used to create the FQDN for the agent pool.",
}
driverFlag.Options["count"] = &types.Flag{
Type: types.IntType,
Usage: "Number of machines (VMs) in the agent pool. Allowed values must be in the range of 1 to 100 (inclusive).",
Default: &types.Default{
DefaultInt: 1,
},
}
driverFlag.Options["max-pods"] = &types.Flag{
Type: types.IntType,
Usage: "Maximum number of pods that can run on a node.",
Default: &types.Default{
DefaultInt: 110,
},
}
driverFlag.Options["agent-pool-name"] = &types.Flag{
Type: types.StringType,
Usage: "Name for the agent pool, upto 12 alphanumeric characters.",
Value: "agentpool0",
}
driverFlag.Options["agent-osdisk-size"] = &types.Flag{
Type: types.IntType,
Usage: `GB size to be used to specify the disk for every machine in the agent pool. If you specify 0, it will apply the default according to the "agent vm size" specified.`,
}
driverFlag.Options["agent-storage-profile"] = &types.Flag{
Type: types.StringType,
Usage: fmt.Sprintf("Storage profile specifies what kind of storage used on machine in the agent pool. Chooses from %v.", containerservice.PossibleStorageProfileTypesValues()),
Value: string(containerservice.ManagedDisks),
}
driverFlag.Options["agent-vm-size"] = &types.Flag{
Type: types.StringType,
Usage: "Size of machine in the agent pool.",
Value: string(containerservice.StandardD1V2),
}
driverFlag.Options["virtual-network-resource-group"] = &types.Flag{
Type: types.StringType,
Usage: "The resource group of an existing Azure Virtual Network. Composite of agent virtual network subnet ID.",
}
driverFlag.Options["virtual-network"] = &types.Flag{
Type: types.StringType,
Usage: "The name of an existing Azure Virtual Network. Composite of agent virtual network subnet ID.",
}
driverFlag.Options["subnet"] = &types.Flag{
Type: types.StringType,
Usage: "The name of an existing Azure Virtual Subnet. Composite of agent virtual network subnet ID.",
}
driverFlag.Options["admin-username"] = &types.Flag{
Type: types.StringType,
Usage: "The administrator username to use for Linux hosts.",
Value: "azureuser",
}
driverFlag.Options["ssh-public-key-contents"] = &types.Flag{
Type: types.StringType,
Usage: `Contents of the SSH public key used to authenticate with Linux hosts. Opposite to "ssh public key".`,
}
driverFlag.Options["ssh-public-key"] = &types.Flag{
Type: types.StringType,
Usage: `Path to the SSH public key used to authenticate with Linux hosts. Opposite to "ssh public key contents".`,
}
driverFlag.Options["dns-service-ip"] = &types.Flag{
Type: types.StringType,
Usage: `An IP address assigned to the Kubernetes DNS service. It must be within the Kubernetes Service address range specified in "service cidr".`,
Value: "10.0.0.10",
}
driverFlag.Options["docker-bridge-cidr"] = &types.Flag{
Type: types.StringType,
Usage: `A CIDR notation IP range assigned to the Docker bridge network. It must not overlap with any Subnet IP ranges or the Kubernetes Service address range specified in "service cidr".`,
Value: "172.17.0.1/16",
}
driverFlag.Options["network-plugin"] = &types.Flag{
Type: types.StringType,
Usage: fmt.Sprintf(`Network plugin used for building Kubernetes network. Chooses from %v.`, containerservice.PossibleNetworkPluginValues()),
Value: string(containerservice.Azure),
}
driverFlag.Options["network-policy"] = &types.Flag{
Type: types.StringType,
Usage: fmt.Sprintf(`Network policy used for building Kubernetes network. Chooses from %v.`, containerservice.PossibleNetworkPolicyValues()),
}
driverFlag.Options["pod-cidr"] = &types.Flag{
Type: types.StringType,
Usage: fmt.Sprintf(`A CIDR notation IP range from which to assign Kubernetes Pod IPs when "network plugin" is specified in %q.`, containerservice.Kubenet),
Value: "172.244.0.0/16",
}
driverFlag.Options["service-cidr"] = &types.Flag{
Type: types.StringType,
Usage: "A CIDR notation IP range from which to assign Kubernetes Service cluster IPs. It must not overlap with any Subnet IP ranges.",
Value: "10.0.0.0/16",
}
driverFlag.Options["location"] = &types.Flag{
Type: types.StringType,
Usage: "Azure Kubernetes cluster location.",
Value: "eastus",
}
driverFlag.Options["master-dns-prefix"] = &types.Flag{
Type: types.StringType,
Usage: "DNS prefix to use the Kubernetes cluster control pane.",
}
driverFlag.Options["kubernetes-version"] = &types.Flag{
Type: types.StringType,
Usage: "Specify the version of Kubernetes.",
Value: "1.11.5",
}
driverFlag.Options["tags"] = &types.Flag{
Type: types.StringSliceType,
Usage: "Tags for Kubernetes cluster. For example, foo=bar.",
}
driverFlag.Options["base-url"] = &types.Flag{
Type: types.StringType,
Usage: "Different resource management API url to use.",
Value: azure.PublicCloud.ResourceManagerEndpoint,
}
driverFlag.Options["auth-base-url"] = &types.Flag{
Type: types.StringType,
Usage: "Different authentication API url to use.",
Value: azure.PublicCloud.ActiveDirectoryEndpoint,
}
driverFlag.Options["client-id"] = &types.Flag{
Type: types.StringType,
Usage: "Azure client ID to use.",
}
driverFlag.Options["client-secret"] = &types.Flag{
Type: types.StringType,
Password: true,
Usage: `Azure client secret associated with the "client id".`,
}
driverFlag.Options["tenant-id"] = &types.Flag{
Type: types.StringType,
Usage: "Azure tenant ID to use.",
}
driverFlag.Options["display-name"] = &types.Flag{
Type: types.StringType,
Usage: "The displayed name of the cluster in the Rancher UI.",
}
return &driverFlag, nil
}
// GetDriverUpdateOptions implements driver interface
func (d *Driver) GetDriverUpdateOptions(ctx context.Context) (*types.DriverFlags, error) {
driverFlag := types.DriverFlags{
Options: make(map[string]*types.Flag),
}
driverFlag.Options["enable-http-application-routing"] = &types.Flag{
Type: types.BoolType,
Usage: `Enable the Kubernetes ingress with automatic public DNS name creation.`,
Default: &types.Default{
DefaultBool: false,
},
}
driverFlag.Options["enable-monitoring"] = &types.Flag{
Type: types.BoolType,
Usage: `Turn on Azure Log Analytics monitoring. Uses the Log Analytics "Default" workspace if it exists, else creates one. if using an existing workspace, specifies "log analytics workspace resource id".`,
Default: &types.Default{
DefaultBool: true,
},
}
driverFlag.Options["log-analytics-workspace-resource-group"] = &types.Flag{
Type: types.StringType,
Usage: `The resource group of an existing Azure Log Analytics Workspace to use for storing monitoring data. If not specified, uses the 'Cluster' resource group.`,
}
driverFlag.Options["log-analytics-workspace"] = &types.Flag{
Type: types.StringType,
Usage: `The name of an existing Azure Log Analytics Workspace to use for storing monitoring data. If not specified, uses '{resource group}-{subscription id}-{location code}'.`,
}
driverFlag.Options["count"] = &types.Flag{
Type: types.IntType,
Usage: "Number of machines (VMs) in the agent pool. Allowed values must be in the range of 1 to 100 (inclusive).",
Default: &types.Default{
DefaultInt: 1,
},
}
driverFlag.Options["kubernetes-version"] = &types.Flag{
Type: types.StringType,
Usage: "Specify the version of Kubernetes.",
Value: "1.11.5",
}
driverFlag.Options["tags"] = &types.Flag{
Type: types.StringSliceType,
Usage: "Tags for Kubernetes cluster. For example, foo=bar.",
}
return &driverFlag, nil
}
// SetDriverOptions implements driver interface
func getStateFromOptions(driverOptions *types.DriverOptions) (state, error) {
state := state{}
state.SubscriptionID = options.GetValueFromDriverOptions(driverOptions, types.StringType, "subscription-id", "subscriptionId").(string)
state.ResourceGroup = options.GetValueFromDriverOptions(driverOptions, types.StringType, "resource-group", "resourceGroup").(string)
state.Name = options.GetValueFromDriverOptions(driverOptions, types.StringType, "name").(string)
state.AzureADClientAppID = options.GetValueFromDriverOptions(driverOptions, types.StringType, "aad-client-app-id", "aadClientAppId").(string)
state.AzureADServerAppID = options.GetValueFromDriverOptions(driverOptions, types.StringType, "aad-server-app-id", "aadServerAppId").(string)
state.AzureADServerAppSecret = options.GetValueFromDriverOptions(driverOptions, types.StringType, "aad-server-app-secret", "aadServerAppSecret").(string)
state.AzureADTenantID = options.GetValueFromDriverOptions(driverOptions, types.StringType, "aad-tenant-id", "aadTenantId").(string)
state.AddonEnableHTTPApplicationRouting = options.GetValueFromDriverOptions(driverOptions, types.BoolType, "enable-http-application-routing", "enableHttpApplicationRouting").(bool)
state.AddonEnableMonitoring = options.GetValueFromDriverOptions(driverOptions, types.BoolType, "enable-monitoring", "enableMonitoring").(bool)
state.LogAnalyticsWorkspaceResourceGroup = options.GetValueFromDriverOptions(driverOptions, types.StringType, "log-analytics-workspace-resource-group", "logAnalyticsWorkspaceResourceGroup").(string)
state.LogAnalyticsWorkspace = options.GetValueFromDriverOptions(driverOptions, types.StringType, "log-analytics-workspace", "logAnalyticsWorkspace").(string)
state.AgentDNSPrefix = options.GetValueFromDriverOptions(driverOptions, types.StringType, "agent-dns-prefix", "agentDnsPrefix").(string)
state.AgentCount = options.GetValueFromDriverOptions(driverOptions, types.IntType, "count").(int64)
state.AgentMaxPods = options.GetValueFromDriverOptions(driverOptions, types.IntType, "max-pods", "maxPods").(int64)
state.AgentName = options.GetValueFromDriverOptions(driverOptions, types.StringType, "agent-pool-name", "agentPoolName").(string)
state.AgentOsdiskSizeGB = options.GetValueFromDriverOptions(driverOptions, types.IntType, "agent-osdisk-size", "agentOsdiskSize", "os-disk-size", "osDiskSizeGb").(int64)
state.AgentStorageProfile = options.GetValueFromDriverOptions(driverOptions, types.StringType, "agent-storage-profile", "agentStorageProfile").(string)
state.AgentVMSize = options.GetValueFromDriverOptions(driverOptions, types.StringType, "agent-vm-size", "agentVmSize").(string)
state.VirtualNetworkResourceGroup = options.GetValueFromDriverOptions(driverOptions, types.StringType, "virtual-network-resource-group", "virtualNetworkResourceGroup").(string)
state.VirtualNetwork = options.GetValueFromDriverOptions(driverOptions, types.StringType, "virtual-network", "virtualNetwork").(string)
state.Subnet = options.GetValueFromDriverOptions(driverOptions, types.StringType, "subnet").(string)
state.LinuxAdminUsername = options.GetValueFromDriverOptions(driverOptions, types.StringType, "admin-username", "adminUsername").(string)
state.LinuxSSHPublicKeyContents = options.GetValueFromDriverOptions(driverOptions, types.StringType, "ssh-public-key-contents", "sshPublicKeyContents", "public-key-contents", "publicKeyContents").(string)
state.LinuxSSHPublicKeyPath = options.GetValueFromDriverOptions(driverOptions, types.StringType, "ssh-public-key", "sshPublicKey", "public-key", "publicKey").(string)
state.NetworkDNSServiceIP = options.GetValueFromDriverOptions(driverOptions, types.StringType, "dns-service-ip", "dnsServiceIp").(string)
state.NetworkDockerBridgeCIDR = options.GetValueFromDriverOptions(driverOptions, types.StringType, "docker-bridge-cidr", "dockerBridgeCidr").(string)
state.NetworkPlugin = options.GetValueFromDriverOptions(driverOptions, types.StringType, "network-plugin", "networkPlugin").(string)
state.NetworkPolicy = options.GetValueFromDriverOptions(driverOptions, types.StringType, "network-policy", "networkPolicy").(string)
state.NetworkPodCIDR = options.GetValueFromDriverOptions(driverOptions, types.StringType, "pod-cidr", "podCidr").(string)
state.NetworkServiceCIDR = options.GetValueFromDriverOptions(driverOptions, types.StringType, "service-cidr", "serviceCidr").(string)
state.Location = options.GetValueFromDriverOptions(driverOptions, types.StringType, "location").(string)
state.DNSPrefix = options.GetValueFromDriverOptions(driverOptions, types.StringType, "master-dns-prefix", "masterDnsPrefix").(string)
state.KubernetesVersion = options.GetValueFromDriverOptions(driverOptions, types.StringType, "kubernetes-version", "kubernetesVersion").(string)
state.Tags = make(map[string]string)
tagValues := options.GetValueFromDriverOptions(driverOptions, types.StringSliceType, "tags").(*types.StringSlice)
for _, part := range tagValues.Value {
kv := strings.Split(part, "=")
if len(kv) == 2 {
state.Tags[kv[0]] = kv[1]
}
}
state.BaseURL = options.GetValueFromDriverOptions(driverOptions, types.StringType, "base-url", "baseUrl").(string)
state.AuthBaseURL = options.GetValueFromDriverOptions(driverOptions, types.StringType, "auth-base-url", "authBaseUrl").(string)
state.ClientID = options.GetValueFromDriverOptions(driverOptions, types.StringType, "client-id", "clientId").(string)
state.ClientSecret = options.GetValueFromDriverOptions(driverOptions, types.StringType, "client-secret", "clientSecret").(string)
state.TenantID = options.GetValueFromDriverOptions(driverOptions, types.StringType, "tenant-id", "tenantId").(string)
state.DisplayName = options.GetValueFromDriverOptions(driverOptions, types.StringType, "display-name", "displayName").(string)
return state, state.validate()
}
func (state state) validate() error {
if state.SubscriptionID == "" {
return fmt.Errorf(`"subscription id" is required`)
}
if state.ResourceGroup == "" {
return fmt.Errorf(`"resource group" is required`)
}
if state.Name == "" {
return fmt.Errorf(`"name" is required`)
}
if state.ClientID == "" {
return fmt.Errorf(`"client id" is required`)
}
if state.ClientSecret == "" {
return fmt.Errorf(`"client secret" is required`)
}
if state.Location == "" {
return fmt.Errorf(`"location" is required`)
}
if state.LinuxSSHPublicKeyContents == "" && state.LinuxSSHPublicKeyPath == "" {
return fmt.Errorf(`"ssh public key contents or path" is required`)
}
return nil
}
func safeSlice(toSlice string, index int) string {
size := len(toSlice)
if index >= size {
index = size - 1
}
return toSlice[:index]
}
func (state state) getDefaultDNSPrefix() string {
namePart := safeSlice(state.Name, 10)
groupPart := safeSlice(state.ResourceGroup, 16)
subscriptionPart := safeSlice(state.SubscriptionID, 6)
return fmt.Sprintf("%v-%v-%v", namePart, groupPart, subscriptionPart)
}
func newClientAuthorizer(state state) (autorest.Authorizer, error) {
authBaseURL := state.AuthBaseURL
if authBaseURL == "" {
authBaseURL = azure.PublicCloud.ActiveDirectoryEndpoint
}
oauthConfig, err := adal.NewOAuthConfig(authBaseURL, state.TenantID)
if err != nil {
return nil, err
}
baseURL := state.BaseURL
if baseURL == "" {
baseURL = azure.PublicCloud.ResourceManagerEndpoint
}
spToken, err := adal.NewServicePrincipalToken(*oauthConfig, state.ClientID, state.ClientSecret, baseURL)
if err != nil {
return nil, err
}
authorizer := autorest.NewBearerAuthorizer(spToken)
return authorizer, nil
}
func newClustersClient(authorizer autorest.Authorizer, state state) (*containerservice.ManagedClustersClient, error) {
if authorizer == nil {
newAuthorizer, err := newClientAuthorizer(state)
if err != nil {
return nil, err
}
authorizer = newAuthorizer
}
baseURL := state.BaseURL
if baseURL == "" {
baseURL = azure.PublicCloud.ResourceManagerEndpoint
}
client := containerservice.NewManagedClustersClientWithBaseURI(baseURL, state.SubscriptionID)
client.Authorizer = authorizer
return &client, nil
}
func newResourceGroupsClient(authorizer autorest.Authorizer, state state) (*resources.GroupsClient, error) {
if authorizer == nil {
newAuthorizer, err := newClientAuthorizer(state)
if err != nil {
return nil, err
}
authorizer = newAuthorizer
}
baseURL := state.BaseURL
if baseURL == "" {
baseURL = azure.PublicCloud.ResourceManagerEndpoint
}
client := resources.NewGroupsClientWithBaseURI(baseURL, state.SubscriptionID)
client.Authorizer = authorizer
return &client, nil
}
func newOperationInsightsWorkspaceClient(authorizer autorest.Authorizer, state state) (*operationalinsights.WorkspacesClient, error) {
if authorizer == nil {
newAuthorizer, err := newClientAuthorizer(state)
if err != nil {
return nil, err
}
authorizer = newAuthorizer
}
baseURL := state.BaseURL
if baseURL == "" {
baseURL = azure.PublicCloud.ResourceManagerEndpoint
}
client := operationalinsights.NewWorkspacesClientWithBaseURI(baseURL, state.SubscriptionID)
client.Authorizer = authorizer
return &client, nil
}
func newRouteTablesClient(authorizer autorest.Authorizer, state state) (*network.RouteTablesClient, error) {
if authorizer == nil {
newAuthorizer, err := newClientAuthorizer(state)
if err != nil {
return nil, err
}
authorizer = newAuthorizer
}
baseURL := state.BaseURL
if baseURL == "" {
baseURL = azure.PublicCloud.ResourceManagerEndpoint
}
client := network.NewRouteTablesClientWithBaseURI(baseURL, state.SubscriptionID)
client.Authorizer = authorizer
return &client, nil
}
func newSecurityGroupsClient(authorizer autorest.Authorizer, state state) (*network.SecurityGroupsClient, error) {
if authorizer == nil {
newAuthorizer, err := newClientAuthorizer(state)
if err != nil {
return nil, err
}
authorizer = newAuthorizer
}
baseURL := state.BaseURL
if baseURL == "" {
baseURL = azure.PublicCloud.ResourceManagerEndpoint
}
client := network.NewSecurityGroupsClientWithBaseURI(baseURL, state.SubscriptionID)
client.Authorizer = authorizer
return &client, nil
}
func newSubnetsClient(authorizer autorest.Authorizer, state state) (*network.SubnetsClient, error) {
if authorizer == nil {
newAuthorizer, err := newClientAuthorizer(state)
if err != nil {
return nil, err
}
authorizer = newAuthorizer
}
baseURL := state.BaseURL
if baseURL == "" {
baseURL = azure.PublicCloud.ResourceManagerEndpoint
}
client := network.NewSubnetsClientWithBaseURI(baseURL, state.SubscriptionID)
client.Authorizer = authorizer
return &client, nil
}
const failedStatus = "Failed"
const succeededStatus = "Succeeded"
const creatingStatus = "Creating"
const updatingStatus = "Updating"
const scalingStatus = "Scaling"
const pollInterval = 30
func (d *Driver) Create(ctx context.Context, options *types.DriverOptions, _ *types.ClusterInfo) (*types.ClusterInfo, error) {
return d.createOrUpdate(ctx, options, true)
}
func (d *Driver) Update(ctx context.Context, info *types.ClusterInfo, options *types.DriverOptions) (*types.ClusterInfo, error) {
return d.createOrUpdate(ctx, options, false)
}
func (d *Driver) createOrUpdate(ctx context.Context, options *types.DriverOptions, creating bool) (*types.ClusterInfo, error) {
driverState, err := getStateFromOptions(options)
if err != nil {
return nil, err
}
info := &types.ClusterInfo{}
err = storeState(info, driverState)
if err != nil {
return info, err
}
azureAuthorizer, err := newClientAuthorizer(driverState)
if err != nil {
return info, err
}
clustersClient, err := newClustersClient(azureAuthorizer, driverState)
if err != nil {
return info, err
}
resourceGroupsClient, err := newResourceGroupsClient(azureAuthorizer, driverState)
if err != nil {
return info, err
}
operationInsightsWorkspaceClient, err := newOperationInsightsWorkspaceClient(azureAuthorizer, driverState)
if err != nil {
return info, err
}
masterDNSPrefix := driverState.DNSPrefix
if masterDNSPrefix == "" {
masterDNSPrefix = driverState.getDefaultDNSPrefix() + "-master"
}
tags := make(map[string]*string)
for key, val := range driverState.Tags {
if val != "" {
tags[key] = to.StringPtr(val)
}
}
displayName := driverState.DisplayName
if displayName == "" {
displayName = driverState.Name
}
tags["displayName"] = to.StringPtr(displayName)
if creating {
if _, err := subnetAlreadyAttached(ctx, driverState, ""); err != nil {
return info, err
}
}
exists, err := d.resourceGroupExists(ctx, resourceGroupsClient, driverState.ResourceGroup)
if err != nil {
return info, err
}
if !exists {
logrus.Infof("resource group %v does not exist, creating", driverState.ResourceGroup)
err = d.createResourceGroup(ctx, resourceGroupsClient, driverState)
if err != nil {
return info, err
}
}
var aadProfile *containerservice.ManagedClusterAADProfile
if driverState.hasAzureActiveDirectoryProfile() {
aadProfile = &containerservice.ManagedClusterAADProfile{
ClientAppID: to.StringPtr(driverState.AzureADClientAppID),
ServerAppID: to.StringPtr(driverState.AzureADServerAppID),
ServerAppSecret: to.StringPtr(driverState.AzureADServerAppSecret),
}
if driverState.AzureADTenantID != "" {
aadProfile.TenantID = to.StringPtr(driverState.AzureADTenantID)
}
}
addonProfiles := map[string]*containerservice.ManagedClusterAddonProfile{
"omsagent": {
Enabled: to.BoolPtr(driverState.AddonEnableMonitoring),
},
"httpApplicationRouting": {
Enabled: to.BoolPtr(driverState.AddonEnableHTTPApplicationRouting),
},
}
if driverState.AddonEnableMonitoring {
logAnalyticsWorkspaceResourceID, err := d.ensureLogAnalyticsWorkspaceForMonitoring(ctx, operationInsightsWorkspaceClient, driverState)
if err != nil {
return info, err
}
if !strings.HasPrefix(logAnalyticsWorkspaceResourceID, "/") {
logAnalyticsWorkspaceResourceID = "/" + logAnalyticsWorkspaceResourceID
}
logAnalyticsWorkspaceResourceID = strings.TrimSuffix(logAnalyticsWorkspaceResourceID, "/")
addonProfiles["omsagent"].Config = map[string]*string{
"logAnalyticsWorkspaceResourceID": to.StringPtr(logAnalyticsWorkspaceResourceID),
}
}
var vmNetSubnetID *string
var networkProfile *containerservice.NetworkProfile
if driverState.hasCustomVirtualNetwork() {
subnet, err := getSubnet(ctx, driverState)
if err != nil {
return info, err
}
vmNetSubnetID = subnet.ID
networkProfile = &containerservice.NetworkProfile{
DNSServiceIP: to.StringPtr(driverState.NetworkDNSServiceIP),
DockerBridgeCidr: to.StringPtr(driverState.NetworkDockerBridgeCIDR),
ServiceCidr: to.StringPtr(driverState.NetworkServiceCIDR),
}
if driverState.NetworkPlugin == "" {
networkProfile.NetworkPlugin = containerservice.Azure
} else {
networkProfile.NetworkPlugin = containerservice.NetworkPlugin(driverState.NetworkPlugin)
}
// if network plugin is 'kubenet', set PodCIDR
if networkProfile.NetworkPlugin == containerservice.Kubenet {
networkProfile.PodCidr = to.StringPtr(driverState.NetworkPodCIDR)
}
if driverState.NetworkPolicy != "" {
networkProfile.NetworkPolicy = containerservice.NetworkPolicy(driverState.NetworkPolicy)
}
}
var agentPoolProfiles *[]containerservice.ManagedClusterAgentPoolProfile
if driverState.hasAgentPoolProfile() {
var countPointer *int32
if driverState.AgentCount > 0 {
countPointer = to.Int32Ptr(int32(driverState.AgentCount))
} else {
countPointer = to.Int32Ptr(1)
}
var maxPodsPointer *int32
if driverState.AgentMaxPods > 0 {
maxPodsPointer = to.Int32Ptr(int32(driverState.AgentMaxPods))
} else {
maxPodsPointer = to.Int32Ptr(110)
}
var osDiskSizeGBPointer *int32
if driverState.AgentOsdiskSizeGB > 0 {
osDiskSizeGBPointer = to.Int32Ptr(int32(driverState.AgentOsdiskSizeGB))
}
agentDNSPrefix := driverState.AgentDNSPrefix
if agentDNSPrefix == "" {
agentDNSPrefix = driverState.getDefaultDNSPrefix() + "-agent"
}
agentStorageProfile := containerservice.ManagedDisks
if driverState.AgentStorageProfile != "" {
agentStorageProfile = containerservice.StorageProfileTypes(driverState.AgentStorageProfile)
}
agentVMSize := containerservice.StandardD1V2
if driverState.AgentVMSize != "" {
agentVMSize = containerservice.VMSizeTypes(driverState.AgentVMSize)
}
agentPoolProfiles = &[]containerservice.ManagedClusterAgentPoolProfile{
{
DNSPrefix: to.StringPtr(agentDNSPrefix),
Count: countPointer,
MaxPods: maxPodsPointer,
Name: to.StringPtr(safeSlice(driverState.AgentName, 12)),
OsDiskSizeGB: osDiskSizeGBPointer,
OsType: containerservice.Linux,
StorageProfile: agentStorageProfile,
VMSize: agentVMSize,
VnetSubnetID: vmNetSubnetID,
},
}
}
var linuxProfile *containerservice.LinuxProfile
if driverState.hasLinuxProfile() {
var publicKey []byte
if driverState.LinuxSSHPublicKeyContents == "" {
publicKey, err = ioutil.ReadFile(driverState.LinuxSSHPublicKeyPath)
if err != nil {
return info, err
}
} else {
publicKey = []byte(driverState.LinuxSSHPublicKeyContents)
}
publicKeyContents := string(publicKey)
linuxProfile = &containerservice.LinuxProfile{
AdminUsername: to.StringPtr(driverState.LinuxAdminUsername),
SSH: &containerservice.SSHConfiguration{
PublicKeys: &[]containerservice.SSHPublicKey{
{
KeyData: to.StringPtr(publicKeyContents),
},
},
},
}
}
managedCluster := containerservice.ManagedCluster{
Location: to.StringPtr(driverState.Location),
Tags: tags,
ManagedClusterProperties: &containerservice.ManagedClusterProperties{
KubernetesVersion: to.StringPtr(driverState.KubernetesVersion),
DNSPrefix: to.StringPtr(masterDNSPrefix),
AadProfile: aadProfile,
AddonProfiles: addonProfiles,
AgentPoolProfiles: agentPoolProfiles,
LinuxProfile: linuxProfile,
NetworkProfile: networkProfile,
ServicePrincipalProfile: &containerservice.ServicePrincipalProfile{
ClientID: to.StringPtr(driverState.ClientID),
Secret: to.StringPtr(driverState.ClientSecret),
},
},
}
if creating {
managedCluster.ManagedClusterProperties.EnableRBAC = to.BoolPtr(true)
}
logClusterConfig(managedCluster)
_, err = clustersClient.CreateOrUpdate(ctx, driverState.ResourceGroup, driverState.Name, managedCluster)
if err != nil {
return info, err
}
logrus.Info("Request submitted, waiting for cluster to finish creating")
failedCount := 0
for {
result, err := clustersClient.Get(ctx, driverState.ResourceGroup, driverState.Name)
if err != nil {
return info, err
}
switch state := *result.ProvisioningState; state {
case failedStatus:
if failedCount > 3 {
logrus.Errorf("cluster recovery failed, retries depleted")
return info, fmt.Errorf("cluster create has completed with status of 'Failed'")
}
failedCount = failedCount + 1
logrus.Infof("cluster marked as failed but waiting for recovery: retries left %v", 3-failedCount)
time.Sleep(pollInterval * time.Second)
case scalingStatus, creatingStatus, updatingStatus:
logrus.Infof("Cluster %v is %v", driverState.Name, state)
case succeededStatus:
logrus.Info("Cluster provisioned successfully")
info := &types.ClusterInfo{}
err := storeState(info, driverState)
return info, err
default:
logrus.Errorf("Azure failed to provision cluster with state: %v", state)
return info, fmt.Errorf("failed to provision Azure cluster")
}
logrus.Infof("Cluster has not yet completed provisioning, waiting another %v seconds", pollInterval)
time.Sleep(pollInterval * time.Second)
}
}
func (state state) hasCustomVirtualNetwork() bool {
return state.VirtualNetwork != "" && state.Subnet != ""
}
func (state state) hasAzureActiveDirectoryProfile() bool {
return state.AzureADClientAppID != "" && state.AzureADServerAppID != "" && state.AzureADServerAppSecret != ""
}
func (state state) hasAgentPoolProfile() bool {
return state.AgentName != ""
}
func (state state) hasLinuxProfile() bool {
return state.LinuxAdminUsername != "" && (state.LinuxSSHPublicKeyContents != "" || state.LinuxSSHPublicKeyPath != "")
}
func (d *Driver) ensureLogAnalyticsWorkspaceForMonitoring(ctx context.Context, client *operationalinsights.WorkspacesClient, state state) (workspaceID string, err error) {
// log analytics workspaces cannot be created in WCUS region due to capacity limits
// so mapped to EUS per discussion with log analytics team
locationToOmsRegionCodeMap := map[string]string{
"eastus": "EUS",
"westeurope": "WEU",