-
Notifications
You must be signed in to change notification settings - Fork 5
/
jobs.py
executable file
·83 lines (67 loc) · 2.52 KB
/
jobs.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
#!/usr/bin/env python
import os
import sys
base_dir = os.path.realpath(os.path.dirname(__file__))
worker_dir = os.path.join(base_dir, 'workers')
if not os.path.exists(worker_dir):
os.mkdir(worker_dir)
from dotenv import load_dotenv
load_dotenv(os.path.join(base_dir, '.env'))
from farnsworth.models import Job
def color_me(s, padto=0, ljust=True, extra=None):
if len(s) < padto:
if ljust:
s = s.ljust(padto)
else:
s = s.rjust(padto)
hcolor = sum(map(ord, s)) % 7 + 31
return '\x1b[%d%sm%s\x1b[0m' % (hcolor, ';' + str(extra) if extra is not None else '', s)
def spawn_job(ident):
os.chdir(worker_dir)
logfile = str(ident) + '.log'
pidfile = str(ident) + '.pid'
os.system('JOB_ID=%d worker >%s 2>&1 & echo $! >%s' % (ident, logfile, pidfile))
def is_job_alive(jid):
pid_file = os.path.join(worker_dir, '%d.pid' % jid)
try:
with open(pid_file) as f: the_pid = int(f.read())
os.kill(the_pid, 0)
except (OSError, IOError):
return False
return True
def kill_job(jid, signal=15):
pid_file = os.path.join(worker_dir, '%d.pid' % jid)
try:
with open(pid_file) as f: the_pid = int(f.read())
os.kill(the_pid, signal)
except (OSError, IOError):
print 'Job is not running!'
def print_jobs():
print ' ID Priority CS Name CB Name Worker Status'
print '--------------------------------------------------------------------------------------'
for j in Job.select(Job.id, Job.worker, Job.priority, Job.cs, Job.cbn, Job.started_at) \
.where(Job.completed_at == None) \
.order_by(Job.priority.desc()).execute():
cs = '' if j.cs is None else j.cs.name
cbn = '' if j.cbn is None else j.cbn.name
if j.started_at is None:
status = 'pending'
elif is_job_alive(j.id):
status = 'alive'
else:
status = 'crashed!'
print ' %6d %3d %s %s %s %s' % (j.id, j.priority, color_me(cs, 15), color_me(cbn, 20), color_me(j.worker, 20), color_me(status))
def usage():
print 'Usage: ./jobs.py (list | start <id> | kill <id>)'
if __name__ == '__main__':
try:
if sys.argv[1] == 'list':
print_jobs()
elif sys.argv[1] == 'start':
spawn_job(int(sys.argv[2]))
elif sys.argv[1] == 'kill':
kill_job(int(sys.argv[2]))
else:
usage()
except (KeyError, IndexError, ValueError):
usage()