[IMP] account_voucher: added case2_usd_eur_debtor_in_eur.yml
[odoo/odoo.git] / openerp / wsgi.py
index 6e9dd5e..5a8f19f 100644 (file)
@@ -25,21 +25,21 @@ 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 openerp
 import openerp.tools.config as config
-import openerp.service.websrv_lib as websrv_lib
+import service.websrv_lib as websrv_lib
 
 def xmlrpc_return(start_response, service, method, params):
     """ Helper to call a service's method with some params, using a
@@ -107,17 +107,9 @@ def legacy_wsgi_xmlrpc(environ, start_response):
 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)
-
-    # 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)
+        return return_options(environ, start_response)
 
     http_dir = websrv_lib.find_http_service(environ['PATH_INFO'])
     if http_dir:
@@ -125,18 +117,23 @@ def wsgi_webdav(environ, start_response):
         if path.startswith('/'):
             environ['PATH_INFO'] = path
         else:
-            environ['PATH_INFO'] = '/' + npath
+            environ['PATH_INFO'] = '/' + path
         return http_to_wsgi(http_dir)(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')]
+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 []
 
 def http_to_wsgi(http_dir):
     """
-    Turn BaseHTTPRequestHandler into a WSGI entry point.
+    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.
@@ -175,10 +172,10 @@ def http_to_wsgi(http_dir):
         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 TODO
 
         # Initialize the underlying handler and associated auth. provider.
-        handler = http_dir.instanciate_handler(openerp.service.websrv_lib.noconnection(con), environ['REMOTE_ADDR'], server)
+        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.
@@ -201,7 +198,6 @@ def http_to_wsgi(http_dir):
                 # 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 handler.headers.get('User-Agent', '')):
-                    print 'self.log_error("Cannot require auth at %s", self.request_version)'
                     start_response("403 Forbidden", [])
                     return []
                 start_response("401 Authorization required", [
@@ -212,7 +208,6 @@ def http_to_wsgi(http_dir):
                     ])
                 return ['Blah'] # self.auth_required_msg
             except websrv_lib.AuthRejectedExc,e:
-                print '("Rejected auth: %s" % e.args[0])'
                 start_response("403 %s" % (e.args[0],), [])
                 return []
 
@@ -223,7 +218,7 @@ def http_to_wsgi(http_dir):
         # needed.
         if not hasattr(handler, method_name):
             if handler.command == 'OPTIONS':
-                return return_options(start_response)
+                return return_options(environ, start_response)
             start_response("501 Unsupported method (%r)" % handler.command, [])
             return []
 
@@ -261,7 +256,7 @@ def parse_http_response(s):
     response.begin()
     return response
 
-# WSGI handlers provided by modules loaded with the --load command-line option.
+# WSGI handlers registered through the register_wsgi_handler() function below.
 module_handlers = []
 
 def register_wsgi_handler(handler):
@@ -277,31 +272,66 @@ 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,
+        wsgi_jsonrpc,
+        legacy_wsgi_xmlrpc,
         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 +341,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):