forked from rancher/machine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ec2.go
670 lines (580 loc) · 19.8 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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
package amz
import (
"encoding/base64"
"encoding/xml"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"github.com/docker/machine/libmachine/log"
"github.com/docker/machine/libmachine/mcnutils"
awsauth "github.com/smartystreets/go-aws-auth"
)
type (
EC2 struct {
Endpoint string
Auth Auth
Region string
}
Instance struct {
info EC2Instance
}
EC2Instance struct {
InstanceId string `xml:"instanceId"`
ImageId string `xml:"imageId"`
InstanceState struct {
Code int `xml:"code"`
Name string `xml:"name"`
} `xml:"instanceState"`
PrivateDnsName string `xml:"privateDnsName"`
DnsName string `xml:"dnsName"`
Reason string `xml:"reason"`
AmiLaunchIndex string `xml:"amiLaunchIndex"`
ProductCodes string `xml:"productCodes"`
InstanceType string `xml:"instanceType"`
LaunchTime string `xml:"launchTime"`
Placement struct {
AvailabilityZone string `xml:"availabilityZone"`
GroupName string `xml:"groupName"`
Tenancy string `xml:"tenancy"`
} `xml:"placement"`
KernelId string `xml:"kernelId"`
Monitoring struct {
State string `xml:"state"`
} `xml:"monitoring"`
SubnetId string `xml:"subnetId"`
VpcId string `xml:"vpcId"`
IpAddress string `xml:"ipAddress"`
PrivateIpAddress string `xml:"privateIpAddress"`
SourceDestCheck bool `xml:"sourceDestCheck"`
GroupSet []struct {
GroupId string `xml:"groupId"`
GroupName string `xml:"groupName"`
} `xml:"groupSet"`
StateReason struct {
Code string `xml:"code"`
Message string `xml:"message"`
} `xml:"stateReason"`
Architecture string `xml:"architecture"`
RootDeviceType string `xml:"rootDeviceType"`
RootDeviceName string `xml:"rootDeviceName"`
BlockDeviceMapping string `xml:"blockDeviceMapping"`
VirtualizationType string `xml:"virtualizationType"`
ClientToken string `xml:"clientToken"`
Hypervisor string `xml:"hypervisor"`
NetworkInterfaceSet []struct {
NetworkInterfaceId string `xml:"networkInterfaceId"`
SubnetId string `xml:"subnetId"`
VpcId string `xml:"vpcId"`
Description string `xml:"description"`
OwnerId string `xml:"ownerId"`
Status string `xml:"status"`
MacAddress string `xml:"macAddress"`
PrivateIpAddress string `xml:"privateIpAddress"`
PrivateDnsName string `xml:"privateDnsName"`
SourceDestCheck string `xml:"sourceDestCheck"`
GroupSet []struct {
GroupId string `xml:"groupId"`
GroupName string `xml:"groupName"`
} `xml:"groupSet>item"`
Attachment struct {
AttachmentId string `xml:"attachmentId"`
DeviceIndex string `xml:"deviceIndex"`
Status string `xml:"status"`
AttachTime string `xml:"attachTime"`
DeleteOnTermination bool `xml:"deleteOnTermination"`
} `xml:"attachment"`
PrivateIpAddressesSet []struct {
PrivateIpAddress string `xml:"privateIpAddress"`
PrivateDnsName string `xml:"privateDnsName"`
Primary bool `xml:"primary"`
} `xml:"privateIpAddressesSet>item"`
} `xml:"networkInterfaceSet>item"`
EbsOptimized bool `xml:"ebsOptimized"`
}
RunInstancesResponse struct {
RequestId string `xml:"requestId"`
ReservationId string `xml:"reservationId"`
OwnerId string `xml:"ownerId"`
Instances []EC2Instance `xml:"instancesSet>item"`
}
RequestSpotInstancesResponse struct {
RequestId string `xml:"requestId"`
SpotInstanceRequestSet []struct {
SpotInstanceRequestId string `xml:"spotInstanceRequestId"`
State string `xml:"state"`
} `xml:"spotInstanceRequestSet>item"`
}
)
func newAwsApiResponseError(r http.Response) error {
var errorResponse ErrorResponse
if err := getDecodedResponse(r, &errorResponse); err != nil {
return fmt.Errorf("Error decoding error response: %s", err)
}
msg := ""
for _, e := range errorResponse.Errors {
msg += fmt.Sprintf("%s\n", e.Message)
}
return fmt.Errorf("Non-200 API response: code=%d message=%s", r.StatusCode, msg)
}
func newAwsApiCallError(err error) error {
return fmt.Errorf("Problem with AWS API call: %s", err)
}
func getDecodedResponse(r http.Response, into interface{}) error {
defer r.Body.Close()
if err := xml.NewDecoder(r.Body).Decode(into); err != nil {
return fmt.Errorf("Error decoding error response: %s", err)
}
return nil
}
func NewEC2(auth Auth, region string) *EC2 {
endpoint := fmt.Sprintf("https://ec2.%s.amazonaws.com", region)
return &EC2{
Endpoint: endpoint,
Auth: auth,
Region: region,
}
}
func (e *EC2) awsApiCall(v url.Values) (*http.Response, error) {
v.Set("Version", "2014-06-15")
log.Debug("Making AWS API call with values:")
mcnutils.DumpVal(v)
client := &http.Client{}
finalEndpoint := fmt.Sprintf("%s?%s", e.Endpoint, v.Encode())
req, err := http.NewRequest("GET", finalEndpoint, nil)
if err != nil {
return &http.Response{}, fmt.Errorf("error creating request from client")
}
req.Header.Add("Content-type", "application/json")
awsauth.Sign4(req, awsauth.Credentials{
AccessKeyID: e.Auth.AccessKey,
SecretAccessKey: e.Auth.SecretKey,
SecurityToken: e.Auth.SessionToken,
})
resp, err := client.Do(req)
if err != nil {
fmt.Printf("client encountered error while doing the request: %s", err.Error())
return resp, fmt.Errorf("client encountered error while doing the request: %s", err)
}
if resp.StatusCode != http.StatusOK {
return resp, newAwsApiResponseError(*resp)
}
return resp, nil
}
func (e *EC2) RunInstance(amiId string, instanceType string, zone string, minCount int, maxCount int, securityGroup string, keyName string, subnetId string, bdm *BlockDeviceMapping, role string, privateIPOnly bool, monitoring bool) (EC2Instance, error) {
instance := Instance{}
v := url.Values{}
v.Set("Action", "RunInstances")
v.Set("ImageId", amiId)
v.Set("Placement.AvailabilityZone", e.Region+zone)
v.Set("MinCount", strconv.Itoa(minCount))
v.Set("MaxCount", strconv.Itoa(maxCount))
v.Set("KeyName", keyName)
v.Set("InstanceType", instanceType)
v.Set("NetworkInterface.0.DeviceIndex", "0")
v.Set("NetworkInterface.0.SecurityGroupId.0", securityGroup)
v.Set("NetworkInterface.0.SubnetId", subnetId)
if privateIPOnly {
v.Set("NetworkInterface.0.AssociatePublicIpAddress", "0")
} else {
v.Set("NetworkInterface.0.AssociatePublicIpAddress", "1")
}
if monitoring {
v.Set("Monitoring.Enabled", "1")
} else {
v.Set("Monitoring.Enabled", "0")
}
if len(role) > 0 {
v.Set("IamInstanceProfile.Name", role)
}
if bdm != nil {
v.Set("BlockDeviceMapping.0.DeviceName", bdm.DeviceName)
v.Set("BlockDeviceMapping.0.VirtualName", bdm.VirtualName)
v.Set("BlockDeviceMapping.0.Ebs.VolumeSize", strconv.FormatInt(bdm.VolumeSize, 10))
v.Set("BlockDeviceMapping.0.Ebs.VolumeType", bdm.VolumeType)
deleteOnTerm := 0
if bdm.DeleteOnTermination {
deleteOnTerm = 1
}
v.Set("BlockDeviceMapping.0.Ebs.DeleteOnTermination", strconv.Itoa(deleteOnTerm))
}
resp, err := e.awsApiCall(v)
if err != nil {
return instance.info, newAwsApiCallError(err)
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return instance.info, fmt.Errorf("Error reading AWS response body")
}
unmarshalledResponse := RunInstancesResponse{}
err = xml.Unmarshal(contents, &unmarshalledResponse)
if err != nil {
return instance.info, fmt.Errorf("Error unmarshalling AWS response XML: %s", err)
}
instance.info = unmarshalledResponse.Instances[0]
return instance.info, nil
}
func (e *EC2) RequestSpotInstances(amiId string, instanceType string, zone string, instanceCount int, securityGroup string, keyName string, subnetId string, bdm *BlockDeviceMapping, role string, spotPrice string, monitoring bool) (string, error) {
v := url.Values{}
v.Set("Action", "RequestSpotInstances")
v.Set("LaunchSpecification.ImageId", amiId)
v.Set("LaunchSpecification.Placement.AvailabilityZone", e.Region+zone)
v.Set("InstanceCount", strconv.Itoa(instanceCount))
v.Set("SpotPrice", spotPrice)
v.Set("LaunchSpecification.KeyName", keyName)
v.Set("LaunchSpecification.InstanceType", instanceType)
v.Set("LaunchSpecification.NetworkInterface.0.DeviceIndex", "0")
v.Set("LaunchSpecification.NetworkInterface.0.SecurityGroupId.0", securityGroup)
v.Set("LaunchSpecification.NetworkInterface.0.SubnetId", subnetId)
v.Set("LaunchSpecification.NetworkInterface.0.AssociatePublicIpAddress", "1")
if monitoring {
v.Set("LaunchSpecification.Monitoring.Enabled", "1")
} else {
v.Set("LaunchSpecification.Monitoring.Enabled", "0")
}
if len(role) > 0 {
v.Set("LaunchSpecification.IamInstanceProfile.Name", role)
}
if bdm != nil {
v.Set("LaunchSpecification.BlockDeviceMapping.0.DeviceName", bdm.DeviceName)
v.Set("LaunchSpecification.BlockDeviceMapping.0.VirtualName", bdm.VirtualName)
v.Set("LaunchSpecification.BlockDeviceMapping.0.Ebs.VolumeSize", strconv.FormatInt(bdm.VolumeSize, 10))
v.Set("LaunchSpecification.BlockDeviceMapping.0.Ebs.VolumeType", bdm.VolumeType)
deleteOnTerm := 0
if bdm.DeleteOnTermination {
deleteOnTerm = 1
}
v.Set("LaunchSpecification.BlockDeviceMapping.0.Ebs.DeleteOnTermination", strconv.Itoa(deleteOnTerm))
}
resp, err := e.awsApiCall(v)
if err != nil {
return "", newAwsApiCallError(err)
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("Error reading AWS response body")
}
unmarshalledResponse := RequestSpotInstancesResponse{}
err = xml.Unmarshal(contents, &unmarshalledResponse)
if err != nil {
return "", fmt.Errorf("Error unmarshalling AWS response XML: %s", err)
}
return unmarshalledResponse.SpotInstanceRequestSet[0].SpotInstanceRequestId, nil
}
func (e *EC2) DescribeSpotInstanceRequests(spotInstanceRequestId string) (string, string, error) {
v := url.Values{}
v.Set("Action", "DescribeSpotInstanceRequests")
v.Set("SpotInstanceRequestId.0", spotInstanceRequestId)
resp, err := e.awsApiCall(v)
if err != nil {
return "", "", newAwsApiCallError(err)
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", "", fmt.Errorf("Error reading AWS response body")
}
unmarshalledResponse := DescribeSpotInstanceRequestsResponse{}
err = xml.Unmarshal(contents, &unmarshalledResponse)
if err != nil {
return "", "", fmt.Errorf("Error unmarshalling AWS response XML: %s", err)
}
if code := unmarshalledResponse.SpotInstanceRequestSet[0].Status.Code; code != "fulfilled" {
return code, "", nil
}
return "fulfilled", unmarshalledResponse.SpotInstanceRequestSet[0].InstanceId, nil
}
func (e *EC2) DeleteKeyPair(name string) error {
v := url.Values{}
v.Set("Action", "DeleteKeyPair")
v.Set("KeyName", name)
_, err := e.awsApiCall(v)
if err != nil {
return fmt.Errorf("Error making API call to delete keypair :%s", err)
}
return nil
}
func (e *EC2) CreateKeyPair(name string) ([]byte, error) {
v := url.Values{}
v.Set("Action", "CreateKeyPair")
v.Set("KeyName", name)
resp, err := e.awsApiCall(v)
if err != nil {
return nil, fmt.Errorf("Error trying API call to create keypair: %s", err)
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Error reading AWS response body")
}
unmarshalledResponse := CreateKeyPairResponse{}
if xml.Unmarshal(contents, &unmarshalledResponse); err != nil {
return nil, fmt.Errorf("Error unmarshalling AWS response XML: %s", err)
}
key := unmarshalledResponse.KeyMaterial
return key, nil
}
func (e *EC2) ImportKeyPair(name, publicKey string) error {
keyMaterial := base64.StdEncoding.EncodeToString([]byte(publicKey))
v := url.Values{}
v.Set("Action", "ImportKeyPair")
v.Set("KeyName", name)
v.Set("PublicKeyMaterial", keyMaterial)
resp, err := e.awsApiCall(v)
if err != nil {
return fmt.Errorf("Error trying API call to create keypair: %s", err)
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("Error reading AWS response body")
}
unmarshalledResponse := ImportKeyPairResponse{}
if xml.Unmarshal(contents, &unmarshalledResponse); err != nil {
return fmt.Errorf("Error unmarshalling AWS response XML: %s", err)
}
return nil
}
func (e *EC2) CreateTags(id string, tags map[string]string) error {
v := url.Values{}
v.Set("Action", "CreateTags")
v.Set("ResourceId.1", id)
counter := 1
for k, val := range tags {
v.Set(fmt.Sprintf("Tag.%d.Key", counter), k)
v.Set(fmt.Sprintf("Tag.%d.Value", counter), val)
counter += 1
}
resp, err := e.awsApiCall(v)
defer resp.Body.Close()
if err != nil {
return err
}
createTagsResponse := &CreateTagsResponse{}
if err := getDecodedResponse(*resp, &createTagsResponse); err != nil {
return fmt.Errorf("Error decoding create tags response: %s", err)
}
return nil
}
func (e *EC2) CreateSecurityGroup(name string, description string, vpcId string) (*SecurityGroup, error) {
v := url.Values{}
v.Set("Action", "CreateSecurityGroup")
v.Set("GroupName", name)
v.Set("GroupDescription", url.QueryEscape(description))
v.Set("VpcId", vpcId)
resp, err := e.awsApiCall(v)
defer resp.Body.Close()
if err != nil {
// ugly hack since API has no way to check if SG already exists
if resp.StatusCode == http.StatusBadRequest {
var errorResponse ErrorResponse
if err := getDecodedResponse(*resp, &errorResponse); err != nil {
return nil, fmt.Errorf("Error decoding error response: %s", err)
}
if errorResponse.Errors[0].Code == ErrorDuplicateGroup {
return nil, nil
}
}
return nil, fmt.Errorf("Error making API call to create security group: %s", err)
}
createSecurityGroupResponse := CreateSecurityGroupResponse{}
if err := getDecodedResponse(*resp, &createSecurityGroupResponse); err != nil {
return nil, fmt.Errorf("Error decoding create security groups response: %s", err)
}
group := &SecurityGroup{
GroupId: createSecurityGroupResponse.GroupId,
VpcId: vpcId,
}
return group, nil
}
func (e *EC2) AuthorizeSecurityGroup(groupId string, permissions []IpPermission) error {
v := url.Values{}
v.Set("Action", "AuthorizeSecurityGroupIngress")
v.Set("GroupId", groupId)
for index, perm := range permissions {
n := index + 1 // amazon starts counting from 1 not 0
v.Set(fmt.Sprintf("IpPermissions.%d.IpProtocol", n), perm.IpProtocol)
v.Set(fmt.Sprintf("IpPermissions.%d.FromPort", n), strconv.Itoa(perm.FromPort))
v.Set(fmt.Sprintf("IpPermissions.%d.ToPort", n), strconv.Itoa(perm.ToPort))
v.Set(fmt.Sprintf("IpPermissions.%d.IpRanges.1.CidrIp", n), perm.IpRange)
}
resp, err := e.awsApiCall(v)
defer resp.Body.Close()
if err != nil {
return fmt.Errorf("Error making API call to authorize security group ingress: %s", err)
}
return nil
}
func (e *EC2) DeleteSecurityGroup(groupId string) error {
v := url.Values{}
v.Set("Action", "DeleteSecurityGroup")
v.Set("GroupId", groupId)
resp, err := e.awsApiCall(v)
defer resp.Body.Close()
if err != nil {
return fmt.Errorf("Error making API call to delete security group: %s", err)
}
deleteSecurityGroupResponse := DeleteSecurityGroupResponse{}
if err := getDecodedResponse(*resp, &deleteSecurityGroupResponse); err != nil {
return fmt.Errorf("Error decoding delete security groups response: %s", err)
}
return nil
}
func (e *EC2) GetSecurityGroups() ([]SecurityGroup, error) {
sgs := []SecurityGroup{}
resp, err := e.performStandardAction("DescribeSecurityGroups")
if err != nil {
return sgs, err
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return sgs, fmt.Errorf("Error reading AWS response body: %s", err)
}
unmarshalledResponse := DescribeSecurityGroupsResponse{}
if err = xml.Unmarshal(contents, &unmarshalledResponse); err != nil {
return sgs, fmt.Errorf("Error unmarshalling AWS response XML: %s", err)
}
sgs = unmarshalledResponse.SecurityGroupInfo
return sgs, nil
}
func (e *EC2) GetSecurityGroupById(id string) (*SecurityGroup, error) {
groups, err := e.GetSecurityGroups()
if err != nil {
return nil, err
}
for _, g := range groups {
if g.GroupId == id {
return &g, nil
}
}
return nil, nil
}
func (e *EC2) GetSubnets(filters []Filter) ([]Subnet, error) {
subnets := []Subnet{}
v := url.Values{}
v.Set("Action", "DescribeSubnets")
for idx, filter := range filters {
n := idx + 1 // amazon starts counting from 1 not 0
v.Set(fmt.Sprintf("Filter.%d.Name", n), filter.Name)
v.Set(fmt.Sprintf("Filter.%d.Value", n), filter.Value)
}
resp, err := e.awsApiCall(v)
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return subnets, fmt.Errorf("Error reading AWS response body: %s", err)
}
unmarshalledResponse := DescribeSubnetsResponse{}
if err = xml.Unmarshal(contents, &unmarshalledResponse); err != nil {
return subnets, fmt.Errorf("Error unmarshalling AWS response XML: %s", err)
}
subnets = unmarshalledResponse.SubnetSet
return subnets, nil
}
func (e *EC2) GetKeyPairs() ([]KeyPair, error) {
keyPairs := []KeyPair{}
resp, err := e.performStandardAction("DescribeKeyPairs")
if err != nil {
return keyPairs, err
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return keyPairs, fmt.Errorf("Error reading AWS response body: %s", err)
}
unmarshalledResponse := DescribeKeyPairsResponse{}
if err = xml.Unmarshal(contents, &unmarshalledResponse); err != nil {
return keyPairs, fmt.Errorf("Error unmarshalling AWS response XML: %s", err)
}
keyPairs = unmarshalledResponse.KeySet
return keyPairs, nil
}
func (e *EC2) GetKeyPair(name string) (*KeyPair, error) {
keyPairs, err := e.GetKeyPairs()
if err != nil {
return nil, err
}
for _, key := range keyPairs {
if key.KeyName == name {
return &key, nil
}
}
return nil, nil
}
func (e *EC2) GetInstance(instanceId string) (EC2Instance, error) {
ec2Instance := EC2Instance{}
resp, err := e.performInstanceAction(instanceId, "DescribeInstances", nil)
if err != nil {
return ec2Instance, err
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return ec2Instance, fmt.Errorf("Error reading AWS response body: %s", err)
}
unmarshalledResponse := DescribeInstancesResponse{}
if err = xml.Unmarshal(contents, &unmarshalledResponse); err != nil {
return ec2Instance, fmt.Errorf("Error unmarshalling AWS response XML: %s", err)
}
if len(unmarshalledResponse.ReservationSet) > 0 {
reservationSet := unmarshalledResponse.ReservationSet[0]
ec2Instance = reservationSet.InstancesSet[0]
}
return ec2Instance, nil
}
func (e *EC2) StartInstance(instanceId string) error {
if _, err := e.performInstanceAction(instanceId, "StartInstances", nil); err != nil {
return err
}
return nil
}
func (e *EC2) RestartInstance(instanceId string) error {
if _, err := e.performInstanceAction(instanceId, "RebootInstances", nil); err != nil {
return err
}
return nil
}
func (e *EC2) StopInstance(instanceId string, force bool) error {
vars := make(map[string]string)
if force {
vars["Force"] = "1"
}
if _, err := e.performInstanceAction(instanceId, "StopInstances", &vars); err != nil {
return err
}
return nil
}
func (e *EC2) TerminateInstance(instanceId string) error {
if _, err := e.performInstanceAction(instanceId, "TerminateInstances", nil); err != nil {
return err
}
return nil
}
func (e *EC2) performStandardAction(action string) (*http.Response, error) {
v := url.Values{}
v.Set("Action", action)
resp, err := e.awsApiCall(v)
if err != nil {
return resp, newAwsApiCallError(err)
}
return resp, nil
}
func (e *EC2) performInstanceAction(instanceId, action string, extraVars *map[string]string) (*http.Response, error) {
v := url.Values{}
v.Set("Action", action)
v.Set("InstanceId.1", instanceId)
if extraVars != nil {
for k, val := range *extraVars {
v.Set(k, val)
}
}
resp, err := e.awsApiCall(v)
if err != nil {
return resp, newAwsApiCallError(err)
}
return resp, nil
}