Merge branch '20520-instance-init-command'
[arvados.git] / lib / cloud / ec2 / ec2.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package ec2
6
7 import (
8         "crypto/md5"
9         "crypto/rsa"
10         "crypto/sha1"
11         "crypto/x509"
12         "encoding/base64"
13         "encoding/json"
14         "fmt"
15         "math/big"
16         "strconv"
17         "sync"
18         "sync/atomic"
19         "time"
20
21         "git.arvados.org/arvados.git/lib/cloud"
22         "git.arvados.org/arvados.git/sdk/go/arvados"
23         "github.com/aws/aws-sdk-go/aws"
24         "github.com/aws/aws-sdk-go/aws/awserr"
25         "github.com/aws/aws-sdk-go/aws/credentials"
26         "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
27         "github.com/aws/aws-sdk-go/aws/ec2metadata"
28         "github.com/aws/aws-sdk-go/aws/request"
29         "github.com/aws/aws-sdk-go/aws/session"
30         "github.com/aws/aws-sdk-go/service/ec2"
31         "github.com/sirupsen/logrus"
32         "golang.org/x/crypto/ssh"
33 )
34
35 // Driver is the ec2 implementation of the cloud.Driver interface.
36 var Driver = cloud.DriverFunc(newEC2InstanceSet)
37
38 const (
39         throttleDelayMin = time.Second
40         throttleDelayMax = time.Minute
41 )
42
43 type ec2InstanceSetConfig struct {
44         AccessKeyID             string
45         SecretAccessKey         string
46         Region                  string
47         SecurityGroupIDs        arvados.StringSet
48         SubnetID                string
49         AdminUsername           string
50         EBSVolumeType           string
51         EBSPrice                float64
52         IAMInstanceProfile      string
53         SpotPriceUpdateInterval arvados.Duration
54 }
55
56 type ec2Interface interface {
57         DescribeKeyPairs(input *ec2.DescribeKeyPairsInput) (*ec2.DescribeKeyPairsOutput, error)
58         ImportKeyPair(input *ec2.ImportKeyPairInput) (*ec2.ImportKeyPairOutput, error)
59         RunInstances(input *ec2.RunInstancesInput) (*ec2.Reservation, error)
60         DescribeInstances(input *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error)
61         DescribeInstanceStatusPages(input *ec2.DescribeInstanceStatusInput, fn func(*ec2.DescribeInstanceStatusOutput, bool) bool) error
62         DescribeSpotPriceHistoryPages(input *ec2.DescribeSpotPriceHistoryInput, fn func(*ec2.DescribeSpotPriceHistoryOutput, bool) bool) error
63         CreateTags(input *ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error)
64         TerminateInstances(input *ec2.TerminateInstancesInput) (*ec2.TerminateInstancesOutput, error)
65 }
66
67 type ec2InstanceSet struct {
68         ec2config              ec2InstanceSetConfig
69         instanceSetID          cloud.InstanceSetID
70         logger                 logrus.FieldLogger
71         client                 ec2Interface
72         keysMtx                sync.Mutex
73         keys                   map[string]string
74         throttleDelayCreate    atomic.Value
75         throttleDelayInstances atomic.Value
76
77         prices        map[priceKey][]cloud.InstancePrice
78         pricesLock    sync.Mutex
79         pricesUpdated map[priceKey]time.Time
80 }
81
82 func newEC2InstanceSet(config json.RawMessage, instanceSetID cloud.InstanceSetID, _ cloud.SharedResourceTags, logger logrus.FieldLogger) (prv cloud.InstanceSet, err error) {
83         instanceSet := &ec2InstanceSet{
84                 instanceSetID: instanceSetID,
85                 logger:        logger,
86         }
87         err = json.Unmarshal(config, &instanceSet.ec2config)
88         if err != nil {
89                 return nil, err
90         }
91
92         sess, err := session.NewSession()
93         if err != nil {
94                 return nil, err
95         }
96         // First try any static credentials, fall back to an IAM instance profile/role
97         creds := credentials.NewChainCredentials(
98                 []credentials.Provider{
99                         &credentials.StaticProvider{Value: credentials.Value{AccessKeyID: instanceSet.ec2config.AccessKeyID, SecretAccessKey: instanceSet.ec2config.SecretAccessKey}},
100                         &ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess)},
101                 })
102
103         awsConfig := aws.NewConfig().WithCredentials(creds).WithRegion(instanceSet.ec2config.Region)
104         instanceSet.client = ec2.New(session.Must(session.NewSession(awsConfig)))
105         instanceSet.keys = make(map[string]string)
106         if instanceSet.ec2config.EBSVolumeType == "" {
107                 instanceSet.ec2config.EBSVolumeType = "gp2"
108         }
109         return instanceSet, nil
110 }
111
112 func awsKeyFingerprint(pk ssh.PublicKey) (md5fp string, sha1fp string, err error) {
113         // AWS key fingerprints don't use the usual key fingerprint
114         // you get from ssh-keygen or ssh.FingerprintLegacyMD5()
115         // (you can get that from md5.Sum(pk.Marshal())
116         //
117         // AWS uses the md5 or sha1 of the PKIX DER encoding of the
118         // public key, so calculate those fingerprints here.
119         var rsaPub struct {
120                 Name string
121                 E    *big.Int
122                 N    *big.Int
123         }
124         if err := ssh.Unmarshal(pk.Marshal(), &rsaPub); err != nil {
125                 return "", "", fmt.Errorf("agent: Unmarshal failed to parse public key: %v", err)
126         }
127         rsaPk := rsa.PublicKey{
128                 E: int(rsaPub.E.Int64()),
129                 N: rsaPub.N,
130         }
131         pkix, _ := x509.MarshalPKIXPublicKey(&rsaPk)
132         md5pkix := md5.Sum([]byte(pkix))
133         sha1pkix := sha1.Sum([]byte(pkix))
134         md5fp = ""
135         sha1fp = ""
136         for i := 0; i < len(md5pkix); i++ {
137                 md5fp += fmt.Sprintf(":%02x", md5pkix[i])
138         }
139         for i := 0; i < len(sha1pkix); i++ {
140                 sha1fp += fmt.Sprintf(":%02x", sha1pkix[i])
141         }
142         return md5fp[1:], sha1fp[1:], nil
143 }
144
145 func (instanceSet *ec2InstanceSet) Create(
146         instanceType arvados.InstanceType,
147         imageID cloud.ImageID,
148         newTags cloud.InstanceTags,
149         initCommand cloud.InitCommand,
150         publicKey ssh.PublicKey) (cloud.Instance, error) {
151
152         keyname, err := instanceSet.getKeyName(publicKey)
153         if err != nil {
154                 return nil, err
155         }
156
157         ec2tags := []*ec2.Tag{}
158         for k, v := range newTags {
159                 ec2tags = append(ec2tags, &ec2.Tag{
160                         Key:   aws.String(k),
161                         Value: aws.String(v),
162                 })
163         }
164
165         var groups []string
166         for sg := range instanceSet.ec2config.SecurityGroupIDs {
167                 groups = append(groups, sg)
168         }
169
170         rii := ec2.RunInstancesInput{
171                 ImageId:      aws.String(string(imageID)),
172                 InstanceType: &instanceType.ProviderType,
173                 MaxCount:     aws.Int64(1),
174                 MinCount:     aws.Int64(1),
175                 KeyName:      &keyname,
176
177                 NetworkInterfaces: []*ec2.InstanceNetworkInterfaceSpecification{
178                         {
179                                 AssociatePublicIpAddress: aws.Bool(false),
180                                 DeleteOnTermination:      aws.Bool(true),
181                                 DeviceIndex:              aws.Int64(0),
182                                 Groups:                   aws.StringSlice(groups),
183                                 SubnetId:                 &instanceSet.ec2config.SubnetID,
184                         }},
185                 DisableApiTermination:             aws.Bool(false),
186                 InstanceInitiatedShutdownBehavior: aws.String("terminate"),
187                 TagSpecifications: []*ec2.TagSpecification{
188                         {
189                                 ResourceType: aws.String("instance"),
190                                 Tags:         ec2tags,
191                         }},
192                 UserData: aws.String(base64.StdEncoding.EncodeToString([]byte("#!/bin/sh\n" + initCommand + "\n"))),
193         }
194
195         if instanceType.AddedScratch > 0 {
196                 rii.BlockDeviceMappings = []*ec2.BlockDeviceMapping{{
197                         DeviceName: aws.String("/dev/xvdt"),
198                         Ebs: &ec2.EbsBlockDevice{
199                                 DeleteOnTermination: aws.Bool(true),
200                                 VolumeSize:          aws.Int64((int64(instanceType.AddedScratch) + (1<<30 - 1)) >> 30),
201                                 VolumeType:          &instanceSet.ec2config.EBSVolumeType,
202                         }}}
203         }
204
205         if instanceType.Preemptible {
206                 rii.InstanceMarketOptions = &ec2.InstanceMarketOptionsRequest{
207                         MarketType: aws.String("spot"),
208                         SpotOptions: &ec2.SpotMarketOptions{
209                                 InstanceInterruptionBehavior: aws.String("terminate"),
210                                 MaxPrice:                     aws.String(fmt.Sprintf("%v", instanceType.Price)),
211                         }}
212         }
213
214         if instanceSet.ec2config.IAMInstanceProfile != "" {
215                 rii.IamInstanceProfile = &ec2.IamInstanceProfileSpecification{
216                         Name: aws.String(instanceSet.ec2config.IAMInstanceProfile),
217                 }
218         }
219
220         rsv, err := instanceSet.client.RunInstances(&rii)
221         err = wrapError(err, &instanceSet.throttleDelayCreate)
222         if err != nil {
223                 return nil, err
224         }
225         return &ec2Instance{
226                 provider: instanceSet,
227                 instance: rsv.Instances[0],
228         }, nil
229 }
230
231 func (instanceSet *ec2InstanceSet) getKeyName(publicKey ssh.PublicKey) (string, error) {
232         instanceSet.keysMtx.Lock()
233         defer instanceSet.keysMtx.Unlock()
234         md5keyFingerprint, sha1keyFingerprint, err := awsKeyFingerprint(publicKey)
235         if err != nil {
236                 return "", fmt.Errorf("Could not make key fingerprint: %v", err)
237         }
238         if keyname, ok := instanceSet.keys[md5keyFingerprint]; ok {
239                 return keyname, nil
240         }
241         keyout, err := instanceSet.client.DescribeKeyPairs(&ec2.DescribeKeyPairsInput{
242                 Filters: []*ec2.Filter{{
243                         Name:   aws.String("fingerprint"),
244                         Values: []*string{&md5keyFingerprint, &sha1keyFingerprint},
245                 }},
246         })
247         if err != nil {
248                 return "", fmt.Errorf("Could not search for keypair: %v", err)
249         }
250         if len(keyout.KeyPairs) > 0 {
251                 return *(keyout.KeyPairs[0].KeyName), nil
252         }
253         keyname := "arvados-dispatch-keypair-" + md5keyFingerprint
254         _, err = instanceSet.client.ImportKeyPair(&ec2.ImportKeyPairInput{
255                 KeyName:           &keyname,
256                 PublicKeyMaterial: ssh.MarshalAuthorizedKey(publicKey),
257         })
258         if err != nil {
259                 return "", fmt.Errorf("Could not import keypair: %v", err)
260         }
261         instanceSet.keys[md5keyFingerprint] = keyname
262         return keyname, nil
263 }
264
265 func (instanceSet *ec2InstanceSet) Instances(tags cloud.InstanceTags) (instances []cloud.Instance, err error) {
266         var filters []*ec2.Filter
267         for k, v := range tags {
268                 filters = append(filters, &ec2.Filter{
269                         Name:   aws.String("tag:" + k),
270                         Values: []*string{aws.String(v)},
271                 })
272         }
273         needAZs := false
274         dii := &ec2.DescribeInstancesInput{Filters: filters}
275         for {
276                 dio, err := instanceSet.client.DescribeInstances(dii)
277                 err = wrapError(err, &instanceSet.throttleDelayInstances)
278                 if err != nil {
279                         return nil, err
280                 }
281
282                 for _, rsv := range dio.Reservations {
283                         for _, inst := range rsv.Instances {
284                                 if *inst.State.Name != "shutting-down" && *inst.State.Name != "terminated" {
285                                         instances = append(instances, &ec2Instance{
286                                                 provider: instanceSet,
287                                                 instance: inst,
288                                         })
289                                         if aws.StringValue(inst.InstanceLifecycle) == "spot" {
290                                                 needAZs = true
291                                         }
292                                 }
293                         }
294                 }
295                 if dio.NextToken == nil {
296                         break
297                 }
298                 dii.NextToken = dio.NextToken
299         }
300         if needAZs && instanceSet.ec2config.SpotPriceUpdateInterval > 0 {
301                 az := map[string]string{}
302                 err := instanceSet.client.DescribeInstanceStatusPages(&ec2.DescribeInstanceStatusInput{
303                         IncludeAllInstances: aws.Bool(true),
304                 }, func(page *ec2.DescribeInstanceStatusOutput, lastPage bool) bool {
305                         for _, ent := range page.InstanceStatuses {
306                                 az[*ent.InstanceId] = *ent.AvailabilityZone
307                         }
308                         return true
309                 })
310                 if err != nil {
311                         instanceSet.logger.Warnf("error getting instance statuses: %s", err)
312                 }
313                 for _, inst := range instances {
314                         inst := inst.(*ec2Instance)
315                         inst.availabilityZone = az[*inst.instance.InstanceId]
316                 }
317                 instanceSet.updateSpotPrices(instances)
318         }
319         return instances, err
320 }
321
322 type priceKey struct {
323         instanceType     string
324         spot             bool
325         availabilityZone string
326 }
327
328 // Refresh recent spot instance pricing data for the given instances,
329 // unless we already have recent pricing data for all relevant types.
330 func (instanceSet *ec2InstanceSet) updateSpotPrices(instances []cloud.Instance) {
331         if len(instances) == 0 {
332                 return
333         }
334
335         instanceSet.pricesLock.Lock()
336         defer instanceSet.pricesLock.Unlock()
337         if instanceSet.prices == nil {
338                 instanceSet.prices = map[priceKey][]cloud.InstancePrice{}
339                 instanceSet.pricesUpdated = map[priceKey]time.Time{}
340         }
341
342         updateTime := time.Now()
343         staleTime := updateTime.Add(-instanceSet.ec2config.SpotPriceUpdateInterval.Duration())
344         needUpdate := false
345         allTypes := map[string]bool{}
346
347         for _, inst := range instances {
348                 ec2inst := inst.(*ec2Instance).instance
349                 if aws.StringValue(ec2inst.InstanceLifecycle) == "spot" {
350                         pk := priceKey{
351                                 instanceType:     *ec2inst.InstanceType,
352                                 spot:             true,
353                                 availabilityZone: inst.(*ec2Instance).availabilityZone,
354                         }
355                         if instanceSet.pricesUpdated[pk].Before(staleTime) {
356                                 needUpdate = true
357                         }
358                         allTypes[*ec2inst.InstanceType] = true
359                 }
360         }
361         if !needUpdate {
362                 return
363         }
364         var typeFilterValues []*string
365         for instanceType := range allTypes {
366                 typeFilterValues = append(typeFilterValues, aws.String(instanceType))
367         }
368         // Get 3x update interval worth of pricing data. (Ideally the
369         // AWS API would tell us "we have shown you all of the price
370         // changes up to time T", but it doesn't, so we'll just ask
371         // for 3 intervals worth of data on each update, de-duplicate
372         // the data points, and not worry too much about occasionally
373         // missing some data points when our lookups fail twice in a
374         // row.
375         dsphi := &ec2.DescribeSpotPriceHistoryInput{
376                 StartTime: aws.Time(updateTime.Add(-3 * instanceSet.ec2config.SpotPriceUpdateInterval.Duration())),
377                 Filters: []*ec2.Filter{
378                         &ec2.Filter{Name: aws.String("instance-type"), Values: typeFilterValues},
379                         &ec2.Filter{Name: aws.String("product-description"), Values: []*string{aws.String("Linux/UNIX")}},
380                 },
381         }
382         err := instanceSet.client.DescribeSpotPriceHistoryPages(dsphi, func(page *ec2.DescribeSpotPriceHistoryOutput, lastPage bool) bool {
383                 for _, ent := range page.SpotPriceHistory {
384                         if ent.InstanceType == nil || ent.SpotPrice == nil || ent.Timestamp == nil {
385                                 // bogus record?
386                                 continue
387                         }
388                         price, err := strconv.ParseFloat(*ent.SpotPrice, 64)
389                         if err != nil {
390                                 // bogus record?
391                                 continue
392                         }
393                         pk := priceKey{
394                                 instanceType:     *ent.InstanceType,
395                                 spot:             true,
396                                 availabilityZone: *ent.AvailabilityZone,
397                         }
398                         instanceSet.prices[pk] = append(instanceSet.prices[pk], cloud.InstancePrice{
399                                 StartTime: *ent.Timestamp,
400                                 Price:     price,
401                         })
402                         instanceSet.pricesUpdated[pk] = updateTime
403                 }
404                 return true
405         })
406         if err != nil {
407                 instanceSet.logger.Warnf("error retrieving spot instance prices: %s", err)
408         }
409
410         expiredTime := updateTime.Add(-64 * instanceSet.ec2config.SpotPriceUpdateInterval.Duration())
411         for pk, last := range instanceSet.pricesUpdated {
412                 if last.Before(expiredTime) {
413                         delete(instanceSet.pricesUpdated, pk)
414                         delete(instanceSet.prices, pk)
415                 }
416         }
417         for pk, prices := range instanceSet.prices {
418                 instanceSet.prices[pk] = cloud.NormalizePriceHistory(prices)
419         }
420 }
421
422 func (instanceSet *ec2InstanceSet) Stop() {
423 }
424
425 type ec2Instance struct {
426         provider         *ec2InstanceSet
427         instance         *ec2.Instance
428         availabilityZone string // sometimes available for spot instances
429 }
430
431 func (inst *ec2Instance) ID() cloud.InstanceID {
432         return cloud.InstanceID(*inst.instance.InstanceId)
433 }
434
435 func (inst *ec2Instance) String() string {
436         return *inst.instance.InstanceId
437 }
438
439 func (inst *ec2Instance) ProviderType() string {
440         return *inst.instance.InstanceType
441 }
442
443 func (inst *ec2Instance) SetTags(newTags cloud.InstanceTags) error {
444         var ec2tags []*ec2.Tag
445         for k, v := range newTags {
446                 ec2tags = append(ec2tags, &ec2.Tag{
447                         Key:   aws.String(k),
448                         Value: aws.String(v),
449                 })
450         }
451
452         _, err := inst.provider.client.CreateTags(&ec2.CreateTagsInput{
453                 Resources: []*string{inst.instance.InstanceId},
454                 Tags:      ec2tags,
455         })
456
457         return err
458 }
459
460 func (inst *ec2Instance) Tags() cloud.InstanceTags {
461         tags := make(map[string]string)
462
463         for _, t := range inst.instance.Tags {
464                 tags[*t.Key] = *t.Value
465         }
466
467         return tags
468 }
469
470 func (inst *ec2Instance) Destroy() error {
471         _, err := inst.provider.client.TerminateInstances(&ec2.TerminateInstancesInput{
472                 InstanceIds: []*string{inst.instance.InstanceId},
473         })
474         return err
475 }
476
477 func (inst *ec2Instance) Address() string {
478         if inst.instance.PrivateIpAddress != nil {
479                 return *inst.instance.PrivateIpAddress
480         }
481         return ""
482 }
483
484 func (inst *ec2Instance) RemoteUser() string {
485         return inst.provider.ec2config.AdminUsername
486 }
487
488 func (inst *ec2Instance) VerifyHostKey(ssh.PublicKey, *ssh.Client) error {
489         return cloud.ErrNotImplemented
490 }
491
492 // PriceHistory returns the price history for this specific instance.
493 //
494 // AWS documentation is elusive about whether the hourly cost of a
495 // given spot instance changes as the current spot price changes for
496 // the corresponding instance type and availability zone. Our
497 // implementation assumes the answer is yes, based on the following
498 // hints.
499 //
500 // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-requests.html
501 // says: "After your Spot Instance is running, if the Spot price rises
502 // above your maximum price, Amazon EC2 interrupts your Spot
503 // Instance." (This doesn't address what happens when the spot price
504 // rises *without* exceeding your maximum price.)
505 //
506 // https://docs.aws.amazon.com/whitepapers/latest/cost-optimization-leveraging-ec2-spot-instances/how-spot-instances-work.html
507 // says: "You pay the Spot price that's in effect, billed to the
508 // nearest second." (But it's not explicitly stated whether "the price
509 // in effect" changes over time for a given instance.)
510 //
511 // The same page also says, in a discussion about the effect of
512 // specifying a maximum price: "Note that you never pay more than the
513 // Spot price that is in effect when your Spot Instance is running."
514 // (The use of the phrase "is running", as opposed to "was launched",
515 // hints that pricing is dynamic.)
516 func (inst *ec2Instance) PriceHistory(instType arvados.InstanceType) []cloud.InstancePrice {
517         inst.provider.pricesLock.Lock()
518         defer inst.provider.pricesLock.Unlock()
519         // Note updateSpotPrices currently populates
520         // inst.provider.prices only for spot instances, so if
521         // spot==false here, we will return no data.
522         pk := priceKey{
523                 instanceType:     *inst.instance.InstanceType,
524                 spot:             aws.StringValue(inst.instance.InstanceLifecycle) == "spot",
525                 availabilityZone: inst.availabilityZone,
526         }
527         var prices []cloud.InstancePrice
528         for _, price := range inst.provider.prices[pk] {
529                 // ceil(added scratch space in GiB)
530                 gib := (instType.AddedScratch + 1<<30 - 1) >> 30
531                 monthly := inst.provider.ec2config.EBSPrice * float64(gib)
532                 hourly := monthly / 30 / 24
533                 price.Price += hourly
534                 prices = append(prices, price)
535         }
536         return prices
537 }
538
539 type rateLimitError struct {
540         error
541         earliestRetry time.Time
542 }
543
544 func (err rateLimitError) EarliestRetry() time.Time {
545         return err.earliestRetry
546 }
547
548 var isCodeCapacity = map[string]bool{
549         "InsufficientFreeAddressesInSubnet": true,
550         "InsufficientInstanceCapacity":      true,
551         "InsufficientVolumeCapacity":        true,
552         "MaxSpotInstanceCountExceeded":      true,
553         "VcpuLimitExceeded":                 true,
554 }
555
556 // isErrorCapacity returns whether the error is to be throttled based on its code.
557 // Returns false if error is nil.
558 func isErrorCapacity(err error) bool {
559         if aerr, ok := err.(awserr.Error); ok && aerr != nil {
560                 if _, ok := isCodeCapacity[aerr.Code()]; ok {
561                         return true
562                 }
563         }
564         return false
565 }
566
567 type ec2QuotaError struct {
568         error
569 }
570
571 func (er *ec2QuotaError) IsQuotaError() bool {
572         return true
573 }
574
575 func wrapError(err error, throttleValue *atomic.Value) error {
576         if request.IsErrorThrottle(err) {
577                 // Back off exponentially until an upstream call
578                 // either succeeds or returns a non-throttle error.
579                 d, _ := throttleValue.Load().(time.Duration)
580                 d = d*3/2 + time.Second
581                 if d < throttleDelayMin {
582                         d = throttleDelayMin
583                 } else if d > throttleDelayMax {
584                         d = throttleDelayMax
585                 }
586                 throttleValue.Store(d)
587                 return rateLimitError{error: err, earliestRetry: time.Now().Add(d)}
588         } else if isErrorCapacity(err) {
589                 return &ec2QuotaError{err}
590         } else if err != nil {
591                 throttleValue.Store(time.Duration(0))
592                 return err
593         }
594         throttleValue.Store(time.Duration(0))
595         return nil
596 }