forked from jtriley/StarCluster
/
awsutils.py
1499 lines (1375 loc) · 60 KB
/
awsutils.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
# Copyright 2009-2013 Justin Riley
#
# This file is part of StarCluster.
#
# StarCluster is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option) any
# later version.
#
# StarCluster is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
# details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with StarCluster. If not, see <http://www.gnu.org/licenses/>.
"""
EC2/S3 Utility Classes
"""
import os
import re
import time
import base64
import string
import tempfile
import boto
import boto.ec2
import boto.s3.connection
from boto import config as boto_config
from boto.connection import HAVE_HTTPS_CONNECTION
from starcluster import image
from starcluster import utils
from starcluster import static
from starcluster import spinner
from starcluster import webtools
from starcluster import exception
from starcluster import progressbar
from starcluster.utils import print_timing
from starcluster.logger import log
class EasyAWS(object):
def __init__(self, aws_access_key_id, aws_secret_access_key,
connection_authenticator, **kwargs):
"""
Create an EasyAWS object.
Requires aws_access_key_id/aws_secret_access_key from an Amazon Web
Services (AWS) account and a connection_authenticator function that
returns an authenticated AWS connection object
Providing only the keys will default to using Amazon EC2
kwargs are passed to the connection_authenticator's constructor
"""
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
self.connection_authenticator = connection_authenticator
self._conn = None
self._kwargs = kwargs
def reload(self):
self._conn = None
return self.conn
@property
def conn(self):
if self._conn is None:
log.debug('creating self._conn w/ connection_authenticator ' +
'kwargs = %s' % self._kwargs)
validate_certs = self._kwargs.get('validate_certs', True)
if validate_certs:
if not HAVE_HTTPS_CONNECTION:
raise exception.AWSError(
"Failed to validate AWS SSL certificates. "
"SSL certificate validation is only supported "
"on Python>=2.6.\n\nSet AWS_VALIDATE_CERTS=False in "
"the [aws info] section of your config to skip SSL "
"certificate verification and suppress this error AT "
"YOUR OWN RISK.")
if not boto_config.has_section('Boto'):
boto_config.add_section('Boto')
# Hack to get around the fact that boto ignores validate_certs
# if https_validate_certificates is declared in the boto config
boto_config.setbool('Boto', 'https_validate_certificates',
validate_certs)
self._conn = self.connection_authenticator(
self.aws_access_key_id, self.aws_secret_access_key,
**self._kwargs)
self._conn.https_validate_certificates = validate_certs
return self._conn
class EasyEC2(EasyAWS):
def __init__(self, aws_access_key_id, aws_secret_access_key,
aws_ec2_path='/', aws_s3_host=None, aws_s3_path='/',
aws_port=None, aws_region_name=None, aws_is_secure=True,
aws_region_host=None, aws_proxy=None, aws_proxy_port=None,
aws_proxy_user=None, aws_proxy_pass=None,
aws_validate_certs=True, **kwargs):
aws_region = None
if aws_region_name and aws_region_host:
aws_region = boto.ec2.regioninfo.RegionInfo(
name=aws_region_name, endpoint=aws_region_host)
kwargs = dict(is_secure=aws_is_secure, region=aws_region,
port=aws_port, path=aws_ec2_path, proxy=aws_proxy,
proxy_port=aws_proxy_port, proxy_user=aws_proxy_user,
proxy_pass=aws_proxy_pass,
validate_certs=aws_validate_certs)
super(EasyEC2, self).__init__(aws_access_key_id, aws_secret_access_key,
boto.connect_ec2, **kwargs)
kwargs = dict(aws_s3_host=aws_s3_host, aws_s3_path=aws_s3_path,
aws_port=aws_port, aws_is_secure=aws_is_secure,
aws_proxy=aws_proxy, aws_proxy_port=aws_proxy_port,
aws_proxy_user=aws_proxy_user,
aws_proxy_pass=aws_proxy_pass,
aws_validate_certs=aws_validate_certs)
self.s3 = EasyS3(aws_access_key_id, aws_secret_access_key, **kwargs)
self._regions = None
self._platforms = None
self._default_vpc = None
def __repr__(self):
return '<EasyEC2: %s (%s)>' % (self.region.name, self.region.endpoint)
def _fetch_account_attrs(self):
resp = self.conn.describe_account_attributes(
['default-vpc', 'supported-platforms'])
self._platforms = resp[0].attribute_values
self._default_vpc = resp[1].attribute_values[0]
@property
def supported_platforms(self):
if not self._platforms:
self._fetch_account_attrs()
return self._platforms
@property
def default_vpc(self):
if not self._default_vpc:
self._fetch_account_attrs()
return self._default_vpc
def connect_to_region(self, region_name):
"""
Connects to a given region if it exists, raises RegionDoesNotExist
otherwise. Once connected, this object will return only data from the
given region.
"""
region = self.get_region(region_name)
self._kwargs['region'] = region
self._platforms = None
self._default_vpc = None
self.reload()
return self
@property
def region(self):
"""
Returns the current EC2 region used by this EasyEC2 object
"""
return self.conn.region
@property
def regions(self):
"""
This property returns all AWS Regions, caching the results the first
time a request is made to Amazon
"""
if not self._regions:
self._regions = {}
regions = self.conn.get_all_regions()
for region in regions:
self._regions[region.name] = region
return self._regions
def get_region(self, region_name):
"""
Returns boto Region object if it exists, raises RegionDoesNotExist
otherwise.
"""
if not region_name in self.regions:
raise exception.RegionDoesNotExist(region_name)
return self.regions.get(region_name)
def list_regions(self):
"""
Print name/endpoint for all AWS regions
"""
regions = self.regions.items()
regions.sort(reverse=True)
for name, endpoint in regions:
print 'name: ', name
print 'endpoint: ', endpoint.endpoint
print
@property
def registered_images(self):
return self.conn.get_all_images(owners=["self"])
@property
def executable_images(self):
return self.conn.get_all_images(executable_by=["self"])
def get_registered_image(self, image_id):
if not image_id.startswith('ami') or len(image_id) != 12:
raise TypeError("invalid AMI name/id requested: %s" % image_id)
for img in self.registered_images:
if img.id == image_id:
return img
def delete_group(self, group):
"""
This method deletes the security group using group.delete() but in the
case that group.delete() throws a DependencyViolation error it will
keep retrying until it's successful. Waits 5 seconds between each
retry.
"""
s = utils.get_spinner("Removing %s security group..." % group.name)
try:
while True:
try:
return group.delete()
except boto.exception.EC2ResponseError, e:
if e.error_code == 'DependencyViolation':
log.debug('DependencyViolation error - retrying in 5s',
exc_info=True)
time.sleep(5)
else:
raise
finally:
s.stop()
def create_group(self, name, description, auth_ssh=False,
auth_group_traffic=False):
"""
Create security group with name/description. auth_ssh=True
will open port 22 to world (0.0.0.0/0). auth_group_traffic
will allow all traffic between instances in the same security
group
"""
log.info("Creating security group %s..." % name)
sg = self.conn.create_security_group(name, description)
while not self.get_group_or_none(name):
log.info("Waiting for security group %s..." % name)
time.sleep(3)
if auth_ssh:
ssh_port = static.DEFAULT_SSH_PORT
sg.authorize('tcp', ssh_port, ssh_port, static.WORLD_CIDRIP)
if auth_group_traffic:
src_group = self.get_group_or_none(name)
sg.authorize('icmp', -1, -1, src_group=src_group)
sg.authorize('tcp', 1, 65535, src_group=src_group)
sg.authorize('udp', 1, 65535, src_group=src_group)
return sg
def get_all_security_groups(self, groupnames=[]):
"""
Returns all security groups
groupnames - optional list of group names to retrieve
"""
filters = {}
if groupnames:
filters = {'group-name': groupnames}
return self.get_security_groups(filters=filters)
def get_group_or_none(self, name):
"""
Returns group with name if it exists otherwise returns None
"""
try:
return self.get_security_group(name)
except exception.SecurityGroupDoesNotExist:
pass
def get_or_create_group(self, name, description, auth_ssh=True,
auth_group_traffic=False):
"""
Try to return a security group by name. If the group is not found,
attempt to create it. Description only applies to creation.
auth_ssh - authorize ssh traffic from world
auth_group_traffic - authorizes all traffic between members of the
group
"""
sg = self.get_group_or_none(name)
if not sg:
sg = self.create_group(name, description, auth_ssh,
auth_group_traffic)
return sg
def get_security_group(self, groupname):
try:
return self.get_security_groups(
filters={'group-name': groupname})[0]
except boto.exception.EC2ResponseError, e:
if e.error_code == "InvalidGroup.NotFound":
raise exception.SecurityGroupDoesNotExist(groupname)
raise
except IndexError:
raise exception.SecurityGroupDoesNotExist(groupname)
def get_security_groups(self, filters=None):
"""
Returns all security groups on this EC2 account
"""
return self.conn.get_all_security_groups(filters=filters)
def get_permission_or_none(self, group, ip_protocol, from_port, to_port,
cidr_ip=None):
"""
Returns the rule with the specified port range permission (ip_protocol,
from_port, to_port, cidr_ip) defined or None if no such rule exists
"""
for rule in group.rules:
if rule.ip_protocol != ip_protocol:
continue
if int(rule.from_port) != from_port:
continue
if int(rule.to_port) != to_port:
continue
if cidr_ip:
cidr_grants = [g for g in rule.grants if g.cidr_ip == cidr_ip]
if not cidr_grants:
continue
return rule
def has_permission(self, group, ip_protocol, from_port, to_port, cidr_ip):
"""
Checks whether group has the specified port range permission
(ip_protocol, from_port, to_port, cidr_ip) defined
"""
for rule in group.rules:
if rule.ip_protocol != ip_protocol:
continue
if int(rule.from_port) != from_port:
continue
if int(rule.to_port) != to_port:
continue
cidr_grants = [g for g in rule.grants if g.cidr_ip == cidr_ip]
if not cidr_grants:
continue
return True
return False
def create_placement_group(self, name):
"""
Create a new placement group for your account.
This will create the placement group within the region you
are currently connected to.
"""
log.info("Creating placement group %s..." % name)
success = self.conn.create_placement_group(name)
if not success:
log.debug(
"failed to create placement group '%s' (error = %s)" %
(name, success))
raise exception.AWSError(
"failed to create placement group '%s'" % name)
pg = self.get_placement_group_or_none(name)
while not pg:
log.info("Waiting for placement group %s..." % name)
time.sleep(3)
pg = self.get_placement_group_or_none(name)
return pg
def get_placement_groups(self, filters=None):
return self.conn.get_all_placement_groups(filters=filters)
def get_placement_group(self, groupname=None):
try:
return self.get_placement_groups(filters={'group-name':
groupname})[0]
except boto.exception.EC2ResponseError, e:
if e.error_code == "InvalidPlacementGroup.Unknown":
raise exception.PlacementGroupDoesNotExist(groupname)
raise
except IndexError:
raise exception.PlacementGroupDoesNotExist(groupname)
def get_placement_group_or_none(self, name):
"""
Returns placement group with name if it exists otherwise returns None
"""
try:
return self.get_placement_group(name)
except exception.PlacementGroupDoesNotExist:
pass
def get_or_create_placement_group(self, name):
"""
Try to return a placement group by name.
If the group is not found, attempt to create it.
"""
try:
return self.get_placement_group(name)
except exception.PlacementGroupDoesNotExist:
pg = self.create_placement_group(name)
return pg
def request_instances(self, image_id, price=None, instance_type='m1.small',
min_count=1, max_count=1, count=1, key_name=None,
security_groups=None, launch_group=None,
availability_zone_group=None, placement=None,
user_data=None, placement_group=None,
block_device_map=None):
"""
Convenience method for running spot or flat-rate instances
"""
if not block_device_map:
img = self.get_image(image_id)
bdmap = self.create_block_device_map(add_ephemeral_drives=True,
num_ephemeral_drives=24)
# Prune drives from runtime block device map that may override EBS
# volumes specified in the AMIs block device map
for dev in img.block_device_mapping:
bdt = img.block_device_mapping.get(dev)
if not bdt.ephemeral_name and dev in bdmap:
log.debug("EBS volume already mapped to %s by AMI" % dev)
log.debug("Removing %s from runtime block device map" %
dev)
bdmap.pop(dev)
block_device_map = bdmap
if price:
return self.request_spot_instances(
price, image_id, instance_type=instance_type,
count=count, launch_group=launch_group, key_name=key_name,
security_groups=security_groups,
availability_zone_group=availability_zone_group,
placement=placement, placement_group=placement_group,
user_data=user_data, block_device_map=block_device_map)
else:
return self.run_instances(
image_id, instance_type=instance_type,
min_count=min_count, max_count=max_count,
key_name=key_name, security_groups=security_groups,
placement=placement, user_data=user_data,
placement_group=placement_group,
block_device_map=block_device_map)
def request_spot_instances(self, price, image_id, instance_type='m1.small',
count=1, launch_group=None, key_name=None,
availability_zone_group=None,
security_groups=None, placement=None,
placement_group=None, user_data=None,
block_device_map=None):
requests = self.conn.request_spot_instances(
price, image_id, instance_type=instance_type, count=count,
launch_group=launch_group, key_name=key_name,
security_groups=security_groups,
availability_zone_group=availability_zone_group,
placement=placement, placement_group=placement_group,
user_data=user_data, block_device_map=block_device_map)
requests_ids = []
for request in requests:
requests_ids.append(request.id)
#Make sure the spot instance request has been ingested by EC2
#before proceeding. Wait at most 10 sec.
counter = 0
while True:
all_requests = self.conn.get_all_spot_instance_requests()
all_requests.reverse() # start from the end as our request will
# usually be the last
for request in all_requests:
if request.id in requests_ids:
del requests_ids[requests_ids.index(request.id)]
if len(requests_ids) == 0:
#done
return requests
if counter % 10 == 0:
log.info("Still waiting for instances " + str(requests_ids))
log.debug(str(counter) + ": Instance not propagated, sleeping")
time.sleep(1)
counter += 1
def _wait_for_propagation(self, obj_ids, fetch_func, id_filter, obj_name,
max_retries=5, interval=5):
"""
Wait for a list of object ids to appear in the AWS API. Requires a
function that fetches the objects and also takes a filters kwarg. The
id_filter specifies the id filter to use for the objects and
obj_name describes the objects for log messages.
"""
filters = {id_filter: obj_ids}
num_objs = len(obj_ids)
num_reqs = 0
reqs_ids = []
max_retries = max(1, max_retries)
interval = max(1, interval)
s = utils.get_spinner("Waiting for %s to propagate..." % obj_name)
try:
for i in range(max_retries):
reqs = fetch_func(filters=filters)
reqs_ids = [req.id for req in reqs]
num_reqs = len(reqs)
if num_reqs != num_objs:
log.debug("%d: only %d/%d %s have "
"propagated - sleeping..." %
(i, num_reqs, num_objs, obj_name))
time.sleep(interval)
else:
return
finally:
s.stop()
log.warn("Only %d/%d %s propagated..." %
(num_reqs, num_objs, obj_name))
missing = [oid for oid in obj_ids if oid not in reqs_ids]
log.warn("Missing %s: %s" % (obj_name, ', '.join(missing)))
def wait_for_propagation(self, instances=None, spot_requests=None,
max_retries=5, interval=5):
"""
Wait for newly created instances and/or spot_requests to register in
the AWS API by repeatedly calling get_all_{instances, spot_requests}.
Calling this method directly after creating new instances or spot
requests before operating on them helps to avoid eventual consistency
errors about instances or spot requests not existing.
"""
if spot_requests:
spot_ids = [getattr(s, 'id', s) for s in spot_requests]
self._wait_for_propagation(
spot_ids, self.get_all_spot_requests,
'spot-instance-request-id', 'spot requests',
max_retries=max_retries, interval=interval)
if instances:
instance_ids = [getattr(i, 'id', i) for i in instances]
self._wait_for_propagation(
instance_ids, self.get_all_instances, 'instance-id',
'instances', max_retries=max_retries, interval=interval)
def run_instances(self, image_id, instance_type='m1.small', min_count=1,
max_count=1, key_name=None, security_groups=None,
placement=None, user_data=None, placement_group=None,
block_device_map=None):
return self.conn.run_instances(image_id, instance_type=instance_type,
min_count=min_count,
max_count=max_count,
key_name=key_name,
security_groups=security_groups,
placement=placement,
user_data=user_data,
placement_group=placement_group,
block_device_map=block_device_map)
def create_image(self, instance_id, name, description=None,
no_reboot=False):
return self.conn.create_image(instance_id, name,
description=description,
no_reboot=no_reboot)
def register_image(self, name, description=None, image_location=None,
architecture=None, kernel_id=None, ramdisk_id=None,
root_device_name=None, block_device_map=None):
return self.conn.register_image(name=name, description=description,
image_location=image_location,
architecture=architecture,
kernel_id=kernel_id,
ramdisk_id=ramdisk_id,
root_device_name=root_device_name,
block_device_map=block_device_map)
def delete_keypair(self, name):
return self.conn.delete_key_pair(name)
def create_keypair(self, name, output_file=None):
"""
Create a new EC2 keypair and optionally save to output_file
Returns boto.ec2.keypair.KeyPair
"""
if output_file:
output_dir = os.path.dirname(output_file)
if output_dir and not os.path.exists(output_dir):
raise exception.BaseException(
"output directory does not exist")
if os.path.exists(output_file):
raise exception.BaseException(
"cannot save keypair %s: file already exists" %
output_file)
kp = self.conn.create_key_pair(name)
if output_file:
try:
kfile = open(output_file, 'wb')
kfile.write(kp.material)
kfile.close()
os.chmod(output_file, 0400)
except IOError, e:
raise exception.BaseException(str(e))
return kp
def get_keypairs(self, filters={}):
return self.conn.get_all_key_pairs(filters=filters)
def get_keypair(self, keypair):
try:
return self.get_keypairs(filters={'key-name': keypair})[0]
except boto.exception.EC2ResponseError, e:
if e.error_code == "InvalidKeyPair.NotFound":
raise exception.KeyPairDoesNotExist(keypair)
raise
except IndexError:
raise exception.KeyPairDoesNotExist(keypair)
def get_keypair_or_none(self, keypair):
try:
return self.get_keypair(keypair)
except exception.KeyPairDoesNotExist:
pass
def __print_header(self, msg):
print msg
print "-" * len(msg)
def get_image_name(self, img):
image_name = re.sub('\.manifest\.xml$', '',
img.location.split('/')[-1])
return image_name
def get_instance_user_data(self, instance_id):
try:
attrs = self.conn.get_instance_attribute(instance_id, 'userData')
user_data = attrs.get('userData', '') or ''
return base64.b64decode(user_data)
except boto.exception.EC2ResponseError, e:
if e.error_code == "InvalidInstanceID.NotFound":
raise exception.InstanceDoesNotExist(instance_id)
raise e
def get_all_instances(self, instance_ids=[], filters=None):
reservations = self.conn.get_all_instances(instance_ids,
filters=filters)
instances = []
for res in reservations:
insts = res.instances
for i in insts:
# set group info
i.groups = res.groups
instances.extend(insts)
return instances
def get_instance(self, instance_id):
try:
return self.get_all_instances(
filters={'instance-id': instance_id})[0]
except boto.exception.EC2ResponseError, e:
if e.error_code == "InvalidInstanceID.NotFound":
raise exception.InstanceDoesNotExist(instance_id)
raise
except IndexError:
raise exception.InstanceDoesNotExist(instance_id)
def is_valid_conn(self):
try:
self.get_all_instances()
return True
except boto.exception.EC2ResponseError, e:
cred_errs = ['AuthFailure', 'SignatureDoesNotMatch']
if e.error_code in cred_errs:
return False
raise
def get_all_spot_requests(self, spot_ids=[], filters=None):
spots = self.conn.get_all_spot_instance_requests(spot_ids,
filters=filters)
return spots
def list_all_spot_instances(self, show_closed=False):
s = self.conn.get_all_spot_instance_requests()
if not s:
log.info("No spot instance requests found...")
return
spots = []
for spot in s:
if spot.state in ['closed', 'cancelled'] and not show_closed:
continue
state = spot.state or 'N/A'
spot_id = spot.id or 'N/A'
spots.append(spot_id)
type = spot.type
instance_id = spot.instance_id or 'N/A'
create_time = spot.create_time or 'N/A'
launch_group = spot.launch_group or 'N/A'
zone_group = spot.availability_zone_group or 'N/A'
price = spot.price or 'N/A'
lspec = spot.launch_specification
instance_type = lspec.instance_type
image_id = lspec.image_id
zone = lspec.placement
groups = ', '.join([g.id for g in lspec.groups])
print "id: %s" % spot_id
print "price: $%0.2f" % price
print "spot_request_type: %s" % type
print "state: %s" % state
print "instance_id: %s" % instance_id
print "instance_type: %s" % instance_type
print "image_id: %s" % image_id
print "zone: %s" % zone
print "create_time: %s" % create_time
print "launch_group: %s" % launch_group
print "zone_group: %s" % zone_group
print "security_groups: %s" % groups
print
if not spots:
log.info("No spot instance requests found...")
else:
print 'Total: %s' % len(spots)
def show_instance(self, instance):
instance_id = instance.id or 'N/A'
groups = ', '.join([g.name for g in instance.groups])
dns_name = instance.dns_name or 'N/A'
private_dns_name = instance.private_dns_name or 'N/A'
state = instance.state or 'N/A'
private_ip = instance.private_ip_address or 'N/A'
public_ip = instance.ip_address or 'N/A'
zone = instance.placement or 'N/A'
ami = instance.image_id or 'N/A'
virt_type = instance.virtualization_type or 'N/A'
instance_type = instance.instance_type or 'N/A'
keypair = instance.key_name or 'N/A'
uptime = utils.get_elapsed_time(instance.launch_time) or 'N/A'
tags = ', '.join(['%s=%s' % (k, v) for k, v in
instance.tags.iteritems()]) or 'N/A'
if state == 'stopped':
uptime = 'N/A'
print "id: %s" % instance_id
print "dns_name: %s" % dns_name
print "private_dns_name: %s" % private_dns_name
if instance.reason:
print "state: %s (%s)" % (state, instance.reason)
else:
print "state: %s" % state
print "public_ip: %s" % public_ip
print "private_ip: %s" % private_ip
print "zone: %s" % zone
print "ami: %s" % ami
print "virtualization: %s" % virt_type
print "type: %s" % instance_type
print "groups: %s" % groups
print "keypair: %s" % keypair
print "uptime: %s" % uptime
print "tags: %s" % tags
print
def list_all_instances(self, show_terminated=False):
tstates = ['shutting-down', 'terminated']
insts = self.get_all_instances()
if not show_terminated:
insts = [i for i in insts if i.state not in tstates]
if not insts:
log.info("No instances found")
return
for instance in insts:
self.show_instance(instance)
print 'Total: %s' % len(insts)
def list_images(self, images, sort_key=None, reverse=False):
def get_key(obj):
return ' '.join([obj.region.name, obj.location])
if not sort_key:
sort_key = get_key
imgs_i386 = [img for img in images if img.architecture == "i386"]
imgs_i386.sort(key=sort_key, reverse=reverse)
imgs_x86_64 = [img for img in images if img.architecture == "x86_64"]
imgs_x86_64.sort(key=sort_key, reverse=reverse)
print
self.__list_images("32bit Images:", imgs_i386)
self.__list_images("\n64bit Images:", imgs_x86_64)
print "\ntotal images: %d" % len(images)
print
def list_registered_images(self):
images = self.registered_images
log.info("Your registered images:")
self.list_images(images)
def list_executable_images(self):
images = self.executable_images
log.info("Private images owned by other users that you can execute:")
self.list_images(images)
def __list_images(self, msg, imgs):
counter = 0
self.__print_header(msg)
for img in imgs:
name = self.get_image_name(img)
template = "[%d] %s %s %s"
if img.virtualization_type == 'hvm':
template += ' (HVM-EBS)'
elif img.root_device_type == 'ebs':
template += ' (EBS)'
print template % (counter, img.id, img.region.name, name)
counter += 1
def remove_image_files(self, image_name, pretend=True):
if pretend:
log.info("Pretending to remove image files...")
else:
log.info('Removing image files...')
files = self.get_image_files(image_name)
for f in files:
if pretend:
log.info("Would remove file: %s" % f.name)
else:
log.info('Removing file %s' % f.name)
f.delete()
if not pretend:
files = self.get_image_files(image_name)
if len(files) != 0:
log.warn('Not all files deleted, recursing...')
self.remove_image_files(image_name, pretend)
@print_timing("Removing image")
def remove_image(self, image_name, pretend=True, keep_image_data=True):
img = self.get_image(image_name)
if pretend:
log.info('Pretending to deregister AMI: %s' % img.id)
else:
log.info('Deregistering AMI: %s' % img.id)
img.deregister()
if img.root_device_type == "instance-store" and not keep_image_data:
self.remove_image_files(img, pretend=pretend)
elif img.root_device_type == "ebs" and not keep_image_data:
rootdevtype = img.block_device_mapping.get('/dev/sda1', None)
if rootdevtype:
snapid = rootdevtype.snapshot_id
if snapid:
snap = self.get_snapshot(snapid)
if pretend:
log.info("Would remove snapshot: %s" % snapid)
else:
log.info("Removing snapshot: %s" % snapid)
snap.delete()
def list_starcluster_public_images(self):
images = self.conn.get_all_images(owners=[static.STARCLUSTER_OWNER_ID])
log.info("Listing all public StarCluster images...")
imgs = [img for img in images if img.is_public]
def sc_public_sort(obj):
split = obj.name.split('-')
osname, osversion, arch = split[2:5]
osversion = float(osversion)
rc = 0
if split[-1].startswith('rc'):
rc = int(split[-1].replace('rc', ''))
return (osversion, rc)
self.list_images(imgs, sort_key=sc_public_sort, reverse=True)
def create_volume(self, size, zone, snapshot_id=None):
msg = "Creating %sGB volume in zone %s" % (size, zone)
if snapshot_id:
msg += " from snapshot %s" % snapshot_id
log.info(msg)
return self.conn.create_volume(size, zone, snapshot_id)
def remove_volume(self, volume_id):
vol = self.get_volume(volume_id)
vol.delete()
def list_keypairs(self):
keypairs = self.keypairs
if not keypairs:
log.info("No keypairs found...")
return
max_length = max([len(key.name) for key in keypairs])
templ = "%" + str(max_length) + "s %s"
for key in self.keypairs:
print templ % (key.name, key.fingerprint)
def list_zones(self, region=None):
conn = self.conn
if region:
regs = self.conn.get_all_regions()
regions = [r.name for r in regs]
if not region in regions:
raise exception.RegionDoesNotExist(region)
for reg in regs:
if reg.name == region:
region = reg
break
kwargs = {}
kwargs.update(self._kwargs)
kwargs.update(dict(region=region))
conn = self.connection_authenticator(
self.aws_access_key_id, self.aws_secret_access_key, **kwargs)
for zone in conn.get_all_zones():
print 'name: ', zone.name
print 'region: ', zone.region.name
print 'status: ', zone.state
print
def get_zones(self, filters=None):
return self.conn.get_all_zones(filters=filters)
def get_zone(self, zone):
"""
Return zone object representing an EC2 availability zone
Raises exception.ZoneDoesNotExist if not successful
"""
try:
return self.get_zones(filters={'zone-name': zone})[0]
except boto.exception.EC2ResponseError, e:
if e.error_code == "InvalidZone.NotFound":
raise exception.ZoneDoesNotExist(zone, self.region.name)
except IndexError:
raise exception.ZoneDoesNotExist(zone, self.region.name)
def get_zone_or_none(self, zone):
"""
Return zone object representing an EC2 availability zone
Returns None if unsuccessful
"""
try:
return self.get_zone(zone)
except exception.ZoneDoesNotExist:
pass
def create_s3_image(self, instance_id, key_location, aws_user_id,
ec2_cert, ec2_private_key, bucket, image_name="image",
description=None, kernel_id=None, ramdisk_id=None,
remove_image_files=False, **kwargs):
"""
Create instance-store (S3) image from running instance
"""
icreator = image.S3ImageCreator(self, instance_id, key_location,
aws_user_id, ec2_cert,
ec2_private_key, bucket,
image_name=image_name,
description=description,
kernel_id=kernel_id,
ramdisk_id=ramdisk_id,
remove_image_files=remove_image_files)
return icreator.create_image()
def create_ebs_image(self, instance_id, key_location, name,
description=None, snapshot_description=None,
kernel_id=None, ramdisk_id=None, root_vol_size=15,
**kwargs):
"""
Create EBS-backed image from running instance
"""
sdescription = snapshot_description
icreator = image.EBSImageCreator(self, instance_id, key_location,
name, description=description,
snapshot_description=sdescription,
kernel_id=kernel_id,
ramdisk_id=ramdisk_id,
**kwargs)
return icreator.create_image(size=root_vol_size)
def get_images(self, filters=None):
return self.conn.get_all_images(filters=filters)
def get_image(self, image_id):
"""
Return image object representing an AMI.
Raises exception.AMIDoesNotExist if unsuccessful
"""
try:
return self.get_images(filters={'image-id': image_id})[0]
except boto.exception.EC2ResponseError, e:
if e.error_code == "InvalidAMIID.NotFound":
raise exception.AMIDoesNotExist(image_id)
raise
except IndexError:
raise exception.AMIDoesNotExist(image_id)
def get_image_or_none(self, image_id):
"""
Return image object representing an AMI.
Returns None if unsuccessful
"""
try:
return self.get_image(image_id)
except exception.AMIDoesNotExist:
pass
def get_image_files(self, image):
"""
Returns a list of files on S3 for an EC2 instance-store (S3-backed)
image. This includes the image's manifest and part files.
"""
if not hasattr(image, 'id'):
image = self.get_image(image)
if image.root_device_type == 'ebs':
raise exception.AWSError(
"Image %s is an EBS image. No image files on S3." % image.id)
bucket = self.get_image_bucket(image)
bname = re.escape(bucket.name)
prefix = re.sub('^%s\/' % bname, '', image.location)
prefix = re.sub('\.manifest\.xml$', '', prefix)