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 "golang.org/x/crypto/ssh"
32 type AzureProviderConfig struct {
33 SubscriptionID string `json:"subscription_id"`
34 ClientID string `json:"key"`
35 ClientSecret string `json:"secret"`
36 TenantID string `json:"tenant_id"`
37 CloudEnv string `json:"cloud_environment"`
38 ResourceGroup string `json:"resource_group"`
39 Location string `json:"region"`
40 Network string `json:"network"`
41 Subnet string `json:"subnet"`
42 StorageAccount string `json:"storage_account"`
43 BlobContainer string `json:"blob_container"`
44 Image string `json:"image"`
45 DeleteDanglingResourcesAfter float64 `json:"delete_dangling_resources_after"`
48 type VirtualMachinesClientWrapper interface {
49 CreateOrUpdate(ctx context.Context,
50 resourceGroupName string,
52 parameters compute.VirtualMachine) (result compute.VirtualMachine, err error)
53 Delete(ctx context.Context, resourceGroupName string, VMName string) (result *http.Response, err error)
54 ListComplete(ctx context.Context, resourceGroupName string) (result compute.VirtualMachineListResultIterator, err error)
57 type VirtualMachinesClientImpl struct {
58 inner compute.VirtualMachinesClient
61 func (cl *VirtualMachinesClientImpl) CreateOrUpdate(ctx context.Context,
62 resourceGroupName string,
64 parameters compute.VirtualMachine) (result compute.VirtualMachine, err error) {
66 future, err := cl.inner.CreateOrUpdate(ctx, resourceGroupName, VMName, parameters)
68 return compute.VirtualMachine{}, WrapAzureError(err)
70 future.WaitForCompletionRef(ctx, cl.inner.Client)
71 r, err := future.Result(cl.inner)
72 return r, WrapAzureError(err)
75 func (cl *VirtualMachinesClientImpl) Delete(ctx context.Context, resourceGroupName string, VMName string) (result *http.Response, err error) {
76 future, err := cl.inner.Delete(ctx, resourceGroupName, VMName)
78 return nil, WrapAzureError(err)
80 err = future.WaitForCompletionRef(ctx, cl.inner.Client)
81 return future.Response(), WrapAzureError(err)
84 func (cl *VirtualMachinesClientImpl) ListComplete(ctx context.Context, resourceGroupName string) (result compute.VirtualMachineListResultIterator, err error) {
85 r, err := cl.inner.ListComplete(ctx, resourceGroupName)
86 return r, WrapAzureError(err)
89 type InterfacesClientWrapper interface {
90 CreateOrUpdate(ctx context.Context,
91 resourceGroupName string,
92 networkInterfaceName string,
93 parameters network.Interface) (result network.Interface, err error)
94 Delete(ctx context.Context, resourceGroupName string, networkInterfaceName string) (result *http.Response, err error)
95 ListComplete(ctx context.Context, resourceGroupName string) (result network.InterfaceListResultIterator, err error)
98 type InterfacesClientImpl struct {
99 inner network.InterfacesClient
102 func (cl *InterfacesClientImpl) Delete(ctx context.Context, resourceGroupName string, VMName string) (result *http.Response, err error) {
103 future, err := cl.inner.Delete(ctx, resourceGroupName, VMName)
105 return nil, WrapAzureError(err)
107 err = future.WaitForCompletionRef(ctx, cl.inner.Client)
108 return future.Response(), WrapAzureError(err)
111 func (cl *InterfacesClientImpl) CreateOrUpdate(ctx context.Context,
112 resourceGroupName string,
113 networkInterfaceName string,
114 parameters network.Interface) (result network.Interface, err error) {
116 future, err := cl.inner.CreateOrUpdate(ctx, resourceGroupName, networkInterfaceName, parameters)
118 return network.Interface{}, WrapAzureError(err)
120 future.WaitForCompletionRef(ctx, cl.inner.Client)
121 r, err := future.Result(cl.inner)
122 return r, WrapAzureError(err)
125 func (cl *InterfacesClientImpl) ListComplete(ctx context.Context, resourceGroupName string) (result network.InterfaceListResultIterator, err error) {
126 r, err := cl.inner.ListComplete(ctx, resourceGroupName)
127 return r, WrapAzureError(err)
130 var quotaRe = regexp.MustCompile(`(?i:exceed|quota|limit)`)
132 type AzureRateLimitError struct {
134 earliestRetry time.Time
137 func (ar *AzureRateLimitError) EarliestRetry() time.Time {
138 return ar.earliestRetry
141 type AzureQuotaError struct {
145 func (ar *AzureQuotaError) IsQuotaError() bool {
149 func WrapAzureError(err error) error {
150 de, ok := err.(autorest.DetailedError)
154 rq, ok := de.Original.(*azure.RequestError)
158 if rq.Response == nil {
161 if rq.Response.StatusCode == 429 || len(rq.Response.Header["Retry-After"]) >= 1 {
163 ra := rq.Response.Header["Retry-After"][0]
164 earliestRetry, parseErr := http.ParseTime(ra)
166 // Could not parse as a timestamp, must be number of seconds
167 dur, parseErr := strconv.ParseInt(ra, 10, 64)
169 earliestRetry = time.Now().Add(time.Duration(dur) * time.Second)
173 // Couldn't make sense of retry-after,
174 // so set retry to 20 seconds
175 earliestRetry = time.Now().Add(20 * time.Second)
177 return &AzureRateLimitError{*rq, earliestRetry}
179 if rq.ServiceError == nil {
182 if quotaRe.FindString(rq.ServiceError.Code) != "" || quotaRe.FindString(rq.ServiceError.Message) != "" {
183 return &AzureQuotaError{*rq}
188 type AzureProvider struct {
189 azconfig AzureProviderConfig
190 vmClient VirtualMachinesClientWrapper
191 netClient InterfacesClientWrapper
192 storageAcctClient storageacct.AccountsClient
193 azureEnv azure.Environment
194 interfaces map[string]network.Interface
199 func NewAzureProvider(azcfg AzureProviderConfig, dispatcherID string) (prv InstanceProvider, err error) {
200 ap := AzureProvider{}
201 err = ap.setup(azcfg, dispatcherID)
208 func (az *AzureProvider) setup(azcfg AzureProviderConfig, dispatcherID string) (err error) {
210 vmClient := compute.NewVirtualMachinesClient(az.azconfig.SubscriptionID)
211 netClient := network.NewInterfacesClient(az.azconfig.SubscriptionID)
212 storageAcctClient := storageacct.NewAccountsClient(az.azconfig.SubscriptionID)
214 az.azureEnv, err = azure.EnvironmentFromName(az.azconfig.CloudEnv)
219 authorizer, err := auth.ClientCredentialsConfig{
220 ClientID: az.azconfig.ClientID,
221 ClientSecret: az.azconfig.ClientSecret,
222 TenantID: az.azconfig.TenantID,
223 Resource: az.azureEnv.ResourceManagerEndpoint,
224 AADEndpoint: az.azureEnv.ActiveDirectoryEndpoint,
230 vmClient.Authorizer = authorizer
231 netClient.Authorizer = authorizer
232 storageAcctClient.Authorizer = authorizer
234 az.vmClient = &VirtualMachinesClientImpl{vmClient}
235 az.netClient = &InterfacesClientImpl{netClient}
236 az.storageAcctClient = storageAcctClient
238 az.dispatcherID = dispatcherID
239 az.namePrefix = fmt.Sprintf("compute-%s-", az.dispatcherID)
244 func (az *AzureProvider) Create(ctx context.Context,
245 instanceType arvados.InstanceType,
247 newTags InstanceTags,
248 publicKey ssh.PublicKey) (Instance, error) {
250 if len(newTags["node-token"]) == 0 {
251 return nil, fmt.Errorf("Must provide tag 'node-token'")
254 name, err := randutil.String(15, "abcdefghijklmnopqrstuvwxyz0123456789")
259 name = az.namePrefix + name
260 log.Printf("name is %v", name)
262 timestamp := time.Now().Format(time.RFC3339Nano)
264 tags := make(map[string]*string)
265 tags["created-at"] = ×tamp
266 for k, v := range newTags {
268 tags["dispatch-"+k] = &newstr
271 tags["dispatch-instance-type"] = &instanceType.Name
273 nicParameters := network.Interface{
274 Location: &az.azconfig.Location,
276 InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
277 IPConfigurations: &[]network.InterfaceIPConfiguration{
278 network.InterfaceIPConfiguration{
279 Name: to.StringPtr("ip1"),
280 InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
281 Subnet: &network.Subnet{
282 ID: to.StringPtr(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers"+
283 "/Microsoft.Network/virtualnetworks/%s/subnets/%s",
284 az.azconfig.SubscriptionID,
285 az.azconfig.ResourceGroup,
287 az.azconfig.Subnet)),
289 PrivateIPAllocationMethod: network.Dynamic,
295 nic, err := az.netClient.CreateOrUpdate(ctx, az.azconfig.ResourceGroup, name+"-nic", nicParameters)
297 return nil, WrapAzureError(err)
300 log.Printf("Created NIC %v", *nic.ID)
302 instance_vhd := fmt.Sprintf("https://%s.blob.%s/%s/%s-os.vhd",
303 az.azconfig.StorageAccount,
304 az.azureEnv.StorageEndpointSuffix,
305 az.azconfig.BlobContainer,
308 log.Printf("URI instance vhd %v", instance_vhd)
310 customData := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(`#!/bin/sh
311 echo '%s-%s' > /home/crunch/node-token`, name, newTags["node-token"])))
313 vmParameters := compute.VirtualMachine{
314 Location: &az.azconfig.Location,
316 VirtualMachineProperties: &compute.VirtualMachineProperties{
317 HardwareProfile: &compute.HardwareProfile{
318 VMSize: compute.VirtualMachineSizeTypes(instanceType.ProviderType),
320 StorageProfile: &compute.StorageProfile{
321 OsDisk: &compute.OSDisk{
322 OsType: compute.Linux,
323 Name: to.StringPtr(name + "-os"),
324 CreateOption: compute.FromImage,
325 Image: &compute.VirtualHardDisk{
326 URI: to.StringPtr(string(imageId)),
328 Vhd: &compute.VirtualHardDisk{
333 NetworkProfile: &compute.NetworkProfile{
334 NetworkInterfaces: &[]compute.NetworkInterfaceReference{
335 compute.NetworkInterfaceReference{
337 NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
338 Primary: to.BoolPtr(true),
343 OsProfile: &compute.OSProfile{
345 AdminUsername: to.StringPtr("crunch"),
346 LinuxConfiguration: &compute.LinuxConfiguration{
347 DisablePasswordAuthentication: to.BoolPtr(true),
348 SSH: &compute.SSHConfiguration{
349 PublicKeys: &[]compute.SSHPublicKey{
350 compute.SSHPublicKey{
351 Path: to.StringPtr("/home/crunch/.ssh/authorized_keys"),
352 KeyData: to.StringPtr(string(ssh.MarshalAuthorizedKey(publicKey))),
357 CustomData: &customData,
362 vm, err := az.vmClient.CreateOrUpdate(ctx, az.azconfig.ResourceGroup, name, vmParameters)
364 return nil, WrapAzureError(err)
367 return &AzureInstance{
374 func (az *AzureProvider) Instances(ctx context.Context) ([]Instance, error) {
375 interfaces, err := az.ManageNics(ctx)
380 result, err := az.vmClient.ListComplete(ctx, az.azconfig.ResourceGroup)
382 return nil, WrapAzureError(err)
385 instances := make([]Instance, 0)
387 for ; result.NotDone(); err = result.Next() {
389 return nil, WrapAzureError(err)
391 if strings.HasPrefix(*result.Value().Name, az.namePrefix) {
392 instances = append(instances, &AzureInstance{
395 nic: interfaces[*(*result.Value().NetworkProfile.NetworkInterfaces)[0].ID]})
398 return instances, nil
401 func (az *AzureProvider) ManageNics(ctx context.Context) (map[string]network.Interface, error) {
402 result, err := az.netClient.ListComplete(ctx, az.azconfig.ResourceGroup)
404 return nil, WrapAzureError(err)
407 interfaces := make(map[string]network.Interface)
409 timestamp := time.Now()
410 wg := sync.WaitGroup{}
411 deletechannel := make(chan string, 20)
416 for i := 0; i < 4; i += 1 {
419 nicname, ok := <-deletechannel
423 _, delerr := az.netClient.Delete(context.Background(), az.azconfig.ResourceGroup, nicname)
425 log.Printf("Error deleting %v: %v", nicname, delerr)
427 log.Printf("Deleted %v", nicname)
434 for ; result.NotDone(); err = result.Next() {
436 log.Printf("Error listing nics: %v", err)
437 return interfaces, nil
439 if strings.HasPrefix(*result.Value().Name, az.namePrefix) {
440 if result.Value().VirtualMachine != nil {
441 interfaces[*result.Value().ID] = result.Value()
443 if result.Value().Tags["created-at"] != nil {
444 created_at, err := time.Parse(time.RFC3339Nano, *result.Value().Tags["created-at"])
446 //log.Printf("found dangling NIC %v created %v seconds ago", *result.Value().Name, timestamp.Sub(created_at).Seconds())
447 if timestamp.Sub(created_at).Seconds() > az.azconfig.DeleteDanglingResourcesAfter {
448 log.Printf("Will delete %v because it is older than %v s", *result.Value().Name, az.azconfig.DeleteDanglingResourcesAfter)
450 deletechannel <- *result.Value().Name
457 return interfaces, nil
460 func (az *AzureProvider) ManageBlobs(ctx context.Context) {
461 result, err := az.storageAcctClient.ListKeys(ctx, az.azconfig.ResourceGroup, az.azconfig.StorageAccount)
463 log.Printf("Couldn't get account keys %v", err)
467 key1 := *(*result.Keys)[0].Value
468 client, err := storage.NewBasicClientOnSovereignCloud(az.azconfig.StorageAccount, key1, az.azureEnv)
470 log.Printf("Couldn't make client %v", err)
474 blobsvc := client.GetBlobService()
475 blobcont := blobsvc.GetContainerReference(az.azconfig.BlobContainer)
477 timestamp := time.Now()
478 wg := sync.WaitGroup{}
479 deletechannel := make(chan storage.Blob, 20)
484 for i := 0; i < 4; i += 1 {
487 blob, ok := <-deletechannel
491 err := blob.Delete(nil)
493 log.Printf("error deleting %v: %v", blob.Name, err)
495 log.Printf("Deleted blob %v", blob.Name)
502 page := storage.ListBlobsParameters{Prefix: az.namePrefix}
505 response, err := blobcont.ListBlobs(page)
507 log.Printf("Error listing blobs %v", err)
510 for _, b := range response.Blobs {
511 age := timestamp.Sub(time.Time(b.Properties.LastModified))
512 if b.Properties.BlobType == storage.BlobTypePage &&
513 b.Properties.LeaseState == "available" &&
514 b.Properties.LeaseStatus == "unlocked" &&
515 age.Seconds() > az.azconfig.DeleteDanglingResourcesAfter {
517 log.Printf("Blob %v is unlocked and not modified for %v seconds, will delete", b.Name, age.Seconds())
522 if response.NextMarker != "" {
523 page.Marker = response.NextMarker
530 func (az *AzureProvider) Stop() {
533 type AzureInstance struct {
534 provider *AzureProvider
535 nic network.Interface
536 vm compute.VirtualMachine
539 func (ai *AzureInstance) ID() InstanceID {
540 return InstanceID(*ai.vm.ID)
543 func (ai *AzureInstance) String() string {
547 func (ai *AzureInstance) SetTags(ctx context.Context, newTags InstanceTags) error {
548 tags := make(map[string]*string)
550 for k, v := range ai.vm.Tags {
551 if !strings.HasPrefix(k, "dispatch-") {
555 for k, v := range newTags {
557 tags["dispatch-"+k] = &newstr
560 vmParameters := compute.VirtualMachine{
561 Location: &ai.provider.azconfig.Location,
564 vm, err := ai.provider.vmClient.CreateOrUpdate(ctx, ai.provider.azconfig.ResourceGroup, *ai.vm.Name, vmParameters)
566 return WrapAzureError(err)
573 func (ai *AzureInstance) Tags(ctx context.Context) (InstanceTags, error) {
574 tags := make(map[string]string)
576 for k, v := range ai.vm.Tags {
577 if strings.HasPrefix(k, "dispatch-") {
585 func (ai *AzureInstance) Destroy(ctx context.Context) error {
586 _, err := ai.provider.vmClient.Delete(ctx, ai.provider.azconfig.ResourceGroup, *ai.vm.Name)
587 return WrapAzureError(err)
590 func (ai *AzureInstance) Address() string {
591 return *(*ai.nic.IPConfigurations)[0].PrivateIPAddress
594 func (ai *AzureInstance) VerifyPublicKey(ctx context.Context, receivedKey ssh.PublicKey, client *ssh.Client) error {
595 remoteFingerprint := ssh.FingerprintSHA256(receivedKey)
597 tags, _ := ai.Tags(ctx)
599 tg := tags["ssh-pubkey-fingerprint"]
601 if remoteFingerprint == tg {
604 return fmt.Errorf("Key fingerprint did not match, expected %q got %q", tg, remoteFingerprint)
608 nodetokenTag := tags["node-token"]
609 if nodetokenTag == "" {
610 return fmt.Errorf("Missing node token tag")
613 sess, err := client.NewSession()
618 nodetokenbytes, err := sess.Output("cat /home/crunch/node-token")
623 nodetoken := strings.TrimSpace(string(nodetokenbytes))
625 expectedToken := fmt.Sprintf("%s-%s", *ai.vm.Name, nodetokenTag)
626 log.Printf("%q %q", nodetoken, expectedToken)
628 if strings.TrimSpace(nodetoken) != expectedToken {
629 return fmt.Errorf("Node token did not match, expected %q got %q", expectedToken, nodetoken)
632 sess, err = client.NewSession()
637 keyfingerprintbytes, err := sess.Output("ssh-keygen -E sha256 -l -f /etc/ssh/ssh_host_rsa_key.pub")
642 sp := strings.Split(string(keyfingerprintbytes), " ")
644 log.Printf("%q %q", remoteFingerprint, sp[1])
646 if remoteFingerprint != sp[1] {
647 return fmt.Errorf("Key fingerprint did not match, expected %q got %q", sp[1], remoteFingerprint)
650 tags["ssh-pubkey-fingerprint"] = sp[1]
651 delete(tags, "node-token")
652 ai.SetTags(ctx, tags)