[IMP] improved useability on modules
[odoo/odoo.git] / openerp / wsgi.py
index 422d4a7..be7d2bf 100644 (file)
@@ -25,243 +25,354 @@ This module offers a WSGI interface to OpenERP.
 
 """
 
-from wsgiref.simple_server import make_server
-from SimpleXMLRPCServer import SimpleXMLRPCDispatcher
 import httplib
 import urllib
 import xmlrpclib
 import StringIO
 
+import logging
 import os
 import signal
 import sys
+import threading
 import time
+import traceback
 
 import openerp
+import openerp.modules
 import openerp.tools.config as config
+import service.websrv_lib as websrv_lib
+
+# XML-RPC fault codes. Some care must be taken when changing these: the
+# constants are also defined client-side and must remain in sync.
+# User code must use the exceptions defined in ``openerp.exceptions`` (not
+# create directly ``xmlrpclib.Fault`` objects).
+RPC_FAULT_CODE_CLIENT_ERROR = 1 # indistinguishable from app. error.
+RPC_FAULT_CODE_APPLICATION_ERROR = 1
+RPC_FAULT_CODE_WARNING = 2
+RPC_FAULT_CODE_ACCESS_DENIED = 3
+RPC_FAULT_CODE_ACCESS_ERROR = 4
+
+# The new (6.1) versioned RPC paths.
+XML_RPC_PATH = '/openerp/xmlrpc'
+XML_RPC_PATH_1 = '/openerp/xmlrpc/1'
+JSON_RPC_PATH = '/openerp/jsonrpc'
+JSON_RPC_PATH_1 = '/openerp/jsonrpc/1'
+
+def xmlrpc_return(start_response, service, method, params, legacy_exceptions=False):
+    """
+    Helper to call a service's method with some params, using a wsgi-supplied
+    ``start_response`` callback.
 
-def xmlrpc_return(start_response, service, method, params):
-    """ Helper to call a service's method with some params, using a
-    wsgi-supplied ``start_response`` callback."""
-    # This mimics SimpleXMLRPCDispatcher._marshaled_dispatch() for exception
-    # handling.
+    This is the place to look at to see the mapping between core exceptions
+    and XML-RPC fault codes.
+    """
+    # Map OpenERP core exceptions to XML-RPC fault codes. Specific exceptions
+    # defined in ``openerp.exceptions`` are mapped to specific fault codes;
+    # all the other exceptions are mapped to the generic
+    # RPC_FAULT_CODE_APPLICATION_ERROR value.
+    # This also mimics SimpleXMLRPCDispatcher._marshaled_dispatch() for
+    # exception handling.
     try:
-        result = openerp.netsvc.dispatch_rpc(service, method, params, None) # TODO auth
+        result = openerp.netsvc.dispatch_rpc(service, method, params)
         response = xmlrpclib.dumps((result,), methodresponse=1, allow_none=False, encoding=None)
-    except openerp.netsvc.OpenERPDispatcherException, e:
-        fault = xmlrpclib.Fault(openerp.tools.exception_to_unicode(e.exception), e.traceback)
-        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
-    except:
-        exc_type, exc_value, exc_tb = sys.exc_info()
-        fault = xmlrpclib.Fault(1, "%s:%s" % (exc_type, exc_value))
-        response = xmlrpclib.dumps(fault, allow_none=None, encoding=None)
+    except Exception, e:
+        if legacy_exceptions:
+            response = xmlrpc_handle_exception_legacy(e)
+        else:
+            response = xmlrpc_handle_exception(e)
     start_response("200 OK", [('Content-Type','text/xml'), ('Content-Length', str(len(response)))])
     return [response]
 
-def wsgi_xmlrpc(environ, start_response):
+def xmlrpc_handle_exception(e):
+    if isinstance(e, openerp.osv.osv.except_osv): # legacy
+        fault = xmlrpclib.Fault(RPC_FAULT_CODE_WARNING, openerp.tools.ustr(e.value))
+        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
+    elif isinstance(e, openerp.exceptions.Warning):
+        fault = xmlrpclib.Fault(RPC_FAULT_CODE_WARNING, str(e))
+        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
+    elif isinstance (e, openerp.exceptions.AccessError):
+        fault = xmlrpclib.Fault(RPC_FAULT_CODE_ACCESS_ERROR, str(e))
+        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
+    elif isinstance(e, openerp.exceptions.AccessDenied):
+        fault = xmlrpclib.Fault(RPC_FAULT_CODE_ACCESS_DENIED, str(e))
+        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
+    elif isinstance(e, openerp.exceptions.DeferredException):
+        info = e.traceback
+        # Which one is the best ?
+        formatted_info = "".join(traceback.format_exception(*info))
+        #formatted_info = openerp.tools.exception_to_unicode(e) + '\n' + info
+        fault = xmlrpclib.Fault(RPC_FAULT_CODE_APPLICATION_ERROR, formatted_info)
+        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
+    else:
+        if hasattr(e, 'message') and e.message == 'AccessDenied': # legacy
+            fault = xmlrpclib.Fault(RPC_FAULT_CODE_ACCESS_DENIED, str(e))
+            response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
+        else:
+            info = sys.exc_info()
+            # Which one is the best ?
+            formatted_info = "".join(traceback.format_exception(*info))
+            #formatted_info = openerp.tools.exception_to_unicode(e) + '\n' + info
+            fault = xmlrpclib.Fault(RPC_FAULT_CODE_APPLICATION_ERROR, formatted_info)
+            response = xmlrpclib.dumps(fault, allow_none=None, encoding=None)
+    return response
+
+def xmlrpc_handle_exception_legacy(e):
+    if isinstance(e, openerp.osv.osv.except_osv):
+        fault = xmlrpclib.Fault('warning -- ' + e.name + '\n\n' + e.value, '')
+        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
+    elif isinstance(e, openerp.exceptions.Warning):
+        fault = xmlrpclib.Fault('warning -- Warning\n\n' + str(e), '')
+        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
+    elif isinstance(e, openerp.exceptions.AccessError):
+        fault = xmlrpclib.Fault('warning -- AccessError\n\n' + str(e), '')
+        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
+    elif isinstance(e, openerp.exceptions.AccessDenied):
+        fault = xmlrpclib.Fault('AccessDenied', str(e))
+        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
+    elif isinstance(e, openerp.exceptions.DeferredException):
+        info = e.traceback
+        formatted_info = "".join(traceback.format_exception(*info))
+        fault = xmlrpclib.Fault(openerp.tools.ustr(e.message), formatted_info)
+        response = xmlrpclib.dumps(fault, allow_none=False, encoding=None)
+    else:
+        info = sys.exc_info()
+        formatted_info = "".join(traceback.format_exception(*info))
+        fault = xmlrpclib.Fault(openerp.tools.exception_to_unicode(e), formatted_info)
+        response = xmlrpclib.dumps(fault, allow_none=None, encoding=None)
+    return response
+
+def wsgi_xmlrpc_1(environ, start_response):
     """ The main OpenERP WSGI handler."""
-    if environ['REQUEST_METHOD'] == 'POST' and environ['PATH_INFO'].startswith('/openerp/xmlrpc'):
+    if environ['REQUEST_METHOD'] == 'POST' and environ['PATH_INFO'].startswith(XML_RPC_PATH_1):
         length = int(environ['CONTENT_LENGTH'])
         data = environ['wsgi.input'].read(length)
 
         params, method = xmlrpclib.loads(data)
 
-        path = environ['PATH_INFO'][len('/openerp/xmlrpc'):]
+        path = environ['PATH_INFO'][len(XML_RPC_PATH_1):]
         if path.startswith('/'): path = path[1:]
         if path.endswith('/'): p = path[:-1]
         path = path.split('/')
 
-        # All routes are hard-coded. Need a way to register addons-supplied handlers.
+        # All routes are hard-coded.
 
         # No need for a db segment.
         if len(path) == 1:
             service = path[0]
 
             if service == 'common':
-                if method in ('create_database', 'list', 'server_version'):
-                    return xmlrpc_return(start_response, 'db', method, params)
-                else:
-                    return xmlrpc_return(start_response, 'common', method, params)
+                if method in ('server_version',):
+                    service = 'db'
+            return xmlrpc_return(start_response, service, method, params)
+
         # A db segment must be given.
         elif len(path) == 2:
             service, db_name = path
             params = (db_name,) + params
 
-            if service == 'model':
-                return xmlrpc_return(start_response, 'object', method, params)
-            elif service == 'report':
-                return xmlrpc_return(start_response, 'report', method, params)
+            return xmlrpc_return(start_response, service, method, params)
+
+        # A db segment and a model segment must be given.
+        elif len(path) == 3 and path[0] == 'model':
+            service, db_name, model_name = path
+            params = (db_name,) + params[:2] + (model_name,) + params[2:]
+            service = 'object'
+            return xmlrpc_return(start_response, service, method, params)
+
+        # The body has been read, need to raise an exception (not return None).
+        fault = xmlrpclib.Fault(RPC_FAULT_CODE_CLIENT_ERROR, '')
+        response = xmlrpclib.dumps(fault, allow_none=None, encoding=None)
+        start_response("200 OK", [('Content-Type','text/xml'), ('Content-Length', str(len(response)))])
+        return [response]
+
+def wsgi_xmlrpc(environ, start_response):
+    """ WSGI handler to return the versions."""
+    if environ['REQUEST_METHOD'] == 'POST' and environ['PATH_INFO'].startswith(XML_RPC_PATH):
+        length = int(environ['CONTENT_LENGTH'])
+        data = environ['wsgi.input'].read(length)
+
+        params, method = xmlrpclib.loads(data)
+
+        path = environ['PATH_INFO'][len(XML_RPC_PATH):]
+        if path.startswith('/'): path = path[1:]
+        if path.endswith('/'): p = path[:-1]
+        path = path.split('/')
+
+        # All routes are hard-coded.
+
+        if len(path) == 1 and path[0] == '' and method in ('version',):
+            return xmlrpc_return(start_response, 'common', method, ())
 
-        # TODO the body has been read, need to raise an exception (not return None).
+        # The body has been read, need to raise an exception (not return None).
+        fault = xmlrpclib.Fault(RPC_FAULT_CODE_CLIENT_ERROR, '')
+        response = xmlrpclib.dumps(fault, allow_none=None, encoding=None)
+        start_response("200 OK", [('Content-Type','text/xml'), ('Content-Length', str(len(response)))])
+        return [response]
 
-def legacy_wsgi_xmlrpc(environ, start_response):
+def wsgi_xmlrpc_legacy(environ, start_response):
     if environ['REQUEST_METHOD'] == 'POST' and environ['PATH_INFO'].startswith('/xmlrpc/'):
         length = int(environ['CONTENT_LENGTH'])
         data = environ['wsgi.input'].read(length)
         path = environ['PATH_INFO'][len('/xmlrpc/'):] # expected to be one of db, object, ...
 
         params, method = xmlrpclib.loads(data)
-        return xmlrpc_return(start_response, path, method, params)
+        return xmlrpc_return(start_response, path, method, params, True)
 
 def wsgi_jsonrpc(environ, start_response):
     pass
 
-def wsgi_modules(environ, start_response):
-    """ WSGI handler dispatching to addons-provided entry points."""
-    pass
-
 def wsgi_webdav(environ, start_response):
-    if environ['REQUEST_METHOD'] == 'OPTIONS' and environ['PATH_INFO'] == '*':
-        return return_options(start_response)
-    if environ['PATH_INFO'].startswith('/webdav'): # TODO depends on config
-        environ['PATH_INFO'] = '/' + environ['PATH_INFO'][len('/webdav'):]
-        return wsgi_to_http(environ, start_response)
-
-def return_options(start_response):
-    # TODO Microsoft specifi header, see websrv_lib do_OPTIONS 
-    options = [('DAV', '1 2'), ('Allow', 'GET HEAD PROPFIND OPTIONS REPORT')]
+    pi = environ['PATH_INFO']
+    if environ['REQUEST_METHOD'] == 'OPTIONS' and pi in ['*','/']:
+        return return_options(environ, start_response)
+    elif pi.startswith('/webdav'):
+        http_dir = websrv_lib.find_http_service(pi)
+        if http_dir:
+            path = pi[len(http_dir.path):]
+            if path.startswith('/'):
+                environ['PATH_INFO'] = path
+            else:
+                environ['PATH_INFO'] = '/' + path
+            return http_to_wsgi(http_dir)(environ, start_response)
+
+def return_options(environ, start_response):
+    # Microsoft specific header, see
+    # http://www.ibm.com/developerworks/rational/library/2089.html
+    if 'Microsoft' in environ.get('User-Agent', ''):
+        option = [('MS-Author-Via', 'DAV')]
+    else:
+        option = []
+    options += [('DAV', '1 2'), ('Allow', 'GET HEAD PROPFIND OPTIONS REPORT')]
     start_response("200 OK", [('Content-Length', str(0))] + options)
     return []
 
-webdav = None
-
-def wsgi_to_http(environ, start_response):
+def http_to_wsgi(http_dir):
     """
-    Forward a WSGI request to a BaseHTTPRequestHandler.
+    Turn a BaseHTTPRequestHandler into a WSGI entry point.
+
+    Actually the argument is not a bare BaseHTTPRequestHandler but is wrapped
+    (as a class, so it needs to be instanciated) in a HTTPDir.
 
     This code is adapted from wbsrv_lib.MultiHTTPHandler._handle_one_foreign().
     It is a temporary solution: the HTTP sub-handlers (in particular the
     document_webdav addon) have to be WSGIfied.
     """
-    global webdav
-    # Make sure the addons are loaded in the registry, so they have a chance
-    # to register themselves in the 'service' layer.
-    openerp.pooler.get_db_and_pool('xx', update_module=[], pooljobs=False)
-
-    scheme = environ['wsgi.url_scheme']
-
-    headers = {}
-    for key, value in environ.items():
-        if key.startswith('HTTP_'):
-            key = key[5:].replace('_', '-').title()
-            headers[key] = value
-        if key == 'CONTENT_LENGTH':
-            key = key.replace('_', '-').title()
-            headers[key] = value
-    if environ.get('Content-Type'):
-        headers['Content-Type'] = environ['Content-Type']
-
-    path = urllib.quote(environ.get('PATH_INFO', ''))
-    if environ.get('QUERY_STRING'):
-        path += '?' + environ['QUERY_STRING']
-
-    class Dummy():
-        pass
-    server = Dummy()
-    server.server_name = environ['SERVER_NAME']
-    server.server_port = int(environ['SERVER_PORT'])
-    con = openerp.service.websrv_lib.noconnection(environ['gunicorn.socket']) # None
-    fore = webdav.handler(openerp.service.websrv_lib.noconnection(con), environ['REMOTE_ADDR'], server)
-
-    # let's pretend we are a Multi handler
-    class M():
-        def __init__(self):
-            self.sec_realms = {}
-            self.shared_headers = []
-            self.shared_response = ''
-            self.shared_body = ''
-        def send_error(self, code, msg):
-            self.shared_response = str(code) + ' ' + msg
-        def send_response(self, code, msg):
-            self.shared_response = str(code) + ' ' + msg
-        def send_header(self, a, b):
-            self.shared_headers.append((a, b))
-        def end_headers(self, *args, **kwargs):
+    def wsgi_handler(environ, start_response):
+
+        # Extract from the WSGI environment the necessary data.
+        scheme = environ['wsgi.url_scheme']
+
+        headers = {}
+        for key, value in environ.items():
+            if key.startswith('HTTP_'):
+                key = key[5:].replace('_', '-').title()
+                headers[key] = value
+            if key == 'CONTENT_LENGTH':
+                key = key.replace('_', '-').title()
+                headers[key] = value
+        if environ.get('Content-Type'):
+            headers['Content-Type'] = environ['Content-Type']
+
+        path = urllib.quote(environ.get('PATH_INFO', ''))
+        if environ.get('QUERY_STRING'):
+            path += '?' + environ['QUERY_STRING']
+
+        request_version = 'HTTP/1.1' # TODO
+        request_line = "%s %s %s\n" % (environ['REQUEST_METHOD'], path, request_version)
+
+        class Dummy(object):
             pass
 
-    multi = M()
-
-    webdav.auth_provider.setupAuth(multi, fore)
-
-    request_version = 'HTTP/1.1' # TODO
-    fore.wfile = StringIO.StringIO()
-    fore.rfile = environ['wsgi.input']
-    fore.headers = headers
-    fore.command = environ['REQUEST_METHOD']
-    fore.path = path
-    fore.request_version = request_version
-    fore.close_connection = 1
-
-    fore.raw_requestline = "%s %s %s\n" % (environ['REQUEST_METHOD'], path, request_version)
-    fore.requestline = fore.raw_requestline
-
-    from openerp.service.websrv_lib import AuthRequiredExc, AuthRejectedExc
-
-    def go():
-        auth_provider = webdav.auth_provider
-        if auth_provider and auth_provider.realm:
+        # Let's pretend we have a server to hand to the handler.
+        server = Dummy()
+        server.server_name = environ['SERVER_NAME']
+        server.server_port = int(environ['SERVER_PORT'])
+
+        # Initialize the underlying handler and associated auth. provider.
+        con = openerp.service.websrv_lib.noconnection(environ['wsgi.input'])
+        handler = http_dir.instanciate_handler(con, environ['REMOTE_ADDR'], server)
+
+        # Populate the handler as if it is called by a regular HTTP server
+        # and the request is already parsed.
+        handler.wfile = StringIO.StringIO()
+        handler.rfile = environ['wsgi.input']
+        handler.headers = headers
+        handler.command = environ['REQUEST_METHOD']
+        handler.path = path
+        handler.request_version = request_version
+        handler.close_connection = 1
+        handler.raw_requestline = request_line
+        handler.requestline = request_line
+
+        # Handle authentication if there is an auth. provider associated to
+        # the handler.
+        if hasattr(handler, 'auth_provider'):
             try:
-                multi.sec_realms[auth_provider.realm].checkRequest(fore, path)
-            except AuthRequiredExc, ae:
+                handler.auth_provider.checkRequest(handler, path)
+            except websrv_lib.AuthRequiredExc, ae:
                 # Darwin 9.x.x webdav clients will report "HTTP/1.0" to us, while they support (and need) the
                 # authorisation features of HTTP/1.1 
-                if request_version != 'HTTP/1.1' and ('Darwin/9.' not in fore.headers.get('User-Agent', '')):
-                    print 'self.log_error("Cannot require auth at %s", self.request_version)'
-                    multi.send_error(403)
-                    return
-                #self._get_ignore_body(fore) # consume any body that came, not loose sync with input
-                multi.send_response(401,'Authorization required')
-                multi.send_header('WWW-Authenticate','%s realm="%s"' % (ae.atype,ae.realm))
-                multi.send_header('Connection', 'keep-alive')
-                multi.send_header('Content-Type','text/html')
-                multi.send_header('Content-Length', 4) # len(self.auth_required_msg))
-                multi.end_headers()
-                #self.wfile.write(self.auth_required_msg)
-                multi.shared_body = 'Blah'
-                return
-            except AuthRejectedExc,e:
-                print '("Rejected auth: %s" % e.args[0])'
-                multi.send_error(403,e.args[0])
-                return
-        mname = 'do_' + fore.command
-        if not hasattr(fore, mname):
-            if fore.command == 'OPTIONS':
-                return return_options(start_response)
-            multi.send_error(501, "Unsupported method (%r)" % fore.command)
-            return
-        method = getattr(fore, mname)
+                if request_version != 'HTTP/1.1' and ('Darwin/9.' not in handler.headers.get('User-Agent', '')):
+                    start_response("403 Forbidden", [])
+                    return []
+                start_response("401 Authorization required", [
+                    ('WWW-Authenticate', '%s realm="%s"' % (ae.atype,ae.realm)),
+                    # ('Connection', 'keep-alive'),
+                    ('Content-Type', 'text/html'),
+                    ('Content-Length', 4), # len(self.auth_required_msg)
+                    ])
+                return ['Blah'] # self.auth_required_msg
+            except websrv_lib.AuthRejectedExc,e:
+                start_response("403 %s" % (e.args[0],), [])
+                return []
+
+        method_name = 'do_' + handler.command
+
+        # Support the OPTIONS method even when not provided directly by the
+        # handler. TODO I would prefer to remove it and fix the handler if
+        # needed.
+        if not hasattr(handler, method_name):
+            if handler.command == 'OPTIONS':
+                return return_options(environ, start_response)
+            start_response("501 Unsupported method (%r)" % handler.command, [])
+            return []
+
+        # Finally, call the handler's method.
         try:
+            method = getattr(handler, method_name)
             method()
-            if hasattr(fore, '_flush'):
-                fore._flush()
-            response = fore.wfile.getvalue()
-            class DummySocket(StringIO.StringIO):
-                """
-                This is used to provide a StringIO to httplib.HTTPResponse
-                which, instead of taking a file object, expects a socket and
-                uses its makefile() method.
-                """
-                def makefile(self, *args, **kw):
-                    return self
-            response = httplib.HTTPResponse(DummySocket(response))
-            response.begin()
+            # The DAV handler buffers its output and provides a _flush()
+            # method.
+            getattr(handler, '_flush', lambda: None)()
+            response = parse_http_response(handler.wfile.getvalue())
             response_headers = response.getheaders()
             body = response.read()
             start_response(str(response.status) + ' ' + response.reason, response_headers)
             return [body]
-        except (AuthRejectedExc, AuthRequiredExc):
+        except (websrv_lib.AuthRejectedExc, websrv_lib.AuthRequiredExc):
             raise
         except Exception, e:
-            multi.send_error(500, "Internal error")
-            return
-    res = go()
-    if res is None:
-        start_response(multi.shared_response, multi.shared_headers)
-        return [multi.shared_body]
-    else:
-        return res
-
-# WSGI handlers provided by modules loaded with the --load command-line option.
+            start_response("500 Internal error", [])
+            return []
+
+    return wsgi_handler
+
+def parse_http_response(s):
+    """ Turn a HTTP response string into a httplib.HTTPResponse object."""
+    class DummySocket(StringIO.StringIO):
+        """
+        This is used to provide a StringIO to httplib.HTTPResponse
+        which, instead of taking a file object, expects a socket and
+        uses its makefile() method.
+        """
+        def makefile(self, *args, **kw):
+            return self
+    response = httplib.HTTPResponse(DummySocket(s))
+    response.begin()
+    return response
+
+# WSGI handlers registered through the register_wsgi_handler() function below.
 module_handlers = []
 
 def register_wsgi_handler(handler):
@@ -277,31 +388,67 @@ def application(environ, start_response):
 
     # Try all handlers until one returns some result (i.e. not None).
     wsgi_handlers = [
-        #wsgi_xmlrpc,
-        #wsgi_jsonrpc,
-        #legacy_wsgi_xmlrpc,
-        #wsgi_modules,
+        wsgi_xmlrpc_1,
+        wsgi_xmlrpc,
+        wsgi_jsonrpc,
+        wsgi_xmlrpc_legacy,
         wsgi_webdav
-        ] #+ module_handlers
+        ] + module_handlers
     for handler in wsgi_handlers:
         result = handler(environ, start_response)
         if result is None:
             continue
         return result
 
-    # We never returned from the loop. Needs something else than 200 OK.
+    # We never returned from the loop.
     response = 'No handler found.\n'
-    start_response('200 OK', [('Content-Type', 'text/plain'), ('Content-Length', str(len(response)))])
+    start_response('404 Not Found', [('Content-Type', 'text/plain'), ('Content-Length', str(len(response)))])
     return [response]
 
+# The WSGI server, started by start_server(), stopped by stop_server().
+httpd = None
+
 def serve():
-    """ Serve XMLRPC requests via wsgiref's simple_server.
+    """ Serve HTTP requests via werkzeug development server.
 
-    Blocking, should probably be called in its own process.
+    If werkzeug can not be imported, we fall back to wsgiref's simple_server.
+
+    Calling this function is blocking, you might want to call it in its own
+    thread.
     """
-    httpd = make_server('localhost', config['xmlrpc_port'], application)
+
+    global httpd
+
+    # TODO Change the xmlrpc_* options to http_*
+    interface = config['xmlrpc_interface'] or '0.0.0.0'
+    port = config['xmlrpc_port']
+    try:
+        import werkzeug.serving
+        httpd = werkzeug.serving.make_server(interface, port, application, threaded=True)
+        logging.getLogger('wsgi').info('HTTP service (werkzeug) running on %s:%s', interface, port)
+    except ImportError, e:
+        import wsgiref.simple_server
+        logging.getLogger('wsgi').warn('Werkzeug module unavailable, falling back to wsgiref.')
+        httpd = wsgiref.simple_server.make_server(interface, port, application)
+        logging.getLogger('wsgi').info('HTTP service (wsgiref) running on %s:%s', interface, port)
+
     httpd.serve_forever()
 
+def start_server():
+    """ Call serve() in its own thread.
+
+    The WSGI server can be shutdown with stop_server() below.
+    """
+    threading.Thread(target=openerp.wsgi.serve).start()
+
+def stop_server():
+    """ Initiate the shutdown of the WSGI server.
+
+    The server is supposed to have been started by start_server() above.
+    """
+    if httpd:
+        httpd.shutdown()
+
 # Master process id, can be used for signaling.
 arbiter_pid = None
 
@@ -311,27 +458,10 @@ def on_starting(server):
     global arbiter_pid
     arbiter_pid = os.getpid() # TODO check if this is true even after replacing the executable
     config = openerp.tools.config
-    config['addons_path'] = '/home/openerp/repos/addons/trunk-xmlrpc' # need a config file
-    #config['log_level'] = 10 # debug
     #openerp.tools.cache = kill_workers_cache
     openerp.netsvc.init_logger()
     openerp.osv.osv.start_object_proxy()
     openerp.service.web_services.start_web_services()
-    test_in_thread()
-
-def test_in_thread():
-    def f():
-        import time
-        time.sleep(2)
-        print ">>>> test thread"
-        cr = openerp.sql_db.db_connect('xx').cursor()
-        module_name = 'document_webdav'
-        fp = openerp.tools.file_open('/home/openerp/repos/addons/trunk-xmlrpc/document_webdav/test/webdav_test1.yml')
-        openerp.tools.convert_yaml_import(cr, module_name, fp, {}, 'update', True)
-        cr.close()
-        print "<<<< test thread"
-    import threading
-    threading.Thread(target=f).start()
 
 # Install our own signal handler on the master process.
 def when_ready(server):