├── tests ├── __init__.py ├── examples │ ├── migration_mixed_digits2.yml │ ├── migration_mixed_digits.yml │ ├── migration.yml │ ├── migration_no_backup.yml │ └── migration_with_backup.yml ├── context.py ├── test_parse.py ├── test_operation.py ├── test_version.py ├── test_env_default.py ├── test_migration_file.py └── test_backup.py ├── marabunta ├── __init__.py ├── __main__.py ├── helpers.py ├── output.py ├── exception.py ├── web.py ├── version.py ├── html │ └── migration.html ├── core.py ├── database.py ├── runner.py ├── parser.py ├── config.py └── model.py ├── setup.cfg ├── .gitattributes ├── MANIFEST.in ├── .github ├── dependabot.yml └── workflows │ └── main.yml ├── AUTHORS.rst ├── .flake8 ├── tox.ini ├── .gitignore ├── setup.py ├── .pre-commit-config.yaml ├── README.rst ├── HISTORY.rst └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /marabunta/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal=1 3 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | HISTORY.rst merge=union 2 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include HISTORY.rst 3 | include-recursive marabunta/html * 4 | -------------------------------------------------------------------------------- /marabunta/__main__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from .core import main 4 | 5 | main() 6 | -------------------------------------------------------------------------------- /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: pip 4 | directory: "/" 5 | schedule: 6 | interval: daily 7 | time: "02:00" 8 | open-pull-requests-limit: 99 9 | -------------------------------------------------------------------------------- /marabunta/helpers.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016-2017 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | import sys 6 | PY3 = sys.version_info[0] == 3 7 | string_types = (str, bytes) if PY3 else (str, unicode) # noqa 8 | -------------------------------------------------------------------------------- /AUTHORS.rst: -------------------------------------------------------------------------------- 1 | Author 2 | ------ 3 | 4 | - Guewen Baconnier (Camptocamp) 5 | 6 | Contributors 7 | ------------ 8 | 9 | - Leonardo Pistone (Camptocamp) 10 | - Sébastien Alix (Camptocamp) 11 | - Simone Orsi (Camptocamp) 12 | - Iván Todorovitch (Camptocamp) 13 | - Yannick Vaucher (Camptocamp) 14 | - Alexandre Fayolle (Camptocamp) 15 | - Stéphane Mangin (Camptocamp) 16 | -------------------------------------------------------------------------------- /tests/examples/migration_mixed_digits2.yml: -------------------------------------------------------------------------------- 1 | migration: 2 | options: 3 | # --workers=0 --stop-after-init are automatically added 4 | install_command: odoo 5 | install_args: --log-level=debug 6 | versions: 7 | - version: setup 8 | - version: 10.17.0 9 | - version: 10.17.1 10 | # here we switch to new versioning 11 | - version: 10.0.0.18.0 12 | - version: 10.0.0.19.0 13 | 14 | -------------------------------------------------------------------------------- /.flake8: -------------------------------------------------------------------------------- 1 | [flake8] 2 | max-line-length = 88 3 | max-complexity = 16 4 | # B = bugbear 5 | # B9 = bugbear opinionated (incl line length) 6 | select = E,F,W,B,B9 7 | # E203: whitespace before ':' (black behaviour) 8 | # E501: flake8 line length (covered by bugbear B950) 9 | # W503: line break before binary operator (black behaviour) 10 | # W504: line break after binary operator (black behaviour) 11 | ignore = E203,E501,W503,W504 12 | exclude = 13 | ./.git 14 | .eggs/ 15 | -------------------------------------------------------------------------------- /tests/context.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # flake8: noqa 4 | # we want to ignore: 5 | # F401 'marabunta' imported but unused 6 | # E402 module level import not at top of file 7 | 8 | import os 9 | import sys 10 | sys.path.insert(0, os.path.abspath('..')) 11 | 12 | # put the marabunta package in the python path so we can use 13 | # it in tests without the need to be installed in site-packages 14 | 15 | import marabunta # noqa: imported from other test files 16 | -------------------------------------------------------------------------------- /tests/examples/migration_mixed_digits.yml: -------------------------------------------------------------------------------- 1 | migration: 2 | options: 3 | # --workers=0 --stop-after-init are automatically added 4 | install_command: odoo 5 | install_args: --log-level=debug 6 | versions: 7 | - version: setup 8 | - version: 11.0.2 9 | - version: 11.1.0 10 | - version: 11.1.5 11 | - version: 11.2.0 12 | - version: 11.3.0 13 | # here we switch to new versioning 14 | - version: 11.0.0.3.1 15 | - version: 11.0.0.3.2 16 | - version: 11.0.1.0.0 17 | - version: 11.0.2.0.0 18 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py38,py39,py310,py311,lint 3 | 4 | [testenv] 5 | extras = test 6 | commands = py.test {posargs} 7 | 8 | [testenv:lint] 9 | basepython = python3.11 10 | skip_install=true 11 | deps = 12 | flake8 13 | readme_renderer 14 | commands = 15 | flake8 {posargs} marabunta/ tests/ 16 | python setup.py check -r -s 17 | 18 | [testenv:docs] 19 | deps = 20 | Sphinx>=1.4.0 21 | . 22 | commands = 23 | sphinx-build -E -W -c docs -b html docs/ docs/_build/html 24 | 25 | [pytest] 26 | addopts = -q 27 | norecursedirs = *.egg .git .* _* 28 | -------------------------------------------------------------------------------- /marabunta/output.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016-2017 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | import sys 6 | 7 | LOG_DECORATION = u'|> ' 8 | 9 | supports_colors = hasattr(sys.stdout, 'isatty') and sys.stdout.isatty() 10 | 11 | 12 | def print_decorated(message, *args, **kwargs): 13 | if supports_colors: 14 | template = u'\033[1m{}{}\033[0m' 15 | else: 16 | template = u'{}{}' 17 | message = template.format( 18 | LOG_DECORATION, 19 | message, 20 | ) 21 | safe_print(message, *args, **kwargs) 22 | 23 | 24 | def safe_print(ustring, errors='replace', **kwargs): 25 | """ Safely print a unicode string """ 26 | encoding = sys.stdout.encoding or 'utf-8' 27 | if sys.version_info[0] == 3: 28 | print(ustring, **kwargs) 29 | else: 30 | bytestr = ustring.encode(encoding, errors=errors) 31 | print(bytestr, **kwargs) 32 | -------------------------------------------------------------------------------- /tests/examples/migration.yml: -------------------------------------------------------------------------------- 1 | migration: 2 | options: 3 | # --workers=0 --stop-after-init are automatically added 4 | install_command: odoo 5 | install_args: --log-level=debug 6 | versions: 7 | - version: setup 8 | operations: 9 | pre: # executed before 'addons' 10 | - echo 'pre-operation' 11 | post: # executed after 'addons' 12 | - echo 'post-operation' 13 | modes: 14 | full: 15 | operations: 16 | pre: 17 | - echo 'pre-operation executed only when the mode is full' 18 | sample: 19 | operations: 20 | post: 21 | - echo 'post-operation executed only when the mode is sample' 22 | 23 | - version: 0.0.2 24 | # nothing to do 25 | 26 | - version: 0.0.3 27 | operations: 28 | pre: 29 | - echo 'foobar' 30 | - echo 'foobarbaz' 31 | post: 32 | - echo 'post-op with unicode é â' 33 | 34 | - version: 0.0.4 35 | -------------------------------------------------------------------------------- /tests/examples/migration_no_backup.yml: -------------------------------------------------------------------------------- 1 | migration: 2 | options: 3 | # --workers=0 --stop-after-init are automatically added 4 | install_command: odoo 5 | install_args: --log-level=debug 6 | versions: 7 | - version: 0.0.1 8 | operations: 9 | pre: # executed before 'addons' 10 | - echo 'pre-operation' 11 | post: # executed after 'addons' 12 | - echo 'post-operation' 13 | modes: 14 | full: 15 | operations: 16 | pre: 17 | - echo 'pre-operation executed only when the mode is full' 18 | sample: 19 | operations: 20 | post: 21 | - echo 'post-operation executed only when the mode is sample' 22 | 23 | - version: 0.0.2 24 | # nothing to do 25 | 26 | - version: 0.0.3 27 | operations: 28 | pre: 29 | - echo 'foobar' 30 | - echo 'foobarbaz' 31 | post: 32 | - echo 'post-op with unicode é â' 33 | 34 | - version: 0.0.4 35 | -------------------------------------------------------------------------------- /marabunta/exception.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016-2017 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | 6 | class MarabuntaError(Exception): 7 | pass 8 | 9 | 10 | class MigrationError(Exception): 11 | pass 12 | 13 | 14 | class ParseError(MarabuntaError): 15 | 16 | def __init__(self, message, example=None): 17 | super(ParseError, self).__init__(message) 18 | self.example = example 19 | 20 | def __str__(self): 21 | if not self.example: 22 | return super(ParseError, self).__str__() 23 | msg = (u'An error occured during the parsing of the configuration ' 24 | u'file. Here is an example to help you to figure out ' 25 | u'your issue.\n{}\n{}').format(self.example, self.args[0]) 26 | return msg 27 | 28 | 29 | class ConfigurationError(MarabuntaError): 30 | pass 31 | 32 | 33 | class OperationError(MarabuntaError): 34 | pass 35 | 36 | 37 | class BackupError(MigrationError): 38 | """An error happened during the execution of the backup. 39 | """ 40 | pass 41 | -------------------------------------------------------------------------------- /tests/examples/migration_with_backup.yml: -------------------------------------------------------------------------------- 1 | migration: 2 | options: 3 | # --workers=0 --stop-after-init are automatically added 4 | install_command: odoo 5 | install_args: --log-level=debug 6 | backup: 7 | command: echo "backup command" 8 | stop_on_failure: true 9 | ignore_if: test 1 != 1 10 | versions: 11 | - version: setup 12 | operations: 13 | pre: # executed before 'addons' 14 | - echo 'pre-operation' 15 | post: # executed after 'addons' 16 | - echo 'post-operation' 17 | modes: 18 | full: 19 | operations: 20 | pre: 21 | - echo 'pre-operation executed only when the mode is full' 22 | sample: 23 | operations: 24 | post: 25 | - echo 'post-operation executed only when the mode is sample' 26 | 27 | - version: 0.0.2 28 | # nothing to do 29 | 30 | - version: 0.0.3 31 | operations: 32 | pre: 33 | - echo 'foobar' 34 | - echo 'foobarbaz' 35 | post: 36 | - echo 'post-op with unicode é â' 37 | 38 | - version: 0.0.4 39 | backup: true 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by https://www.gitignore.io/api/python 2 | 3 | ### Python ### 4 | # Byte-compiled / optimized / DLL files 5 | __pycache__/ 6 | *.py[cod] 7 | *$py.class 8 | 9 | # C extensions 10 | *.so 11 | 12 | # Distribution / packaging 13 | .Python 14 | env/ 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | *.egg-info/ 27 | .installed.cfg 28 | *.egg 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *,cover 49 | .hypothesis/ 50 | .pytest_cache/ 51 | 52 | # Translations 53 | *.mo 54 | *.pot 55 | 56 | # Django stuff: 57 | *.log 58 | local_settings.py 59 | 60 | # Flask stuff: 61 | instance/ 62 | .webassets-cache 63 | 64 | # Scrapy stuff: 65 | .scrapy 66 | 67 | # Sphinx documentation 68 | docs/_build/ 69 | 70 | # PyBuilder 71 | target/ 72 | 73 | # IPython Notebook 74 | .ipynb_checkpoints 75 | 76 | # pyenv 77 | .python-version 78 | 79 | # celery beat schedule file 80 | celerybeat-schedule 81 | 82 | # dotenv 83 | .env 84 | .env3 85 | 86 | # virtualenv 87 | venv/ 88 | ENV/ 89 | 90 | # Spyder project settings 91 | .spyderproject 92 | 93 | # Rope project settings 94 | .ropeproject 95 | 96 | # editors 97 | TAGS 98 | -------------------------------------------------------------------------------- /tests/test_parse.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016-2017 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | 6 | from io import StringIO 7 | import pytest 8 | from marabunta.parser import YamlParser, YAML_EXAMPLE 9 | from ruamel.yaml.constructor import DuplicateKeyError 10 | 11 | YAML_WITH_EXCEPTION = u""" 12 | migration: 13 | options: 14 | # --workers=0 --stop-after-init are automatically added 15 | install_command: odoo 16 | install_args: --log-level=debug 17 | backup: 18 | command: echo "backup command on $database $db_user $db_password $db_host $db_port" 19 | stop_on_failure: true 20 | ignore_if: test "${RUNNING_ENV}" != "prod" 21 | versions: 22 | - version: setup 23 | operations: 24 | pre: # executed before 'addons' 25 | - echo 'pre-operation' 26 | addons: 27 | upgrade: # executed as odoo --stop-after-init -i/-u ... 28 | - base 29 | - document 30 | # remove: # uninstalled with a python script 31 | operations: 32 | post: # executed after 'addons' 33 | - anthem songs::install 34 | """ # noqa 35 | 36 | 37 | def test_parse_yaml_example(): 38 | file_example = StringIO(YAML_EXAMPLE) 39 | parser = YamlParser.parser_from_buffer(file_example) 40 | migration = parser.parse() 41 | assert len(migration.versions) == 4 42 | 43 | 44 | def test_dublicate_key_exception(): 45 | yaml_file = StringIO(YAML_WITH_EXCEPTION) 46 | with pytest.raises(DuplicateKeyError): 47 | parser = YamlParser.parser_from_buffer(yaml_file) 48 | parser.parse() 49 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Test and publish 2 | 3 | on: 4 | push: 5 | branches: 6 | - "master" 7 | tags: 8 | - "*.*.*" 9 | pull_request: 10 | 11 | jobs: 12 | 13 | lint: 14 | runs-on: ubuntu-latest 15 | steps: 16 | - uses: actions/checkout@v3 17 | - name: Setup Python 18 | uses: actions/setup-python@v4 19 | with: 20 | python-version: "3.11" 21 | - name: Install tox 22 | run: pip install tox 23 | - name: Run lint 24 | run: tox -e lint 25 | 26 | test: 27 | runs-on: ubuntu-latest 28 | strategy: 29 | matrix: 30 | python: ["3.8", "3.9", "3.10", "3.11"] 31 | 32 | steps: 33 | - uses: actions/checkout@v3 34 | - name: Setup Python 35 | uses: actions/setup-python@v4 36 | with: 37 | python-version: ${{ matrix.python }} 38 | - name: Install tox 39 | run: pip install tox 40 | - name: Run tests 41 | run: tox -e py 42 | 43 | deploy: 44 | runs-on: ubuntu-latest 45 | needs: [lint, test] 46 | if: startsWith(github.ref, 'refs/tags') 47 | steps: 48 | - uses: actions/checkout@v3 49 | - name: Setup Python 50 | uses: actions/setup-python@v4 51 | with: 52 | python-version: "3.11" 53 | - name: Install dependencies 54 | run: | 55 | python -m pip install --upgrade pip 56 | pip install build 57 | - name: Build package 58 | run: python -m build 59 | - name: Publish package to PyPI 60 | uses: pypa/gh-action-pypi-publish@release/v1 61 | with: 62 | user: __token__ 63 | password: ${{ secrets.PYPI_API_TOKEN }} 64 | -------------------------------------------------------------------------------- /marabunta/web.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2017 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | import os 6 | 7 | from werkzeug.wrappers import Request, Response 8 | from werkzeug.serving import run_simple 9 | 10 | 11 | class WebApp(object): 12 | 13 | def __init__(self, host, port, custom_maintenance_file=None, 14 | resp_status=503, resp_retry_after=300, 15 | healthcheck_path=None): 16 | self.host = host 17 | self.port = port 18 | if not custom_maintenance_file: 19 | custom_maintenance_file = os.path.join( 20 | os.path.dirname(__file__), 21 | 'html/migration.html' 22 | ) 23 | self.resp_status = resp_status 24 | self.resp_retry_after = resp_retry_after 25 | self.healthcheck_path = healthcheck_path 26 | with open(custom_maintenance_file, 'r') as f: 27 | self.maintenance_html = f.read() 28 | 29 | def serve(self): 30 | run_simple(self.host, self.port, self) 31 | 32 | def dispatch_request(self, request): 33 | if self.healthcheck_path and request.path == self.healthcheck_path: 34 | # Return HTTP 200 for healthcheck kind of requests 35 | # It can be used on some platform to know that the service is 36 | # running as expected. 37 | return Response(self.maintenance_html, mimetype='text/html') 38 | return Response( 39 | self.maintenance_html, 40 | status=self.resp_status, 41 | headers={'Retry-After': self.resp_retry_after}, 42 | mimetype='text/html' 43 | ) 44 | 45 | def wsgi_app(self, environ, start_response): 46 | request = Request(environ) 47 | response = self.dispatch_request(request) 48 | return response(environ, start_response) 49 | 50 | def __call__(self, environ, start_response): 51 | return self.wsgi_app(environ, start_response) 52 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | import sys 3 | 4 | from setuptools import setup, find_packages 5 | 6 | if (sys.version_info[:3] < (3, 0)): 7 | with open('README.rst') as f: 8 | readme = f.read() 9 | else: 10 | with open('README.rst', encoding='utf-8') as f: 11 | readme = f.read() 12 | with open('HISTORY.rst') as f: 13 | history = f.read() 14 | 15 | test_deps = [ 16 | "pytest", 17 | "mock", 18 | ] 19 | 20 | extras = { 21 | 'test': test_deps, 22 | } 23 | 24 | setup( 25 | name='marabunta', 26 | use_scm_version=True, 27 | description='Migration tool for Odoo', 28 | long_description=readme + '\n\n' + history, 29 | author='Camptocamp (Guewen Baconnier)', 30 | author_email='guewen.baconnier@camptocamp.com', 31 | url='https://github.com/camptocamp/marabunta', 32 | license='AGPLv3+', 33 | packages=find_packages(exclude=('tests', 'docs')), 34 | install_requires=[ 35 | "psycopg2", 36 | "ruamel.yaml>=0.15.1", 37 | "pexpect", 38 | "werkzeug", 39 | ], 40 | setup_requires=[ 41 | 'setuptools_scm', 42 | ], 43 | tests_require=test_deps, 44 | extras_require=extras, 45 | include_package_data=True, 46 | package_data={ 47 | 'marabunta': ['html/*.html'], 48 | }, 49 | classifiers=( 50 | 'Development Status :: 3 - Alpha', 51 | 'Intended Audience :: Developers', 52 | 'Natural Language :: English', 53 | 'License :: OSI Approved :: ' 54 | 'GNU Affero General Public License v3 or later (AGPLv3+)', 55 | 'Programming Language :: Python', 56 | 'Programming Language :: Python :: 3', 57 | 'Programming Language :: Python :: 3.7', 58 | 'Programming Language :: Python :: 3.8', 59 | 'Programming Language :: Python :: 3.9', 60 | 'Programming Language :: Python :: 3.10', 61 | 'Programming Language :: Python :: 3.11', 62 | 'Programming Language :: Python :: Implementation :: CPython', 63 | 'Programming Language :: Python :: Implementation :: PyPy', 64 | ), 65 | entry_points={ 66 | 'console_scripts': ['marabunta = marabunta.core:main'] 67 | }, 68 | ) 69 | -------------------------------------------------------------------------------- /tests/test_operation.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016-2017 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | import os 6 | 7 | import pytest 8 | 9 | from marabunta.exception import BackupError 10 | from marabunta.model import Operation, SilentOperation, BackupOperation 11 | 12 | 13 | def test_from_single_unicode(): 14 | op = Operation(u'ls -l') 15 | assert op.command == 'ls -l' 16 | 17 | 18 | def test_from_single_str(): 19 | op = Operation('ls -l') 20 | assert op.command == 'ls -l' 21 | 22 | 23 | def test_from_list_of_unicode(): 24 | op = Operation([u'ls', u'-l']) 25 | assert op.command == 'ls -l' 26 | 27 | 28 | def test_from_list_of_str(): 29 | op = Operation(['ls', '-l']) 30 | assert op.command == 'ls -l' 31 | 32 | 33 | def test_log_execute_output(capfd): 34 | op = Operation(u'echo hello world') 35 | logs = [] 36 | 37 | def log(msg, **kwargs): 38 | logs.append(msg) 39 | 40 | op.execute(log) 41 | assert logs == [u'echo hello world', u'hello world'] 42 | assert capfd.readouterr() == (u'hello world\r\n', '') 43 | 44 | 45 | def test_shell_operation(capfd): 46 | # must be able to read env. variables 47 | test = os.environ['PYTEST_CURRENT_TEST'] 48 | op = Operation('echo $PYTEST_CURRENT_TEST', shell=True) 49 | logs = [] 50 | 51 | def log(msg, **kwargs): 52 | logs.append(msg) 53 | 54 | op.execute(log) 55 | assert logs == [u'echo $PYTEST_CURRENT_TEST', test] 56 | assert capfd.readouterr() == (u'%s\r\n' % test, '') 57 | 58 | 59 | def test_silent_operation(capfd): 60 | op = SilentOperation('echo foo') 61 | op.execute() 62 | assert capfd.readouterr() == ('', '') 63 | 64 | 65 | def test_silent_operation_shell(capfd): 66 | op = SilentOperation('echo foo', shell=True) 67 | op.execute() 68 | assert capfd.readouterr() == ('', '') 69 | 70 | 71 | def test_backup_operation_stop_on_failure(capfd): 72 | op = BackupOperation('false', stop_on_failure=True) 73 | with pytest.raises(BackupError): 74 | op.execute(lambda x: None) 75 | 76 | 77 | def test_backup_operation_no_stop_on_failure(capfd): 78 | op = BackupOperation('false', stop_on_failure=False) 79 | op.execute(lambda x: None) 80 | -------------------------------------------------------------------------------- /tests/test_version.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016-2018 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | from marabunta.version import MarabuntaVersion 6 | 7 | 8 | def test_marabuntaversion(): 9 | versions = ( 10 | ('1.5.1', '1.5.2b2', ValueError), 11 | ('161', '3.10a', ValueError), 12 | ('8.02', '8.02', ValueError), 13 | ('3.4j', '1996.07.12', ValueError), 14 | ('3.2.pl0', '3.1.1.6', ValueError), 15 | ('2g6', '11g', ValueError), 16 | ('0.9', '2.2', ValueError), 17 | ('1.2.1', '1.2', ValueError), 18 | ('1.1', '1.2.2', ValueError), 19 | ('1.2', '1.1', ValueError), 20 | ('1.2.1', '1.2.2', -1), 21 | ('1.2.2', '1.2', ValueError), 22 | ('1.2', '1.2.2', ValueError), 23 | ('0.4.0', '0.4', ValueError), 24 | ('1.13++', '5.5.kw', ValueError), 25 | 26 | ('0.4.0', '0.4.0', 0), 27 | ('0.4.0', '0.4.1', -1), 28 | ('0.4.1', '0.4.0', 1), 29 | ('0.4.0', '0.0.0.4.0', 0), 30 | ('9.9.6', '9.0.0.9.6', 0), 31 | ('9.0.1.2.3', '9.0.1.2.3', 0), 32 | ('9.0.1.2.3', '10.0.0.1.2', -1), 33 | ('10.0.1.2.3', '10.0.3.1.2', -1), 34 | ('10.0.0.1.0', '10.0.0.1.2', -1), 35 | ('11.0.0.0.1', '11.0.0.1.0', -1), 36 | ('9.0.1.2.3', '9.0.1.2.2', 1), 37 | ('10.0.3.1.2', '10.0.1.2.3', 1), 38 | ('10.0.0.1.2', '10.0.0.1.0', 1), 39 | ('11.0.0.1.0', '11.0.0.0.1', 1), 40 | 41 | ('setup', 'setup', 0), 42 | ('0.0.0', 'setup', 1), 43 | ('setup', '0.0.0', -1), 44 | ('0.0.0.0.0', 'setup', 1), 45 | ('setup', '0.0.0.0.0', -1), 46 | ('1.2.3', 'setup', 1), 47 | ('setup', '4.5.6', -1), 48 | ('11.0.1.0.0', 'setup', 1), 49 | ('setup', '10.0.0.0.1', -1), 50 | ) 51 | 52 | for v1, v2, expected in versions: 53 | try: 54 | actual = MarabuntaVersion(v1)._cmp(MarabuntaVersion(v2)) 55 | except ValueError: 56 | if expected is ValueError: 57 | continue 58 | else: 59 | raise AssertionError(("cmp(%s, %s) " 60 | "shouldn't raise ValueError") 61 | % (v1, v2)) 62 | assert expected == actual 63 | -------------------------------------------------------------------------------- /tests/test_env_default.py: -------------------------------------------------------------------------------- 1 | from marabunta.config import EnvDefault, BoolEnvDefault 2 | 3 | import os 4 | 5 | 6 | def test_env_default_str(): 7 | os.environ['test_var'] = 'Foo' 8 | test = EnvDefault('test_var', option_strings='', dest='test_var') 9 | assert test.default == 'Foo' 10 | 11 | 12 | def test_env_default_str_multiple(): 13 | os.environ['test_var_2'] = 'Foo' 14 | test = EnvDefault(('test_var', 'test_var_2'), option_strings='', dest='test_var') 15 | assert test.default == 'Foo' 16 | 17 | 18 | def test_env_default_with_regular_default(): 19 | # Env var is set, so it's used instead of the regular default 20 | os.environ['test_var_3'] = 'Foo' 21 | test = EnvDefault('test_var', option_strings='', dest='test_var', default='Bar') 22 | assert test.default == 'Foo' 23 | 24 | 25 | def test_env_default_with_regular_default_and_no_env_var(): 26 | # No env var set, so the regular default should be used 27 | test = EnvDefault('test_var_4', option_strings='', dest='test_var', default='Bar') 28 | assert test.default == 'Bar' 29 | 30 | 31 | def test_env_default_with_regular_default_and_no_env_var_and_no_regular_default(): 32 | # No env var set, no regular default, so it should be None 33 | test = EnvDefault('test_var_5', option_strings='', dest='test_var') 34 | assert test.default is None 35 | 36 | 37 | def test_bool_env_default_str(): 38 | os.environ['test_var'] = 'True' 39 | test = BoolEnvDefault('test_var', option_strings='', dest='test_var') 40 | assert test.default 41 | 42 | os.environ['test_var'] = 'true' 43 | test = BoolEnvDefault('test_var', option_strings='', dest='test_var') 44 | assert test.default 45 | 46 | os.environ['test_var'] = '1' 47 | test = BoolEnvDefault('test_var', option_strings='', dest='test_var') 48 | assert test.default 49 | 50 | os.environ['test_var'] = 'False' 51 | test = BoolEnvDefault('test_var', option_strings='', dest='test_var') 52 | assert not test.default 53 | 54 | os.environ['test_var'] = 'false' 55 | test = BoolEnvDefault('test_var', option_strings='', dest='test_var') 56 | assert not test.default 57 | 58 | os.environ['test_var'] = '3' 59 | test = BoolEnvDefault('test_var', option_strings='', dest='test_var') 60 | assert not test.default 61 | 62 | del os.environ['test_var'] 63 | test = BoolEnvDefault('test_var', option_strings='', dest='test_var') 64 | assert not test.default 65 | -------------------------------------------------------------------------------- /marabunta/version.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016-2018 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | import re 6 | from distutils.version import Version 7 | 8 | 9 | FIRST_VERSION = 'setup' 10 | 11 | 12 | class MarabuntaVersion(Version): 13 | 14 | """Version numbering for Camptocamp software idealists. 15 | Implements the Camptocamp interface for version number classes as 16 | described above. A version number consists of three or five 17 | dot-separated numeric components, without any options. 18 | 19 | The following are valid version numbers (shown in the order that 20 | would be obtained by sorting according to the supplied cmp function): 21 | 22 | 0.4.0 0.0.0.4.0 (these two are equivalent) 23 | 0.4.1 0.0.0.4.1 (these two are equivalent) 24 | 9.9.6 9.0.0.9.6 (these two are equivalent) 25 | 10.0.4 26 | 9.0.1.2.3 27 | 10.0.0.1.2 28 | 11.1.2.3.4 29 | 30 | The following are examples of invalid version numbers: 31 | 32 | 1 33 | 0.4 34 | 0.5a1 35 | 0.5b3 36 | 2.7.2.2 37 | 1.3.a4 38 | 1.3pl1 39 | 1.3c4 40 | 11.0.1.2.3a1 41 | 42 | """ 43 | 44 | version_re = re.compile( 45 | r'^(\d+)\.(\d+)\.(\d+)(\.(\d+)\.(\d+))?$|^' + FIRST_VERSION + '$', 46 | re.VERBOSE 47 | ) 48 | 49 | def parse(self, version_str): 50 | match = self.version_re.match(version_str) 51 | if not match: 52 | raise ValueError("invalid version number '%s'" % version_str) 53 | 54 | if match.string == FIRST_VERSION: 55 | self.version = match.string 56 | else: 57 | (major, minor, patch, revision, build) = \ 58 | match.group(1, 2, 3, 5, 6) 59 | 60 | if build: 61 | self.version = tuple(map(int, [ 62 | major, minor, patch, revision, build 63 | ])) 64 | else: 65 | self.version = tuple(map(int, [ 66 | major, 0, 0, minor, patch 67 | ])) 68 | 69 | def __str__(self): 70 | 71 | if self.version == FIRST_VERSION: 72 | return self.version 73 | 74 | version_str = '.'.join(map(str, self.version)) 75 | 76 | return version_str 77 | 78 | def __cmp__(self, other): 79 | return self._cmp(other) 80 | 81 | def _cmp(self, other): 82 | if isinstance(other, str): 83 | other = MarabuntaVersion(other) 84 | 85 | if self.version != other.version: 86 | if self.version == FIRST_VERSION: 87 | return -1 88 | if other.version == FIRST_VERSION: 89 | return 1 90 | if self.version < other.version: 91 | return -1 92 | else: 93 | return 1 94 | return 0 95 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | default_language_version: 2 | python: python3 3 | repos: 4 | - repo: local 5 | hooks: 6 | # These files are most likely copier diff rejection junks; if found, 7 | # review them manually, fix the problem (if needed) and remove them 8 | - id: forbidden-files 9 | name: forbidden files 10 | entry: found forbidden files; remove them 11 | language: fail 12 | files: "\\.rej$" 13 | - repo: https://github.com/myint/autoflake 14 | rev: v2.1.1 15 | hooks: 16 | - id: autoflake 17 | args: 18 | - --expand-star-imports 19 | - --ignore-init-module-imports 20 | - --in-place 21 | - --remove-all-unused-imports 22 | - --remove-duplicate-keys 23 | - --remove-unused-variables 24 | - repo: https://github.com/psf/black 25 | rev: 23.3.0 26 | hooks: 27 | - id: black 28 | - repo: https://github.com/pre-commit/mirrors-prettier 29 | rev: v3.1.0 30 | hooks: 31 | - id: prettier 32 | name: prettier (with plugin-xml) 33 | additional_dependencies: 34 | - "prettier@2.1.2" 35 | - "@prettier/plugin-xml@0.12.0" 36 | args: 37 | - --plugin=@prettier/plugin-xml 38 | files: \.(css|htm|html|js|json|jsx|less|md|scss|toml|ts|xml|yaml|yml)$ 39 | - repo: https://github.com/pre-commit/mirrors-eslint 40 | rev: v8.40.0 41 | hooks: 42 | - id: eslint 43 | verbose: true 44 | args: 45 | - --color 46 | - --fix 47 | - repo: https://github.com/pre-commit/pre-commit-hooks 48 | rev: v4.4.0 49 | hooks: 50 | - id: trailing-whitespace 51 | # exclude autogenerated files 52 | exclude: /README\.rst$|\.pot?$ 53 | - id: end-of-file-fixer 54 | # exclude autogenerated files 55 | exclude: /README\.rst$|\.pot?$ 56 | - id: debug-statements 57 | - id: fix-encoding-pragma 58 | args: ["--remove"] 59 | - id: check-case-conflict 60 | - id: check-docstring-first 61 | - id: check-executables-have-shebangs 62 | - id: check-merge-conflict 63 | # exclude files where underlines are not distinguishable from merge conflicts 64 | exclude: /README\.rst$|^docs/.*\.rst$ 65 | - id: check-symlinks 66 | - id: check-xml 67 | - id: mixed-line-ending 68 | args: ["--fix=lf"] 69 | - repo: https://github.com/asottile/pyupgrade 70 | rev: v3.4.0 71 | hooks: 72 | - id: pyupgrade 73 | args: ["--keep-percent-format"] 74 | - repo: https://github.com/PyCQA/isort 75 | rev: 5.12.0 76 | hooks: 77 | - id: isort 78 | name: isort except __init__.py 79 | args: 80 | - --settings=. 81 | exclude: /__init__\.py$ 82 | - repo: https://github.com/PyCQA/flake8 83 | rev: 6.0.0 84 | hooks: 85 | - id: flake8 86 | name: flake8 87 | additional_dependencies: ["flake8-bugbear==20.1.4"] 88 | -------------------------------------------------------------------------------- /marabunta/html/migration.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | odoo maintenance 6 | 7 | 8 | 113 | 114 | 115 |
116 |
117 |
Waiting...
118 |
119 |

odoo maintenance

120 |

An upgrade of the application is currently in progress... please come back later.

121 |
122 | 123 | 124 | -------------------------------------------------------------------------------- /marabunta/core.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016-2017 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | """ 6 | Marabunta is a name given to the migration of the legionary ants or to the ants 7 | themselves. Restless, they eat and digest everything in their way. 8 | 9 | This tool aims to run migrations for Odoo versions as efficiencly as a 10 | Marabunta migration. 11 | 12 | It loads migration instructions from a YAML file and run the operations if 13 | required. 14 | 15 | """ 16 | 17 | import logging 18 | import time 19 | import threading 20 | 21 | from .config import Config, get_args_parser 22 | from .database import Database, MigrationTable 23 | from .output import safe_print 24 | from .parser import YamlParser 25 | from .runner import Runner 26 | from .web import WebApp 27 | 28 | from pkg_resources import get_distribution, DistributionNotFound 29 | 30 | try: 31 | __version__ = get_distribution(__name__).version 32 | except DistributionNotFound: 33 | # package is not installed 34 | pass 35 | 36 | logging.getLogger('werkzeug').setLevel(logging.ERROR) 37 | 38 | # The number below has been generated as below: 39 | # pg_lock accepts an int8 so we build an hash composed with 40 | # contextual information and we throw away some bits 41 | # lock_name = 'marabunta' 42 | # hasher = hashlib.sha1() 43 | # hasher.update('{}'.format(lock_name)) 44 | # lock_ident = struct.unpack('q', hasher.digest()[:8]) 45 | # we just need an integer 46 | ADVISORY_LOCK_IDENT = 7141416871301361999 47 | 48 | 49 | def pg_advisory_lock(cursor, lock_ident): 50 | cursor.execute('SELECT pg_try_advisory_xact_lock(%s);', (lock_ident,)) 51 | acquired = cursor.fetchone()[0] 52 | return acquired 53 | 54 | 55 | class ApplicationLock(threading.Thread): 56 | 57 | def __init__(self, connection): 58 | self.acquired = False 59 | self.connection = connection 60 | self.replica = False 61 | self.stop = False 62 | super(ApplicationLock, self).__init__() 63 | 64 | def run(self): 65 | with self.connection.cursor() as cursor: 66 | # If the migration is run concurrently (in several 67 | # containers, hosts, ...), only 1 is allowed to proceed 68 | # with the migration. It will be the first one to win 69 | # the advisory lock. The others will be flagged as 'replica'. 70 | while not pg_advisory_lock(cursor, ADVISORY_LOCK_IDENT): 71 | if not self.replica: # print only the first time 72 | safe_print('A concurrent process is already ' 73 | 'running the migration') 74 | self.replica = True 75 | time.sleep(0.5) 76 | else: 77 | self.acquired = True 78 | idx = 0 79 | while not self.stop: 80 | # keep the connection alive to maintain the advisory 81 | # lock by running a query every 30 seconds 82 | if idx == 60: 83 | cursor.execute("SELECT 1") 84 | idx = 0 85 | idx += 1 86 | # keep the sleep small to be able to exit quickly 87 | # when 'stop' is set to True 88 | time.sleep(0.5) 89 | 90 | 91 | class WebServer(threading.Thread): 92 | 93 | def __init__(self, app): 94 | super(WebServer, self).__init__() 95 | self.app = app 96 | 97 | def run(self): 98 | self.app.serve() 99 | 100 | 101 | def migrate(config): 102 | """Perform a migration according to config. 103 | 104 | :param config: The configuration to be applied 105 | :type config: Config 106 | """ 107 | webapp = WebApp(config.web_host, config.web_port, 108 | custom_maintenance_file=config.web_custom_html, 109 | resp_status=config.web_resp_status, 110 | resp_retry_after=config.web_resp_retry_after, 111 | healthcheck_path=config.web_healthcheck_path) 112 | 113 | webserver = WebServer(webapp) 114 | webserver.daemon = True 115 | webserver.start() 116 | 117 | migration_parser = YamlParser.parse_from_file(config.migration_file) 118 | migration = migration_parser.parse() 119 | 120 | database = Database(config) 121 | 122 | with database.connect() as lock_connection: 123 | application_lock = ApplicationLock(lock_connection) 124 | application_lock.start() 125 | 126 | while not application_lock.acquired: 127 | time.sleep(0.5) 128 | else: 129 | if application_lock.replica: 130 | # when a replica could finally acquire a lock, it 131 | # means that the concurrent process has finished the 132 | # migration or that it failed to run it. 133 | # In both cases after the lock is released, this process will 134 | # verify if it has still to do something (if the other process 135 | # failed mainly). 136 | application_lock.stop = True 137 | application_lock.join() 138 | # we are not in the replica or the lock is released: go on for the 139 | # migration 140 | 141 | try: 142 | table = MigrationTable(database) 143 | runner = Runner(config, migration, database, table) 144 | runner.perform() 145 | finally: 146 | application_lock.stop = True 147 | application_lock.join() 148 | 149 | 150 | def main(): 151 | """Parse the command line and run :func:`migrate`.""" 152 | parser = get_args_parser() 153 | args = parser.parse_args() 154 | config = Config.from_parse_args(args) 155 | migrate(config) 156 | 157 | 158 | if __name__ == '__main__': 159 | main() 160 | -------------------------------------------------------------------------------- /marabunta/database.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016-2017 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | import json 6 | 7 | import psycopg2 8 | 9 | from collections import namedtuple 10 | from contextlib import contextmanager 11 | 12 | 13 | class Database(object): 14 | 15 | def __init__(self, config): 16 | self.config = config 17 | self.name = config.database 18 | 19 | def dsn(self): 20 | cfg = self.config 21 | params = { 22 | 'dbname': cfg.database, 23 | } 24 | if cfg.db_host: 25 | params['host'] = cfg.db_host 26 | if cfg.db_port: 27 | params['port'] = cfg.db_port 28 | if cfg.db_user: 29 | params['user'] = cfg.db_user 30 | if cfg.db_password: 31 | params['password'] = cfg.db_password 32 | return params 33 | 34 | @contextmanager 35 | def connect(self, autocommit=False): 36 | with psycopg2.connect(**self.dsn()) as conn: 37 | if autocommit: 38 | conn.autocommit = True 39 | yield conn 40 | 41 | @contextmanager 42 | def cursor_autocommit(self): 43 | with self.connect(autocommit=True) as conn: 44 | with conn.cursor() as cursor: 45 | yield cursor 46 | 47 | 48 | VersionRecord = namedtuple( 49 | 'VersionRecord', 50 | 'number date_start date_done log addons' 51 | ) 52 | 53 | 54 | class MigrationTable(object): 55 | 56 | def __init__(self, database): 57 | self.database = database 58 | self.table_name = 'marabunta_version' 59 | self.VersionRecord = VersionRecord 60 | self._versions = None 61 | 62 | def create_if_not_exists(self): 63 | with self.database.cursor_autocommit() as cursor: 64 | query = """ 65 | CREATE TABLE IF NOT EXISTS {} ( 66 | number VARCHAR NOT NULL, 67 | date_start TIMESTAMP NOT NULL, 68 | date_done TIMESTAMP, 69 | log TEXT, 70 | addons TEXT, 71 | 72 | CONSTRAINT version_pk PRIMARY KEY (number) 73 | ); 74 | """.format(self.table_name) 75 | cursor.execute(query) 76 | 77 | def versions(self): 78 | """ Read versions from the table 79 | 80 | The versions are kept in cache for the next reads. 81 | """ 82 | if self._versions is None: 83 | with self.database.cursor_autocommit() as cursor: 84 | query = """ 85 | SELECT number, 86 | date_start, 87 | date_done, 88 | log, 89 | addons 90 | FROM {} 91 | """.format(self.table_name) 92 | cursor.execute(query) 93 | rows = cursor.fetchall() 94 | versions = [] 95 | for row in rows: 96 | row = list(row) 97 | # convert 'addons' to json 98 | row[4] = json.loads(row[4]) if row[4] else [] 99 | versions.append( 100 | self.VersionRecord(*row) 101 | ) 102 | self._versions = versions 103 | return self._versions 104 | 105 | def start_version(self, number, start): 106 | with self.database.cursor_autocommit() as cursor: 107 | query = """ 108 | SELECT number FROM {} 109 | WHERE number = %s 110 | """.format(self.table_name) 111 | cursor.execute(query, (number,)) 112 | if cursor.fetchone(): 113 | query = """ 114 | UPDATE {} 115 | SET date_start = %s, 116 | date_done = NULL, 117 | log = NULL, 118 | addons = NULL 119 | WHERE number = %s 120 | """.format(self.table_name) 121 | cursor.execute(query, (start, number)) 122 | else: 123 | query = """ 124 | INSERT INTO {} 125 | (number, date_start) 126 | VALUES (%s, %s) 127 | """.format(self.table_name) 128 | cursor.execute(query, (number, start)) 129 | self._versions = None # reset versions cache 130 | 131 | def record_log(self, number, log): 132 | with self.database.cursor_autocommit() as cursor: 133 | query = """ 134 | UPDATE {} 135 | SET log = %s 136 | WHERE number = %s 137 | """.format(self.table_name) 138 | cursor.execute(query, (log, number)) 139 | self._versions = None # reset versions cache 140 | 141 | def finish_version(self, number, end, log, addons): 142 | with self.database.cursor_autocommit() as cursor: 143 | query = """ 144 | UPDATE {} 145 | SET date_done = %s, 146 | log = %s, 147 | addons = %s 148 | WHERE number = %s 149 | """.format(self.table_name) 150 | cursor.execute(query, (end, log, json.dumps(addons), number)) 151 | self._versions = None # reset versions cache 152 | 153 | 154 | class IrModuleModule(object): 155 | 156 | def __init__(self, database): 157 | self.database = database 158 | self.table_name = 'ir_module_module' 159 | self.ModuleRecord = namedtuple( 160 | 'ModuleRecord', 161 | 'name state' 162 | ) 163 | 164 | def read_state(self): 165 | with self.database.cursor_autocommit() as cursor: 166 | if not table_exists(cursor, self.table_name): 167 | # relation ir_module_module does not exists, 168 | # this is a new DB, no addon is installed 169 | return [] 170 | 171 | addons_query = """ 172 | SELECT name, state 173 | FROM {} 174 | """.format(self.table_name) 175 | cursor.execute(addons_query) 176 | rows = cursor.fetchall() 177 | return [self.ModuleRecord(*row) for row in rows] 178 | 179 | 180 | def table_exists(cursor, tablename, schema='public'): 181 | query = """ 182 | SELECT EXISTS ( 183 | SELECT 1 184 | FROM information_schema.tables 185 | WHERE table_schema = %s 186 | AND table_name = %s 187 | )""" 188 | cursor.execute(query, (schema, tablename)) 189 | res = cursor.fetchone()[0] 190 | return res 191 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | 🐜🐜🐜 Marabunta 🐜🐜🐜 2 | ======================= 3 | 4 | .. image:: https://travis-ci.org/camptocamp/marabunta.svg?branch=master 5 | :target: https://travis-ci.org/camptocamp/marabunta 6 | 7 | *Marabunta is a name given to the migration of the legionary ants or to the ants 8 | themselves. Restless, they eat and digest everything in their way.* 9 | 10 | Marabunta is used to provide an easy way to create Updates for Odoo fast and run easily. It also allows to differentiate between different environment to provide for instance sample data. 11 | 12 | 13 | Usage 14 | ===== 15 | After installing marabunta, it will be available as a console command. To run properly it requires a migration file (which defines what has to updated/executed) and odoos connection parameters (view options in the options section. 16 | 17 | At each run marabunta verifies the versions from the migration file and and processes new ones. 18 | It is very much recommended to configure it, so that marabunta is ran automatically if odoo is started. 19 | For instance adding it to your docker entrypoint. 20 | 21 | Features 22 | ======== 23 | 24 | * backup: Marabunta allows for a backup command to be executed before the migration. 25 | * addon upgrades: Marabunta is able to install or upgrade odoo addons. 26 | * operations: Allows to execute commands before or after upgrading modules. 27 | * modes: Modes allow the user to execute commands only on a certain environment. e.g. creation of sample data on a dev system. 28 | * maintenance page: publish an html page during the migration. 29 | 30 | Versioning systems 31 | ------------------ 32 | Currently Marabunta allows for two different Versioning systems: 33 | The classic Major.Minor.Bugfix and the Five digits long versions for OdooMajor.OdooMinor.Major.Minor.Bugfix. 34 | Although the first marabunta version must be **setup** for the initial setup of your instance. (Find out more about the rationale here ) 35 | 36 | 37 | Options 38 | ======= 39 | +-------------------------+----------+-----------------------------------+-------------------------------------------------------------------+ 40 | | option | shortcut | envvar | purpose | 41 | +=========================+==========+===================================+===================================================================+ 42 | | --migration-file | -f | MARABUNTA_MIGRATION_FILE | Definition file for the migration. | 43 | +-------------------------+----------+-----------------------------------+-------------------------------------------------------------------+ 44 | | --database | -d | MARABUNTA_DATABASE | Database we want to run the migration on. | 45 | +-------------------------+----------+-----------------------------------+-------------------------------------------------------------------+ 46 | | --db-user | -u | MARABUNTA_DB_USER, PGUSER | Database user. | 47 | +-------------------------+----------+-----------------------------------+-------------------------------------------------------------------+ 48 | | --db-password | -w | MARABUNTA_DB_PASSWORD, PGPASSWORD | Database password. | 49 | +-------------------------+----------+-----------------------------------+-------------------------------------------------------------------+ 50 | | --db-port | -p | MARABUNTA_DB_PORT, PGPORT | Database port (defaults to 5432). | 51 | +-------------------------+----------+-----------------------------------+-------------------------------------------------------------------+ 52 | | --db-host | -H | MARABUNTA_DB_HOST, PGHOST | Database port (defaults to None). | 53 | +-------------------------+----------+-----------------------------------+-------------------------------------------------------------------+ 54 | | --mode | | MARABUNTA_MODE | Mode marabunta runs in for different envs. | 55 | +-------------------------+----------+-----------------------------------+-------------------------------------------------------------------+ 56 | | --allow-serie | | MARABUNTA_ALLOW_SERIE | Allow multiple versions to be upgraded at once. | 57 | +-------------------------+----------+-----------------------------------+-------------------------------------------------------------------+ 58 | | --force-version | | MARABUNTA_FORCE_VERSION | Force the upgrade to a version no matter what. | 59 | +-------------------------+----------+-----------------------------------+-------------------------------------------------------------------+ 60 | | --override-translations | | MARABUNTA_OVERRIDE_TRANSLATIONS | Force translations override | 61 | +-------------------------+----------+-----------------------------------+-------------------------------------------------------------------+ 62 | | --web-host | | MARABUNTA_WEB_HOST | Interface to bind for the maintenance page. (defaults to 0.0.0.0).| 63 | +-------------------------+----------+-----------------------------------+-------------------------------------------------------------------+ 64 | | --web-port | | MARABUNTA_WEB_PORT | Port for the maintenance page. (defaults to 8069). | 65 | +-------------------------+----------+-----------------------------------+-------------------------------------------------------------------+ 66 | | --web-custom-html | | MARABUNTA_WEB_CUSTOM_HTML | Path to custom maintenance html page to serve. | 67 | +-------------------------+----------+-----------------------------------+-------------------------------------------------------------------+ 68 | 69 | YAML layout & Example 70 | ===================== 71 | Here is an Example migration file:: 72 | 73 | migration: 74 | options: 75 | # This includes general options which are used everytime marabunta is called. 76 | # --workers=0 --stop-after-init are automatically added 77 | install_command: odoo #Command which starts odoo 78 | install_args: --log-level=debug # additional Arguments 79 | backup: # Defines how the backup should be done before the migration. 80 | command: echo "backup command on ${DB_NAME}" 81 | stop_on_failure: true 82 | ignore_if: test "${RUNNING_ENV}" != "prod" 83 | versions: 84 | - version: setup # Setup is always the initia. version< 85 | operations: 86 | pre: # executed before 'addons' 87 | - echo 'pre-operation' 88 | post: # executed after 'addons' 89 | - anthem songs::install 90 | addons: 91 | upgrade: # executed as odoo --stop-after-init -i/-u ... 92 | - base 93 | - document 94 | modes: 95 | full: 96 | operations: 97 | pre: 98 | - echo 'pre-operation executed only when the mode is full' 99 | post: 100 | - anthem songs::load_production_data 101 | sample: 102 | operations: 103 | post: 104 | - anthem songs::load_sample_data 105 | addons: 106 | upgrade: 107 | - sample_addon 108 | 109 | - version: 0.0.2 110 | backup: false 111 | # nothing to do this can be used to keep marabunta and gittag in sync 112 | 113 | - version: 0.0.3 114 | operations: 115 | pre: # we also can execute os commands 116 | - echo 'foobar' 117 | - ls 118 | - bin/script_test.sh 119 | post: 120 | - echo 'post-op' 121 | 122 | - version: 0.0.4 123 | backup: false 124 | override_translations: true 125 | addons: 126 | upgrade: 127 | - popeye 128 | 129 | 130 | Run the tests 131 | ------------- 132 | 133 | To run ``marabunta`` tests, it is a good idea to do an *editable* 134 | install of it in a virtualenv, and then intall and run ``pytest`` as 135 | follows:: 136 | 137 | $ git clone https://github.com/camptocamp/marabunta.git 138 | Cloning into 'marabunta'... 139 | $ cd marabunta 140 | $ virtualenv -p YOUR_PYTHON env 141 | $ source env/bin/activate 142 | $ pip install '.[test]' 143 | $ py.test tests 144 | -------------------------------------------------------------------------------- /marabunta/runner.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016-2017 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | import traceback 6 | import sys 7 | 8 | from datetime import datetime 9 | 10 | from .database import IrModuleModule 11 | from .exception import MigrationError, OperationError 12 | from .output import print_decorated, safe_print 13 | from .version import MarabuntaVersion 14 | 15 | LOG_DECORATION = u'|> ' 16 | 17 | 18 | class Runner(object): 19 | 20 | def __init__(self, config, migration, database, table): 21 | self.config = config 22 | self.migration = migration 23 | self.database = database 24 | self.table = table 25 | # we keep the addons upgrading during a run in this set, 26 | # this is only useful when using 'allow_serie', 27 | # if an addon has just been installed or updated, 28 | # we don't want to do it again for another version 29 | self.upgraded_addons = set() 30 | 31 | def log(self, message, decorated=True, stdout=True): 32 | if not stdout: 33 | return 34 | if decorated: 35 | app_message = u'migration: {}'.format( 36 | message, 37 | ) 38 | print_decorated(app_message) 39 | else: 40 | safe_print(message) 41 | 42 | def perform(self): 43 | self.table.create_if_not_exists() 44 | 45 | db_versions = self.table.versions() 46 | 47 | if not self.config.force_version: 48 | unfinished = [db_version for db_version 49 | in db_versions 50 | if not db_version.date_done] 51 | if unfinished: 52 | raise MigrationError( 53 | u'Upgrade of version {} has been attempted and failed. ' 54 | u'You may want to restore the backup or to run again the ' 55 | u'migration with the MARABUNTA_FORCE_VERSION ' 56 | u'environment variable ' 57 | u'or to fix it manually (in that case, you will have to ' 58 | u'update the \'marabunta_version\' table yourself.' 59 | .format(u','.join(v.number for v in unfinished)) 60 | ) 61 | 62 | unprocessed = [version for version in self.migration.versions 63 | if not version.skip(db_versions)] 64 | 65 | if not self.config.allow_serie: 66 | if len(unprocessed) > 1: 67 | raise MigrationError( 68 | u'Only one version can be upgraded at a time.\n' 69 | u'The following versions need to be applied: {}.\n'.format( 70 | [v.number for v in unprocessed] 71 | ) 72 | ) 73 | 74 | if not self.config.force_version and db_versions and unprocessed: 75 | installed = max(MarabuntaVersion(v.number) for v in db_versions) 76 | next_unprocess = min( 77 | MarabuntaVersion(v.number) for v in unprocessed 78 | ) 79 | if installed > next_unprocess: 80 | raise MigrationError( 81 | u'The version you are trying to install ({}) is below ' 82 | u'the current database version ({}).'.format( 83 | next_unprocess, installed 84 | ) 85 | ) 86 | 87 | backup_options = self.migration.options.backup 88 | run_backup = False 89 | if backup_options: 90 | run_backup = ( 91 | # If we are forcing a version, we want a backup 92 | self.config.force_version 93 | # If any of the version not yet processed, including the noop 94 | # versions, need a backup, we run it. (note: by default, 95 | # noop versions don't trigger a backup but it can be 96 | # explicitly activated) 97 | or any(version.backup for version in self.migration.versions 98 | if not version.is_processed(db_versions)) 99 | ) 100 | if run_backup: 101 | try: 102 | backup_options.ignore_if_operation().execute() 103 | except OperationError: 104 | pass 105 | else: 106 | run_backup = False 107 | if run_backup: 108 | backup_operation = backup_options.command_operation(self.config) 109 | backup_operation.execute(self.log) 110 | 111 | for version in self.migration.versions: 112 | # when we force-execute one version, we skip all the others 113 | if self.config.force_version: 114 | if self.config.force_version != version.number: 115 | continue 116 | else: 117 | self.log( 118 | u'force-execute version {}'.format(version.number) 119 | ) 120 | 121 | self.log(u'processing version {}'.format(version.number)) 122 | VersionRunner(self, version).perform() 123 | 124 | 125 | class VersionRunner(object): 126 | 127 | def __init__(self, runner, version): 128 | self.runner = runner 129 | self.table = runner.table 130 | self.migration = runner.migration 131 | self.config = runner.config 132 | self.database = runner.database 133 | self.version = version 134 | self.logs = [] 135 | 136 | def log(self, message, decorated=True, stdout=True): 137 | self.logs.append(message) 138 | if not stdout: 139 | return 140 | if decorated: 141 | app_message = u'version {}: {}'.format( 142 | self.version.number, 143 | message, 144 | ) 145 | print_decorated(app_message) 146 | else: 147 | safe_print(message) 148 | 149 | def start(self): 150 | self.log(u'start') 151 | self.table.start_version(self.version.number, datetime.now()) 152 | 153 | def finish(self): 154 | self.log(u'done') 155 | module_table = IrModuleModule(self.database) 156 | addons_state = module_table.read_state() 157 | self.table.finish_version(self.version.number, datetime.now(), 158 | u'\n'.join(self.logs), 159 | [state._asdict() for state in addons_state]) 160 | 161 | def perform(self): 162 | """Perform the version upgrade on the database. 163 | """ 164 | db_versions = self.table.versions() 165 | 166 | version = self.version 167 | if (version.is_processed(db_versions) and 168 | not self.config.force_version == self.version.number): 169 | self.log( 170 | u'version {} is already installed'.format(version.number) 171 | ) 172 | return 173 | 174 | self.start() 175 | try: 176 | self._perform_version(version) 177 | except Exception: 178 | if sys.version_info < (3, 4): 179 | msg = traceback.format_exc().decode('utf8', errors='ignore') 180 | else: 181 | msg = traceback.format_exc() 182 | error = u'\n'.join(self.logs + [u'\n', msg]) 183 | self.table.record_log(version.number, error) 184 | raise 185 | self.finish() 186 | 187 | def _perform_version(self, version): 188 | """Inner method for version upgrade. 189 | 190 | Not intended for standalone use. This method performs the actual 191 | version upgrade with all the pre, post operations and addons upgrades. 192 | 193 | :param version: The migration version to upgrade to 194 | :type version: Instance of Version class 195 | """ 196 | if version.is_noop(): 197 | self.log(u'version {} is a noop'.format(version.number)) 198 | else: 199 | self.log(u'execute base pre-operations') 200 | for operation in version.pre_operations(): 201 | operation.execute(self.log) 202 | if self.config.mode: 203 | self.log(u'execute %s pre-operations' % self.config.mode) 204 | for operation in version.pre_operations(mode=self.config.mode): 205 | operation.execute(self.log) 206 | 207 | self.perform_addons() 208 | 209 | self.log(u'execute base post-operations') 210 | for operation in version.post_operations(): 211 | operation.execute(self.log) 212 | if self.config.mode: 213 | self.log(u'execute %s post-operations' % self.config.mode) 214 | for operation in version.post_operations(self.config.mode): 215 | operation.execute(self.log) 216 | 217 | def perform_addons(self): 218 | version = self.version 219 | 220 | module_table = IrModuleModule(self.database) 221 | addons_state = module_table.read_state() 222 | 223 | upgrade_operation = version.upgrade_addons_operation( 224 | addons_state, 225 | mode=self.config.mode 226 | ) 227 | # exclude the addons already installed or updated during this run 228 | # when 'allow_serie' is active 229 | exclude = self.runner.upgraded_addons 230 | self.log(u'installation / upgrade of addons') 231 | operation = upgrade_operation.operation(exclude_addons=exclude) 232 | if operation: 233 | operation.execute(self.log) 234 | self.runner.upgraded_addons |= (upgrade_operation.to_install | 235 | upgrade_operation.to_upgrade) 236 | -------------------------------------------------------------------------------- /marabunta/parser.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016-2017 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | import io 6 | from ruamel.yaml import YAML 7 | import warnings 8 | 9 | from .exception import ParseError 10 | from .model import ( 11 | Migration, 12 | MigrationOption, 13 | Version, 14 | Operation, 15 | MigrationBackupOption, 16 | ) 17 | from .version import FIRST_VERSION 18 | 19 | 20 | YAML_EXAMPLE = u""" 21 | migration: 22 | options: 23 | # --workers=0 --stop-after-init are automatically added 24 | install_command: odoo 25 | install_args: --log-level=debug 26 | backup: 27 | command: echo "backup command on $database $db_user $db_password $db_host $db_port" 28 | stop_on_failure: true 29 | ignore_if: test "${RUNNING_ENV}" != "prod" 30 | versions: 31 | - version: setup 32 | operations: 33 | pre: # executed before 'addons' 34 | - echo 'pre-operation' 35 | post: # executed after 'addons' 36 | - anthem songs::install 37 | addons: 38 | upgrade: # executed as odoo --stop-after-init -i/-u ... 39 | - base 40 | - document 41 | # remove: # uninstalled with a python script 42 | modes: 43 | full: 44 | operations: 45 | pre: 46 | - echo 'pre-operation executed only when the mode is full' 47 | post: 48 | - anthem songs::load_production_data 49 | sample: 50 | operations: 51 | post: 52 | - anthem songs::load_sample_data 53 | addons: 54 | upgrade: 55 | - sample_addon 56 | 57 | - version: 0.0.2 58 | backup: false 59 | # nothing to do 60 | 61 | - version: 0.0.3 62 | operations: 63 | pre: 64 | - echo 'foobar' 65 | - ls 66 | - bin/script_test.sh 67 | post: 68 | - echo 'post-op' 69 | 70 | - version: 0.0.4 71 | backup: false 72 | override_translations: true 73 | addons: 74 | upgrade: 75 | - popeye 76 | 77 | """ # noqa 78 | 79 | 80 | class YamlParser(object): 81 | 82 | def __init__(self, parsed): 83 | self.parsed = parsed 84 | 85 | @classmethod 86 | def parser_from_buffer(cls, fp): 87 | """Construct YamlParser from a file pointer.""" 88 | yaml = YAML(typ="safe") 89 | return cls(yaml.load(fp)) 90 | 91 | @classmethod 92 | def parse_from_file(cls, filename): 93 | """Construct YamlParser from a filename.""" 94 | with io.open(filename, 'r', encoding='utf-8') as fh: 95 | return cls.parser_from_buffer(fh) 96 | 97 | def check_dict_expected_keys(self, expected_keys, current, dict_name): 98 | """ Check that we don't have unknown keys in a dictionary. 99 | 100 | It does not raise an error if we have less keys than expected. 101 | """ 102 | if not isinstance(current, dict): 103 | raise ParseError(u"'{}' key must be a dict".format(dict_name), 104 | YAML_EXAMPLE) 105 | expected_keys = set(expected_keys) 106 | current_keys = {key for key in current} 107 | extra_keys = current_keys - expected_keys 108 | if extra_keys: 109 | message = u"{}: the keys {} are unexpected. (allowed keys: {})" 110 | raise ParseError( 111 | message.format( 112 | dict_name, 113 | list(extra_keys), 114 | list(expected_keys), 115 | ), 116 | YAML_EXAMPLE, 117 | ) 118 | 119 | def parse(self): 120 | """Check input and return a :class:`Migration` instance.""" 121 | if not self.parsed.get('migration'): 122 | raise ParseError(u"'migration' key is missing", YAML_EXAMPLE) 123 | self.check_dict_expected_keys( 124 | {'options', 'versions'}, self.parsed['migration'], 'migration', 125 | ) 126 | return self._parse_migrations() 127 | 128 | def _parse_migrations(self): 129 | """Build a :class:`Migration` instance.""" 130 | migration = self.parsed['migration'] 131 | options = self._parse_options(migration) 132 | versions = self._parse_versions(migration, options) 133 | return Migration(versions, options) 134 | 135 | def _parse_options(self, migration): 136 | """Build :class:`MigrationOption` and 137 | :class:`MigrationBackupOption` instances.""" 138 | options = migration.get('options', {}) 139 | install_command = options.get('install_command') 140 | backup = options.get('backup') 141 | if backup: 142 | self.check_dict_expected_keys( 143 | {'command', 'ignore_if', 'stop_on_failure'}, 144 | options['backup'], 'backup', 145 | ) 146 | backup = MigrationBackupOption( 147 | command=backup.get('command'), 148 | ignore_if=backup.get('ignore_if'), 149 | stop_on_failure=backup.get('stop_on_failure', True), 150 | ) 151 | return MigrationOption( 152 | install_command=install_command, 153 | backup=backup, 154 | ) 155 | 156 | def _parse_versions(self, migration, options): 157 | versions = migration.get('versions') or [] 158 | if not isinstance(versions, list): 159 | raise ParseError(u"'versions' key must be a list", YAML_EXAMPLE) 160 | if versions[0]['version'] != FIRST_VERSION: 161 | warnings_msg = u'First version should be named `setup`' 162 | warnings.warn(warnings_msg, FutureWarning) 163 | return [self._parse_version(version, options) for version in versions] 164 | 165 | def _parse_operations(self, version, operations, mode=None): 166 | self.check_dict_expected_keys( 167 | {'pre', 'post'}, operations, 'operations', 168 | ) 169 | for operation_type, commands in operations.items(): 170 | if not isinstance(commands, list): 171 | raise ParseError(u"'%s' key must be a list" % 172 | (operation_type,), YAML_EXAMPLE) 173 | for command in commands: 174 | version.add_operation( 175 | operation_type, 176 | Operation(command), 177 | mode=mode, 178 | ) 179 | 180 | def _parse_addons(self, version, addons, mode=None): 181 | self.check_dict_expected_keys( 182 | {'upgrade', 'remove'}, addons, 'addons', 183 | ) 184 | upgrade = addons.get('upgrade') or [] 185 | if upgrade: 186 | if not isinstance(upgrade, list): 187 | raise ParseError(u"'upgrade' key must be a list", YAML_EXAMPLE) 188 | version.add_upgrade_addons(upgrade, mode=mode) 189 | remove = addons.get('remove') or [] 190 | if remove: 191 | if not isinstance(remove, list): 192 | raise ParseError(u"'remove' key must be a list", YAML_EXAMPLE) 193 | version.add_remove_addons(remove, mode=mode) 194 | 195 | def _parse_backup(self, version, backup=True, mode=None): 196 | if not isinstance(backup, bool): 197 | raise ParseError(u"'backup' key must be a boolean", YAML_EXAMPLE) 198 | version.backup = backup 199 | 200 | def _parse_override_translations(self, version, parsed_version): 201 | override_translations = parsed_version.get('override_translations') 202 | if override_translations not in (True, False, None): 203 | raise ParseError( 204 | "'override_translations' key must be a boolean", YAML_EXAMPLE 205 | ) 206 | version.override_translations = override_translations 207 | 208 | def _parse_version(self, parsed_version, options): 209 | self.check_dict_expected_keys( 210 | { 211 | "version", 212 | "operations", 213 | "addons", 214 | "modes", 215 | "backup", 216 | "override_translations", 217 | }, 218 | parsed_version, 219 | "versions", 220 | ) 221 | number = parsed_version.get('version') 222 | version = Version(number, options) 223 | 224 | # parse the main operations, backup and addons 225 | operations = parsed_version.get('operations') or {} 226 | self._parse_operations(version, operations) 227 | 228 | addons = parsed_version.get('addons') or {} 229 | self._parse_addons(version, addons) 230 | 231 | # parse the modes operations and addons 232 | modes = parsed_version.get('modes', {}) 233 | if not isinstance(modes, dict): 234 | raise ParseError(u"'modes' key must be a dict", YAML_EXAMPLE) 235 | for mode_name, mode in modes.items(): 236 | self.check_dict_expected_keys( 237 | {'operations', 'addons'}, mode, mode_name, 238 | ) 239 | mode_operations = mode.get('operations') or {} 240 | self._parse_operations(version, mode_operations, mode=mode_name) 241 | 242 | mode_addons = mode.get('addons') or {} 243 | self._parse_addons(version, mode_addons, mode=mode_name) 244 | 245 | # backup should be added last, as it depends if the version is noop 246 | backup = parsed_version.get('backup') 247 | if backup is None: 248 | if version.is_noop(): 249 | # For noop steps backup defaults to False 250 | backup = False 251 | else: 252 | backup = True 253 | self._parse_backup(version, backup) 254 | 255 | # If translations needs to be overridden 256 | self._parse_override_translations(version, parsed_version) 257 | 258 | return version 259 | -------------------------------------------------------------------------------- /marabunta/config.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016-2017 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | from distutils.util import strtobool 6 | import argparse 7 | import os 8 | 9 | 10 | class Config(object): 11 | def __init__(self, 12 | migration_file, 13 | database, 14 | db_user=None, 15 | db_password=None, 16 | db_port=5432, 17 | db_host='localhost', 18 | mode=None, 19 | allow_serie=False, 20 | force_version=None, 21 | override_translations=False, 22 | web_host='localhost', 23 | web_port=8069, 24 | web_resp_status=503, 25 | web_resp_retry_after=300, # 5 minutes 26 | web_custom_html=None, 27 | web_healthcheck_path=None): 28 | self.migration_file = migration_file 29 | self.database = database 30 | self.db_user = db_user 31 | self.db_password = db_password 32 | self.db_port = db_port 33 | self.db_host = db_host 34 | self.mode = mode 35 | self.allow_serie = allow_serie 36 | self.force_version = force_version 37 | if force_version and not allow_serie: 38 | self.allow_serie = True 39 | self.override_translations = override_translations 40 | self.web_host = web_host 41 | self.web_port = web_port 42 | self.web_resp_status = web_resp_status 43 | self.web_resp_retry_after = web_resp_retry_after 44 | self.web_custom_html = web_custom_html 45 | self.web_healthcheck_path = web_healthcheck_path 46 | 47 | @classmethod 48 | def from_parse_args(cls, args): 49 | """Constructor from command line args. 50 | 51 | :param args: parse command line arguments 52 | :type args: argparse.ArgumentParser 53 | 54 | """ 55 | 56 | return cls(args.migration_file, 57 | args.database, 58 | db_user=args.db_user, 59 | db_password=args.db_password, 60 | db_port=args.db_port, 61 | db_host=args.db_host, 62 | mode=args.mode, 63 | allow_serie=args.allow_serie, 64 | force_version=args.force_version, 65 | override_translations=args.override_translations, 66 | web_host=args.web_host, 67 | web_port=args.web_port, 68 | web_resp_status=args.web_resp_status, 69 | web_resp_retry_after=args.web_resp_retry_after, 70 | web_custom_html=args.web_custom_html, 71 | web_healthcheck_path=args.web_healthcheck_path, 72 | ) 73 | 74 | 75 | class EnvDefault(argparse.Action): 76 | 77 | def __init__(self, envvar, required=True, default=None, **kwargs): 78 | if envvar: 79 | default_from_env = self.get_default(envvar) 80 | if default_from_env is not None: 81 | default = default_from_env 82 | if required and default is not None: 83 | required = False 84 | super(EnvDefault, self).__init__(default=default, required=required, 85 | **kwargs) 86 | 87 | def get_default(self, envvar): 88 | # Handle string (single env var) 89 | if isinstance(envvar, str): 90 | return os.getenv(envvar) 91 | # Handle iterable (multiple env vars) - check in order 92 | for var in envvar: 93 | value = os.getenv(var) 94 | if value is not None: 95 | return value 96 | return None 97 | 98 | def __call__(self, parser, namespace, values, option_string=None): 99 | setattr(namespace, self.dest, values) 100 | 101 | 102 | class BoolEnvDefault(EnvDefault): 103 | 104 | def get_default(self, envvar): 105 | val = super().get_default(envvar) or '' 106 | try: 107 | return strtobool(val.lower()) 108 | except ValueError: 109 | return False 110 | 111 | 112 | def get_args_parser(): 113 | """Return a parser for command line options.""" 114 | parser = argparse.ArgumentParser( 115 | description='Marabunta: Migrating ants for Odoo') 116 | parser.add_argument('--migration-file', '-f', 117 | action=EnvDefault, 118 | envvar='MARABUNTA_MIGRATION_FILE', 119 | required=True, 120 | help='The yaml file containing the migration steps') 121 | parser.add_argument('--database', '-d', 122 | action=EnvDefault, 123 | envvar=['MARABUNTA_DATABASE', 'PGDATABASE'], 124 | required=True, 125 | help="Odoo's database") 126 | parser.add_argument('--db-user', '-u', 127 | action=EnvDefault, 128 | envvar=['MARABUNTA_DB_USER', 'PGUSER'], 129 | required=True, 130 | help="Odoo's database user") 131 | parser.add_argument('--db-password', '-w', 132 | action=EnvDefault, 133 | envvar=['MARABUNTA_DB_PASSWORD', 'PGPASSWORD'], 134 | required=False, 135 | help="Odoo's database password") 136 | parser.add_argument('--db-port', '-p', 137 | action=EnvDefault, 138 | envvar=['MARABUNTA_DB_PORT', 'PGPORT'], 139 | type=int, 140 | default=5432, 141 | required=False, 142 | help="Odoo's database port") 143 | parser.add_argument('--db-host', '-H', 144 | action=EnvDefault, 145 | envvar=['MARABUNTA_DB_HOST', 'PGHOST'], 146 | required=False, 147 | help="Odoo's database host") 148 | parser.add_argument('--mode', 149 | action=EnvDefault, 150 | envvar='MARABUNTA_MODE', 151 | required=False, 152 | help="Specify the mode in which we run the migration," 153 | "such as 'sample' or 'full'. Additional operations " 154 | "of this mode will be executed after the main " 155 | "operations and the addons list of this mode " 156 | "will be merged with the main addons list.") 157 | parser.add_argument('--allow-serie', 158 | action=BoolEnvDefault, 159 | required=False, 160 | envvar='MARABUNTA_ALLOW_SERIE', 161 | help='Allow to run more than 1 version upgrade at a ' 162 | 'time.') 163 | parser.add_argument('--force-version', 164 | required=False, 165 | default=os.environ.get('MARABUNTA_FORCE_VERSION'), 166 | help='Force upgrade of a version, even if it has ' 167 | 'already been applied.') 168 | parser.add_argument("--override-translations", 169 | required=False, 170 | default=os.environ.get("MARABUNTA_OVERRIDE_TRANSLATIONS"), 171 | help="Force override of translations.") 172 | 173 | group = parser.add_argument_group( 174 | title='Web', 175 | description='Configuration related to the internal web server, ' 176 | 'used to publish a maintenance page during the migration.', 177 | ) 178 | group.add_argument('--web-host', 179 | required=False, 180 | default=os.environ.get('MARABUNTA_WEB_HOST', '0.0.0.0'), 181 | help='Host for the web server') 182 | group.add_argument('--web-port', 183 | type=int, 184 | required=False, 185 | default=os.environ.get('MARABUNTA_WEB_PORT', 8069), 186 | help='Port for the web server') 187 | group.add_argument('--web-resp-status', 188 | type=int, 189 | required=False, 190 | default=os.environ.get( 191 | 'MARABUNTA_WEB_RESP_STATUS', 503 192 | ), 193 | help='Response HTTP status code of the web server') 194 | group.add_argument('--web-resp-retry-after', 195 | type=int, 196 | required=False, 197 | default=os.environ.get( 198 | 'MARABUNTA_WEB_RESP_RETRY_AFTER', 300 199 | ), 200 | help=( 201 | '"Retry-After" header value (in seconds) of ' 202 | 'response delivered by the web server') 203 | ) 204 | group.add_argument('--web-custom-html', 205 | required=False, 206 | default=os.environ.get( 207 | 'MARABUNTA_WEB_CUSTOM_HTML' 208 | ), 209 | help='Path to a custom html file to publish') 210 | group.add_argument('--web-healthcheck-path', 211 | required=False, 212 | default=os.environ.get( 213 | 'MARABUNTA_WEB_HEALTHCHECK_PATH' 214 | ), 215 | help=( 216 | 'URL Path used for health checks HTTP requests. ' 217 | 'Such monitoring requests will return HTTP 200 ' 218 | 'status code instead of the default 503.' 219 | )) 220 | return parser 221 | -------------------------------------------------------------------------------- /HISTORY.rst: -------------------------------------------------------------------------------- 1 | .. :changelog: 2 | 3 | Release History 4 | --------------- 5 | 6 | Unreleased 7 | ++++++++++ 8 | 9 | **Features** 10 | 11 | **Bugfixes** 12 | 13 | **Improvements** 14 | 15 | **Build** 16 | 17 | * Remove dependency on future 18 | 19 | 0.13.0 (2025-01-30) 20 | +++++++++++++++++++ 21 | 22 | **Features** 23 | 24 | * mode: demo has been deprecated in favor of sample 25 | 26 | **Improvements** 27 | 28 | * I18N overwrite option 29 | 30 | Migration allows using a `override_translations` version's option in order to 31 | allow usage of Odoo parameter `--i18n-overwrite`. 32 | Command option is `MARABUNTA_OVERRIDE_TRANSLATIONS` 33 | 34 | **Build** 35 | 36 | * Depend on psycopg2 rather than psycopg2-binary 37 | * Deprecate 3.7 38 | 39 | 40 | 0.12.0 (2024-01-09) 41 | +++++++++++++++++++ 42 | 43 | **Improvements** 44 | 45 | * allow connecting to a local database server without password (using ident) 46 | 47 | 48 | 0.11.0 (2023-09-12) 49 | +++++++++++++++++++ 50 | 51 | **Bugfixes** 52 | 53 | * Fix the build and release workflow 54 | 55 | **Build** 56 | 57 | * Deprecate python 2.7, 3.5 and 3.6 58 | * Support python 3.9, 3.10 and 3.11 59 | 60 | 61 | 0.10.7 (2022-05-24) 62 | +++++++++++++++++++ 63 | 64 | **Bugfixes** 65 | 66 | * Fix parsing of command line arguments (and related environment variables): 67 | ``--db-port``, ``--web-port``, ``--web-resp-status`` and 68 | ``--web-resp-retry-after`` 69 | 70 | **Improvements** 71 | 72 | * Switch to Psycopg2 binary wheel 73 | 74 | **Build** 75 | 76 | * Test for python 3.6, 3.7 and 3.8 77 | 78 | 0.10.6 (2021-09-14) 79 | +++++++++++++++++++ 80 | 81 | **Improvements** 82 | 83 | * Web server returns status 503 instead of 200 84 | * New option 'web-healthcheck-path' 85 | 86 | 0.10.5 (2020-12-08) 87 | +++++++++++++++++++ 88 | 89 | **Bugfixes** 90 | 91 | * Fix backup operation if force_version is set 92 | 93 | **Improvements** 94 | 95 | * Prevent text from bouncing in maintenance page 96 | * raise an exception if there is duplicate keys in migration file 97 | 98 | 0.10.4 (2019-02-15) 99 | +++++++++++++++++++ 100 | 101 | **Bugfixes** 102 | 103 | * Fix BoolEnvDefault when envvar is not defined 104 | 105 | 0.10.3 (2019-02-13) 106 | +++++++++++++++++++ 107 | 108 | **Bugfixes** 109 | 110 | * ALLOW_SERIES shouldn't be true if a false value is given. 111 | 112 | 0.10.2 (2018-12-12) 113 | +++++++++++++++++++ 114 | 115 | **Bugfixes** 116 | 117 | * Crash when forcing upgrade of a version and no backup command is configured 118 | 119 | 0.10.1 (2018-11-09) 120 | +++++++++++++++++++ 121 | 122 | **Build** 123 | 124 | * The lib is now automaticaly published to Pypi by Travis when a tag is added 125 | 126 | 127 | 0.10.0 (2018-11-06) 128 | +++++++++++++++++++ 129 | 130 | **Backward incompatible change** 131 | 132 | * In the migration yaml file, the ``command`` and ``command_args`` options are 133 | now all merged into ``command`` 134 | 135 | **Features** 136 | 137 | * Backup command and backup's ignore_if are now run in a 'sh' shell so we can 138 | inject environment variables in the commands 139 | * Backup command can now use ``$database``, ``$db_host``, ``$db_port``, 140 | ``$db_user``, ``$db_password`` that will be substituted by the current 141 | configuration values 142 | 143 | **Bugfixes** 144 | 145 | * When starting 2 concurrent marabunta process and the first fail, it releases 146 | the lock and the second would start odoo without actually run the migration. 147 | Now, when the migration lock is released, the other process(es) will recheck 148 | all versions as well before running odoo. 149 | 150 | **Documentation** 151 | 152 | * Add some high-level documentation 153 | 154 | 155 | 0.9.0 (2018-09-04) 156 | ++++++++++++++++++ 157 | 158 | **Features** 159 | 160 | 161 | * 1st version it's always "setup" 162 | 163 | In all projects' usecases the 1st version is always to setup the initial state. 164 | Adopting `setup` as the 1st version makes also easier to squash intermediate version 165 | all in one as the project and its releases grow up. 166 | 167 | * Support 5 digits version 168 | 169 | Now you can use 5 digits versions as per odoo modules. 170 | For instance: `11.0.3.0.1`. This give us better numbering for patches 171 | and makes versionig withing Odoo world more consistent. 172 | Old 3 digits versions are still supported for backward compat. 173 | 174 | Full rationale for above changes available here 175 | 176 | https://github.com/camptocamp/marabunta/commit/9b96acaff8e7eecbf82ff592b7bb927b4cd82f02 177 | 178 | * Backup option 179 | 180 | Migration allows using a `backup` command in order to perform specific 181 | commands (unless explicitly opted-out) before the migration step. 182 | 183 | No backup machinery provided as you are suppose to run your own command 184 | to execute the backup. 185 | 186 | 187 | **Bugfixes** 188 | 189 | * Build Py3 wheel on release 190 | 191 | 192 | 0.8.0 (2017-11-16) 193 | ++++++++++++++++++ 194 | 195 | Python3! 196 | 197 | 0.7.3 (2017-11-01) 198 | ++++++++++++++++++ 199 | 200 | **Bugfixes** 201 | 202 | * Support special chars (such as +) in Postgres passwords. The passwords were 203 | incorrectly passed through unquote_plus, which transform the + char to a 204 | space. 205 | 206 | 0.7.2 (2017-09-15) 207 | ++++++++++++++++++ 208 | 209 | **Bugfixes** 210 | 211 | * Use --no-xmlrpc option when running odoo as the new web server use the same port, 212 | it's not needed anyway 213 | 214 | 0.7.1 (2017-09-11) 215 | ++++++++++++++++++ 216 | 217 | **Bugfixes** 218 | 219 | * Include maintenance html file in the distribution 220 | 221 | 222 | 0.7.0 (2017-09-08) 223 | ++++++++++++++++++ 224 | 225 | **Features** 226 | 227 | * Publish a maintenance web page during migration. The host and port are 228 | configurable with new options. By default the port match odoo's (8069). A 229 | default maintenance is provided, but it can be configured as well. 230 | * When a migration fails, the log alongside the traceback are logged in the 231 | ``marabunta_version`` table. 232 | 233 | **Bugfixes** 234 | 235 | * Commands with unicode chars make the migration fail 236 | 237 | **Build** 238 | 239 | * Removed python3 from tox, it doesn't run on py3 and we can't make them run 240 | now. Odoo is still python2, py3 compat will come when it'll switch. 241 | 242 | 243 | 0.6.3 (2016-12-12) 244 | ++++++++++++++++++ 245 | 246 | 247 | **Bugfixes** 248 | 249 | * The new connection opened in 0.6.2 might suffer from the same issue of 250 | timeout than before 0.6.0: the connection is long-lived but there is no 251 | keep-alive for this connection. Open a new connection for each update in 252 | marabunta_version, which might be spaced between long subprocess operations 253 | 254 | 255 | 0.6.2 (2016-12-12) 256 | ++++++++++++++++++ 257 | 258 | **Bugfixes** 259 | 260 | * Autocommit the operations done in the marabunta_version table. Previously, 261 | after an exception, the changes to marabunta_version were rollbacked, which 262 | is not the expected behavior (it makes the migration restart ceaseless). 263 | As a side effect, Marabunta now opens 2 connections. The connection opened 264 | for the adsivory lock cannot commit before the end because it would release 265 | the lock. 266 | 267 | 268 | 0.6.1 (2016-11-25) 269 | ++++++++++++++++++ 270 | 271 | Important bugfix! The changes in the ``marabunta_version`` were never 272 | committed, so migration would run again. 273 | 274 | **Bugfixes** 275 | 276 | * Commit the connection so changes are not rollbacked. 277 | 278 | 0.6.0 (2016-11-21) 279 | ++++++++++++++++++ 280 | 281 | **Improvements** 282 | 283 | * Rework of the database connections: 284 | 285 | * The advisory lock is opened in a cursor in a thread, this cursor 286 | periodically executes a dummy 'SELECT 1' to be sure that the connection 287 | stay alive (not killed with a timeout) when a long-running subprocess is 288 | run. 289 | * The operations in database are executed in short-lived cursors. This 290 | prevents an issue we had when the open cursor was locking 291 | 'ir_module_module', preventing odoo to install/update properly. 292 | 293 | * Try to disable colors in output if the term does not support colors 294 | 295 | 296 | 0.5.1 (2016-10-26) 297 | ++++++++++++++++++ 298 | 299 | * Fix: marabunta processes run concurrently all tried to run the migration, 300 | this is better handled with a PostgreSQL advisory lock now 301 | 302 | 303 | 0.5.0 (2016-10-12) 304 | ++++++++++++++++++ 305 | 306 | Odoo 10 Support 307 | 308 | **Features** 309 | 310 | - Switch the default command line for running odoo to ``odoo`` instead of 311 | ``odoo.py`` (renamed in Odoo 10). For usage with previous version, you must 312 | specify the ``install_command`` in the ``migration.yml`` file. 313 | 314 | 315 | 0.4.2 (2016-08-17) 316 | ++++++++++++++++++ 317 | 318 | **Bugfixes** 319 | 320 | - Prevent error (25, 'Inappropriate ioctl for device') when 321 | stdout is not a tty by disabling the interactive mode. 322 | 323 | 324 | 0.4.1 (2016-07-27) 325 | ++++++++++++++++++ 326 | 327 | **Bugfixes** 328 | 329 | - Do not print on stdout the result of operations twice 330 | 331 | 332 | 0.4.0 (2016-07-26) 333 | ++++++++++++++++++ 334 | 335 | **Improvements** 336 | 337 | - New dependency on ``pexpect``. Used to create a pseudo-tty to execute the 338 | operations. It enables line buffering and interactivity for pdb in the 339 | children processes. 340 | 341 | **Fixes** 342 | 343 | - Noop operations are really considered as such 344 | 345 | 346 | 0.3.3 (2016-07-12) 347 | ++++++++++++++++++ 348 | 349 | **Fixes** 350 | 351 | - Encode print's outputs to the stdout's encoding or to utf8 by default 352 | 353 | 0.3.2 (2016-07-08) 354 | ++++++++++++++++++ 355 | 356 | **Fixes** 357 | 358 | - Failure when there are no version to process 359 | 360 | 0.3.1 (2016-07-07) 361 | ++++++++++++++++++ 362 | 363 | **Fixes** 364 | 365 | - Fix decoding issues with output of subprocesses 366 | 367 | 0.3.0 (2016-07-06) 368 | ++++++++++++++++++ 369 | 370 | Introducing **modes**. 371 | 372 | **Backward incompatible changes** 373 | 374 | - ``--demo`` is replaced by a more general ``--mode`` argument, 375 | the equivalent being ``--mode=demo`` 376 | - ``MARABUNTA_DEMO`` is replaced by ``MARABUNTA_MODE`` 377 | - the configuration file has now operations and addons by "modes", allowing to 378 | load some different scripts or install different addons for different modes 379 | (the addons list are merged and the operations of the modes are executed 380 | after the main ones):: 381 | 382 | - version: 0.0.1 383 | operations: 384 | pre: # executed before 'addons' 385 | - echo 'pre-operation' 386 | post: # executed after 'addons' 387 | - anthem songs::install 388 | addons: 389 | upgrade: 390 | - base 391 | modes: 392 | prod: 393 | operations: 394 | pre: 395 | - echo 'pre-operation executed only when the mode is prod' 396 | post: 397 | - anthem songs::load_production_data 398 | demo: 399 | operations: 400 | post: 401 | - anthem songs::load_demo_data 402 | addons: 403 | upgrade: 404 | - demo_addon 405 | 406 | - ``--force`` renamed to ``--allow-serie`` 407 | - ``MARABUNTA_FORCE`` renamed to ``MARABUNTA_ALLOW_SERIE`` 408 | - ``--project-file`` renamed to ``--migration-file`` 409 | - ``MARABUNTA_PROJECT_FILE`` renamed to ``MARABUNTA_MIGRATION_FILE`` 410 | 411 | **Improvements** 412 | 413 | - When 'allow_serie' is used, the same Odoo addon will not be 414 | upgraded more than one time when it is in the 'upgrade' section of 415 | more than one version 416 | 417 | **Fixes** 418 | 419 | - Fix error when there is no db version in the database 420 | - Fix error ``AttributeError: 'bool' object has no attribute 'number'`` 421 | when there is an unfinished version 422 | - Fix error when the db version is above the unprocessed version 423 | 424 | 0.2.2 (2016-06-23) 425 | ++++++++++++++++++ 426 | 427 | **Improvements** 428 | 429 | - Adapted the README so that it is rendered as ReST on pypi. 430 | 431 | 0.2.1 (2016-06-23) 432 | ++++++++++++++++++ 433 | 434 | **Bugfixes** 435 | 436 | - Fixed the version information of the package and release date. 437 | 438 | 0.2.0 (2016-06-23) 439 | ++++++++++++++++++ 440 | 441 | **Features** 442 | 443 | - Added support for Python 3.4 and 3.5 in addition to 2.7. 444 | 445 | **Bugfixes** 446 | 447 | - Fixed a crash with empty install args 448 | 449 | **Improvements** 450 | 451 | - Use YAML ``safe_load`` for added security. 452 | 453 | **Documentation** 454 | 455 | - Bootstrapped the Sphinx documentation. 456 | 457 | **Build** 458 | 459 | - Switched to tox for the build. This allow to run the same tests in all 460 | environment locally like in travis. The travis configuration just calls tox 461 | now. 462 | - Added runtime dependencies to the package, kept separate from the build and test dependencies (installed separately by tox). 463 | 464 | 0.1.1 (2016-06-08) 465 | ++++++++++++++++++ 466 | 467 | - Fixed problems with packaging so that now marabunta can be installable from 468 | pypi. 469 | 470 | 0.1.0 (2016-06-08) 471 | ++++++++++++++++++ 472 | 473 | Initial release. This corresponds to the initial work of Guewen Baconnier. 474 | -------------------------------------------------------------------------------- /tests/test_migration_file.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016-2017 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | import pytest 6 | import os 7 | 8 | import mock 9 | 10 | from marabunta.config import Config 11 | from marabunta.database import Database, MigrationTable, VersionRecord 12 | from marabunta.parser import YamlParser 13 | from marabunta.runner import Runner 14 | from marabunta.exception import MigrationError 15 | 16 | 17 | @pytest.fixture 18 | def runner_gen(request): 19 | def runner(filename, allow_serie=True, mode=None, db_versions=None): 20 | migration_file = os.path.join(request.fspath.dirname, 21 | 'examples', filename) 22 | config = Config(migration_file, 23 | 'test', 24 | allow_serie=allow_serie, 25 | mode=mode) 26 | migration_parser = YamlParser.parse_from_file(config.migration_file) 27 | migration = migration_parser.parse() 28 | table = mock.MagicMock(spec=MigrationTable) 29 | table.versions.return_value = db_versions or [] 30 | database = mock.MagicMock(spec=Database) 31 | return Runner(config, migration, database, table) 32 | return runner 33 | 34 | 35 | def test_example_file_output(runner_gen, request, capfd): 36 | runner = runner_gen('migration.yml') 37 | runner.perform() 38 | expected = ( 39 | u'|> migration: processing version setup\n' 40 | u'|> version setup: start\n' 41 | u'|> version setup: execute base pre-operations\n' 42 | u'|> version setup: echo \'pre-operation\'\n' 43 | u'pre-operation\r\n' 44 | u'|> version setup: installation / upgrade of addons\n' 45 | u'|> version setup: execute base post-operations\n' 46 | u'|> version setup: echo \'post-operation\'\n' 47 | u'post-operation\r\n' 48 | u'|> version setup: done\n' 49 | u'|> migration: processing version 0.0.2\n' 50 | u'|> version 0.0.2: start\n' 51 | u'|> version 0.0.2: version 0.0.2 is a noop\n' 52 | u'|> version 0.0.2: done\n' 53 | u'|> migration: processing version 0.0.3\n' 54 | u'|> version 0.0.3: start\n' 55 | u'|> version 0.0.3: execute base pre-operations\n' 56 | u'|> version 0.0.3: echo \'foobar\'\n' 57 | u'foobar\r\n' 58 | u'|> version 0.0.3: echo \'foobarbaz\'\n' 59 | u'foobarbaz\r\n' 60 | u'|> version 0.0.3: installation / upgrade of addons\n' 61 | u'|> version 0.0.3: execute base post-operations\n' 62 | u'|> version 0.0.3: echo \'post-op with unicode é â\'\n' 63 | u'post-op with unicode é â\r\n' 64 | u'|> version 0.0.3: done\n' 65 | u'|> migration: processing version 0.0.4\n' 66 | u'|> version 0.0.4: start\n' 67 | u'|> version 0.0.4: version 0.0.4 is a noop\n' 68 | u'|> version 0.0.4: done\n', 69 | u'' 70 | ) 71 | assert expected == capfd.readouterr() 72 | 73 | 74 | def test_example_file_output_mode(runner_gen, request, capfd): 75 | runner = runner_gen('migration.yml', mode='full') 76 | runner.perform() 77 | expected = ( 78 | u'|> migration: processing version setup\n' 79 | u'|> version setup: start\n' 80 | u'|> version setup: execute base pre-operations\n' 81 | u'|> version setup: echo \'pre-operation\'\n' 82 | u'pre-operation\r\n' 83 | u'|> version setup: execute full pre-operations\n' 84 | u'|> version setup: echo \'pre-operation executed only' 85 | u' when the mode is full\'\n' 86 | u'pre-operation executed only when the mode is full\r\n' 87 | u'|> version setup: installation / upgrade of addons\n' 88 | u'|> version setup: execute base post-operations\n' 89 | u'|> version setup: echo \'post-operation\'\n' 90 | u'post-operation\r\n' 91 | u'|> version setup: execute full post-operations\n' 92 | u'|> version setup: done\n' 93 | u'|> migration: processing version 0.0.2\n' 94 | u'|> version 0.0.2: start\n' 95 | u'|> version 0.0.2: version 0.0.2 is a noop\n' 96 | u'|> version 0.0.2: done\n' 97 | u'|> migration: processing version 0.0.3\n' 98 | u'|> version 0.0.3: start\n' 99 | u'|> version 0.0.3: execute base pre-operations\n' 100 | u'|> version 0.0.3: echo \'foobar\'\n' 101 | u'foobar\r\n' 102 | u'|> version 0.0.3: echo \'foobarbaz\'\n' 103 | u'foobarbaz\r\n' 104 | u'|> version 0.0.3: execute full pre-operations\n' 105 | u'|> version 0.0.3: installation / upgrade of addons\n' 106 | u'|> version 0.0.3: execute base post-operations\n' 107 | u'|> version 0.0.3: echo \'post-op with unicode é â\'\n' 108 | u'post-op with unicode é â\r\n' 109 | u'|> version 0.0.3: execute full post-operations\n' 110 | u'|> version 0.0.3: done\n' 111 | u'|> migration: processing version 0.0.4\n' 112 | u'|> version 0.0.4: start\n' 113 | u'|> version 0.0.4: version 0.0.4 is a noop\n' 114 | u'|> version 0.0.4: done\n', 115 | u'' 116 | ) 117 | assert expected == capfd.readouterr() 118 | 119 | 120 | def test_example_no_setup_file_output(runner_gen, request, capfd): 121 | msg = 'First version should be named `setup`' 122 | with pytest.warns(FutureWarning, match=msg): 123 | runner = runner_gen('migration_no_backup.yml') 124 | runner.perform() 125 | expected = ( 126 | u'|> migration: processing version 0.0.1\n' 127 | u'|> version 0.0.1: start\n' 128 | u'|> version 0.0.1: execute base pre-operations\n' 129 | u'|> version 0.0.1: echo \'pre-operation\'\n' 130 | u'pre-operation\r\n' 131 | u'|> version 0.0.1: installation / upgrade of addons\n' 132 | u'|> version 0.0.1: execute base post-operations\n' 133 | u'|> version 0.0.1: echo \'post-operation\'\n' 134 | u'post-operation\r\n' 135 | u'|> version 0.0.1: done\n' 136 | u'|> migration: processing version 0.0.2\n' 137 | u'|> version 0.0.2: start\n' 138 | u'|> version 0.0.2: version 0.0.2 is a noop\n' 139 | u'|> version 0.0.2: done\n' 140 | u'|> migration: processing version 0.0.3\n' 141 | u'|> version 0.0.3: start\n' 142 | u'|> version 0.0.3: execute base pre-operations\n' 143 | u'|> version 0.0.3: echo \'foobar\'\n' 144 | u'foobar\r\n' 145 | u'|> version 0.0.3: echo \'foobarbaz\'\n' 146 | u'foobarbaz\r\n' 147 | u'|> version 0.0.3: installation / upgrade of addons\n' 148 | u'|> version 0.0.3: execute base post-operations\n' 149 | u'|> version 0.0.3: echo \'post-op with unicode é â\'\n' 150 | u'post-op with unicode é â\r\n' 151 | u'|> version 0.0.3: done\n' 152 | u'|> migration: processing version 0.0.4\n' 153 | u'|> version 0.0.4: start\n' 154 | u'|> version 0.0.4: version 0.0.4 is a noop\n' 155 | u'|> version 0.0.4: done\n', 156 | u'' 157 | ) 158 | assert expected == capfd.readouterr() 159 | 160 | 161 | def test_example_no_setup_file_output_mode(runner_gen, request, capfd): 162 | msg = 'First version should be named `setup`' 163 | with pytest.warns(FutureWarning, match=msg): 164 | runner = runner_gen('migration_no_backup.yml', mode='full') 165 | runner.perform() 166 | expected = ( 167 | u'|> migration: processing version 0.0.1\n' 168 | u'|> version 0.0.1: start\n' 169 | u'|> version 0.0.1: execute base pre-operations\n' 170 | u'|> version 0.0.1: echo \'pre-operation\'\n' 171 | u'pre-operation\r\n' 172 | u'|> version 0.0.1: execute full pre-operations\n' 173 | u'|> version 0.0.1: echo \'pre-operation executed only' 174 | u' when the mode is full\'\n' 175 | u'pre-operation executed only when the mode is full\r\n' 176 | u'|> version 0.0.1: installation / upgrade of addons\n' 177 | u'|> version 0.0.1: execute base post-operations\n' 178 | u'|> version 0.0.1: echo \'post-operation\'\n' 179 | u'post-operation\r\n' 180 | u'|> version 0.0.1: execute full post-operations\n' 181 | u'|> version 0.0.1: done\n' 182 | u'|> migration: processing version 0.0.2\n' 183 | u'|> version 0.0.2: start\n' 184 | u'|> version 0.0.2: version 0.0.2 is a noop\n' 185 | u'|> version 0.0.2: done\n' 186 | u'|> migration: processing version 0.0.3\n' 187 | u'|> version 0.0.3: start\n' 188 | u'|> version 0.0.3: execute base pre-operations\n' 189 | u'|> version 0.0.3: echo \'foobar\'\n' 190 | u'foobar\r\n' 191 | u'|> version 0.0.3: echo \'foobarbaz\'\n' 192 | u'foobarbaz\r\n' 193 | u'|> version 0.0.3: execute full pre-operations\n' 194 | u'|> version 0.0.3: installation / upgrade of addons\n' 195 | u'|> version 0.0.3: execute base post-operations\n' 196 | u'|> version 0.0.3: echo \'post-op with unicode é â\'\n' 197 | u'post-op with unicode é â\r\n' 198 | u'|> version 0.0.3: execute full post-operations\n' 199 | u'|> version 0.0.3: done\n' 200 | u'|> migration: processing version 0.0.4\n' 201 | u'|> version 0.0.4: start\n' 202 | u'|> version 0.0.4: version 0.0.4 is a noop\n' 203 | u'|> version 0.0.4: done\n', 204 | u'' 205 | ) 206 | assert expected == capfd.readouterr() 207 | 208 | 209 | def test_mixed_digits_output_mode(runner_gen, request, capfd): 210 | old_versions = [ 211 | # 'number date_start date_done log addons' 212 | VersionRecord('11.0.2', '2018-09-01', '2018-09-01', '', ''), 213 | VersionRecord('11.1.0', '2018-09-02', '2018-09-02', '', ''), 214 | VersionRecord('11.1.5', '2018-09-03', '2018-09-03', '', ''), 215 | VersionRecord('11.2.0', '2018-09-04', '2018-09-04', '', ''), 216 | VersionRecord('11.3.0', '2018-09-05', '2018-09-05', '', ''), 217 | ] 218 | runner = runner_gen( 219 | 'migration_mixed_digits.yml', mode='full', db_versions=old_versions) 220 | runner.perform() 221 | expected = ( 222 | u'|> migration: processing version setup', 223 | u'|> version setup: start', 224 | u'|> version setup: version setup is a noop', 225 | u'|> version setup: done', 226 | u'|> migration: processing version 11.0.2', 227 | u'|> version 11.0.2: version 11.0.2 is already installed', 228 | u'|> migration: processing version 11.1.0', 229 | u'|> version 11.1.0: version 11.1.0 is already installed', 230 | u'|> migration: processing version 11.1.5', 231 | u'|> version 11.1.5: version 11.1.5 is already installed', 232 | u'|> migration: processing version 11.2.0', 233 | u'|> version 11.2.0: version 11.2.0 is already installed', 234 | u'|> migration: processing version 11.3.0', 235 | u'|> version 11.3.0: version 11.3.0 is already installed', 236 | u'|> migration: processing version 11.0.0.3.1', 237 | u'|> version 11.0.0.3.1: start', 238 | u'|> version 11.0.0.3.1: version 11.0.0.3.1 is a noop', 239 | u'|> version 11.0.0.3.1: done', 240 | u'|> migration: processing version 11.0.0.3.2', 241 | u'|> version 11.0.0.3.2: start', 242 | u'|> version 11.0.0.3.2: version 11.0.0.3.2 is a noop', 243 | u'|> version 11.0.0.3.2: done', 244 | u'|> migration: processing version 11.0.1.0.0', 245 | u'|> version 11.0.1.0.0: start', 246 | u'|> version 11.0.1.0.0: version 11.0.1.0.0 is a noop', 247 | u'|> version 11.0.1.0.0: done', 248 | u'|> migration: processing version 11.0.2.0.0', 249 | u'|> version 11.0.2.0.0: start', 250 | u'|> version 11.0.2.0.0: version 11.0.2.0.0 is a noop', 251 | u'|> version 11.0.2.0.0: done', 252 | ) 253 | output = capfd.readouterr() # ease debug 254 | assert expected == tuple(output.out.splitlines()) 255 | 256 | 257 | def test_mixed_digits_output_mode2(runner_gen, request, capfd): 258 | # migrate 1st one 3 digit version then a 5 digit one 259 | old_versions = [ 260 | # 'number date_start date_done log addons' 261 | VersionRecord('10.17.0', '2018-09-06', '2018-09-06', '', ''), 262 | ] 263 | runner = runner_gen( 264 | 'migration_mixed_digits2.yml', mode='full', db_versions=old_versions) 265 | runner.perform() 266 | expected = ( 267 | u'|> migration: processing version setup', 268 | u'|> version setup: start', 269 | u'|> version setup: version setup is a noop', 270 | u'|> version setup: done', 271 | u'|> migration: processing version 10.17.0', 272 | u'|> version 10.17.0: version 10.17.0 is already installed', 273 | u'|> migration: processing version 10.17.1', 274 | u'|> version 10.17.1: start', 275 | u'|> version 10.17.1: version 10.17.1 is a noop', 276 | u'|> version 10.17.1: done', 277 | u'|> migration: processing version 10.0.0.18.0', 278 | u'|> version 10.0.0.18.0: start', 279 | u'|> version 10.0.0.18.0: version 10.0.0.18.0 is a noop', 280 | u'|> version 10.0.0.18.0: done', 281 | u'|> migration: processing version 10.0.0.19.0', 282 | u'|> version 10.0.0.19.0: start', 283 | u'|> version 10.0.0.19.0: version 10.0.0.19.0 is a noop', 284 | u'|> version 10.0.0.19.0: done', 285 | ) 286 | output = capfd.readouterr() # ease debug 287 | assert expected == tuple(output.out.splitlines()) 288 | 289 | 290 | # All other tests already rely on allow series working when set to true. 291 | # so we only have one test making sure it doesn't work if it is set false. 292 | def test_allow_series_false(runner_gen, request, capfd): 293 | runner = runner_gen('migration.yml', allow_serie=False) 294 | with pytest.raises( 295 | MigrationError, 296 | match=r"[.]*Only one version can be upgraded at a time.[.]*" 297 | ): 298 | runner.perform() 299 | -------------------------------------------------------------------------------- /marabunta/model.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2016-2018 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) 4 | 5 | import sys 6 | 7 | from builtins import object 8 | from io import StringIO 9 | from string import Template 10 | 11 | import pexpect 12 | 13 | from .exception import ConfigurationError, OperationError, BackupError 14 | from .helpers import string_types 15 | from .version import MarabuntaVersion 16 | 17 | 18 | class Migration(object): 19 | 20 | def __init__(self, versions, options): 21 | self._versions = versions 22 | self.options = options 23 | 24 | @property 25 | def versions(self): 26 | return sorted(self._versions, key=lambda v: MarabuntaVersion(v.number)) 27 | 28 | 29 | class MigrationOption(object): 30 | 31 | def __init__(self, install_command=None, install_args=None, backup=None): 32 | """Options block in a migration. 33 | 34 | :param install_command: Command ran for addons install 35 | :type install_command: String 36 | :param install_args: Arguments for an install command 37 | :type install_args: String 38 | :param backup: Backup options 39 | :type backup: Dict 40 | """ 41 | self.install_command = install_command or u'odoo' 42 | self.install_args = install_args or u'' 43 | self.backup = backup 44 | 45 | 46 | class MigrationBackupOption(object): 47 | 48 | def __init__(self, command, ignore_if, stop_on_failure=True): 49 | """Backup option in migration. 50 | 51 | Migration allows using a backup command in order to perform specific 52 | commands (unless explicitly opted-out) before the migration step. 53 | 54 | The command can contain placeholders that will be replaced by the 55 | current configuration values: 56 | 57 | * ``$database`` 58 | * ``$db_user`` 59 | * ``$db_password`` 60 | * ``$db_host`` 61 | * ``$db_port`` 62 | 63 | :param command: Backup command to execute 64 | :type command: String 65 | :param ignore_if: A command, that is evaluated 66 | without error -> backup is ignored 67 | :type ignore_if: String 68 | :param stop_on_failure: To either stop migration 69 | if backup commands fails or to ignore it 70 | :type stop_on_failure: Boolean 71 | """ 72 | self._command = command 73 | self._ignore_if = ignore_if 74 | self._stop_on_failure = stop_on_failure 75 | self._ignore_if = ignore_if 76 | 77 | def command_operation(self, config): 78 | template = Template(self._command) 79 | command = template.safe_substitute( 80 | database=config.database, 81 | db_user=config.db_user, 82 | db_password=config.db_password, 83 | db_port=config.db_port, 84 | db_host=config.db_host, 85 | ) 86 | return BackupOperation( 87 | command, 88 | shell=True, 89 | stop_on_failure=self._stop_on_failure, 90 | ) 91 | 92 | def ignore_if_operation(self): 93 | if self._ignore_if is None or self._ignore_if is False: 94 | # if ignore_if parameter was not specified - always backup 95 | return SilentOperation('false', shell=True) 96 | elif self._ignore_if is True: 97 | # if it is specifically True 98 | return SilentOperation('true', shell=True) 99 | return SilentOperation(self._ignore_if, shell=True) 100 | 101 | 102 | class Version(object): 103 | 104 | def __init__(self, number, options): 105 | """Base class for a migration version. 106 | 107 | :param number: Valid version number 108 | :type number: String 109 | :param options: Version options 110 | :type options: Instance of a MigrationOption class 111 | """ 112 | try: 113 | MarabuntaVersion().parse(number) 114 | except ValueError: 115 | raise ConfigurationError( 116 | u'{} is not a valid version'.format(number) 117 | ) 118 | self.number = number 119 | self._version_modes = {} 120 | self.options = options 121 | self.backup = False 122 | self.override_translations = False 123 | 124 | def is_processed(self, db_versions): 125 | """Check if version is already applied in the database. 126 | 127 | :param db_versions: 128 | """ 129 | return self.number in (v.number for v in db_versions if v.date_done) 130 | 131 | def is_noop(self): 132 | """Check if version is a no operation version. 133 | """ 134 | has_operations = [mode.pre_operations or mode.post_operations 135 | for mode in self._version_modes.values()] 136 | has_upgrade_addons = [mode.upgrade_addons or mode.remove_addons 137 | for mode in self._version_modes.values()] 138 | noop = not any((has_upgrade_addons, has_operations)) 139 | return noop 140 | 141 | def skip(self, db_versions): 142 | """Version is either noop, or it has been processed already. 143 | """ 144 | return self.is_noop() or self.is_processed(db_versions) 145 | 146 | def _get_version_mode(self, mode=None): 147 | """Return a VersionMode for a mode name. 148 | 149 | When the mode is None, we are working with the 'base' mode. 150 | """ 151 | version_mode = self._version_modes.get(mode) 152 | if not version_mode: 153 | version_mode = self._version_modes[mode] = VersionMode(name=mode) 154 | return version_mode 155 | 156 | def add_operation(self, operation_type, operation, mode=None): 157 | """Add an operation to the version 158 | 159 | :param mode: Name of the mode in which the operation is executed 160 | :type mode: str 161 | :param operation_type: one of 'pre', 'post' 162 | :type operation_type: str 163 | :param operation: the operation to add 164 | :type operation: :class:`marabunta.model.Operation` 165 | """ 166 | version_mode = self._get_version_mode(mode=mode) 167 | if operation_type == 'pre': 168 | version_mode.add_pre(operation) 169 | elif operation_type == 'post': 170 | version_mode.add_post(operation) 171 | else: 172 | raise ConfigurationError( 173 | u"Type of operation must be 'pre' or 'post', got %s" % 174 | (operation_type,) 175 | ) 176 | 177 | def add_upgrade_addons(self, addons, mode=None): 178 | version_mode = self._get_version_mode(mode=mode) 179 | version_mode.add_upgrade_addons(addons) 180 | 181 | def add_remove_addons(self, addons, mode=None): 182 | version_mode = self._get_version_mode(mode=mode) 183 | version_mode.add_remove_addons(addons) 184 | raise ConfigurationError( 185 | u'Removing addons is not yet supported because it cannot be done ' 186 | u'using the command line. You have to uninstall addons using ' 187 | u'an Odoo (\'import openerp\') script' 188 | ) 189 | 190 | def pre_operations(self, mode=None): 191 | """ Return pre-operations only for the mode asked """ 192 | version_mode = self._get_version_mode(mode=mode) 193 | return version_mode.pre_operations 194 | 195 | def post_operations(self, mode=None): 196 | """ Return post-operations only for the mode asked """ 197 | version_mode = self._get_version_mode(mode=mode) 198 | return version_mode.post_operations 199 | 200 | def upgrade_addons_operation(self, addons_state, mode=None): 201 | """ Return merged set of main addons and mode's addons """ 202 | installed = set(a.name for a in addons_state 203 | if a.state in ('installed', 'to upgrade')) 204 | 205 | base_mode = self._get_version_mode() 206 | addons_list = base_mode.upgrade_addons.copy() 207 | if mode: 208 | add_mode = self._get_version_mode(mode=mode) 209 | addons_list |= add_mode.upgrade_addons 210 | 211 | to_install = addons_list - installed 212 | to_upgrade = installed & addons_list 213 | 214 | return UpgradeAddonsOperation(self.options, to_install, to_upgrade, self.override_translations) 215 | 216 | def remove_addons_operation(self): 217 | raise NotImplementedError 218 | 219 | def __repr__(self): 220 | return u'Version<{}>'.format(self.number) 221 | 222 | 223 | class VersionMode(object): 224 | 225 | def __init__(self, name=None): 226 | self.name = name 227 | self.pre_operations = [] 228 | self.post_operations = [] 229 | self.upgrade_addons = set() 230 | self.remove_addons = set() 231 | 232 | def add_pre(self, operation): 233 | self.pre_operations.append(operation) 234 | 235 | def add_post(self, operation): 236 | self.post_operations.append(operation) 237 | 238 | def __repr__(self): 239 | name = self.name if self.name else 'base' 240 | return u'VersionMode<{}>'.format(name) 241 | 242 | def add_upgrade_addons(self, addons): 243 | self.upgrade_addons.update(addons) 244 | 245 | def add_remove_addons(self, addons): 246 | self.remove_addons.update(addons) 247 | raise ConfigurationError( 248 | u'Removing addons is not yet supported because it cannot be done ' 249 | u'using the command line. You have to uninstall addons using ' 250 | u'an Odoo (\'import openerp\') script' 251 | ) 252 | 253 | 254 | class UpgradeAddonsOperation(object): 255 | 256 | def __init__(self, options, to_install, to_upgrade, override_translations=False): 257 | self.options = options 258 | self.to_install = set(to_install) 259 | self.to_upgrade = set(to_upgrade) 260 | self.override_translations = override_translations 261 | 262 | def operation(self, exclude_addons=None): 263 | if exclude_addons is None: 264 | exclude_addons = set() 265 | install_command = self.options.install_command 266 | install_args = self.options.install_args[:] or [] 267 | install_args += [u'--workers=0', u'--stop-after-init', u'--no-http'] 268 | 269 | to_install = self.to_install - exclude_addons 270 | if to_install: 271 | install_args += [u'-i', u','.join(to_install)] 272 | 273 | to_upgrade = self.to_upgrade - exclude_addons 274 | if to_upgrade: 275 | install_args += [u'-u', u','.join(to_upgrade)] 276 | 277 | if to_install or to_upgrade: 278 | # if we don't have addons to install or upgrade, an issue will 279 | # be raised by Odoo if we add the `--i18n-overwrite` flag 280 | if self.override_translations: 281 | install_args += [u'--i18n-overwrite'] 282 | return Operation([install_command] + install_args) 283 | else: 284 | return Operation('') 285 | 286 | 287 | class Operation(object): 288 | 289 | def __init__(self, command, shell=False): 290 | """ Wrap a pexpect spawn command 291 | 292 | :param command: the command to run as string 293 | :param shell: boolean, when True, wraps the command in ``sh -c`` 294 | so bash environment variables are interpolated 295 | """ 296 | if not isinstance(command, string_types): 297 | command = u' '.join(command) 298 | self.command = command 299 | self.shell = shell 300 | 301 | def _spawn_command(self): 302 | if self.shell: 303 | return "sh", ["-c", self.command] 304 | else: 305 | return self.command, [] 306 | 307 | def __bool__(self): 308 | return bool(self.command) 309 | 310 | def _execute(self, log, interactive=True): 311 | assert self.command 312 | cmd, options = self._spawn_command() 313 | child = pexpect.spawn(cmd, options, timeout=None, encoding='utf8') 314 | # interact() will transfer the child's stdout to 315 | # stdout, but we also copy the output in a buffer 316 | # so we can save the logs in the database 317 | log_buffer = StringIO() 318 | if interactive: 319 | # use the interactive mode so we can use pdb in the 320 | # migration scripts 321 | child.interact() 322 | else: 323 | # set the logfile to stdout so we have an unbuffered 324 | # output 325 | child.logfile = sys.stdout 326 | child.expect(pexpect.EOF) 327 | # child.before contains all the the output of the child program 328 | # before the EOF 329 | # child.before is unicode 330 | log_buffer.write(child.before) 331 | child.close() 332 | if child.signalstatus is not None: 333 | raise OperationError( 334 | u"command '{}' has been interrupted by signal {}".format( 335 | self.command, 336 | child.signalstatus 337 | ) 338 | ) 339 | elif child.exitstatus != 0: 340 | raise OperationError( 341 | u"command '{}' returned {}".format( 342 | self.command, 343 | child.exitstatus 344 | ) 345 | ) 346 | log_buffer.seek(0) 347 | # the pseudo-tty used for the child process returns 348 | # lines with \r\n endings 349 | msg = '\n'.join(log_buffer.read().splitlines()) 350 | log(msg, decorated=False, stdout=False) 351 | 352 | def execute(self, log): 353 | log(u'{}'.format(self.command)) 354 | self._execute(log, interactive=sys.stdout.isatty()) 355 | 356 | def __repr__(self): 357 | return u'Operation<{}>'.format(self.command) 358 | 359 | 360 | class SilentOperation(Operation): 361 | """Operation that does not require logging or interactivity. """ 362 | 363 | def _execute(self): 364 | assert self.command 365 | cmd, options = self._spawn_command() 366 | child = pexpect.spawn(cmd, options, timeout=None, encoding='utf8') 367 | child.expect(pexpect.EOF) 368 | child.close() 369 | if child.signalstatus is not None: 370 | raise OperationError( 371 | u"command '{}' has been interrupted by signal {}".format( 372 | ' '.join(self.command), 373 | child.signalstatus 374 | ) 375 | ) 376 | elif child.exitstatus != 0: 377 | raise OperationError( 378 | u"command '{}' returned {}".format( 379 | ' '.join(self.command), 380 | child.exitstatus 381 | ) 382 | ) 383 | 384 | def execute(self): 385 | self._execute() 386 | 387 | 388 | class BackupOperation(Operation): 389 | 390 | def __init__(self, command, shell=False, stop_on_failure=True): 391 | super(BackupOperation, self).__init__(command, shell=shell) 392 | self.stop_on_failure = stop_on_failure 393 | 394 | def execute(self, log): 395 | log('Backing up...') 396 | try: 397 | self._execute(log, interactive=sys.stdout.isatty()) 398 | except OperationError: 399 | if self.stop_on_failure: 400 | raise BackupError( 401 | u"Backup command failed, stopping migration." 402 | ) 403 | else: 404 | log(u"Backup command failed, ignored by configuration. " 405 | u"Resuming migration") 406 | -------------------------------------------------------------------------------- /tests/test_backup.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # Copyright 2018 Camptocamp SA 3 | # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl) 4 | 5 | import os 6 | import pytest 7 | 8 | import mock 9 | 10 | from marabunta.config import Config 11 | from marabunta.database import Database, MigrationTable 12 | from marabunta.model import MigrationBackupOption 13 | from marabunta.parser import YamlParser 14 | from marabunta.runner import Runner 15 | from marabunta.exception import BackupError 16 | 17 | 18 | # Split runner generation, so we can effortlessly 19 | # change the parameters of backup in tests 20 | @pytest.fixture 21 | def runner_gen(request): 22 | def runner(parser, config): 23 | migration = parser.parse() 24 | table = mock.MagicMock(spec=MigrationTable) 25 | table.versions.return_value = [] 26 | database = mock.MagicMock(spec=Database) 27 | return Runner(config, migration, database, table) 28 | return runner 29 | 30 | 31 | @pytest.fixture 32 | def parse_yaml(request): 33 | def parser(filename, allow_serie=True, mode=None): 34 | migration_file = os.path.join(request.fspath.dirname, 35 | 'examples', filename) 36 | config = Config(migration_file, 37 | 'test', 38 | allow_serie=allow_serie, 39 | mode=mode) 40 | migration_parser = YamlParser.parse_from_file(config.migration_file) 41 | return migration_parser, config 42 | return parser 43 | 44 | 45 | def test_backup(runner_gen, parse_yaml, request, capfd): 46 | # Simple test that backing up works 47 | backup_params, config = parse_yaml('migration_with_backup.yml') 48 | runner = runner_gen(backup_params, config) 49 | runner.perform() 50 | expected = ( 51 | u'|> migration: Backing up...\n' 52 | u'backup command\r\n' 53 | u'|> migration: processing version setup\n' 54 | u'|> version setup: start\n' 55 | u'|> version setup: execute base pre-operations\n' 56 | u'|> version setup: echo \'pre-operation\'\n' 57 | u'pre-operation\r\n' 58 | u'|> version setup: installation / upgrade of addons\n' 59 | u'|> version setup: execute base post-operations\n' 60 | u'|> version setup: echo \'post-operation\'\n' 61 | u'post-operation\r\n' 62 | u'|> version setup: done\n' 63 | u'|> migration: processing version 0.0.2\n' 64 | u'|> version 0.0.2: start\n' 65 | u'|> version 0.0.2: version 0.0.2 is a noop\n' 66 | u'|> version 0.0.2: done\n' 67 | u'|> migration: processing version 0.0.3\n' 68 | u'|> version 0.0.3: start\n' 69 | u'|> version 0.0.3: execute base pre-operations\n' 70 | u'|> version 0.0.3: echo \'foobar\'\n' 71 | u'foobar\r\n' 72 | u'|> version 0.0.3: echo \'foobarbaz\'\n' 73 | u'foobarbaz\r\n' 74 | u'|> version 0.0.3: installation / upgrade of addons\n' 75 | u'|> version 0.0.3: execute base post-operations\n' 76 | u'|> version 0.0.3: echo \'post-op with unicode é â\'\n' 77 | u'post-op with unicode é â\r\n' 78 | u'|> version 0.0.3: done\n' 79 | u'|> migration: processing version 0.0.4\n' 80 | u'|> version 0.0.4: start\n' 81 | u'|> version 0.0.4: version 0.0.4 is a noop\n' 82 | u'|> version 0.0.4: done\n' 83 | ) 84 | out = capfd.readouterr().out 85 | assert expected == out 86 | 87 | 88 | def test_backup_ignore_1(runner_gen, parse_yaml, request, capfd): 89 | # Test that backing up is ignored if ignore_if evaluates to True 90 | backup_params, config = parse_yaml('migration_with_backup.yml') 91 | backup_params.parsed['migration']['options']['backup'].update({ 92 | 'ignore_if': 'test 1 = 1', 93 | }) 94 | runner = runner_gen(backup_params, config) 95 | runner.perform() 96 | expected = ( 97 | u'|> migration: processing version setup\n' 98 | u'|> version setup: start\n' 99 | u'|> version setup: execute base pre-operations\n' 100 | u'|> version setup: echo \'pre-operation\'\n' 101 | u'pre-operation\r\n' 102 | u'|> version setup: installation / upgrade of addons\n' 103 | u'|> version setup: execute base post-operations\n' 104 | u'|> version setup: echo \'post-operation\'\n' 105 | u'post-operation\r\n' 106 | u'|> version setup: done\n' 107 | u'|> migration: processing version 0.0.2\n' 108 | u'|> version 0.0.2: start\n' 109 | u'|> version 0.0.2: version 0.0.2 is a noop\n' 110 | u'|> version 0.0.2: done\n' 111 | u'|> migration: processing version 0.0.3\n' 112 | u'|> version 0.0.3: start\n' 113 | u'|> version 0.0.3: execute base pre-operations\n' 114 | u'|> version 0.0.3: echo \'foobar\'\n' 115 | u'foobar\r\n' 116 | u'|> version 0.0.3: echo \'foobarbaz\'\n' 117 | u'foobarbaz\r\n' 118 | u'|> version 0.0.3: installation / upgrade of addons\n' 119 | u'|> version 0.0.3: execute base post-operations\n' 120 | u'|> version 0.0.3: echo \'post-op with unicode é â\'\n' 121 | u'post-op with unicode é â\r\n' 122 | u'|> version 0.0.3: done\n' 123 | u'|> migration: processing version 0.0.4\n' 124 | u'|> version 0.0.4: start\n' 125 | u'|> version 0.0.4: version 0.0.4 is a noop\n' 126 | u'|> version 0.0.4: done\n' 127 | ) 128 | out = capfd.readouterr().out 129 | assert expected == out 130 | 131 | 132 | def test_backup_ignore_2(runner_gen, parse_yaml, request, capfd): 133 | # Test that backing up is NOT ignored if no ignore_if set 134 | backup_params, config = parse_yaml('migration_with_backup.yml') 135 | backup_params.parsed['migration']['options']['backup'].pop('ignore_if') 136 | runner = runner_gen(backup_params, config) 137 | runner.perform() 138 | expected = ( 139 | u'|> migration: Backing up...\n' 140 | u'backup command\r\n' 141 | u'|> migration: processing version setup\n' 142 | u'|> version setup: start\n' 143 | u'|> version setup: execute base pre-operations\n' 144 | u'|> version setup: echo \'pre-operation\'\n' 145 | u'pre-operation\r\n' 146 | u'|> version setup: installation / upgrade of addons\n' 147 | u'|> version setup: execute base post-operations\n' 148 | u'|> version setup: echo \'post-operation\'\n' 149 | u'post-operation\r\n' 150 | u'|> version setup: done\n' 151 | u'|> migration: processing version 0.0.2\n' 152 | u'|> version 0.0.2: start\n' 153 | u'|> version 0.0.2: version 0.0.2 is a noop\n' 154 | u'|> version 0.0.2: done\n' 155 | u'|> migration: processing version 0.0.3\n' 156 | u'|> version 0.0.3: start\n' 157 | u'|> version 0.0.3: execute base pre-operations\n' 158 | u'|> version 0.0.3: echo \'foobar\'\n' 159 | u'foobar\r\n' 160 | u'|> version 0.0.3: echo \'foobarbaz\'\n' 161 | u'foobarbaz\r\n' 162 | u'|> version 0.0.3: installation / upgrade of addons\n' 163 | u'|> version 0.0.3: execute base post-operations\n' 164 | u'|> version 0.0.3: echo \'post-op with unicode é â\'\n' 165 | u'post-op with unicode é â\r\n' 166 | u'|> version 0.0.3: done\n' 167 | u'|> migration: processing version 0.0.4\n' 168 | u'|> version 0.0.4: start\n' 169 | u'|> version 0.0.4: version 0.0.4 is a noop\n' 170 | u'|> version 0.0.4: done\n' 171 | ) 172 | out = capfd.readouterr().out 173 | assert expected == out 174 | 175 | 176 | def test_backup_ignore_3(runner_gen, parse_yaml, request, capfd): 177 | # Test that backing up is ignored if ignore_if evaluates to True 178 | # and MARABUNTA_FORCE_VERSION is set 179 | backup_params, config = parse_yaml('migration_with_backup.yml') 180 | backup_params.parsed['migration']['options']['backup'].update({ 181 | 'ignore_if': 'test -z "$UNKNOWN_VAR"', 182 | }) 183 | config.force_version = "0.0.4" 184 | runner = runner_gen(backup_params, config) 185 | runner.perform() 186 | expected = ( 187 | u'|> migration: force-execute version 0.0.4\n' 188 | u'|> migration: processing version 0.0.4\n' 189 | u'|> version 0.0.4: start\n' 190 | u'|> version 0.0.4: version 0.0.4 is a noop\n' 191 | u'|> version 0.0.4: done\n' 192 | ) 193 | out = capfd.readouterr().out 194 | assert expected == out 195 | 196 | 197 | def test_backup_stop_on_failure_true(runner_gen, parse_yaml, request, capfd): 198 | # Test that the migration is failed if stop_on_failure is true and 199 | # backup command fails 200 | with pytest.raises(BackupError): 201 | backup_params, config = parse_yaml('migration_with_backup.yml') 202 | backup_params.parsed['migration']['options']['backup'].update({ 203 | 'command': 'test 1 != 1', 204 | }) 205 | runner = runner_gen(backup_params, config) 206 | runner.perform() 207 | 208 | 209 | def test_backup_no_stop_on_failure(runner_gen, parse_yaml, request, capfd): 210 | # Test that the migration is failed if stop_on_failure is not specified 211 | # and backup command fails 212 | with pytest.raises(BackupError): 213 | backup_params, config = parse_yaml('migration_with_backup.yml') 214 | backup_params.parsed['migration']['options']['backup'].update({ 215 | 'command': 'test 1 != 1', 216 | }) 217 | backup_params.parsed['migration']['options']['backup'].pop( 218 | "stop_on_failure", 219 | ) 220 | runner = runner_gen(backup_params, config) 221 | runner.perform() 222 | 223 | 224 | def test_backup_stop_on_failure_false(runner_gen, parse_yaml, request, capfd): 225 | # Test that the migration continues if stop_on_failure is false and 226 | # backup command fails 227 | backup_params, config = parse_yaml('migration_with_backup.yml') 228 | backup_params.parsed['migration']['options']['backup'].update({ 229 | 'command': 'test 1 != 1', 230 | 'stop_on_failure': False, 231 | }) 232 | runner = runner_gen(backup_params, config) 233 | runner.perform() 234 | 235 | expected = ( 236 | u'|> migration: Backing up...\n' 237 | u'|> migration: Backup command failed, ignored by configuration.' 238 | u' Resuming migration\n' 239 | u'|> migration: processing version setup\n' 240 | u'|> version setup: start\n' 241 | u'|> version setup: execute base pre-operations\n' 242 | u'|> version setup: echo \'pre-operation\'\n' 243 | u'pre-operation\r\n' 244 | u'|> version setup: installation / upgrade of addons\n' 245 | u'|> version setup: execute base post-operations\n' 246 | u'|> version setup: echo \'post-operation\'\n' 247 | u'post-operation\r\n' 248 | u'|> version setup: done\n' 249 | u'|> migration: processing version 0.0.2\n' 250 | u'|> version 0.0.2: start\n' 251 | u'|> version 0.0.2: version 0.0.2 is a noop\n' 252 | u'|> version 0.0.2: done\n' 253 | u'|> migration: processing version 0.0.3\n' 254 | u'|> version 0.0.3: start\n' 255 | u'|> version 0.0.3: execute base pre-operations\n' 256 | u'|> version 0.0.3: echo \'foobar\'\n' 257 | u'foobar\r\n' 258 | u'|> version 0.0.3: echo \'foobarbaz\'\n' 259 | u'foobarbaz\r\n' 260 | u'|> version 0.0.3: installation / upgrade of addons\n' 261 | u'|> version 0.0.3: execute base post-operations\n' 262 | u'|> version 0.0.3: echo \'post-op with unicode é â\'\n' 263 | u'post-op with unicode é â\r\n' 264 | u'|> version 0.0.3: done\n' 265 | u'|> migration: processing version 0.0.4\n' 266 | u'|> version 0.0.4: start\n' 267 | u'|> version 0.0.4: version 0.0.4 is a noop\n' 268 | u'|> version 0.0.4: done\n' 269 | ) 270 | out = capfd.readouterr().out 271 | assert expected == out 272 | 273 | 274 | def test_backup_noop(runner_gen, parse_yaml, request, capfd): 275 | # Test that backup is triggered when noop version has explicit backup=true 276 | backup_params, config = parse_yaml('migration_with_backup.yml') 277 | # set all migration steps to backup false except the last one 278 | for version in backup_params.parsed['migration']['versions']: 279 | if version['version'] not in ['0.0.4', '0.0.2']: 280 | version['backup'] = False 281 | runner = runner_gen(backup_params, config) 282 | runner.perform() 283 | 284 | expected = ( 285 | u'|> migration: Backing up...\n' 286 | u'backup command\r\n' 287 | u'|> migration: processing version setup\n' 288 | u'|> version setup: start\n' 289 | u'|> version setup: execute base pre-operations\n' 290 | u'|> version setup: echo \'pre-operation\'\n' 291 | u'pre-operation\r\n' 292 | u'|> version setup: installation / upgrade of addons\n' 293 | u'|> version setup: execute base post-operations\n' 294 | u'|> version setup: echo \'post-operation\'\n' 295 | u'post-operation\r\n' 296 | u'|> version setup: done\n' 297 | u'|> migration: processing version 0.0.2\n' 298 | u'|> version 0.0.2: start\n' 299 | u'|> version 0.0.2: version 0.0.2 is a noop\n' 300 | u'|> version 0.0.2: done\n' 301 | u'|> migration: processing version 0.0.3\n' 302 | u'|> version 0.0.3: start\n' 303 | u'|> version 0.0.3: execute base pre-operations\n' 304 | u'|> version 0.0.3: echo \'foobar\'\n' 305 | u'foobar\r\n' 306 | u'|> version 0.0.3: echo \'foobarbaz\'\n' 307 | u'foobarbaz\r\n' 308 | u'|> version 0.0.3: installation / upgrade of addons\n' 309 | u'|> version 0.0.3: execute base post-operations\n' 310 | u'|> version 0.0.3: echo \'post-op with unicode é â\'\n' 311 | u'post-op with unicode é â\r\n' 312 | u'|> version 0.0.3: done\n' 313 | u'|> migration: processing version 0.0.4\n' 314 | u'|> version 0.0.4: start\n' 315 | u'|> version 0.0.4: version 0.0.4 is a noop\n' 316 | u'|> version 0.0.4: done\n' 317 | ) 318 | out = capfd.readouterr().out 319 | assert expected == out 320 | 321 | 322 | @pytest.fixture 323 | def placeholders_config(): 324 | database = 'a_db' 325 | db_user = 'a_user' 326 | db_password = 'a_password' 327 | db_port = 'a_port' 328 | db_host = 'a_host' 329 | return Config( 330 | 'migration.yml', 331 | database, 332 | db_user=db_user, 333 | db_password=db_password, 334 | db_port=db_port, 335 | db_host=db_host, 336 | ) 337 | 338 | 339 | def test_backup_command_placeholders(placeholders_config): 340 | # all parameters are substituted 341 | options = MigrationBackupOption( 342 | 'echo $database $db_user $db_password $db_host $db_port', 343 | 'test 1 != 1', 344 | ) 345 | operation = options.command_operation(placeholders_config) 346 | assert operation.command == ( 347 | 'echo a_db a_user a_password a_host a_port' 348 | ) 349 | 350 | 351 | def test_backup_command_placeholders_extra(placeholders_config): 352 | # extra parameters are ignored 353 | options = MigrationBackupOption( 354 | 'echo $database $db_user $db_password $db_host $db_port $foo', 355 | 'test 1 != 1', 356 | ) 357 | operation = options.command_operation(placeholders_config) 358 | assert operation.command == ( 359 | 'echo a_db a_user a_password a_host a_port $foo' 360 | ) 361 | 362 | 363 | def test_backup_command_placeholders_missing(placeholders_config): 364 | # no failure if not using all placeholders 365 | options = MigrationBackupOption( 366 | 'echo $database', 367 | 'test 1 != 1', 368 | ) 369 | operation = options.command_operation(placeholders_config) 370 | assert operation.command == ( 371 | 'echo a_db' 372 | ) 373 | 374 | 375 | def test_backup_force_version(runner_gen, parse_yaml, request, capfd): 376 | # Test that backup is triggered when using force_version 377 | backup_params, config = parse_yaml('migration_with_backup.yml') 378 | config.force_version = '0.0.3' 379 | runner = runner_gen(backup_params, config) 380 | runner.perform() 381 | expected = ( 382 | u'|> migration: Backing up...\n' 383 | u'backup command\r\n' 384 | u'|> migration: force-execute version 0.0.3\n' 385 | u'|> migration: processing version 0.0.3\n' 386 | u'|> version 0.0.3: start\n' 387 | u'|> version 0.0.3: execute base pre-operations\n' 388 | u"|> version 0.0.3: echo 'foobar'\n" 389 | u'foobar\r\n' 390 | u"|> version 0.0.3: echo 'foobarbaz'\n" 391 | u'foobarbaz\r\n' 392 | u'|> version 0.0.3: installation / upgrade of addons\n' 393 | u'|> version 0.0.3: execute base post-operations\n' 394 | u"|> version 0.0.3: echo 'post-op with unicode é â'\n" 395 | u'post-op with unicode é â\r\n' 396 | u'|> version 0.0.3: done\n' 397 | ) 398 | out = capfd.readouterr().out 399 | assert expected == out 400 | 401 | 402 | def test_backup_force_version_no_backup_command(runner_gen, parse_yaml, 403 | request, capfd): 404 | # Test that backup is not triggered when using force_version but no backup 405 | # command is configured 406 | backup_params, config = parse_yaml('migration_no_backup.yml') 407 | config.force_version = '0.0.3' 408 | with pytest.warns(FutureWarning): 409 | # FutureWarning already tested in test_migration_file.py 410 | runner = runner_gen(backup_params, config) 411 | runner.perform() 412 | expected = ( 413 | u'|> migration: force-execute version 0.0.3\n' 414 | u'|> migration: processing version 0.0.3\n' 415 | u'|> version 0.0.3: start\n' 416 | u'|> version 0.0.3: execute base pre-operations\n' 417 | u"|> version 0.0.3: echo 'foobar'\n" 418 | u'foobar\r\n' 419 | u"|> version 0.0.3: echo 'foobarbaz'\n" 420 | u'foobarbaz\r\n' 421 | u'|> version 0.0.3: installation / upgrade of addons\n' 422 | u'|> version 0.0.3: execute base post-operations\n' 423 | u"|> version 0.0.3: echo 'post-op with unicode é â'\n" 424 | u'post-op with unicode é â\r\n' 425 | u'|> version 0.0.3: done\n' 426 | ) 427 | out = capfd.readouterr().out 428 | assert expected == out 429 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | GNU AFFERO GENERAL PUBLIC LICENSE 3 | Version 3, 19 November 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The GNU Affero General Public License is a free, copyleft license for 12 | software and other kinds of works, specifically designed to ensure 13 | cooperation with the community in the case of network server software. 14 | 15 | The licenses for most software and other practical works are designed 16 | to take away your freedom to share and change the works. By contrast, 17 | our General Public Licenses are intended to guarantee your freedom to 18 | share and change all versions of a program--to make sure it remains free 19 | software for all its users. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | them if you wish), that you receive source code or can get it if you 25 | want it, that you can change the software or use pieces of it in new 26 | free programs, and that you know you can do these things. 27 | 28 | Developers that use our General Public Licenses protect your rights 29 | with two steps: (1) assert copyright on the software, and (2) offer 30 | you this License which gives you legal permission to copy, distribute 31 | and/or modify the software. 32 | 33 | A secondary benefit of defending all users' freedom is that 34 | improvements made in alternate versions of the program, if they 35 | receive widespread use, become available for other developers to 36 | incorporate. Many developers of free software are heartened and 37 | encouraged by the resulting cooperation. However, in the case of 38 | software used on network servers, this result may fail to come about. 39 | The GNU General Public License permits making a modified version and 40 | letting the public access it on a server without ever releasing its 41 | source code to the public. 42 | 43 | The GNU Affero General Public License is designed specifically to 44 | ensure that, in such cases, the modified source code becomes available 45 | to the community. It requires the operator of a network server to 46 | provide the source code of the modified version running there to the 47 | users of that server. Therefore, public use of a modified version, on 48 | a publicly accessible server, gives the public access to the source 49 | code of the modified version. 50 | 51 | An older license, called the Affero General Public License and 52 | published by Affero, was designed to accomplish similar goals. This is 53 | a different license, not a version of the Affero GPL, but Affero has 54 | released a new version of the Affero GPL which permits relicensing under 55 | this license. 56 | 57 | The precise terms and conditions for copying, distribution and 58 | modification follow. 59 | 60 | TERMS AND CONDITIONS 61 | 62 | 0. Definitions. 63 | 64 | "This License" refers to version 3 of the GNU Affero General Public License. 65 | 66 | "Copyright" also means copyright-like laws that apply to other kinds of 67 | works, such as semiconductor masks. 68 | 69 | "The Program" refers to any copyrightable work licensed under this 70 | License. Each licensee is addressed as "you". "Licensees" and 71 | "recipients" may be individuals or organizations. 72 | 73 | To "modify" a work means to copy from or adapt all or part of the work 74 | in a fashion requiring copyright permission, other than the making of an 75 | exact copy. The resulting work is called a "modified version" of the 76 | earlier work or a work "based on" the earlier work. 77 | 78 | A "covered work" means either the unmodified Program or a work based 79 | on the Program. 80 | 81 | To "propagate" a work means to do anything with it that, without 82 | permission, would make you directly or secondarily liable for 83 | infringement under applicable copyright law, except executing it on a 84 | computer or modifying a private copy. Propagation includes copying, 85 | distribution (with or without modification), making available to the 86 | public, and in some countries other activities as well. 87 | 88 | To "convey" a work means any kind of propagation that enables other 89 | parties to make or receive copies. Mere interaction with a user through 90 | a computer network, with no transfer of a copy, is not conveying. 91 | 92 | An interactive user interface displays "Appropriate Legal Notices" 93 | to the extent that it includes a convenient and prominently visible 94 | feature that (1) displays an appropriate copyright notice, and (2) 95 | tells the user that there is no warranty for the work (except to the 96 | extent that warranties are provided), that licensees may convey the 97 | work under this License, and how to view a copy of this License. If 98 | the interface presents a list of user commands or options, such as a 99 | menu, a prominent item in the list meets this criterion. 100 | 101 | 1. Source Code. 102 | 103 | The "source code" for a work means the preferred form of the work 104 | for making modifications to it. "Object code" means any non-source 105 | form of a work. 106 | 107 | A "Standard Interface" means an interface that either is an official 108 | standard defined by a recognized standards body, or, in the case of 109 | interfaces specified for a particular programming language, one that 110 | is widely used among developers working in that language. 111 | 112 | The "System Libraries" of an executable work include anything, other 113 | than the work as a whole, that (a) is included in the normal form of 114 | packaging a Major Component, but which is not part of that Major 115 | Component, and (b) serves only to enable use of the work with that 116 | Major Component, or to implement a Standard Interface for which an 117 | implementation is available to the public in source code form. A 118 | "Major Component", in this context, means a major essential component 119 | (kernel, window system, and so on) of the specific operating system 120 | (if any) on which the executable work runs, or a compiler used to 121 | produce the work, or an object code interpreter used to run it. 122 | 123 | The "Corresponding Source" for a work in object code form means all 124 | the source code needed to generate, install, and (for an executable 125 | work) run the object code and to modify the work, including scripts to 126 | control those activities. However, it does not include the work's 127 | System Libraries, or general-purpose tools or generally available free 128 | programs which are used unmodified in performing those activities but 129 | which are not part of the work. For example, Corresponding Source 130 | includes interface definition files associated with source files for 131 | the work, and the source code for shared libraries and dynamically 132 | linked subprograms that the work is specifically designed to require, 133 | such as by intimate data communication or control flow between those 134 | subprograms and other parts of the work. 135 | 136 | The Corresponding Source need not include anything that users 137 | can regenerate automatically from other parts of the Corresponding 138 | Source. 139 | 140 | The Corresponding Source for a work in source code form is that 141 | same work. 142 | 143 | 2. Basic Permissions. 144 | 145 | All rights granted under this License are granted for the term of 146 | copyright on the Program, and are irrevocable provided the stated 147 | conditions are met. This License explicitly affirms your unlimited 148 | permission to run the unmodified Program. The output from running a 149 | covered work is covered by this License only if the output, given its 150 | content, constitutes a covered work. This License acknowledges your 151 | rights of fair use or other equivalent, as provided by copyright law. 152 | 153 | You may make, run and propagate covered works that you do not 154 | convey, without conditions so long as your license otherwise remains 155 | in force. You may convey covered works to others for the sole purpose 156 | of having them make modifications exclusively for you, or provide you 157 | with facilities for running those works, provided that you comply with 158 | the terms of this License in conveying all material for which you do 159 | not control copyright. Those thus making or running the covered works 160 | for you must do so exclusively on your behalf, under your direction 161 | and control, on terms that prohibit them from making any copies of 162 | your copyrighted material outside their relationship with you. 163 | 164 | Conveying under any other circumstances is permitted solely under 165 | the conditions stated below. Sublicensing is not allowed; section 10 166 | makes it unnecessary. 167 | 168 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 169 | 170 | No covered work shall be deemed part of an effective technological 171 | measure under any applicable law fulfilling obligations under article 172 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 173 | similar laws prohibiting or restricting circumvention of such 174 | measures. 175 | 176 | When you convey a covered work, you waive any legal power to forbid 177 | circumvention of technological measures to the extent such circumvention 178 | is effected by exercising rights under this License with respect to 179 | the covered work, and you disclaim any intention to limit operation or 180 | modification of the work as a means of enforcing, against the work's 181 | users, your or third parties' legal rights to forbid circumvention of 182 | technological measures. 183 | 184 | 4. Conveying Verbatim Copies. 185 | 186 | You may convey verbatim copies of the Program's source code as you 187 | receive it, in any medium, provided that you conspicuously and 188 | appropriately publish on each copy an appropriate copyright notice; 189 | keep intact all notices stating that this License and any 190 | non-permissive terms added in accord with section 7 apply to the code; 191 | keep intact all notices of the absence of any warranty; and give all 192 | recipients a copy of this License along with the Program. 193 | 194 | You may charge any price or no price for each copy that you convey, 195 | and you may offer support or warranty protection for a fee. 196 | 197 | 5. Conveying Modified Source Versions. 198 | 199 | You may convey a work based on the Program, or the modifications to 200 | produce it from the Program, in the form of source code under the 201 | terms of section 4, provided that you also meet all of these conditions: 202 | 203 | a) The work must carry prominent notices stating that you modified 204 | it, and giving a relevant date. 205 | 206 | b) The work must carry prominent notices stating that it is 207 | released under this License and any conditions added under section 208 | 7. This requirement modifies the requirement in section 4 to 209 | "keep intact all notices". 210 | 211 | c) You must license the entire work, as a whole, under this 212 | License to anyone who comes into possession of a copy. This 213 | License will therefore apply, along with any applicable section 7 214 | additional terms, to the whole of the work, and all its parts, 215 | regardless of how they are packaged. This License gives no 216 | permission to license the work in any other way, but it does not 217 | invalidate such permission if you have separately received it. 218 | 219 | d) If the work has interactive user interfaces, each must display 220 | Appropriate Legal Notices; however, if the Program has interactive 221 | interfaces that do not display Appropriate Legal Notices, your 222 | work need not make them do so. 223 | 224 | A compilation of a covered work with other separate and independent 225 | works, which are not by their nature extensions of the covered work, 226 | and which are not combined with it such as to form a larger program, 227 | in or on a volume of a storage or distribution medium, is called an 228 | "aggregate" if the compilation and its resulting copyright are not 229 | used to limit the access or legal rights of the compilation's users 230 | beyond what the individual works permit. Inclusion of a covered work 231 | in an aggregate does not cause this License to apply to the other 232 | parts of the aggregate. 233 | 234 | 6. Conveying Non-Source Forms. 235 | 236 | You may convey a covered work in object code form under the terms 237 | of sections 4 and 5, provided that you also convey the 238 | machine-readable Corresponding Source under the terms of this License, 239 | in one of these ways: 240 | 241 | a) Convey the object code in, or embodied in, a physical product 242 | (including a physical distribution medium), accompanied by the 243 | Corresponding Source fixed on a durable physical medium 244 | customarily used for software interchange. 245 | 246 | b) Convey the object code in, or embodied in, a physical product 247 | (including a physical distribution medium), accompanied by a 248 | written offer, valid for at least three years and valid for as 249 | long as you offer spare parts or customer support for that product 250 | model, to give anyone who possesses the object code either (1) a 251 | copy of the Corresponding Source for all the software in the 252 | product that is covered by this License, on a durable physical 253 | medium customarily used for software interchange, for a price no 254 | more than your reasonable cost of physically performing this 255 | conveying of source, or (2) access to copy the 256 | Corresponding Source from a network server at no charge. 257 | 258 | c) Convey individual copies of the object code with a copy of the 259 | written offer to provide the Corresponding Source. This 260 | alternative is allowed only occasionally and noncommercially, and 261 | only if you received the object code with such an offer, in accord 262 | with subsection 6b. 263 | 264 | d) Convey the object code by offering access from a designated 265 | place (gratis or for a charge), and offer equivalent access to the 266 | Corresponding Source in the same way through the same place at no 267 | further charge. You need not require recipients to copy the 268 | Corresponding Source along with the object code. If the place to 269 | copy the object code is a network server, the Corresponding Source 270 | may be on a different server (operated by you or a third party) 271 | that supports equivalent copying facilities, provided you maintain 272 | clear directions next to the object code saying where to find the 273 | Corresponding Source. Regardless of what server hosts the 274 | Corresponding Source, you remain obligated to ensure that it is 275 | available for as long as needed to satisfy these requirements. 276 | 277 | e) Convey the object code using peer-to-peer transmission, provided 278 | you inform other peers where the object code and Corresponding 279 | Source of the work are being offered to the general public at no 280 | charge under subsection 6d. 281 | 282 | A separable portion of the object code, whose source code is excluded 283 | from the Corresponding Source as a System Library, need not be 284 | included in conveying the object code work. 285 | 286 | A "User Product" is either (1) a "consumer product", which means any 287 | tangible personal property which is normally used for personal, family, 288 | or household purposes, or (2) anything designed or sold for incorporation 289 | into a dwelling. In determining whether a product is a consumer product, 290 | doubtful cases shall be resolved in favor of coverage. For a particular 291 | product received by a particular user, "normally used" refers to a 292 | typical or common use of that class of product, regardless of the status 293 | of the particular user or of the way in which the particular user 294 | actually uses, or expects or is expected to use, the product. A product 295 | is a consumer product regardless of whether the product has substantial 296 | commercial, industrial or non-consumer uses, unless such uses represent 297 | the only significant mode of use of the product. 298 | 299 | "Installation Information" for a User Product means any methods, 300 | procedures, authorization keys, or other information required to install 301 | and execute modified versions of a covered work in that User Product from 302 | a modified version of its Corresponding Source. The information must 303 | suffice to ensure that the continued functioning of the modified object 304 | code is in no case prevented or interfered with solely because 305 | modification has been made. 306 | 307 | If you convey an object code work under this section in, or with, or 308 | specifically for use in, a User Product, and the conveying occurs as 309 | part of a transaction in which the right of possession and use of the 310 | User Product is transferred to the recipient in perpetuity or for a 311 | fixed term (regardless of how the transaction is characterized), the 312 | Corresponding Source conveyed under this section must be accompanied 313 | by the Installation Information. But this requirement does not apply 314 | if neither you nor any third party retains the ability to install 315 | modified object code on the User Product (for example, the work has 316 | been installed in ROM). 317 | 318 | The requirement to provide Installation Information does not include a 319 | requirement to continue to provide support service, warranty, or updates 320 | for a work that has been modified or installed by the recipient, or for 321 | the User Product in which it has been modified or installed. Access to a 322 | network may be denied when the modification itself materially and 323 | adversely affects the operation of the network or violates the rules and 324 | protocols for communication across the network. 325 | 326 | Corresponding Source conveyed, and Installation Information provided, 327 | in accord with this section must be in a format that is publicly 328 | documented (and with an implementation available to the public in 329 | source code form), and must require no special password or key for 330 | unpacking, reading or copying. 331 | 332 | 7. Additional Terms. 333 | 334 | "Additional permissions" are terms that supplement the terms of this 335 | License by making exceptions from one or more of its conditions. 336 | Additional permissions that are applicable to the entire Program shall 337 | be treated as though they were included in this License, to the extent 338 | that they are valid under applicable law. If additional permissions 339 | apply only to part of the Program, that part may be used separately 340 | under those permissions, but the entire Program remains governed by 341 | this License without regard to the additional permissions. 342 | 343 | When you convey a copy of a covered work, you may at your option 344 | remove any additional permissions from that copy, or from any part of 345 | it. (Additional permissions may be written to require their own 346 | removal in certain cases when you modify the work.) You may place 347 | additional permissions on material, added by you to a covered work, 348 | for which you have or can give appropriate copyright permission. 349 | 350 | Notwithstanding any other provision of this License, for material you 351 | add to a covered work, you may (if authorized by the copyright holders of 352 | that material) supplement the terms of this License with terms: 353 | 354 | a) Disclaiming warranty or limiting liability differently from the 355 | terms of sections 15 and 16 of this License; or 356 | 357 | b) Requiring preservation of specified reasonable legal notices or 358 | author attributions in that material or in the Appropriate Legal 359 | Notices displayed by works containing it; or 360 | 361 | c) Prohibiting misrepresentation of the origin of that material, or 362 | requiring that modified versions of such material be marked in 363 | reasonable ways as different from the original version; or 364 | 365 | d) Limiting the use for publicity purposes of names of licensors or 366 | authors of the material; or 367 | 368 | e) Declining to grant rights under trademark law for use of some 369 | trade names, trademarks, or service marks; or 370 | 371 | f) Requiring indemnification of licensors and authors of that 372 | material by anyone who conveys the material (or modified versions of 373 | it) with contractual assumptions of liability to the recipient, for 374 | any liability that these contractual assumptions directly impose on 375 | those licensors and authors. 376 | 377 | All other non-permissive additional terms are considered "further 378 | restrictions" within the meaning of section 10. If the Program as you 379 | received it, or any part of it, contains a notice stating that it is 380 | governed by this License along with a term that is a further 381 | restriction, you may remove that term. If a license document contains 382 | a further restriction but permits relicensing or conveying under this 383 | License, you may add to a covered work material governed by the terms 384 | of that license document, provided that the further restriction does 385 | not survive such relicensing or conveying. 386 | 387 | If you add terms to a covered work in accord with this section, you 388 | must place, in the relevant source files, a statement of the 389 | additional terms that apply to those files, or a notice indicating 390 | where to find the applicable terms. 391 | 392 | Additional terms, permissive or non-permissive, may be stated in the 393 | form of a separately written license, or stated as exceptions; 394 | the above requirements apply either way. 395 | 396 | 8. Termination. 397 | 398 | You may not propagate or modify a covered work except as expressly 399 | provided under this License. Any attempt otherwise to propagate or 400 | modify it is void, and will automatically terminate your rights under 401 | this License (including any patent licenses granted under the third 402 | paragraph of section 11). 403 | 404 | However, if you cease all violation of this License, then your 405 | license from a particular copyright holder is reinstated (a) 406 | provisionally, unless and until the copyright holder explicitly and 407 | finally terminates your license, and (b) permanently, if the copyright 408 | holder fails to notify you of the violation by some reasonable means 409 | prior to 60 days after the cessation. 410 | 411 | Moreover, your license from a particular copyright holder is 412 | reinstated permanently if the copyright holder notifies you of the 413 | violation by some reasonable means, this is the first time you have 414 | received notice of violation of this License (for any work) from that 415 | copyright holder, and you cure the violation prior to 30 days after 416 | your receipt of the notice. 417 | 418 | Termination of your rights under this section does not terminate the 419 | licenses of parties who have received copies or rights from you under 420 | this License. If your rights have been terminated and not permanently 421 | reinstated, you do not qualify to receive new licenses for the same 422 | material under section 10. 423 | 424 | 9. Acceptance Not Required for Having Copies. 425 | 426 | You are not required to accept this License in order to receive or 427 | run a copy of the Program. Ancillary propagation of a covered work 428 | occurring solely as a consequence of using peer-to-peer transmission 429 | to receive a copy likewise does not require acceptance. However, 430 | nothing other than this License grants you permission to propagate or 431 | modify any covered work. These actions infringe copyright if you do 432 | not accept this License. Therefore, by modifying or propagating a 433 | covered work, you indicate your acceptance of this License to do so. 434 | 435 | 10. Automatic Licensing of Downstream Recipients. 436 | 437 | Each time you convey a covered work, the recipient automatically 438 | receives a license from the original licensors, to run, modify and 439 | propagate that work, subject to this License. You are not responsible 440 | for enforcing compliance by third parties with this License. 441 | 442 | An "entity transaction" is a transaction transferring control of an 443 | organization, or substantially all assets of one, or subdividing an 444 | organization, or merging organizations. If propagation of a covered 445 | work results from an entity transaction, each party to that 446 | transaction who receives a copy of the work also receives whatever 447 | licenses to the work the party's predecessor in interest had or could 448 | give under the previous paragraph, plus a right to possession of the 449 | Corresponding Source of the work from the predecessor in interest, if 450 | the predecessor has it or can get it with reasonable efforts. 451 | 452 | You may not impose any further restrictions on the exercise of the 453 | rights granted or affirmed under this License. For example, you may 454 | not impose a license fee, royalty, or other charge for exercise of 455 | rights granted under this License, and you may not initiate litigation 456 | (including a cross-claim or counterclaim in a lawsuit) alleging that 457 | any patent claim is infringed by making, using, selling, offering for 458 | sale, or importing the Program or any portion of it. 459 | 460 | 11. Patents. 461 | 462 | A "contributor" is a copyright holder who authorizes use under this 463 | License of the Program or a work on which the Program is based. The 464 | work thus licensed is called the contributor's "contributor version". 465 | 466 | A contributor's "essential patent claims" are all patent claims 467 | owned or controlled by the contributor, whether already acquired or 468 | hereafter acquired, that would be infringed by some manner, permitted 469 | by this License, of making, using, or selling its contributor version, 470 | but do not include claims that would be infringed only as a 471 | consequence of further modification of the contributor version. For 472 | purposes of this definition, "control" includes the right to grant 473 | patent sublicenses in a manner consistent with the requirements of 474 | this License. 475 | 476 | Each contributor grants you a non-exclusive, worldwide, royalty-free 477 | patent license under the contributor's essential patent claims, to 478 | make, use, sell, offer for sale, import and otherwise run, modify and 479 | propagate the contents of its contributor version. 480 | 481 | In the following three paragraphs, a "patent license" is any express 482 | agreement or commitment, however denominated, not to enforce a patent 483 | (such as an express permission to practice a patent or covenant not to 484 | sue for patent infringement). To "grant" such a patent license to a 485 | party means to make such an agreement or commitment not to enforce a 486 | patent against the party. 487 | 488 | If you convey a covered work, knowingly relying on a patent license, 489 | and the Corresponding Source of the work is not available for anyone 490 | to copy, free of charge and under the terms of this License, through a 491 | publicly available network server or other readily accessible means, 492 | then you must either (1) cause the Corresponding Source to be so 493 | available, or (2) arrange to deprive yourself of the benefit of the 494 | patent license for this particular work, or (3) arrange, in a manner 495 | consistent with the requirements of this License, to extend the patent 496 | license to downstream recipients. "Knowingly relying" means you have 497 | actual knowledge that, but for the patent license, your conveying the 498 | covered work in a country, or your recipient's use of the covered work 499 | in a country, would infringe one or more identifiable patents in that 500 | country that you have reason to believe are valid. 501 | 502 | If, pursuant to or in connection with a single transaction or 503 | arrangement, you convey, or propagate by procuring conveyance of, a 504 | covered work, and grant a patent license to some of the parties 505 | receiving the covered work authorizing them to use, propagate, modify 506 | or convey a specific copy of the covered work, then the patent license 507 | you grant is automatically extended to all recipients of the covered 508 | work and works based on it. 509 | 510 | A patent license is "discriminatory" if it does not include within 511 | the scope of its coverage, prohibits the exercise of, or is 512 | conditioned on the non-exercise of one or more of the rights that are 513 | specifically granted under this License. You may not convey a covered 514 | work if you are a party to an arrangement with a third party that is 515 | in the business of distributing software, under which you make payment 516 | to the third party based on the extent of your activity of conveying 517 | the work, and under which the third party grants, to any of the 518 | parties who would receive the covered work from you, a discriminatory 519 | patent license (a) in connection with copies of the covered work 520 | conveyed by you (or copies made from those copies), or (b) primarily 521 | for and in connection with specific products or compilations that 522 | contain the covered work, unless you entered into that arrangement, 523 | or that patent license was granted, prior to 28 March 2007. 524 | 525 | Nothing in this License shall be construed as excluding or limiting 526 | any implied license or other defenses to infringement that may 527 | otherwise be available to you under applicable patent law. 528 | 529 | 12. No Surrender of Others' Freedom. 530 | 531 | If conditions are imposed on you (whether by court order, agreement or 532 | otherwise) that contradict the conditions of this License, they do not 533 | excuse you from the conditions of this License. If you cannot convey a 534 | covered work so as to satisfy simultaneously your obligations under this 535 | License and any other pertinent obligations, then as a consequence you may 536 | not convey it at all. For example, if you agree to terms that obligate you 537 | to collect a royalty for further conveying from those to whom you convey 538 | the Program, the only way you could satisfy both those terms and this 539 | License would be to refrain entirely from conveying the Program. 540 | 541 | 13. Remote Network Interaction; Use with the GNU General Public License. 542 | 543 | Notwithstanding any other provision of this License, if you modify the 544 | Program, your modified version must prominently offer all users 545 | interacting with it remotely through a computer network (if your version 546 | supports such interaction) an opportunity to receive the Corresponding 547 | Source of your version by providing access to the Corresponding Source 548 | from a network server at no charge, through some standard or customary 549 | means of facilitating copying of software. This Corresponding Source 550 | shall include the Corresponding Source for any work covered by version 3 551 | of the GNU General Public License that is incorporated pursuant to the 552 | following paragraph. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the work with which it is combined will remain governed by version 560 | 3 of the GNU General Public License. 561 | 562 | 14. Revised Versions of this License. 563 | 564 | The Free Software Foundation may publish revised and/or new versions of 565 | the GNU Affero General Public License from time to time. Such new versions 566 | will be similar in spirit to the present version, but may differ in detail to 567 | address new problems or concerns. 568 | 569 | Each version is given a distinguishing version number. If the 570 | Program specifies that a certain numbered version of the GNU Affero General 571 | Public License "or any later version" applies to it, you have the 572 | option of following the terms and conditions either of that numbered 573 | version or of any later version published by the Free Software 574 | Foundation. If the Program does not specify a version number of the 575 | GNU Affero General Public License, you may choose any version ever published 576 | by the Free Software Foundation. 577 | 578 | If the Program specifies that a proxy can decide which future 579 | versions of the GNU Affero General Public License can be used, that proxy's 580 | public statement of acceptance of a version permanently authorizes you 581 | to choose that version for the Program. 582 | 583 | Later license versions may give you additional or different 584 | permissions. However, no additional obligations are imposed on any 585 | author or copyright holder as a result of your choosing to follow a 586 | later version. 587 | 588 | 15. Disclaimer of Warranty. 589 | 590 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 591 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 592 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 593 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 594 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 595 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 596 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 597 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 598 | 599 | 16. Limitation of Liability. 600 | 601 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 602 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 603 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 604 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 605 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 606 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 607 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 608 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 609 | SUCH DAMAGES. 610 | 611 | 17. Interpretation of Sections 15 and 16. 612 | 613 | If the disclaimer of warranty and limitation of liability provided 614 | above cannot be given local legal effect according to their terms, 615 | reviewing courts shall apply local law that most closely approximates 616 | an absolute waiver of all civil liability in connection with the 617 | Program, unless a warranty or assumption of liability accompanies a 618 | copy of the Program in return for a fee. 619 | 620 | END OF TERMS AND CONDITIONS 621 | 622 | How to Apply These Terms to Your New Programs 623 | 624 | If you develop a new program, and you want it to be of the greatest 625 | possible use to the public, the best way to achieve this is to make it 626 | free software which everyone can redistribute and change under these terms. 627 | 628 | To do so, attach the following notices to the program. It is safest 629 | to attach them to the start of each source file to most effectively 630 | state the exclusion of warranty; and each file should have at least 631 | the "copyright" line and a pointer to where the full notice is found. 632 | 633 | 634 | Copyright (C) 635 | 636 | This program is free software: you can redistribute it and/or modify 637 | it under the terms of the GNU Affero General Public License as published by 638 | the Free Software Foundation, either version 3 of the License, or 639 | (at your option) any later version. 640 | 641 | This program is distributed in the hope that it will be useful, 642 | but WITHOUT ANY WARRANTY; without even the implied warranty of 643 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 644 | GNU Affero General Public License for more details. 645 | 646 | You should have received a copy of the GNU Affero General Public License 647 | along with this program. If not, see . 648 | 649 | Also add information on how to contact you by electronic and paper mail. 650 | 651 | If your software can interact with users remotely through a computer 652 | network, you should also make sure that it provides a way for users to 653 | get its source. For example, if your program is a web application, its 654 | interface could display a "Source" link that leads users to an archive 655 | of the code. There are many ways you could offer source, and different 656 | solutions will be better for different programs; see section 13 for the 657 | specific requirements. 658 | 659 | You should also get your employer (if you work as a programmer) or school, 660 | if any, to sign a "copyright disclaimer" for the program, if necessary. 661 | For more information on this, and how to apply and follow the GNU AGPL, see 662 | . 663 | --------------------------------------------------------------------------------