1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
18 "git.arvados.org/arvados.git/lib/cloud"
19 "git.arvados.org/arvados.git/sdk/go/arvados"
20 "github.com/aws/aws-sdk-go/aws"
21 "github.com/aws/aws-sdk-go/aws/credentials"
22 "github.com/aws/aws-sdk-go/aws/session"
23 "github.com/aws/aws-sdk-go/service/ec2"
24 "github.com/sirupsen/logrus"
25 "golang.org/x/crypto/ssh"
28 // Driver is the ec2 implementation of the cloud.Driver interface.
29 var Driver = cloud.DriverFunc(newEC2InstanceSet)
31 type ec2InstanceSetConfig struct {
33 SecretAccessKey string
35 SecurityGroupIDs arvados.StringSet
41 type ec2Interface interface {
42 DescribeKeyPairs(input *ec2.DescribeKeyPairsInput) (*ec2.DescribeKeyPairsOutput, error)
43 ImportKeyPair(input *ec2.ImportKeyPairInput) (*ec2.ImportKeyPairOutput, error)
44 RunInstances(input *ec2.RunInstancesInput) (*ec2.Reservation, error)
45 DescribeInstances(input *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error)
46 CreateTags(input *ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error)
47 TerminateInstances(input *ec2.TerminateInstancesInput) (*ec2.TerminateInstancesOutput, error)
50 type ec2InstanceSet struct {
51 ec2config ec2InstanceSetConfig
52 instanceSetID cloud.InstanceSetID
53 logger logrus.FieldLogger
56 keys map[string]string
59 func newEC2InstanceSet(config json.RawMessage, instanceSetID cloud.InstanceSetID, _ cloud.SharedResourceTags, logger logrus.FieldLogger) (prv cloud.InstanceSet, err error) {
60 instanceSet := &ec2InstanceSet{
61 instanceSetID: instanceSetID,
64 err = json.Unmarshal(config, &instanceSet.ec2config)
68 awsConfig := aws.NewConfig().
69 WithCredentials(credentials.NewStaticCredentials(
70 instanceSet.ec2config.AccessKeyID,
71 instanceSet.ec2config.SecretAccessKey,
73 WithRegion(instanceSet.ec2config.Region)
74 instanceSet.client = ec2.New(session.Must(session.NewSession(awsConfig)))
75 instanceSet.keys = make(map[string]string)
76 if instanceSet.ec2config.EBSVolumeType == "" {
77 instanceSet.ec2config.EBSVolumeType = "gp2"
79 return instanceSet, nil
82 func awsKeyFingerprint(pk ssh.PublicKey) (md5fp string, sha1fp string, err error) {
83 // AWS key fingerprints don't use the usual key fingerprint
84 // you get from ssh-keygen or ssh.FingerprintLegacyMD5()
85 // (you can get that from md5.Sum(pk.Marshal())
87 // AWS uses the md5 or sha1 of the PKIX DER encoding of the
88 // public key, so calculate those fingerprints here.
94 if err := ssh.Unmarshal(pk.Marshal(), &rsaPub); err != nil {
95 return "", "", fmt.Errorf("agent: Unmarshal failed to parse public key: %v", err)
97 rsaPk := rsa.PublicKey{
98 E: int(rsaPub.E.Int64()),
101 pkix, _ := x509.MarshalPKIXPublicKey(&rsaPk)
102 md5pkix := md5.Sum([]byte(pkix))
103 sha1pkix := sha1.Sum([]byte(pkix))
106 for i := 0; i < len(md5pkix); i += 1 {
107 md5fp += fmt.Sprintf(":%02x", md5pkix[i])
109 for i := 0; i < len(sha1pkix); i += 1 {
110 sha1fp += fmt.Sprintf(":%02x", sha1pkix[i])
112 return md5fp[1:], sha1fp[1:], nil
115 func (instanceSet *ec2InstanceSet) Create(
116 instanceType arvados.InstanceType,
117 imageID cloud.ImageID,
118 newTags cloud.InstanceTags,
119 initCommand cloud.InitCommand,
120 publicKey ssh.PublicKey) (cloud.Instance, error) {
122 md5keyFingerprint, sha1keyFingerprint, err := awsKeyFingerprint(publicKey)
124 return nil, fmt.Errorf("Could not make key fingerprint: %v", err)
126 instanceSet.keysMtx.Lock()
129 if keyname, ok = instanceSet.keys[md5keyFingerprint]; !ok {
130 keyout, err := instanceSet.client.DescribeKeyPairs(&ec2.DescribeKeyPairsInput{
131 Filters: []*ec2.Filter{&ec2.Filter{
132 Name: aws.String("fingerprint"),
133 Values: []*string{&md5keyFingerprint, &sha1keyFingerprint},
137 return nil, fmt.Errorf("Could not search for keypair: %v", err)
140 if len(keyout.KeyPairs) > 0 {
141 keyname = *(keyout.KeyPairs[0].KeyName)
143 keyname = "arvados-dispatch-keypair-" + md5keyFingerprint
144 _, err := instanceSet.client.ImportKeyPair(&ec2.ImportKeyPairInput{
146 PublicKeyMaterial: ssh.MarshalAuthorizedKey(publicKey),
149 return nil, fmt.Errorf("Could not import keypair: %v", err)
152 instanceSet.keys[md5keyFingerprint] = keyname
154 instanceSet.keysMtx.Unlock()
156 ec2tags := []*ec2.Tag{}
157 for k, v := range newTags {
158 ec2tags = append(ec2tags, &ec2.Tag{
160 Value: aws.String(v),
165 for sg := range instanceSet.ec2config.SecurityGroupIDs {
166 groups = append(groups, sg)
169 rii := ec2.RunInstancesInput{
170 ImageId: aws.String(string(imageID)),
171 InstanceType: &instanceType.ProviderType,
172 MaxCount: aws.Int64(1),
173 MinCount: aws.Int64(1),
176 NetworkInterfaces: []*ec2.InstanceNetworkInterfaceSpecification{
177 &ec2.InstanceNetworkInterfaceSpecification{
178 AssociatePublicIpAddress: aws.Bool(false),
179 DeleteOnTermination: aws.Bool(true),
180 DeviceIndex: aws.Int64(0),
181 Groups: aws.StringSlice(groups),
182 SubnetId: &instanceSet.ec2config.SubnetID,
184 DisableApiTermination: aws.Bool(false),
185 InstanceInitiatedShutdownBehavior: aws.String("terminate"),
186 TagSpecifications: []*ec2.TagSpecification{
187 &ec2.TagSpecification{
188 ResourceType: aws.String("instance"),
191 UserData: aws.String(base64.StdEncoding.EncodeToString([]byte("#!/bin/sh\n" + initCommand + "\n"))),
194 if instanceType.AddedScratch > 0 {
195 rii.BlockDeviceMappings = []*ec2.BlockDeviceMapping{&ec2.BlockDeviceMapping{
196 DeviceName: aws.String("/dev/xvdt"),
197 Ebs: &ec2.EbsBlockDevice{
198 DeleteOnTermination: aws.Bool(true),
199 VolumeSize: aws.Int64((int64(instanceType.AddedScratch) + (1<<30 - 1)) >> 30),
200 VolumeType: &instanceSet.ec2config.EBSVolumeType,
204 if instanceType.Preemptible {
205 rii.InstanceMarketOptions = &ec2.InstanceMarketOptionsRequest{
206 MarketType: aws.String("spot"),
207 SpotOptions: &ec2.SpotMarketOptions{
208 InstanceInterruptionBehavior: aws.String("terminate"),
209 MaxPrice: aws.String(fmt.Sprintf("%v", instanceType.Price)),
213 rsv, err := instanceSet.client.RunInstances(&rii)
220 provider: instanceSet,
221 instance: rsv.Instances[0],
225 func (instanceSet *ec2InstanceSet) Instances(tags cloud.InstanceTags) (instances []cloud.Instance, err error) {
226 var filters []*ec2.Filter
227 for k, v := range tags {
228 filters = append(filters, &ec2.Filter{
229 Name: aws.String("tag:" + k),
230 Values: []*string{aws.String(v)},
233 dii := &ec2.DescribeInstancesInput{Filters: filters}
235 dio, err := instanceSet.client.DescribeInstances(dii)
240 for _, rsv := range dio.Reservations {
241 for _, inst := range rsv.Instances {
242 if *inst.State.Name != "shutting-down" && *inst.State.Name != "terminated" {
243 instances = append(instances, &ec2Instance{instanceSet, inst})
247 if dio.NextToken == nil {
248 return instances, err
250 dii.NextToken = dio.NextToken
254 func (az *ec2InstanceSet) Stop() {
257 type ec2Instance struct {
258 provider *ec2InstanceSet
259 instance *ec2.Instance
262 func (inst *ec2Instance) ID() cloud.InstanceID {
263 return cloud.InstanceID(*inst.instance.InstanceId)
266 func (inst *ec2Instance) String() string {
267 return *inst.instance.InstanceId
270 func (inst *ec2Instance) ProviderType() string {
271 return *inst.instance.InstanceType
274 func (inst *ec2Instance) SetTags(newTags cloud.InstanceTags) error {
275 var ec2tags []*ec2.Tag
276 for k, v := range newTags {
277 ec2tags = append(ec2tags, &ec2.Tag{
279 Value: aws.String(v),
283 _, err := inst.provider.client.CreateTags(&ec2.CreateTagsInput{
284 Resources: []*string{inst.instance.InstanceId},
291 func (inst *ec2Instance) Tags() cloud.InstanceTags {
292 tags := make(map[string]string)
294 for _, t := range inst.instance.Tags {
295 tags[*t.Key] = *t.Value
301 func (inst *ec2Instance) Destroy() error {
302 _, err := inst.provider.client.TerminateInstances(&ec2.TerminateInstancesInput{
303 InstanceIds: []*string{inst.instance.InstanceId},
308 func (inst *ec2Instance) Address() string {
309 if inst.instance.PrivateIpAddress != nil {
310 return *inst.instance.PrivateIpAddress
316 func (inst *ec2Instance) RemoteUser() string {
317 return inst.provider.ec2config.AdminUsername
320 func (inst *ec2Instance) VerifyHostKey(ssh.PublicKey, *ssh.Client) error {
321 return cloud.ErrNotImplemented