- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathnode.py
More file actions
Latest commit
231 lines (190 loc) · 7.51 KB
/
Copy pathnode.py
File metadata and controls
231 lines (190 loc) · 7.51 KB
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
importtime
fromboto.ec2.connectionimportEC2Connection
fromboto.ec2.blockdevicemappingimportBlockDeviceType
fromboto.ec2.blockdevicemappingimportBlockDeviceMapping
fromfabric.apiimportsettings, sudo
fromparse_clientimportParseClient
fromjobimportJob
classNode(object):
""" Object representing an EC2 node """
# list of job names
jobs= []
def__init__(self, **kwargs):
""" new Node """
self.name=kwargs['name']
self.key_name=kwargs.get('key_name')
self.zone=kwargs.get('zone')
self.instance_type=kwargs.get('instance_type')
self.user=kwargs.get('user')
self.ami=kwargs.get('ami')
self.security_group=kwargs.get('security_group')
# optional
self.instance_id=kwargs.get('instance_id')
self.public_dns_name=kwargs.get('public_dns_name')
self.private_dns_name=kwargs.get('private_dns_name')
self.ip_address=kwargs.get('ip_address')
self.private_ip_address=kwargs.get('private_ip_address')
ifkwargs.get('job'):
self.jobs.append(kwargs['job'])
elifkwargs.get('jobs'):
self.jobs=kwargs['jobs']
# Parse reference
self.object_id=kwargs.get('objectId')
# Experimenting
self.ebs=False
defto_dict(self):
""" Return dictoionary reprenstation of object """
return {
'name': self.name,
'instance_id': self.instance_id,
'ami': self.ami,
'key_name': self.key_name,
'zone': self.zone,
'instance_type': self.instance_type,
'public_dns_name': self.public_dns_name,
'private_dns_name': self.private_dns_name,
'ip_address': self.ip_address,
'private_ip_address': self.private_ip_address,
'user': self.user,
'jobs': self.jobs
}
deflaunch(self):
'''Launch a single instance of the provided ami '''
conn=EC2Connection()
# Declare the block device mapping for ephemeral disks
mapping=None
ifself.ebs:
# TODO - toggle instance storage
mapping=BlockDeviceMapping()
eph0=BlockDeviceType()
eph1=BlockDeviceType()
eph0.ephemeral_name='ephemeral0'
eph1.ephemeral_name='ephemeral1'
mapping['/dev/sdb'] =eph0
mapping['/dev/sdc'] =eph1
# Now, ask for a reservation
reservation=conn.run_instances(self.ami, instance_type=self.instance_type,
key_name=self.key_name, placement=self.zone,
block_device_map=mapping, security_groups=[self.security_group])
# And assume that the instance we're talking about is the first in the list
# This is not always a good assumption, and will likely depend on the specifics
# of your launching situation. For launching an isolated instance while no
# other actions are taking place, this is sufficient.
instance=reservation.instances[0]
print('Waiting for instance to start...')
# Check up on its status every so often
try:
status=instance.update()
except:
pass
whilestatus=='pending':
time.sleep(5)
try:
status=instance.update()
except:
pass
ifstatus=='running':
print('New instance "'+instance.id+'" accessible at '+instance.public_dns_name)
# Name the instance
conn.create_tags([instance.id], {'Name': self.name})
# update properties
self.instance_id=instance.id
self.private_dns_name=instance.private_dns_name
self.public_dns_name=instance.public_dns_name
self.ip_address=instance.ip_address
self.private_ip_address=instance.private_ip_address
ParseClient.add_node(self.to_dict())
ifself.try_connect():
self.refresh_jobs()
returnTrue
else:
print('Instance status: '+status)
returnFalse
deftry_connect(self):
""" Test SSH connection in a rety loop """
tries=0
whileTrue:
try:
tries+=1
withsettings(host_string='%s@%s'% (self.user, self.ip_address)):
sudo("hostname")
returnTrue
except:
time.sleep(5)
iftries>=10:
print"Unable to connect after %d tries"%tries
returnFalse
defrefresh_jobs(self):
""" Run all jobs """
withsettings(host_string='%s@%s'% (self.user, self.ip_address)):
# Run init from Base job class, once per run
job_obj=Job()
job_obj.update_packages()
# Run all nodes jobs
forjobinself.jobs:
self.run_single_job(job)
defrun_single_job(self, job):
""" Connect to box and run job """
template_vars= {
'nodes': ParseClient.get_all_nodes()
}
withsettings(host_string='%s@%s'% (self.user, self.ip_address)):
job_obj=self.get_job_module(job)
job_obj.run(template_vars)
defterminate(self):
''' Terminate this instance '''
conn=EC2Connection()
try:
conn.terminate_instances([self.instance_id])
except:
pass
ParseClient.delete_node(self.object_id)
defmock_launch(self):
""" For testing """
mock= {
'name': self.name,
'key_name': self.key_name,
'ami': self.ami,
'zone': self.zone,
'instance_type': self.instance_type,
'user':self.user,
'jobs':self.jobs,
'public_dns_name': u'ec2-107-21-159-143.compute-1.amazonaws.com',
'ip_address': u'107.21.159.143',
'private_dns_name': u'ip-10-29-6-45.ec2.internal',
'id': u'i-e2a5559d',
'dns_name': u'ec2-107-21-159-143.compute-1.amazonaws.com',
'private_ip_address': u'10.29.6.45'
}
ifParseClient.add_node(mock):
print"Node stored on remote"
else:
print"Node storage failed on remote"
defget_job_module(self, job):
""" Helper to get hob object dynamically """
obj=self.get_class("jobs.%s"%job)
returnobj()
@staticmethod
defget_class(kls):
""" Source: http://stackoverflow.com/questions/452969/does-python-have-an-equivalent-to-java-class-forname """
parts=kls.split('.')
module=".".join(parts[:-1])
mod=__import__( module )
forcompinparts[1:]:
mod=getattr(mod, comp)
returnmod
defadd_job(self, job):
""" Add a job to node, update node on remote """
ifjobnotinself.jobs:
self.jobs.append(job)
ParseClient.update_node(self.object_id, self.to_dict())
@staticmethod
defget_node(name):
""" Retrive node from remote, return Node object """
result=ParseClient.get_node(name)
returnresultifresultisNoneelseNode(**result)
@staticmethod
defget_all_nodes():
""" Retrieve an array of Node objects """
result=ParseClient.get_all_nodes()
return [Node(**n) forninresult]