blob: 9bf0124497fb57a299e8586eb9ac835bade607cc [file] [log] [blame]
Joshua Hesketh0ddd6382013-07-26 10:33:36 +10001#!/usr/bin/python2
2#
Joshua Hesketh39a0fee2013-07-31 12:00:53 +10003# Copyright 2013 Rackspace Australia
4#
5# Licensed under the Apache License, Version 2.0 (the "License"); you may
6# not use this file except in compliance with the License. You may obtain
7# a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
13# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
14# License for the specific language governing permissions and limitations
15# under the License.
Joshua Hesketh0ddd6382013-07-26 10:33:36 +100016
Joshua Hesketh1377f6f2013-07-26 12:02:15 +100017
18""" worker_server.py is an executable worker server that loads and runs
19task_plugins. """
20
Joshua Hesketh0ddd6382013-07-26 10:33:36 +100021import argparse
22import daemon
23import extras
Joshua Hesketh0ddd6382013-07-26 10:33:36 +100024import json
25import logging
26import os
27import signal
28import sys
29
30import worker_manager
31
32# as of python-daemon 1.6 it doesn't bundle pidlockfile anymore
33# instead it depends on lockfile-0.9.1 which uses pidfile.
Joshua Hesketh1377f6f2013-07-26 12:02:15 +100034PID_FILE_MODULE = extras.try_imports(['daemon.pidlockfile', 'daemon.pidfile'])
Joshua Hesketh0ddd6382013-07-26 10:33:36 +100035
36
37class Server(object):
38
39 """ This is the worker server object to be daemonized """
Joshua Hesketh363d0042013-07-26 11:44:07 +100040 log = logging.getLogger("worker_server.Server")
Joshua Hesketh0ddd6382013-07-26 10:33:36 +100041
42 def __init__(self, config):
43 # Config init
44 self.config = config
45 self.manager = None
46 self.plugins = []
47 self.load_plugins()
48
49 # Python logging output file.
50 self.debug_log = self.config['debug_log']
51
52 self.tasks = {}
53
54 def setup_logging(self):
55 if self.debug_log:
Joshua Hesketh6b6700b2013-07-26 16:47:32 +100056 if not os.path.isdir(os.path.dirname(self.debug_log)):
57 os.makedirs(os.path.dirname(self.debug_log))
Joshua Hesketh0ddd6382013-07-26 10:33:36 +100058 logging.basicConfig(format='%(asctime)s %(message)s',
59 filename=self.debug_log, level=logging.DEBUG)
60 else:
61 logging.basicConfig(format='%(asctime)s %(message)s',
62 level=logging.WARN)
63 self.log.debug('Log pusher starting.')
64
65 def load_plugins(self):
66 """ Load the available plugins from task_plugins """
67 # Load plugins
Joshua Hesketh6b6700b2013-07-26 16:47:32 +100068 for plugin in self.config['plugins']:
Joshua Hesketha74f49d2013-09-06 15:52:49 +100069 self.plugins.append({
70 'module': __import__('turbo_hipster.task_plugins.' +
Joshua Hesketh3b74fcd2013-09-06 16:19:52 +100071 plugin['name'] + '.task',
72 fromlist='turbo_hipster.task_plugins' +
73 plugin['name']),
Joshua Hesketh4acd7162013-09-06 16:05:37 +100074 'plugin_config': plugin
Joshua Hesketha74f49d2013-09-06 15:52:49 +100075 })
Joshua Hesketh0ddd6382013-07-26 10:33:36 +100076
77 def run_tasks(self):
78 """ Run the tasks """
79 for plugin in self.plugins:
Joshua Hesketha74f49d2013-09-06 15:52:49 +100080 module = plugin['module']
Joshua Hesketh12176932013-09-17 13:34:46 +100081 self.tasks[module.__worker_name__] = module.Runner(
82 self.config,
83 plugin['plugin_config']
84 )
Joshua Hesketha74f49d2013-09-06 15:52:49 +100085 self.tasks[module.__worker_name__].daemon = True
86 self.tasks[module.__worker_name__].start()
Joshua Hesketh0ddd6382013-07-26 10:33:36 +100087
88 self.manager = worker_manager.GearmanManager(self.config, self.tasks)
89 self.manager.daemon = True
90 self.manager.start()
91
92 def exit_handler(self, signum):
93 signal.signal(signal.SIGUSR1, signal.SIG_IGN)
94 for task_name, task in self.tasks.items():
95 task.stop()
96 self.manager.stop()
97 sys.exit(0)
98
99 def main(self):
100 self.setup_logging()
101 self.run_tasks()
102
103 while True:
104 try:
105 signal.pause()
106 except KeyboardInterrupt:
107 print "Ctrl + C: asking tasks to exit nicely...\n"
108 self.exit_handler(signal.SIGINT)
109
110
111def main():
112 parser = argparse.ArgumentParser()
113 parser.add_argument('-c', '--config',
114 default=
Joshua Hesketh363d0042013-07-26 11:44:07 +1000115 '/etc/turbo-hipster/config.json',
Joshua Hesketh0ddd6382013-07-26 10:33:36 +1000116 help='Path to json config file.')
Joshua Hesketh05d01582013-09-09 15:16:08 +1000117 parser.add_argument('-b', '--background', action='store_true',
118 help='Run as a daemon in the background.')
Joshua Hesketh0ddd6382013-07-26 10:33:36 +1000119 parser.add_argument('-p', '--pidfile',
Joshua Hesketh363d0042013-07-26 11:44:07 +1000120 default='/var/run/turbo-hipster/'
Joshua Heskethe58ecb22013-09-06 12:39:46 +1000121 'turbo-hipster-worker-server.pid',
Joshua Hesketh0ddd6382013-07-26 10:33:36 +1000122 help='PID file to lock during daemonization.')
123 args = parser.parse_args()
124
125 with open(args.config, 'r') as config_stream:
126 config = json.load(config_stream)
127
128 server = Server(config)
129
Joshua Hesketh478f1512013-07-26 11:47:27 +1000130 if args.background:
Joshua Hesketh1377f6f2013-07-26 12:02:15 +1000131 pidfile = PID_FILE_MODULE.TimeoutPIDLockFile(args.pidfile, 10)
Joshua Hesketh0ddd6382013-07-26 10:33:36 +1000132 with daemon.DaemonContext(pidfile=pidfile):
133 server.main()
Joshua Hesketh478f1512013-07-26 11:47:27 +1000134 else:
135 server.main()
Joshua Hesketh0ddd6382013-07-26 10:33:36 +1000136
137
138if __name__ == '__main__':
Joshua Heskethac445b52013-08-14 12:55:22 +1000139 sys.path.insert(0, os.path.abspath(
140 os.path.join(os.path.dirname(__file__), '../')))
Joshua Hesketh0ddd6382013-07-26 10:33:36 +1000141 main()