1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
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"
35 // Driver is the ec2 implementation of the cloud.Driver interface.
36 var Driver = cloud.DriverFunc(newEC2InstanceSet)
39 throttleDelayMin = time.Second
40 throttleDelayMax = time.Minute
43 type ec2InstanceSetConfig struct {
45 SecretAccessKey string
47 SecurityGroupIDs arvados.StringSet
52 IAMInstanceProfile string
53 SpotPriceUpdateInterval arvados.Duration
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)
67 type ec2InstanceSet struct {
68 ec2config ec2InstanceSetConfig
69 instanceSetID cloud.InstanceSetID
70 logger logrus.FieldLogger
73 keys map[string]string
74 throttleDelayCreate atomic.Value
75 throttleDelayInstances atomic.Value
77 prices map[priceKey][]cloud.InstancePrice
79 pricesUpdated map[priceKey]time.Time
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,
87 err = json.Unmarshal(config, &instanceSet.ec2config)
92 sess, err := session.NewSession()
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)},
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"
109 return instanceSet, nil
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())
117 // AWS uses the md5 or sha1 of the PKIX DER encoding of the
118 // public key, so calculate those fingerprints here.
124 if err := ssh.Unmarshal(pk.Marshal(), &rsaPub); err != nil {
125 return "", "", fmt.Errorf("agent: Unmarshal failed to parse public key: %v", err)
127 rsaPk := rsa.PublicKey{
128 E: int(rsaPub.E.Int64()),
131 pkix, _ := x509.MarshalPKIXPublicKey(&rsaPk)
132 md5pkix := md5.Sum([]byte(pkix))
133 sha1pkix := sha1.Sum([]byte(pkix))
136 for i := 0; i < len(md5pkix); i++ {
137 md5fp += fmt.Sprintf(":%02x", md5pkix[i])
139 for i := 0; i < len(sha1pkix); i++ {
140 sha1fp += fmt.Sprintf(":%02x", sha1pkix[i])
142 return md5fp[1:], sha1fp[1:], nil
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) {
152 keyname, err := instanceSet.getKeyName(publicKey)
157 ec2tags := []*ec2.Tag{}
158 for k, v := range newTags {
159 ec2tags = append(ec2tags, &ec2.Tag{
161 Value: aws.String(v),
166 for sg := range instanceSet.ec2config.SecurityGroupIDs {
167 groups = append(groups, sg)
170 rii := ec2.RunInstancesInput{
171 ImageId: aws.String(string(imageID)),
172 InstanceType: &instanceType.ProviderType,
173 MaxCount: aws.Int64(1),
174 MinCount: aws.Int64(1),
177 NetworkInterfaces: []*ec2.InstanceNetworkInterfaceSpecification{
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,
185 DisableApiTermination: aws.Bool(false),
186 InstanceInitiatedShutdownBehavior: aws.String("terminate"),
187 TagSpecifications: []*ec2.TagSpecification{
189 ResourceType: aws.String("instance"),
192 UserData: aws.String(base64.StdEncoding.EncodeToString([]byte("#!/bin/sh\n" + initCommand + "\n"))),
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,
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)),
214 if instanceSet.ec2config.IAMInstanceProfile != "" {
215 rii.IamInstanceProfile = &ec2.IamInstanceProfileSpecification{
216 Name: aws.String(instanceSet.ec2config.IAMInstanceProfile),
220 rsv, err := instanceSet.client.RunInstances(&rii)
221 err = wrapError(err, &instanceSet.throttleDelayCreate)
226 provider: instanceSet,
227 instance: rsv.Instances[0],
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)
236 return "", fmt.Errorf("Could not make key fingerprint: %v", err)
238 if keyname, ok := instanceSet.keys[md5keyFingerprint]; ok {
241 keyout, err := instanceSet.client.DescribeKeyPairs(&ec2.DescribeKeyPairsInput{
242 Filters: []*ec2.Filter{{
243 Name: aws.String("fingerprint"),
244 Values: []*string{&md5keyFingerprint, &sha1keyFingerprint},
248 return "", fmt.Errorf("Could not search for keypair: %v", err)
250 if len(keyout.KeyPairs) > 0 {
251 return *(keyout.KeyPairs[0].KeyName), nil
253 keyname := "arvados-dispatch-keypair-" + md5keyFingerprint
254 _, err = instanceSet.client.ImportKeyPair(&ec2.ImportKeyPairInput{
256 PublicKeyMaterial: ssh.MarshalAuthorizedKey(publicKey),
259 return "", fmt.Errorf("Could not import keypair: %v", err)
261 instanceSet.keys[md5keyFingerprint] = keyname
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)},
274 dii := &ec2.DescribeInstancesInput{Filters: filters}
276 dio, err := instanceSet.client.DescribeInstances(dii)
277 err = wrapError(err, &instanceSet.throttleDelayInstances)
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,
289 if aws.StringValue(inst.InstanceLifecycle) == "spot" {
295 if dio.NextToken == nil {
298 dii.NextToken = dio.NextToken
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
311 instanceSet.logger.Warnf("error getting instance statuses: %s", err)
313 for _, inst := range instances {
314 inst := inst.(*ec2Instance)
315 inst.availabilityZone = az[*inst.instance.InstanceId]
317 instanceSet.updateSpotPrices(instances)
319 return instances, err
322 type priceKey struct {
325 availabilityZone string
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 {
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{}
342 updateTime := time.Now()
343 staleTime := updateTime.Add(-instanceSet.ec2config.SpotPriceUpdateInterval.Duration())
345 allTypes := map[string]bool{}
347 for _, inst := range instances {
348 ec2inst := inst.(*ec2Instance).instance
349 if aws.StringValue(ec2inst.InstanceLifecycle) == "spot" {
351 instanceType: *ec2inst.InstanceType,
353 availabilityZone: inst.(*ec2Instance).availabilityZone,
355 if instanceSet.pricesUpdated[pk].Before(staleTime) {
358 allTypes[*ec2inst.InstanceType] = true
364 var typeFilterValues []*string
365 for instanceType := range allTypes {
366 typeFilterValues = append(typeFilterValues, aws.String(instanceType))
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
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")}},
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 {
388 price, err := strconv.ParseFloat(*ent.SpotPrice, 64)
394 instanceType: *ent.InstanceType,
396 availabilityZone: *ent.AvailabilityZone,
398 instanceSet.prices[pk] = append(instanceSet.prices[pk], cloud.InstancePrice{
399 StartTime: *ent.Timestamp,
402 instanceSet.pricesUpdated[pk] = updateTime
407 instanceSet.logger.Warnf("error retrieving spot instance prices: %s", err)
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)
417 for pk, prices := range instanceSet.prices {
418 instanceSet.prices[pk] = cloud.NormalizePriceHistory(prices)
422 func (instanceSet *ec2InstanceSet) Stop() {
425 type ec2Instance struct {
426 provider *ec2InstanceSet
427 instance *ec2.Instance
428 availabilityZone string // sometimes available for spot instances
431 func (inst *ec2Instance) ID() cloud.InstanceID {
432 return cloud.InstanceID(*inst.instance.InstanceId)
435 func (inst *ec2Instance) String() string {
436 return *inst.instance.InstanceId
439 func (inst *ec2Instance) ProviderType() string {
440 return *inst.instance.InstanceType
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{
448 Value: aws.String(v),
452 _, err := inst.provider.client.CreateTags(&ec2.CreateTagsInput{
453 Resources: []*string{inst.instance.InstanceId},
460 func (inst *ec2Instance) Tags() cloud.InstanceTags {
461 tags := make(map[string]string)
463 for _, t := range inst.instance.Tags {
464 tags[*t.Key] = *t.Value
470 func (inst *ec2Instance) Destroy() error {
471 _, err := inst.provider.client.TerminateInstances(&ec2.TerminateInstancesInput{
472 InstanceIds: []*string{inst.instance.InstanceId},
477 func (inst *ec2Instance) Address() string {
478 if inst.instance.PrivateIpAddress != nil {
479 return *inst.instance.PrivateIpAddress
484 func (inst *ec2Instance) RemoteUser() string {
485 return inst.provider.ec2config.AdminUsername
488 func (inst *ec2Instance) VerifyHostKey(ssh.PublicKey, *ssh.Client) error {
489 return cloud.ErrNotImplemented
492 // PriceHistory returns the price history for this specific instance.
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
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.)
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.)
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.
523 instanceType: *inst.instance.InstanceType,
524 spot: aws.StringValue(inst.instance.InstanceLifecycle) == "spot",
525 availabilityZone: inst.availabilityZone,
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)
539 type rateLimitError struct {
541 earliestRetry time.Time
544 func (err rateLimitError) EarliestRetry() time.Time {
545 return err.earliestRetry
548 var isCodeCapacity = map[string]bool{
549 "InsufficientFreeAddressesInSubnet": true,
550 "InsufficientInstanceCapacity": true,
551 "InsufficientVolumeCapacity": true,
552 "MaxSpotInstanceCountExceeded": true,
553 "VcpuLimitExceeded": true,
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 {
567 type ec2QuotaError struct {
571 func (er *ec2QuotaError) IsQuotaError() bool {
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 {
583 } else if d > throttleDelayMax {
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))
594 throttleValue.Store(time.Duration(0))