[MERGE] forward port of branch saas-3 up to 309ca4f
[odoo/odoo.git] / openerp / tools / config.py
index 7320d29..0e5cecb 100644 (file)
@@ -1,9 +1,9 @@
-# -*- coding: utf-8 -*-
+#openerp.loggers.handlers. -*- coding: utf-8 -*-
 ##############################################################################
 #
 #    OpenERP, Open Source Management Solution
 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
-#    Copyright (C) 2010-2012 OpenERP s.a. (<http://openerp.com>).
+#    Copyright (C) 2010-2014 OpenERP s.a. (<http://openerp.com>).
 #
 #    This program is free software: you can redistribute it and/or modify
 #    it under the terms of the GNU Affero General Public License as
@@ -29,6 +29,7 @@ import openerp.conf
 import openerp.loglevels as loglevels
 import logging
 import openerp.release as release
+import appdirs
 
 class MyOption (optparse.Option, object):
     """ optparse Option with two additional attributes.
@@ -59,6 +60,18 @@ def check_ssl():
 
 DEFAULT_LOG_HANDLER = [':INFO']
 
+def _get_default_datadir():
+    home = os.path.expanduser('~')
+    if os.path.exists(home):
+        func = appdirs.user_data_dir
+    else:
+        if sys.platform in ['win32', 'darwin']:
+            func = appdirs.site_data_dir
+        else:
+            func = lambda **kwarg: "/var/lib/%s" % kwarg['appname'].lower()
+    # No "version" kwarg as session and filestore paths are shared against series
+    return func(appname=release.product_name, appauthor=release.author)
+
 class configmanager(object):
     def __init__(self, fname=None):
         # Options not exposed on the command line. Command line options will be added
@@ -72,9 +85,10 @@ class configmanager(object):
         }
 
         # Not exposed in the configuration file.
-        self.blacklist_for_save = set(
-            ['publisher_warranty_url', 'load_language', 'root_path',
-            'init', 'save', 'config', 'update', 'stop_after_init'])
+        self.blacklist_for_save = set([
+            'publisher_warranty_url', 'load_language', 'root_path',
+            'init', 'save', 'config', 'update', 'stop_after_init'
+        ])
 
         # dictionary mapping option destination (keys in self.options) to MyOptions.
         self.casts = {}
@@ -83,7 +97,10 @@ class configmanager(object):
         self.config_file = fname
         self.has_ssl = check_ssl()
 
-        self._LOGLEVELS = dict([(getattr(loglevels, 'LOG_%s' % x), getattr(logging, x)) for x in ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET')])
+        self._LOGLEVELS = dict([
+            (getattr(loglevels, 'LOG_%s' % x), getattr(logging, x)) 
+            for x in ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET')
+        ])
 
         version = "%s %s" % (release.description, release.version)
         self.parser = parser = optparse.OptionParser(version=version, option_class=MyOption)
@@ -106,6 +123,9 @@ class configmanager(object):
                          help="specify additional addons paths (separated by commas).",
                          action="callback", callback=self._check_addons_path, nargs=1, type="string")
         group.add_option("--load", dest="server_wide_modules", help="Comma-separated list of server-wide modules default=web")
+
+        group.add_option("-D", "--data-dir", dest="data_dir", my_default=_get_default_datadir(),
+                         help="Directory where to store Odoo data")
         parser.add_option_group(group)
 
         # XML-RPC / HTTP
@@ -141,23 +161,15 @@ class configmanager(object):
         parser.add_option_group(group)
 
         # WEB
-        # TODO move to web addons after MetaOption merge
         group = optparse.OptionGroup(parser, "Web interface Configuration")
         group.add_option("--db-filter", dest="dbfilter", my_default='.*',
                          help="Filter listed database", metavar="REGEXP")
         parser.add_option_group(group)
 
-        # Static HTTP
-        group = optparse.OptionGroup(parser, "Static HTTP service")
-        group.add_option("--static-http-enable", dest="static_http_enable", action="store_true", my_default=False, help="enable static HTTP service for serving plain HTML files")
-        group.add_option("--static-http-document-root", dest="static_http_document_root", help="specify the directory containing your static HTML files (e.g '/var/www/')")
-        group.add_option("--static-http-url-prefix", dest="static_http_url_prefix", help="specify the URL root prefix where you want web browsers to access your static HTML files (e.g '/')")
-        parser.add_option_group(group)
-
         # Testing Group
         group = optparse.OptionGroup(parser, "Testing Configuration")
         group.add_option("--test-file", dest="test_file", my_default=False,
-                         help="Launch a YML test file.")
+                         help="Launch a python or YML test file.")
         group.add_option("--test-report-directory", dest="test_report_directory", my_default=False,
                          help="If set, will save sample of all reports in this directory.")
         group.add_option("--test-enable", action="store_true", dest="test_enable",
@@ -172,16 +184,20 @@ class configmanager(object):
         group.add_option("--logrotate", dest="logrotate", action="store_true", my_default=False, help="enable logfile rotation")
         group.add_option("--syslog", action="store_true", dest="syslog", my_default=False, help="Send the log to the syslog server")
         group.add_option('--log-handler', action="append", default=DEFAULT_LOG_HANDLER, my_default=DEFAULT_LOG_HANDLER, metavar="PREFIX:LEVEL", help='setup a handler at LEVEL for a given PREFIX. An empty PREFIX indicates the root logger. This option can be repeated. Example: "openerp.orm:DEBUG" or "werkzeug:CRITICAL" (default: ":INFO")')
-        group.add_option('--log-request', action="append_const", dest="log_handler", const="openerp.netsvc.rpc.request:DEBUG", help='shortcut for --log-handler=openerp.netsvc.rpc.request:DEBUG')
-        group.add_option('--log-response', action="append_const", dest="log_handler", const="openerp.netsvc.rpc.response:DEBUG", help='shortcut for --log-handler=openerp.netsvc.rpc.response:DEBUG')
-        group.add_option('--log-web', action="append_const", dest="log_handler", const="openerp.addons.web.http:DEBUG", help='shortcut for --log-handler=openerp.addons.web.http:DEBUG')
+        group.add_option('--log-request', action="append_const", dest="log_handler", const="openerp.http.rpc.request:DEBUG", help='shortcut for --log-handler=openerp.http.rpc.request:DEBUG')
+        group.add_option('--log-response', action="append_const", dest="log_handler", const="openerp.http.rpc.response:DEBUG", help='shortcut for --log-handler=openerp.http.rpc.response:DEBUG')
+        group.add_option('--log-web', action="append_const", dest="log_handler", const="openerp.http:DEBUG", help='shortcut for --log-handler=openerp.http:DEBUG')
         group.add_option('--log-sql', action="append_const", dest="log_handler", const="openerp.sql_db:DEBUG", help='shortcut for --log-handler=openerp.sql_db:DEBUG')
+        group.add_option('--log-db', dest='log_db', help="Logging database", my_default=False)
         # For backward-compatibility, map the old log levels to something
         # quite close.
-        levels = ['info', 'debug_rpc', 'warn', 'test', 'critical',
-            'debug_sql', 'error', 'debug', 'debug_rpc_answer', 'notset']
-        group.add_option('--log-level', dest='log_level', type='choice', choices=levels,
-            my_default='info', help='specify the level of the logging. Accepted values: ' + str(levels) + ' (deprecated option).')
+        levels = [
+            'info', 'debug_rpc', 'warn', 'test', 'critical',
+            'debug_sql', 'error', 'debug', 'debug_rpc_answer', 'notset'
+        ]
+        group.add_option('--log-level', dest='log_level', type='choice',
+                         choices=levels, my_default='info',
+                         help='specify the level of the logging. Accepted values: %s (deprecated option).' % (levels,))
 
         parser.add_option_group(group)
 
@@ -220,7 +236,7 @@ class configmanager(object):
         parser.add_option_group(group)
 
         group = optparse.OptionGroup(parser, "Internationalisation options",
-            "Use these options to translate OpenERP to another language."
+            "Use these options to translate Odoo to another language."
             "See i18n section of the user manual. Option '-d' is mandatory."
             "Option '-l' is mandatory in case of importation"
             )
@@ -245,7 +261,8 @@ class configmanager(object):
 
         # Advanced options
         group = optparse.OptionGroup(parser, "Advanced options")
-        group.add_option('--auto-reload', dest='auto_reload', action='store_true', my_default=False, help='enable auto reload')
+        if os.name == 'posix':
+            group.add_option('--auto-reload', dest='auto_reload', action='store_true', my_default=False, help='enable auto reload')
         group.add_option('--debug', dest='debug_mode', action='store_true', my_default=False, help='enable debug mode')
         group.add_option("--stop-after-init", action="store_true", dest="stop_after_init", my_default=False,
                           help="stop the server after its initialization")
@@ -265,29 +282,32 @@ class configmanager(object):
                          type="int")
         group.add_option("--unaccent", dest="unaccent", my_default=False, action="store_true",
                          help="Use the unaccent function provided by the database when available.")
+        group.add_option("--geoip-db", dest="geoip_database", my_default='/usr/share/GeoIP/GeoLiteCity.dat',
+                         help="Absolute path to the GeoIP database file.")
         parser.add_option_group(group)
 
-        group = optparse.OptionGroup(parser, "Multiprocessing options")
-        # TODO sensible default for the three following limits.
-        group.add_option("--workers", dest="workers", my_default=0,
-                         help="Specify the number of workers, 0 disable prefork mode.",
-                         type="int")
-        group.add_option("--limit-memory-soft", dest="limit_memory_soft", my_default=640 * 1024 * 1024,
-                         help="Maximum allowed virtual memory per worker, when reached the worker be reset after the current request (default 671088640 aka 640MB).",
-                         type="int")
-        group.add_option("--limit-memory-hard", dest="limit_memory_hard", my_default=768 * 1024 * 1024,
-                         help="Maximum allowed virtual memory per worker, when reached, any memory allocation will fail (default 805306368 aka 768MB).",
-                         type="int")
-        group.add_option("--limit-time-cpu", dest="limit_time_cpu", my_default=60,
-                         help="Maximum allowed CPU time per request (default 60).",
-                         type="int")
-        group.add_option("--limit-time-real", dest="limit_time_real", my_default=120,
-                         help="Maximum allowed Real time per request (default 120).",
-                         type="int")
-        group.add_option("--limit-request", dest="limit_request", my_default=8192,
-                         help="Maximum number of request to be processed per worker (default 8192).",
-                         type="int")
-        parser.add_option_group(group)
+        if os.name == 'posix':
+            group = optparse.OptionGroup(parser, "Multiprocessing options")
+            # TODO sensible default for the three following limits.
+            group.add_option("--workers", dest="workers", my_default=0,
+                             help="Specify the number of workers, 0 disable prefork mode.",
+                             type="int")
+            group.add_option("--limit-memory-soft", dest="limit_memory_soft", my_default=2048 * 1024 * 1024,
+                             help="Maximum allowed virtual memory per worker, when reached the worker be reset after the current request (default 671088640 aka 640MB).",
+                             type="int")
+            group.add_option("--limit-memory-hard", dest="limit_memory_hard", my_default=2560 * 1024 * 1024,
+                             help="Maximum allowed virtual memory per worker, when reached, any memory allocation will fail (default 805306368 aka 768MB).",
+                             type="int")
+            group.add_option("--limit-time-cpu", dest="limit_time_cpu", my_default=60,
+                             help="Maximum allowed CPU time per request (default 60).",
+                             type="int")
+            group.add_option("--limit-time-real", dest="limit_time_real", my_default=120,
+                             help="Maximum allowed Real time per request (default 120).",
+                             type="int")
+            group.add_option("--limit-request", dest="limit_request", my_default=8192,
+                             help="Maximum number of request to be processed per worker (default 8192).",
+                             type="int")
+            parser.add_option_group(group)
 
         # Copy all optparse options (i.e. MyOption) into self.options.
         for group in parser.option_groups:
@@ -296,9 +316,10 @@ class configmanager(object):
                     self.options[option.dest] = option.my_default
                     self.casts[option.dest] = option
 
-        self.parse_config(None, False)
+        # generate default config
+        self._parse_config()
 
-    def parse_config(self, args=None, complete=True):
+    def parse_config(self, args=None):
         """ Parse the configuration file (if any) and the command-line
         arguments.
 
@@ -312,10 +333,12 @@ class configmanager(object):
         Typical usage of this method:
 
             openerp.tools.config.parse_config(sys.argv[1:])
-
-        :param complete: this is a hack used in __init__(), leave it to True.
-
         """
+        self._parse_config(args)
+        openerp.netsvc.init_logger()
+        openerp.modules.module.initialize_sys_path()
+
+    def _parse_config(self, args=None):
         if args is None:
             args = []
         opt, args = self.parser.parse_args(args)
@@ -348,6 +371,7 @@ class configmanager(object):
         # (../etc from the server)
         # if the server is run by an unprivileged user, he has to specify location of a config file where he has the rights to write,
         # else he won't be able to save the configurations, or even to start the server...
+        # TODO use appdirs
         if os.name == 'nt':
             rcfilepath = os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), 'openerp-server.conf')
         else:
@@ -358,7 +382,6 @@ class configmanager(object):
                 or os.environ.get('OPENERP_SERVER') or rcfilepath)
         self.load()
 
-
         # Verify that we want to log or not, if not the output will go to stdout
         if self.options['logfile'] in ('None', 'False'):
             self.options['logfile'] = False
@@ -374,9 +397,9 @@ class configmanager(object):
                 'db_maxconn', 'import_partial', 'addons_path',
                 'xmlrpc', 'syslog', 'without_demo', 'timezone',
                 'xmlrpcs_interface', 'xmlrpcs_port', 'xmlrpcs',
-                'static_http_enable', 'static_http_document_root', 'static_http_url_prefix',
-                'secure_cert_file', 'secure_pkey_file', 'dbfilter', 'log_handler', 'log_level'
-                ]
+                'secure_cert_file', 'secure_pkey_file', 'dbfilter', 'log_handler', 'log_level', 'log_db',
+                'geoip_database',
+        ]
 
         for arg in keys:
             # Copy the command-line argument (except the special case for log_handler, due to
@@ -387,7 +410,6 @@ class configmanager(object):
             elif isinstance(self.options[arg], basestring) and self.casts[arg].type in optparse.Option.TYPE_CHECKER:
                 self.options[arg] = optparse.Option.TYPE_CHECKER[self.casts[arg].type](self.casts[arg], arg, self.options[arg])
 
-
         if isinstance(self.options['log_handler'], basestring):
             self.options['log_handler'] = self.options['log_handler'].split(',')
 
@@ -399,11 +421,22 @@ class configmanager(object):
             'list_db', 'xmlrpcs', 'proxy_mode',
             'test_file', 'test_enable', 'test_commit', 'test_report_directory',
             'osv_memory_count_limit', 'osv_memory_age_limit', 'max_cron_threads', 'unaccent',
-            'workers', 'limit_memory_hard', 'limit_memory_soft', 'limit_time_cpu', 'limit_time_real', 'limit_request', 'auto_reload'
+            'data_dir',
+        ]
+
+        posix_keys = [
+            'auto_reload', 'workers',
+            'limit_memory_hard', 'limit_memory_soft',
+            'limit_time_cpu', 'limit_time_real', 'limit_request',
         ]
 
+        if os.name == 'posix':
+            keys += posix_keys
+        else:
+            self.options.update(dict.fromkeys(posix_keys, None))
+
+        # Copy the command-line arguments...
         for arg in keys:
-            # Copy the command-line argument...
             if getattr(opt, arg) is not None:
                 self.options[arg] = getattr(opt, arg)
             # ... or keep, but cast, the config file value.
@@ -412,7 +445,9 @@ class configmanager(object):
 
         self.options['root_path'] = os.path.abspath(os.path.expanduser(os.path.expandvars(os.path.dirname(openerp.__file__))))
         if not self.options['addons_path'] or self.options['addons_path']=='None':
-            self.options['addons_path'] = os.path.join(self.options['root_path'], 'addons')
+            base_addons = os.path.join(self.options['root_path'], 'addons')
+            main_addons = os.path.abspath(os.path.join(self.options['root_path'], '../addons'))
+            self.options['addons_path'] = '%s,%s' % (base_addons, main_addons)
         else:
             self.options['addons_path'] = ",".join(
                     os.path.abspath(os.path.expanduser(os.path.expandvars(x)))
@@ -476,8 +511,6 @@ class configmanager(object):
             openerp.conf.server_wide_modules = map(lambda m: m.strip(), opt.server_wide_modules.split(','))
         else:
             openerp.conf.server_wide_modules = ['web','web_kanban']
-        if complete:
-            openerp.modules.module.initialize_sys_path()
 
     def _generate_pgpassfile(self):
         """
@@ -617,6 +650,27 @@ class configmanager(object):
     def __getitem__(self, key):
         return self.options[key]
 
+    @property
+    def addons_data_dir(self):
+        d = os.path.join(self['data_dir'], 'addons', release.series)
+        if not os.path.exists(d):
+            os.makedirs(d, 0700)
+        else:
+            os.chmod(d, 0700)
+        return d
+
+    @property
+    def session_dir(self):
+        d = os.path.join(self['data_dir'], 'sessions')
+        if not os.path.exists(d):
+            os.makedirs(d, 0700)
+        else:
+            os.chmod(d, 0700)
+        return d
+
+    def filestore(self, dbname):
+        return os.path.join(self['data_dir'], 'filestore', dbname)
+
 config = configmanager()