-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
azure.go
1561 lines (1414 loc) · 47.8 KB
/
azure.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 The Cockroach Authors.
//
// Use of this software is governed by the Business Source License
// included in the file licenses/BSL.txt.
//
// As of the Change Date specified in that file, in accordance with
// the Business Source License, use of this software will be governed
// by the Apache License, Version 2.0, included in the file
// licenses/APL.txt.
package azure
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/profiles/latest/compute/mgmt/compute"
"github.com/Azure/azure-sdk-for-go/profiles/latest/network/mgmt/network"
"github.com/Azure/azure-sdk-for-go/profiles/latest/resources/mgmt/resources"
"github.com/Azure/azure-sdk-for-go/profiles/latest/resources/mgmt/subscriptions"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/to"
"github.com/cockroachdb/cockroach/pkg/roachprod/logger"
"github.com/cockroachdb/cockroach/pkg/roachprod/vm"
"github.com/cockroachdb/cockroach/pkg/roachprod/vm/flagstub"
"github.com/cockroachdb/cockroach/pkg/util/syncutil"
"github.com/cockroachdb/cockroach/pkg/util/timeutil"
"github.com/cockroachdb/errors"
"golang.org/x/sync/errgroup"
)
const (
// ProviderName is "azure".
ProviderName = "azure"
remoteUser = "ubuntu"
tagComment = "comment"
tagSubnet = "subnetPrefix"
)
// providerInstance is the instance to be registered into vm.Providers by Init.
var providerInstance = &Provider{}
// Init registers the Azure provider with vm.Providers.
//
// If the Azure CLI utilities are not installed, the provider is a stub.
func Init() error {
const cliErr = "please install the Azure CLI utilities " +
"(https://docs.microsoft.com/en-us/cli/azure/install-azure-cli)"
const authErr = "unable to authenticate; please use `az login` or double check environment variables"
providerInstance = New()
providerInstance.OperationTimeout = 10 * time.Minute
providerInstance.SyncDelete = false
// If the appropriate environment variables are not set for api access,
// then the authenticated CLI must be installed.
if !hasEnvAuth {
if _, err := exec.LookPath("az"); err != nil {
vm.Providers[ProviderName] = flagstub.New(&Provider{}, cliErr)
return err
}
}
if _, err := providerInstance.getAuthToken(); err != nil {
vm.Providers[ProviderName] = flagstub.New(&Provider{}, authErr)
return err
}
vm.Providers[ProviderName] = providerInstance
return nil
}
// Provider implements the vm.Provider interface for the Microsoft Azure
// cloud.
type Provider struct {
// The maximum amount of time for an Azure API operation to take.
OperationTimeout time.Duration
// Wait for deletions to finish before returning.
SyncDelete bool
mu struct {
syncutil.Mutex
authorizer autorest.Authorizer
subscriptionId string
resourceGroups map[string]resources.Group
subnets map[string]network.Subnet
securityGroups map[string]network.SecurityGroup
}
}
func (p *Provider) CreateVolumeSnapshot(
l *logger.Logger, volume vm.Volume, vsco vm.VolumeSnapshotCreateOpts,
) (vm.VolumeSnapshot, error) {
// TODO(leon): implement
panic("unimplemented")
}
func (p *Provider) ListVolumeSnapshots(
l *logger.Logger, vslo vm.VolumeSnapshotListOpts,
) ([]vm.VolumeSnapshot, error) {
panic("unimplemented")
}
func (p *Provider) DeleteVolumeSnapshots(l *logger.Logger, snapshots ...vm.VolumeSnapshot) error {
panic("unimplemented")
}
func (p *Provider) CreateVolume(*logger.Logger, vm.VolumeCreateOpts) (vm.Volume, error) {
panic("unimplemented")
}
func (p *Provider) DeleteVolume(l *logger.Logger, volume vm.Volume, vm *vm.VM) error {
panic("unimplemented")
}
func (p *Provider) ListVolumes(l *logger.Logger, vm *vm.VM) ([]vm.Volume, error) {
return vm.NonBootAttachedVolumes, nil
}
func (p *Provider) AttachVolume(*logger.Logger, vm.Volume, *vm.VM) (string, error) {
panic("unimplemented")
}
// New constructs a new Provider instance.
func New() *Provider {
p := &Provider{}
p.mu.resourceGroups = make(map[string]resources.Group)
p.mu.securityGroups = make(map[string]network.SecurityGroup)
p.mu.subnets = make(map[string]network.Subnet)
return p
}
// Active implements vm.Provider and always returns true.
func (p *Provider) Active() bool {
return true
}
// ProjectActive is part of the vm.Provider interface.
func (p *Provider) ProjectActive(project string) bool {
return project == ""
}
// CleanSSH implements vm.Provider, is a no-op, and returns nil.
func (p *Provider) CleanSSH(l *logger.Logger) error {
return nil
}
// ConfigSSH is part of the vm.Provider interface and is a no-op.
func (p *Provider) ConfigSSH(l *logger.Logger, zones []string) error {
// On Azure, the SSH public key is set as part of VM instance creation.
return nil
}
func getAzureDefaultLabelMap(opts vm.CreateOpts) map[string]string {
m := vm.GetDefaultLabelMap(opts)
m[vm.TagCreated] = timeutil.Now().Format(time.RFC3339)
return m
}
func (p *Provider) AddLabels(l *logger.Logger, vms vm.List, labels map[string]string) error {
l.Printf("adding labels to Azure VMs not yet supported")
return nil
}
func (p *Provider) RemoveLabels(l *logger.Logger, vms vm.List, labels []string) error {
l.Printf("removing labels from Azure VMs not yet supported")
return nil
}
// Create implements vm.Provider.
func (p *Provider) Create(
l *logger.Logger, names []string, opts vm.CreateOpts, vmProviderOpts vm.ProviderOpts,
) error {
providerOpts := vmProviderOpts.(*ProviderOpts)
// Load the user's SSH public key to configure the resulting VMs.
var sshKey string
sshFile := os.ExpandEnv("${HOME}/.ssh/id_rsa.pub")
if _, err := os.Stat(sshFile); err == nil {
if bytes, err := os.ReadFile(sshFile); err == nil {
sshKey = string(bytes)
} else {
return errors.Wrapf(err, "could not read SSH public key file")
}
} else {
return errors.Wrapf(err, "could not find SSH public key file")
}
m := getAzureDefaultLabelMap(opts)
clusterTags := make(map[string]*string)
for key, value := range opts.CustomLabels {
_, ok := m[strings.ToLower(key)]
if ok {
return fmt.Errorf("duplicate label name defined: %s", key)
}
clusterTags[key] = to.StringPtr(value)
}
for key, value := range m {
clusterTags[key] = to.StringPtr(value)
}
getClusterResourceGroupName := func(location string) string {
return fmt.Sprintf("%s-%s", opts.ClusterName, location)
}
ctx, cancel := context.WithTimeout(context.Background(), p.OperationTimeout)
defer cancel()
if len(providerOpts.Locations) == 0 {
if opts.GeoDistributed {
providerOpts.Locations = defaultLocations
} else {
providerOpts.Locations = []string{defaultLocations[0]}
}
}
if len(providerOpts.Zone) == 0 {
providerOpts.Zone = defaultZone
}
if _, err := p.createVNets(l, ctx, providerOpts.Locations, *providerOpts); err != nil {
return err
}
// Effectively a map of node number to location.
nodeLocations := vm.ZonePlacement(len(providerOpts.Locations), len(names))
// Invert it.
nodesByLocIdx := make(map[int][]int, len(providerOpts.Locations))
for nodeIdx, locIdx := range nodeLocations {
nodesByLocIdx[locIdx] = append(nodesByLocIdx[locIdx], nodeIdx)
}
errs, _ := errgroup.WithContext(ctx)
for locIdx, nodes := range nodesByLocIdx {
// Shadow variables for closure.
locIdx := locIdx
nodes := nodes
errs.Go(func() error {
location := providerOpts.Locations[locIdx]
// Create a resource group within the location.
group, err := p.getOrCreateResourceGroup(ctx, getClusterResourceGroupName(location), location, clusterTags)
if err != nil {
return err
}
subnet, ok := func() (network.Subnet, bool) {
p.mu.Lock()
defer p.mu.Unlock()
s, ok := p.mu.subnets[location]
return s, ok
}()
if !ok {
return errors.Errorf("missing subnet for location %q", location)
}
for _, nodeIdx := range nodes {
name := names[nodeIdx]
errs.Go(func() error {
_, err := p.createVM(l, ctx, group, subnet, name, sshKey, opts, *providerOpts)
err = errors.Wrapf(err, "creating VM %s", name)
if err == nil {
l.Printf("created VM %s", name)
}
return err
})
}
return nil
})
}
return errs.Wait()
}
// Delete implements the vm.Provider interface.
func (p *Provider) Delete(l *logger.Logger, vms vm.List) error {
ctx, cancel := context.WithTimeout(context.Background(), p.OperationTimeout)
defer cancel()
sub, err := p.getSubscription(ctx)
if err != nil {
return err
}
client := compute.NewVirtualMachinesClient(sub)
if client.Authorizer, err = p.getAuthorizer(); err != nil {
return err
}
var futures []compute.VirtualMachinesDeleteFuture
for _, vm := range vms {
parts, err := parseAzureID(vm.ProviderID)
if err != nil {
return err
}
future, err := client.Delete(ctx, parts.resourceGroup, parts.resourceName, nil)
if err != nil {
return errors.Wrapf(err, "could not delete %s", vm.ProviderID)
}
futures = append(futures, future)
}
if !p.SyncDelete {
return nil
}
for _, future := range futures {
if err := future.WaitForCompletionRef(ctx, client.Client); err != nil {
return err
}
if _, err := future.Result(client); err != nil {
return err
}
}
return nil
}
// Reset implements the vm.Provider interface. It is a no-op.
func (p *Provider) Reset(l *logger.Logger, vms vm.List) error {
return nil
}
// DeleteCluster implements the vm.DeleteCluster interface, providing
// a fast-path to tear down all resources associated with a cluster.
func (p *Provider) DeleteCluster(l *logger.Logger, name string) error {
ctx, cancel := context.WithTimeout(context.Background(), p.OperationTimeout)
defer cancel()
sub, err := p.getSubscription(ctx)
if err != nil {
return err
}
client := resources.NewGroupsClient(sub)
if client.Authorizer, err = p.getAuthorizer(); err != nil {
return err
}
filter := fmt.Sprintf("tagName eq '%s' and tagValue eq '%s'", vm.TagCluster, name)
it, err := client.ListComplete(ctx, filter, nil /* limit */)
if err != nil {
return err
}
var futures []resources.GroupsDeleteFuture
for it.NotDone() {
group := it.Value()
// Don't bother waiting for the cluster to get torn down.
future, err := client.Delete(ctx, *group.Name)
if err != nil {
return err
}
l.Printf("marked Azure resource group %s for deletion\n", *group.Name)
futures = append(futures, future)
if err := it.NextWithContext(ctx); err != nil {
return err
}
}
if !p.SyncDelete {
return nil
}
for _, future := range futures {
if err := future.WaitForCompletionRef(ctx, client.Client); err != nil {
return err
}
if _, err := future.Result(client); err != nil {
return err
}
}
return nil
}
// Extend implements the vm.Provider interface.
func (p *Provider) Extend(l *logger.Logger, vms vm.List, lifetime time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), p.OperationTimeout)
defer cancel()
sub, err := p.getSubscription(ctx)
if err != nil {
return err
}
client := compute.NewVirtualMachinesClient(sub)
if client.Authorizer, err = p.getAuthorizer(); err != nil {
return err
}
futures := make([]compute.VirtualMachinesUpdateFuture, len(vms))
for idx, m := range vms {
vmParts, err := parseAzureID(m.ProviderID)
if err != nil {
return err
}
// N.B. VirtualMachineUpdate below overwrites _all_ VM tags. Hence, we must copy all unmodified tags.
tags := make(map[string]*string)
// Copy all known VM tags.
for k, v := range m.Labels {
tags[k] = to.StringPtr(v)
}
// Overwrite Lifetime tag.
tags[vm.TagLifetime] = to.StringPtr(lifetime.String())
update := compute.VirtualMachineUpdate{
Tags: tags,
}
futures[idx], err = client.Update(ctx, vmParts.resourceGroup, vmParts.resourceName, update)
if err != nil {
return err
}
}
for _, future := range futures {
if err := future.WaitForCompletionRef(ctx, client.Client); err != nil {
return err
}
if _, err := future.Result(client); err != nil {
return err
}
}
return nil
}
// FindActiveAccount implements vm.Provider.
func (p *Provider) FindActiveAccount(l *logger.Logger) (string, error) {
// It's a JSON Web Token, so we'll just dissect it enough to get the
// data that we want. There are three base64-encoded segments
// separated by periods. The second segment is the "claims" JSON
// object.
token, err := p.getAuthToken()
if err != nil {
return "", err
}
parts := strings.Split(token, ".")
if len(parts) != 3 {
return "", errors.Errorf("unexpected number of segments; expected 3, had %d", len(parts))
}
a := base64.NewDecoder(base64.RawStdEncoding, strings.NewReader(parts[1]))
var data struct {
Username string `json:"upn"`
}
if err := json.NewDecoder(a).Decode(&data); err != nil {
return "", errors.Wrapf(err, "could not decode JWT claims segment")
}
// If this is in an email address format, we just want the username.
username, _, _ := strings.Cut(data.Username, "@")
return username, nil
}
// List implements the vm.Provider interface. This will query all
// Azure VMs in the subscription and select those with a roachprod tag.
func (p *Provider) List(l *logger.Logger, opts vm.ListOptions) (vm.List, error) {
ctx, cancel := context.WithTimeout(context.Background(), p.OperationTimeout)
defer cancel()
sub, err := p.getSubscription(ctx)
if err != nil {
return nil, err
}
// We're just going to list all VMs and filter.
client := compute.NewVirtualMachinesClient(sub)
if client.Authorizer, err = p.getAuthorizer(); err != nil {
return nil, err
}
it, err := client.ListAllComplete(ctx, "false")
if err != nil {
return nil, err
}
// Keep track of which clusters we find through listing VMs.
// If later we need to list resource groups to find empty clusters,
// we want to make sure we don't add anything twice.
foundClusters := make(map[string]bool)
var ret vm.List
for it.NotDone() {
found := it.Value()
if _, ok := found.Tags[vm.TagRoachprod]; !ok {
if err := it.NextWithContext(ctx); err != nil {
return nil, err
}
continue
}
tags := make(map[string]string)
for key, value := range found.Tags {
tags[key] = *value
}
m := vm.VM{
Name: *found.Name,
Labels: tags,
Provider: ProviderName,
ProviderID: *found.ID,
RemoteUser: remoteUser,
VPC: "global",
MachineType: string(found.HardwareProfile.VMSize),
// We add a fake availability-zone suffix since other roachprod
// code assumes particular formats. For example, "eastus2z".
Zone: *found.Location + "z",
}
if createdPtr := found.Tags[vm.TagCreated]; createdPtr == nil {
m.Errors = append(m.Errors, vm.ErrNoExpiration)
} else if parsed, err := time.Parse(time.RFC3339, *createdPtr); err == nil {
m.CreatedAt = parsed
} else {
m.Errors = append(m.Errors, vm.ErrNoExpiration)
}
if lifetimePtr := found.Tags[vm.TagLifetime]; lifetimePtr == nil {
m.Errors = append(m.Errors, vm.ErrNoExpiration)
} else if parsed, err := time.ParseDuration(*lifetimePtr); err == nil {
m.Lifetime = parsed
} else {
m.Errors = append(m.Errors, vm.ErrNoExpiration)
}
// The network info needs a separate request.
nicID, err := parseAzureID(*(*found.NetworkProfile.NetworkInterfaces)[0].ID)
if err != nil {
return nil, err
}
if err := p.fillNetworkDetails(ctx, &m, nicID); errors.Is(err, vm.ErrBadNetwork) {
m.Errors = append(m.Errors, err)
} else if err != nil {
return nil, err
}
clusterName, _ := m.ClusterName()
foundClusters[clusterName] = true
ret = append(ret, m)
if err := it.NextWithContext(ctx); err != nil {
return nil, err
}
}
// Azure allows for clusters to exist even if the attached VM no longer exists.
// Such a cluster won't be found by listing all azure VMs like above.
// Normally we don't want to access these clusters except for deleting them.
if opts.IncludeEmptyClusters {
groupsClient := resources.NewGroupsClient(sub)
if groupsClient.Authorizer, err = p.getAuthorizer(); err != nil {
return nil, err
}
// List all resource groups for clusters under the subscription.
filter := fmt.Sprintf("tagName eq '%s'", vm.TagCluster)
it, err := groupsClient.ListComplete(ctx, filter, nil /* limit */)
if err != nil {
return nil, err
}
for it.NotDone() {
resourceGroup := it.Value()
if _, ok := resourceGroup.Tags[vm.TagRoachprod]; !ok {
if err := it.NextWithContext(ctx); err != nil {
return nil, err
}
continue
}
// Resource Groups have the name format "user-<clusterid>-<region>",
// while clusters have the name format "user-<clusterid>".
parts := strings.Split(*resourceGroup.Name, "-")
clusterName := strings.Join(parts[:len(parts)-1], "-")
if foundClusters[clusterName] {
if err := it.NextWithContext(ctx); err != nil {
return nil, err
}
continue
}
// The cluster does not have a VM, but roachprod assumes that this is not
// possible and implements providers on the VM level. A VM-less cluster will
// not have access to provider info or methods. To still allow this cluster to
// be deleted, we must create a fake VM, indicated by EmptyCluster.
m := vm.VM{
Name: *resourceGroup.Name,
Provider: ProviderName,
RemoteUser: remoteUser,
VPC: "global",
// We add a fake availability-zone suffix since other roachprod
// code assumes particular formats. For example, "eastus2z".
Zone: *resourceGroup.Location + "z",
EmptyCluster: true,
}
// We ignore any parsing errors here as roachprod tries to destroy "bad VMs".
// We don't want that since this is a fake VM, we need to destroy the resource
// group instead. This will be done by GC when it sees that no m.CreatedAt exists.
createdPtr := resourceGroup.Tags[vm.TagCreated]
if createdPtr != nil {
parsed, _ := time.Parse(time.RFC3339, *createdPtr)
m.CreatedAt = parsed
}
lifetimePtr := resourceGroup.Tags[vm.TagLifetime]
if lifetimePtr != nil {
parsed, _ := time.ParseDuration(*lifetimePtr)
m.Lifetime = parsed
}
ret = append(ret, m)
if err := it.NextWithContext(ctx); err != nil {
return nil, err
}
}
}
return ret, nil
}
// Name implements vm.Provider.
func (p *Provider) Name() string {
return ProviderName
}
func (p *Provider) createVM(
l *logger.Logger,
ctx context.Context,
group resources.Group,
subnet network.Subnet,
name, sshKey string,
opts vm.CreateOpts,
providerOpts ProviderOpts,
) (vm compute.VirtualMachine, err error) {
startupArgs := azureStartupArgs{RemoteUser: remoteUser}
if !opts.SSDOpts.UseLocalSSD {
// We define lun42 explicitly in the data disk request below.
lun := 42
startupArgs.AttachedDiskLun = &lun
}
startupScript, err := evalStartupTemplate(startupArgs)
if err != nil {
return vm, err
}
sub, err := p.getSubscription(ctx)
if err != nil {
return
}
client := compute.NewVirtualMachinesClient(sub)
if client.Authorizer, err = p.getAuthorizer(); err != nil {
return
}
// We first need to allocate a NIC to give the VM network access
ip, err := p.createIP(l, ctx, group, name, providerOpts)
if err != nil {
return
}
nic, err := p.createNIC(l, ctx, group, ip, subnet)
if err != nil {
return
}
tags := make(map[string]*string)
for key, value := range opts.CustomLabels {
tags[key] = to.StringPtr(value)
}
m := getAzureDefaultLabelMap(opts)
for key, value := range m {
tags[key] = to.StringPtr(value)
}
osVolumeSize := int32(opts.OsVolumeSize)
if osVolumeSize < 32 {
l.Printf("WARNING: increasing the OS volume size to minimally allowed 32GB")
osVolumeSize = 32
}
// Derived from
// https://github.com/Azure-Samples/azure-sdk-for-go-samples/blob/79e3f3af791c3873d810efe094f9d61e93a6ccaa/compute/vm.go#L41
vm = compute.VirtualMachine{
Location: group.Location,
Zones: to.StringSlicePtr([]string{providerOpts.Zone}),
Tags: tags,
VirtualMachineProperties: &compute.VirtualMachineProperties{
HardwareProfile: &compute.HardwareProfile{
VMSize: compute.VirtualMachineSizeTypes(providerOpts.MachineType),
},
StorageProfile: &compute.StorageProfile{
// From https://discourse.ubuntu.com/t/find-ubuntu-images-on-microsoft-azure/18918
// You can find available versions by running the following command:
// az vm image list --all --publisher Canonical
// To get the latest 20.04 version:
// az vm image list --all --publisher Canonical | \
// jq '[.[] | select(.sku=="20_04-lts")] | max_by(.version)'
ImageReference: &compute.ImageReference{
Publisher: to.StringPtr("Canonical"),
Offer: to.StringPtr("0001-com-ubuntu-server-focal"),
Sku: to.StringPtr("20_04-lts"),
Version: to.StringPtr("20.04.202109080"),
},
OsDisk: &compute.OSDisk{
CreateOption: compute.DiskCreateOptionTypesFromImage,
ManagedDisk: &compute.ManagedDiskParameters{
StorageAccountType: compute.StorageAccountTypesStandardSSDLRS,
},
DiskSizeGB: to.Int32Ptr(osVolumeSize),
},
},
OsProfile: &compute.OSProfile{
ComputerName: to.StringPtr(name),
AdminUsername: to.StringPtr(remoteUser),
// Per the docs, the cloud-init script should be uploaded already
// base64-encoded.
CustomData: to.StringPtr(startupScript),
LinuxConfiguration: &compute.LinuxConfiguration{
SSH: &compute.SSHConfiguration{
PublicKeys: &[]compute.SSHPublicKey{
{
Path: to.StringPtr(fmt.Sprintf("/home/%s/.ssh/authorized_keys", remoteUser)),
KeyData: to.StringPtr(sshKey),
},
},
},
},
},
NetworkProfile: &compute.NetworkProfile{
NetworkInterfaces: &[]compute.NetworkInterfaceReference{
{
ID: nic.ID,
NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
Primary: to.BoolPtr(true),
},
},
},
},
},
}
if !opts.SSDOpts.UseLocalSSD {
caching := compute.CachingTypesNone
switch providerOpts.DiskCaching {
case "read-only":
caching = compute.CachingTypesReadOnly
case "read-write":
caching = compute.CachingTypesReadWrite
case "none":
caching = compute.CachingTypesNone
default:
err = errors.Newf("unsupported caching behavior: %s", providerOpts.DiskCaching)
return
}
dataDisks := []compute.DataDisk{
{
DiskSizeGB: to.Int32Ptr(providerOpts.NetworkDiskSize),
Caching: caching,
Lun: to.Int32Ptr(42),
},
}
switch providerOpts.NetworkDiskType {
case "ultra-disk":
var ultraDisk compute.Disk
ultraDisk, err = p.createUltraDisk(l, ctx, group, name+"-ultra-disk", providerOpts)
if err != nil {
return
}
// UltraSSD specific disk configurations.
dataDisks[0].CreateOption = compute.DiskCreateOptionTypesAttach
dataDisks[0].Name = ultraDisk.Name
dataDisks[0].ManagedDisk = &compute.ManagedDiskParameters{
StorageAccountType: compute.StorageAccountTypesUltraSSDLRS,
ID: ultraDisk.ID,
}
// UltraSSDs must be enabled separately.
vm.AdditionalCapabilities = &compute.AdditionalCapabilities{
UltraSSDEnabled: to.BoolPtr(true),
}
case "premium-disk":
// premium-disk specific disk configurations.
dataDisks[0].CreateOption = compute.DiskCreateOptionTypesEmpty
dataDisks[0].ManagedDisk = &compute.ManagedDiskParameters{
StorageAccountType: compute.StorageAccountTypesPremiumLRS,
}
default:
err = errors.Newf("unsupported network disk type: %s", providerOpts.NetworkDiskType)
return
}
vm.StorageProfile.DataDisks = &dataDisks
}
future, err := client.CreateOrUpdate(ctx, *group.Name, name, vm)
if err != nil {
return
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return
}
return future.Result(client)
}
// createNIC creates a network adapter that is bound to the given public IP address.
func (p *Provider) createNIC(
l *logger.Logger,
ctx context.Context,
group resources.Group,
ip network.PublicIPAddress,
subnet network.Subnet,
) (iface network.Interface, err error) {
sub, err := p.getSubscription(ctx)
if err != nil {
return
}
client := network.NewInterfacesClient(sub)
if client.Authorizer, err = p.getAuthorizer(); err != nil {
return
}
_, sg := p.getResourcesAndSecurityGroupByName("", p.getVnetNetworkSecurityGroupName(*group.Location))
future, err := client.CreateOrUpdate(ctx, *group.Name, *ip.Name, network.Interface{
Name: ip.Name,
Location: group.Location,
InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
IPConfigurations: &[]network.InterfaceIPConfiguration{
{
Name: to.StringPtr("ipConfig"),
InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
Subnet: &subnet,
PrivateIPAllocationMethod: network.IPAllocationMethodDynamic,
PublicIPAddress: &ip,
},
},
},
NetworkSecurityGroup: &sg,
EnableAcceleratedNetworking: to.BoolPtr(true),
Primary: to.BoolPtr(true),
},
})
if err != nil {
return
}
if err = future.WaitForCompletionRef(ctx, client.Client); err != nil {
return
}
iface, err = future.Result(client)
if err == nil {
l.Printf("created NIC %s %s", *iface.Name, *(*iface.IPConfigurations)[0].PrivateIPAddress)
}
return
}
func (p *Provider) getOrCreateNetworkSecurityGroup(
ctx context.Context, name string, resourceGroup resources.Group,
) (network.SecurityGroup, error) {
group, ok := func() (network.SecurityGroup, bool) {
p.mu.Lock()
defer p.mu.Unlock()
g, ok := p.mu.securityGroups[name]
return g, ok
}()
if ok {
return group, nil
}
sub, err := p.getSubscription(ctx)
if err != nil {
return network.SecurityGroup{}, err
}
client := network.NewSecurityGroupsClient(sub)
if client.Authorizer, err = p.getAuthorizer(); err != nil {
return network.SecurityGroup{}, err
}
if client.Authorizer, err = p.getAuthorizer(); err != nil {
return network.SecurityGroup{}, err
}
cacheAndReturn := func(group network.SecurityGroup) (network.SecurityGroup, error) {
p.mu.Lock()
defer p.mu.Unlock()
p.mu.securityGroups[name] = group
return group, nil
}
future, err := client.CreateOrUpdate(ctx, *resourceGroup.Name, name, network.SecurityGroup{
SecurityGroupPropertiesFormat: &network.SecurityGroupPropertiesFormat{
SecurityRules: &[]network.SecurityRule{
{
Name: to.StringPtr("SSH_Inbound"),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Priority: to.Int32Ptr(300),
Protocol: network.SecurityRuleProtocolTCP,
Access: network.SecurityRuleAccessAllow,
Direction: network.SecurityRuleDirectionInbound,
SourceAddressPrefix: to.StringPtr("*"),
SourcePortRange: to.StringPtr("*"),
DestinationAddressPrefix: to.StringPtr("*"),
DestinationPortRange: to.StringPtr("22"),
},
},
{
Name: to.StringPtr("SSH_Outbound"),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Priority: to.Int32Ptr(301),
Protocol: network.SecurityRuleProtocolTCP,
Access: network.SecurityRuleAccessAllow,
Direction: network.SecurityRuleDirectionOutbound,
SourceAddressPrefix: to.StringPtr("*"),
SourcePortRange: to.StringPtr("*"),
DestinationAddressPrefix: to.StringPtr("*"),
DestinationPortRange: to.StringPtr("*"),
},
},
{
Name: to.StringPtr("HTTP_Inbound"),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Priority: to.Int32Ptr(320),
Protocol: network.SecurityRuleProtocolTCP,
Access: network.SecurityRuleAccessAllow,
Direction: network.SecurityRuleDirectionInbound,
SourceAddressPrefix: to.StringPtr("*"),
SourcePortRange: to.StringPtr("*"),
DestinationAddressPrefix: to.StringPtr("*"),
DestinationPortRange: to.StringPtr("80"),
},
},
{
Name: to.StringPtr("HTTP_Outbound"),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Priority: to.Int32Ptr(321),
Protocol: network.SecurityRuleProtocolTCP,
Access: network.SecurityRuleAccessAllow,
Direction: network.SecurityRuleDirectionOutbound,
SourceAddressPrefix: to.StringPtr("*"),
SourcePortRange: to.StringPtr("*"),
DestinationAddressPrefix: to.StringPtr("*"),
DestinationPortRange: to.StringPtr("*"),
},
},
{
Name: to.StringPtr("HTTPS_Inbound"),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Priority: to.Int32Ptr(340),
Protocol: network.SecurityRuleProtocolTCP,
Access: network.SecurityRuleAccessAllow,
Direction: network.SecurityRuleDirectionInbound,
SourceAddressPrefix: to.StringPtr("*"),
SourcePortRange: to.StringPtr("*"),
DestinationAddressPrefix: to.StringPtr("*"),
DestinationPortRange: to.StringPtr("443"),
},
},
{
Name: to.StringPtr("HTTPS_Outbound"),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Priority: to.Int32Ptr(341),
Protocol: network.SecurityRuleProtocolTCP,
Access: network.SecurityRuleAccessAllow,
Direction: network.SecurityRuleDirectionOutbound,
SourceAddressPrefix: to.StringPtr("*"),
SourcePortRange: to.StringPtr("*"),
DestinationAddressPrefix: to.StringPtr("*"),
DestinationPortRange: to.StringPtr("*"),
},
},
{
Name: to.StringPtr("CockroachPG_Inbound"),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Priority: to.Int32Ptr(342),
Protocol: network.SecurityRuleProtocolTCP,
Access: network.SecurityRuleAccessAllow,
Direction: network.SecurityRuleDirectionInbound,
SourceAddressPrefix: to.StringPtr("*"),
SourcePortRange: to.StringPtr("*"),
DestinationAddressPrefix: to.StringPtr("*"),
DestinationPortRange: to.StringPtr("26257"),
},
},
{
Name: to.StringPtr("CockroachAdmin_Inbound"),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Priority: to.Int32Ptr(343),
Protocol: network.SecurityRuleProtocolTCP,
Access: network.SecurityRuleAccessAllow,
Direction: network.SecurityRuleDirectionInbound,
SourceAddressPrefix: to.StringPtr("*"),
SourcePortRange: to.StringPtr("*"),
DestinationAddressPrefix: to.StringPtr("*"),
DestinationPortRange: to.StringPtr("26258"),
},
},
{
Name: to.StringPtr("Grafana_Inbound"),
SecurityRulePropertiesFormat: &network.SecurityRulePropertiesFormat{
Priority: to.Int32Ptr(344),
Protocol: network.SecurityRuleProtocolTCP,