1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
19 "git.curoverse.com/arvados.git/lib/cloud"
20 "git.curoverse.com/arvados.git/sdk/go/arvados"
21 "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-06-01/compute"
22 "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-06-01/network"
23 storageacct "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2018-02-01/storage"
24 "github.com/Azure/azure-sdk-for-go/storage"
25 "github.com/Azure/go-autorest/autorest"
26 "github.com/Azure/go-autorest/autorest/azure"
27 "github.com/Azure/go-autorest/autorest/azure/auth"
28 "github.com/Azure/go-autorest/autorest/to"
29 "github.com/jmcvetta/randutil"
30 "github.com/sirupsen/logrus"
31 "golang.org/x/crypto/ssh"
34 // Driver is the azure implementation of the cloud.Driver interface.
35 var Driver = cloud.DriverFunc(newAzureInstanceSet)
37 type azureInstanceSetConfig struct {
42 CloudEnvironment string
49 DeleteDanglingResourcesAfter arvados.Duration
53 const tagKeyInstanceSecret = "InstanceSecret"
55 type containerWrapper interface {
56 GetBlobReference(name string) *storage.Blob
57 ListBlobs(params storage.ListBlobsParameters) (storage.BlobListResponse, error)
60 type virtualMachinesClientWrapper interface {
61 createOrUpdate(ctx context.Context,
62 resourceGroupName string,
64 parameters compute.VirtualMachine) (result compute.VirtualMachine, err error)
65 delete(ctx context.Context, resourceGroupName string, VMName string) (result *http.Response, err error)
66 listComplete(ctx context.Context, resourceGroupName string) (result compute.VirtualMachineListResultIterator, err error)
69 type virtualMachinesClientImpl struct {
70 inner compute.VirtualMachinesClient
73 func (cl *virtualMachinesClientImpl) createOrUpdate(ctx context.Context,
74 resourceGroupName string,
76 parameters compute.VirtualMachine) (result compute.VirtualMachine, err error) {
78 future, err := cl.inner.CreateOrUpdate(ctx, resourceGroupName, VMName, parameters)
80 return compute.VirtualMachine{}, wrapAzureError(err)
82 future.WaitForCompletionRef(ctx, cl.inner.Client)
83 r, err := future.Result(cl.inner)
84 return r, wrapAzureError(err)
87 func (cl *virtualMachinesClientImpl) delete(ctx context.Context, resourceGroupName string, VMName string) (result *http.Response, err error) {
88 future, err := cl.inner.Delete(ctx, resourceGroupName, VMName)
90 return nil, wrapAzureError(err)
92 err = future.WaitForCompletionRef(ctx, cl.inner.Client)
93 return future.Response(), wrapAzureError(err)
96 func (cl *virtualMachinesClientImpl) listComplete(ctx context.Context, resourceGroupName string) (result compute.VirtualMachineListResultIterator, err error) {
97 r, err := cl.inner.ListComplete(ctx, resourceGroupName)
98 return r, wrapAzureError(err)
101 type interfacesClientWrapper interface {
102 createOrUpdate(ctx context.Context,
103 resourceGroupName string,
104 networkInterfaceName string,
105 parameters network.Interface) (result network.Interface, err error)
106 delete(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result *http.Response, err error)
107 listComplete(ctx context.Context, resourceGroupName string) (result network.InterfaceListResultIterator, err error)
110 type interfacesClientImpl struct {
111 inner network.InterfacesClient
114 func (cl *interfacesClientImpl) delete(ctx context.Context, resourceGroupName string, VMName string) (result *http.Response, err error) {
115 future, err := cl.inner.Delete(ctx, resourceGroupName, VMName)
117 return nil, wrapAzureError(err)
119 err = future.WaitForCompletionRef(ctx, cl.inner.Client)
120 return future.Response(), wrapAzureError(err)
123 func (cl *interfacesClientImpl) createOrUpdate(ctx context.Context,
124 resourceGroupName string,
125 networkInterfaceName string,
126 parameters network.Interface) (result network.Interface, err error) {
128 future, err := cl.inner.CreateOrUpdate(ctx, resourceGroupName, networkInterfaceName, parameters)
130 return network.Interface{}, wrapAzureError(err)
132 future.WaitForCompletionRef(ctx, cl.inner.Client)
133 r, err := future.Result(cl.inner)
134 return r, wrapAzureError(err)
137 func (cl *interfacesClientImpl) listComplete(ctx context.Context, resourceGroupName string) (result network.InterfaceListResultIterator, err error) {
138 r, err := cl.inner.ListComplete(ctx, resourceGroupName)
139 return r, wrapAzureError(err)
142 var quotaRe = regexp.MustCompile(`(?i:exceed|quota|limit)`)
144 type azureRateLimitError struct {
149 func (ar *azureRateLimitError) EarliestRetry() time.Time {
153 type azureQuotaError struct {
157 func (ar *azureQuotaError) IsQuotaError() bool {
161 func wrapAzureError(err error) error {
162 de, ok := err.(autorest.DetailedError)
166 rq, ok := de.Original.(*azure.RequestError)
170 if rq.Response == nil {
173 if rq.Response.StatusCode == 429 || len(rq.Response.Header["Retry-After"]) >= 1 {
175 ra := rq.Response.Header["Retry-After"][0]
176 earliestRetry, parseErr := http.ParseTime(ra)
178 // Could not parse as a timestamp, must be number of seconds
179 dur, parseErr := strconv.ParseInt(ra, 10, 64)
181 earliestRetry = time.Now().Add(time.Duration(dur) * time.Second)
183 // Couldn't make sense of retry-after,
184 // so set retry to 20 seconds
185 earliestRetry = time.Now().Add(20 * time.Second)
188 return &azureRateLimitError{*rq, earliestRetry}
190 if rq.ServiceError == nil {
193 if quotaRe.FindString(rq.ServiceError.Code) != "" || quotaRe.FindString(rq.ServiceError.Message) != "" {
194 return &azureQuotaError{*rq}
199 type azureInstanceSet struct {
200 azconfig azureInstanceSetConfig
201 vmClient virtualMachinesClientWrapper
202 netClient interfacesClientWrapper
203 blobcont containerWrapper
204 azureEnv azure.Environment
205 interfaces map[string]network.Interface
209 stopFunc context.CancelFunc
210 stopWg sync.WaitGroup
211 deleteNIC chan string
212 deleteBlob chan storage.Blob
213 logger logrus.FieldLogger
216 func newAzureInstanceSet(config json.RawMessage, dispatcherID cloud.InstanceSetID, logger logrus.FieldLogger) (prv cloud.InstanceSet, err error) {
217 azcfg := azureInstanceSetConfig{}
218 err = json.Unmarshal(config, &azcfg)
223 ap := azureInstanceSet{logger: logger}
224 err = ap.setup(azcfg, string(dispatcherID))
231 func (az *azureInstanceSet) setup(azcfg azureInstanceSetConfig, dispatcherID string) (err error) {
233 vmClient := compute.NewVirtualMachinesClient(az.azconfig.SubscriptionID)
234 netClient := network.NewInterfacesClient(az.azconfig.SubscriptionID)
235 storageAcctClient := storageacct.NewAccountsClient(az.azconfig.SubscriptionID)
237 az.azureEnv, err = azure.EnvironmentFromName(az.azconfig.CloudEnvironment)
242 authorizer, err := auth.ClientCredentialsConfig{
243 ClientID: az.azconfig.ClientID,
244 ClientSecret: az.azconfig.ClientSecret,
245 TenantID: az.azconfig.TenantID,
246 Resource: az.azureEnv.ResourceManagerEndpoint,
247 AADEndpoint: az.azureEnv.ActiveDirectoryEndpoint,
253 vmClient.Authorizer = authorizer
254 netClient.Authorizer = authorizer
255 storageAcctClient.Authorizer = authorizer
257 az.vmClient = &virtualMachinesClientImpl{vmClient}
258 az.netClient = &interfacesClientImpl{netClient}
260 result, err := storageAcctClient.ListKeys(az.ctx, az.azconfig.ResourceGroup, az.azconfig.StorageAccount)
262 az.logger.WithError(err).Warn("Couldn't get account keys")
266 key1 := *(*result.Keys)[0].Value
267 client, err := storage.NewBasicClientOnSovereignCloud(az.azconfig.StorageAccount, key1, az.azureEnv)
269 az.logger.WithError(err).Warn("Couldn't make client")
273 blobsvc := client.GetBlobService()
274 az.blobcont = blobsvc.GetContainerReference(az.azconfig.BlobContainer)
276 az.dispatcherID = dispatcherID
277 az.namePrefix = fmt.Sprintf("compute-%s-", az.dispatcherID)
279 az.ctx, az.stopFunc = context.WithCancel(context.Background())
282 defer az.stopWg.Done()
284 tk := time.NewTicker(5 * time.Minute)
287 case <-az.ctx.Done():
296 az.deleteNIC = make(chan string)
297 az.deleteBlob = make(chan storage.Blob)
299 for i := 0; i < 4; i++ {
302 nicname, ok := <-az.deleteNIC
306 _, delerr := az.netClient.delete(context.Background(), az.azconfig.ResourceGroup, nicname)
308 az.logger.WithError(delerr).Warnf("Error deleting %v", nicname)
310 az.logger.Printf("Deleted NIC %v", nicname)
316 blob, ok := <-az.deleteBlob
320 err := blob.Delete(nil)
322 az.logger.WithError(err).Warnf("Error deleting %v", blob.Name)
324 az.logger.Printf("Deleted blob %v", blob.Name)
333 func (az *azureInstanceSet) Create(
334 instanceType arvados.InstanceType,
335 imageID cloud.ImageID,
336 newTags cloud.InstanceTags,
337 initCommand cloud.InitCommand,
338 publicKey ssh.PublicKey) (cloud.Instance, error) {
341 defer az.stopWg.Done()
343 name, err := randutil.String(15, "abcdefghijklmnopqrstuvwxyz0123456789")
348 name = az.namePrefix + name
350 timestamp := time.Now().Format(time.RFC3339Nano)
352 tags := make(map[string]*string)
353 tags["created-at"] = ×tamp
354 for k, v := range newTags {
356 tags["dispatch-"+k] = &newstr
359 nicParameters := network.Interface{
360 Location: &az.azconfig.Location,
362 InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
363 IPConfigurations: &[]network.InterfaceIPConfiguration{
364 network.InterfaceIPConfiguration{
365 Name: to.StringPtr("ip1"),
366 InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
367 Subnet: &network.Subnet{
368 ID: to.StringPtr(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers"+
369 "/Microsoft.Network/virtualnetworks/%s/subnets/%s",
370 az.azconfig.SubscriptionID,
371 az.azconfig.ResourceGroup,
373 az.azconfig.Subnet)),
375 PrivateIPAllocationMethod: network.Dynamic,
381 nic, err := az.netClient.createOrUpdate(az.ctx, az.azconfig.ResourceGroup, name+"-nic", nicParameters)
383 return nil, wrapAzureError(err)
386 blobname := fmt.Sprintf("%s-os.vhd", name)
387 instanceVhd := fmt.Sprintf("https://%s.blob.%s/%s/%s",
388 az.azconfig.StorageAccount,
389 az.azureEnv.StorageEndpointSuffix,
390 az.azconfig.BlobContainer,
393 customData := base64.StdEncoding.EncodeToString([]byte("#!/bin/sh\n" + initCommand + "\n"))
395 vmParameters := compute.VirtualMachine{
396 Location: &az.azconfig.Location,
398 VirtualMachineProperties: &compute.VirtualMachineProperties{
399 HardwareProfile: &compute.HardwareProfile{
400 VMSize: compute.VirtualMachineSizeTypes(instanceType.ProviderType),
402 StorageProfile: &compute.StorageProfile{
403 OsDisk: &compute.OSDisk{
404 OsType: compute.Linux,
405 Name: to.StringPtr(name + "-os"),
406 CreateOption: compute.FromImage,
407 Image: &compute.VirtualHardDisk{
408 URI: to.StringPtr(string(imageID)),
410 Vhd: &compute.VirtualHardDisk{
415 NetworkProfile: &compute.NetworkProfile{
416 NetworkInterfaces: &[]compute.NetworkInterfaceReference{
417 compute.NetworkInterfaceReference{
419 NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
420 Primary: to.BoolPtr(true),
425 OsProfile: &compute.OSProfile{
427 AdminUsername: to.StringPtr(az.azconfig.AdminUsername),
428 LinuxConfiguration: &compute.LinuxConfiguration{
429 DisablePasswordAuthentication: to.BoolPtr(true),
430 SSH: &compute.SSHConfiguration{
431 PublicKeys: &[]compute.SSHPublicKey{
433 Path: to.StringPtr("/home/" + az.azconfig.AdminUsername + "/.ssh/authorized_keys"),
434 KeyData: to.StringPtr(string(ssh.MarshalAuthorizedKey(publicKey))),
439 CustomData: &customData,
444 vm, err := az.vmClient.createOrUpdate(az.ctx, az.azconfig.ResourceGroup, name, vmParameters)
446 _, delerr := az.blobcont.GetBlobReference(blobname).DeleteIfExists(nil)
448 az.logger.WithError(delerr).Warnf("Error cleaning up vhd blob after failed create")
451 _, delerr = az.netClient.delete(context.Background(), az.azconfig.ResourceGroup, *nic.Name)
453 az.logger.WithError(delerr).Warnf("Error cleaning up NIC after failed create")
456 return nil, wrapAzureError(err)
459 return &azureInstance{
466 func (az *azureInstanceSet) Instances(cloud.InstanceTags) ([]cloud.Instance, error) {
468 defer az.stopWg.Done()
470 interfaces, err := az.manageNics()
475 result, err := az.vmClient.listComplete(az.ctx, az.azconfig.ResourceGroup)
477 return nil, wrapAzureError(err)
480 instances := make([]cloud.Instance, 0)
482 for ; result.NotDone(); err = result.Next() {
484 return nil, wrapAzureError(err)
486 if strings.HasPrefix(*result.Value().Name, az.namePrefix) {
487 instances = append(instances, &azureInstance{
490 nic: interfaces[*(*result.Value().NetworkProfile.NetworkInterfaces)[0].ID]})
493 return instances, nil
496 // ManageNics returns a list of Azure network interface resources.
497 // Also performs garbage collection of NICs which have "namePrefix", are
498 // not associated with a virtual machine and have a "create-at" time
499 // more than DeleteDanglingResourcesAfter (to prevent racing and
500 // deleting newly created NICs) in the past are deleted.
501 func (az *azureInstanceSet) manageNics() (map[string]network.Interface, error) {
503 defer az.stopWg.Done()
505 result, err := az.netClient.listComplete(az.ctx, az.azconfig.ResourceGroup)
507 return nil, wrapAzureError(err)
510 interfaces := make(map[string]network.Interface)
512 timestamp := time.Now()
513 for ; result.NotDone(); err = result.Next() {
515 az.logger.WithError(err).Warnf("Error listing nics")
516 return interfaces, nil
518 if strings.HasPrefix(*result.Value().Name, az.namePrefix) {
519 if result.Value().VirtualMachine != nil {
520 interfaces[*result.Value().ID] = result.Value()
522 if result.Value().Tags["created-at"] != nil {
523 createdAt, err := time.Parse(time.RFC3339Nano, *result.Value().Tags["created-at"])
525 if timestamp.Sub(createdAt) > az.azconfig.DeleteDanglingResourcesAfter.Duration() {
526 az.logger.Printf("Will delete %v because it is older than %s", *result.Value().Name, az.azconfig.DeleteDanglingResourcesAfter)
527 az.deleteNIC <- *result.Value().Name
534 return interfaces, nil
537 // ManageBlobs garbage collects blobs (VM disk images) in the
538 // configured storage account container. It will delete blobs which
539 // have "namePrefix", are "available" (which means they are not
540 // leased to a VM) and haven't been modified for
541 // DeleteDanglingResourcesAfter seconds.
542 func (az *azureInstanceSet) manageBlobs() {
544 page := storage.ListBlobsParameters{Prefix: az.namePrefix}
545 timestamp := time.Now()
548 response, err := az.blobcont.ListBlobs(page)
550 az.logger.WithError(err).Warn("Error listing blobs")
553 for _, b := range response.Blobs {
554 age := timestamp.Sub(time.Time(b.Properties.LastModified))
555 if b.Properties.BlobType == storage.BlobTypePage &&
556 b.Properties.LeaseState == "available" &&
557 b.Properties.LeaseStatus == "unlocked" &&
558 age.Seconds() > az.azconfig.DeleteDanglingResourcesAfter.Duration().Seconds() {
560 az.logger.Printf("Blob %v is unlocked and not modified for %v seconds, will delete", b.Name, age.Seconds())
564 if response.NextMarker != "" {
565 page.Marker = response.NextMarker
572 func (az *azureInstanceSet) Stop() {
579 type azureInstance struct {
580 provider *azureInstanceSet
581 nic network.Interface
582 vm compute.VirtualMachine
585 func (ai *azureInstance) ID() cloud.InstanceID {
586 return cloud.InstanceID(*ai.vm.ID)
589 func (ai *azureInstance) String() string {
593 func (ai *azureInstance) ProviderType() string {
594 return string(ai.vm.VirtualMachineProperties.HardwareProfile.VMSize)
597 func (ai *azureInstance) SetTags(newTags cloud.InstanceTags) error {
598 ai.provider.stopWg.Add(1)
599 defer ai.provider.stopWg.Done()
601 tags := make(map[string]*string)
603 for k, v := range ai.vm.Tags {
604 if !strings.HasPrefix(k, "dispatch-") {
608 for k, v := range newTags {
610 tags["dispatch-"+k] = &newstr
613 vmParameters := compute.VirtualMachine{
614 Location: &ai.provider.azconfig.Location,
617 vm, err := ai.provider.vmClient.createOrUpdate(ai.provider.ctx, ai.provider.azconfig.ResourceGroup, *ai.vm.Name, vmParameters)
619 return wrapAzureError(err)
626 func (ai *azureInstance) Tags() cloud.InstanceTags {
627 tags := make(map[string]string)
629 for k, v := range ai.vm.Tags {
630 if strings.HasPrefix(k, "dispatch-") {
638 func (ai *azureInstance) Destroy() error {
639 ai.provider.stopWg.Add(1)
640 defer ai.provider.stopWg.Done()
642 _, err := ai.provider.vmClient.delete(ai.provider.ctx, ai.provider.azconfig.ResourceGroup, *ai.vm.Name)
643 return wrapAzureError(err)
646 func (ai *azureInstance) Address() string {
647 if ai.nic.IPConfigurations != nil &&
648 len(*ai.nic.IPConfigurations) > 0 &&
649 (*ai.nic.IPConfigurations)[0].PrivateIPAddress != nil {
651 return *(*ai.nic.IPConfigurations)[0].PrivateIPAddress
656 func (ai *azureInstance) RemoteUser() string {
657 return ai.provider.azconfig.AdminUsername
660 func (ai *azureInstance) VerifyHostKey(ssh.PublicKey, *ssh.Client) error {
661 return cloud.ErrNotImplemented