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.

498 lines
19KB

  1. # -*- coding: utf-8 -*-
  2. import base64
  3. import json
  4. import logging
  5. import os
  6. import shutil
  7. import subprocess
  8. import tempfile
  9. import zipfile
  10. from contextlib import closing
  11. from xml.etree import ElementTree as ET
  12. import psycopg2
  13. from psycopg2.extensions import quote_ident
  14. from decorator import decorator
  15. from pytz import country_timezones
  16. import odoo
  17. import odoo.release
  18. import odoo.sql_db
  19. import odoo.tools
  20. from odoo import SUPERUSER_ID
  21. from odoo.exceptions import AccessDenied
  22. from odoo.release import version_info
  23. from odoo.sql_db import db_connect
  24. from odoo.tools import SQL
  25. from odoo.tools.misc import exec_pg_environ, find_pg_tool
  26. _logger = logging.getLogger(__name__)
  27. class DatabaseExists(Warning):
  28. pass
  29. def database_identifier(cr, name: str) -> SQL:
  30. """Quote a database identifier.
  31. Use instead of `SQL.identifier` to accept all kinds of identifiers.
  32. """
  33. name = quote_ident(name, cr._cnx)
  34. return SQL(name)
  35. def check_db_management_enabled(method):
  36. def if_db_mgt_enabled(method, self, *args, **kwargs):
  37. if not odoo.tools.config['list_db']:
  38. _logger.error('Database management functions blocked, admin disabled database listing')
  39. raise AccessDenied()
  40. return method(self, *args, **kwargs)
  41. return decorator(if_db_mgt_enabled, method)
  42. #----------------------------------------------------------
  43. # Master password required
  44. #----------------------------------------------------------
  45. def check_super(passwd):
  46. if passwd and odoo.tools.config.verify_admin_password(passwd):
  47. return True
  48. raise odoo.exceptions.AccessDenied()
  49. # This should be moved to odoo.modules.db, along side initialize().
  50. def _initialize_db(id, db_name, demo, lang, user_password, login='admin', country_code=None, phone=None):
  51. try:
  52. db = odoo.sql_db.db_connect(db_name)
  53. with closing(db.cursor()) as cr:
  54. # TODO this should be removed as it is done by Registry.new().
  55. odoo.modules.db.initialize(cr)
  56. odoo.tools.config['load_language'] = lang
  57. cr.commit()
  58. registry = odoo.modules.registry.Registry.new(db_name, demo, None, update_module=True)
  59. with closing(registry.cursor()) as cr:
  60. env = odoo.api.Environment(cr, SUPERUSER_ID, {})
  61. if lang:
  62. modules = env['ir.module.module'].search([('state', '=', 'installed')])
  63. modules._update_translations(lang)
  64. if country_code:
  65. country = env['res.country'].search([('code', 'ilike', country_code)])[0]
  66. env['res.company'].browse(1).write({'country_id': country_code and country.id, 'currency_id': country_code and country.currency_id.id})
  67. if len(country_timezones.get(country_code, [])) == 1:
  68. users = env['res.users'].search([])
  69. users.write({'tz': country_timezones[country_code][0]})
  70. if phone:
  71. env['res.company'].browse(1).write({'phone': phone})
  72. if '@' in login:
  73. env['res.company'].browse(1).write({'email': login})
  74. # update admin's password and lang and login
  75. values = {'password': user_password, 'lang': lang}
  76. if login:
  77. values['login'] = login
  78. emails = odoo.tools.email_split(login)
  79. if emails:
  80. values['email'] = emails[0]
  81. env.ref('base.user_admin').write(values)
  82. cr.commit()
  83. except Exception as e:
  84. _logger.exception('CREATE DATABASE failed:')
  85. def _create_empty_database(name):
  86. db = odoo.sql_db.db_connect('postgres')
  87. with closing(db.cursor()) as cr:
  88. chosen_template = odoo.tools.config['db_template']
  89. cr.execute("SELECT datname FROM pg_database WHERE datname = %s",
  90. (name,), log_exceptions=False)
  91. if cr.fetchall():
  92. raise DatabaseExists("database %r already exists!" % (name,))
  93. else:
  94. # database-altering operations cannot be executed inside a transaction
  95. cr.rollback()
  96. cr._cnx.autocommit = True
  97. # 'C' collate is only safe with template0, but provides more useful indexes
  98. cr.execute(SQL(
  99. "CREATE DATABASE %s ENCODING 'unicode' %s TEMPLATE %s",
  100. database_identifier(cr, name),
  101. SQL("LC_COLLATE 'C'") if chosen_template == 'template0' else SQL(""),
  102. database_identifier(cr, chosen_template),
  103. ))
  104. # TODO: add --extension=trigram,unaccent
  105. try:
  106. db = odoo.sql_db.db_connect(name)
  107. with db.cursor() as cr:
  108. cr.execute("CREATE EXTENSION IF NOT EXISTS pg_trgm")
  109. if odoo.tools.config['unaccent']:
  110. cr.execute("CREATE EXTENSION IF NOT EXISTS unaccent")
  111. # From PostgreSQL's point of view, making 'unaccent' immutable is incorrect
  112. # because it depends on external data - see
  113. # https://www.postgresql.org/message-id/flat/201012021544.oB2FiTn1041521@wwwmaster.postgresql.org#201012021544.oB2FiTn1041521@wwwmaster.postgresql.org
  114. # But in the case of Odoo, we consider that those data don't
  115. # change in the lifetime of a database. If they do change, all
  116. # indexes created with this function become corrupted!
  117. cr.execute("ALTER FUNCTION unaccent(text) IMMUTABLE")
  118. except psycopg2.Error as e:
  119. _logger.warning("Unable to create PostgreSQL extensions : %s", e)
  120. # restore legacy behaviour on pg15+
  121. try:
  122. db = odoo.sql_db.db_connect(name)
  123. with db.cursor() as cr:
  124. cr.execute("GRANT CREATE ON SCHEMA PUBLIC TO PUBLIC")
  125. except psycopg2.Error as e:
  126. _logger.warning("Unable to make public schema public-accessible: %s", e)
  127. @check_db_management_enabled
  128. def exp_create_database(db_name, demo, lang, user_password='admin', login='admin', country_code=None, phone=None):
  129. """ Similar to exp_create but blocking."""
  130. _logger.info('Create database `%s`.', db_name)
  131. _create_empty_database(db_name)
  132. _initialize_db(id, db_name, demo, lang, user_password, login, country_code, phone)
  133. return True
  134. @check_db_management_enabled
  135. def exp_duplicate_database(db_original_name, db_name, neutralize_database=False):
  136. _logger.info('Duplicate database `%s` to `%s`.', db_original_name, db_name)
  137. odoo.sql_db.close_db(db_original_name)
  138. db = odoo.sql_db.db_connect('postgres')
  139. with closing(db.cursor()) as cr:
  140. # database-altering operations cannot be executed inside a transaction
  141. cr._cnx.autocommit = True
  142. _drop_conn(cr, db_original_name)
  143. cr.execute(SQL(
  144. "CREATE DATABASE %s ENCODING 'unicode' TEMPLATE %s",
  145. database_identifier(cr, db_name),
  146. database_identifier(cr, db_original_name),
  147. ))
  148. registry = odoo.modules.registry.Registry.new(db_name)
  149. with registry.cursor() as cr:
  150. # if it's a copy of a database, force generation of a new dbuuid
  151. env = odoo.api.Environment(cr, SUPERUSER_ID, {})
  152. env['ir.config_parameter'].init(force=True)
  153. if neutralize_database:
  154. odoo.modules.neutralize.neutralize_database(cr)
  155. from_fs = odoo.tools.config.filestore(db_original_name)
  156. to_fs = odoo.tools.config.filestore(db_name)
  157. if os.path.exists(from_fs) and not os.path.exists(to_fs):
  158. shutil.copytree(from_fs, to_fs)
  159. return True
  160. def _drop_conn(cr, db_name):
  161. # Try to terminate all other connections that might prevent
  162. # dropping the database
  163. try:
  164. # PostgreSQL 9.2 renamed pg_stat_activity.procpid to pid:
  165. # http://www.postgresql.org/docs/9.2/static/release-9-2.html#AEN110389
  166. pid_col = 'pid' if cr._cnx.server_version >= 90200 else 'procpid'
  167. cr.execute("""SELECT pg_terminate_backend(%(pid_col)s)
  168. FROM pg_stat_activity
  169. WHERE datname = %%s AND
  170. %(pid_col)s != pg_backend_pid()""" % {'pid_col': pid_col},
  171. (db_name,))
  172. except Exception:
  173. pass
  174. @check_db_management_enabled
  175. def exp_drop(db_name):
  176. if db_name not in list_dbs(True):
  177. return False
  178. odoo.modules.registry.Registry.delete(db_name)
  179. odoo.sql_db.close_db(db_name)
  180. db = odoo.sql_db.db_connect('postgres')
  181. with closing(db.cursor()) as cr:
  182. # database-altering operations cannot be executed inside a transaction
  183. cr._cnx.autocommit = True
  184. _drop_conn(cr, db_name)
  185. try:
  186. cr.execute(SQL('DROP DATABASE %s', database_identifier(cr, db_name)))
  187. except Exception as e:
  188. _logger.info('DROP DB: %s failed:\n%s', db_name, e)
  189. raise Exception("Couldn't drop database %s: %s" % (db_name, e))
  190. else:
  191. _logger.info('DROP DB: %s', db_name)
  192. fs = odoo.tools.config.filestore(db_name)
  193. if os.path.exists(fs):
  194. shutil.rmtree(fs)
  195. return True
  196. @check_db_management_enabled
  197. def exp_dump(db_name, format):
  198. with tempfile.TemporaryFile(mode='w+b') as t:
  199. dump_db(db_name, t, format)
  200. t.seek(0)
  201. return base64.b64encode(t.read()).decode()
  202. @check_db_management_enabled
  203. def dump_db_manifest(cr):
  204. pg_version = "%d.%d" % divmod(cr._obj.connection.server_version / 100, 100)
  205. cr.execute("SELECT name, latest_version FROM ir_module_module WHERE state = 'installed'")
  206. modules = dict(cr.fetchall())
  207. manifest = {
  208. 'odoo_dump': '1',
  209. 'db_name': cr.dbname,
  210. 'version': odoo.release.version,
  211. 'version_info': odoo.release.version_info,
  212. 'major_version': odoo.release.major_version,
  213. 'pg_version': pg_version,
  214. 'modules': modules,
  215. }
  216. return manifest
  217. @check_db_management_enabled
  218. def dump_db(db_name, stream, backup_format='zip'):
  219. """Dump database `db` into file-like object `stream` if stream is None
  220. return a file object with the dump """
  221. _logger.info('DUMP DB: %s format %s', db_name, backup_format)
  222. cmd = [find_pg_tool('pg_dump'), '--no-owner', db_name]
  223. env = exec_pg_environ()
  224. if backup_format == 'zip':
  225. with tempfile.TemporaryDirectory() as dump_dir:
  226. filestore = odoo.tools.config.filestore(db_name)
  227. if os.path.exists(filestore):
  228. shutil.copytree(filestore, os.path.join(dump_dir, 'filestore'))
  229. with open(os.path.join(dump_dir, 'manifest.json'), 'w') as fh:
  230. db = odoo.sql_db.db_connect(db_name)
  231. with db.cursor() as cr:
  232. json.dump(dump_db_manifest(cr), fh, indent=4)
  233. cmd.insert(-1, '--file=' + os.path.join(dump_dir, 'dump.sql'))
  234. subprocess.run(cmd, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, check=True)
  235. if stream:
  236. odoo.tools.osutil.zip_dir(dump_dir, stream, include_dir=False, fnct_sort=lambda file_name: file_name != 'dump.sql')
  237. else:
  238. t=tempfile.TemporaryFile()
  239. odoo.tools.osutil.zip_dir(dump_dir, t, include_dir=False, fnct_sort=lambda file_name: file_name != 'dump.sql')
  240. t.seek(0)
  241. return t
  242. else:
  243. cmd.insert(-1, '--format=c')
  244. stdout = subprocess.Popen(cmd, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE).stdout
  245. if stream:
  246. shutil.copyfileobj(stdout, stream)
  247. else:
  248. return stdout
  249. @check_db_management_enabled
  250. def exp_restore(db_name, data, copy=False):
  251. def chunks(d, n=8192):
  252. for i in range(0, len(d), n):
  253. yield d[i:i+n]
  254. data_file = tempfile.NamedTemporaryFile(delete=False)
  255. try:
  256. for chunk in chunks(data):
  257. data_file.write(base64.b64decode(chunk))
  258. data_file.close()
  259. restore_db(db_name, data_file.name, copy=copy)
  260. finally:
  261. os.unlink(data_file.name)
  262. return True
  263. @check_db_management_enabled
  264. def restore_db(db, dump_file, copy=False, neutralize_database=False):
  265. assert isinstance(db, str)
  266. if exp_db_exist(db):
  267. _logger.warning('RESTORE DB: %s already exists', db)
  268. raise Exception("Database already exists")
  269. _logger.info('RESTORING DB: %s', db)
  270. _create_empty_database(db)
  271. filestore_path = None
  272. with tempfile.TemporaryDirectory() as dump_dir:
  273. if zipfile.is_zipfile(dump_file):
  274. # v8 format
  275. with zipfile.ZipFile(dump_file, 'r') as z:
  276. # only extract known members!
  277. filestore = [m for m in z.namelist() if m.startswith('filestore/')]
  278. z.extractall(dump_dir, ['dump.sql'] + filestore)
  279. if filestore:
  280. filestore_path = os.path.join(dump_dir, 'filestore')
  281. pg_cmd = 'psql'
  282. pg_args = ['-q', '-f', os.path.join(dump_dir, 'dump.sql')]
  283. else:
  284. # <= 7.0 format (raw pg_dump output)
  285. pg_cmd = 'pg_restore'
  286. pg_args = ['--no-owner', dump_file]
  287. r = subprocess.run(
  288. [find_pg_tool(pg_cmd), '--dbname=' + db, *pg_args],
  289. env=exec_pg_environ(),
  290. stdout=subprocess.DEVNULL,
  291. stderr=subprocess.STDOUT,
  292. )
  293. if r.returncode != 0:
  294. raise Exception("Couldn't restore database")
  295. registry = odoo.modules.registry.Registry.new(db)
  296. with registry.cursor() as cr:
  297. env = odoo.api.Environment(cr, SUPERUSER_ID, {})
  298. if copy:
  299. # if it's a copy of a database, force generation of a new dbuuid
  300. env['ir.config_parameter'].init(force=True)
  301. if neutralize_database:
  302. odoo.modules.neutralize.neutralize_database(cr)
  303. if filestore_path:
  304. filestore_dest = env['ir.attachment']._filestore()
  305. shutil.move(filestore_path, filestore_dest)
  306. _logger.info('RESTORE DB: %s', db)
  307. @check_db_management_enabled
  308. def exp_rename(old_name, new_name):
  309. odoo.modules.registry.Registry.delete(old_name)
  310. odoo.sql_db.close_db(old_name)
  311. db = odoo.sql_db.db_connect('postgres')
  312. with closing(db.cursor()) as cr:
  313. # database-altering operations cannot be executed inside a transaction
  314. cr._cnx.autocommit = True
  315. _drop_conn(cr, old_name)
  316. try:
  317. cr.execute(SQL('ALTER DATABASE %s RENAME TO %s', database_identifier(cr, old_name), database_identifier(cr, new_name)))
  318. _logger.info('RENAME DB: %s -> %s', old_name, new_name)
  319. except Exception as e:
  320. _logger.info('RENAME DB: %s -> %s failed:\n%s', old_name, new_name, e)
  321. raise Exception("Couldn't rename database %s to %s: %s" % (old_name, new_name, e))
  322. old_fs = odoo.tools.config.filestore(old_name)
  323. new_fs = odoo.tools.config.filestore(new_name)
  324. if os.path.exists(old_fs) and not os.path.exists(new_fs):
  325. shutil.move(old_fs, new_fs)
  326. return True
  327. @check_db_management_enabled
  328. def exp_change_admin_password(new_password):
  329. odoo.tools.config.set_admin_password(new_password)
  330. odoo.tools.config.save(['admin_passwd'])
  331. return True
  332. @check_db_management_enabled
  333. def exp_migrate_databases(databases):
  334. for db in databases:
  335. _logger.info('migrate database %s', db)
  336. odoo.tools.config['update']['base'] = True
  337. odoo.modules.registry.Registry.new(db, force_demo=False, update_module=True)
  338. return True
  339. #----------------------------------------------------------
  340. # No master password required
  341. #----------------------------------------------------------
  342. @odoo.tools.mute_logger('odoo.sql_db')
  343. def exp_db_exist(db_name):
  344. ## Not True: in fact, check if connection to database is possible. The database may exists
  345. try:
  346. db = odoo.sql_db.db_connect(db_name)
  347. with db.cursor():
  348. return True
  349. except Exception:
  350. return False
  351. def list_dbs(force=False):
  352. if not odoo.tools.config['list_db'] and not force:
  353. raise odoo.exceptions.AccessDenied()
  354. if not odoo.tools.config['dbfilter'] and odoo.tools.config['db_name']:
  355. # In case --db-filter is not provided and --database is passed, Odoo will not
  356. # fetch the list of databases available on the postgres server and instead will
  357. # use the value of --database as comma seperated list of exposed databases.
  358. res = sorted(db.strip() for db in odoo.tools.config['db_name'].split(','))
  359. return res
  360. chosen_template = odoo.tools.config['db_template']
  361. templates_list = tuple({'postgres', chosen_template})
  362. db = odoo.sql_db.db_connect('postgres')
  363. with closing(db.cursor()) as cr:
  364. try:
  365. cr.execute("select datname from pg_database where datdba=(select usesysid from pg_user where usename=current_user) and not datistemplate and datallowconn and datname not in %s order by datname", (templates_list,))
  366. return [name for (name,) in cr.fetchall()]
  367. except Exception:
  368. _logger.exception('Listing databases failed:')
  369. return []
  370. def list_db_incompatible(databases):
  371. """"Check a list of databases if they are compatible with this version of Odoo
  372. :param databases: A list of existing Postgresql databases
  373. :return: A list of databases that are incompatible
  374. """
  375. incompatible_databases = []
  376. server_version = '.'.join(str(v) for v in version_info[:2])
  377. for database_name in databases:
  378. with closing(db_connect(database_name).cursor()) as cr:
  379. if odoo.tools.sql.table_exists(cr, 'ir_module_module'):
  380. cr.execute("SELECT latest_version FROM ir_module_module WHERE name=%s", ('base',))
  381. base_version = cr.fetchone()
  382. if not base_version or not base_version[0]:
  383. incompatible_databases.append(database_name)
  384. else:
  385. # e.g. 10.saas~15
  386. local_version = '.'.join(base_version[0].split('.')[:2])
  387. if local_version != server_version:
  388. incompatible_databases.append(database_name)
  389. else:
  390. incompatible_databases.append(database_name)
  391. for database_name in incompatible_databases:
  392. # release connection
  393. odoo.sql_db.close_db(database_name)
  394. return incompatible_databases
  395. def exp_list(document=False):
  396. if not odoo.tools.config['list_db']:
  397. raise odoo.exceptions.AccessDenied()
  398. return list_dbs()
  399. def exp_list_lang():
  400. return odoo.tools.misc.scan_languages()
  401. def exp_list_countries():
  402. list_countries = []
  403. root = ET.parse(os.path.join(odoo.tools.config['root_path'], 'addons/base/data/res_country_data.xml')).getroot()
  404. for country in root.find('data').findall('record[@model="res.country"]'):
  405. name = country.find('field[@name="name"]').text
  406. code = country.find('field[@name="code"]').text
  407. list_countries.append([code, name])
  408. return sorted(list_countries, key=lambda c: c[1])
  409. def exp_server_version():
  410. """ Return the version of the server
  411. Used by the client to verify the compatibility with its own version
  412. """
  413. return odoo.release.version
  414. #----------------------------------------------------------
  415. # db service dispatch
  416. #----------------------------------------------------------
  417. def dispatch(method, params):
  418. g = globals()
  419. exp_method_name = 'exp_' + method
  420. if method in ['db_exist', 'list', 'list_lang', 'server_version']:
  421. return g[exp_method_name](*params)
  422. elif exp_method_name in g:
  423. passwd = params[0]
  424. params = params[1:]
  425. check_super(passwd)
  426. return g[exp_method_name](*params)
  427. else:
  428. raise KeyError("Method not found: %s" % method)
上海开阖软件有限公司 沪ICP备12045867号-1