20259: Add documentation for banner and tooltip features
[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         md5keyFingerprint, sha1keyFingerprint, err := awsKeyFingerprint(publicKey)
153         if err != nil {
154                 return nil, fmt.Errorf("Could not make key fingerprint: %v", err)
155         }
156         instanceSet.keysMtx.Lock()
157         var keyname string
158         var ok bool
159         if keyname, ok = instanceSet.keys[md5keyFingerprint]; !ok {
160                 keyout, err := instanceSet.client.DescribeKeyPairs(&ec2.DescribeKeyPairsInput{
161                         Filters: []*ec2.Filter{{
162                                 Name:   aws.String("fingerprint"),
163                                 Values: []*string{&md5keyFingerprint, &sha1keyFingerprint},
164                         }},
165                 })
166                 if err != nil {
167                         return nil, fmt.Errorf("Could not search for keypair: %v", err)
168                 }
169
170                 if len(keyout.KeyPairs) > 0 {
171                         keyname = *(keyout.KeyPairs[0].KeyName)
172                 } else {
173                         keyname = "arvados-dispatch-keypair-" + md5keyFingerprint
174                         _, err := instanceSet.client.ImportKeyPair(&ec2.ImportKeyPairInput{
175                                 KeyName:           &keyname,
176                                 PublicKeyMaterial: ssh.MarshalAuthorizedKey(publicKey),
177                         })
178                         if err != nil {
179                                 return nil, fmt.Errorf("Could not import keypair: %v", err)
180                         }
181                 }
182                 instanceSet.keys[md5keyFingerprint] = keyname
183         }
184         instanceSet.keysMtx.Unlock()
185
186         ec2tags := []*ec2.Tag{}
187         for k, v := range newTags {
188                 ec2tags = append(ec2tags, &ec2.Tag{
189                         Key:   aws.String(k),
190                         Value: aws.String(v),
191                 })
192         }
193
194         var groups []string
195         for sg := range instanceSet.ec2config.SecurityGroupIDs {
196                 groups = append(groups, sg)
197         }
198
199         rii := ec2.RunInstancesInput{
200                 ImageId:      aws.String(string(imageID)),
201                 InstanceType: &instanceType.ProviderType,
202                 MaxCount:     aws.Int64(1),
203                 MinCount:     aws.Int64(1),
204                 KeyName:      &keyname,
205
206                 NetworkInterfaces: []*ec2.InstanceNetworkInterfaceSpecification{
207                         {
208                                 AssociatePublicIpAddress: aws.Bool(false),
209                                 DeleteOnTermination:      aws.Bool(true),
210                                 DeviceIndex:              aws.Int64(0),
211                                 Groups:                   aws.StringSlice(groups),
212                                 SubnetId:                 &instanceSet.ec2config.SubnetID,
213                         }},
214                 DisableApiTermination:             aws.Bool(false),
215                 InstanceInitiatedShutdownBehavior: aws.String("terminate"),
216                 TagSpecifications: []*ec2.TagSpecification{
217                         {
218                                 ResourceType: aws.String("instance"),
219                                 Tags:         ec2tags,
220                         }},
221                 UserData: aws.String(base64.StdEncoding.EncodeToString([]byte("#!/bin/sh\n" + initCommand + "\n"))),
222         }
223
224         if instanceType.AddedScratch > 0 {
225                 rii.BlockDeviceMappings = []*ec2.BlockDeviceMapping{{
226                         DeviceName: aws.String("/dev/xvdt"),
227                         Ebs: &ec2.EbsBlockDevice{
228                                 DeleteOnTermination: aws.Bool(true),
229                                 VolumeSize:          aws.Int64((int64(instanceType.AddedScratch) + (1<<30 - 1)) >> 30),
230                                 VolumeType:          &instanceSet.ec2config.EBSVolumeType,
231                         }}}
232         }
233
234         if instanceType.Preemptible {
235                 rii.InstanceMarketOptions = &ec2.InstanceMarketOptionsRequest{
236                         MarketType: aws.String("spot"),
237                         SpotOptions: &ec2.SpotMarketOptions{
238                                 InstanceInterruptionBehavior: aws.String("terminate"),
239                                 MaxPrice:                     aws.String(fmt.Sprintf("%v", instanceType.Price)),
240                         }}
241         }
242
243         if instanceSet.ec2config.IAMInstanceProfile != "" {
244                 rii.IamInstanceProfile = &ec2.IamInstanceProfileSpecification{
245                         Name: aws.String(instanceSet.ec2config.IAMInstanceProfile),
246                 }
247         }
248
249         rsv, err := instanceSet.client.RunInstances(&rii)
250         err = wrapError(err, &instanceSet.throttleDelayCreate)
251         if err != nil {
252                 return nil, err
253         }
254         return &ec2Instance{
255                 provider: instanceSet,
256                 instance: rsv.Instances[0],
257         }, nil
258 }
259
260 func (instanceSet *ec2InstanceSet) Instances(tags cloud.InstanceTags) (instances []cloud.Instance, err error) {
261         var filters []*ec2.Filter
262         for k, v := range tags {
263                 filters = append(filters, &ec2.Filter{
264                         Name:   aws.String("tag:" + k),
265                         Values: []*string{aws.String(v)},
266                 })
267         }
268         needAZs := false
269         dii := &ec2.DescribeInstancesInput{Filters: filters}
270         for {
271                 dio, err := instanceSet.client.DescribeInstances(dii)
272                 err = wrapError(err, &instanceSet.throttleDelayInstances)
273                 if err != nil {
274                         return nil, err
275                 }
276
277                 for _, rsv := range dio.Reservations {
278                         for _, inst := range rsv.Instances {
279                                 if *inst.State.Name != "shutting-down" && *inst.State.Name != "terminated" {
280                                         instances = append(instances, &ec2Instance{
281                                                 provider: instanceSet,
282                                                 instance: inst,
283                                         })
284                                         if aws.StringValue(inst.InstanceLifecycle) == "spot" {
285                                                 needAZs = true
286                                         }
287                                 }
288                         }
289                 }
290                 if dio.NextToken == nil {
291                         break
292                 }
293                 dii.NextToken = dio.NextToken
294         }
295         if needAZs && instanceSet.ec2config.SpotPriceUpdateInterval > 0 {
296                 az := map[string]string{}
297                 err := instanceSet.client.DescribeInstanceStatusPages(&ec2.DescribeInstanceStatusInput{
298                         IncludeAllInstances: aws.Bool(true),
299                 }, func(page *ec2.DescribeInstanceStatusOutput, lastPage bool) bool {
300                         for _, ent := range page.InstanceStatuses {
301                                 az[*ent.InstanceId] = *ent.AvailabilityZone
302                         }
303                         return true
304                 })
305                 if err != nil {
306                         instanceSet.logger.Warnf("error getting instance statuses: %s", err)
307                 }
308                 for _, inst := range instances {
309                         inst := inst.(*ec2Instance)
310                         inst.availabilityZone = az[*inst.instance.InstanceId]
311                 }
312                 instanceSet.updateSpotPrices(instances)
313         }
314         return instances, err
315 }
316
317 type priceKey struct {
318         instanceType     string
319         spot             bool
320         availabilityZone string
321 }
322
323 // Refresh recent spot instance pricing data for the given instances,
324 // unless we already have recent pricing data for all relevant types.
325 func (instanceSet *ec2InstanceSet) updateSpotPrices(instances []cloud.Instance) {
326         if len(instances) == 0 {
327                 return
328         }
329
330         instanceSet.pricesLock.Lock()
331         defer instanceSet.pricesLock.Unlock()
332         if instanceSet.prices == nil {
333                 instanceSet.prices = map[priceKey][]cloud.InstancePrice{}
334                 instanceSet.pricesUpdated = map[priceKey]time.Time{}
335         }
336
337         updateTime := time.Now()
338         staleTime := updateTime.Add(-instanceSet.ec2config.SpotPriceUpdateInterval.Duration())
339         needUpdate := false
340         allTypes := map[string]bool{}
341
342         for _, inst := range instances {
343                 ec2inst := inst.(*ec2Instance).instance
344                 if aws.StringValue(ec2inst.InstanceLifecycle) == "spot" {
345                         pk := priceKey{
346                                 instanceType:     *ec2inst.InstanceType,
347                                 spot:             true,
348                                 availabilityZone: inst.(*ec2Instance).availabilityZone,
349                         }
350                         if instanceSet.pricesUpdated[pk].Before(staleTime) {
351                                 needUpdate = true
352                         }
353                         allTypes[*ec2inst.InstanceType] = true
354                 }
355         }
356         if !needUpdate {
357                 return
358         }
359         var typeFilterValues []*string
360         for instanceType := range allTypes {
361                 typeFilterValues = append(typeFilterValues, aws.String(instanceType))
362         }
363         // Get 3x update interval worth of pricing data. (Ideally the
364         // AWS API would tell us "we have shown you all of the price
365         // changes up to time T", but it doesn't, so we'll just ask
366         // for 3 intervals worth of data on each update, de-duplicate
367         // the data points, and not worry too much about occasionally
368         // missing some data points when our lookups fail twice in a
369         // row.
370         dsphi := &ec2.DescribeSpotPriceHistoryInput{
371                 StartTime: aws.Time(updateTime.Add(-3 * instanceSet.ec2config.SpotPriceUpdateInterval.Duration())),
372                 Filters: []*ec2.Filter{
373                         &ec2.Filter{Name: aws.String("instance-type"), Values: typeFilterValues},
374                         &ec2.Filter{Name: aws.String("product-description"), Values: []*string{aws.String("Linux/UNIX")}},
375                 },
376         }
377         err := instanceSet.client.DescribeSpotPriceHistoryPages(dsphi, func(page *ec2.DescribeSpotPriceHistoryOutput, lastPage bool) bool {
378                 for _, ent := range page.SpotPriceHistory {
379                         if ent.InstanceType == nil || ent.SpotPrice == nil || ent.Timestamp == nil {
380                                 // bogus record?
381                                 continue
382                         }
383                         price, err := strconv.ParseFloat(*ent.SpotPrice, 64)
384                         if err != nil {
385                                 // bogus record?
386                                 continue
387                         }
388                         pk := priceKey{
389                                 instanceType:     *ent.InstanceType,
390                                 spot:             true,
391                                 availabilityZone: *ent.AvailabilityZone,
392                         }
393                         instanceSet.prices[pk] = append(instanceSet.prices[pk], cloud.InstancePrice{
394                                 StartTime: *ent.Timestamp,
395                                 Price:     price,
396                         })
397                         instanceSet.pricesUpdated[pk] = updateTime
398                 }
399                 return true
400         })
401         if err != nil {
402                 instanceSet.logger.Warnf("error retrieving spot instance prices: %s", err)
403         }
404
405         expiredTime := updateTime.Add(-64 * instanceSet.ec2config.SpotPriceUpdateInterval.Duration())
406         for pk, last := range instanceSet.pricesUpdated {
407                 if last.Before(expiredTime) {
408                         delete(instanceSet.pricesUpdated, pk)
409                         delete(instanceSet.prices, pk)
410                 }
411         }
412         for pk, prices := range instanceSet.prices {
413                 instanceSet.prices[pk] = cloud.NormalizePriceHistory(prices)
414         }
415 }
416
417 func (instanceSet *ec2InstanceSet) Stop() {
418 }
419
420 type ec2Instance struct {
421         provider         *ec2InstanceSet
422         instance         *ec2.Instance
423         availabilityZone string // sometimes available for spot instances
424 }
425
426 func (inst *ec2Instance) ID() cloud.InstanceID {
427         return cloud.InstanceID(*inst.instance.InstanceId)
428 }
429
430 func (inst *ec2Instance) String() string {
431         return *inst.instance.InstanceId
432 }
433
434 func (inst *ec2Instance) ProviderType() string {
435         return *inst.instance.InstanceType
436 }
437
438 func (inst *ec2Instance) SetTags(newTags cloud.InstanceTags) error {
439         var ec2tags []*ec2.Tag
440         for k, v := range newTags {
441                 ec2tags = append(ec2tags, &ec2.Tag{
442                         Key:   aws.String(k),
443                         Value: aws.String(v),
444                 })
445         }
446
447         _, err := inst.provider.client.CreateTags(&ec2.CreateTagsInput{
448                 Resources: []*string{inst.instance.InstanceId},
449                 Tags:      ec2tags,
450         })
451
452         return err
453 }
454
455 func (inst *ec2Instance) Tags() cloud.InstanceTags {
456         tags := make(map[string]string)
457
458         for _, t := range inst.instance.Tags {
459                 tags[*t.Key] = *t.Value
460         }
461
462         return tags
463 }
464
465 func (inst *ec2Instance) Destroy() error {
466         _, err := inst.provider.client.TerminateInstances(&ec2.TerminateInstancesInput{
467                 InstanceIds: []*string{inst.instance.InstanceId},
468         })
469         return err
470 }
471
472 func (inst *ec2Instance) Address() string {
473         if inst.instance.PrivateIpAddress != nil {
474                 return *inst.instance.PrivateIpAddress
475         }
476         return ""
477 }
478
479 func (inst *ec2Instance) RemoteUser() string {
480         return inst.provider.ec2config.AdminUsername
481 }
482
483 func (inst *ec2Instance) VerifyHostKey(ssh.PublicKey, *ssh.Client) error {
484         return cloud.ErrNotImplemented
485 }
486
487 // PriceHistory returns the price history for this specific instance.
488 //
489 // AWS documentation is elusive about whether the hourly cost of a
490 // given spot instance changes as the current spot price changes for
491 // the corresponding instance type and availability zone. Our
492 // implementation assumes the answer is yes, based on the following
493 // hints.
494 //
495 // https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/spot-requests.html
496 // says: "After your Spot Instance is running, if the Spot price rises
497 // above your maximum price, Amazon EC2 interrupts your Spot
498 // Instance." (This doesn't address what happens when the spot price
499 // rises *without* exceeding your maximum price.)
500 //
501 // https://docs.aws.amazon.com/whitepapers/latest/cost-optimization-leveraging-ec2-spot-instances/how-spot-instances-work.html
502 // says: "You pay the Spot price that's in effect, billed to the
503 // nearest second." (But it's not explicitly stated whether "the price
504 // in effect" changes over time for a given instance.)
505 //
506 // The same page also says, in a discussion about the effect of
507 // specifying a maximum price: "Note that you never pay more than the
508 // Spot price that is in effect when your Spot Instance is running."
509 // (The use of the phrase "is running", as opposed to "was launched",
510 // hints that pricing is dynamic.)
511 func (inst *ec2Instance) PriceHistory(instType arvados.InstanceType) []cloud.InstancePrice {
512         inst.provider.pricesLock.Lock()
513         defer inst.provider.pricesLock.Unlock()
514         // Note updateSpotPrices currently populates
515         // inst.provider.prices only for spot instances, so if
516         // spot==false here, we will return no data.
517         pk := priceKey{
518                 instanceType:     *inst.instance.InstanceType,
519                 spot:             aws.StringValue(inst.instance.InstanceLifecycle) == "spot",
520                 availabilityZone: inst.availabilityZone,
521         }
522         var prices []cloud.InstancePrice
523         for _, price := range inst.provider.prices[pk] {
524                 // ceil(added scratch space in GiB)
525                 gib := (instType.AddedScratch + 1<<30 - 1) >> 30
526                 monthly := inst.provider.ec2config.EBSPrice * float64(gib)
527                 hourly := monthly / 30 / 24
528                 price.Price += hourly
529                 prices = append(prices, price)
530         }
531         return prices
532 }
533
534 type rateLimitError struct {
535         error
536         earliestRetry time.Time
537 }
538
539 func (err rateLimitError) EarliestRetry() time.Time {
540         return err.earliestRetry
541 }
542
543 var isCodeCapacity = map[string]bool{
544         "InsufficientFreeAddressesInSubnet": true,
545         "InsufficientInstanceCapacity":      true,
546         "InsufficientVolumeCapacity":        true,
547         "MaxSpotInstanceCountExceeded":      true,
548         "VcpuLimitExceeded":                 true,
549 }
550
551 // isErrorCapacity returns whether the error is to be throttled based on its code.
552 // Returns false if error is nil.
553 func isErrorCapacity(err error) bool {
554         if aerr, ok := err.(awserr.Error); ok && aerr != nil {
555                 if _, ok := isCodeCapacity[aerr.Code()]; ok {
556                         return true
557                 }
558         }
559         return false
560 }
561
562 type ec2QuotaError struct {
563         error
564 }
565
566 func (er *ec2QuotaError) IsQuotaError() bool {
567         return true
568 }
569
570 func wrapError(err error, throttleValue *atomic.Value) error {
571         if request.IsErrorThrottle(err) {
572                 // Back off exponentially until an upstream call
573                 // either succeeds or returns a non-throttle error.
574                 d, _ := throttleValue.Load().(time.Duration)
575                 d = d*3/2 + time.Second
576                 if d < throttleDelayMin {
577                         d = throttleDelayMin
578                 } else if d > throttleDelayMax {
579                         d = throttleDelayMax
580                 }
581                 throttleValue.Store(d)
582                 return rateLimitError{error: err, earliestRetry: time.Now().Add(d)}
583         } else if isErrorCapacity(err) {
584                 return &ec2QuotaError{err}
585         } else if err != nil {
586                 throttleValue.Store(time.Duration(0))
587                 return err
588         }
589         throttleValue.Store(time.Duration(0))
590         return nil
591 }