gooderp18绿色标准版
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

181 line
6.0KB

  1. # Part of Odoo. See LICENSE file for full copyright and licensing details.
  2. """
  3. OpenERP - Server
  4. OpenERP is an ERP+CRM program for small and medium businesses.
  5. The whole source code is distributed under the terms of the
  6. GNU Public Licence.
  7. (c) 2003-TODAY, Fabien Pinckaers - OpenERP SA
  8. """
  9. import atexit
  10. import csv # pylint: disable=deprecated-module
  11. import logging
  12. import os
  13. import re
  14. import sys
  15. from pathlib import Path
  16. from psycopg2.errors import InsufficientPrivilege
  17. import odoo
  18. from . import Command
  19. __author__ = odoo.release.author
  20. __version__ = odoo.release.version
  21. # Also use the `odoo` logger for the main script.
  22. _logger = logging.getLogger('odoo')
  23. re._MAXCACHE = 4096 # default is 512, a little too small for odoo
  24. def check_root_user():
  25. """Warn if the process's user is 'root' (on POSIX system)."""
  26. if os.name == 'posix':
  27. import getpass
  28. if getpass.getuser() == 'root':
  29. sys.stderr.write("Running as user 'root' is a security risk.\n")
  30. def check_postgres_user():
  31. """ Exit if the configured database user is 'postgres'.
  32. This function assumes the configuration has been initialized.
  33. """
  34. config = odoo.tools.config
  35. if (config['db_user'] or os.environ.get('PGUSER')) == 'postgres':
  36. sys.stderr.write("Using the database user 'postgres' is a security risk, aborting.")
  37. sys.exit(1)
  38. def report_configuration():
  39. """ Log the server version and some configuration values.
  40. This function assumes the configuration has been initialized.
  41. """
  42. config = odoo.tools.config
  43. _logger.info("Odoo version %s", __version__)
  44. if os.path.isfile(config.rcfile):
  45. _logger.info("Using configuration file at " + config.rcfile)
  46. _logger.info('addons paths: %s', odoo.addons.__path__)
  47. if config.get('upgrade_path'):
  48. _logger.info('upgrade path: %s', config['upgrade_path'])
  49. host = config['db_host'] or os.environ.get('PGHOST', 'default')
  50. port = config['db_port'] or os.environ.get('PGPORT', 'default')
  51. user = config['db_user'] or os.environ.get('PGUSER', 'default')
  52. _logger.info('database: %s@%s:%s', user, host, port)
  53. replica_host = config['db_replica_host']
  54. replica_port = config['db_replica_port']
  55. if replica_host is not False or replica_port:
  56. _logger.info('replica database: %s@%s:%s', user, replica_host or 'default', replica_port or 'default')
  57. if sys.version_info[:2] > odoo.MAX_PY_VERSION:
  58. _logger.warning("Python %s is not officially supported, please use Python %s instead",
  59. '.'.join(map(str, sys.version_info[:2])),
  60. '.'.join(map(str, odoo.MAX_PY_VERSION))
  61. )
  62. def rm_pid_file(main_pid):
  63. config = odoo.tools.config
  64. if config['pidfile'] and main_pid == os.getpid():
  65. try:
  66. os.unlink(config['pidfile'])
  67. except OSError:
  68. pass
  69. def setup_pid_file():
  70. """ Create a file with the process id written in it.
  71. This function assumes the configuration has been initialized.
  72. """
  73. config = odoo.tools.config
  74. if not odoo.evented and config['pidfile']:
  75. pid = os.getpid()
  76. with open(config['pidfile'], 'w') as fd:
  77. fd.write(str(pid))
  78. atexit.register(rm_pid_file, pid)
  79. def export_translation():
  80. config = odoo.tools.config
  81. dbname = config['db_name']
  82. if config["language"]:
  83. msg = "language %s" % (config["language"],)
  84. else:
  85. msg = "new language"
  86. _logger.info('writing translation file for %s to %s', msg,
  87. config["translate_out"])
  88. fileformat = os.path.splitext(config["translate_out"])[-1][1:].lower()
  89. # .pot is the same fileformat as .po
  90. if fileformat == "pot":
  91. fileformat = "po"
  92. with open(config["translate_out"], "wb") as buf:
  93. registry = odoo.modules.registry.Registry.new(dbname)
  94. with registry.cursor() as cr:
  95. odoo.tools.translate.trans_export(config["language"],
  96. config["translate_modules"] or ["all"], buf, fileformat, cr)
  97. _logger.info('translation file written successfully')
  98. def import_translation():
  99. config = odoo.tools.config
  100. overwrite = config["overwrite_existing_translations"]
  101. dbname = config['db_name']
  102. registry = odoo.modules.registry.Registry.new(dbname)
  103. with registry.cursor() as cr:
  104. translation_importer = odoo.tools.translate.TranslationImporter(cr)
  105. translation_importer.load_file(config["translate_in"], config["language"])
  106. translation_importer.save(overwrite=overwrite)
  107. def main(args):
  108. check_root_user()
  109. odoo.tools.config.parse_config(args, setup_logging=True)
  110. check_postgres_user()
  111. report_configuration()
  112. config = odoo.tools.config
  113. # the default limit for CSV fields in the module is 128KiB, which is not
  114. # quite sufficient to import images to store in attachment. 500MiB is a
  115. # bit overkill, but better safe than sorry I guess
  116. csv.field_size_limit(500 * 1024 * 1024)
  117. preload = []
  118. if config['db_name']:
  119. preload = config['db_name'].split(',')
  120. for db_name in preload:
  121. try:
  122. odoo.service.db._create_empty_database(db_name)
  123. config['init']['base'] = True
  124. except InsufficientPrivilege as err:
  125. # We use an INFO loglevel on purpose in order to avoid
  126. # reporting unnecessary warnings on build environment
  127. # using restricted database access.
  128. _logger.info("Could not determine if database %s exists, "
  129. "skipping auto-creation: %s", db_name, err)
  130. except odoo.service.db.DatabaseExists:
  131. pass
  132. if config["translate_out"]:
  133. export_translation()
  134. sys.exit(0)
  135. if config["translate_in"]:
  136. import_translation()
  137. sys.exit(0)
  138. stop = config["stop_after_init"]
  139. setup_pid_file()
  140. rc = odoo.service.server.start(preload=preload, stop=stop)
  141. sys.exit(rc)
  142. class Server(Command):
  143. """Start the odoo server (default command)"""
  144. def run(self, args):
  145. odoo.tools.config.parser.prog = f'{Path(sys.argv[0]).name} {self.name}'
  146. main(args)
上海开阖软件有限公司 沪ICP备12045867号-1