[svn r599] Automated test scripts in Python (it will runs over gcov, and generate reports on GMyth library running).
3 __author__ = "Gustavo Sverzut Barbieri / Artur Duque de Souza"
4 __author_email__ = "barbieri@gmail.com / artur.souza@indt.org.br"
15 import lib.utils as utils
18 __all__ = ("Transcoder", "RequestHandler", "Server", "serve_forever",
19 "load_plugins_transcoders")
21 class Transcoder(object):
22 log = log.getLogger("gms.transcoder")
23 priority = 0 # negative values have higher priorities
24 name = None # to be used in requests
26 def __init__(self, params):
31 def params_first(self, key, default=None):
33 return self.params[key][0]
36 return self.params[key][0]
42 def get_mimetype(self):
43 mux = self.params_first("mux", "mpg")
48 return "video/x-msvideo"
50 return "application/octet-stream"
54 def start(self, outfile):
65 return '%s("%s", mux="%s", params=%s, addr=%s)' % \
66 (self.__class__.__name__,
67 self.params_first("uri", "None"),
68 self.params_first("mux", "mpg"),
76 class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
77 log = log.getLogger("gms.request")
79 transcoders = utils.PluginSet(Transcoder)
82 "Status": "/status.do",
83 "Stop": "/stop-transcoder.do",
84 "Shutdown": "/shutdown.do"
88 def load_plugins_transcoders(cls, directory):
89 cls.transcoders.load_from_directory(directory)
91 if cls.def_transcoder is None and cls.transcoders:
92 cls.def_transcoder = cls.transcoders[0].name
93 # load_plugins_transcoders()
96 def do_dispatch(self, body):
99 pieces = urlparse.urlparse(self.path)
100 self.path = pieces[2]
101 self.query = cgi.parse_qs(pieces[4])
104 self.serve_main(body)
105 elif self.path == "/shutdown.do":
106 self.serve_shutdown(body)
107 elif self.path == "/stop-transcoder.do":
108 self.serve_stop_transcoder(body)
109 elif self.path == "/status.do":
110 self.serve_status(body)
111 elif self.path == "/play.do":
112 self.serve_play(body)
113 elif self.path == "/stream.do":
114 self.serve_stream(body)
116 self.send_error(404, "File not found")
121 self.do_dispatch(True)
126 self.do_dispatch(False)
130 def _nav_items(self):
132 for name, url in self.menu.items():
133 ret += utils.getHTML("menu", {"name": name, "url": url})
138 def _create_html_item(self, opt):
139 return "<li>%s</li>\n" % opt
142 def serve_main(self, body):
143 self.send_response(200)
144 self.send_header("Content-Type", "text/html")
145 self.send_header('Connection', 'close')
148 self.wfile.write(utils.getHTML("index", {"menu": self._nav_items()}))
152 def serve_shutdown(self, body):
153 self.send_response(200)
154 self.send_header("Content-Type", "text/html")
155 self.send_header('Connection', 'close')
158 self.wfile.write(utils.getHTML("shutdown"))
159 self.server.server_close()
163 def serve_stop_all_transcoders(self, body):
164 self.send_response(200)
165 self.send_header("Content-Type", "text/html")
166 self.send_header('Connection', 'close')
169 self.server.stop_transcoders()
170 self.wfile.write(utils.getHTML("stop_all", {"menu": self._nav_items()}))
171 # serve_stop_all_transcoders()
174 def serve_stop_selected_transcoders(self, body, requests):
175 self.send_response(200)
176 self.send_header("Content-Type", "text/html")
177 self.send_header('Connection', 'close')
181 transcoders = self.server.get_transcoders()
185 host, port = req.split(":")
192 for t, r in transcoders:
193 if r.client_address == addr:
197 self.log.info("Plugin already stopped")
199 opts += self._create_html_item("%s: %s:%s" % (
200 t, addr[0], addr[1]))
204 self.wfile.write(utils.getHTML("stop_selected",
205 {"menu": self._nav_items(),
207 # serve_stop_selected_transcoders()
210 def serve_stop_transcoder(self, body):
211 req = self.query.get("request", None)
212 if req and "all" in req:
213 self.serve_stop_all_transcoders(body)
215 self.serve_stop_selected_transcoders(body, req)
217 self.serve_status(body)
218 # serve_stop_transcoder()
221 def serve_status(self, body):
222 self.send_response(200)
223 self.send_header("Content-Type", "text/html")
224 self.send_header('Connection', 'close')
228 tl = self.server.get_transcoders()
230 running = "<p>No running transcoder.</p>\n"
234 running = "<p>Running transcoders:</p>\n"
235 stopall = self._create_html_item("<a href='%s?request=all'>[STOP ALL]</a>" %
238 for transcoder, request in tl:
239 stopone = self._create_html_item("%s: %s:%s<a href='%s?request=%s:%s'>"
241 transcoder, request.client_address[0], request.client_address[1],
242 self.menu["Stop"], request.client_address[0], request.client_address[1]) )
244 self.wfile.write(utils.getHTML("status",
245 {"menu": self._nav_items(),
248 "stopone": stopone}))
252 def _get_transcoder(self):
253 # get transcoder option: mencoder is the default
254 request_transcoders = self.query.get("transcoder", ["mencoder"])
256 for t in request_transcoders:
257 transcoder = self.transcoders.get(t)
262 return self.transcoders[self.def_transcoder]
266 def serve_stream(self, body):
267 transcoder = self._get_transcoder()
269 obj = transcoder(self.query)
271 self.send_error(500, str(e))
274 self.send_response(200)
275 self.send_header("Content-Type", obj.get_mimetype())
276 self.send_header('Connection', 'close')
280 self.server.add_transcoders(self, obj)
281 obj.start(self.wfile)
282 self.server.del_transcoders(self, obj)
286 def log_request(self, code='-', size='-'):
287 self.log.info('"%s" %s %s', self.requestline, str(code), str(size))
291 def log_error(self, format, *args):
292 self.log.error("%s: %s" % (self.address_string(), format % args))
296 def log_message(self, format, *args):
297 self.log.info("%s: %s" % (self.address_string(), format % args))
303 class Server(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
304 log = log.getLogger("gms.server")
307 _lock = threading.RLock()
309 def serve_forever(self):
310 self.log.info("GMyth-Streamer serving HTTP on %s:%s" %
311 self.socket.getsockname())
314 self.handle_request()
315 except KeyboardInterrupt, e:
318 self.log.debug("Stopping all remaining transcoders...")
319 self.stop_transcoders()
320 self.log.debug("Transcoders stopped!")
324 def get_request(self):
326 old = skt.gettimeout()
333 except socket.timeout, e:
335 raise socket.error("Not running")
339 def server_close(self):
341 self.stop_transcoders()
343 BaseHTTPServer.HTTPServer.server_close(self)
347 def stop_transcoders(self):
349 for transcoder, request in self._transcoders.iteritems():
350 self.log.info("Stop transcoder: %s, client=%s" %
351 (transcoder, request.client_address))
357 def get_transcoders(self):
360 return self._transcoders.items()
366 def add_transcoders(self, request, transcoder):
369 self._transcoders[transcoder] = request
375 def del_transcoders(self, request, transcoder):
378 del self._transcoders[transcoder]
386 def serve_forever(host="0.0.0.0", port=40000):
388 RequestHandler.protocol_version = "HTTP/1.0"
389 httpd = Server(addr, RequestHandler)
390 httpd.serve_forever()
394 def load_plugins_transcoders(directory):
395 RequestHandler.load_plugins_transcoders(directory)
396 # load_plugins_transcoders()