forked from kubernetes/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ec2.go
2599 lines (2277 loc) · 73.2 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
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// goamz - Go packages to interact with the Amazon Web Services.
//
// https://wiki.ubuntu.com/goamz
//
// Copyright (c) 2011 Canonical Ltd.
//
// Written by Gustavo Niemeyer <gustavo.niemeyer@canonical.com>
//
package ec2
import (
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/xml"
"fmt"
"log"
"net/http"
"net/http/httputil"
"net/url"
"sort"
"strconv"
"strings"
"time"
"github.com/mitchellh/goamz/aws"
)
const debug = false
// The EC2 type encapsulates operations with a specific EC2 region.
type EC2 struct {
aws.Auth
aws.Region
httpClient *http.Client
private byte // Reserve the right of using private data.
}
// New creates a new EC2.
func NewWithClient(auth aws.Auth, region aws.Region, client *http.Client) *EC2 {
return &EC2{auth, region, client, 0}
}
func New(auth aws.Auth, region aws.Region) *EC2 {
return NewWithClient(auth, region, aws.RetryingClient)
}
// ----------------------------------------------------------------------------
// Filtering helper.
// Filter builds filtering parameters to be used in an EC2 query which supports
// filtering. For example:
//
// filter := NewFilter()
// filter.Add("architecture", "i386")
// filter.Add("launch-index", "0")
// resp, err := ec2.Instances(nil, filter)
//
type Filter struct {
m map[string][]string
}
// NewFilter creates a new Filter.
func NewFilter() *Filter {
return &Filter{make(map[string][]string)}
}
// Add appends a filtering parameter with the given name and value(s).
func (f *Filter) Add(name string, value ...string) {
f.m[name] = append(f.m[name], value...)
}
func (f *Filter) addParams(params map[string]string) {
if f != nil {
a := make([]string, len(f.m))
i := 0
for k := range f.m {
a[i] = k
i++
}
sort.StringSlice(a).Sort()
for i, k := range a {
prefix := "Filter." + strconv.Itoa(i+1)
params[prefix+".Name"] = k
for j, v := range f.m[k] {
params[prefix+".Value."+strconv.Itoa(j+1)] = v
}
}
}
}
// ----------------------------------------------------------------------------
// Request dispatching logic.
// Error encapsulates an error returned by EC2.
//
// See http://goo.gl/VZGuC for more details.
type Error struct {
// HTTP status code (200, 403, ...)
StatusCode int
// EC2 error code ("UnsupportedOperation", ...)
Code string
// The human-oriented error message
Message string
RequestId string `xml:"RequestID"`
}
func (err *Error) Error() string {
if err.Code == "" {
return err.Message
}
return fmt.Sprintf("%s (%s)", err.Message, err.Code)
}
// For now a single error inst is being exposed. In the future it may be useful
// to provide access to all of them, but rather than doing it as an array/slice,
// use a *next pointer, so that it's backward compatible and it continues to be
// easy to handle the first error, which is what most people will want.
type xmlErrors struct {
RequestId string `xml:"RequestID"`
Errors []Error `xml:"Errors>Error"`
}
var timeNow = time.Now
func (ec2 *EC2) query(params map[string]string, resp interface{}) error {
params["Version"] = "2014-05-01"
params["Timestamp"] = timeNow().In(time.UTC).Format(time.RFC3339)
endpoint, err := url.Parse(ec2.Region.EC2Endpoint)
if err != nil {
return err
}
if endpoint.Path == "" {
endpoint.Path = "/"
}
sign(ec2.Auth, "GET", endpoint.Path, params, endpoint.Host)
endpoint.RawQuery = multimap(params).Encode()
if debug {
log.Printf("get { %v } -> {\n", endpoint.String())
}
r, err := ec2.httpClient.Get(endpoint.String())
if err != nil {
return err
}
defer r.Body.Close()
if debug {
dump, _ := httputil.DumpResponse(r, true)
log.Printf("response:\n")
log.Printf("%v\n}\n", string(dump))
}
if r.StatusCode != 200 {
return buildError(r)
}
err = xml.NewDecoder(r.Body).Decode(resp)
return err
}
func multimap(p map[string]string) url.Values {
q := make(url.Values, len(p))
for k, v := range p {
q[k] = []string{v}
}
return q
}
func buildError(r *http.Response) error {
errors := xmlErrors{}
xml.NewDecoder(r.Body).Decode(&errors)
var err Error
if len(errors.Errors) > 0 {
err = errors.Errors[0]
}
err.RequestId = errors.RequestId
err.StatusCode = r.StatusCode
if err.Message == "" {
err.Message = r.Status
}
return &err
}
func makeParams(action string) map[string]string {
params := make(map[string]string)
params["Action"] = action
return params
}
func addParamsList(params map[string]string, label string, ids []string) {
for i, id := range ids {
params[label+"."+strconv.Itoa(i+1)] = id
}
}
func addBlockDeviceParams(prename string, params map[string]string, blockdevices []BlockDeviceMapping) {
for i, k := range blockdevices {
// Fixup index since Amazon counts these from 1
prefix := prename + "BlockDeviceMapping." + strconv.Itoa(i+1) + "."
if k.DeviceName != "" {
params[prefix+"DeviceName"] = k.DeviceName
}
if k.VirtualName != "" {
params[prefix+"VirtualName"] = k.VirtualName
}
if k.SnapshotId != "" {
params[prefix+"Ebs.SnapshotId"] = k.SnapshotId
}
if k.VolumeType != "" {
params[prefix+"Ebs.VolumeType"] = k.VolumeType
}
if k.IOPS != 0 {
params[prefix+"Ebs.Iops"] = strconv.FormatInt(k.IOPS, 10)
}
if k.VolumeSize != 0 {
params[prefix+"Ebs.VolumeSize"] = strconv.FormatInt(k.VolumeSize, 10)
}
if k.DeleteOnTermination {
params[prefix+"Ebs.DeleteOnTermination"] = "true"
}
if k.Encrypted {
params[prefix+"Ebs.Encrypted"] = "true"
}
if k.NoDevice {
params[prefix+"NoDevice"] = ""
}
}
}
// ----------------------------------------------------------------------------
// Instance management functions and types.
// The RunInstances type encapsulates options for the respective request in EC2.
//
// See http://goo.gl/Mcm3b for more details.
type RunInstances struct {
ImageId string
MinCount int
MaxCount int
KeyName string
InstanceType string
SecurityGroups []SecurityGroup
IamInstanceProfile string
KernelId string
RamdiskId string
UserData []byte
AvailZone string
PlacementGroupName string
Monitoring bool
SubnetId string
AssociatePublicIpAddress bool
DisableAPITermination bool
ShutdownBehavior string
PrivateIPAddress string
BlockDevices []BlockDeviceMapping
}
// Response to a RunInstances request.
//
// See http://goo.gl/Mcm3b for more details.
type RunInstancesResp struct {
RequestId string `xml:"requestId"`
ReservationId string `xml:"reservationId"`
OwnerId string `xml:"ownerId"`
SecurityGroups []SecurityGroup `xml:"groupSet>item"`
Instances []Instance `xml:"instancesSet>item"`
}
// Instance encapsulates a running instance in EC2.
//
// See http://goo.gl/OCH8a for more details.
type Instance struct {
InstanceId string `xml:"instanceId"`
InstanceType string `xml:"instanceType"`
ImageId string `xml:"imageId"`
PrivateDNSName string `xml:"privateDnsName"`
DNSName string `xml:"dnsName"`
KeyName string `xml:"keyName"`
AMILaunchIndex int `xml:"amiLaunchIndex"`
Hypervisor string `xml:"hypervisor"`
VirtType string `xml:"virtualizationType"`
Monitoring string `xml:"monitoring>state"`
AvailZone string `xml:"placement>availabilityZone"`
PlacementGroupName string `xml:"placement>groupName"`
State InstanceState `xml:"instanceState"`
Tags []Tag `xml:"tagSet>item"`
VpcId string `xml:"vpcId"`
SubnetId string `xml:"subnetId"`
IamInstanceProfile string `xml:"iamInstanceProfile"`
PrivateIpAddress string `xml:"privateIpAddress"`
PublicIpAddress string `xml:"ipAddress"`
Architecture string `xml:"architecture"`
LaunchTime time.Time `xml:"launchTime"`
SourceDestCheck bool `xml:"sourceDestCheck"`
SecurityGroups []SecurityGroup `xml:"groupSet>item"`
}
// RunInstances starts new instances in EC2.
// If options.MinCount and options.MaxCount are both zero, a single instance
// will be started; otherwise if options.MaxCount is zero, options.MinCount
// will be used insteead.
//
// See http://goo.gl/Mcm3b for more details.
func (ec2 *EC2) RunInstances(options *RunInstances) (resp *RunInstancesResp, err error) {
params := makeParams("RunInstances")
params["ImageId"] = options.ImageId
params["InstanceType"] = options.InstanceType
var min, max int
if options.MinCount == 0 && options.MaxCount == 0 {
min = 1
max = 1
} else if options.MaxCount == 0 {
min = options.MinCount
max = min
} else {
min = options.MinCount
max = options.MaxCount
}
params["MinCount"] = strconv.Itoa(min)
params["MaxCount"] = strconv.Itoa(max)
token, err := clientToken()
if err != nil {
return nil, err
}
params["ClientToken"] = token
if options.KeyName != "" {
params["KeyName"] = options.KeyName
}
if options.KernelId != "" {
params["KernelId"] = options.KernelId
}
if options.RamdiskId != "" {
params["RamdiskId"] = options.RamdiskId
}
if options.UserData != nil {
userData := make([]byte, b64.EncodedLen(len(options.UserData)))
b64.Encode(userData, options.UserData)
params["UserData"] = string(userData)
}
if options.AvailZone != "" {
params["Placement.AvailabilityZone"] = options.AvailZone
}
if options.PlacementGroupName != "" {
params["Placement.GroupName"] = options.PlacementGroupName
}
if options.Monitoring {
params["Monitoring.Enabled"] = "true"
}
if options.SubnetId != "" && options.AssociatePublicIpAddress {
// If we have a non-default VPC / Subnet specified, we can flag
// AssociatePublicIpAddress to get a Public IP assigned. By default these are not provided.
// You cannot specify both SubnetId and the NetworkInterface.0.* parameters though, otherwise
// you get: Network interfaces and an instance-level subnet ID may not be specified on the same request
// You also need to attach Security Groups to the NetworkInterface instead of the instance,
// to avoid: Network interfaces and an instance-level security groups may not be specified on
// the same request
params["NetworkInterface.0.DeviceIndex"] = "0"
params["NetworkInterface.0.AssociatePublicIpAddress"] = "true"
params["NetworkInterface.0.SubnetId"] = options.SubnetId
i := 1
for _, g := range options.SecurityGroups {
// We only have SecurityGroupId's on NetworkInterface's, no SecurityGroup params.
if g.Id != "" {
params["NetworkInterface.0.SecurityGroupId."+strconv.Itoa(i)] = g.Id
i++
}
}
} else {
if options.SubnetId != "" {
params["SubnetId"] = options.SubnetId
}
i, j := 1, 1
for _, g := range options.SecurityGroups {
if g.Id != "" {
params["SecurityGroupId."+strconv.Itoa(i)] = g.Id
i++
} else {
params["SecurityGroup."+strconv.Itoa(j)] = g.Name
j++
}
}
}
if options.IamInstanceProfile != "" {
params["IamInstanceProfile.Name"] = options.IamInstanceProfile
}
if options.DisableAPITermination {
params["DisableApiTermination"] = "true"
}
if options.ShutdownBehavior != "" {
params["InstanceInitiatedShutdownBehavior"] = options.ShutdownBehavior
}
if options.PrivateIPAddress != "" {
params["PrivateIpAddress"] = options.PrivateIPAddress
}
addBlockDeviceParams("", params, options.BlockDevices)
resp = &RunInstancesResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
func clientToken() (string, error) {
// Maximum EC2 client token size is 64 bytes.
// Each byte expands to two when hex encoded.
buf := make([]byte, 32)
_, err := rand.Read(buf)
if err != nil {
return "", err
}
return hex.EncodeToString(buf), nil
}
// ----------------------------------------------------------------------------
// Spot Instance management functions and types.
// The RequestSpotInstances type encapsulates options for the respective request in EC2.
//
// See http://goo.gl/GRZgCD for more details.
type RequestSpotInstances struct {
SpotPrice string
InstanceCount int
Type string
ImageId string
KeyName string
InstanceType string
SecurityGroups []SecurityGroup
IamInstanceProfile string
KernelId string
RamdiskId string
UserData []byte
AvailZone string
PlacementGroupName string
Monitoring bool
SubnetId string
AssociatePublicIpAddress bool
PrivateIPAddress string
BlockDevices []BlockDeviceMapping
}
type SpotInstanceSpec struct {
ImageId string
KeyName string
InstanceType string
SecurityGroups []SecurityGroup
IamInstanceProfile string
KernelId string
RamdiskId string
UserData []byte
AvailZone string
PlacementGroupName string
Monitoring bool
SubnetId string
AssociatePublicIpAddress bool
PrivateIPAddress string
BlockDevices []BlockDeviceMapping
}
type SpotLaunchSpec struct {
ImageId string `xml:"imageId"`
KeyName string `xml:"keyName"`
InstanceType string `xml:"instanceType"`
SecurityGroups []SecurityGroup `xml:"groupSet>item"`
IamInstanceProfile string `xml:"iamInstanceProfile"`
KernelId string `xml:"kernelId"`
RamdiskId string `xml:"ramdiskId"`
PlacementGroupName string `xml:"placement>groupName"`
Monitoring bool `xml:"monitoring>enabled"`
SubnetId string `xml:"subnetId"`
BlockDevices []BlockDeviceMapping `xml:"blockDeviceMapping>item"`
}
type SpotStatus struct {
Code string `xml:"code"`
UpdateTime string `xml:"updateTime"`
Message string `xml:"message"`
}
type SpotRequestResult struct {
SpotRequestId string `xml:"spotInstanceRequestId"`
SpotPrice string `xml:"spotPrice"`
Type string `xml:"type"`
AvailZone string `xml:"launchedAvailabilityZone"`
InstanceId string `xml:"instanceId"`
State string `xml:"state"`
Status SpotStatus `xml:"status"`
SpotLaunchSpec SpotLaunchSpec `xml:"launchSpecification"`
CreateTime string `xml:"createTime"`
Tags []Tag `xml:"tagSet>item"`
}
// Response to a RequestSpotInstances request.
//
// See http://goo.gl/GRZgCD for more details.
type RequestSpotInstancesResp struct {
RequestId string `xml:"requestId"`
SpotRequestResults []SpotRequestResult `xml:"spotInstanceRequestSet>item"`
}
// RequestSpotInstances requests a new spot instances in EC2.
func (ec2 *EC2) RequestSpotInstances(options *RequestSpotInstances) (resp *RequestSpotInstancesResp, err error) {
params := makeParams("RequestSpotInstances")
prefix := "LaunchSpecification" + "."
params["SpotPrice"] = options.SpotPrice
params[prefix+"ImageId"] = options.ImageId
params[prefix+"InstanceType"] = options.InstanceType
if options.InstanceCount != 0 {
params["InstanceCount"] = strconv.Itoa(options.InstanceCount)
}
if options.KeyName != "" {
params[prefix+"KeyName"] = options.KeyName
}
if options.KernelId != "" {
params[prefix+"KernelId"] = options.KernelId
}
if options.RamdiskId != "" {
params[prefix+"RamdiskId"] = options.RamdiskId
}
if options.UserData != nil {
userData := make([]byte, b64.EncodedLen(len(options.UserData)))
b64.Encode(userData, options.UserData)
params[prefix+"UserData"] = string(userData)
}
if options.AvailZone != "" {
params[prefix+"Placement.AvailabilityZone"] = options.AvailZone
}
if options.PlacementGroupName != "" {
params[prefix+"Placement.GroupName"] = options.PlacementGroupName
}
if options.Monitoring {
params[prefix+"Monitoring.Enabled"] = "true"
}
if options.SubnetId != "" && options.AssociatePublicIpAddress {
// If we have a non-default VPC / Subnet specified, we can flag
// AssociatePublicIpAddress to get a Public IP assigned. By default these are not provided.
// You cannot specify both SubnetId and the NetworkInterface.0.* parameters though, otherwise
// you get: Network interfaces and an instance-level subnet ID may not be specified on the same request
// You also need to attach Security Groups to the NetworkInterface instead of the instance,
// to avoid: Network interfaces and an instance-level security groups may not be specified on
// the same request
params[prefix+"NetworkInterface.0.DeviceIndex"] = "0"
params[prefix+"NetworkInterface.0.AssociatePublicIpAddress"] = "true"
params[prefix+"NetworkInterface.0.SubnetId"] = options.SubnetId
i := 1
for _, g := range options.SecurityGroups {
// We only have SecurityGroupId's on NetworkInterface's, no SecurityGroup params.
if g.Id != "" {
params[prefix+"NetworkInterface.0.SecurityGroupId."+strconv.Itoa(i)] = g.Id
i++
}
}
} else {
if options.SubnetId != "" {
params[prefix+"SubnetId"] = options.SubnetId
}
i, j := 1, 1
for _, g := range options.SecurityGroups {
if g.Id != "" {
params[prefix+"SecurityGroupId."+strconv.Itoa(i)] = g.Id
i++
} else {
params[prefix+"SecurityGroup."+strconv.Itoa(j)] = g.Name
j++
}
}
}
if options.IamInstanceProfile != "" {
params[prefix+"IamInstanceProfile.Name"] = options.IamInstanceProfile
}
if options.PrivateIPAddress != "" {
params[prefix+"PrivateIpAddress"] = options.PrivateIPAddress
}
addBlockDeviceParams(prefix, params, options.BlockDevices)
resp = &RequestSpotInstancesResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
// Response to a DescribeSpotInstanceRequests request.
//
// See http://goo.gl/KsKJJk for more details.
type SpotRequestsResp struct {
RequestId string `xml:"requestId"`
SpotRequestResults []SpotRequestResult `xml:"spotInstanceRequestSet>item"`
}
// DescribeSpotInstanceRequests returns details about spot requests in EC2. Both parameters
// are optional, and if provided will limit the spot requests returned to those
// matching the given spot request ids or filtering rules.
//
// See http://goo.gl/KsKJJk for more details.
func (ec2 *EC2) DescribeSpotRequests(spotrequestIds []string, filter *Filter) (resp *SpotRequestsResp, err error) {
params := makeParams("DescribeSpotInstanceRequests")
addParamsList(params, "SpotInstanceRequestId", spotrequestIds)
filter.addParams(params)
resp = &SpotRequestsResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
// Response to a CancelSpotInstanceRequests request.
//
// See http://goo.gl/3BKHj for more details.
type CancelSpotRequestResult struct {
SpotRequestId string `xml:"spotInstanceRequestId"`
State string `xml:"state"`
}
type CancelSpotRequestsResp struct {
RequestId string `xml:"requestId"`
CancelSpotRequestResults []CancelSpotRequestResult `xml:"spotInstanceRequestSet>item"`
}
// CancelSpotRequests requests the cancellation of spot requests when the given ids.
//
// See http://goo.gl/3BKHj for more details.
func (ec2 *EC2) CancelSpotRequests(spotrequestIds []string) (resp *CancelSpotRequestsResp, err error) {
params := makeParams("CancelSpotInstanceRequests")
addParamsList(params, "SpotInstanceRequestId", spotrequestIds)
resp = &CancelSpotRequestsResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
// Response to a TerminateInstances request.
//
// See http://goo.gl/3BKHj for more details.
type TerminateInstancesResp struct {
RequestId string `xml:"requestId"`
StateChanges []InstanceStateChange `xml:"instancesSet>item"`
}
// InstanceState encapsulates the state of an instance in EC2.
//
// See http://goo.gl/y3ZBq for more details.
type InstanceState struct {
Code int `xml:"code"` // Watch out, bits 15-8 have unpublished meaning.
Name string `xml:"name"`
}
// InstanceStateChange informs of the previous and current states
// for an instance when a state change is requested.
type InstanceStateChange struct {
InstanceId string `xml:"instanceId"`
CurrentState InstanceState `xml:"currentState"`
PreviousState InstanceState `xml:"previousState"`
}
// TerminateInstances requests the termination of instances when the given ids.
//
// See http://goo.gl/3BKHj for more details.
func (ec2 *EC2) TerminateInstances(instIds []string) (resp *TerminateInstancesResp, err error) {
params := makeParams("TerminateInstances")
addParamsList(params, "InstanceId", instIds)
resp = &TerminateInstancesResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
// Response to a DescribeInstances request.
//
// See http://goo.gl/mLbmw for more details.
type InstancesResp struct {
RequestId string `xml:"requestId"`
Reservations []Reservation `xml:"reservationSet>item"`
}
// Reservation represents details about a reservation in EC2.
//
// See http://goo.gl/0ItPT for more details.
type Reservation struct {
ReservationId string `xml:"reservationId"`
OwnerId string `xml:"ownerId"`
RequesterId string `xml:"requesterId"`
SecurityGroups []SecurityGroup `xml:"groupSet>item"`
Instances []Instance `xml:"instancesSet>item"`
}
// Instances returns details about instances in EC2. Both parameters
// are optional, and if provided will limit the instances returned to those
// matching the given instance ids or filtering rules.
//
// See http://goo.gl/4No7c for more details.
func (ec2 *EC2) Instances(instIds []string, filter *Filter) (resp *InstancesResp, err error) {
params := makeParams("DescribeInstances")
addParamsList(params, "InstanceId", instIds)
filter.addParams(params)
resp = &InstancesResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
// ----------------------------------------------------------------------------
// Volume management
// The CreateVolume request parameters
//
// See http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-CreateVolume.html
type CreateVolume struct {
AvailZone string
Size int64
SnapshotId string
VolumeType string
IOPS int64
Encrypted bool
}
// Response to an AttachVolume request
type AttachVolumeResp struct {
RequestId string `xml:"requestId"`
VolumeId string `xml:"volumeId"`
InstanceId string `xml:"instanceId"`
Device string `xml:"device"`
Status string `xml:"status"`
AttachTime string `xml:"attachTime"`
}
// Response to a CreateVolume request
type CreateVolumeResp struct {
RequestId string `xml:"requestId"`
VolumeId string `xml:"volumeId"`
Size int64 `xml:"size"`
SnapshotId string `xml:"snapshotId"`
AvailZone string `xml:"availabilityZone"`
Status string `xml:"status"`
CreateTime string `xml:"createTime"`
VolumeType string `xml:"volumeType"`
IOPS int64 `xml:"iops"`
Encrypted bool `xml:"encrypted"`
}
// Volume is a single volume.
type Volume struct {
VolumeId string `xml:"volumeId"`
Size string `xml:"size"`
SnapshotId string `xml:"snapshotId"`
AvailZone string `xml:"availabilityZone"`
Status string `xml:"status"`
Attachments []VolumeAttachment `xml:"attachmentSet>item"`
VolumeType string `xml:"volumeType"`
IOPS int64 `xml:"iops"`
Encrypted bool `xml:"encrypted"`
Tags []Tag `xml:"tagSet>item"`
}
type VolumeAttachment struct {
VolumeId string `xml:"volumeId"`
InstanceId string `xml:"instanceId"`
Device string `xml:"device"`
Status string `xml:"status"`
}
// Response to a DescribeVolumes request
type VolumesResp struct {
RequestId string `xml:"requestId"`
Volumes []Volume `xml:"volumeSet>item"`
}
// Attach a volume.
func (ec2 *EC2) AttachVolume(volumeId string, instanceId string, device string) (resp *AttachVolumeResp, err error) {
params := makeParams("AttachVolume")
params["VolumeId"] = volumeId
params["InstanceId"] = instanceId
params["Device"] = device
resp = &AttachVolumeResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
// Create a new volume.
func (ec2 *EC2) CreateVolume(options *CreateVolume) (resp *CreateVolumeResp, err error) {
params := makeParams("CreateVolume")
params["AvailabilityZone"] = options.AvailZone
if options.Size > 0 {
params["Size"] = strconv.FormatInt(options.Size, 10)
}
if options.SnapshotId != "" {
params["SnapshotId"] = options.SnapshotId
}
if options.VolumeType != "" {
params["VolumeType"] = options.VolumeType
}
if options.IOPS > 0 {
params["Iops"] = strconv.FormatInt(options.IOPS, 10)
}
if options.Encrypted {
params["Encrypted"] = "true"
}
resp = &CreateVolumeResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
// Delete an EBS volume.
func (ec2 *EC2) DeleteVolume(id string) (resp *SimpleResp, err error) {
params := makeParams("DeleteVolume")
params["VolumeId"] = id
resp = &SimpleResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
// Detaches an EBS volume.
func (ec2 *EC2) DetachVolume(id string) (resp *SimpleResp, err error) {
params := makeParams("DetachVolume")
params["VolumeId"] = id
resp = &SimpleResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
// Finds or lists all volumes.
func (ec2 *EC2) Volumes(volIds []string, filter *Filter) (resp *VolumesResp, err error) {
params := makeParams("DescribeVolumes")
addParamsList(params, "VolumeId", volIds)
filter.addParams(params)
resp = &VolumesResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
// ----------------------------------------------------------------------------
// ElasticIp management (for VPC)
// The AllocateAddress request parameters
//
// see http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AllocateAddress.html
type AllocateAddress struct {
Domain string
}
// Response to an AllocateAddress request
type AllocateAddressResp struct {
RequestId string `xml:"requestId"`
PublicIp string `xml:"publicIp"`
Domain string `xml:"domain"`
AllocationId string `xml:"allocationId"`
}
// The AssociateAddress request parameters
//
// http://docs.aws.amazon.com/AWSEC2/latest/APIReference/ApiReference-query-AssociateAddress.html
type AssociateAddress struct {
InstanceId string
PublicIp string
AllocationId string
AllowReassociation bool
}
// Response to an AssociateAddress request
type AssociateAddressResp struct {
RequestId string `xml:"requestId"`
Return bool `xml:"return"`
AssociationId string `xml:"associationId"`
}
// Address represents an Elastic IP Address
// See http://goo.gl/uxCjp7 for more details
type Address struct {
PublicIp string `xml:"publicIp"`
AllocationId string `xml:"allocationId"`
Domain string `xml:"domain"`
InstanceId string `xml:"instanceId"`
AssociationId string `xml:"associationId"`
NetworkInterfaceId string `xml:"networkInterfaceId"`
NetworkInterfaceOwnerId string `xml:"networkInterfaceOwnerId"`
PrivateIpAddress string `xml:"privateIpAddress"`
}
type DescribeAddressesResp struct {
RequestId string `xml:"requestId"`
Addresses []Address `xml:"addressesSet>item"`
}
// Allocate a new Elastic IP.
func (ec2 *EC2) AllocateAddress(options *AllocateAddress) (resp *AllocateAddressResp, err error) {
params := makeParams("AllocateAddress")
params["Domain"] = options.Domain
resp = &AllocateAddressResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
// Release an Elastic IP (VPC).
func (ec2 *EC2) ReleaseAddress(id string) (resp *SimpleResp, err error) {
params := makeParams("ReleaseAddress")
params["AllocationId"] = id
resp = &SimpleResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
// Release an Elastic IP (Public)
func (ec2 *EC2) ReleasePublicAddress(publicIp string) (resp *SimpleResp, err error) {
params := makeParams("ReleaseAddress")
params["PublicIp"] = publicIp
resp = &SimpleResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
// Associate an address with a VPC instance.
func (ec2 *EC2) AssociateAddress(options *AssociateAddress) (resp *AssociateAddressResp, err error) {
params := makeParams("AssociateAddress")
params["InstanceId"] = options.InstanceId
if options.PublicIp != "" {
params["PublicIp"] = options.PublicIp
}
if options.AllocationId != "" {
params["AllocationId"] = options.AllocationId
}
if options.AllowReassociation {
params["AllowReassociation"] = "true"
}
resp = &AssociateAddressResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err
}
return
}
// Disassociate an address from a VPC instance.
func (ec2 *EC2) DisassociateAddress(id string) (resp *SimpleResp, err error) {
params := makeParams("DisassociateAddress")
params["AssociationId"] = id
resp = &SimpleResp{}
err = ec2.query(params, resp)
if err != nil {
return nil, err