From 0c2ac7bcf2b81aca785dc14afc1734101ec6f89a Mon Sep 17 00:00:00 2001 From: Davide Alberani Date: Thu, 16 Apr 2015 00:06:01 +0200 Subject: [PATCH] draft of async runner of commands --- eventman_server.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/eventman_server.py b/eventman_server.py index af6fe60..b5a0749 100755 --- a/eventman_server.py +++ b/eventman_server.py @@ -18,6 +18,7 @@ limitations under the License. """ import os +import subprocess import tornado.httpserver import tornado.ioloop @@ -72,6 +73,24 @@ class CollectionHandler(BaseHandler): # set of documents we're managing (a collection in MongoDB or a table in a SQL database) collection = None + def run_command(self, cmd, callback=None): + self.ioloop = tornado.ioloop.IOLoop.instance() + p = subprocess.Popen(cmd, close_fds=True, + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + import datetime + self.tm = self.ioloop.add_timeout(datetime.timedelta(seconds=3), lambda: self.timeout(callback)) + self.ioloop.add_handler(p.stdout.fileno(), + self.async_callback(self.on_response, callback, p), self.ioloop.READ) + + def timeout(self, callback, *args): + callback((None, 'aaaaazzzz')) + + def on_response(self, callback, pipe, fd, events): + self.ioloop.remove_timeout(self.tm) + stdoutdata, stderrdata = pipe.communicate() + callback((pipe.returncode, stdoutdata)) + self.ioloop.remove_handler(fd) + def _filter_results(self, results, params): """Filter a list using keys and values from a dictionary. @@ -147,6 +166,17 @@ class CollectionHandler(BaseHandler): self.write({'success': True}) + +class TestHandler(CollectionHandler): + + @tornado.web.asynchronous + @gen.engine + def get(self): + #ret, resp = yield gen.Task(self.run_command, ['echo', str(self.arguments)]) + ret, resp = yield gen.Task(self.run_command, ['sleep', '10']) + self.write('ok: %s: %s\n' % (ret, resp)) + self.finish() + class PersonsHandler(CollectionHandler): """Handle requests for Persons.""" collection = 'persons' @@ -320,6 +350,8 @@ def run(): (r"/events/?(?P\w+)?/?(?P\w+)?/?(?P\w+)?", EventsHandler, init_params), (r"/(?:index.html)?", RootHandler, init_params), (r"/ebcsvpersons", EbCSVImportPersonsHandler, init_params), + + (r"/test", TestHandler, init_params), (r'/(.*)', tornado.web.StaticFileHandler, {"path": "angular_app"}) ], template_path=os.path.join(os.path.dirname(__file__), "templates"),