Skip to content

Commit 6ce5e44

Browse files
committed
Major Refactoring
1 parent a75060b commit 6ce5e44

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

aws.py

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
import random
2+
import boto3
3+
from base import ProxyRotator
4+
5+
class AWSCommand(object):
6+
'''Class encapsulating the aws ec2 API'''
7+
8+
def __init__(self, config=None):
9+
self.ec2 = boto3.resource('ec2')
10+
self.config = config
11+
12+
def create_ec2(self, **params):
13+
return self.ec2.create_instances(MaxCount=1, MinCount=1, **params)[0]
14+
15+
def get_proxies(self):
16+
proxies = []
17+
filters=[
18+
{'Name':'image-id', 'Values':[self.config.aws_image_id]},
19+
{'Name': 'instance-state-name', 'Values': ['running']}
20+
]
21+
for instance in self.ec2.instances.filter(Filters=filters):
22+
proxies.append(','.join([instance.public_ip_address, '0', instance.id,'0','0']))
23+
return proxies
24+
25+
def delete_ec2(self, instance_id):
26+
instance = self.ec2.Instance(instance_id)
27+
instance.terminate()
28+
instance.wait_until_terminated()
29+
30+
31+
class AwsProxyRotator(ProxyRotator):
32+
""" AWS implementation of ProxyRotator """
33+
34+
def __init__(self, cfg='proxy.conf', test_mode=False, rotate=False, region=None):
35+
super(AwsProxyRotator, self).__init__(cfg, test_mode, rotate, region)
36+
#AWS resource manager
37+
self.aws_command = AWSCommand(config=self.config)
38+
self.vps_command = self.aws_command
39+
40+
def delete_instance(self, instance_id):
41+
""" Delete instance by id """
42+
return self.aws_command.delete_ec2(instance_id)
43+
44+
def make_new_instance(self, region=None, test=False, verbose=False):
45+
# If calling as test, make up an ip
46+
if test:
47+
return '.'.join(map(lambda x: str(random.randrange(20, 100)), range(4))), random.randrange(10000,
48+
50000)
49+
params = dict(ImageId=self.config.aws_image_id,
50+
InstanceType=self.config.aws_instance_type,
51+
KeyName=self.config.aws_key_name,
52+
SecurityGroupIds=self.config.aws_security_groups,
53+
SubnetId=self.config.aws_subnet_id ,
54+
DryRun=True)
55+
56+
print 'Making new ec2...'
57+
ec2_instance = self.aws_command.create_ec2(**params)
58+
ec2_instance.wait_until_running()
59+
time.sleep(10)
60+
61+
ip = ec2_instance.public_ip_address
62+
pid = ec2_instance.id
63+
64+
# Post process the host
65+
print 'Post-processing',ip,'...'
66+
self.post_process(ip)
67+
68+
return ip, pid
69+
70+
def drop(self):
71+
""" Drop all instances in current configuration (except the LB) """
72+
73+
print 'Dropping all proxies ...'
74+
proxies = self.aws_command.get_proxies()
75+
76+
for item in proxies:
77+
ip,_,instance_id = item.split(',')
78+
print '\tDropping ec2',instance_id,'with IP',ip,'...'
79+
self.aws_command.delete_ec2(instance_id)
80+

0 commit comments

Comments
 (0)