-
Notifications
You must be signed in to change notification settings - Fork 0
/
ec2.go
235 lines (200 loc) · 6.21 KB
/
ec2.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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package child
import (
"fmt"
"log"
"net"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/djmitche/proj/internal/config"
"github.com/djmitche/proj/internal/ssh"
)
func setupEc2(ec2HostConfig *config.Ec2HostConfig, childConfig *config.ChildConfig) (*ec2.EC2, error) {
var creds *credentials.Credentials
if ec2HostConfig.Access_Key != "" {
if ec2HostConfig.Secret_Key == "" {
return nil, fmt.Errorf("config includes ec2 id but not secret")
}
creds = credentials.NewStaticCredentials(
ec2HostConfig.Access_Key,
ec2HostConfig.Secret_Key,
"")
}
svc := ec2.New(session.New(), &aws.Config{
Region: aws.String(ec2HostConfig.Region),
Credentials: creds})
log.Printf("Connected to EC2 in region %s", ec2HostConfig.Region)
return svc, nil
}
func findInstance(ec2HostConfig *config.Ec2HostConfig, svc *ec2.EC2) (*ec2.Instance, error) {
region, name := ec2HostConfig.Region, ec2HostConfig.Name
log.Printf("Searching for instance named %q in region %s", name, region)
params := &ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("tag:Name"),
Values: []*string{
aws.String(ec2HostConfig.Name),
},
},
},
}
resp, err := svc.DescribeInstances(params)
if err != nil {
return nil, err
}
if len(resp.Reservations) < 1 {
return nil, fmt.Errorf("no instance found in %s with name %s", region, name)
}
if len(resp.Reservations) > 1 || len(resp.Reservations[0].Instances) != 1 {
return nil, fmt.Errorf("multiple instances found in %s with name %s", region, name)
}
return resp.Reservations[0].Instances[0], nil
}
// Get the instance address, optionally re-calling fetchInstance in case the instance data does
// not contain an address.
func instanceAddress(_instance *ec2.Instance, ec2HostConfig *config.Ec2HostConfig, svc *ec2.EC2) (instance *ec2.Instance, address string, err error) {
instance = _instance
instance, address, err = _getInstanceAddress(instance)
if err != nil {
instance, err = findInstance(ec2HostConfig, svc)
if err != nil {
return
}
}
instance, address, err = _getInstanceAddress(instance)
return
}
func _getInstanceAddress(_instance *ec2.Instance) (instance *ec2.Instance, address string, err error) {
instance = _instance
err = nil
// first try for an Ipv6 address
for _, netif := range instance.NetworkInterfaces {
for _, ipv6 := range netif.Ipv6Addresses {
if ipv6.Ipv6Address != nil {
log.Printf("Found IPv6 address %s", *ipv6.Ipv6Address)
address = *ipv6.Ipv6Address
return
}
}
}
if instance.PublicIpAddress != nil {
log.Printf("Found IPv4 address %s", *instance.PublicIpAddress)
address = *instance.PublicIpAddress
return
}
err = fmt.Errorf("No public addresses found")
return
}
func startInstance(ec2HostConfig *config.Ec2HostConfig, instance *ec2.Instance, svc *ec2.EC2) error {
startCalled := false
instanceId := *instance.InstanceId
// wait until the state is anything but "pending"
statePoll:
for {
state, err := getInstanceState(instanceId, svc)
if err != nil {
return err
}
log.Printf("Instance %s is in state %s", instanceId, state)
switch state {
case "pending", "shutting-down", "stopping":
// for any of the transient states, just wait
time.Sleep(time.Second / 2)
case "running":
// running is the state we want to get to
break statePoll
case "stopped":
log.Printf("starting instance %s", instanceId)
if startCalled {
return fmt.Errorf("instance %s did not enter the running state", instanceId)
}
// start a stopped instance
params := &ec2.StartInstancesInput{
InstanceIds: []*string{aws.String(instanceId)},
}
_, err := svc.StartInstances(params)
if err != nil {
return err
}
startCalled = true
// wait a beat for EC2 to realize that it's not stopped anymore
time.Sleep(2 * time.Second)
case "terminated":
return fmt.Errorf("Instance is terminated")
}
}
// wait for SSH port to be open, too
for {
var err error
var address string
instance, address, err = instanceAddress(instance, ec2HostConfig, svc)
if err != nil {
return fmt.Errorf("Could not get instance address: %s", err)
}
var hostport string
if strings.ContainsRune(address, ':') {
hostport = fmt.Sprintf("[%s]:22", address)
} else {
hostport = fmt.Sprintf("%s:22", address)
}
conn, err := net.Dial("tcp", hostport)
if err != nil {
log.Printf("connecting to %s:22: %s; retrying", address, err)
time.Sleep(time.Second / 2)
} else {
conn.Close()
break
}
}
return nil
}
// get the current state for an EC2 instance
func getInstanceState(instanceId string, svc *ec2.EC2) (string, error) {
params := &ec2.DescribeInstancesInput{
InstanceIds: []*string{&instanceId},
}
resp, err := svc.DescribeInstances(params)
if err != nil {
return "", err
}
if len(resp.Reservations) < 1 {
return "", fmt.Errorf("instance %s not found", instanceId)
}
if len(resp.Reservations) > 1 || len(resp.Reservations[0].Instances) != 1 {
return "", fmt.Errorf("Multiple instances %s found (?!)", instanceId)
}
return *resp.Reservations[0].Instances[0].State.Name, nil
}
func ec2Child(info *childInfo) error {
instanceName := info.childConfig.Ec2.Instance
ec2HostConfig, ok := info.hostConfig.Ec2[instanceName]
if !ok {
return fmt.Errorf("EC2 instance %q not defined in configuration file", instanceName)
}
svc, err := setupEc2(ec2HostConfig, info.childConfig)
if err != nil {
return fmt.Errorf("while setting up ec2 access: %s", err)
}
// look up the instance matching this description
instance, err := findInstance(ec2HostConfig, svc)
if err != nil {
return fmt.Errorf("while searching for ec2 instance: %s", err)
}
log.Printf("Found instance id %s (type %s)", *instance.InstanceId, *instance.InstanceType)
err = startInstance(ec2HostConfig, instance, svc)
if err != nil {
return fmt.Errorf("while starting instance: %s", err)
}
instance, address, err := instanceAddress(instance, ec2HostConfig, svc)
if err != nil {
return fmt.Errorf("Could not get instance address: %s", err)
}
return ssh.Run(address, &ec2HostConfig.SshCommonConfig, info.path)
}
func init() {
childFuncs["ec2"] = ec2Child
}