1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
20 "git.arvados.org/arvados.git/lib/cloud"
21 "git.arvados.org/arvados.git/sdk/go/arvados"
22 "github.com/aws/aws-sdk-go/aws"
23 "github.com/aws/aws-sdk-go/aws/credentials"
24 "github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
25 "github.com/aws/aws-sdk-go/aws/ec2metadata"
26 "github.com/aws/aws-sdk-go/aws/request"
27 "github.com/aws/aws-sdk-go/aws/session"
28 "github.com/aws/aws-sdk-go/service/ec2"
29 "github.com/sirupsen/logrus"
30 "golang.org/x/crypto/ssh"
33 // Driver is the ec2 implementation of the cloud.Driver interface.
34 var Driver = cloud.DriverFunc(newEC2InstanceSet)
37 throttleDelayMin = time.Second
38 throttleDelayMax = time.Minute
41 type ec2InstanceSetConfig struct {
43 SecretAccessKey string
45 SecurityGroupIDs arvados.StringSet
51 type ec2Interface interface {
52 DescribeKeyPairs(input *ec2.DescribeKeyPairsInput) (*ec2.DescribeKeyPairsOutput, error)
53 ImportKeyPair(input *ec2.ImportKeyPairInput) (*ec2.ImportKeyPairOutput, error)
54 RunInstances(input *ec2.RunInstancesInput) (*ec2.Reservation, error)
55 DescribeInstances(input *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error)
56 CreateTags(input *ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error)
57 TerminateInstances(input *ec2.TerminateInstancesInput) (*ec2.TerminateInstancesOutput, error)
60 type ec2InstanceSet struct {
61 ec2config ec2InstanceSetConfig
62 instanceSetID cloud.InstanceSetID
63 logger logrus.FieldLogger
66 keys map[string]string
67 throttleDelayCreate atomic.Value
68 throttleDelayInstances atomic.Value
71 func newEC2InstanceSet(config json.RawMessage, instanceSetID cloud.InstanceSetID, _ cloud.SharedResourceTags, logger logrus.FieldLogger) (prv cloud.InstanceSet, err error) {
72 instanceSet := &ec2InstanceSet{
73 instanceSetID: instanceSetID,
76 err = json.Unmarshal(config, &instanceSet.ec2config)
81 sess, err := session.NewSession()
85 // First try any static credentials, fall back to an IAM instance profile/role
86 creds := credentials.NewChainCredentials(
87 []credentials.Provider{
88 &credentials.StaticProvider{Value: credentials.Value{AccessKeyID: instanceSet.ec2config.AccessKeyID, SecretAccessKey: instanceSet.ec2config.SecretAccessKey}},
89 &ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess)},
92 awsConfig := aws.NewConfig().WithCredentials(creds).WithRegion(instanceSet.ec2config.Region)
93 instanceSet.client = ec2.New(session.Must(session.NewSession(awsConfig)))
94 instanceSet.keys = make(map[string]string)
95 if instanceSet.ec2config.EBSVolumeType == "" {
96 instanceSet.ec2config.EBSVolumeType = "gp2"
98 return instanceSet, nil
101 func awsKeyFingerprint(pk ssh.PublicKey) (md5fp string, sha1fp string, err error) {
102 // AWS key fingerprints don't use the usual key fingerprint
103 // you get from ssh-keygen or ssh.FingerprintLegacyMD5()
104 // (you can get that from md5.Sum(pk.Marshal())
106 // AWS uses the md5 or sha1 of the PKIX DER encoding of the
107 // public key, so calculate those fingerprints here.
113 if err := ssh.Unmarshal(pk.Marshal(), &rsaPub); err != nil {
114 return "", "", fmt.Errorf("agent: Unmarshal failed to parse public key: %v", err)
116 rsaPk := rsa.PublicKey{
117 E: int(rsaPub.E.Int64()),
120 pkix, _ := x509.MarshalPKIXPublicKey(&rsaPk)
121 md5pkix := md5.Sum([]byte(pkix))
122 sha1pkix := sha1.Sum([]byte(pkix))
125 for i := 0; i < len(md5pkix); i++ {
126 md5fp += fmt.Sprintf(":%02x", md5pkix[i])
128 for i := 0; i < len(sha1pkix); i++ {
129 sha1fp += fmt.Sprintf(":%02x", sha1pkix[i])
131 return md5fp[1:], sha1fp[1:], nil
134 func (instanceSet *ec2InstanceSet) Create(
135 instanceType arvados.InstanceType,
136 imageID cloud.ImageID,
137 newTags cloud.InstanceTags,
138 initCommand cloud.InitCommand,
139 publicKey ssh.PublicKey) (cloud.Instance, error) {
141 md5keyFingerprint, sha1keyFingerprint, err := awsKeyFingerprint(publicKey)
143 return nil, fmt.Errorf("Could not make key fingerprint: %v", err)
145 instanceSet.keysMtx.Lock()
148 if keyname, ok = instanceSet.keys[md5keyFingerprint]; !ok {
149 keyout, err := instanceSet.client.DescribeKeyPairs(&ec2.DescribeKeyPairsInput{
150 Filters: []*ec2.Filter{{
151 Name: aws.String("fingerprint"),
152 Values: []*string{&md5keyFingerprint, &sha1keyFingerprint},
156 return nil, fmt.Errorf("Could not search for keypair: %v", err)
159 if len(keyout.KeyPairs) > 0 {
160 keyname = *(keyout.KeyPairs[0].KeyName)
162 keyname = "arvados-dispatch-keypair-" + md5keyFingerprint
163 _, err := instanceSet.client.ImportKeyPair(&ec2.ImportKeyPairInput{
165 PublicKeyMaterial: ssh.MarshalAuthorizedKey(publicKey),
168 return nil, fmt.Errorf("Could not import keypair: %v", err)
171 instanceSet.keys[md5keyFingerprint] = keyname
173 instanceSet.keysMtx.Unlock()
175 ec2tags := []*ec2.Tag{}
176 for k, v := range newTags {
177 ec2tags = append(ec2tags, &ec2.Tag{
179 Value: aws.String(v),
184 for sg := range instanceSet.ec2config.SecurityGroupIDs {
185 groups = append(groups, sg)
188 rii := ec2.RunInstancesInput{
189 ImageId: aws.String(string(imageID)),
190 InstanceType: &instanceType.ProviderType,
191 MaxCount: aws.Int64(1),
192 MinCount: aws.Int64(1),
195 NetworkInterfaces: []*ec2.InstanceNetworkInterfaceSpecification{
197 AssociatePublicIpAddress: aws.Bool(false),
198 DeleteOnTermination: aws.Bool(true),
199 DeviceIndex: aws.Int64(0),
200 Groups: aws.StringSlice(groups),
201 SubnetId: &instanceSet.ec2config.SubnetID,
203 DisableApiTermination: aws.Bool(false),
204 InstanceInitiatedShutdownBehavior: aws.String("terminate"),
205 TagSpecifications: []*ec2.TagSpecification{
207 ResourceType: aws.String("instance"),
210 UserData: aws.String(base64.StdEncoding.EncodeToString([]byte("#!/bin/sh\n" + initCommand + "\n"))),
213 if instanceType.AddedScratch > 0 {
214 rii.BlockDeviceMappings = []*ec2.BlockDeviceMapping{{
215 DeviceName: aws.String("/dev/xvdt"),
216 Ebs: &ec2.EbsBlockDevice{
217 DeleteOnTermination: aws.Bool(true),
218 VolumeSize: aws.Int64((int64(instanceType.AddedScratch) + (1<<30 - 1)) >> 30),
219 VolumeType: &instanceSet.ec2config.EBSVolumeType,
223 if instanceType.Preemptible {
224 rii.InstanceMarketOptions = &ec2.InstanceMarketOptionsRequest{
225 MarketType: aws.String("spot"),
226 SpotOptions: &ec2.SpotMarketOptions{
227 InstanceInterruptionBehavior: aws.String("terminate"),
228 MaxPrice: aws.String(fmt.Sprintf("%v", instanceType.Price)),
232 rsv, err := instanceSet.client.RunInstances(&rii)
233 err = wrapError(err, &instanceSet.throttleDelayCreate)
239 provider: instanceSet,
240 instance: rsv.Instances[0],
244 func (instanceSet *ec2InstanceSet) Instances(tags cloud.InstanceTags) (instances []cloud.Instance, err error) {
245 var filters []*ec2.Filter
246 for k, v := range tags {
247 filters = append(filters, &ec2.Filter{
248 Name: aws.String("tag:" + k),
249 Values: []*string{aws.String(v)},
252 dii := &ec2.DescribeInstancesInput{Filters: filters}
254 dio, err := instanceSet.client.DescribeInstances(dii)
255 err = wrapError(err, &instanceSet.throttleDelayInstances)
260 for _, rsv := range dio.Reservations {
261 for _, inst := range rsv.Instances {
262 if *inst.State.Name != "shutting-down" && *inst.State.Name != "terminated" {
263 instances = append(instances, &ec2Instance{instanceSet, inst})
267 if dio.NextToken == nil {
268 return instances, err
270 dii.NextToken = dio.NextToken
274 func (instanceSet *ec2InstanceSet) Stop() {
277 type ec2Instance struct {
278 provider *ec2InstanceSet
279 instance *ec2.Instance
282 func (inst *ec2Instance) ID() cloud.InstanceID {
283 return cloud.InstanceID(*inst.instance.InstanceId)
286 func (inst *ec2Instance) String() string {
287 return *inst.instance.InstanceId
290 func (inst *ec2Instance) ProviderType() string {
291 return *inst.instance.InstanceType
294 func (inst *ec2Instance) SetTags(newTags cloud.InstanceTags) error {
295 var ec2tags []*ec2.Tag
296 for k, v := range newTags {
297 ec2tags = append(ec2tags, &ec2.Tag{
299 Value: aws.String(v),
303 _, err := inst.provider.client.CreateTags(&ec2.CreateTagsInput{
304 Resources: []*string{inst.instance.InstanceId},
311 func (inst *ec2Instance) Tags() cloud.InstanceTags {
312 tags := make(map[string]string)
314 for _, t := range inst.instance.Tags {
315 tags[*t.Key] = *t.Value
321 func (inst *ec2Instance) Destroy() error {
322 _, err := inst.provider.client.TerminateInstances(&ec2.TerminateInstancesInput{
323 InstanceIds: []*string{inst.instance.InstanceId},
328 func (inst *ec2Instance) Address() string {
329 if inst.instance.PrivateIpAddress != nil {
330 return *inst.instance.PrivateIpAddress
335 func (inst *ec2Instance) RemoteUser() string {
336 return inst.provider.ec2config.AdminUsername
339 func (inst *ec2Instance) VerifyHostKey(ssh.PublicKey, *ssh.Client) error {
340 return cloud.ErrNotImplemented
343 type rateLimitError struct {
345 earliestRetry time.Time
348 func (err rateLimitError) EarliestRetry() time.Time {
349 return err.earliestRetry
352 func wrapError(err error, throttleValue *atomic.Value) error {
353 if request.IsErrorThrottle(err) {
354 // Back off exponentially until an upstream call
355 // either succeeds or returns a non-throttle error.
356 d, _ := throttleValue.Load().(time.Duration)
357 d = d*3/2 + time.Second
358 if d < throttleDelayMin {
360 } else if d > throttleDelayMax {
363 throttleValue.Store(d)
364 return rateLimitError{error: err, earliestRetry: time.Now().Add(d)}
365 } else if err != nil {
366 throttleValue.Store(time.Duration(0))
369 throttleValue.Store(time.Duration(0))