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 md5keyFingerprint, sha1keyFingerprint, err := awsKeyFingerprint(publicKey)
154 return nil, fmt.Errorf("Could not make key fingerprint: %v", err)
156 instanceSet.keysMtx.Lock()
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},
167 return nil, fmt.Errorf("Could not search for keypair: %v", err)
170 if len(keyout.KeyPairs) > 0 {
171 keyname = *(keyout.KeyPairs[0].KeyName)
173 keyname = "arvados-dispatch-keypair-" + md5keyFingerprint
174 _, err := instanceSet.client.ImportKeyPair(&ec2.ImportKeyPairInput{
176 PublicKeyMaterial: ssh.MarshalAuthorizedKey(publicKey),
179 return nil, fmt.Errorf("Could not import keypair: %v", err)
182 instanceSet.keys[md5keyFingerprint] = keyname
184 instanceSet.keysMtx.Unlock()
186 ec2tags := []*ec2.Tag{}
187 for k, v := range newTags {
188 ec2tags = append(ec2tags, &ec2.Tag{
190 Value: aws.String(v),
195 for sg := range instanceSet.ec2config.SecurityGroupIDs {
196 groups = append(groups, sg)
199 rii := ec2.RunInstancesInput{
200 ImageId: aws.String(string(imageID)),
201 InstanceType: &instanceType.ProviderType,
202 MaxCount: aws.Int64(1),
203 MinCount: aws.Int64(1),
206 NetworkInterfaces: []*ec2.InstanceNetworkInterfaceSpecification{
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,
214 DisableApiTermination: aws.Bool(false),
215 InstanceInitiatedShutdownBehavior: aws.String("terminate"),
216 TagSpecifications: []*ec2.TagSpecification{
218 ResourceType: aws.String("instance"),
221 UserData: aws.String(base64.StdEncoding.EncodeToString([]byte("#!/bin/sh\n" + initCommand + "\n"))),
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,
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)),
243 if instanceSet.ec2config.IAMInstanceProfile != "" {
244 rii.IamInstanceProfile = &ec2.IamInstanceProfileSpecification{
245 Name: aws.String(instanceSet.ec2config.IAMInstanceProfile),
249 rsv, err := instanceSet.client.RunInstances(&rii)
250 err = wrapError(err, &instanceSet.throttleDelayCreate)
255 provider: instanceSet,
256 instance: rsv.Instances[0],
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)},
269 dii := &ec2.DescribeInstancesInput{Filters: filters}
271 dio, err := instanceSet.client.DescribeInstances(dii)
272 err = wrapError(err, &instanceSet.throttleDelayInstances)
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,
284 if aws.StringValue(inst.InstanceLifecycle) == "spot" {
290 if dio.NextToken == nil {
293 dii.NextToken = dio.NextToken
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
306 instanceSet.logger.Warnf("error getting instance statuses: %s", err)
308 for _, inst := range instances {
309 inst := inst.(*ec2Instance)
310 inst.availabilityZone = az[*inst.instance.InstanceId]
312 instanceSet.updateSpotPrices(instances)
314 return instances, err
317 type priceKey struct {
320 availabilityZone string
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 {
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{}
337 updateTime := time.Now()
338 staleTime := updateTime.Add(-instanceSet.ec2config.SpotPriceUpdateInterval.Duration())
340 allTypes := map[string]bool{}
342 for _, inst := range instances {
343 ec2inst := inst.(*ec2Instance).instance
344 if aws.StringValue(ec2inst.InstanceLifecycle) == "spot" {
346 instanceType: *ec2inst.InstanceType,
348 availabilityZone: inst.(*ec2Instance).availabilityZone,
350 if instanceSet.pricesUpdated[pk].Before(staleTime) {
353 allTypes[*ec2inst.InstanceType] = true
359 var typeFilterValues []*string
360 for instanceType := range allTypes {
361 typeFilterValues = append(typeFilterValues, aws.String(instanceType))
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
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")}},
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 {
383 price, err := strconv.ParseFloat(*ent.SpotPrice, 64)
389 instanceType: *ent.InstanceType,
391 availabilityZone: *ent.AvailabilityZone,
393 instanceSet.prices[pk] = append(instanceSet.prices[pk], cloud.InstancePrice{
394 StartTime: *ent.Timestamp,
397 instanceSet.pricesUpdated[pk] = updateTime
402 instanceSet.logger.Warnf("error retrieving spot instance prices: %s", err)
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)
412 for pk, prices := range instanceSet.prices {
413 instanceSet.prices[pk] = cloud.NormalizePriceHistory(prices)
417 func (instanceSet *ec2InstanceSet) Stop() {
420 type ec2Instance struct {
421 provider *ec2InstanceSet
422 instance *ec2.Instance
423 availabilityZone string // sometimes available for spot instances
426 func (inst *ec2Instance) ID() cloud.InstanceID {
427 return cloud.InstanceID(*inst.instance.InstanceId)
430 func (inst *ec2Instance) String() string {
431 return *inst.instance.InstanceId
434 func (inst *ec2Instance) ProviderType() string {
435 return *inst.instance.InstanceType
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{
443 Value: aws.String(v),
447 _, err := inst.provider.client.CreateTags(&ec2.CreateTagsInput{
448 Resources: []*string{inst.instance.InstanceId},
455 func (inst *ec2Instance) Tags() cloud.InstanceTags {
456 tags := make(map[string]string)
458 for _, t := range inst.instance.Tags {
459 tags[*t.Key] = *t.Value
465 func (inst *ec2Instance) Destroy() error {
466 _, err := inst.provider.client.TerminateInstances(&ec2.TerminateInstancesInput{
467 InstanceIds: []*string{inst.instance.InstanceId},
472 func (inst *ec2Instance) Address() string {
473 if inst.instance.PrivateIpAddress != nil {
474 return *inst.instance.PrivateIpAddress
479 func (inst *ec2Instance) RemoteUser() string {
480 return inst.provider.ec2config.AdminUsername
483 func (inst *ec2Instance) VerifyHostKey(ssh.PublicKey, *ssh.Client) error {
484 return cloud.ErrNotImplemented
487 // PriceHistory returns the price history for this specific instance.
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
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.)
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.)
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.
518 instanceType: *inst.instance.InstanceType,
519 spot: aws.StringValue(inst.instance.InstanceLifecycle) == "spot",
520 availabilityZone: inst.availabilityZone,
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)
534 type rateLimitError struct {
536 earliestRetry time.Time
539 func (err rateLimitError) EarliestRetry() time.Time {
540 return err.earliestRetry
543 var isCodeCapacity = map[string]bool{
544 "InsufficientFreeAddressesInSubnet": true,
545 "InsufficientInstanceCapacity": true,
546 "InsufficientVolumeCapacity": true,
547 "MaxSpotInstanceCountExceeded": true,
548 "VcpuLimitExceeded": true,
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 {
562 type ec2QuotaError struct {
566 func (er *ec2QuotaError) IsQuotaError() bool {
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 {
578 } else if d > throttleDelayMax {
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))
589 throttleValue.Store(time.Duration(0))