This repository was archived by the owner on Feb 21, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathelastic-hpccloud-mom-trigger.py
More file actions
executable file
·321 lines (253 loc) · 9.65 KB
/
elastic-hpccloud-mom-trigger.py
File metadata and controls
executable file
·321 lines (253 loc) · 9.65 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
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
#!/usr/bin/env python
from datetime import datetime, timedelta
from argparse import ArgumentParser
from threading import Thread
import xml.etree.ElementTree as xml
import re
import pwd
import grp
import socket
import oca
class OneClient():
"""A simple OpenNebula API test class"""
ONE_ENDPOINT = 'https://api.hpccloud.surfsara.nl/RPC2'
ONE_USER = 'dccn-hongl' # replace this with your HPC Cloud UI username
ONE_PASSWORD = 'o^SYYLp3' # replace this with your HPC Cloud UI password
def __init__(self):
self.client = oca.Client(self.ONE_USER + ':' + self.ONE_PASSWORD, self.ONE_ENDPOINT)
def ask_version(self):
return self.client.version()
def getListOfVmTemplates(self):
pool = oca.VmTemplatePool(self.client)
pool.info()
return pool
def getVmTemplateByName(self, templateName):
pool = oca.VmTemplatePool(self.client)
pool.info()
return pool.get_by_name(templateName)
def deleteVmTemplateByName(self, templateName):
self.getVmTemplateByName(templateName).delete()
def cloneVmTemplate(self, templateName, newTemplateName):
t = self.getVmTemplateByName(templateName)
t.clone(name=newTemplateName)
return self.getVmTemplateByName(newTemplateName)
def getListOfVMs(self):
pool = oca.VirtualMachinePool(self.client)
pool.info()
return pool
def getVmByName(self, vmName):
pool = oca.VirtualMachinePool(self.client)
pool.info()
return pool.get_by_name(vmName)
def startVmByTemplate(self, vmName, vmTemplateName):
vmt = self.getVmTemplateByName(vmTemplateName)
print vmt.info()
vmt.instantiate(vmName)
vm = self.getVmByName(vmName)
while vm.str_lcm_state != 'RUNNING':
vm.info()
print("%s:%s:%s" % (vm.id, vm.str_state, vm.str_lcm_state))
return vm
def stopVmByName(self, vmName):
pool = oca.VirtualMachinePool(self.client)
pool.info()
vm = pool.get_by_name(vmName)
vm.shutdown()
while vm.str_state != 'DONE':
vm.info()
print("%s:%s:%s" % (vm.id, vm.str_state, vm.str_lcm_state))
return vm
def stopVmById(self, vmId):
pool = oca.VirtualMachinePool(self.client)
pool.info()
vm = pool.get_by_id(vmId)
vm.shutdown()
while vm.str_state != 'DONE':
vm.info()
print("%s:%s:%s" % (vm.id, vm.str_state, vm.str_lcm_state))
return vm
def stopVmByIp(self, vmIp):
pool = oca.VirtualMachinePool(self.client)
pool.info()
vms = filter( lambda x:x.template.nics[0].ip == vmIp, list(pool) )
if not vms:
return None
else:
vm = vms[0]
vm.shutdown()
while vm.str_state != 'DONE':
vm.info()
print("%s:%s:%s" % (vm.id, vm.str_state, vm.str_lcm_state))
return vm
class VmStarter(Thread):
def __init__(self, jobid, ncore, memGB, ttl, name_vmt, name_vm):
Thread.__init__(self)
self.jobid = jobid
self.ncore = ncore
self.memGB = memGB
self.n_vm = name_vm
self.n_vmt = name_vmt
# resolve walltime string into timedelta object with 1 hour extra overhead/buffer
data = ttl.split(':')
reversed(data)
td_args = {}
td_keys = ['seconds','minutes','hours','days']
for i in xrange(len(data)):
td_args[ td_keys[i] ] = int(data[i])
self.ttl = timedelta( **td_args ) + timedelta(hours=1)
def run(self):
oc = OneClient()
## start VM from template
vm = oc.startVmByTemplate(self.n_vm, self.n_vmt)
ip = vm.template.nics[0].ip
ttl_s = datetime.strftime(datetime.utcnow() + self.ttl, '%Y-%m-%dT%H:%M:%SZ')
print('%s: vm %s started, ip: %s' % (vm.id, vm.name, ip))
# TODO: execute system call to add dynamic node to Torque resource manager
qmgr_cmd = 'create node %s.vm.surfsara.nl np=%d,TTL=%s,requestid=%s' % (ip, self.ncore, ttl_s, self.jobid)
print(qmgr_cmd)
class VmStopper(Thread):
def __init__(self, nameOrId):
Thread.__init__(self)
self.nameOrId = nameOrId
def run(self):
oc = OneClient()
vm = None
if re.match('^[0-9]+$', self.nameOrId):
vm = oc.stopVmById(int(self.nameOrId))
else:
try:
socket.inet_aton(self.nameOrId)
vm = oc.stopVmByIp(self.nameOrId)
except socket.error:
vm = oc.stopVmByName(self.nameOrId)
print('%s: vm %s stopped' % (vm.id, vm.name))
def prepareTemplate(base, jobid, ncore, memGB, udata, gdata):
''' create/register new template for job, and return the registered template name'''
oc = OneClient()
## clone template for this current VM
vmt_name = 't_job' + str(jobid)
t = oc.cloneVmTemplate(base, vmt_name)
r = xml.fromstring(t.template.xml)
c = r.find('CONTEXT')
i = c.getchildren().index(c.find('START_SCRIPT'))
# list of user attributes and values for the current user
uinfo = {'TRQ_UID' : str(udata.pw_uid),
'TRQ_UNAME' : udata.pw_name,
'TRQ_UHOME' : udata.pw_dir,
'TRQ_GID' : str(gdata.gr_gid),
'TRQ_GNAME' : gdata.gr_name}
# update template with current user's information
for k,v in uinfo.iteritems():
i+=1
# remove existing user information from template
for e in c.findall(k):
c.remove(e)
# add current user information from template
e = xml.Element(k)
e.text = v
c.insert(i,e)
t.update(xml.tostring(r))
return vmt_name
def deployVMs(args):
request = args.request
jobid = args.jobid
user = args.user
# get user's system information
udata = None
gdata = None
try:
udata = pwd.getpwnam(user)
gdata = grp.getgrgid(udata.pw_gid)
except KeyError:
pass
# ISSUE: there is no memory and core information in the $REQUESTGEOMETRY of Moab?
memGB = 8
ncore = 1
# determin VM's TTL from the walltime information from the $REQUESTGEOMETRY of Moab?
walltime = request.split('@')[-1]
# determine number of nodes from the $REQUESTGEOMETRY of Moab, or 1 node
nnode = 1
try:
nnode = int(request.split('@')[0])
except ValueError:
pass
# prepare template
vmt_name = prepareTemplate('torque-mom.%dC%dG' % (ncore, memGB),
jobid, ncore, memGB, udata, gdata)
# start nodes, each has 1 core and 8 GB memory
threads = []
for i in xrange(nnode):
vm_name = 'trq-j%s-n%d' % (str(jobid), i+1)
t = VmStarter(jobid, ncore, memGB, walltime, vmt_name, vm_name)
threads.append(t)
t.start()
# remove the VM template when all starting threads are finished
for t in threads:
t.join()
print('removing template %s' % vmt_name)
oc = OneClient()
oc.deleteVmTemplateByName(vmt_name)
def shutdownVMs(args):
for n in args.name:
t = VmStopper(n)
t.start()
def listObjs(args):
oc = OneClient()
if args.target == 'vm':
for p in oc.getListOfVMs():
print('%s: %s' % (p.id, p.name))
elif args.target == 'template':
for p in oc.getListOfVmTemplates():
r = xml.fromstring(p.template.xml)
c = r.find('CONTEXT')
for k in ['TRQ_UID', 'TRQ_UNAME', 'TRQ_UHOME', 'TRQ_GID', 'TRQ_GNAME']:
for e in c.findall(k):
c.remove(e)
print('%s: %s, %s' % (p.id, p.name, xml.tostring(r)))
if __name__ == '__main__':
parser = ArgumentParser(description='deploy/shutdown VMs on SURFSara HPC cloud, using predefined templates', version="0.1")
subparser = parser.add_subparsers()
# arguments for deploy
deploy = subparser.add_parser('deploy')
deploy.add_argument('-j','--jobid',
action = 'store',
dest = 'jobid',
type = int,
required = True,
help = 'the torque/moab job id')
deploy.add_argument('-u','--user',
action = 'store',
dest = 'user',
type = str,
required = True,
help = 'the torque/moab job user name')
deploy.add_argument('-r','--request-geometry',
action = 'store',
dest = 'request',
type = str,
default = '1@12:00:00',
help = 'the job request geometry')
deploy.set_defaults(func=deployVMs)
# arguments for shutdown
shutdown = subparser.add_parser('shutdown')
shutdown.add_argument('-n', '--node-name',
action = 'store',
dest = 'name',
required = True,
type = str,
nargs = '*',
help = 'the name of VMs')
shutdown.set_defaults(func=shutdownVMs)
# arguments for shutdown
listo = subparser.add_parser('list')
listo.add_argument('-t','--target',
action = 'store',
dest = 'target',
type = str,
choices = ['vm','template'],
default = 'vm',
help = 'list objects in the targeting pool')
listo.set_defaults(func=listObjs)
##
cmd = parser.parse_args()
cmd.func(cmd)