blob: 6e3a2ad21ca8b6b1a9fbe66c38ae2c910b5e6cbc [file] [log] [blame]
Joshua Hesketh0ddd6382013-07-26 10:33:36 +10001#!/usr/bin/python2
2#
3# Copyright 2013 ...
4
Joshua Hesketh1377f6f2013-07-26 12:02:15 +10005
6""" worker_server.py is an executable worker server that loads and runs
7task_plugins. """
8
Joshua Hesketh0ddd6382013-07-26 10:33:36 +10009import argparse
10import daemon
11import extras
12import imp
13import json
14import logging
15import os
16import signal
17import sys
18
19import worker_manager
20
21# as of python-daemon 1.6 it doesn't bundle pidlockfile anymore
22# instead it depends on lockfile-0.9.1 which uses pidfile.
Joshua Hesketh1377f6f2013-07-26 12:02:15 +100023PID_FILE_MODULE = extras.try_imports(['daemon.pidlockfile', 'daemon.pidfile'])
Joshua Hesketh0ddd6382013-07-26 10:33:36 +100024
25
26class Server(object):
27
28 """ This is the worker server object to be daemonized """
Joshua Hesketh363d0042013-07-26 11:44:07 +100029 log = logging.getLogger("worker_server.Server")
Joshua Hesketh0ddd6382013-07-26 10:33:36 +100030
31 def __init__(self, config):
32 # Config init
33 self.config = config
34 self.manager = None
35 self.plugins = []
36 self.load_plugins()
37
38 # Python logging output file.
39 self.debug_log = self.config['debug_log']
40
41 self.tasks = {}
42
43 def setup_logging(self):
44 if self.debug_log:
Joshua Hesketh6b6700b2013-07-26 16:47:32 +100045 if not os.path.isdir(os.path.dirname(self.debug_log)):
46 os.makedirs(os.path.dirname(self.debug_log))
Joshua Hesketh0ddd6382013-07-26 10:33:36 +100047 logging.basicConfig(format='%(asctime)s %(message)s',
48 filename=self.debug_log, level=logging.DEBUG)
49 else:
50 logging.basicConfig(format='%(asctime)s %(message)s',
51 level=logging.WARN)
52 self.log.debug('Log pusher starting.')
53
54 def load_plugins(self):
55 """ Load the available plugins from task_plugins """
56 # Load plugins
Joshua Hesketh6b6700b2013-07-26 16:47:32 +100057 for plugin in self.config['plugins']:
58 print
59 plugin_info = imp.find_module('task',
60 [(os.path.dirname(
61 os.path.realpath(__file__)) +
62 '/task_plugins/' + plugin)])
63 self.plugins.append(imp.load_module('task', *plugin_info))
Joshua Hesketh0ddd6382013-07-26 10:33:36 +100064
65 def run_tasks(self):
66 """ Run the tasks """
67 for plugin in self.plugins:
68 self.tasks[plugin.__worker_name__] = plugin.Runner(self.config)
69 self.tasks[plugin.__worker_name__].daemon = True
70 self.tasks[plugin.__worker_name__].start()
71
72 self.manager = worker_manager.GearmanManager(self.config, self.tasks)
73 self.manager.daemon = True
74 self.manager.start()
75
76 def exit_handler(self, signum):
77 signal.signal(signal.SIGUSR1, signal.SIG_IGN)
78 for task_name, task in self.tasks.items():
79 task.stop()
80 self.manager.stop()
81 sys.exit(0)
82
83 def main(self):
84 self.setup_logging()
85 self.run_tasks()
86
87 while True:
88 try:
89 signal.pause()
90 except KeyboardInterrupt:
91 print "Ctrl + C: asking tasks to exit nicely...\n"
92 self.exit_handler(signal.SIGINT)
93
94
95def main():
96 parser = argparse.ArgumentParser()
97 parser.add_argument('-c', '--config',
98 default=
Joshua Hesketh363d0042013-07-26 11:44:07 +100099 '/etc/turbo-hipster/config.json',
Joshua Hesketh0ddd6382013-07-26 10:33:36 +1000100 help='Path to json config file.')
Joshua Hesketh478f1512013-07-26 11:47:27 +1000101 parser.add_argument('--background', action='store_true',
102 help='Run in the background.')
Joshua Hesketh0ddd6382013-07-26 10:33:36 +1000103 parser.add_argument('-p', '--pidfile',
Joshua Hesketh363d0042013-07-26 11:44:07 +1000104 default='/var/run/turbo-hipster/'
Joshua Hesketh0ddd6382013-07-26 10:33:36 +1000105 'sql-migrate-gearman-worker.pid',
106 help='PID file to lock during daemonization.')
107 args = parser.parse_args()
108
109 with open(args.config, 'r') as config_stream:
110 config = json.load(config_stream)
111
112 server = Server(config)
113
Joshua Hesketh478f1512013-07-26 11:47:27 +1000114 if args.background:
Joshua Hesketh1377f6f2013-07-26 12:02:15 +1000115 pidfile = PID_FILE_MODULE.TimeoutPIDLockFile(args.pidfile, 10)
Joshua Hesketh0ddd6382013-07-26 10:33:36 +1000116 with daemon.DaemonContext(pidfile=pidfile):
117 server.main()
Joshua Hesketh478f1512013-07-26 11:47:27 +1000118 else:
119 server.main()
Joshua Hesketh0ddd6382013-07-26 10:33:36 +1000120
121
122if __name__ == '__main__':
123 main()