1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
19 "git.curoverse.com/arvados.git/sdk/go/arvados"
20 "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-06-01/compute"
21 "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-06-01/network"
22 storageacct "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2018-02-01/storage"
23 "github.com/Azure/azure-sdk-for-go/storage"
24 "github.com/Azure/go-autorest/autorest"
25 "github.com/Azure/go-autorest/autorest/azure"
26 "github.com/Azure/go-autorest/autorest/azure/auth"
27 "github.com/Azure/go-autorest/autorest/to"
28 "github.com/jmcvetta/randutil"
29 "github.com/mitchellh/mapstructure"
30 "golang.org/x/crypto/ssh"
33 type AzureInstanceSetConfig struct {
34 SubscriptionID string `mapstructure:"subscription_id"`
35 ClientID string `mapstructure:"key"`
36 ClientSecret string `mapstructure:"secret"`
37 TenantID string `mapstructure:"tenant_id"`
38 CloudEnv string `mapstructure:"cloud_environment"`
39 ResourceGroup string `mapstructure:"resource_group"`
40 Location string `mapstructure:"region"`
41 Network string `mapstructure:"network"`
42 Subnet string `mapstructure:"subnet"`
43 StorageAccount string `mapstructure:"storage_account"`
44 BlobContainer string `mapstructure:"blob_container"`
45 Image string `mapstructure:"image"`
46 DeleteDanglingResourcesAfter float64 `mapstructure:"delete_dangling_resources_after"`
49 type VirtualMachinesClientWrapper interface {
50 CreateOrUpdate(ctx context.Context,
51 resourceGroupName string,
53 parameters compute.VirtualMachine) (result compute.VirtualMachine, err error)
54 Delete(ctx context.Context, resourceGroupName string, VMName string) (result *http.Response, err error)
55 ListComplete(ctx context.Context, resourceGroupName string) (result compute.VirtualMachineListResultIterator, err error)
58 type VirtualMachinesClientImpl struct {
59 inner compute.VirtualMachinesClient
62 func (cl *VirtualMachinesClientImpl) CreateOrUpdate(ctx context.Context,
63 resourceGroupName string,
65 parameters compute.VirtualMachine) (result compute.VirtualMachine, err error) {
67 future, err := cl.inner.CreateOrUpdate(ctx, resourceGroupName, VMName, parameters)
69 return compute.VirtualMachine{}, WrapAzureError(err)
71 future.WaitForCompletionRef(ctx, cl.inner.Client)
72 r, err := future.Result(cl.inner)
73 return r, WrapAzureError(err)
76 func (cl *VirtualMachinesClientImpl) Delete(ctx context.Context, resourceGroupName string, VMName string) (result *http.Response, err error) {
77 future, err := cl.inner.Delete(ctx, resourceGroupName, VMName)
79 return nil, WrapAzureError(err)
81 err = future.WaitForCompletionRef(ctx, cl.inner.Client)
82 return future.Response(), WrapAzureError(err)
85 func (cl *VirtualMachinesClientImpl) ListComplete(ctx context.Context, resourceGroupName string) (result compute.VirtualMachineListResultIterator, err error) {
86 r, err := cl.inner.ListComplete(ctx, resourceGroupName)
87 return r, WrapAzureError(err)
90 type InterfacesClientWrapper interface {
91 CreateOrUpdate(ctx context.Context,
92 resourceGroupName string,
93 networkInterfaceName string,
94 parameters network.Interface) (result network.Interface, err error)
95 Delete(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result *http.Response, err error)
96 ListComplete(ctx context.Context, resourceGroupName string) (result network.InterfaceListResultIterator, err error)
99 type InterfacesClientImpl struct {
100 inner network.InterfacesClient
103 func (cl *InterfacesClientImpl) Delete(ctx context.Context, resourceGroupName string, VMName string) (result *http.Response, err error) {
104 future, err := cl.inner.Delete(ctx, resourceGroupName, VMName)
106 return nil, WrapAzureError(err)
108 err = future.WaitForCompletionRef(ctx, cl.inner.Client)
109 return future.Response(), WrapAzureError(err)
112 func (cl *InterfacesClientImpl) CreateOrUpdate(ctx context.Context,
113 resourceGroupName string,
114 networkInterfaceName string,
115 parameters network.Interface) (result network.Interface, err error) {
117 future, err := cl.inner.CreateOrUpdate(ctx, resourceGroupName, networkInterfaceName, parameters)
119 return network.Interface{}, WrapAzureError(err)
121 future.WaitForCompletionRef(ctx, cl.inner.Client)
122 r, err := future.Result(cl.inner)
123 return r, WrapAzureError(err)
126 func (cl *InterfacesClientImpl) ListComplete(ctx context.Context, resourceGroupName string) (result network.InterfaceListResultIterator, err error) {
127 r, err := cl.inner.ListComplete(ctx, resourceGroupName)
128 return r, WrapAzureError(err)
131 var quotaRe = regexp.MustCompile(`(?i:exceed|quota|limit)`)
133 type AzureRateLimitError struct {
135 earliestRetry time.Time
138 func (ar *AzureRateLimitError) EarliestRetry() time.Time {
139 return ar.earliestRetry
142 type AzureQuotaError struct {
146 func (ar *AzureQuotaError) IsQuotaError() bool {
150 func WrapAzureError(err error) error {
151 de, ok := err.(autorest.DetailedError)
155 rq, ok := de.Original.(*azure.RequestError)
159 if rq.Response == nil {
162 if rq.Response.StatusCode == 429 || len(rq.Response.Header["Retry-After"]) >= 1 {
164 ra := rq.Response.Header["Retry-After"][0]
165 earliestRetry, parseErr := http.ParseTime(ra)
167 // Could not parse as a timestamp, must be number of seconds
168 dur, parseErr := strconv.ParseInt(ra, 10, 64)
170 earliestRetry = time.Now().Add(time.Duration(dur) * time.Second)
174 // Couldn't make sense of retry-after,
175 // so set retry to 20 seconds
176 earliestRetry = time.Now().Add(20 * time.Second)
178 return &AzureRateLimitError{*rq, earliestRetry}
180 if rq.ServiceError == nil {
183 if quotaRe.FindString(rq.ServiceError.Code) != "" || quotaRe.FindString(rq.ServiceError.Message) != "" {
184 return &AzureQuotaError{*rq}
189 type AzureInstanceSet struct {
190 azconfig AzureInstanceSetConfig
191 vmClient VirtualMachinesClientWrapper
192 netClient InterfacesClientWrapper
193 storageAcctClient storageacct.AccountsClient
194 azureEnv azure.Environment
195 interfaces map[string]network.Interface
199 stopFunc context.CancelFunc
200 stopWg sync.WaitGroup
201 deleteNIC chan string
202 deleteBlob chan storage.Blob
205 func NewAzureInstanceSet(config map[string]interface{}, dispatcherID InstanceSetID) (prv InstanceSet, err error) {
206 azcfg := AzureInstanceSetConfig{}
207 if err = mapstructure.Decode(config, &azcfg); err != nil {
210 ap := AzureInstanceSet{}
211 err = ap.setup(azcfg, string(dispatcherID))
218 func (az *AzureInstanceSet) setup(azcfg AzureInstanceSetConfig, dispatcherID string) (err error) {
220 vmClient := compute.NewVirtualMachinesClient(az.azconfig.SubscriptionID)
221 netClient := network.NewInterfacesClient(az.azconfig.SubscriptionID)
222 storageAcctClient := storageacct.NewAccountsClient(az.azconfig.SubscriptionID)
224 az.azureEnv, err = azure.EnvironmentFromName(az.azconfig.CloudEnv)
229 authorizer, err := auth.ClientCredentialsConfig{
230 ClientID: az.azconfig.ClientID,
231 ClientSecret: az.azconfig.ClientSecret,
232 TenantID: az.azconfig.TenantID,
233 Resource: az.azureEnv.ResourceManagerEndpoint,
234 AADEndpoint: az.azureEnv.ActiveDirectoryEndpoint,
240 vmClient.Authorizer = authorizer
241 netClient.Authorizer = authorizer
242 storageAcctClient.Authorizer = authorizer
244 az.vmClient = &VirtualMachinesClientImpl{vmClient}
245 az.netClient = &InterfacesClientImpl{netClient}
246 az.storageAcctClient = storageAcctClient
248 az.dispatcherID = dispatcherID
249 az.namePrefix = fmt.Sprintf("compute-%s-", az.dispatcherID)
251 az.ctx, az.stopFunc = context.WithCancel(context.Background())
253 tk := time.NewTicker(5 * time.Minute)
256 case <-az.ctx.Done():
264 az.deleteNIC = make(chan string)
265 az.deleteBlob = make(chan storage.Blob)
267 for i := 0; i < 4; i += 1 {
270 nicname, ok := <-az.deleteNIC
274 _, delerr := az.netClient.Delete(context.Background(), az.azconfig.ResourceGroup, nicname)
276 log.Printf("Error deleting %v: %v", nicname, delerr)
278 log.Printf("Deleted %v", nicname)
284 blob, ok := <-az.deleteBlob
288 err := blob.Delete(nil)
290 log.Printf("error deleting %v: %v", blob.Name, err)
292 log.Printf("Deleted blob %v", blob.Name)
301 func (az *AzureInstanceSet) Create(
302 instanceType arvados.InstanceType,
304 newTags InstanceTags,
305 publicKey ssh.PublicKey) (Instance, error) {
308 defer az.stopWg.Done()
310 if len(newTags["node-token"]) == 0 {
311 return nil, fmt.Errorf("Must provide tag 'node-token'")
314 name, err := randutil.String(15, "abcdefghijklmnopqrstuvwxyz0123456789")
319 name = az.namePrefix + name
321 timestamp := time.Now().Format(time.RFC3339Nano)
323 tags := make(map[string]*string)
324 tags["created-at"] = ×tamp
325 for k, v := range newTags {
327 tags["dispatch-"+k] = &newstr
330 tags["dispatch-instance-type"] = &instanceType.Name
332 nicParameters := network.Interface{
333 Location: &az.azconfig.Location,
335 InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
336 IPConfigurations: &[]network.InterfaceIPConfiguration{
337 network.InterfaceIPConfiguration{
338 Name: to.StringPtr("ip1"),
339 InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
340 Subnet: &network.Subnet{
341 ID: to.StringPtr(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers"+
342 "/Microsoft.Network/virtualnetworks/%s/subnets/%s",
343 az.azconfig.SubscriptionID,
344 az.azconfig.ResourceGroup,
346 az.azconfig.Subnet)),
348 PrivateIPAllocationMethod: network.Dynamic,
354 nic, err := az.netClient.CreateOrUpdate(az.ctx, az.azconfig.ResourceGroup, name+"-nic", nicParameters)
356 return nil, WrapAzureError(err)
359 instance_vhd := fmt.Sprintf("https://%s.blob.%s/%s/%s-os.vhd",
360 az.azconfig.StorageAccount,
361 az.azureEnv.StorageEndpointSuffix,
362 az.azconfig.BlobContainer,
365 customData := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(`#!/bin/sh
366 echo '%s-%s' > /home/crunch/node-token`, name, newTags["node-token"])))
368 vmParameters := compute.VirtualMachine{
369 Location: &az.azconfig.Location,
371 VirtualMachineProperties: &compute.VirtualMachineProperties{
372 HardwareProfile: &compute.HardwareProfile{
373 VMSize: compute.VirtualMachineSizeTypes(instanceType.ProviderType),
375 StorageProfile: &compute.StorageProfile{
376 OsDisk: &compute.OSDisk{
377 OsType: compute.Linux,
378 Name: to.StringPtr(name + "-os"),
379 CreateOption: compute.FromImage,
380 Image: &compute.VirtualHardDisk{
381 URI: to.StringPtr(string(imageId)),
383 Vhd: &compute.VirtualHardDisk{
388 NetworkProfile: &compute.NetworkProfile{
389 NetworkInterfaces: &[]compute.NetworkInterfaceReference{
390 compute.NetworkInterfaceReference{
392 NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
393 Primary: to.BoolPtr(true),
398 OsProfile: &compute.OSProfile{
400 AdminUsername: to.StringPtr("crunch"),
401 LinuxConfiguration: &compute.LinuxConfiguration{
402 DisablePasswordAuthentication: to.BoolPtr(true),
403 SSH: &compute.SSHConfiguration{
404 PublicKeys: &[]compute.SSHPublicKey{
405 compute.SSHPublicKey{
406 Path: to.StringPtr("/home/crunch/.ssh/authorized_keys"),
407 KeyData: to.StringPtr(string(ssh.MarshalAuthorizedKey(publicKey))),
412 CustomData: &customData,
417 vm, err := az.vmClient.CreateOrUpdate(az.ctx, az.azconfig.ResourceGroup, name, vmParameters)
419 return nil, WrapAzureError(err)
422 return &AzureInstance{
429 func (az *AzureInstanceSet) Instances(InstanceTags) ([]Instance, error) {
431 defer az.stopWg.Done()
433 interfaces, err := az.ManageNics()
438 result, err := az.vmClient.ListComplete(az.ctx, az.azconfig.ResourceGroup)
440 return nil, WrapAzureError(err)
443 instances := make([]Instance, 0)
445 for ; result.NotDone(); err = result.Next() {
447 return nil, WrapAzureError(err)
449 if strings.HasPrefix(*result.Value().Name, az.namePrefix) {
450 instances = append(instances, &AzureInstance{
453 nic: interfaces[*(*result.Value().NetworkProfile.NetworkInterfaces)[0].ID]})
456 return instances, nil
459 // ManageNics returns a list of Azure network interface resources.
460 // Also performs garbage collection of NICs which have "namePrefix", are
461 // not associated with a virtual machine and have a "create-at" time
462 // more than DeleteDanglingResourcesAfter (to prevent racing and
463 // deleting newly created NICs) in the past are deleted.
464 func (az *AzureInstanceSet) ManageNics() (map[string]network.Interface, error) {
466 defer az.stopWg.Done()
468 result, err := az.netClient.ListComplete(az.ctx, az.azconfig.ResourceGroup)
470 return nil, WrapAzureError(err)
473 interfaces := make(map[string]network.Interface)
475 timestamp := time.Now()
476 for ; result.NotDone(); err = result.Next() {
478 log.Printf("Error listing nics: %v", err)
479 return interfaces, nil
481 if strings.HasPrefix(*result.Value().Name, az.namePrefix) {
482 if result.Value().VirtualMachine != nil {
483 interfaces[*result.Value().ID] = result.Value()
485 if result.Value().Tags["created-at"] != nil {
486 created_at, err := time.Parse(time.RFC3339Nano, *result.Value().Tags["created-at"])
488 if timestamp.Sub(created_at).Seconds() > az.azconfig.DeleteDanglingResourcesAfter {
489 log.Printf("Will delete %v because it is older than %v s", *result.Value().Name, az.azconfig.DeleteDanglingResourcesAfter)
490 az.deleteNIC <- *result.Value().Name
497 return interfaces, nil
500 // ManageBlobs garbage collects blobs (VM disk images) in the
501 // configured storage account container. It will delete blobs which
502 // have "namePrefix", are "available" (which means they are not
503 // leased to a VM) and haven't been modified for
504 // DeleteDanglingResourcesAfter seconds.
505 func (az *AzureInstanceSet) ManageBlobs() {
507 defer az.stopWg.Done()
509 result, err := az.storageAcctClient.ListKeys(az.ctx, az.azconfig.ResourceGroup, az.azconfig.StorageAccount)
511 log.Printf("Couldn't get account keys %v", err)
515 key1 := *(*result.Keys)[0].Value
516 client, err := storage.NewBasicClientOnSovereignCloud(az.azconfig.StorageAccount, key1, az.azureEnv)
518 log.Printf("Couldn't make client %v", err)
522 blobsvc := client.GetBlobService()
523 blobcont := blobsvc.GetContainerReference(az.azconfig.BlobContainer)
525 page := storage.ListBlobsParameters{Prefix: az.namePrefix}
526 timestamp := time.Now()
529 response, err := blobcont.ListBlobs(page)
531 log.Printf("Error listing blobs %v", err)
534 for _, b := range response.Blobs {
535 age := timestamp.Sub(time.Time(b.Properties.LastModified))
536 if b.Properties.BlobType == storage.BlobTypePage &&
537 b.Properties.LeaseState == "available" &&
538 b.Properties.LeaseStatus == "unlocked" &&
539 age.Seconds() > az.azconfig.DeleteDanglingResourcesAfter {
541 log.Printf("Blob %v is unlocked and not modified for %v seconds, will delete", b.Name, age.Seconds())
545 if response.NextMarker != "" {
546 page.Marker = response.NextMarker
553 func (az *AzureInstanceSet) Stop() {
560 type AzureInstance struct {
561 provider *AzureInstanceSet
562 nic network.Interface
563 vm compute.VirtualMachine
566 func (ai *AzureInstance) ID() InstanceID {
567 return InstanceID(*ai.vm.ID)
570 func (ai *AzureInstance) String() string {
574 func (ai *AzureInstance) ProviderType() string {
575 return string(ai.vm.VirtualMachineProperties.HardwareProfile.VMSize)
578 func (ai *AzureInstance) SetTags(newTags InstanceTags) error {
579 ai.provider.stopWg.Add(1)
580 defer ai.provider.stopWg.Done()
582 tags := make(map[string]*string)
584 for k, v := range ai.vm.Tags {
585 if !strings.HasPrefix(k, "dispatch-") {
589 for k, v := range newTags {
591 tags["dispatch-"+k] = &newstr
594 vmParameters := compute.VirtualMachine{
595 Location: &ai.provider.azconfig.Location,
598 vm, err := ai.provider.vmClient.CreateOrUpdate(ai.provider.ctx, ai.provider.azconfig.ResourceGroup, *ai.vm.Name, vmParameters)
600 return WrapAzureError(err)
607 func (ai *AzureInstance) Tags() InstanceTags {
608 tags := make(map[string]string)
610 for k, v := range ai.vm.Tags {
611 if strings.HasPrefix(k, "dispatch-") {
619 func (ai *AzureInstance) Destroy() error {
620 ai.provider.stopWg.Add(1)
621 defer ai.provider.stopWg.Done()
623 _, err := ai.provider.vmClient.Delete(ai.provider.ctx, ai.provider.azconfig.ResourceGroup, *ai.vm.Name)
624 return WrapAzureError(err)
627 func (ai *AzureInstance) Address() string {
628 return *(*ai.nic.IPConfigurations)[0].PrivateIPAddress
631 func (ai *AzureInstance) VerifyHostKey(receivedKey ssh.PublicKey, client *ssh.Client) error {
632 ai.provider.stopWg.Add(1)
633 defer ai.provider.stopWg.Done()
635 remoteFingerprint := ssh.FingerprintSHA256(receivedKey)
639 tg := tags["ssh-pubkey-fingerprint"]
641 if remoteFingerprint == tg {
644 return fmt.Errorf("Key fingerprint did not match, expected %q got %q", tg, remoteFingerprint)
648 nodetokenTag := tags["node-token"]
649 if nodetokenTag == "" {
650 return fmt.Errorf("Missing node token tag")
653 sess, err := client.NewSession()
658 nodetokenbytes, err := sess.Output("cat /home/crunch/node-token")
663 nodetoken := strings.TrimSpace(string(nodetokenbytes))
665 expectedToken := fmt.Sprintf("%s-%s", *ai.vm.Name, nodetokenTag)
667 if strings.TrimSpace(nodetoken) != expectedToken {
668 return fmt.Errorf("Node token did not match, expected %q got %q", expectedToken, nodetoken)
671 sess, err = client.NewSession()
676 keyfingerprintbytes, err := sess.Output("ssh-keygen -E sha256 -l -f /etc/ssh/ssh_host_rsa_key.pub")
681 sp := strings.Split(string(keyfingerprintbytes), " ")
683 if remoteFingerprint != sp[1] {
684 return fmt.Errorf("Key fingerprint did not match, expected %q got %q", sp[1], remoteFingerprint)
687 tags["ssh-pubkey-fingerprint"] = sp[1]
688 delete(tags, "node-token")