14324: Fix tests
[arvados.git] / lib / cloud / azure.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package cloud
6
7 import (
8         "context"
9         "encoding/base64"
10         "fmt"
11         "net/http"
12         "regexp"
13         "strconv"
14         "strings"
15         "sync"
16         "time"
17
18         "git.curoverse.com/arvados.git/sdk/go/arvados"
19         "github.com/Azure/azure-sdk-for-go/services/compute/mgmt/2018-06-01/compute"
20         "github.com/Azure/azure-sdk-for-go/services/network/mgmt/2018-06-01/network"
21         storageacct "github.com/Azure/azure-sdk-for-go/services/storage/mgmt/2018-02-01/storage"
22         "github.com/Azure/azure-sdk-for-go/storage"
23         "github.com/Azure/go-autorest/autorest"
24         "github.com/Azure/go-autorest/autorest/azure"
25         "github.com/Azure/go-autorest/autorest/azure/auth"
26         "github.com/Azure/go-autorest/autorest/to"
27         "github.com/jmcvetta/randutil"
28         "github.com/mitchellh/mapstructure"
29         "github.com/sirupsen/logrus"
30         "golang.org/x/crypto/ssh"
31 )
32
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"`
47 }
48
49 type VirtualMachinesClientWrapper interface {
50         CreateOrUpdate(ctx context.Context,
51                 resourceGroupName string,
52                 VMName 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)
56 }
57
58 type VirtualMachinesClientImpl struct {
59         inner compute.VirtualMachinesClient
60 }
61
62 func (cl *VirtualMachinesClientImpl) CreateOrUpdate(ctx context.Context,
63         resourceGroupName string,
64         VMName string,
65         parameters compute.VirtualMachine) (result compute.VirtualMachine, err error) {
66
67         future, err := cl.inner.CreateOrUpdate(ctx, resourceGroupName, VMName, parameters)
68         if err != nil {
69                 return compute.VirtualMachine{}, WrapAzureError(err)
70         }
71         future.WaitForCompletionRef(ctx, cl.inner.Client)
72         r, err := future.Result(cl.inner)
73         return r, WrapAzureError(err)
74 }
75
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)
78         if err != nil {
79                 return nil, WrapAzureError(err)
80         }
81         err = future.WaitForCompletionRef(ctx, cl.inner.Client)
82         return future.Response(), WrapAzureError(err)
83 }
84
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)
88 }
89
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)
97 }
98
99 type InterfacesClientImpl struct {
100         inner network.InterfacesClient
101 }
102
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)
105         if err != nil {
106                 return nil, WrapAzureError(err)
107         }
108         err = future.WaitForCompletionRef(ctx, cl.inner.Client)
109         return future.Response(), WrapAzureError(err)
110 }
111
112 func (cl *InterfacesClientImpl) CreateOrUpdate(ctx context.Context,
113         resourceGroupName string,
114         networkInterfaceName string,
115         parameters network.Interface) (result network.Interface, err error) {
116
117         future, err := cl.inner.CreateOrUpdate(ctx, resourceGroupName, networkInterfaceName, parameters)
118         if err != nil {
119                 return network.Interface{}, WrapAzureError(err)
120         }
121         future.WaitForCompletionRef(ctx, cl.inner.Client)
122         r, err := future.Result(cl.inner)
123         return r, WrapAzureError(err)
124 }
125
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)
129 }
130
131 var quotaRe = regexp.MustCompile(`(?i:exceed|quota|limit)`)
132
133 type AzureRateLimitError struct {
134         azure.RequestError
135         earliestRetry time.Time
136 }
137
138 func (ar *AzureRateLimitError) EarliestRetry() time.Time {
139         return ar.earliestRetry
140 }
141
142 type AzureQuotaError struct {
143         azure.RequestError
144 }
145
146 func (ar *AzureQuotaError) IsQuotaError() bool {
147         return true
148 }
149
150 func WrapAzureError(err error) error {
151         de, ok := err.(autorest.DetailedError)
152         if !ok {
153                 return err
154         }
155         rq, ok := de.Original.(*azure.RequestError)
156         if !ok {
157                 return err
158         }
159         if rq.Response == nil {
160                 return err
161         }
162         if rq.Response.StatusCode == 429 || len(rq.Response.Header["Retry-After"]) >= 1 {
163                 // API throttling
164                 ra := rq.Response.Header["Retry-After"][0]
165                 earliestRetry, parseErr := http.ParseTime(ra)
166                 if parseErr != nil {
167                         // Could not parse as a timestamp, must be number of seconds
168                         dur, parseErr := strconv.ParseInt(ra, 10, 64)
169                         if parseErr != nil {
170                                 earliestRetry = time.Now().Add(time.Duration(dur) * time.Second)
171                         }
172                 }
173                 if parseErr != nil {
174                         // Couldn't make sense of retry-after,
175                         // so set retry to 20 seconds
176                         earliestRetry = time.Now().Add(20 * time.Second)
177                 }
178                 return &AzureRateLimitError{*rq, earliestRetry}
179         }
180         if rq.ServiceError == nil {
181                 return err
182         }
183         if quotaRe.FindString(rq.ServiceError.Code) != "" || quotaRe.FindString(rq.ServiceError.Message) != "" {
184                 return &AzureQuotaError{*rq}
185         }
186         return err
187 }
188
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
196         dispatcherID      string
197         namePrefix        string
198         ctx               context.Context
199         stopFunc          context.CancelFunc
200         stopWg            sync.WaitGroup
201         deleteNIC         chan string
202         deleteBlob        chan storage.Blob
203         logger            logrus.FieldLogger
204 }
205
206 func NewAzureInstanceSet(config map[string]interface{}, dispatcherID InstanceSetID, logger logrus.FieldLogger) (prv InstanceSet, err error) {
207         azcfg := AzureInstanceSetConfig{}
208         if err = mapstructure.Decode(config, &azcfg); err != nil {
209                 return nil, err
210         }
211         ap := AzureInstanceSet{logger: logger}
212         err = ap.setup(azcfg, string(dispatcherID))
213         if err != nil {
214                 return nil, err
215         }
216         return &ap, nil
217 }
218
219 func (az *AzureInstanceSet) setup(azcfg AzureInstanceSetConfig, dispatcherID string) (err error) {
220         az.azconfig = azcfg
221         vmClient := compute.NewVirtualMachinesClient(az.azconfig.SubscriptionID)
222         netClient := network.NewInterfacesClient(az.azconfig.SubscriptionID)
223         storageAcctClient := storageacct.NewAccountsClient(az.azconfig.SubscriptionID)
224
225         az.azureEnv, err = azure.EnvironmentFromName(az.azconfig.CloudEnv)
226         if err != nil {
227                 return err
228         }
229
230         authorizer, err := auth.ClientCredentialsConfig{
231                 ClientID:     az.azconfig.ClientID,
232                 ClientSecret: az.azconfig.ClientSecret,
233                 TenantID:     az.azconfig.TenantID,
234                 Resource:     az.azureEnv.ResourceManagerEndpoint,
235                 AADEndpoint:  az.azureEnv.ActiveDirectoryEndpoint,
236         }.Authorizer()
237         if err != nil {
238                 return err
239         }
240
241         vmClient.Authorizer = authorizer
242         netClient.Authorizer = authorizer
243         storageAcctClient.Authorizer = authorizer
244
245         az.vmClient = &VirtualMachinesClientImpl{vmClient}
246         az.netClient = &InterfacesClientImpl{netClient}
247         az.storageAcctClient = storageAcctClient
248
249         az.dispatcherID = dispatcherID
250         az.namePrefix = fmt.Sprintf("compute-%s-", az.dispatcherID)
251
252         az.ctx, az.stopFunc = context.WithCancel(context.Background())
253         go func() {
254                 tk := time.NewTicker(5 * time.Minute)
255                 for {
256                         select {
257                         case <-az.ctx.Done():
258                                 return
259                         case <-tk.C:
260                                 az.ManageBlobs()
261                         }
262                 }
263         }()
264
265         az.deleteNIC = make(chan string)
266         az.deleteBlob = make(chan storage.Blob)
267
268         for i := 0; i < 4; i += 1 {
269                 go func() {
270                         for {
271                                 nicname, ok := <-az.deleteNIC
272                                 if !ok {
273                                         return
274                                 }
275                                 _, delerr := az.netClient.Delete(context.Background(), az.azconfig.ResourceGroup, nicname)
276                                 if delerr != nil {
277                                         az.logger.WithError(delerr).Warnf("Error deleting %v", nicname)
278                                 } else {
279                                         az.logger.Printf("Deleted NIC %v", nicname)
280                                 }
281                         }
282                 }()
283                 go func() {
284                         for {
285                                 blob, ok := <-az.deleteBlob
286                                 if !ok {
287                                         return
288                                 }
289                                 err := blob.Delete(nil)
290                                 if err != nil {
291                                         az.logger.WithError(err).Warnf("Error deleting %v", blob.Name)
292                                 } else {
293                                         az.logger.Printf("Deleted blob %v", blob.Name)
294                                 }
295                         }
296                 }()
297         }
298
299         return nil
300 }
301
302 func (az *AzureInstanceSet) Create(
303         instanceType arvados.InstanceType,
304         imageId ImageID,
305         newTags InstanceTags,
306         publicKey ssh.PublicKey) (Instance, error) {
307
308         az.stopWg.Add(1)
309         defer az.stopWg.Done()
310
311         if len(newTags["node-token"]) == 0 {
312                 return nil, fmt.Errorf("Must provide tag 'node-token'")
313         }
314
315         name, err := randutil.String(15, "abcdefghijklmnopqrstuvwxyz0123456789")
316         if err != nil {
317                 return nil, err
318         }
319
320         name = az.namePrefix + name
321
322         timestamp := time.Now().Format(time.RFC3339Nano)
323
324         tags := make(map[string]*string)
325         tags["created-at"] = &timestamp
326         for k, v := range newTags {
327                 newstr := v
328                 tags["dispatch-"+k] = &newstr
329         }
330
331         tags["dispatch-instance-type"] = &instanceType.Name
332
333         nicParameters := network.Interface{
334                 Location: &az.azconfig.Location,
335                 Tags:     tags,
336                 InterfacePropertiesFormat: &network.InterfacePropertiesFormat{
337                         IPConfigurations: &[]network.InterfaceIPConfiguration{
338                                 network.InterfaceIPConfiguration{
339                                         Name: to.StringPtr("ip1"),
340                                         InterfaceIPConfigurationPropertiesFormat: &network.InterfaceIPConfigurationPropertiesFormat{
341                                                 Subnet: &network.Subnet{
342                                                         ID: to.StringPtr(fmt.Sprintf("/subscriptions/%s/resourceGroups/%s/providers"+
343                                                                 "/Microsoft.Network/virtualnetworks/%s/subnets/%s",
344                                                                 az.azconfig.SubscriptionID,
345                                                                 az.azconfig.ResourceGroup,
346                                                                 az.azconfig.Network,
347                                                                 az.azconfig.Subnet)),
348                                                 },
349                                                 PrivateIPAllocationMethod: network.Dynamic,
350                                         },
351                                 },
352                         },
353                 },
354         }
355         nic, err := az.netClient.CreateOrUpdate(az.ctx, az.azconfig.ResourceGroup, name+"-nic", nicParameters)
356         if err != nil {
357                 return nil, WrapAzureError(err)
358         }
359
360         instance_vhd := fmt.Sprintf("https://%s.blob.%s/%s/%s-os.vhd",
361                 az.azconfig.StorageAccount,
362                 az.azureEnv.StorageEndpointSuffix,
363                 az.azconfig.BlobContainer,
364                 name)
365
366         customData := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(`#!/bin/sh
367 echo '%s-%s' > /home/crunch/node-token`, name, newTags["node-token"])))
368
369         vmParameters := compute.VirtualMachine{
370                 Location: &az.azconfig.Location,
371                 Tags:     tags,
372                 VirtualMachineProperties: &compute.VirtualMachineProperties{
373                         HardwareProfile: &compute.HardwareProfile{
374                                 VMSize: compute.VirtualMachineSizeTypes(instanceType.ProviderType),
375                         },
376                         StorageProfile: &compute.StorageProfile{
377                                 OsDisk: &compute.OSDisk{
378                                         OsType:       compute.Linux,
379                                         Name:         to.StringPtr(name + "-os"),
380                                         CreateOption: compute.FromImage,
381                                         Image: &compute.VirtualHardDisk{
382                                                 URI: to.StringPtr(string(imageId)),
383                                         },
384                                         Vhd: &compute.VirtualHardDisk{
385                                                 URI: &instance_vhd,
386                                         },
387                                 },
388                         },
389                         NetworkProfile: &compute.NetworkProfile{
390                                 NetworkInterfaces: &[]compute.NetworkInterfaceReference{
391                                         compute.NetworkInterfaceReference{
392                                                 ID: nic.ID,
393                                                 NetworkInterfaceReferenceProperties: &compute.NetworkInterfaceReferenceProperties{
394                                                         Primary: to.BoolPtr(true),
395                                                 },
396                                         },
397                                 },
398                         },
399                         OsProfile: &compute.OSProfile{
400                                 ComputerName:  &name,
401                                 AdminUsername: to.StringPtr("crunch"),
402                                 LinuxConfiguration: &compute.LinuxConfiguration{
403                                         DisablePasswordAuthentication: to.BoolPtr(true),
404                                         SSH: &compute.SSHConfiguration{
405                                                 PublicKeys: &[]compute.SSHPublicKey{
406                                                         compute.SSHPublicKey{
407                                                                 Path:    to.StringPtr("/home/crunch/.ssh/authorized_keys"),
408                                                                 KeyData: to.StringPtr(string(ssh.MarshalAuthorizedKey(publicKey))),
409                                                         },
410                                                 },
411                                         },
412                                 },
413                                 CustomData: &customData,
414                         },
415                 },
416         }
417
418         vm, err := az.vmClient.CreateOrUpdate(az.ctx, az.azconfig.ResourceGroup, name, vmParameters)
419         if err != nil {
420                 return nil, WrapAzureError(err)
421         }
422
423         return &AzureInstance{
424                 provider: az,
425                 nic:      nic,
426                 vm:       vm,
427         }, nil
428 }
429
430 func (az *AzureInstanceSet) Instances(InstanceTags) ([]Instance, error) {
431         az.stopWg.Add(1)
432         defer az.stopWg.Done()
433
434         interfaces, err := az.ManageNics()
435         if err != nil {
436                 return nil, err
437         }
438
439         result, err := az.vmClient.ListComplete(az.ctx, az.azconfig.ResourceGroup)
440         if err != nil {
441                 return nil, WrapAzureError(err)
442         }
443
444         instances := make([]Instance, 0)
445
446         for ; result.NotDone(); err = result.Next() {
447                 if err != nil {
448                         return nil, WrapAzureError(err)
449                 }
450                 if strings.HasPrefix(*result.Value().Name, az.namePrefix) {
451                         instances = append(instances, &AzureInstance{
452                                 provider: az,
453                                 vm:       result.Value(),
454                                 nic:      interfaces[*(*result.Value().NetworkProfile.NetworkInterfaces)[0].ID]})
455                 }
456         }
457         return instances, nil
458 }
459
460 // ManageNics returns a list of Azure network interface resources.
461 // Also performs garbage collection of NICs which have "namePrefix", are
462 // not associated with a virtual machine and have a "create-at" time
463 // more than DeleteDanglingResourcesAfter (to prevent racing and
464 // deleting newly created NICs) in the past are deleted.
465 func (az *AzureInstanceSet) ManageNics() (map[string]network.Interface, error) {
466         az.stopWg.Add(1)
467         defer az.stopWg.Done()
468
469         result, err := az.netClient.ListComplete(az.ctx, az.azconfig.ResourceGroup)
470         if err != nil {
471                 return nil, WrapAzureError(err)
472         }
473
474         interfaces := make(map[string]network.Interface)
475
476         timestamp := time.Now()
477         for ; result.NotDone(); err = result.Next() {
478                 if err != nil {
479                         az.logger.WithError(err).Warnf("Error listing nics")
480                         return interfaces, nil
481                 }
482                 if strings.HasPrefix(*result.Value().Name, az.namePrefix) {
483                         if result.Value().VirtualMachine != nil {
484                                 interfaces[*result.Value().ID] = result.Value()
485                         } else {
486                                 if result.Value().Tags["created-at"] != nil {
487                                         created_at, err := time.Parse(time.RFC3339Nano, *result.Value().Tags["created-at"])
488                                         if err == nil {
489                                                 if timestamp.Sub(created_at).Seconds() > az.azconfig.DeleteDanglingResourcesAfter {
490                                                         az.logger.Printf("Will delete %v because it is older than %v s", *result.Value().Name, az.azconfig.DeleteDanglingResourcesAfter)
491                                                         az.deleteNIC <- *result.Value().Name
492                                                 }
493                                         }
494                                 }
495                         }
496                 }
497         }
498         return interfaces, nil
499 }
500
501 // ManageBlobs garbage collects blobs (VM disk images) in the
502 // configured storage account container.  It will delete blobs which
503 // have "namePrefix", are "available" (which means they are not
504 // leased to a VM) and haven't been modified for
505 // DeleteDanglingResourcesAfter seconds.
506 func (az *AzureInstanceSet) ManageBlobs() {
507         az.stopWg.Add(1)
508         defer az.stopWg.Done()
509
510         result, err := az.storageAcctClient.ListKeys(az.ctx, az.azconfig.ResourceGroup, az.azconfig.StorageAccount)
511         if err != nil {
512                 az.logger.WithError(err).Warn("Couldn't get account keys")
513                 return
514         }
515
516         key1 := *(*result.Keys)[0].Value
517         client, err := storage.NewBasicClientOnSovereignCloud(az.azconfig.StorageAccount, key1, az.azureEnv)
518         if err != nil {
519                 az.logger.WithError(err).Warn("Couldn't make client")
520                 return
521         }
522
523         blobsvc := client.GetBlobService()
524         blobcont := blobsvc.GetContainerReference(az.azconfig.BlobContainer)
525
526         page := storage.ListBlobsParameters{Prefix: az.namePrefix}
527         timestamp := time.Now()
528
529         for {
530                 response, err := blobcont.ListBlobs(page)
531                 if err != nil {
532                         az.logger.WithError(err).Warn("Error listing blobs")
533                         return
534                 }
535                 for _, b := range response.Blobs {
536                         age := timestamp.Sub(time.Time(b.Properties.LastModified))
537                         if b.Properties.BlobType == storage.BlobTypePage &&
538                                 b.Properties.LeaseState == "available" &&
539                                 b.Properties.LeaseStatus == "unlocked" &&
540                                 age.Seconds() > az.azconfig.DeleteDanglingResourcesAfter {
541
542                                 az.logger.Printf("Blob %v is unlocked and not modified for %v seconds, will delete", b.Name, age.Seconds())
543                                 az.deleteBlob <- b
544                         }
545                 }
546                 if response.NextMarker != "" {
547                         page.Marker = response.NextMarker
548                 } else {
549                         break
550                 }
551         }
552 }
553
554 func (az *AzureInstanceSet) Stop() {
555         az.stopFunc()
556         az.stopWg.Wait()
557         close(az.deleteNIC)
558         close(az.deleteBlob)
559 }
560
561 type AzureInstance struct {
562         provider *AzureInstanceSet
563         nic      network.Interface
564         vm       compute.VirtualMachine
565 }
566
567 func (ai *AzureInstance) ID() InstanceID {
568         return InstanceID(*ai.vm.ID)
569 }
570
571 func (ai *AzureInstance) String() string {
572         return *ai.vm.Name
573 }
574
575 func (ai *AzureInstance) ProviderType() string {
576         return string(ai.vm.VirtualMachineProperties.HardwareProfile.VMSize)
577 }
578
579 func (ai *AzureInstance) SetTags(newTags InstanceTags) error {
580         ai.provider.stopWg.Add(1)
581         defer ai.provider.stopWg.Done()
582
583         tags := make(map[string]*string)
584
585         for k, v := range ai.vm.Tags {
586                 if !strings.HasPrefix(k, "dispatch-") {
587                         tags[k] = v
588                 }
589         }
590         for k, v := range newTags {
591                 newstr := v
592                 tags["dispatch-"+k] = &newstr
593         }
594
595         vmParameters := compute.VirtualMachine{
596                 Location: &ai.provider.azconfig.Location,
597                 Tags:     tags,
598         }
599         vm, err := ai.provider.vmClient.CreateOrUpdate(ai.provider.ctx, ai.provider.azconfig.ResourceGroup, *ai.vm.Name, vmParameters)
600         if err != nil {
601                 return WrapAzureError(err)
602         }
603         ai.vm = vm
604
605         return nil
606 }
607
608 func (ai *AzureInstance) Tags() InstanceTags {
609         tags := make(map[string]string)
610
611         for k, v := range ai.vm.Tags {
612                 if strings.HasPrefix(k, "dispatch-") {
613                         tags[k[9:]] = *v
614                 }
615         }
616
617         return tags
618 }
619
620 func (ai *AzureInstance) Destroy() error {
621         ai.provider.stopWg.Add(1)
622         defer ai.provider.stopWg.Done()
623
624         _, err := ai.provider.vmClient.Delete(ai.provider.ctx, ai.provider.azconfig.ResourceGroup, *ai.vm.Name)
625         return WrapAzureError(err)
626 }
627
628 func (ai *AzureInstance) Address() string {
629         return *(*ai.nic.IPConfigurations)[0].PrivateIPAddress
630 }
631
632 func (ai *AzureInstance) VerifyHostKey(receivedKey ssh.PublicKey, client *ssh.Client) error {
633         ai.provider.stopWg.Add(1)
634         defer ai.provider.stopWg.Done()
635
636         remoteFingerprint := ssh.FingerprintSHA256(receivedKey)
637
638         tags := ai.Tags()
639
640         tg := tags["ssh-pubkey-fingerprint"]
641         if tg != "" {
642                 if remoteFingerprint == tg {
643                         return nil
644                 } else {
645                         return fmt.Errorf("Key fingerprint did not match, expected %q got %q", tg, remoteFingerprint)
646                 }
647         }
648
649         nodetokenTag := tags["node-token"]
650         if nodetokenTag == "" {
651                 return fmt.Errorf("Missing node token tag")
652         }
653
654         sess, err := client.NewSession()
655         if err != nil {
656                 return err
657         }
658
659         nodetokenbytes, err := sess.Output("cat /home/crunch/node-token")
660         if err != nil {
661                 return err
662         }
663
664         nodetoken := strings.TrimSpace(string(nodetokenbytes))
665
666         expectedToken := fmt.Sprintf("%s-%s", *ai.vm.Name, nodetokenTag)
667
668         if strings.TrimSpace(nodetoken) != expectedToken {
669                 return fmt.Errorf("Node token did not match, expected %q got %q", expectedToken, nodetoken)
670         }
671
672         sess, err = client.NewSession()
673         if err != nil {
674                 return err
675         }
676
677         keyfingerprintbytes, err := sess.Output("ssh-keygen -E sha256 -l -f /etc/ssh/ssh_host_rsa_key.pub")
678         if err != nil {
679                 return err
680         }
681
682         sp := strings.Split(string(keyfingerprintbytes), " ")
683
684         if remoteFingerprint != sp[1] {
685                 return fmt.Errorf("Key fingerprint did not match, expected %q got %q", sp[1], remoteFingerprint)
686         }
687
688         tags["ssh-pubkey-fingerprint"] = sp[1]
689         delete(tags, "node-token")
690         ai.SetTags(tags)
691         return nil
692 }