-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
97 lines (90 loc) · 2.33 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
package main
import (
"context"
"fmt"
"os"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/nathants/libaws/lib"
)
var (
uid = os.Getenv("uid")
keypairName = "test-keypair-" + uid
profileName = "test-profile-" + uid
ec2Name = "test-ec2-" + uid
vpcName = "test-vpc-" + uid
sgName = "test-sg-" + uid
inBucket = "in-bucket-" + uid
outBucket = "out-bucket-" + uid
)
const initTemplate = `#!/bin/bash
(
set -xeou pipefail
sudo apk update
sudo apk add aws-cli
echo "$(aws s3 cp s3://%s/%s -) from ec2" | aws s3 cp - s3://%s/%s
sudo poweroff
) &> /tmp/log.txt
`
func formatInitTemplate(inBucket, inKey, outBucket, outKey string) string {
return fmt.Sprintf(initTemplate, inBucket, inKey, outBucket, outKey)
}
func handleRequest(ctx context.Context, event events.S3Event) (events.APIGatewayProxyResponse, error) {
sgID, err := lib.EC2SgID(ctx, vpcName, sgName)
if err != nil {
panic(err)
}
amiID, user, err := lib.EC2AmiBase(ctx, lib.EC2AmiAlpine3160, lib.EC2ArchAmd64)
if err != nil {
panic(err)
}
vpcID, err := lib.VpcID(ctx, vpcName)
if err != nil {
panic(err)
}
zones, err := lib.EC2ZonesWithInstance(ctx, ec2.InstanceTypeT3Small)
if err != nil {
panic(err)
}
subnets, err := lib.VpcSubnets(ctx, vpcID)
if err != nil {
panic(err)
}
var spotSubnetIDs []string
for _, subnet := range subnets {
for _, zone := range zones {
if zone == *subnet.AvailabilityZone {
spotSubnetIDs = append(spotSubnetIDs, *subnet.SubnetId)
break
}
}
}
if len(spotSubnetIDs) == 0 {
panic("no availability")
}
for _, record := range event.Records {
key := record.S3.Object.Key
_, err := lib.EC2RequestSpotFleet(ctx, ec2.AllocationStrategyLowestPrice, &lib.EC2Config{
NumInstances: 1,
SgID: sgID,
SubnetIds: spotSubnetIDs,
Name: ec2Name + ":" + key,
AmiID: amiID,
Key: keypairName,
Profile: profileName,
UserName: user,
InstanceType: ec2.InstanceTypeT3Small,
SecondsTimeout: 900,
Gigs: 8,
Init: formatInitTemplate(inBucket, key, outBucket, key),
})
if err != nil {
panic(err)
}
}
return events.APIGatewayProxyResponse{StatusCode: 200}, nil
}
func main() {
lambda.Start(handleRequest)
}