1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
19 "git.curoverse.com/arvados.git/lib/cloud"
20 "git.curoverse.com/arvados.git/sdk/go/arvados"
21 "github.com/aws/aws-sdk-go/aws"
22 "github.com/aws/aws-sdk-go/aws/credentials"
23 "github.com/aws/aws-sdk-go/aws/session"
24 "github.com/aws/aws-sdk-go/service/ec2"
25 "github.com/sirupsen/logrus"
26 "golang.org/x/crypto/ssh"
29 const arvadosDispatchID = "arvados-dispatch-id"
30 const tagPrefix = "arvados-dispatch-tag-"
32 // Driver is the ec2 implementation of the cloud.Driver interface.
33 var Driver = cloud.DriverFunc(newEC2InstanceSet)
35 type ec2InstanceSetConfig struct {
37 SecretAccessKey string
39 SecurityGroupIDs []string
45 type ec2Interface interface {
46 DescribeKeyPairs(input *ec2.DescribeKeyPairsInput) (*ec2.DescribeKeyPairsOutput, error)
47 ImportKeyPair(input *ec2.ImportKeyPairInput) (*ec2.ImportKeyPairOutput, error)
48 RunInstances(input *ec2.RunInstancesInput) (*ec2.Reservation, error)
49 DescribeInstances(input *ec2.DescribeInstancesInput) (*ec2.DescribeInstancesOutput, error)
50 CreateTags(input *ec2.CreateTagsInput) (*ec2.CreateTagsOutput, error)
51 TerminateInstances(input *ec2.TerminateInstancesInput) (*ec2.TerminateInstancesOutput, error)
54 type ec2InstanceSet struct {
55 ec2config ec2InstanceSetConfig
56 dispatcherID cloud.InstanceSetID
57 logger logrus.FieldLogger
60 keys map[string]string
63 func newEC2InstanceSet(config json.RawMessage, dispatcherID cloud.InstanceSetID, logger logrus.FieldLogger) (prv cloud.InstanceSet, err error) {
64 instanceSet := &ec2InstanceSet{
65 dispatcherID: dispatcherID,
68 err = json.Unmarshal(config, &instanceSet.ec2config)
72 awsConfig := aws.NewConfig().
73 WithCredentials(credentials.NewStaticCredentials(
74 instanceSet.ec2config.AccessKeyID,
75 instanceSet.ec2config.SecretAccessKey,
77 WithRegion(instanceSet.ec2config.Region)
78 instanceSet.client = ec2.New(session.Must(session.NewSession(awsConfig)))
79 instanceSet.keys = make(map[string]string)
80 if instanceSet.ec2config.EBSVolumeType == "" {
81 instanceSet.ec2config.EBSVolumeType = "gp2"
83 return instanceSet, nil
86 func awsKeyFingerprint(pk ssh.PublicKey) (md5fp string, sha1fp string, err error) {
87 // AWS key fingerprints don't use the usual key fingerprint
88 // you get from ssh-keygen or ssh.FingerprintLegacyMD5()
89 // (you can get that from md5.Sum(pk.Marshal())
91 // AWS uses the md5 or sha1 of the PKIX DER encoding of the
92 // public key, so calculate those fingerprints here.
98 if err := ssh.Unmarshal(pk.Marshal(), &rsaPub); err != nil {
99 return "", "", fmt.Errorf("agent: Unmarshal failed to parse public key: %v", err)
101 rsaPk := rsa.PublicKey{
102 E: int(rsaPub.E.Int64()),
105 pkix, _ := x509.MarshalPKIXPublicKey(&rsaPk)
106 md5pkix := md5.Sum([]byte(pkix))
107 sha1pkix := sha1.Sum([]byte(pkix))
110 for i := 0; i < len(md5pkix); i += 1 {
111 md5fp += fmt.Sprintf(":%02x", md5pkix[i])
113 for i := 0; i < len(sha1pkix); i += 1 {
114 sha1fp += fmt.Sprintf(":%02x", sha1pkix[i])
116 return md5fp[1:], sha1fp[1:], nil
119 func (instanceSet *ec2InstanceSet) Create(
120 instanceType arvados.InstanceType,
121 imageID cloud.ImageID,
122 newTags cloud.InstanceTags,
123 initCommand cloud.InitCommand,
124 publicKey ssh.PublicKey) (cloud.Instance, error) {
126 md5keyFingerprint, sha1keyFingerprint, err := awsKeyFingerprint(publicKey)
128 return nil, fmt.Errorf("Could not make key fingerprint: %v", err)
130 instanceSet.keysMtx.Lock()
133 if keyname, ok = instanceSet.keys[md5keyFingerprint]; !ok {
134 keyout, err := instanceSet.client.DescribeKeyPairs(&ec2.DescribeKeyPairsInput{
135 Filters: []*ec2.Filter{&ec2.Filter{
136 Name: aws.String("fingerprint"),
137 Values: []*string{&md5keyFingerprint, &sha1keyFingerprint},
141 return nil, fmt.Errorf("Could not search for keypair: %v", err)
144 if len(keyout.KeyPairs) > 0 {
145 keyname = *(keyout.KeyPairs[0].KeyName)
147 keyname = "arvados-dispatch-keypair-" + md5keyFingerprint
148 _, err := instanceSet.client.ImportKeyPair(&ec2.ImportKeyPairInput{
150 PublicKeyMaterial: ssh.MarshalAuthorizedKey(publicKey),
153 return nil, fmt.Errorf("Could not import keypair: %v", err)
156 instanceSet.keys[md5keyFingerprint] = keyname
158 instanceSet.keysMtx.Unlock()
160 ec2tags := []*ec2.Tag{
162 Key: aws.String(arvadosDispatchID),
163 Value: aws.String(string(instanceSet.dispatcherID)),
166 Key: aws.String("arvados-class"),
167 Value: aws.String("dynamic-compute"),
170 for k, v := range newTags {
171 ec2tags = append(ec2tags, &ec2.Tag{
172 Key: aws.String(tagPrefix + k),
173 Value: aws.String(v),
177 rii := ec2.RunInstancesInput{
178 ImageId: aws.String(string(imageID)),
179 InstanceType: &instanceType.ProviderType,
180 MaxCount: aws.Int64(1),
181 MinCount: aws.Int64(1),
184 NetworkInterfaces: []*ec2.InstanceNetworkInterfaceSpecification{
185 &ec2.InstanceNetworkInterfaceSpecification{
186 AssociatePublicIpAddress: aws.Bool(false),
187 DeleteOnTermination: aws.Bool(true),
188 DeviceIndex: aws.Int64(0),
189 Groups: aws.StringSlice(instanceSet.ec2config.SecurityGroupIDs),
190 SubnetId: &instanceSet.ec2config.SubnetID,
192 DisableApiTermination: aws.Bool(false),
193 InstanceInitiatedShutdownBehavior: aws.String("terminate"),
194 UserData: aws.String(base64.StdEncoding.EncodeToString([]byte("#!/bin/sh\n" + initCommand + "\n"))),
195 TagSpecifications: []*ec2.TagSpecification{
196 &ec2.TagSpecification{
197 ResourceType: aws.String("instance"),
202 if instanceType.AddedScratch > 0 {
203 rii.BlockDeviceMappings = []*ec2.BlockDeviceMapping{&ec2.BlockDeviceMapping{
204 DeviceName: aws.String("/dev/xvdt"),
205 Ebs: &ec2.EbsBlockDevice{
206 DeleteOnTermination: aws.Bool(true),
207 VolumeSize: aws.Int64((int64(instanceType.AddedScratch) + (1<<30 - 1)) >> 30),
208 VolumeType: &instanceSet.ec2config.EBSVolumeType,
212 if instanceType.Preemptible {
213 rii.InstanceMarketOptions = &ec2.InstanceMarketOptionsRequest{
214 MarketType: aws.String("spot"),
215 SpotOptions: &ec2.SpotMarketOptions{
216 InstanceInterruptionBehavior: aws.String("terminate"),
217 MaxPrice: aws.String(fmt.Sprintf("%v", instanceType.Price)),
221 rsv, err := instanceSet.client.RunInstances(&rii)
228 provider: instanceSet,
229 instance: rsv.Instances[0],
233 func (instanceSet *ec2InstanceSet) Instances(cloud.InstanceTags) (instances []cloud.Instance, err error) {
234 dii := &ec2.DescribeInstancesInput{
235 Filters: []*ec2.Filter{&ec2.Filter{
236 Name: aws.String("tag:" + arvadosDispatchID),
237 Values: []*string{aws.String(string(instanceSet.dispatcherID))},
241 dio, err := instanceSet.client.DescribeInstances(dii)
246 for _, rsv := range dio.Reservations {
247 for _, inst := range rsv.Instances {
248 if *inst.State.Name != "shutting-down" && *inst.State.Name != "terminated" {
249 instances = append(instances, &ec2Instance{instanceSet, inst})
253 if dio.NextToken == nil {
254 return instances, err
256 dii.NextToken = dio.NextToken
260 func (az *ec2InstanceSet) Stop() {
263 type ec2Instance struct {
264 provider *ec2InstanceSet
265 instance *ec2.Instance
268 func (inst *ec2Instance) ID() cloud.InstanceID {
269 return cloud.InstanceID(*inst.instance.InstanceId)
272 func (inst *ec2Instance) String() string {
273 return *inst.instance.InstanceId
276 func (inst *ec2Instance) ProviderType() string {
277 return *inst.instance.InstanceType
280 func (inst *ec2Instance) SetTags(newTags cloud.InstanceTags) error {
281 ec2tags := []*ec2.Tag{
283 Key: aws.String(arvadosDispatchID),
284 Value: aws.String(string(inst.provider.dispatcherID)),
287 for k, v := range newTags {
288 ec2tags = append(ec2tags, &ec2.Tag{
289 Key: aws.String(tagPrefix + k),
290 Value: aws.String(v),
294 _, err := inst.provider.client.CreateTags(&ec2.CreateTagsInput{
295 Resources: []*string{inst.instance.InstanceId},
302 func (inst *ec2Instance) Tags() cloud.InstanceTags {
303 tags := make(map[string]string)
305 for _, t := range inst.instance.Tags {
306 if strings.HasPrefix(*t.Key, tagPrefix) {
307 tags[(*t.Key)[len(tagPrefix):]] = *t.Value
314 func (inst *ec2Instance) Destroy() error {
315 _, err := inst.provider.client.TerminateInstances(&ec2.TerminateInstancesInput{
316 InstanceIds: []*string{inst.instance.InstanceId},
321 func (inst *ec2Instance) Address() string {
322 if inst.instance.PrivateIpAddress != nil {
323 return *inst.instance.PrivateIpAddress
329 func (inst *ec2Instance) RemoteUser() string {
330 return inst.provider.ec2config.AdminUsername
333 func (inst *ec2Instance) VerifyHostKey(ssh.PublicKey, *ssh.Client) error {
334 return cloud.ErrNotImplemented