-
Notifications
You must be signed in to change notification settings - Fork 928
/
ec2.py
2257 lines (1872 loc) · 74.6 KB
/
ec2.py
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
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Amazon EC2, Eucalyptus and Nimbus drivers.
"""
import re
import sys
import base64
import copy
import warnings
from xml.etree import ElementTree as ET
from libcloud.utils.py3 import b, basestring
from libcloud.utils.xml import fixxpath, findtext, findattr, findall
from libcloud.utils.publickey import get_pubkey_ssh2_fingerprint
from libcloud.utils.publickey import get_pubkey_comment
from libcloud.utils.iso8601 import parse_date
from libcloud.common.aws import AWSBaseResponse, SignedAWSConnection
from libcloud.common.types import (InvalidCredsError, MalformedResponseError,
LibcloudError)
from libcloud.compute.providers import Provider
from libcloud.compute.base import Node, NodeDriver, NodeLocation, NodeSize
from libcloud.compute.base import NodeImage, StorageVolume, VolumeSnapshot
from libcloud.compute.base import KeyPair
from libcloud.compute.types import NodeState, KeyPairDoesNotExistError
API_VERSION = '2013-10-15'
NAMESPACE = 'http://ec2.amazonaws.com/doc/%s/' % (API_VERSION)
"""
Sizes must be hardcoded, because Amazon doesn't provide an API to fetch them.
From http://aws.amazon.com/ec2/instance-types/
"""
INSTANCE_TYPES = {
't1.micro': {
'id': 't1.micro',
'name': 'Micro Instance',
'ram': 613,
'disk': 15,
'bandwidth': None
},
'm1.small': {
'id': 'm1.small',
'name': 'Small Instance',
'ram': 1740,
'disk': 160,
'bandwidth': None
},
'm1.medium': {
'id': 'm1.medium',
'name': 'Medium Instance',
'ram': 3700,
'disk': 410,
'bandwidth': None
},
'm1.large': {
'id': 'm1.large',
'name': 'Large Instance',
'ram': 7680,
'disk': 850,
'bandwidth': None
},
'm1.xlarge': {
'id': 'm1.xlarge',
'name': 'Extra Large Instance',
'ram': 15360,
'disk': 1690,
'bandwidth': None
},
'c1.medium': {
'id': 'c1.medium',
'name': 'High-CPU Medium Instance',
'ram': 1740,
'disk': 350,
'bandwidth': None
},
'c1.xlarge': {
'id': 'c1.xlarge',
'name': 'High-CPU Extra Large Instance',
'ram': 7680,
'disk': 1690,
'bandwidth': None
},
'm2.xlarge': {
'id': 'm2.xlarge',
'name': 'High-Memory Extra Large Instance',
'ram': 17510,
'disk': 420,
'bandwidth': None
},
'm2.2xlarge': {
'id': 'm2.2xlarge',
'name': 'High-Memory Double Extra Large Instance',
'ram': 35021,
'disk': 850,
'bandwidth': None
},
'm2.4xlarge': {
'id': 'm2.4xlarge',
'name': 'High-Memory Quadruple Extra Large Instance',
'ram': 70042,
'disk': 1690,
'bandwidth': None
},
'm3.xlarge': {
'id': 'm3.xlarge',
'name': 'Extra Large Instance',
'ram': 15360,
'disk': None,
'bandwidth': None
},
'm3.2xlarge': {
'id': 'm3.2xlarge',
'name': 'Double Extra Large Instance',
'ram': 30720,
'disk': None,
'bandwidth': None
},
'cg1.4xlarge': {
'id': 'cg1.4xlarge',
'name': 'Cluster GPU Quadruple Extra Large Instance',
'ram': 22528,
'disk': 1690,
'bandwidth': None
},
'cc1.4xlarge': {
'id': 'cc1.4xlarge',
'name': 'Cluster Compute Quadruple Extra Large Instance',
'ram': 23552,
'disk': 1690,
'bandwidth': None
},
'cc2.8xlarge': {
'id': 'cc2.8xlarge',
'name': 'Cluster Compute Eight Extra Large Instance',
'ram': 63488,
'disk': 3370,
'bandwidth': None
},
# c3 instances have 2 SSDs of the specified disk size
'c3.large': {
'id': 'c3.large',
'name': 'Compute Optimized Large Instance',
'ram': 3750,
'disk': 16,
'bandwidth': None
},
'c3.xlarge': {
'id': 'c3.xlarge',
'name': 'Compute Optimized Extra Large Instance',
'ram': 7000,
'disk': 40,
'bandwidth': None
},
'c3.2xlarge': {
'id': 'c3.2xlarge',
'name': 'Compute Optimized Double Extra Large Instance',
'ram': 15000,
'disk': 80,
'bandwidth': None
},
'c3.4xlarge': {
'id': 'c3.4xlarge',
'name': 'Compute Optimized Quadruple Extra Large Instance',
'ram': 30000,
'disk': 160,
'bandwidth': None
},
'c3.8xlarge': {
'id': 'c3.8xlarge',
'name': 'Compute Optimized Eight Extra Large Instance',
'ram': 60000,
'disk': 320,
'bandwidth': None
},
'cr1.8xlarge': {
'id': 'cr1.8xlarge',
'name': 'High Memory Cluster Eight Extra Large',
'ram': 244000,
'disk': 240,
'bandwidth': None
},
'hs1.8xlarge': {
'id': 'hs1.8xlarge',
'name': 'High Storage Eight Extra Large Instance',
'ram': 119808,
'disk': 48000,
'bandwidth': None
}
}
REGION_DETAILS = {
'us-east-1': {
'endpoint': 'ec2.us-east-1.amazonaws.com',
'api_name': 'ec2_us_east',
'country': 'USA',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge',
'cc1.4xlarge',
'cc2.8xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge',
'cg1.4xlarge',
'cr1.8xlarge',
'hs1.8xlarge'
]
},
'us-west-1': {
'endpoint': 'ec2.us-west-1.amazonaws.com',
'api_name': 'ec2_us_west',
'country': 'USA',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge'
]
},
'us-west-2': {
'endpoint': 'ec2.us-west-2.amazonaws.com',
'api_name': 'ec2_us_west_oregon',
'country': 'US',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'c1.medium',
'c1.xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge',
'cc2.8xlarge'
]
},
'eu-west-1': {
'endpoint': 'ec2.eu-west-1.amazonaws.com',
'api_name': 'ec2_eu_west',
'country': 'Ireland',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge',
'cc2.8xlarge'
]
},
'ap-southeast-1': {
'endpoint': 'ec2.ap-southeast-1.amazonaws.com',
'api_name': 'ec2_ap_southeast',
'country': 'Singapore',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge',
'hs1.8xlarge'
]
},
'ap-northeast-1': {
'endpoint': 'ec2.ap-northeast-1.amazonaws.com',
'api_name': 'ec2_ap_northeast',
'country': 'Japan',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge'
]
},
'sa-east-1': {
'endpoint': 'ec2.sa-east-1.amazonaws.com',
'api_name': 'ec2_sa_east',
'country': 'Brazil',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge'
]
},
'ap-southeast-2': {
'endpoint': 'ec2.ap-southeast-2.amazonaws.com',
'api_name': 'ec2_ap_southeast_2',
'country': 'Australia',
'instance_types': [
't1.micro',
'm1.small',
'm1.medium',
'm1.large',
'm1.xlarge',
'm2.xlarge',
'm2.2xlarge',
'm2.4xlarge',
'm3.xlarge',
'm3.2xlarge',
'c1.medium',
'c1.xlarge',
'c3.large',
'c3.xlarge',
'c3.2xlarge',
'c3.4xlarge',
'c3.8xlarge',
'hs1.8xlarge'
]
},
'nimbus': {
# Nimbus clouds have 3 EC2-style instance types but their particular
# RAM allocations are configured by the admin
'country': 'custom',
'instance_types': [
'm1.small',
'm1.large',
'm1.xlarge'
]
}
}
VALID_EC2_REGIONS = REGION_DETAILS.keys()
VALID_EC2_REGIONS = [r for r in VALID_EC2_REGIONS if r != 'nimbus']
class EC2NodeLocation(NodeLocation):
def __init__(self, id, name, country, driver, availability_zone):
super(EC2NodeLocation, self).__init__(id, name, country, driver)
self.availability_zone = availability_zone
def __repr__(self):
return (('<EC2NodeLocation: id=%s, name=%s, country=%s, '
'availability_zone=%s driver=%s>')
% (self.id, self.name, self.country,
self.availability_zone, self.driver.name))
class EC2Response(AWSBaseResponse):
"""
EC2 specific response parsing and error handling.
"""
def parse_error(self):
err_list = []
# Okay, so for Eucalyptus, you can get a 403, with no body,
# if you are using the wrong user/password.
msg = "Failure: 403 Forbidden"
if self.status == 403 and self.body[:len(msg)] == msg:
raise InvalidCredsError(msg)
try:
body = ET.XML(self.body)
except:
raise MalformedResponseError("Failed to parse XML",
body=self.body, driver=EC2NodeDriver)
for err in body.findall('Errors/Error'):
code, message = err.getchildren()
err_list.append('%s: %s' % (code.text, message.text))
if code.text == 'InvalidClientTokenId':
raise InvalidCredsError(err_list[-1])
if code.text == 'SignatureDoesNotMatch':
raise InvalidCredsError(err_list[-1])
if code.text == 'AuthFailure':
raise InvalidCredsError(err_list[-1])
if code.text == 'OptInRequired':
raise InvalidCredsError(err_list[-1])
if code.text == 'IdempotentParameterMismatch':
raise IdempotentParamError(err_list[-1])
if code.text == 'InvalidKeyPair.NotFound':
# TODO: Use connection context instead
match = re.match(r'.*\'(.+?)\'.*', message.text)
if match:
name = match.groups()[0]
else:
name = None
raise KeyPairDoesNotExistError(name=name,
driver=self.connection.driver)
return '\n'.join(err_list)
class EC2Connection(SignedAWSConnection):
"""
Represents a single connection to the EC2 Endpoint.
"""
version = API_VERSION
host = REGION_DETAILS['us-east-1']['endpoint']
responseCls = EC2Response
class ExEC2AvailabilityZone(object):
"""
Extension class which stores information about an EC2 availability zone.
Note: This class is EC2 specific.
"""
def __init__(self, name, zone_state, region_name):
self.name = name
self.zone_state = zone_state
self.region_name = region_name
def __repr__(self):
return (('<ExEC2AvailabilityZone: name=%s, zone_state=%s, '
'region_name=%s>')
% (self.name, self.zone_state, self.region_name))
class BaseEC2NodeDriver(NodeDriver):
"""
Base Amazon EC2 node driver.
Used for main EC2 and other derivate driver classes to inherit from it.
"""
connectionCls = EC2Connection
features = {'create_node': ['ssh_key']}
path = '/'
NODE_STATE_MAP = {
'pending': NodeState.PENDING,
'running': NodeState.RUNNING,
'shutting-down': NodeState.UNKNOWN,
'terminated': NodeState.TERMINATED
}
def _pathlist(self, key, arr):
"""
Converts a key and an array of values into AWS query param format.
"""
params = {}
i = 0
for value in arr:
i += 1
params["%s.%s" % (key, i)] = value
return params
def _get_boolean(self, element):
tag = "{%s}%s" % (NAMESPACE, 'return')
return element.findtext(tag) == 'true'
def _get_state_boolean(self, element):
"""
Checks for the instances's state
"""
state = findall(element=element,
xpath='instancesSet/item/currentState/name',
namespace=NAMESPACE)[0].text
return state in ('stopping', 'pending', 'starting')
def _get_terminate_boolean(self, element):
status = element.findtext(".//{%s}%s" % (NAMESPACE, 'name'))
return any([term_status == status
for term_status
in ('shutting-down', 'terminated')])
def _to_nodes(self, object, xpath, groups=None):
return [self._to_node(el, groups=groups)
for el in object.findall(fixxpath(xpath=xpath,
namespace=NAMESPACE))]
def _to_node(self, element, groups=None):
try:
state = self.NODE_STATE_MAP[findattr(element=element,
xpath="instanceState/name",
namespace=NAMESPACE)
]
except KeyError:
state = NodeState.UNKNOWN
instance_id = findtext(element=element, xpath='instanceId',
namespace=NAMESPACE)
tags = dict((findtext(element=item, xpath='key', namespace=NAMESPACE),
findtext(element=item, xpath='value',
namespace=NAMESPACE))
for item in findall(element=element,
xpath='tagSet/item',
namespace=NAMESPACE)
)
name = tags.get('Name', instance_id)
public_ip = findtext(element=element, xpath='ipAddress',
namespace=NAMESPACE)
public_ips = [public_ip] if public_ip else []
private_ip = findtext(element=element, xpath='privateIpAddress',
namespace=NAMESPACE)
private_ips = [private_ip] if private_ip else []
n = Node(
id=findtext(element=element, xpath='instanceId',
namespace=NAMESPACE),
name=name,
state=state,
public_ips=public_ips,
private_ips=private_ips,
driver=self.connection.driver,
extra={
'dns_name': findattr(element=element, xpath="dnsName",
namespace=NAMESPACE),
'instanceId': findattr(element=element, xpath="instanceId",
namespace=NAMESPACE),
'imageId': findattr(element=element, xpath="imageId",
namespace=NAMESPACE),
'private_dns': findattr(element=element,
xpath="privateDnsName",
namespace=NAMESPACE),
'status': findattr(element=element, xpath="instanceState/name",
namespace=NAMESPACE),
'keyname': findattr(element=element, xpath="keyName",
namespace=NAMESPACE),
'launchindex': findattr(element=element,
xpath="amiLaunchIndex",
namespace=NAMESPACE),
'productcode': [
p.text for p in findall(
element=element,
xpath="productCodesSet/item/productCode",
namespace=NAMESPACE
)],
'instancetype': findattr(element=element, xpath="instanceType",
namespace=NAMESPACE),
'launchdatetime': findattr(element=element, xpath="launchTime",
namespace=NAMESPACE),
'availability': findattr(element,
xpath="placement/availabilityZone",
namespace=NAMESPACE),
'kernelid': findattr(element=element, xpath="kernelId",
namespace=NAMESPACE),
'ramdiskid': findattr(element=element, xpath="ramdiskId",
namespace=NAMESPACE),
'clienttoken': findattr(element=element, xpath="clientToken",
namespace=NAMESPACE),
'groups': groups,
'tags': tags,
'iam_profile': findattr(element, xpath="iamInstanceProfile/id",
namespace=NAMESPACE)
}
)
return n
def _to_images(self, object):
return [self._to_image(el) for el in object.findall(
fixxpath(xpath='imagesSet/item', namespace=NAMESPACE))
]
def _to_image(self, element):
n = NodeImage(
id=findtext(element=element, xpath='imageId', namespace=NAMESPACE),
name=findtext(element=element, xpath='imageLocation',
namespace=NAMESPACE),
driver=self.connection.driver,
extra={
'state': findattr(element=element, xpath="imageState",
namespace=NAMESPACE),
'ownerid': findattr(element=element, xpath="imageOwnerId",
namespace=NAMESPACE),
'owneralias': findattr(element=element,
xpath="imageOwnerAlias",
namespace=NAMESPACE),
'ispublic': findattr(element=element,
xpath="isPublic",
namespace=NAMESPACE),
'architecture': findattr(element=element,
xpath="architecture",
namespace=NAMESPACE),
'imagetype': findattr(element=element,
xpath="imageType",
namespace=NAMESPACE),
'platform': findattr(element=element,
xpath="platform",
namespace=NAMESPACE),
'rootdevicetype': findattr(element=element,
xpath="rootDeviceType",
namespace=NAMESPACE),
'virtualizationtype': findattr(
element=element, xpath="virtualizationType",
namespace=NAMESPACE),
'hypervisor': findattr(element=element,
xpath="hypervisor",
namespace=NAMESPACE)
}
)
return n
def _to_volume(self, element, name):
volId = findtext(element=element, xpath='volumeId',
namespace=NAMESPACE)
size = findtext(element=element, xpath='size', namespace=NAMESPACE)
state = findtext(element=element, xpath='status', namespace=NAMESPACE)
create_time = findtext(element=element, xpath='createTime',
namespace=NAMESPACE)
device = findtext(element=element, xpath='attachmentSet/item/device',
namespace=NAMESPACE)
return StorageVolume(id=volId,
name=name,
size=int(size),
driver=self,
extra={'state': state,
'device': device,
'create-time': parse_date(create_time)})
def _to_snapshots(self, response):
return [self._to_snapshot(el) for el in response.findall(
fixxpath(xpath='snapshotSet/item', namespace=NAMESPACE))
]
def _to_snapshot(self, element):
snapId = findtext(element=element, xpath='snapshotId',
namespace=NAMESPACE)
volId = findtext(element=element, xpath='volumeId',
namespace=NAMESPACE)
size = findtext(element=element, xpath='volumeSize',
namespace=NAMESPACE)
state = findtext(element=element, xpath='status',
namespace=NAMESPACE)
description = findtext(element=element, xpath='description',
namespace=NAMESPACE)
return VolumeSnapshot(snapId, size=int(size), driver=self,
extra={'volume_id': volId,
'description': description,
'state': state})
def list_nodes(self, ex_node_ids=None):
"""
List all nodes
Ex_node_ids parameter is used to filter the list of
nodes that should be returned. Only the nodes
with the corresponding node ids will be returned.
:param ex_node_ids: List of ``node.id``
:type ex_node_ids: ``list`` of ``str``
:rtype: ``list`` of :class:`Node`
"""
params = {'Action': 'DescribeInstances'}
if ex_node_ids:
params.update(self._pathlist('InstanceId', ex_node_ids))
elem = self.connection.request(self.path, params=params).object
nodes = []
for rs in findall(element=elem, xpath='reservationSet/item',
namespace=NAMESPACE):
groups = [g.findtext('')
for g in findall(element=rs,
xpath='groupSet/item/groupId',
namespace=NAMESPACE)]
nodes += self._to_nodes(rs, 'instancesSet/item', groups)
nodes_elastic_ips_mappings = self.ex_describe_addresses(nodes)
for node in nodes:
ips = nodes_elastic_ips_mappings[node.id]
node.public_ips.extend(ips)
return nodes
def list_sizes(self, location=None):
available_types = REGION_DETAILS[self.region_name]['instance_types']
sizes = []
for instance_type in available_types:
attributes = INSTANCE_TYPES[instance_type]
attributes = copy.deepcopy(attributes)
price = self._get_size_price(size_id=instance_type)
attributes.update({'price': price})
sizes.append(NodeSize(driver=self, **attributes))
return sizes
def list_images(self, location=None, ex_image_ids=None, ex_owner=None):
"""
List all images
Ex_image_ids parameter is used to filter the list of
images that should be returned. Only the images
with the corresponding image ids will be returned.
Ex_owner parameter is used to filter the list of
images that should be returned. Only the images
with the corresponding owner will be returned.
Valid values: amazon|aws-marketplace|self|all|aws id
:param ex_image_ids: List of ``NodeImage.id``
:type ex_image_ids: ``list`` of ``str``
:param ex_owner: Owner name
:type ex_image_ids: ``str``
:rtype: ``list`` of :class:`NodeImage`
"""
params = {'Action': 'DescribeImages'}
if ex_owner:
params.update({'Owner.1': ex_owner})
if ex_image_ids:
params.update(self._pathlist('ImageId', ex_image_ids))
images = self._to_images(
self.connection.request(self.path, params=params).object
)
return images
def ex_get_limits(self):
"""
Retrieve account resource limits.
:rtype: ``dict``
"""
attributes = ['max-instances', 'max-elastic-ips',
'vpc-max-elastic-ips']
params = {}
params['Action'] = 'DescribeAccountAttributes'
for index, attribute in enumerate(attributes):
params['AttributeName.%s' % (index)] = attribute
response = self.connection.request(self.path, params=params)
data = response.object
elems = data.findall(fixxpath(xpath='accountAttributeSet/item',
namespace=NAMESPACE))
result = {'resource': {}}
for elem in elems:
name = findtext(element=elem, xpath='attributeName',
namespace=NAMESPACE)
value = findtext(element=elem,
xpath='attributeValueSet/item/attributeValue',
namespace=NAMESPACE)
result['resource'][name] = int(value)
return result
def list_locations(self):
locations = []
for index, availability_zone in \
enumerate(self.ex_list_availability_zones()):
locations.append(EC2NodeLocation(
index, availability_zone.name, self.country, self,
availability_zone)
)
return locations
def list_volumes(self, node=None):
params = {
'Action': 'DescribeVolumes',
}
if node:
params.update({
'Filter.1.Name': 'attachment.instance-id',
'Filter.1.Value': node.id,
})
response = self.connection.request(self.path, params=params).object
volumes = [self._to_volume(el, '') for el in response.findall(
fixxpath(xpath='volumeSet/item', namespace=NAMESPACE))
]
return volumes
def create_volume(self, size, name, location=None, snapshot=None):
"""
:param location: Datacenter in which to create a volume in.
:type location: :class:`ExEC2AvailabilityZone`
"""
params = {
'Action': 'CreateVolume',
'Size': str(size)}
if location is not None:
params['AvailabilityZone'] = location.availability_zone.name
volume = self._to_volume(
self.connection.request(self.path, params=params).object,
name=name)
self.ex_create_tags(volume, {'Name': name})
return volume
def destroy_volume(self, volume):
params = {
'Action': 'DeleteVolume',
'VolumeId': volume.id}
response = self.connection.request(self.path, params=params).object
return self._get_boolean(response)
def attach_volume(self, node, volume, device):
params = {
'Action': 'AttachVolume',
'VolumeId': volume.id,
'InstanceId': node.id,
'Device': device}
self.connection.request(self.path, params=params)
return True
def detach_volume(self, volume):
params = {
'Action': 'DetachVolume',
'VolumeId': volume.id}
self.connection.request(self.path, params=params)
return True
def create_volume_snapshot(self, volume, name=None):
"""
Create snapshot from volume
:param volume: Instance of ``StorageVolume``
:type volume: ``StorageVolume``
:param name: Description for snapshot
:type name: ``str``
:rtype: :class:`VolumeSnapshot`
"""
params = {
'Action': 'CreateSnapshot',
'VolumeId': volume.id,
}
if name:
params.update({
'Description': name,
})
response = self.connection.request(self.path, params=params).object
snapshot = self._to_snapshot(response)
return snapshot
def list_volume_snapshots(self, snapshot):
return self.list_snapshots(snapshot)
def list_snapshots(self, snapshot=None, owner=None):
"""
Describe all snapshots.
:param snapshot: If provided, only return snapshot information for the
provided snapshot.
:param owner: Owner for snapshot: self|amazon|ID
:type owner: ``str``
:rtype: ``list`` of :class:`VolumeSnapshot`
"""
params = {
'Action': 'DescribeSnapshots',
}
if snapshot:
params.update({
'SnapshotId.1': snapshot.id,
})
if owner:
params.update({
'Owner.1': owner,
})
response = self.connection.request(self.path, params=params).object
snapshots = self._to_snapshots(response)
return snapshots
def destroy_volume_snapshot(self, snapshot):
params = {
'Action': 'DeleteSnapshot',
'SnapshotId': snapshot.id
}
response = self.connection.request(self.path, params=params).object
return self._get_boolean(response)
def _to_key_pairs(self, elems):
key_pairs = [self._to_key_pair(elem=elem) for elem in elems]
return key_pairs
def _to_key_pair(self, elem):
name = findtext(element=elem, xpath='keyName', namespace=NAMESPACE)
fingerprint = findtext(element=elem, xpath='keyFingerprint',
namespace=NAMESPACE).strip()
private_key = findtext(element=elem, xpath='keyMaterial',
namespace=NAMESPACE)
key_pair = KeyPair(name=name,
public_key=None,
fingerprint=fingerprint,
private_key=private_key,
driver=self)
return key_pair
def list_key_pairs(self):
params = {
'Action': 'DescribeKeyPairs'
}
response = self.connection.request(self.path, params=params)
elems = findall(element=response.object, xpath='keySet/item',
namespace=NAMESPACE)
key_pairs = self._to_key_pairs(elems=elems)
return key_pairs
def get_key_pair(self, name):
params = {
'Action': 'DescribeKeyPairs',
'KeyName': name
}
response = self.connection.request(self.path, params=params)