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 {
267 tags["dispatch-"+k] = &v
270 tags["dispatch-instance-type"] = &instanceType.Name
272 nicParameters := network.Interface{
273 Location: &az.azconfig.Location,
275 InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
276 IPConfigurations: &[]network.InterfaceIPConfiguration{
277 network.InterfaceIPConfiguration{
278 Name: to.StringPtr("ip1"),
279 InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
280 Subnet: &network.Subnet{
281 ID: to.StringPtr(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers"+
282 "/Microsoft.Network/virtualnetworks/%s/subnets/%s",
283 az.azconfig.SubscriptionID,
284 az.azconfig.ResourceGroup,
286 az.azconfig.Subnet)),
288 PrivateIPAllocationMethod: network.Dynamic,
294 nic, err := az.netClient.CreateOrUpdate(ctx, az.azconfig.ResourceGroup, name+"-nic", nicParameters)
296 return nil, WrapAzureError(err)
299 log.Printf("Created NIC %v", *nic.ID)
301 instance_vhd := fmt.Sprintf("https://%s.blob.%s/%s/%s-os.vhd",
302 az.azconfig.StorageAccount,
303 az.azureEnv.StorageEndpointSuffix,
304 az.azconfig.BlobContainer,
307 log.Printf("URI instance vhd %v", instance_vhd)
309 customData := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(`#!/bin/sh
310 echo '%s-%s' > /home/crunch/node-token`, name, newTags["node-token"])))
312 vmParameters := compute.VirtualMachine{
313 Location: &az.azconfig.Location,
315 VirtualMachineProperties: &compute.VirtualMachineProperties{
316 HardwareProfile: &compute.HardwareProfile{
317 VMSize: compute.VirtualMachineSizeTypes(instanceType.ProviderType),
319 StorageProfile: &compute.StorageProfile{
320 OsDisk: &compute.OSDisk{
321 OsType: compute.Linux,
322 Name: to.StringPtr(name + "-os"),
323 CreateOption: compute.FromImage,
324 Image: &compute.VirtualHardDisk{
325 URI: to.StringPtr(string(imageId)),
327 Vhd: &compute.VirtualHardDisk{
332 NetworkProfile: &compute.NetworkProfile{
333 NetworkInterfaces: &[]compute.NetworkInterfaceReference{
334 compute.NetworkInterfaceReference{
336 NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
337 Primary: to.BoolPtr(true),
342 OsProfile: &compute.OSProfile{
344 AdminUsername: to.StringPtr("crunch"),
345 LinuxConfiguration: &compute.LinuxConfiguration{
346 DisablePasswordAuthentication: to.BoolPtr(true),
347 SSH: &compute.SSHConfiguration{
348 PublicKeys: &[]compute.SSHPublicKey{
349 compute.SSHPublicKey{
350 Path: to.StringPtr("/home/crunch/.ssh/authorized_keys"),
351 KeyData: to.StringPtr(string(ssh.MarshalAuthorizedKey(publicKey))),
356 CustomData: &customData,
361 vm, err := az.vmClient.CreateOrUpdate(ctx, az.azconfig.ResourceGroup, name, vmParameters)
363 return nil, WrapAzureError(err)
366 return &AzureInstance{
373 func (az *AzureProvider) Instances(ctx context.Context) ([]Instance, error) {
374 interfaces, err := az.ManageNics(ctx)
379 result, err := az.vmClient.ListComplete(ctx, az.azconfig.ResourceGroup)
381 return nil, WrapAzureError(err)
384 instances := make([]Instance, 0)
386 for ; result.NotDone(); err = result.Next() {
388 return nil, WrapAzureError(err)
390 if strings.HasPrefix(*result.Value().Name, az.namePrefix) {
391 instances = append(instances, &AzureInstance{
394 nic: interfaces[*(*result.Value().NetworkProfile.NetworkInterfaces)[0].ID]})
397 return instances, nil
400 func (az *AzureProvider) ManageNics(ctx context.Context) (map[string]network.Interface, error) {
401 result, err := az.netClient.ListComplete(ctx, az.azconfig.ResourceGroup)
403 return nil, WrapAzureError(err)
406 interfaces := make(map[string]network.Interface)
408 timestamp := time.Now()
409 wg := sync.WaitGroup{}
410 deletechannel := make(chan string, 20)
415 for i := 0; i < 4; i += 1 {
418 nicname, ok := <-deletechannel
422 _, delerr := az.netClient.Delete(context.Background(), az.azconfig.ResourceGroup, nicname)
424 log.Printf("Error deleting %v: %v", nicname, delerr)
426 log.Printf("Deleted %v", nicname)
433 for ; result.NotDone(); err = result.Next() {
435 log.Printf("Error listing nics: %v", err)
436 return interfaces, nil
438 if strings.HasPrefix(*result.Value().Name, az.namePrefix) {
439 if result.Value().VirtualMachine != nil {
440 interfaces[*result.Value().ID] = result.Value()
442 if result.Value().Tags["created-at"] != nil {
443 created_at, err := time.Parse(time.RFC3339Nano, *result.Value().Tags["created-at"])
445 //log.Printf("found dangling NIC %v created %v seconds ago", *result.Value().Name, timestamp.Sub(created_at).Seconds())
446 if timestamp.Sub(created_at).Seconds() > az.azconfig.DeleteDanglingResourcesAfter {
447 log.Printf("Will delete %v because it is older than %v s", *result.Value().Name, az.azconfig.DeleteDanglingResourcesAfter)
449 deletechannel <- *result.Value().Name
456 return interfaces, nil
459 func (az *AzureProvider) ManageBlobs(ctx context.Context) {
460 result, err := az.storageAcctClient.ListKeys(ctx, az.azconfig.ResourceGroup, az.azconfig.StorageAccount)
462 log.Printf("Couldn't get account keys %v", err)
466 key1 := *(*result.Keys)[0].Value
467 client, err := storage.NewBasicClientOnSovereignCloud(az.azconfig.StorageAccount, key1, az.azureEnv)
469 log.Printf("Couldn't make client %v", err)
473 blobsvc := client.GetBlobService()
474 blobcont := blobsvc.GetContainerReference(az.azconfig.BlobContainer)
476 timestamp := time.Now()
477 wg := sync.WaitGroup{}
478 deletechannel := make(chan storage.Blob, 20)
483 for i := 0; i < 4; i += 1 {
486 blob, ok := <-deletechannel
490 err := blob.Delete(nil)
492 log.Printf("error deleting %v: %v", blob.Name, err)
494 log.Printf("Deleted blob %v", blob.Name)
501 page := storage.ListBlobsParameters{Prefix: az.namePrefix}
504 response, err := blobcont.ListBlobs(page)
506 log.Printf("Error listing blobs %v", err)
509 for _, b := range response.Blobs {
510 age := timestamp.Sub(time.Time(b.Properties.LastModified))
511 if b.Properties.BlobType == storage.BlobTypePage &&
512 b.Properties.LeaseState == "available" &&
513 b.Properties.LeaseStatus == "unlocked" &&
514 age.Seconds() > az.azconfig.DeleteDanglingResourcesAfter {
516 log.Printf("Blob %v is unlocked and not modified for %v seconds, will delete", b.Name, age.Seconds())
521 if response.NextMarker != "" {
522 page.Marker = response.NextMarker
529 func (az *AzureProvider) Stop() {
532 type AzureInstance struct {
533 provider *AzureProvider
534 nic network.Interface
535 vm compute.VirtualMachine
538 func (ai *AzureInstance) ID() InstanceID {
539 return InstanceID(*ai.vm.ID)
542 func (ai *AzureInstance) String() string {
546 func (ai *AzureInstance) SetTags(ctx context.Context, newTags InstanceTags) error {
547 tags := make(map[string]*string)
549 for k, v := range ai.vm.Tags {
550 if !strings.HasPrefix(k, "dispatch-") {
554 for k, v := range newTags {
555 tags["dispatch-"+k] = &v
558 vmParameters := compute.VirtualMachine{
559 Location: &ai.provider.azconfig.Location,
562 vm, err := ai.provider.vmClient.CreateOrUpdate(ctx, ai.provider.azconfig.ResourceGroup, *ai.vm.Name, vmParameters)
564 return WrapAzureError(err)
571 func (ai *AzureInstance) Tags(ctx context.Context) (InstanceTags, error) {
572 tags := make(map[string]string)
574 for k, v := range ai.vm.Tags {
575 if strings.HasPrefix(k, "dispatch-") {
583 func (ai *AzureInstance) Destroy(ctx context.Context) error {
584 _, err := ai.provider.vmClient.Delete(ctx, ai.provider.azconfig.ResourceGroup, *ai.vm.Name)
585 return WrapAzureError(err)
588 func (ai *AzureInstance) Address() string {
589 return *(*ai.nic.IPConfigurations)[0].PrivateIPAddress
592 func (ai *AzureInstance) VerifyPublicKey(ctx context.Context, receivedKey ssh.PublicKey, client *ssh.Client) error {
593 remoteFingerprint := ssh.FingerprintSHA256(receivedKey)
595 tags, _ := ai.Tags(ctx)
597 tg := tags["ssh-pubkey-fingerprint"]
599 if remoteFingerprint == tg {
602 return fmt.Errorf("Key fingerprint did not match")
606 sess, err := client.NewSession()
611 nodetoken, err := sess.Output("cat /home/crunch/node-token")
616 expectedToken := fmt.Sprintf("%s-%s", *ai.vm.Name, tags["node-token"])
617 log.Printf("%q %q", string(nodetoken), expectedToken)
619 if string(nodetoken) == expectedToken {
620 sess, err := client.NewSession()
625 keyfingerprintbytes, err := sess.Output("ssh-keygen -E sha256 -l -f /etc/ssh/ssh_host_rsa_key.pub")
630 sp := strings.Split(string(keyfingerprintbytes), " ")
632 log.Printf("%q %q", remoteFingerprint, sp[1])
634 if remoteFingerprint == sp[1] {
635 tags["ssh-pubkey-fingerprint"] = sp[1]
636 ai.SetTags(ctx, tags)
641 return fmt.Errorf("Key fingerprint did not match")