-
Notifications
You must be signed in to change notification settings - Fork 0
/
odin.py
443 lines (341 loc) · 13.9 KB
/
odin.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
#!/usr/bin/env python
# encoding: utf-8
"""
Odin.py
Created by Stephen Holiday on 2012-03-27.
Copyright (c) 2012 Stephen Holiday. All rights reserved.
Attempts to follow the Google Python Style Guide:
http://google-styleguide.googlecode.com/svn/trunk/pyguide.html
Not because I think it's the best, but because it's a standard.
"""
import logging
import odin_pb2
import random
import signal
import sys
import threading
import time
import xmlrpclib
import zookeeper
logger = logging.getLogger()
ZOO_OPEN_ACL_UNSAFE = {"perms": 0x1f, "scheme": "world", "id": "anyone"}
def path_join(a, b):
return a + '/' + b
def path_pop(a):
return a.split('/').pop()
def path_cell(a):
parts = a.split('/')
return '/' + parts[1] + '/' + parts[2]
class Odin():
'''
A machine in the cell exists via a node like:
/odin/cell/machines/m-??????
These are ephemeral. If we are creating a node, we will use create
sequence.
A job exists in the cell via a node like:
/odin/cell/jobs/j-?????
Maybe not ephemeral, but deleted when completed. Create sequence.
A task that is to be run on a machine is at:
/odin/cell/tasks/m-????/task-????
Where m-??? is the machine and the task is sequential. The contents is
in the job. Any new tasks under there will start a job on the machine.
'''
_cell = None
_cell_default = '/odin/test'
_z = None
def __init__(self, zookeeper_servers='localhost:2181',
cell=_cell_default):
if cell is None:
self._cell = self._cell_default
else:
self._cell = cell
logger.debug(self._cell)
zookeeper.set_debug_level(zookeeper.LOG_LEVEL_ERROR)
self._z = zookeeper.init(zookeeper_servers)
self._recursivelyCreatePath('%s/machines/' % self._cell)
self._recursivelyCreatePath('%s/jobs/' % self._cell)
self._recursivelyCreatePath('%s/tasks/' % self._cell)
self._recursivelyCreatePath('%s/politicians/' % self._cell)
def __del__(self):
zookeeper.close(self._z)
def create_machine(self, data, cell=None):
if not isinstance(data, odin_pb2.Machine):
raise TypeError('data must be a protobuffer Machine')
if cell is None:
cell = self._cell
machine = zookeeper.create(self._z,
'%s/machines/m-' % cell,
data.SerializeToString(),
[ZOO_OPEN_ACL_UNSAFE],
zookeeper.SEQUENCE | zookeeper.EPHEMERAL)
machine_name = path_pop(machine)
cell_name = path_cell(machine)
zookeeper.create(self._z,
'%s/tasks/%s' % (cell_name, machine_name),
'',
[ZOO_OPEN_ACL_UNSAFE])
return machine
def register_machine(self, machine, data):
if not isinstance(data, odin_pb2.Machine):
raise TypeError('data must be a protobuffer Machine')
zookeeper.create(self._z,
machine,
data.SerializeToString(),
[ZOO_OPEN_ACL_UNSAFE],
zookeeper.EPHEMERAL)
def remove_machine(self, machine):
try:
zookeeper.delete(self._z,
machine)
return True
except zookeeper.NoNodeException:
return False
def get_machine(self, machine):
return odin_pb2.Machine.FromString(zookeeper.get(self._z, machine)[0])
def get_tasks(self, machine):
machine_name = path_pop(machine)
cell = path_cell(machine)
tasks_dir = '%s/tasks/%s' % (cell, machine_name)
children = zookeeper.get_children(self._z, tasks_dir)
tasks = list()
for child_id in children:
child = '%s/%s' % (tasks_dir, child_id)
tasks.append(self.get_task(child))
return tasks
def get_task(self, task):
return odin_pb2.Task.FromString(zookeeper.get(self._z, task)[0])
def watch_tasks(self, machine, watcher):
machine_name = path_pop(machine)
cell = path_cell(machine)
tasks_dir = '%s/tasks/%s' % (cell, machine_name)
children = zookeeper.get_children(self._z, tasks_dir, watcher)
tasks = list()
for child_id in children:
tasks.append(child_id)
return tasks
def get_politicians(self, watcher=None, cell=None):
if cell is None:
cell = self._cell
if watcher is None:
children = zookeeper.get_children(self._z, '%s/politicians' % (cell))
else:
children = zookeeper.get_children(self._z, '%s/politicians' % (cell),
watcher)
children = sorted(children)
politicians = list()
for child in children:
politicians.append('%s/politicians/%s' % (cell, child))
return sorted(politicians)
def add_politician(self, data, cell=None):
if not isinstance(data, odin_pb2.Politician):
raise TypeError('data must be a protobuffer Politician')
if cell is None:
cell = self._cell
return zookeeper.create(self._z,
'%s/politicians/p-' % (cell),
data.SerializeToString(),
[ZOO_OPEN_ACL_UNSAFE],
zookeeper.SEQUENCE | zookeeper.EPHEMERAL)
def add_task_to_machine(self, task, machine):
if not isinstance(task, odin_pb2.Task):
raise TypeError('task must be a protobuffer Task')
machine_name = path_pop(machine)
cell_name = path_cell(machine)
return zookeeper.create(self._z,
'%s/tasks/%s/t-' % (cell_name, machine_name),
task.SerializeToString(),
[ZOO_OPEN_ACL_UNSAFE],
zookeeper.SEQUENCE)
def _recursivelyCreatePath(self, path, intermediate_data=''):
'''
Should do a check to see if this dir already exists.
'''
current_path = ''
for part in path.split('/'):
if len(part) > 0:
try:
current_path += '/' + part
zookeeper.create(self._z,
current_path,
intermediate_data,
[ZOO_OPEN_ACL_UNSAFE])
except zookeeper.NodeExistsException:
pass
class OdinMachine(threading.Thread):
'''
A machine that will run tasks given from the Odin cluster.
'''
_machine = None
_odin = None
_supervisor = None
_supervisor_default_group = 'dynamic'
_supervisor_methods = []
_tasks = {}
_tasks_lock = threading.Lock()
def __init__(self, machine=None, cell=None,
supervisor_url="http://localhost:9001/RPC2"):
threading.Thread.__init__(self)
self._machine = machine
self._supervisor = xmlrpclib.ServerProxy(supervisor_url)
self._supervisor_methods = self._supervisor.system.listMethods()
self.reset_group()
#rint self._supervisor_methods
# Create an Odin connection.
logger.debug(cell)
self._odin = Odin(cell=cell)
machine_data = odin_pb2.Machine()
if self._machine is None:
self._machine = self._odin.create_machine(machine_data)
else:
self._odin.register_machine(self._machine, machine_data)
# PUBLIC Methods
def has_twiddler(self):
return 'twiddler.getAPIVersion' in self._supervisor_methods
def create_process(self, name, config, group=_supervisor_default_group):
return self._supervisor.twiddler.addProgramToGroup(group, name, config)
def remove_process(self, name, group=_supervisor_default_group):
return self._supervisor.supervisor.removeProcessFromGroup(group, name)
def get_process_info(self, name, group=_supervisor_default_group):
return self._supervisor.supervisor.getProcessInfo('%s:%s' % (group, name))
def get_processes(self, group=_supervisor_default_group):
return self._supervisor.supervisor.getAllProcessInfo()
def get_log(self, name, group=_supervisor_default_group):
return self._supervisor.supervisor.readProcessStderrLog(
'%s:%s' % (group, name), 0, 0)
def run(self):
'''
Thread runner.
'''
self.run_tasks(self._odin.watch_tasks(self._machine,
self._tasks_watcher))
while True:
time.sleep(60)
logger.debug('Heartbeat.')
def reset_group(self, group=_supervisor_default_group):
'''
Stops all tasks and removes the group, adding it back.
'''
self._supervisor.supervisor.stopProcessGroup(group)
processes = self.get_processes()
for process in processes:
if process['group'] == group:
logger.debug('Stopping process %s' % process['name'])
self._supervisor.twiddler.removeProcessFromGroup(
group, process['name'])
self._supervisor.supervisor.removeProcessGroup(group)
self._supervisor.supervisor.addProcessGroup(group)
def task_to_config(self, task):
config = dict()
for key in ['command', 'directory', 'umask', 'priority', 'autorestart',
'startsecs', 'startretries', 'stopsignal', 'stopwaitsecs',
'user', 'redirect_stderr', 'stdout_logfile',
'stdout_logfile_maxbytes', 'stdout_logfile_backups',
'stdout_capture_maxbytes', 'stderr_logfile',
'stderr_logfile_maxbytes', 'stderr_logfile_backups',
'stderr_capture_maxbytes']:
if task.runnable.HasField(key):
config[key] = getattr(task.runnable, key)
return config
def get_task(self, task_id):
machine_name = path_pop(self._machine)
cell = path_cell(self._machine)
task = '%s/tasks/%s/%s' % (cell, machine_name, task_id)
return self._odin.get_task(task)
def run_tasks(self, tasks):
logger.debug('run_tasks on %s tasks.' % len(tasks))
self._tasks_lock.acquire()
for task_id in tasks:
if task_id in self._tasks:
logger.debug('Already have task %s.' % task_id)
else:
logger.debug('New task %s. Let\'s start it.' % task_id)
self._tasks[task_id] = self.get_task(task_id)
config = self.task_to_config(self._tasks[task_id])
print config
self.create_process(task_id, config)
self._tasks_lock.release()
# Private Methods
def _tasks_watcher(self, z, event, state, path):
'''
Watcher for a change in tasks.
'''
#line = (z, type(event), type(state), path)
#logger.debug(line)
logger.debug('Task List changed for %s.' % path)
self.run_tasks(self._odin.watch_tasks(self._machine,
self._tasks_watcher))
class OdinPolitician(threading.Thread):
'''
A possible scheduler of an Odin cell.
/odin/cell-name/politicians/p-?????
The politician with the lowest id is the leader.
'''
_politician = None
_odin = None
_is_leader = False
def __init__(self, cell=None):
threading.Thread.__init__(self)
# Create an Odin connection.
self._odin = Odin(cell=cell)
politician = odin_pb2.Politician()
self._politician = self._odin.add_politician(politician)
def check_leadership(self):
'''
The right way to do this is to watch the previous node, avoids herd
problem.
'''
politicians = self._odin.get_politicians(self._politicians_watcher)
if politicians[0] == self._politician:
self._is_leader = True
logger.info('We are the leader!')
else:
self._is_leader = False
logger.info('We are not the leader :(')
def _politicians_watcher(self, z, event, state, path):
'''
Watcher for a change in leaders.
'''
#line = (z, type(event), type(state), path)
#logger.debug(line)
logger.debug('Task List changed for %s.' % path)
self.check_leadership()
def run(self):
'''
Thread runner.
'''
self.check_leadership()
while True:
time.sleep(10)
logger.debug('Heartbeat: _is_leader:%s' % self._is_leader)
def signal_handler(self, signal, frame):
print 'Kill signal received'
sys.exit(0)
def main(argv=None):
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGTSTP, signal_handler)
logger.setLevel(logging.DEBUG)
log_format = '%(asctime)s\t%(name)s:%(process)d\t%(filename)s:%(lineno)d\t%(levelname)s\t%(message)s'
formatter = logging.Formatter(log_format)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
logger.info('Starting OdinMachine.')
cell = '/odin/test%s' % random.randint(0, 9999)
odin_politician = OdinPolitician(cell=cell)
odin_politician.start()
odin_politician2 = OdinPolitician(cell=cell)
odin_politician2.start()
odin_machine = OdinMachine(cell=cell)
odin_machine.start()
task_1 = odin_pb2.Task()
task_1.runnable.command = 'ls'
task_1.runnable.startsecs = 0
task_name = odin_machine._odin.add_task_to_machine(task_1,
odin_machine._machine)
logger.debug('Added task %s' % task_name)
odin_machine.join()
odin_politician.join()
logger.info('Threads joined.')
if __name__ == '__main__':
main()