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.

173 lines
6.0 KiB

  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 LasLabs Inc.
  3. # Copyright 2018 ACSONE SA/NV.
  4. # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl).
  5. import json
  6. import logging
  7. import os
  8. from openerp import api, exceptions, models, tools
  9. from openerp.modules.module import get_module_path
  10. from ..addon_hash import addon_hash
  11. PARAM_INSTALLED_CHECKSUMS = \
  12. 'module_auto_update.installed_checksums'
  13. PARAM_EXCLUDE_PATTERNS = \
  14. 'module_auto_update.exclude_patterns'
  15. DEFAULT_EXCLUDE_PATTERNS = \
  16. '*.pyc,*.pyo,i18n/*.pot,i18n_extra/*.pot,static/*'
  17. _logger = logging.getLogger(__name__)
  18. class FailedUpgradeError(exceptions.Warning):
  19. pass
  20. class IncompleteUpgradeError(exceptions.Warning):
  21. pass
  22. def ensure_module_state(env, modules, state):
  23. # read module states, bypassing any Odoo cache
  24. env.cr.execute(
  25. "SELECT name FROM ir_module_module "
  26. "WHERE id IN %s AND state != %s",
  27. (tuple(modules.ids), state),
  28. )
  29. names = [r[0] for r in env.cr.fetchall()]
  30. if names:
  31. raise FailedUpgradeError(
  32. "The following modules should be in state '%s' "
  33. "at this stage: %s. Bailing out for safety." %
  34. (state, ','.join(names), ),
  35. )
  36. class Module(models.Model):
  37. _inherit = 'ir.module.module'
  38. @api.multi
  39. def _get_checksum_dir(self):
  40. self.ensure_one()
  41. exclude_patterns = self.env["ir.config_parameter"].get_param(
  42. PARAM_EXCLUDE_PATTERNS,
  43. DEFAULT_EXCLUDE_PATTERNS,
  44. )
  45. exclude_patterns = [p.strip() for p in exclude_patterns.split(',')]
  46. keep_langs = self.env['res.lang'].search([]).mapped('code')
  47. module_path = get_module_path(self.name)
  48. if module_path and os.path.isdir(module_path):
  49. checksum_dir = addon_hash(
  50. module_path,
  51. exclude_patterns,
  52. keep_langs,
  53. )
  54. else:
  55. checksum_dir = False
  56. return checksum_dir
  57. @api.model
  58. def _get_saved_checksums(self):
  59. Icp = self.env['ir.config_parameter']
  60. return json.loads(Icp.get_param(PARAM_INSTALLED_CHECKSUMS, '{}'))
  61. @api.model
  62. def _save_checksums(self, checksums):
  63. Icp = self.env['ir.config_parameter']
  64. Icp.set_param(PARAM_INSTALLED_CHECKSUMS, json.dumps(checksums))
  65. @api.model
  66. def _save_installed_checksums(self):
  67. checksums = {}
  68. installed_modules = self.search([('state', '=', 'installed')])
  69. for module in installed_modules:
  70. checksums[module.name] = module._get_checksum_dir()
  71. self._save_checksums(checksums)
  72. @api.model
  73. def _get_modules_partially_installed(self):
  74. return self.search([
  75. ('state', 'in', ('to install', 'to remove', 'to upgrade')),
  76. ])
  77. @api.model
  78. def _get_modules_with_changed_checksum(self):
  79. saved_checksums = self._get_saved_checksums()
  80. installed_modules = self.search([('state', '=', 'installed')])
  81. return installed_modules.filtered(
  82. lambda r: r._get_checksum_dir() != saved_checksums.get(r.name),
  83. )
  84. @api.model
  85. def upgrade_changed_checksum(self, overwrite_existing_translations=False):
  86. """Run an upgrade of the database, upgrading only changed modules.
  87. Installed modules for which the checksum has changed since the
  88. last successful run of this method are marked "to upgrade",
  89. then the normal Odoo scheduled upgrade process
  90. is launched.
  91. If there is no module with a changed checksum, and no module in state
  92. other than installed, uninstalled, uninstallable, this method does
  93. nothing, otherwise the normal Odoo upgrade process is launched.
  94. After a successful upgrade, the checksums of installed modules are
  95. saved.
  96. In case of error during the upgrade, an exception is raised.
  97. If any module remains to upgrade or to uninstall after the upgrade
  98. process, an exception is raised as well.
  99. Note: this method commits the current transaction at each important
  100. step, it is therefore not intended to be run as part of a
  101. larger transaction.
  102. """
  103. _logger.info(
  104. "Checksum upgrade starting (i18n-overwrite=%s)...",
  105. overwrite_existing_translations
  106. )
  107. tools.config['overwrite_existing_translations'] = \
  108. overwrite_existing_translations
  109. _logger.info("Updating modules list...")
  110. self.update_list()
  111. changed_modules = self._get_modules_with_changed_checksum()
  112. if not changed_modules and not self._get_modules_partially_installed():
  113. _logger.info("No checksum change detected in installed modules "
  114. "and all modules installed, nothing to do.")
  115. return
  116. _logger.info("Marking the following modules to upgrade, "
  117. "for their checksums changed: %s...",
  118. ','.join(changed_modules.mapped('name')))
  119. changed_modules.button_upgrade()
  120. self.env.cr.commit() # pylint: disable=invalid-commit
  121. # in rare situations, button_upgrade may fail without
  122. # exception, this would lead to corruption because
  123. # no upgrade would be performed and save_installed_checksums
  124. # would update cheksums for modules that have not been upgraded
  125. ensure_module_state(self.env, changed_modules, 'to upgrade')
  126. _logger.info("Upgrading...")
  127. self.env['base.module.upgrade'].upgrade_module()
  128. self.env.cr.commit() # pylint: disable=invalid-commit
  129. _logger.info("Upgrade successful, updating checksums...")
  130. self._save_installed_checksums()
  131. self.env.cr.commit() # pylint: disable=invalid-commit
  132. partial_modules = self._get_modules_partially_installed()
  133. if partial_modules:
  134. raise IncompleteUpgradeError(
  135. "Checksum upgrade successful "
  136. "but incomplete for the following modules: %s" %
  137. ','.join(partial_modules.mapped('name'))
  138. )
  139. _logger.info("Checksum upgrade complete.")