gooderp18绿色标准版
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

809 行
43KB

  1. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  2. import configparser as ConfigParser
  3. import errno
  4. import logging
  5. import optparse
  6. import glob
  7. import os
  8. import sys
  9. import tempfile
  10. import warnings
  11. import odoo
  12. from os.path import expandvars, expanduser, abspath, realpath, normcase
  13. from .. import release, conf, loglevels
  14. from . import appdirs
  15. from passlib.context import CryptContext
  16. crypt_context = CryptContext(schemes=['pbkdf2_sha512', 'plaintext'],
  17. deprecated=['plaintext'],
  18. pbkdf2_sha512__rounds=600_000)
  19. class MyOption (optparse.Option, object):
  20. """ optparse Option with two additional attributes.
  21. The list of command line options (getopt.Option) is used to create the
  22. list of the configuration file options. When reading the file, and then
  23. reading the command line arguments, we don't want optparse.parse results
  24. to override the configuration file values. But if we provide default
  25. values to optparse, optparse will return them and we can't know if they
  26. were really provided by the user or not. A solution is to not use
  27. optparse's default attribute, but use a custom one (that will be copied
  28. to create the default values of the configuration file).
  29. """
  30. def __init__(self, *opts, **attrs):
  31. self.my_default = attrs.pop('my_default', None)
  32. super(MyOption, self).__init__(*opts, **attrs)
  33. DEFAULT_LOG_HANDLER = ':INFO'
  34. def _get_default_datadir():
  35. home = os.path.expanduser('~')
  36. if os.path.isdir(home):
  37. func = appdirs.user_data_dir
  38. else:
  39. if sys.platform in ['win32', 'darwin']:
  40. func = appdirs.site_data_dir
  41. else:
  42. func = lambda **kwarg: "/var/lib/%s" % kwarg['appname'].lower()
  43. # No "version" kwarg as session and filestore paths are shared against series
  44. return func(appname=release.product_name, appauthor=release.author)
  45. def _deduplicate_loggers(loggers):
  46. """ Avoid saving multiple logging levels for the same loggers to a save
  47. file, that just takes space and the list can potentially grow unbounded
  48. if for some odd reason people use :option`--save`` all the time.
  49. """
  50. # dict(iterable) -> the last item of iterable for any given key wins,
  51. # which is what we want and expect. Output order should not matter as
  52. # there are no duplicates within the output sequence
  53. return (
  54. '{}:{}'.format(logger, level)
  55. for logger, level in dict(it.split(':') for it in loggers).items()
  56. )
  57. class configmanager(object):
  58. def __init__(self, fname=None):
  59. """Constructor.
  60. :param fname: a shortcut allowing to instantiate :class:`configmanager`
  61. from Python code without resorting to environment
  62. variable
  63. """
  64. # Options not exposed on the command line. Command line options will be added
  65. # from optparse's parser.
  66. self.options = {
  67. 'admin_passwd': 'admin',
  68. 'csv_internal_sep': ',',
  69. 'publisher_warranty_url': 'http://services.odoo.com/publisher-warranty/',
  70. 'reportgz': False,
  71. 'root_path': None,
  72. 'websocket_keep_alive_timeout': 3600,
  73. 'websocket_rate_limit_burst': 10,
  74. 'websocket_rate_limit_delay': 0.2,
  75. }
  76. # Not exposed in the configuration file.
  77. self.blacklist_for_save = set([
  78. 'publisher_warranty_url', 'load_language', 'root_path',
  79. 'init', 'save', 'config', 'update', 'stop_after_init', 'dev_mode', 'shell_interface',
  80. ])
  81. # dictionary mapping option destination (keys in self.options) to MyOptions.
  82. self.casts = {}
  83. self.misc = {}
  84. self.config_file = fname
  85. self._LOGLEVELS = dict([
  86. (getattr(loglevels, 'LOG_%s' % x), getattr(logging, x))
  87. for x in ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'NOTSET')
  88. ])
  89. version = "%s %s" % (release.description, release.version)
  90. self.parser = parser = optparse.OptionParser(version=version, option_class=MyOption)
  91. # Server startup config
  92. group = optparse.OptionGroup(parser, "Common options")
  93. group.add_option("-c", "--config", dest="config", help="specify alternate config file")
  94. group.add_option("-s", "--save", action="store_true", dest="save", default=False,
  95. help="save configuration to ~/.odoorc (or to ~/.openerp_serverrc if it exists)")
  96. group.add_option("-i", "--init", dest="init", help="install one or more modules (comma-separated list, use \"all\" for all modules), requires -d")
  97. group.add_option("-u", "--update", dest="update",
  98. help="update one or more modules (comma-separated list, use \"all\" for all modules). Requires -d.")
  99. group.add_option("--without-demo", dest="without_demo",
  100. help="disable loading demo data for modules to be installed (comma-separated, use \"all\" for all modules). Requires -d and -i. Default is %default",
  101. my_default=False)
  102. group.add_option("-P", "--import-partial", dest="import_partial", my_default='',
  103. help="Use this for big data importation, if it crashes you will be able to continue at the current state. Provide a filename to store intermediate importation states.")
  104. group.add_option("--pidfile", dest="pidfile", help="file where the server pid will be stored")
  105. group.add_option("--addons-path", dest="addons_path",
  106. help="specify additional addons paths (separated by commas).",
  107. action="callback", callback=self._check_addons_path, nargs=1, type="string")
  108. group.add_option("--upgrade-path", dest="upgrade_path",
  109. help="specify an additional upgrade path.",
  110. action="callback", callback=self._check_upgrade_path, nargs=1, type="string")
  111. group.add_option("--load", dest="server_wide_modules", help="Comma-separated list of server-wide modules.", my_default='base,web')
  112. group.add_option("-D", "--data-dir", dest="data_dir", my_default=_get_default_datadir(),
  113. help="Directory where to store Odoo data")
  114. parser.add_option_group(group)
  115. # HTTP
  116. group = optparse.OptionGroup(parser, "HTTP Service Configuration")
  117. group.add_option("--http-interface", dest="http_interface", my_default='',
  118. help="Listen interface address for HTTP services. "
  119. "Keep empty to listen on all interfaces (0.0.0.0)")
  120. group.add_option("-p", "--http-port", dest="http_port", my_default=8069,
  121. help="Listen port for the main HTTP service", type="int", metavar="PORT")
  122. group.add_option("--gevent-port", dest="gevent_port", my_default=8072,
  123. help="Listen port for the gevent worker", type="int", metavar="PORT")
  124. group.add_option("--no-http", dest="http_enable", action="store_false", my_default=True,
  125. help="Disable the HTTP and Longpolling services entirely")
  126. group.add_option("--proxy-mode", dest="proxy_mode", action="store_true", my_default=False,
  127. help="Activate reverse proxy WSGI wrappers (headers rewriting) "
  128. "Only enable this when running behind a trusted web proxy!")
  129. group.add_option("--x-sendfile", dest="x_sendfile", action="store_true", my_default=False,
  130. help="Activate X-Sendfile (apache) and X-Accel-Redirect (nginx) "
  131. "HTTP response header to delegate the delivery of large "
  132. "files (assets/attachments) to the web server.")
  133. # HTTP: hidden backwards-compatibility for "*xmlrpc*" options
  134. hidden = optparse.SUPPRESS_HELP
  135. group.add_option("--xmlrpc-interface", dest="http_interface", help=hidden)
  136. group.add_option("--xmlrpc-port", dest="http_port", type="int", help=hidden)
  137. group.add_option("--no-xmlrpc", dest="http_enable", action="store_false", help=hidden)
  138. parser.add_option_group(group)
  139. # WEB
  140. group = optparse.OptionGroup(parser, "Web interface Configuration")
  141. group.add_option("--db-filter", dest="dbfilter", my_default='', metavar="REGEXP",
  142. help="Regular expressions for filtering available databases for Web UI. "
  143. "The expression can use %d (domain) and %h (host) placeholders.")
  144. parser.add_option_group(group)
  145. # Testing Group
  146. group = optparse.OptionGroup(parser, "Testing Configuration")
  147. group.add_option("--test-file", dest="test_file", my_default=False,
  148. help="Launch a python test file.")
  149. group.add_option("--test-enable", action="callback", callback=self._test_enable_callback,
  150. dest='test_enable',
  151. help="Enable unit tests.")
  152. group.add_option("--test-tags", dest="test_tags",
  153. help="Comma-separated list of specs to filter which tests to execute. Enable unit tests if set. "
  154. "A filter spec has the format: [-][tag][/module][:class][.method] "
  155. "The '-' specifies if we want to include or exclude tests matching this spec. "
  156. "The tag will match tags added on a class with a @tagged decorator "
  157. "(all Test classes have 'standard' and 'at_install' tags "
  158. "until explicitly removed, see the decorator documentation). "
  159. "'*' will match all tags. "
  160. "If tag is omitted on include mode, its value is 'standard'. "
  161. "If tag is omitted on exclude mode, its value is '*'. "
  162. "The module, class, and method will respectively match the module name, test class name and test method name. "
  163. "Example: --test-tags :TestClass.test_func,/test_module,external "
  164. "Filtering and executing the tests happens twice: right "
  165. "after each module installation/update and at the end "
  166. "of the modules loading. At each stage tests are filtered "
  167. "by --test-tags specs and additionally by dynamic specs "
  168. "'at_install' and 'post_install' correspondingly.")
  169. group.add_option("--screencasts", dest="screencasts", action="store", my_default=None,
  170. metavar='DIR',
  171. help="Screencasts will go in DIR/{db_name}/screencasts.")
  172. temp_tests_dir = os.path.join(tempfile.gettempdir(), 'odoo_tests')
  173. group.add_option("--screenshots", dest="screenshots", action="store", my_default=temp_tests_dir,
  174. metavar='DIR',
  175. help="Screenshots will go in DIR/{db_name}/screenshots. Defaults to %s." % temp_tests_dir)
  176. parser.add_option_group(group)
  177. # Logging Group
  178. group = optparse.OptionGroup(parser, "Logging Configuration")
  179. group.add_option("--logfile", dest="logfile", help="file where the server log will be stored")
  180. group.add_option("--syslog", action="store_true", dest="syslog", my_default=False, help="Send the log to the syslog server")
  181. group.add_option('--log-handler', action="append", default=[], 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: "odoo.orm:DEBUG" or "werkzeug:CRITICAL" (default: ":INFO")')
  182. group.add_option('--log-web', action="append_const", dest="log_handler", const="odoo.http:DEBUG", help='shortcut for --log-handler=odoo.http:DEBUG')
  183. group.add_option('--log-sql', action="append_const", dest="log_handler", const="odoo.sql_db:DEBUG", help='shortcut for --log-handler=odoo.sql_db:DEBUG')
  184. group.add_option('--log-db', dest='log_db', help="Logging database", my_default=False)
  185. group.add_option('--log-db-level', dest='log_db_level', my_default='warning', help="Logging database level")
  186. # For backward-compatibility, map the old log levels to something
  187. # quite close.
  188. levels = [
  189. 'info', 'debug_rpc', 'warn', 'test', 'critical', 'runbot',
  190. 'debug_sql', 'error', 'debug', 'debug_rpc_answer', 'notset'
  191. ]
  192. group.add_option('--log-level', dest='log_level', type='choice',
  193. choices=levels, my_default='info',
  194. help='specify the level of the logging. Accepted values: %s.' % (levels,))
  195. parser.add_option_group(group)
  196. # SMTP Group
  197. group = optparse.OptionGroup(parser, "SMTP Configuration")
  198. group.add_option('--email-from', dest='email_from', my_default=False,
  199. help='specify the SMTP email address for sending email')
  200. group.add_option('--from-filter', dest='from_filter', my_default=False,
  201. help='specify for which email address the SMTP configuration can be used')
  202. group.add_option('--smtp', dest='smtp_server', my_default='localhost',
  203. help='specify the SMTP server for sending email')
  204. group.add_option('--smtp-port', dest='smtp_port', my_default=25,
  205. help='specify the SMTP port', type="int")
  206. group.add_option('--smtp-ssl', dest='smtp_ssl', action='store_true', my_default=False,
  207. help='if passed, SMTP connections will be encrypted with SSL (STARTTLS)')
  208. group.add_option('--smtp-user', dest='smtp_user', my_default=False,
  209. help='specify the SMTP username for sending email')
  210. group.add_option('--smtp-password', dest='smtp_password', my_default=False,
  211. help='specify the SMTP password for sending email')
  212. group.add_option('--smtp-ssl-certificate-filename', dest='smtp_ssl_certificate_filename', my_default=False,
  213. help='specify the SSL certificate used for authentication')
  214. group.add_option('--smtp-ssl-private-key-filename', dest='smtp_ssl_private_key_filename', my_default=False,
  215. help='specify the SSL private key used for authentication')
  216. parser.add_option_group(group)
  217. group = optparse.OptionGroup(parser, "Database related options")
  218. group.add_option("-d", "--database", dest="db_name", my_default=False,
  219. help="specify the database name")
  220. group.add_option("-r", "--db_user", dest="db_user", my_default=False,
  221. help="specify the database user name")
  222. group.add_option("-w", "--db_password", dest="db_password", my_default=False,
  223. help="specify the database password")
  224. group.add_option("--pg_path", dest="pg_path", help="specify the pg executable path")
  225. group.add_option("--db_host", dest="db_host", my_default=False,
  226. help="specify the database host")
  227. group.add_option("--db_replica_host", dest="db_replica_host", my_default=False,
  228. help="specify the replica host. Specify an empty db_replica_host to use the default unix socket.")
  229. group.add_option("--db_port", dest="db_port", my_default=False,
  230. help="specify the database port", type="int")
  231. group.add_option("--db_replica_port", dest="db_replica_port", my_default=False,
  232. help="specify the replica port", type="int")
  233. group.add_option("--db_sslmode", dest="db_sslmode", type="choice", my_default='prefer',
  234. choices=['disable', 'allow', 'prefer', 'require', 'verify-ca', 'verify-full'],
  235. help="specify the database ssl connection mode (see PostgreSQL documentation)")
  236. group.add_option("--db_maxconn", dest="db_maxconn", type='int', my_default=64,
  237. help="specify the maximum number of physical connections to PostgreSQL")
  238. group.add_option("--db_maxconn_gevent", dest="db_maxconn_gevent", type='int', my_default=False,
  239. help="specify the maximum number of physical connections to PostgreSQL specifically for the gevent worker")
  240. group.add_option("--db-template", dest="db_template", my_default="template0",
  241. help="specify a custom database template to create a new database")
  242. parser.add_option_group(group)
  243. group = optparse.OptionGroup(parser, "Internationalisation options",
  244. "Use these options to translate Odoo to another language. "
  245. "See i18n section of the user manual. Option '-d' is mandatory. "
  246. "Option '-l' is mandatory in case of importation"
  247. )
  248. group.add_option('--load-language', dest="load_language",
  249. help="specifies the languages for the translations you want to be loaded")
  250. group.add_option('-l', "--language", dest="language",
  251. help="specify the language of the translation file. Use it with --i18n-export or --i18n-import")
  252. group.add_option("--i18n-export", dest="translate_out",
  253. help="export all sentences to be translated to a CSV file, a PO file or a TGZ archive and exit")
  254. group.add_option("--i18n-import", dest="translate_in",
  255. help="import a CSV or a PO file with translations and exit. The '-l' option is required.")
  256. group.add_option("--i18n-overwrite", dest="overwrite_existing_translations", action="store_true", my_default=False,
  257. help="overwrites existing translation terms on updating a module or importing a CSV or a PO file.")
  258. group.add_option("--modules", dest="translate_modules",
  259. help="specify modules to export. Use in combination with --i18n-export")
  260. parser.add_option_group(group)
  261. security = optparse.OptionGroup(parser, 'Security-related options')
  262. security.add_option('--no-database-list', action="store_false", dest='list_db', my_default=True,
  263. help="Disable the ability to obtain or view the list of databases. "
  264. "Also disable access to the database manager and selector, "
  265. "so be sure to set a proper --database parameter first")
  266. parser.add_option_group(security)
  267. # Advanced options
  268. group = optparse.OptionGroup(parser, "Advanced options")
  269. group.add_option('--dev', dest='dev_mode', type="string",
  270. help="Enable developer mode. Param: List of options separated by comma. "
  271. "Options : all, reload, qweb, xml")
  272. group.add_option('--shell-interface', dest='shell_interface', type="string",
  273. help="Specify a preferred REPL to use in shell mode. Supported REPLs are: "
  274. "[ipython|ptpython|bpython|python]")
  275. group.add_option("--stop-after-init", action="store_true", dest="stop_after_init", my_default=False,
  276. help="stop the server after its initialization")
  277. group.add_option("--osv-memory-count-limit", dest="osv_memory_count_limit", my_default=0,
  278. help="Force a limit on the maximum number of records kept in the virtual "
  279. "osv_memory tables. By default there is no limit.",
  280. type="int")
  281. group.add_option("--transient-age-limit", dest="transient_age_limit", my_default=1.0,
  282. help="Time limit (decimal value in hours) records created with a "
  283. "TransientModel (mostly wizard) are kept in the database. Default to 1 hour.",
  284. type="float")
  285. group.add_option("--max-cron-threads", dest="max_cron_threads", my_default=2,
  286. help="Maximum number of threads processing concurrently cron jobs (default 2).",
  287. type="int")
  288. group.add_option("--limit-time-worker-cron", dest="limit_time_worker_cron", my_default=0,
  289. help="Maximum time a cron thread/worker stays alive before it is restarted. "
  290. "Set to 0 to disable. (default: 0)",
  291. type="int")
  292. group.add_option("--unaccent", dest="unaccent", my_default=False, action="store_true",
  293. help="Try to enable the unaccent extension when creating new databases.")
  294. group.add_option("--geoip-city-db", "--geoip-db", dest="geoip_city_db", my_default='/usr/share/GeoIP/GeoLite2-City.mmdb',
  295. help="Absolute path to the GeoIP City database file.")
  296. group.add_option("--geoip-country-db", dest="geoip_country_db", my_default='/usr/share/GeoIP/GeoLite2-Country.mmdb',
  297. help="Absolute path to the GeoIP Country database file.")
  298. parser.add_option_group(group)
  299. if os.name == 'posix':
  300. group = optparse.OptionGroup(parser, "Multiprocessing options")
  301. # TODO sensible default for the three following limits.
  302. group.add_option("--workers", dest="workers", my_default=0,
  303. help="Specify the number of workers, 0 disable prefork mode.",
  304. type="int")
  305. group.add_option("--limit-memory-soft", dest="limit_memory_soft", my_default=2048 * 1024 * 1024,
  306. help="Maximum allowed virtual memory per worker (in bytes), when reached the worker be "
  307. "reset after the current request (default 2048MiB).",
  308. type="int")
  309. group.add_option("--limit-memory-soft-gevent", dest="limit_memory_soft_gevent", my_default=False,
  310. help="Maximum allowed virtual memory per gevent worker (in bytes), when reached the worker will be "
  311. "reset after the current request. Defaults to `--limit-memory-soft`.",
  312. type="int")
  313. group.add_option("--limit-memory-hard", dest="limit_memory_hard", my_default=2560 * 1024 * 1024,
  314. help="Maximum allowed virtual memory per worker (in bytes), when reached, any memory "
  315. "allocation will fail (default 2560MiB).",
  316. type="int")
  317. group.add_option("--limit-memory-hard-gevent", dest="limit_memory_hard_gevent", my_default=False,
  318. help="Maximum allowed virtual memory per gevent worker (in bytes), when reached, any memory "
  319. "allocation will fail. Defaults to `--limit-memory-hard`.",
  320. type="int")
  321. group.add_option("--limit-time-cpu", dest="limit_time_cpu", my_default=60,
  322. help="Maximum allowed CPU time per request (default 60).",
  323. type="int")
  324. group.add_option("--limit-time-real", dest="limit_time_real", my_default=120,
  325. help="Maximum allowed Real time per request (default 120).",
  326. type="int")
  327. group.add_option("--limit-time-real-cron", dest="limit_time_real_cron", my_default=-1,
  328. help="Maximum allowed Real time per cron job. (default: --limit-time-real). "
  329. "Set to 0 for no limit. ",
  330. type="int")
  331. group.add_option("--limit-request", dest="limit_request", my_default=2**16,
  332. help="Maximum number of request to be processed per worker (default 65536).",
  333. type="int")
  334. parser.add_option_group(group)
  335. # Copy all optparse options (i.e. MyOption) into self.options.
  336. for group in parser.option_groups:
  337. for option in group.option_list:
  338. if option.dest not in self.options:
  339. self.options[option.dest] = option.my_default
  340. self.casts[option.dest] = option
  341. # generate default config
  342. self._parse_config()
  343. def parse_config(self, args: list[str] | None = None, *, setup_logging: bool | None = None) -> None:
  344. """ Parse the configuration file (if any) and the command-line
  345. arguments.
  346. This method initializes odoo.tools.config and openerp.conf (the
  347. former should be removed in the future) with library-wide
  348. configuration values.
  349. This method must be called before proper usage of this library can be
  350. made.
  351. Typical usage of this method:
  352. odoo.tools.config.parse_config(sys.argv[1:])
  353. """
  354. opt = self._parse_config(args)
  355. if setup_logging is not False:
  356. odoo.netsvc.init_logger()
  357. # warn after having done setup, so it has a chance to show up
  358. # (mostly once this warning is bumped to DeprecationWarning proper)
  359. if setup_logging is None:
  360. warnings.warn(
  361. "As of Odoo 18, it's recommended to specify whether"
  362. " you want Odoo to setup its own logging (or want to"
  363. " handle it yourself)",
  364. category=PendingDeprecationWarning,
  365. stacklevel=2,
  366. )
  367. self._warn_deprecated_options()
  368. odoo.modules.module.initialize_sys_path()
  369. return opt
  370. def _parse_config(self, args=None):
  371. if args is None:
  372. args = []
  373. opt, args = self.parser.parse_args(args)
  374. def die(cond, msg):
  375. if cond:
  376. self.parser.error(msg)
  377. # Ensures no illegitimate argument is silently discarded (avoids insidious "hyphen to dash" problem)
  378. die(args, "unrecognized parameters: '%s'" % " ".join(args))
  379. die(bool(opt.syslog) and bool(opt.logfile),
  380. "the syslog and logfile options are exclusive")
  381. die(opt.translate_in and (not opt.language or not opt.db_name),
  382. "the i18n-import option cannot be used without the language (-l) and the database (-d) options")
  383. die(opt.overwrite_existing_translations and not (opt.translate_in or opt.update),
  384. "the i18n-overwrite option cannot be used without the i18n-import option or without the update option")
  385. die(opt.translate_out and (not opt.db_name),
  386. "the i18n-export option cannot be used without the database (-d) option")
  387. # Check if the config file exists (-c used, but not -s)
  388. die(not opt.save and opt.config and not os.access(opt.config, os.R_OK),
  389. "The config file '%s' selected with -c/--config doesn't exist or is not readable, "\
  390. "use -s/--save if you want to generate it"% opt.config)
  391. # place/search the config file on Win32 near the server installation
  392. # (../etc from the server)
  393. # 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,
  394. # else he won't be able to save the configurations, or even to start the server...
  395. # TODO use appdirs
  396. if os.name == 'nt':
  397. rcfilepath = os.path.join(os.path.abspath(os.path.dirname(sys.argv[0])), 'odoo.conf')
  398. else:
  399. rcfilepath = os.path.expanduser('~/.odoorc')
  400. old_rcfilepath = os.path.expanduser('~/.openerp_serverrc')
  401. die(os.path.isfile(rcfilepath) and os.path.isfile(old_rcfilepath),
  402. "Found '.odoorc' and '.openerp_serverrc' in your path. Please keep only one of "\
  403. "them, preferably '.odoorc'.")
  404. if not os.path.isfile(rcfilepath) and os.path.isfile(old_rcfilepath):
  405. rcfilepath = old_rcfilepath
  406. self.rcfile = os.path.abspath(
  407. self.config_file or opt.config or os.environ.get('ODOO_RC') or os.environ.get('OPENERP_SERVER') or rcfilepath)
  408. self.load()
  409. # Verify that we want to log or not, if not the output will go to stdout
  410. if self.options['logfile'] in ('None', 'False'):
  411. self.options['logfile'] = False
  412. # the same for the pidfile
  413. if self.options['pidfile'] in ('None', 'False'):
  414. self.options['pidfile'] = False
  415. # the same for the test_tags
  416. if self.options['test_tags'] == 'None':
  417. self.options['test_tags'] = None
  418. # and the server_wide_modules
  419. if self.options['server_wide_modules'] in ('', 'None', 'False'):
  420. self.options['server_wide_modules'] = 'base,web'
  421. # if defined do not take the configfile value even if the defined value is None
  422. keys = ['gevent_port', 'http_interface', 'http_port', 'http_enable', 'x_sendfile',
  423. 'db_name', 'db_user', 'db_password', 'db_host', 'db_replica_host', 'db_sslmode',
  424. 'db_port', 'db_replica_port', 'db_template', 'logfile', 'pidfile', 'smtp_port',
  425. 'email_from', 'smtp_server', 'smtp_user', 'smtp_password', 'from_filter',
  426. 'smtp_ssl_certificate_filename', 'smtp_ssl_private_key_filename',
  427. 'db_maxconn', 'db_maxconn_gevent', 'import_partial', 'addons_path', 'upgrade_path',
  428. 'syslog', 'without_demo', 'screencasts', 'screenshots',
  429. 'dbfilter', 'log_level', 'log_db',
  430. 'log_db_level', 'geoip_city_db', 'geoip_country_db', 'dev_mode',
  431. 'shell_interface', 'limit_time_worker_cron',
  432. ]
  433. for arg in keys:
  434. # Copy the command-line argument (except the special case for log_handler, due to
  435. # action=append requiring a real default, so we cannot use the my_default workaround)
  436. if getattr(opt, arg, None) is not None:
  437. self.options[arg] = getattr(opt, arg)
  438. # ... or keep, but cast, the config file value.
  439. elif isinstance(self.options[arg], str) and self.casts[arg].type in optparse.Option.TYPE_CHECKER:
  440. self.options[arg] = optparse.Option.TYPE_CHECKER[self.casts[arg].type](self.casts[arg], arg, self.options[arg])
  441. if isinstance(self.options['log_handler'], str):
  442. self.options['log_handler'] = self.options['log_handler'].split(',')
  443. self.options['log_handler'].extend(opt.log_handler)
  444. # if defined but None take the configfile value
  445. keys = [
  446. 'language', 'translate_out', 'translate_in', 'overwrite_existing_translations',
  447. 'dev_mode', 'shell_interface', 'smtp_ssl', 'load_language',
  448. 'stop_after_init', 'without_demo', 'http_enable', 'syslog',
  449. 'list_db', 'proxy_mode',
  450. 'test_file', 'test_tags',
  451. 'osv_memory_count_limit', 'transient_age_limit', 'max_cron_threads', 'unaccent',
  452. 'data_dir',
  453. 'server_wide_modules',
  454. ]
  455. posix_keys = [
  456. 'workers',
  457. 'limit_memory_hard', 'limit_memory_hard_gevent', 'limit_memory_soft', 'limit_memory_soft_gevent',
  458. 'limit_time_cpu', 'limit_time_real', 'limit_request', 'limit_time_real_cron'
  459. ]
  460. if os.name == 'posix':
  461. keys += posix_keys
  462. else:
  463. self.options.update(dict.fromkeys(posix_keys, None))
  464. # Copy the command-line arguments...
  465. for arg in keys:
  466. if getattr(opt, arg) is not None:
  467. self.options[arg] = getattr(opt, arg)
  468. # ... or keep, but cast, the config file value.
  469. elif isinstance(self.options[arg], str) and self.casts[arg].type in optparse.Option.TYPE_CHECKER:
  470. self.options[arg] = optparse.Option.TYPE_CHECKER[self.casts[arg].type](self.casts[arg], arg, self.options[arg])
  471. ismultidb = ',' in (self.options.get('db_name') or '')
  472. die(ismultidb and (opt.init or opt.update), "Cannot use -i/--init or -u/--update with multiple databases in the -d/--database/db_name")
  473. self.options['root_path'] = self._normalize(os.path.join(os.path.dirname(__file__), '..'))
  474. if not self.options['addons_path'] or self.options['addons_path']=='None':
  475. default_addons = []
  476. base_addons = os.path.join(self.options['root_path'], 'addons')
  477. if os.path.exists(base_addons):
  478. default_addons.append(base_addons)
  479. main_addons = os.path.abspath(os.path.join(self.options['root_path'], '../addons'))
  480. if os.path.exists(main_addons):
  481. default_addons.append(main_addons)
  482. self.options['addons_path'] = ','.join(default_addons)
  483. else:
  484. self.options['addons_path'] = ",".join(
  485. self._normalize(x)
  486. for x in self.options['addons_path'].split(','))
  487. self.options["upgrade_path"] = (
  488. ",".join(self._normalize(x)
  489. for x in self.options['upgrade_path'].split(','))
  490. if self.options['upgrade_path']
  491. else ""
  492. )
  493. self.options['init'] = opt.init and dict.fromkeys(opt.init.split(','), 1) or {}
  494. self.options['demo'] = (dict(self.options['init'])
  495. if not self.options['without_demo'] else {})
  496. self.options['update'] = opt.update and dict.fromkeys(opt.update.split(','), 1) or {}
  497. self.options['translate_modules'] = opt.translate_modules and [m.strip() for m in opt.translate_modules.split(',')] or ['all']
  498. self.options['translate_modules'].sort()
  499. dev_split = [s.strip() for s in opt.dev_mode.split(',')] if opt.dev_mode else []
  500. self.options['dev_mode'] = dev_split + (['reload', 'qweb', 'xml'] if 'all' in dev_split else [])
  501. if opt.pg_path:
  502. self.options['pg_path'] = opt.pg_path
  503. self.options['test_enable'] = bool(self.options['test_tags'])
  504. if opt.save:
  505. self.save()
  506. # normalize path options
  507. for key in ['data_dir', 'logfile', 'pidfile', 'test_file', 'screencasts', 'screenshots', 'pg_path', 'translate_out', 'translate_in', 'geoip_city_db', 'geoip_country_db']:
  508. self.options[key] = self._normalize(self.options[key])
  509. conf.addons_paths = self.options['addons_path'].split(',')
  510. conf.server_wide_modules = [
  511. m.strip() for m in self.options['server_wide_modules'].split(',') if m.strip()
  512. ]
  513. return opt
  514. def _warn_deprecated_options(self):
  515. for old_option_name, new_option_name in [
  516. ('geoip_database', 'geoip_city_db'),
  517. ('osv_memory_age_limit', 'transient_age_limit')
  518. ]:
  519. deprecated_value = self.options.pop(old_option_name, None)
  520. if deprecated_value:
  521. default_value = self.casts[new_option_name].my_default
  522. current_value = self.options[new_option_name]
  523. if deprecated_value in (current_value, default_value):
  524. # Surely this is from a --save that was run in a
  525. # prior version. There is no point in emitting a
  526. # warning because: (1) it holds the same value as
  527. # the correct option, and (2) it is going to be
  528. # automatically removed on the next --save anyway.
  529. pass
  530. elif current_value == default_value:
  531. # deprecated_value != current_value == default_value
  532. # assume the new option was not set
  533. self.options[new_option_name] = deprecated_value
  534. warnings.warn(
  535. f"The {old_option_name!r} option found in the "
  536. "configuration file is a deprecated alias to "
  537. f"{new_option_name!r}, please use the latter.",
  538. DeprecationWarning)
  539. else:
  540. # deprecated_value != current_value != default_value
  541. self.parser.error(
  542. f"The two options {old_option_name!r} "
  543. "(found in the configuration file but "
  544. f"deprecated) and {new_option_name!r} are set "
  545. "to different values. Please remove the first "
  546. "one and make sure the second is correct."
  547. )
  548. def _is_addons_path(self, path):
  549. from odoo.modules.module import MANIFEST_NAMES
  550. for f in os.listdir(path):
  551. modpath = os.path.join(path, f)
  552. if os.path.isdir(modpath):
  553. def hasfile(filename):
  554. return os.path.isfile(os.path.join(modpath, filename))
  555. if hasfile('__init__.py') and any(hasfile(mname) for mname in MANIFEST_NAMES):
  556. return True
  557. return False
  558. def _check_addons_path(self, option, opt, value, parser):
  559. ad_paths = []
  560. for path in value.split(','):
  561. path = path.strip()
  562. res = os.path.abspath(os.path.expanduser(path))
  563. if not os.path.isdir(res):
  564. raise optparse.OptionValueError("option %s: no such directory: %r" % (opt, res))
  565. if not self._is_addons_path(res):
  566. raise optparse.OptionValueError("option %s: the path %r is not a valid addons directory" % (opt, path))
  567. ad_paths.append(res)
  568. setattr(parser.values, option.dest, ",".join(ad_paths))
  569. def _check_upgrade_path(self, option, opt, value, parser):
  570. upgrade_path = []
  571. for path in value.split(','):
  572. path = path.strip()
  573. res = self._normalize(path)
  574. if not os.path.isdir(res):
  575. raise optparse.OptionValueError("option %s: no such directory: %r" % (opt, path))
  576. if not self._is_upgrades_path(res):
  577. raise optparse.OptionValueError("option %s: the path %r is not a valid upgrade directory" % (opt, path))
  578. if res not in upgrade_path:
  579. upgrade_path.append(res)
  580. setattr(parser.values, option.dest, ",".join(upgrade_path))
  581. def _is_upgrades_path(self, res):
  582. return any(
  583. glob.glob(os.path.join(res, f"*/*/{prefix}-*.py"))
  584. for prefix in ["pre", "post", "end"]
  585. )
  586. def _test_enable_callback(self, option, opt, value, parser):
  587. if not parser.values.test_tags:
  588. parser.values.test_tags = "+standard"
  589. def load(self):
  590. outdated_options_map = {
  591. 'xmlrpc_port': 'http_port',
  592. 'xmlrpc_interface': 'http_interface',
  593. 'xmlrpc': 'http_enable',
  594. }
  595. p = ConfigParser.RawConfigParser()
  596. try:
  597. p.read([self.rcfile])
  598. for (name,value) in p.items('options'):
  599. name = outdated_options_map.get(name, name)
  600. if value=='True' or value=='true':
  601. value = True
  602. if value=='False' or value=='false':
  603. value = False
  604. self.options[name] = value
  605. #parse the other sections, as well
  606. for sec in p.sections():
  607. if sec == 'options':
  608. continue
  609. self.misc.setdefault(sec, {})
  610. for (name, value) in p.items(sec):
  611. if value=='True' or value=='true':
  612. value = True
  613. if value=='False' or value=='false':
  614. value = False
  615. self.misc[sec][name] = value
  616. except IOError:
  617. pass
  618. except ConfigParser.NoSectionError:
  619. pass
  620. def save(self, keys=None):
  621. p = ConfigParser.RawConfigParser()
  622. loglevelnames = dict(zip(self._LOGLEVELS.values(), self._LOGLEVELS))
  623. rc_exists = os.path.exists(self.rcfile)
  624. if rc_exists and keys:
  625. p.read([self.rcfile])
  626. if not p.has_section('options'):
  627. p.add_section('options')
  628. for opt in sorted(self.options):
  629. if keys is not None and opt not in keys:
  630. continue
  631. if opt in ('version', 'language', 'translate_out', 'translate_in', 'overwrite_existing_translations', 'init', 'update'):
  632. continue
  633. if opt in self.blacklist_for_save:
  634. continue
  635. if opt in ('log_level',):
  636. p.set('options', opt, loglevelnames.get(self.options[opt], self.options[opt]))
  637. elif opt == 'log_handler':
  638. p.set('options', opt, ','.join(_deduplicate_loggers(self.options[opt])))
  639. else:
  640. p.set('options', opt, self.options[opt])
  641. for sec in sorted(self.misc):
  642. p.add_section(sec)
  643. for opt in sorted(self.misc[sec]):
  644. p.set(sec,opt,self.misc[sec][opt])
  645. # try to create the directories and write the file
  646. try:
  647. if not rc_exists and not os.path.exists(os.path.dirname(self.rcfile)):
  648. os.makedirs(os.path.dirname(self.rcfile))
  649. try:
  650. p.write(open(self.rcfile, 'w'))
  651. if not rc_exists:
  652. os.chmod(self.rcfile, 0o600)
  653. except IOError:
  654. sys.stderr.write("ERROR: couldn't write the config file\n")
  655. except OSError:
  656. # what to do if impossible?
  657. sys.stderr.write("ERROR: couldn't create the config directory\n")
  658. def get(self, key, default=None):
  659. return self.options.get(key, default)
  660. def pop(self, key, default=None):
  661. return self.options.pop(key, default)
  662. def get_misc(self, sect, key, default=None):
  663. return self.misc.get(sect,{}).get(key, default)
  664. def __setitem__(self, key, value):
  665. self.options[key] = value
  666. if key in self.options and isinstance(self.options[key], str) and \
  667. key in self.casts and self.casts[key].type in optparse.Option.TYPE_CHECKER:
  668. self.options[key] = optparse.Option.TYPE_CHECKER[self.casts[key].type](self.casts[key], key, self.options[key])
  669. def __getitem__(self, key):
  670. return self.options[key]
  671. @property
  672. def addons_data_dir(self):
  673. add_dir = os.path.join(self['data_dir'], 'addons')
  674. d = os.path.join(add_dir, release.series)
  675. if not os.path.exists(d):
  676. try:
  677. # bootstrap parent dir +rwx
  678. if not os.path.exists(add_dir):
  679. os.makedirs(add_dir, 0o700)
  680. # try to make +rx placeholder dir, will need manual +w to activate it
  681. os.makedirs(d, 0o500)
  682. except OSError:
  683. logging.getLogger(__name__).debug('Failed to create addons data dir %s', d)
  684. return d
  685. @property
  686. def session_dir(self):
  687. d = os.path.join(self['data_dir'], 'sessions')
  688. try:
  689. os.makedirs(d, 0o700)
  690. except OSError as e:
  691. if e.errno != errno.EEXIST:
  692. raise
  693. assert os.access(d, os.W_OK), \
  694. "%s: directory is not writable" % d
  695. return d
  696. def filestore(self, dbname):
  697. return os.path.join(self['data_dir'], 'filestore', dbname)
  698. def set_admin_password(self, new_password):
  699. self.options['admin_passwd'] = crypt_context.hash(new_password)
  700. def verify_admin_password(self, password):
  701. """Verifies the super-admin password, possibly updating the stored hash if needed"""
  702. stored_hash = self.options['admin_passwd']
  703. if not stored_hash:
  704. # empty password/hash => authentication forbidden
  705. return False
  706. result, updated_hash = crypt_context.verify_and_update(password, stored_hash)
  707. if result:
  708. if updated_hash:
  709. self.options['admin_passwd'] = updated_hash
  710. return True
  711. def _normalize(self, path):
  712. if not path:
  713. return ''
  714. return normcase(realpath(abspath(expanduser(expandvars(path.strip())))))
  715. config = configmanager()
上海开阖软件有限公司 沪ICP备12045867号-1