gmyth-stream/server/0.2/lib/server.py
author melunko
Tue May 08 15:32:18 2007 +0100 (2007-05-08)
branchtrunk
changeset 636 90bb7f60e0b9
parent 595 5c5cff842d57
child 638 e38953623405
permissions -rw-r--r--
[svn r642] Included possible dependency to libmysqlclient15off package
morphbr@565
     1
#!/usr/bin/env python
morphbr@565
     2
morphbr@565
     3
__author__ = "Gustavo Sverzut Barbieri / Artur Duque de Souza"
morphbr@565
     4
__author_email__ = "barbieri@gmail.com / artur.souza@indt.org.br"
morphbr@565
     5
__license__ = "GPL"
morphbr@565
     6
__version__ = "0.3"
morphbr@565
     7
morphbr@565
     8
import os
morphbr@565
     9
import threading
morphbr@565
    10
import SocketServer
morphbr@565
    11
import BaseHTTPServer
morphbr@565
    12
import socket
morphbr@565
    13
import urlparse
morphbr@565
    14
import cgi
morphbr@565
    15
import lib.utils as utils
morphbr@565
    16
import logging as log
morphbr@565
    17
morphbr@565
    18
__all__ = ("Transcoder", "RequestHandler", "Server", "serve_forever",
morphbr@565
    19
           "load_plugins_transcoders")
morphbr@565
    20
morphbr@565
    21
class Transcoder(object):
morphbr@577
    22
    log = log.getLogger("gms.transcoder")
morphbr@565
    23
    priority = 0   # negative values have higher priorities
morphbr@565
    24
    name = None # to be used in requests
morphbr@595
    25
    status = None
morphbr@565
    26
morphbr@565
    27
    def __init__(self, params):
morphbr@565
    28
        self.params = params
morphbr@565
    29
    # __init__()
morphbr@565
    30
morphbr@565
    31
morphbr@565
    32
    def params_first(self, key, default=None):
morphbr@565
    33
        if default is None:
morphbr@565
    34
            return self.params[key][0]
morphbr@565
    35
        else:
morphbr@565
    36
            try:
morphbr@565
    37
                return self.params[key][0]
morphbr@565
    38
            except:
morphbr@565
    39
                return default
morphbr@565
    40
    # params_first()
morphbr@565
    41
morphbr@565
    42
morphbr@565
    43
    def get_mimetype(self):
morphbr@565
    44
        mux = self.params_first("mux", "mpg")
morphbr@565
    45
morphbr@565
    46
        if mux == "mpeg":
morphbr@565
    47
            return "video/mpeg"
morphbr@565
    48
        elif mux == "avi":
morphbr@565
    49
            return "video/x-msvideo"
morphbr@565
    50
        else:
morphbr@565
    51
            return "application/octet-stream"
morphbr@565
    52
    # get_mimetype()
morphbr@565
    53
morphbr@565
    54
morphbr@565
    55
    def start(self, outfile):
morphbr@565
    56
        return True
morphbr@565
    57
    # start()
morphbr@565
    58
morphbr@565
    59
morphbr@565
    60
    def stop(self):
morphbr@565
    61
        return Tru
morphbr@565
    62
    # stop()
morphbr@565
    63
morphbr@565
    64
morphbr@565
    65
    def __str__(self):
morphbr@577
    66
        return '%s("%s", mux="%s", params=%s, addr=%s)' % \
morphbr@565
    67
               (self.__class__.__name__,
morphbr@565
    68
                self.params_first("uri", "None"),
morphbr@565
    69
                self.params_first("mux", "mpg"),
morphbr@577
    70
                self.params,
morphbr@577
    71
                repr(self))
morphbr@565
    72
    # __str__()
morphbr@565
    73
# Transcoder
morphbr@565
    74
morphbr@565
    75
morphbr@565
    76
morphbr@565
    77
class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
morphbr@577
    78
    log = log.getLogger("gms.request")
morphbr@565
    79
    def_transcoder = None
morphbr@565
    80
    transcoders = utils.PluginSet(Transcoder)
morphbr@565
    81
morphbr@585
    82
    menu = {
morphbr@585
    83
        "Status": "/status.do",
morphbr@585
    84
        "Stop": "/stop-transcoder.do",
morphbr@585
    85
        "Shutdown": "/shutdown.do"
morphbr@585
    86
        }
morphbr@585
    87
morphbr@565
    88
    @classmethod
morphbr@565
    89
    def load_plugins_transcoders(cls, directory):
morphbr@565
    90
        cls.transcoders.load_from_directory(directory)
morphbr@565
    91
morphbr@565
    92
        if cls.def_transcoder is None and cls.transcoders:
morphbr@565
    93
            cls.def_transcoder = cls.transcoders[0].name
morphbr@565
    94
    # load_plugins_transcoders()
morphbr@565
    95
morphbr@565
    96
morphbr@565
    97
    def do_dispatch(self, body):
morphbr@565
    98
        self.url = self.path
morphbr@565
    99
morphbr@565
   100
        pieces = urlparse.urlparse(self.path)
morphbr@565
   101
        self.path = pieces[2]
morphbr@565
   102
        self.query = cgi.parse_qs(pieces[4])
morphbr@565
   103
morphbr@565
   104
        if self.path == "/":
morphbr@565
   105
            self.serve_main(body)
morphbr@565
   106
        elif self.path == "/shutdown.do":
morphbr@565
   107
            self.serve_shutdown(body)
morphbr@565
   108
        elif self.path == "/stop-transcoder.do":
morphbr@565
   109
            self.serve_stop_transcoder(body)
morphbr@565
   110
        elif self.path == "/status.do":
morphbr@565
   111
            self.serve_status(body)
morphbr@565
   112
        elif self.path == "/play.do":
morphbr@565
   113
            self.serve_play(body)
morphbr@565
   114
        elif self.path == "/stream.do":
morphbr@565
   115
            self.serve_stream(body)
morphbr@565
   116
        else:
morphbr@628
   117
            action = self.query.get("action", None)
morphbr@628
   118
            if action is not None:
morphbr@628
   119
                self.serve_stream(body)
morphbr@628
   120
            else:
morphbr@628
   121
                self.send_error(404, "File not found")
morphbr@565
   122
    # do_dispatch()
morphbr@565
   123
morphbr@565
   124
morphbr@565
   125
    def do_GET(self):
morphbr@565
   126
        self.do_dispatch(True)
morphbr@565
   127
    # do_GET()
morphbr@565
   128
morphbr@565
   129
morphbr@565
   130
    def do_HEAD(self):
morphbr@565
   131
        self.do_dispatch(False)
morphbr@565
   132
    # do_HEAD()
morphbr@565
   133
morphbr@565
   134
morphbr@565
   135
    def _nav_items(self):
morphbr@585
   136
        ret = ""
morphbr@585
   137
        for name, url in self.menu.items():
morphbr@585
   138
            ret += utils.getHTML("menu", {"name": name, "url": url})
morphbr@585
   139
morphbr@585
   140
        return ret
morphbr@565
   141
    # _nav_items()
morphbr@565
   142
morphbr@585
   143
    def _create_html_item(self, opt):
morphbr@585
   144
        return "<li>%s</li>\n" % opt
morphbr@585
   145
    # _create_html_item
morphbr@565
   146
morphbr@565
   147
    def serve_main(self, body):
morphbr@565
   148
        self.send_response(200)
morphbr@565
   149
        self.send_header("Content-Type", "text/html")
morphbr@565
   150
        self.send_header('Connection', 'close')
morphbr@565
   151
        self.end_headers()
morphbr@565
   152
        if body:
morphbr@585
   153
            self.wfile.write(utils.getHTML("index", {"menu": self._nav_items()}))
morphbr@565
   154
    # serve_main()
morphbr@565
   155
morphbr@565
   156
morphbr@565
   157
    def serve_shutdown(self, body):
morphbr@565
   158
        self.send_response(200)
morphbr@565
   159
        self.send_header("Content-Type", "text/html")
morphbr@565
   160
        self.send_header('Connection', 'close')
morphbr@565
   161
        self.end_headers()
morphbr@565
   162
        if body:
morphbr@585
   163
            self.wfile.write(utils.getHTML("shutdown"))
morphbr@565
   164
        self.server.server_close()
morphbr@565
   165
    # serve_shutdown()
morphbr@565
   166
morphbr@565
   167
morphbr@565
   168
    def serve_stop_all_transcoders(self, body):
morphbr@565
   169
        self.send_response(200)
morphbr@565
   170
        self.send_header("Content-Type", "text/html")
morphbr@565
   171
        self.send_header('Connection', 'close')
morphbr@565
   172
        self.end_headers()
morphbr@565
   173
        if body:
morphbr@565
   174
            self.server.stop_transcoders()
morphbr@585
   175
            self.wfile.write(utils.getHTML("stop_all", {"menu": self._nav_items()}))
morphbr@565
   176
    # serve_stop_all_transcoders()
morphbr@565
   177
morphbr@565
   178
morphbr@565
   179
    def serve_stop_selected_transcoders(self, body, requests):
morphbr@565
   180
        self.send_response(200)
morphbr@565
   181
        self.send_header("Content-Type", "text/html")
morphbr@565
   182
        self.send_header('Connection', 'close')
morphbr@565
   183
        self.end_headers()
morphbr@585
   184
        opts = ""
morphbr@565
   185
        if body:
morphbr@565
   186
            transcoders = self.server.get_transcoders()
morphbr@565
   187
morphbr@565
   188
            for req in requests:
morphbr@565
   189
                try:
morphbr@565
   190
                    host, port = req.split(":")
morphbr@565
   191
                except IndexError:
morphbr@565
   192
                    continue
morphbr@565
   193
morphbr@565
   194
                port = int(port)
morphbr@565
   195
                addr = (host, port)
morphbr@565
   196
morphbr@565
   197
                for t, r in transcoders:
morphbr@565
   198
                    if r.client_address == addr:
morphbr@571
   199
                        try:
morphbr@571
   200
                            t.stop()
morphbr@571
   201
                        except Exception, e:
morphbr@571
   202
                            self.log.info("Plugin already stopped")
morphbr@571
   203
morphbr@585
   204
                        opts += self._create_html_item("%s: %s:%s" % (
morphbr@585
   205
                            t, addr[0], addr[1]))
morphbr@585
   206
morphbr@565
   207
                        break
morphbr@585
   208
morphbr@585
   209
                self.wfile.write(utils.getHTML("stop_selected",
morphbr@585
   210
                                               {"menu": self._nav_items(),
morphbr@585
   211
                                                "opts": opts}))
morphbr@565
   212
    # serve_stop_selected_transcoders()
morphbr@565
   213
morphbr@565
   214
morphbr@565
   215
    def serve_stop_transcoder(self, body):
morphbr@565
   216
        req = self.query.get("request", None)
morphbr@565
   217
        if req and "all" in req:
morphbr@565
   218
            self.serve_stop_all_transcoders(body)
morphbr@565
   219
        elif req:
morphbr@565
   220
            self.serve_stop_selected_transcoders(body, req)
morphbr@565
   221
        else:
morphbr@565
   222
            self.serve_status(body)
morphbr@565
   223
    # serve_stop_transcoder()
morphbr@565
   224
morphbr@565
   225
morphbr@565
   226
    def serve_status(self, body):
morphbr@565
   227
        self.send_response(200)
morphbr@565
   228
        self.send_header("Content-Type", "text/html")
morphbr@565
   229
        self.send_header('Connection', 'close')
morphbr@565
   230
        self.end_headers()
morphbr@585
   231
morphbr@565
   232
        if body:
morphbr@565
   233
            tl = self.server.get_transcoders()
morphbr@565
   234
            if not tl:
morphbr@585
   235
                running = "<p>No running transcoder.</p>\n"
morphbr@585
   236
                stopall = ""
morphbr@585
   237
                stopone = ""
morphbr@565
   238
            else:
morphbr@585
   239
                running = "<p>Running transcoders:</p>\n"
morphbr@585
   240
                stopall = self._create_html_item("<a href='%s?request=all'>[STOP ALL]</a>" %
morphbr@585
   241
                                                 self.menu["Stop"])
morphbr@585
   242
morphbr@565
   243
                for transcoder, request in tl:
morphbr@585
   244
                    stopone = self._create_html_item("%s: %s:%s<a href='%s?request=%s:%s'>"
morphbr@595
   245
                                                     "[STOP]</a> - Status: %s%%" % (
morphbr@585
   246
                        transcoder, request.client_address[0], request.client_address[1],
morphbr@595
   247
                        self.menu["Stop"], request.client_address[0], request.client_address[1],
morphbr@595
   248
                        transcoder.status) )
morphbr@565
   249
morphbr@585
   250
            self.wfile.write(utils.getHTML("status",
morphbr@585
   251
                                           {"menu": self._nav_items(),
morphbr@585
   252
                                            "running": running,
morphbr@585
   253
                                            "stopall": stopall,
morphbr@585
   254
                                            "stopone": stopone}))
morphbr@565
   255
    # serve_status()
morphbr@565
   256
morphbr@565
   257
morphbr@565
   258
    def _get_transcoder(self):
morphbr@565
   259
        # get transcoder option: mencoder is the default
morphbr@565
   260
        request_transcoders = self.query.get("transcoder", ["mencoder"])
morphbr@565
   261
morphbr@565
   262
        for t in request_transcoders:
morphbr@565
   263
            transcoder = self.transcoders.get(t)
morphbr@565
   264
            if transcoder:
morphbr@565
   265
                return transcoder
morphbr@565
   266
morphbr@565
   267
        if not transcoder:
morphbr@565
   268
            return self.transcoders[self.def_transcoder]
morphbr@565
   269
    # _get_transcoder()
morphbr@565
   270
morphbr@565
   271
morphbr@565
   272
    def serve_stream(self, body):
morphbr@565
   273
        transcoder = self._get_transcoder()
morphbr@565
   274
        try:
morphbr@572
   275
            obj = transcoder(self.query)
morphbr@565
   276
        except Exception, e:
morphbr@565
   277
            self.send_error(500, str(e))
morphbr@565
   278
            return
morphbr@565
   279
morphbr@565
   280
        self.send_response(200)
morphbr@565
   281
        self.send_header("Content-Type", obj.get_mimetype())
morphbr@565
   282
        self.send_header('Connection', 'close')
morphbr@565
   283
        self.end_headers()
morphbr@565
   284
morphbr@565
   285
        if body:
morphbr@565
   286
            self.server.add_transcoders(self, obj)
morphbr@565
   287
            obj.start(self.wfile)
morphbr@565
   288
            self.server.del_transcoders(self, obj)
morphbr@565
   289
    # serve_stream()
morphbr@565
   290
morphbr@565
   291
morphbr@565
   292
    def log_request(self, code='-', size='-'):
morphbr@565
   293
        self.log.info('"%s" %s %s', self.requestline, str(code), str(size))
morphbr@565
   294
    # log_request()
morphbr@565
   295
morphbr@565
   296
morphbr@565
   297
    def log_error(self, format, *args):
morphbr@565
   298
        self.log.error("%s: %s" % (self.address_string(), format % args))
morphbr@565
   299
    # log_error()
morphbr@565
   300
morphbr@565
   301
morphbr@565
   302
    def log_message(self, format, *args):
morphbr@565
   303
        self.log.info("%s: %s" % (self.address_string(), format % args))
morphbr@565
   304
    # log_message()
morphbr@565
   305
# RequestHandler
morphbr@565
   306
morphbr@565
   307
morphbr@565
   308
morphbr@565
   309
class Server(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
morphbr@577
   310
    log = log.getLogger("gms.server")
morphbr@565
   311
    run = True
morphbr@565
   312
    _transcoders = {}
morphbr@565
   313
    _lock = threading.RLock()
morphbr@565
   314
morphbr@565
   315
    def serve_forever(self):
morphbr@565
   316
        self.log.info("GMyth-Streamer serving HTTP on %s:%s" %
morphbr@565
   317
                      self.socket.getsockname())
morphbr@565
   318
        try:
morphbr@565
   319
            while self.run:
morphbr@565
   320
                self.handle_request()
morphbr@565
   321
        except KeyboardInterrupt, e:
morphbr@565
   322
            pass
morphbr@565
   323
morphbr@565
   324
        self.log.debug("Stopping all remaining transcoders...")
morphbr@565
   325
        self.stop_transcoders()
morphbr@565
   326
        self.log.debug("Transcoders stopped!")
morphbr@565
   327
    # serve_forever()
morphbr@565
   328
morphbr@565
   329
morphbr@565
   330
    def get_request(self):
morphbr@565
   331
        skt = self.socket
morphbr@565
   332
        old = skt.gettimeout()
morphbr@565
   333
        skt.settimeout(0.5)
morphbr@565
   334
        while self.run:
morphbr@565
   335
            try:
morphbr@565
   336
                r = skt.accept()
morphbr@565
   337
                skt.settimeout(old)
morphbr@565
   338
                return r
morphbr@565
   339
            except socket.timeout, e:
morphbr@565
   340
                pass
morphbr@565
   341
        raise socket.error("Not running")
morphbr@565
   342
    # get_request()
morphbr@565
   343
morphbr@565
   344
morphbr@565
   345
    def server_close(self):
morphbr@565
   346
        self.run = False
morphbr@565
   347
        self.stop_transcoders()
morphbr@565
   348
morphbr@565
   349
        BaseHTTPServer.HTTPServer.server_close(self)
morphbr@565
   350
    # server_close()
morphbr@565
   351
morphbr@565
   352
morphbr@565
   353
    def stop_transcoders(self):
morphbr@565
   354
        self._lock.acquire()
morphbr@565
   355
        for transcoder, request in self._transcoders.iteritems():
morphbr@565
   356
            self.log.info("Stop transcoder: %s, client=%s" %
morphbr@565
   357
                          (transcoder, request.client_address))
morphbr@565
   358
            transcoder.stop()
morphbr@565
   359
        self._lock.release()
morphbr@565
   360
    # stop_transcoders()
morphbr@565
   361
morphbr@565
   362
morphbr@565
   363
    def get_transcoders(self):
morphbr@565
   364
        self._lock.acquire()
morphbr@565
   365
        try:
morphbr@565
   366
            return self._transcoders.items()
morphbr@565
   367
        finally:
morphbr@565
   368
            self._lock.release()
morphbr@565
   369
    # get_transcoders()
morphbr@565
   370
morphbr@565
   371
morphbr@565
   372
    def add_transcoders(self, request, transcoder):
morphbr@565
   373
        self._lock.acquire()
morphbr@565
   374
        try:
morphbr@565
   375
            self._transcoders[transcoder] = request
morphbr@565
   376
        finally:
morphbr@565
   377
            self._lock.release()
morphbr@565
   378
    # add_transcoders()
morphbr@565
   379
morphbr@565
   380
morphbr@565
   381
    def del_transcoders(self, request, transcoder):
morphbr@565
   382
        self._lock.acquire()
morphbr@565
   383
        try:
morphbr@565
   384
            del self._transcoders[transcoder]
morphbr@565
   385
        finally:
morphbr@565
   386
            self._lock.release()
morphbr@565
   387
    # del_transcoders()
morphbr@565
   388
# Server
morphbr@565
   389
morphbr@565
   390
morphbr@565
   391
morphbr@565
   392
def serve_forever(host="0.0.0.0", port=40000):
morphbr@565
   393
    addr = (host, port)
morphbr@565
   394
    RequestHandler.protocol_version = "HTTP/1.0"
morphbr@565
   395
    httpd = Server(addr, RequestHandler)
morphbr@565
   396
    httpd.serve_forever()
morphbr@565
   397
# serve_forever()
morphbr@565
   398
morphbr@565
   399
morphbr@565
   400
def load_plugins_transcoders(directory):
morphbr@565
   401
    RequestHandler.load_plugins_transcoders(directory)
morphbr@565
   402
# load_plugins_transcoders()