"""
-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
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:
- environ['PATH_INFO'] = '/' + environ['PATH_INFO'][len(http_dir.path):]
+ path = environ['PATH_INFO'][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(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.
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
-
- # Let's pretend we have a Multi handler (i.e. the
- # websrv_lib.MultiHTTPHandler class) to hand to the auth. provider.
- multi = Dummy()
- multi.sec_realms = {}
# Initialize the underlying handler and associated auth. provider.
- handler = http_dir.handler(openerp.service.websrv_lib.noconnection(con), environ['REMOTE_ADDR'], server)
- auth_provider = http_dir.auth_provider
- auth_provider.setupAuth(multi, handler)
+ 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.
# Handle authentication if there is an auth. provider associated to
# the handler.
- if auth_provider and auth_provider.realm:
+ if hasattr(handler, 'auth_provider'):
try:
- multi.sec_realms[auth_provider.realm].checkRequest(handler, path)
+ 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 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", [
])
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],))
+ start_response("403 %s" % (e.args[0],), [])
return []
method_name = 'do_' + handler.command
# needed.
if not hasattr(handler, method_name):
if handler.command == 'OPTIONS':
- return return_options(start_response)
- start_response("501 Unsupported method (%r)" % handler.command)
+ return return_options(environ, start_response)
+ start_response("501 Unsupported method (%r)" % handler.command, [])
return []
# Finally, call the handler's method.
except (websrv_lib.AuthRejectedExc, websrv_lib.AuthRequiredExc):
raise
except Exception, e:
- start_response("500 Internal error")
+ start_response("500 Internal error", [])
return []
return wsgi_handler
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):
# 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.
+
+ If werkzeug can not be imported, we fall back to wsgiref's simple_server.
- Blocking, should probably be called in its own process.
+ 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
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):