This repository has been archived by the owner on Aug 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 44
/
ec2ops.py
4643 lines (4279 loc) · 217 KB
/
ec2ops.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
# Software License Agreement (BSD License)
#
# Copyright (c) 2009-2014, Eucalyptus Systems, Inc.
# All rights reserved.
#
# Redistribution and use of this software in source and binary forms, with or
# without modification, are permitted provided that the following conditions
# are met:
#
# Redistributions of source code must retain the above
# copyright notice, this list of conditions and the
# following disclaimer.
#
# Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the
# following disclaimer in the documentation and/or other
# materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
#
# Author: vic.iglesias@eucalyptus.com
import time
import re
import os
import copy
import socket
import types
import hmac
import json
import hashlib
import base64
import time
import types
import sys
import traceback
from datetime import datetime, timedelta
from subprocess import Popen, PIPE
from boto.ec2.group import Group
from boto.ec2.image import Image
from boto.ec2.instance import Reservation, Instance
from boto.ec2.keypair import KeyPair
from boto.ec2.blockdevicemapping import BlockDeviceMapping, BlockDeviceType
from boto.ec2.securitygroup import SecurityGroup
from boto.ec2.volume import Volume
from boto.ec2.bundleinstance import BundleInstanceTask
from boto.exception import EC2ResponseError
from boto.ec2.regioninfo import RegionInfo
from boto.resultset import ResultSet
from boto.ec2.securitygroup import SecurityGroup, IPPermissions
import boto
from eutester import Eutester
import eutester
from eutester.euinstance import EuInstance
from eutester.windows_instance import WinInstance
from eutester.euvolume import EuVolume
from eutester.eusnapshot import EuSnapshot
from eutester.euzone import EuZone
from testcases.cloud_user.images.conversiontask import ConversionTask
EC2RegionData = {
'us-east-1' : 'ec2.us-east-1.amazonaws.com',
'us-west-1' : 'ec2.us-west-1.amazonaws.com',
'eu-west-1' : 'ec2.eu-west-1.amazonaws.com',
'ap-northeast-1' : 'ec2.ap-northeast-1.amazonaws.com',
'ap-southeast-1' : 'ec2.ap-southeast-1.amazonaws.com'}
class EC2ops(Eutester):
enable_root_user_data = """#cloud-config
disable_root: false"""
@Eutester.printinfo
def __init__(self,
host=None,
credpath=None,
endpoint=None,
aws_access_key_id=None,
aws_secret_access_key = None,
username="root",
region=None,
is_secure=False,
path='/',
port=80,
boto_debug=0,
APIVersion = '2012-07-20'):
"""
:param host:
:param credpath:
:param endpoint:
:param aws_access_key_id:
:param aws_secret_access_key:
:param username:
:param region:
:param is_secure:
:param path:
:param port:
:param boto_debug:
:param APIVersion:
"""
self.aws_access_key_id = aws_access_key_id
self.aws_secret_access_key = aws_secret_access_key
self.user_id = None
self.account_id = None
self.poll_count = 48
self.username = username
self.test_resources = {}
self.setup_ec2_resource_trackers()
self.key_dir = "./"
self.ec2_source_ip = None #Source ip on local test machine used to reach instances
super(EC2ops, self).__init__(credpath=credpath)
self.setup_ec2_connection(host= host,
region=region,
endpoint=endpoint,
aws_access_key_id=self.aws_access_key_id ,
aws_secret_access_key=self.aws_secret_access_key,
is_secure=is_secure,
path=path,
port=port,
boto_debug=boto_debug,
APIVersion=APIVersion)
@Eutester.printinfo
def setup_ec2_connection(self, endpoint=None, aws_access_key_id=None, aws_secret_access_key=None, is_secure=True,host=None ,
region=None, path = "/", port = 443, APIVersion ='2012-07-20', boto_debug=0):
ec2_region = RegionInfo()
if region:
self.debug("Check region: " + str(region))
try:
if not endpoint:
ec2_region.endpoint = EC2RegionData[region]
else:
ec2_region.endpoint = endpoint
except KeyError:
raise Exception( 'Unknown region: %s' % region)
else:
ec2_region.name = 'eucalyptus'
if not host:
if endpoint:
ec2_region.endpoint = endpoint
else:
ec2_region.endpoint = self.get_ec2_ip()
connection_args = { 'aws_access_key_id' : aws_access_key_id,
'aws_secret_access_key': aws_secret_access_key,
'is_secure': is_secure,
'debug':boto_debug,
'port' : port,
'path' : path,
'host' : host}
if re.search('2.6', boto.__version__):
connection_args['validate_certs'] = False
try:
ec2_connection_args = copy.copy(connection_args)
ec2_connection_args['path'] = path
ec2_connection_args['api_version'] = APIVersion
ec2_connection_args['region'] = ec2_region
self.debug("Attempting to create ec2 connection to " + ec2_region.endpoint + ':' + str(port) + path)
self.ec2 = boto.connect_ec2(**ec2_connection_args)
except Exception, e:
self.critical("Was unable to create ec2 connection because of exception: " + str(e))
#Source ip on local test machine used to reach instances
self.ec2_source_ip = None
def setup_ec2_resource_trackers(self):
"""
Setup keys in the test_resources hash in order to track artifacts created
"""
self.test_resources["reservations"] = []
self.test_resources["volumes"] = []
self.test_resources["snapshots"] = []
self.test_resources["keypairs"] = []
self.test_resources["security-groups"] = []
self.test_resources["images"] = []
self.test_resources["addresses"]=[]
self.test_resources["auto-scaling-groups"]=[]
self.test_resources["launch-configurations"]=[]
self.test_resources["conversion-tasks"]=[]
def get_ec2_ip(self):
"""Parse the eucarc for the EC2_URL"""
ec2_url = self.parse_eucarc("EC2_URL")
return ec2_url.split("/")[2].split(":")[0]
def get_ec2_path(self):
"""Parse the eucarc for the EC2_URL"""
ec2_url = self.parse_eucarc("EC2_URL")
ec2_path = "/".join(ec2_url.split("/")[3:])
return ec2_path
def create_tags(self, resource_ids, tags):
"""
Add tags to the given resource
:param resource_ids: List of resources IDs to tag
:param tags: Dict of key value pairs to add, for just a name include a key with a '' value
"""
self.debug("Adding the following tags:" + str(tags))
self.debug("To Resources: " + str(resource_ids))
self.ec2.create_tags(resource_ids=resource_ids, tags=tags)
def delete_tags(self, resource_ids, tags):
"""
Add tags to the given resource
:param resource_ids: List of resources IDs to tag
:param tags: Dict of key value pairs to add, for just a name include a key with a '' value
"""
self.debug("Deleting the following tags:" + str(tags))
self.debug("From Resources: " + str(resource_ids))
self.ec2.delete_tags(resource_ids=resource_ids, tags=tags)
def add_keypair(self, key_name=None):
"""
Add a keypair with name key_name unless it already exists
:param key_name: The name of the keypair to add and download.
"""
if key_name is None:
key_name = "keypair-" + str(int(time.time()))
self.debug("Looking up keypair " + key_name)
key = []
try:
key = self.ec2.get_all_key_pairs(keynames=[key_name])
except EC2ResponseError:
pass
if not key:
self.debug( 'Creating keypair: %s' % key_name)
# Create an SSH key to use when logging into instances.
key = self.ec2.create_key_pair(key_name)
# AWS will store the public key but the private key is
# generated and returned and needs to be stored locally.
# The save method will also chmod the file to protect
# your private key.
key.save(self.key_dir)
#Add the fingerprint header to file
keyfile = open(self.key_dir+key.name+'.pem','r')
data = keyfile.read()
keyfile.close()
keyfile = open(self.key_dir+key.name+'.pem','w')
keyfile.write('KEYPAIR '+str(key.name)+' '+str(key.fingerprint)+"\n")
keyfile.write(data)
keyfile.close()
self.test_resources["keypairs"].append(key)
return key
else:
self.debug( "Key " + key_name + " already exists")
def verify_local_keypath(self,keyname, path=None, exten=".pem"):
"""
Convenience function to verify if a given ssh key 'keyname' exists on the local server at 'path'
:returns: the keypath if the key is found.
>>> instance= self.get_instances(state='running')[0]
>>> keypath = self.get_local_keypath(instance.key_name)
"""
if path is None:
path = os.getcwd()
keypath = path + "/" + keyname + exten
try:
os.stat(keypath)
self.debug("Found key at path:"+str(keypath))
except:
raise Exception("key not found at the provided path:"+str(keypath))
return keypath
@Eutester.printinfo
def get_all_current_local_keys(self,path=None, exten=".pem"):
"""
Convenience function to provide a list of all keys in the local dir at 'path' that exist on the server to help
avoid producing additional keys in test dev.
:param path: Filesystem path to search in
:param exten: extension of private key file
:return: list of key names
"""
keylist = []
keys = self.ec2.get_all_key_pairs()
keyfile = None
for k in keys:
self.debug('Checking local path:'+str(path)+" for keyfile: "+str(k.name)+str(exten))
try:
#will raise exception if keypath is not found
keypath = self.verify_local_keypath(k.name, path, exten)
if not keypath:
continue
keyfile = open(keypath,'r')
for line in keyfile.readlines():
if re.search('KEYPAIR',line):
fingerprint = line.split()[2]
break
keyfile.close()
if fingerprint == k.fingerprint:
self.debug('Found file with matching finger print for key:'+k.name)
keylist.append(k)
except:
self.debug('Did not find local match for key:'+str(k.name))
finally:
if keyfile and not keyfile.closed:
keyfile.close()
return keylist
def delete_keypair(self,keypair):
"""
Delete the keypair object passed in and check that it no longer shows up
:param keypair: Keypair object to delete and check
:return: boolean of whether the operation succeeded
"""
name = keypair.name
self.debug( "Sending delete for keypair: " + name)
keypair.delete()
try:
keypair = self.ec2.get_all_key_pairs(keynames=[name])
except EC2ResponseError:
keypair = []
if len(keypair) > 0:
self.fail("Keypair found after attempt to delete it")
return False
return True
@Eutester.printinfo
def get_windows_instance_password(self,
instance,
private_key_path=None,
key=None,
dir=None,
exten=".pem",
encoded=True):
"""
Get password for a windows instance.
:param instance: euinstance object
:param private_key_path: private key file used to decrypt password
:param key: name of private key
:param dir: Path to private key
:param exten: extension of private key
:param encoded: boolean of whether string returned from server is Base64 encoded
:return: decrypted password
:raise: Exception when private key cannot be found on filesystem
"""
self.debug("get_windows_instance_password, instance:"+str(instance.id)+", keypath:"+str(private_key_path)+
", dir:"+str(dir)+", exten:"+str(exten)+", encoded:"+str(encoded))
key = key or self.get_keypair(instance.key_name)
if private_key_path is None and key is not None:
private_key_path = str(self.verify_local_keypath( key.name , dir, exten))
if not private_key_path:
raise Exception('get_windows_instance_password, keypath not found?')
encrypted_string = self.ec2.get_password_data(instance.id)
if encoded:
string_to_decrypt = base64.b64decode(encrypted_string)
else:
string_to_decrypt = encrypted_string
popen = Popen(['openssl', 'rsautl', '-decrypt', '-inkey',
private_key_path, '-pkcs'], stdin=PIPE, stdout=PIPE)
(stdout, _) = popen.communicate(string_to_decrypt)
return stdout
@Eutester.printinfo
def add_group(self, group_name=None, description=None, fail_if_exists=False ):
"""
Add a security group to the system with name group_name, if it exists dont create it
:param group_name: Name of the security group to create
:param fail_if_exists: IF set, will fail if group already exists, otherwise will return the existing group
:return: boto group object upon success or None for failure
"""
if group_name is None:
group_name = "group-" + str(int(time.time()))
if self.check_group(group_name):
if fail_if_exists:
self.fail( "Group " + group_name + " already exists")
else:
self.debug( "Group " + group_name + " already exists")
group = self.ec2.get_all_security_groups(group_name)[0]
return self.get_security_group(name=group_name)
else:
self.debug( 'Creating Security Group: %s' % group_name)
# Create a security group to control access to instance via SSH.
if not description:
description = group_name
group = self.ec2.create_security_group(group_name, description)
self.test_resources["security-groups"].append(group)
return self.get_security_group(name=group_name)
def delete_group(self, group):
"""
Delete the security group object passed in and check that it no longer shows up
:param group: Group object to delete and check
:return: bool whether operation succeeded
"""
name = group.name
self.debug( "Sending delete for security group: " + name )
group.delete()
if self.check_group(name):
self.fail("Group still found after attempt to delete it")
return False
return True
def check_group(self, group_name):
"""
Check if a group with group_name exists in the system
:param group_name: Group name to check for existence
:return: bool whether operation succeeded
"""
self.debug( "Looking up group " + group_name )
try:
group = self.ec2.get_all_security_groups(groupnames=[group_name])
except EC2ResponseError:
return False
if not group:
return False
else:
return True
@Eutester.printinfo
def authorize_group_by_name(self,
group_name="default",
port=22,
end_port=None,
protocol="tcp",
cidr_ip="0.0.0.0/0",
src_security_group=None,
src_security_group_name=None,
src_security_group_owner_id=None,
force_args=False):
"""
Authorize the group with group_name
:param group_name: Name of the group to authorize, default="default"
:param port: Port to open, default=22
:param end_port: End of port range to open, defaults to 'port' arg.
:param protocol: Protocol to authorize, default=tcp
:param cidr_ip: CIDR subnet to authorize, default="0.0.0.0/0" everything
:param src_security_group_name: Grant access to 'group' from src_security_group_name, default=None
:return:
"""
if not force_args:
if src_security_group or src_security_group_name:
cidr_ip=None
port=None
protocol=None
if src_security_group:
src_security_group_owner_id= src_security_group_owner_id or src_security_group.owner_id
src_security_group_name = src_security_group_name or src_security_group.name
if src_security_group_name and not src_security_group_owner_id:
group = self.get_security_group(name=src_security_group_name)
src_security_group_owner_id = group.owner_id
if end_port is None:
end_port = port
old_api_version = self.ec2.APIVersion
try:
#self.ec2.APIVersion = "2009-10-31"
if src_security_group_name:
self.debug( "Attempting authorization of: {0}, from group:{1},"
" on port range: {2} to {3}, proto:{4}"
.format(group_name, src_security_group, port,
end_port, protocol))
else:
self.debug( "Attempting authorization of:{0}, on port "
"range: {1} to {2}, proto:{3} from {4}"
.format(group_name, port, end_port,
protocol, cidr_ip))
self.ec2.authorize_security_group_deprecated(group_name,
ip_protocol=protocol,
from_port=port,
to_port=end_port,
cidr_ip=cidr_ip,
src_security_group_name=src_security_group_name,
src_security_group_owner_id=src_security_group_owner_id,
)
return True
except self.ec2.ResponseError, e:
if e.code == 'InvalidPermission.Duplicate':
self.debug( 'Security Group: %s already authorized' % group_name )
else:
raise
finally:
self.ec2.APIVersion = old_api_version
def authorize_group(self,
group,
port=22,
end_port=None,
protocol="tcp",
cidr_ip="0.0.0.0/0",
src_security_group=None,
src_security_group_name=None,
src_security_group_owner_id=None,
force_args=False):
"""
Authorize the boto.group object
:param group: boto.group object
:param port: Port to open, default=22
:param end_port: End of port range to open, defaults to 'port' arg.
:param protocol: Protocol to authorize, default=tcp
:param cidr_ip: CIDR subnet to authorize, default="0.0.0.0/0" everything
:param src_security_group_name: Grant access to 'group' from src_security_group_name, default=None
:param force_args: boolean to send arguments w/o the test method sanitizing them
:return: True on success
:raise: Exception if operation fails
"""
return self.authorize_group_by_name(group.name,
port=port,
end_port=end_port,
protocol=protocol,
cidr_ip=cidr_ip,
src_security_group=src_security_group,
src_security_group_name=src_security_group_name,
src_security_group_owner_id=src_security_group_owner_id,
force_args=force_args)
def revoke_all_rules(self, group):
if not isinstance(group, SecurityGroup):
group = self.get_security_group(name=group)
else:
# group obj does not have update() yet...
group = self.get_security_group(id=group.id)
if not group:
raise ValueError('Security group "{0}" not found'.format(group))
self.show_security_group(group)
assert isinstance(group, SecurityGroup)
rules = copy.copy(group.rules)
for r in rules:
self.debug('Attempting to revoke rule:{0}, grants:{1}'
.format(r, r.grants))
assert isinstance(r, IPPermissions)
for grant in r.grants:
if grant.cidr_ip:
self.debug('{0}.revoke(ip_protocol:{1}, from_port:{2}, '
'to_port{3}, cidr_ip:{4})'.format(group.name,
r.ip_protocol,
r.from_port,
r.to_port,
grant))
group.revoke(ip_protocol=r.ip_protocol, from_port=r.from_port,
to_port=r.to_port, cidr_ip=grant.cidr_ip)
if grant.name or grant.group_id:
group.revoke(ip_protocol=r.ip_protocol,
from_port=r.from_port,
to_port=r.to_port,
src_group=grant,
cidr_ip=None )
self.debug('{0}.revoke(ip_protocol:{1}, from_port:{2}, '
'to_port:{3}, src_group:{4})'.format(group.name,
r.ip_protocol,
r.from_port,
r.to_port,
grant))
group = self.get_security_group(id=group.id)
self.debug('AFTER removing all rules...')
self.show_security_group(group)
return group
def show_security_group(self, group):
try:
from prettytable import PrettyTable, ALL
except ImportError as IE:
self.debug('No pretty table import failed:' + str(IE))
return
group = self.get_security_group(id=group.id)
if not group:
raise ValueError('Show sec group failed. Could not fetch group:'
+ str(group))
header = PrettyTable(["Security Group:" + group.name + "/" + group.id])
table = PrettyTable(["CIDR_IP", "SRC_GRP_NAME",
"SRC_GRP_ID", "OWNER_ID", "PORT",
"END_PORT", "PROTO"])
table.align["CIDR_IP"] = 'l'
table.padding_width = 1
for rule in group.rules:
port = rule.from_port
end_port = rule.to_port
proto = rule.ip_protocol
for grant in rule.grants:
table.add_row([grant.cidr_ip, grant.name,
grant.group_id, grant.owner_id, port,
end_port, proto])
table.hrules = ALL
header.add_row([str(table)])
self.debug("\n{0}".format(str(header)))
def revoke(self, group,
port=22,
protocol="tcp",
cidr_ip="0.0.0.0/0",
src_security_group_name=None,
src_security_group_owner_id=None):
if isinstance(group, SecurityGroup):
group_name = group.name
else:
group_name = group
if src_security_group_name:
self.debug( "Attempting revoke of " + group_name + " from " + str(src_security_group_name) +
" on port " + str(port) + " " + str(protocol) )
else:
self.debug( "Attempting revoke of " + group_name + " on port " + str(port) + " " + str(protocol) )
self.ec2.revoke_security_group(group_name,
ip_protocol=protocol,
from_port=port,
to_port=port,
cidr_ip=cidr_ip,
src_security_group_name=src_security_group_name,
src_security_group_owner_id=src_security_group_owner_id)
def terminate_single_instance(self, instance, timeout=300 ):
"""
Terminate an instance
:param instance: boto.instance object to terminate
:param timeout: Time in seconds to wait for terminated state
:return: True on success
"""
instance.terminate()
return self.wait_for_instance(instance, state='terminated', timeout=timeout)
def wait_for_instance(self,instance, state="running", poll_count = None, timeout=480):
"""
Wait for the instance to enter the state
:param instance: Boto instance object to check the state on
:param state: state that we are looking for
:param poll_count: Number of 10 second poll intervals to wait before failure (for legacy test script support)
:param timeout: Time in seconds to wait before failure
:return: True on success
:raise: Exception when instance does not enter proper state
"""
if poll_count is not None:
timeout = poll_count*10
self.debug( "Beginning poll loop for instance " + str(instance) + " to go to " + str(state) )
instance.update()
instance_original_state = instance.state
start = time.time()
elapsed = 0
### If the instance changes state or goes to the desired state before my poll count is complete
while( elapsed < timeout ) and (instance.state != state) and (instance.state != 'terminated'):
#poll_count -= 1
self.debug( "Instance("+instance.id+") State("+instance.state+"), elapsed:"+str(elapsed)+"/"+str(timeout))
time.sleep(10)
instance.update()
elapsed = int(time.time()- start)
if instance.state != instance_original_state:
break
self.debug("Instance("+instance.id+") State("+instance.state+") time elapsed (" +str(elapsed).split('.')[0]+")")
#self.debug( "Waited a total o" + str( (self.poll_count - poll_count) * 10 ) + " seconds" )
if instance.state != state:
raise Exception( str(instance) + " did not enter "+str(state)+" state after elapsed:"+str(elapsed))
self.debug( str(instance) + ' is now in ' + instance.state )
return True
def wait_for_reservation(self,reservation, state="running",timeout=480):
"""
Wait for an entire reservation to enter the state
:param reservation: Boto reservation object to check the state on
:param state: state that we are looking for
:param timeout: How long in seconds to wait for state
:return: True on success
"""
aggregate_result = True
instance_list = reservation
if isinstance(reservation, Reservation):
instance_list = reservation.instances
self.debug( "Beginning poll loop for the " + str(len(instance_list)) + " instance found in " + str(instance_list) )
for instance in instance_list:
if not self.wait_for_instance(instance, state, timeout=timeout):
aggregate_result = False
return aggregate_result
@Eutester.printinfo
def create_volume(self, zone, size=1, eof=True, snapshot=None, timeout=0, poll_interval=10,timepergig=120):
"""
Create a new EBS volume then wait for it to go to available state, size or snapshot is mandatory
:param zone: Availability zone to create the volume in
:param size: Size of the volume to be created
:param count: Number of volumes to be created
:param eof: Boolean, indicates whether to end on first instance of failure
:param snapshot: Snapshot to create the volume from
:param timeout: Time to wait before failing. timeout of 0 results in size of volume * timepergig seconds
:param poll_interval: How often in seconds to poll volume state
:param timepergig: Time to wait per gigabyte size of volume, used when timeout is set to 0
:return:
"""
return self.create_volumes(zone, size=size, count=1, mincount=1, eof=eof, snapshot=snapshot, timeout=timeout, poll_interval=poll_interval,timepergig=timepergig)[0]
@Eutester.printinfo
def create_volumes(self,
zone,
size = 1,
count = 1,
mincount = None,
eof = True,
monitor_to_state = 'available',
delay = 0,
snapshot = None,
timeout=0,
poll_interval = 10,
timepergig = 120 ):
"""
Definition:
Create a multiple new EBS volumes then wait for them to go to available state,
size or snapshot is mandatory
:param zone: Availability zone to create the volume in
:param size: Size of the volume to be created
:param count: Number of volumes to be created
:param mincount: Minimum number of volumes to be created to be considered a success.Default = 'count'
:param eof: Boolean, indicates whether to end on first instance of failure
:param monitor_to_state: String, if not 'None' will monitor created volumes to the provided state
:param snapshot: Snapshot to create the volume from
:param timeout: Time to wait before failing. timeout of 0 results in size of volume * timepergig seconds
:param poll_interval: How often in seconds to poll volume state
:param timepergig: Time to wait per gigabyte size of volume, used when timeout is set to 0
:return: list of volumes
"""
start = time.time()
elapsed = 0
volumes = []
mincount = mincount or count
if mincount > count:
raise Exception('Mincount can not be greater than count')
#if timeout is set to 0, use size to create a reasonable timeout for this volume creation
if timeout == 0:
if snapshot is not None:
timeout = timepergig * int(snapshot.volume_size)
else:
timeout = timepergig * size
if snapshot and not hasattr(snapshot,'eutest_volumes'):
snapshot = self.get_snapshot(snapshot.id)
self.debug( "Sending create volume request, count:"+str(count) )
for x in xrange(0,count):
vol = None
try:
cmdstart = time.time()
vol = self.ec2.create_volume(size, zone, snapshot)
cmdtime = time.time() - cmdstart
if vol:
vol = EuVolume.make_euvol_from_vol(vol, tester=self, cmdstart=cmdstart)
vol.eutest_cmdstart = cmdstart
vol.eutest_createorder = x
vol.eutest_cmdtime = "{0:.2f}".format(cmdtime)
vol.size = size
volumes.append(vol)
except Exception, e:
if eof:
#Clean up any volumes from this operation and raise exception
for vol in volumes:
vol.delete()
raise e
else:
self.debug("Caught exception creating volume,eof is False, continuing. Error:"+str(e))
if delay:
time.sleep(delay)
if len(volumes) < mincount:
#Clean up any volumes from this operation and raise exception
for vol in volumes:
vol.delete()
raise Exception("Created "+str(len(volumes))+"/"+str(count)+
' volumes. Less than minimum specified:'+str(mincount))
self.debug( str(len(volumes))+"/"+str(count)+" requests for volume creation succeeded." )
if volumes:
self.print_euvolume_list(volumes)
if not monitor_to_state:
self.test_resources["volumes"].extend(volumes)
if snapshot:
snapshot.eutest_volumes.extend(volumes)
return volumes
#If we begain the creation of the min volumes, monitor till completion, otherwise cleanup and fail out
retlist = self.monitor_created_euvolumes_to_state(volumes,
eof=eof,
mincount=mincount,
state=monitor_to_state,
poll_interval=poll_interval,
timepergig=timepergig)
self.test_resources["volumes"].extend(retlist)
if snapshot:
snapshot.eutest_volumes.extend(retlist)
return retlist
@Eutester.printinfo
def monitor_created_euvolumes_to_state(self,
volumes,
eof=True,
mincount=None,
state='available',
poll_interval=10,
deletefailed=True,
size=1,
timepergig=120):
"""
Description:
Monitors a list of created volumes until 'state' or failure. Allows for a variety of volumes, using
different types and creation methods to be monitored by a central method.
:param volumes: list of created volumes
:param eof: boolean, if True will end on first failure
:param mincount: minimum number of successful volumes, else fail
:param state: string indicating the expected state to monitor to
:param deletefailed: delete all failed volumes, in eof case deletes 'volumes' list.
In non-eof, if mincount is met, will delete any failed volumes.
:param timepergig: integer, time allowed per gig before failing.
:param poll_interval: int seconds to wait between polling for status
:param size: int size in gigs to request for volume creation
"""
retlist = []
failed = []
elapsed = 0
if not volumes:
raise Exception("Volumes list empty in monitor_created_volumes_to_state")
count = len(volumes)
mincount = mincount or count
self.debug("Monitoring "+str(count)+" volumes for at least "+str(mincount)+" to reach state:"+str(state))
origlist = copy.copy(volumes)
self.debug("Monitoring "+str(count)+" volumes for at least "+str(mincount)+" to reach state:"+str(state))
for volume in volumes:
if not isinstance(volume, EuVolume):
raise Exception("object not of type EuVolume. Found type:"+str(type(volume)))
#volume = EuVolume()
# Wait for the volume to be created.
self.debug( "Polling "+str(len(volumes))+" volumes for status:\""+str(state)+"\"...")
start = time.time()
while volumes:
for volume in volumes:
volume.update()
voltimeout = timepergig * (volume.size or size)
elapsed = time.time()-start
self.debug("Volume #"+str(volume.eutest_createorder)+" ("+volume.id+") State("+volume.status+
"), seconds elapsed: " + str(int(elapsed))+'/'+str(voltimeout))
if volume.status == state:
#add to return list and remove from volumes list
retlist.append(volumes.pop(volumes.index(volume)))
else:
if elapsed > voltimeout:
volume.status = 'timed-out'
if volume.status == 'failed' or volume.status == 'timed-out':
if eof:
#Clean up any volumes from this operation and raise exception
self.debug(str(volume.id) + " - Failed current status:" + str(volume.status))
if deletefailed:
self.debug('Failure caught in monitor volumes, attempting to delete all volumes...')
for vol in origlist:
try:
self.delete_volume(vol)
except Exception, e:
self.debug('Could not delete volume:'+str(vol.id)+", err:"+str(e))
raise Exception(str(volume) + ", failed to reach state:"+str(state)+", vol status:"+
str(volume.eutest_laststatus)+", test status:"+str(vol.status))
else:
#End on failure is not set, so record this failure and move on
msg = str(volume) + " went to: " + volume.status
self.debug(msg)
volume.eutest_failmsg = msg
failed.append(volumes.pop(volumes.index(volume)))
#Fail fast if we know we've exceeded our mincount already
if (count - len(failed)) < mincount:
if deletefailed:
buf = ""
for failedvol in failed:
retlist.remove(failedvol)
buf += str(failedvol.id)+"-state:"+str(failedvol.status) + ","
self.debug(buf)
for vol in origlist:
self.debug('Failure caught in monitor volumes, attempting to delete all volumes...')
try:
self.delete_volume(vol)
except Exception, e:
self.debug('Could not delete volume:'+str(vol.id)+", err:"+str(e))
raise Exception("Mincount of volumes did not enter state:"+str(state)+" due to faults")
self.debug("----Time Elapsed:"+str(int(elapsed))+", Waiting on "+str(len(volumes))+
" volumes to enter state:"+str(state)+"-----")
if volumes:
time.sleep(poll_interval)
else:
break
#We have at least mincount of volumes, delete any failed volumes
if failed and deletefailed:
self.debug( "Deleting volumes that never became available...")
for volume in failed:
self.debug('Failure caught in monitor volumes, attempting to delete all volumes...')
try:
self.delete_volume(volume)
except Exception, e:
self.debug('Could not delete volume:'+str(volume.id)+", err:"+str(e))
buf = str(len(failed))+'/'+str(count)+ " Failed volumes after " +str(elapsed)+" seconds:"
for failedvol in failed:
retlist.remove(failedvol)
buf += str(failedvol.id)+"-state:"+str(failedvol.status)+","
self.debug(buf)
self.print_euvolume_list(origlist)
return retlist
@Eutester.printinfo
def monitor_euvolumes_to_status(self,
euvolumes,
status = None,
attached_status = None,
poll_interval=10,
timeout=180,
eof=True,
validate_args=True):
"""
(See: monitor_created_euvolumes_to_state() if monitoring newly created volumes, otherwise this method is
intended for monitoring attached and in-use states of volume(s). )
Definition: monitors a list of euvolumes to a given state.
Some example valid states:
status = available, attached_status = None
status = in-use, attached_status = attached, attaching, detaching
:param euvolumes: list of euvolumes to monitor
:param status: state of volume expected: ie 'in-use', 'available', 'deleted'
:param attached_status: state of volume's attached data. ie 'attached', 'attaching', 'detaching', 'none'
:param poll_interval: integer seconds between polling for status updates
:param timeout: time to wait before failing
:param eof: exit on first failure encountered, otherwise wait until other volumes pass/fail. Default=True
:param validate_args: boolean, Will check args for a valid status/available_status pair.
If False will monitor to a non-valid state for testing purposes
"""
good = []
failed = []
monitor = []
failmsg = ""
self.debug('Monitor_euvolumes_to_state:'+str(status)+"/"+str(attached_status))
if attached_status and not status:
status = 'in-use'
#check for valid states in given arguments...
if validate_args:
if (status != 'available') and (status != 'in-use') and (status != 'deleted') and (status != 'failed'):
raise Exception('Invalid volume states in monitor request:'+str(status)+" != in-use or available")
if attached_status is None:
if status != 'available':
raise Exception('Invalid volume states in monitor request:'+str(status)+"/"+str(attached_status))
else:
if (attached_status == 'attached') or (attached_status == 'attaching') or \
(attached_status == 'detaching') or (attached_status == 'detaching'):
if status != 'in-use':
raise Exception('Invalid volume states in monitor request:'+str(status)+"/"+str(attached_status))
else:
raise Exception('Invalid volume states in monitor request:'+str(status)+"/"+str(attached_status)+
" != attached, attaching, detaching")
start = time.time()
elapsed = 0
self.debug('Updating volume list before monitoring...')
for vol in euvolumes:
try:
vol = self.get_volume(vol.id)
if not isinstance(vol, EuVolume):
vol = EuVolume.make_euvol_from_vol(vol,self)
monitor.append(vol)
except:
self.debug(self.get_traceback())
self.print_euvolume_list(monitor)