summaryrefslogtreecommitdiff
path: root/keystone/common/sql/upgrades.py
blob: f0657e01ac6355e801d25f8fc87538531a1f58da (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
# Copyright 2013 OpenStack Foundation
# Copyright 2013 Red Hat, Inc.
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

import os

from migrate import exceptions as migrate_exceptions
from migrate.versioning import api as migrate_api
from migrate.versioning import repository as migrate_repository
from oslo_db import exception as db_exception
import sqlalchemy as sa

from keystone.common import sql
from keystone import exception
from keystone.i18n import _

INITIAL_VERSION = 72
LATEST_VERSION = 79
EXPAND_REPO = 'expand_repo'
DATA_MIGRATION_REPO = 'data_migration_repo'
CONTRACT_REPO = 'contract_repo'


def _get_migrate_repo_path(repo_name):
    abs_path = os.path.abspath(
        os.path.join(
            os.path.dirname(sql.__file__),
            'legacy_migrations',
            repo_name,
        )
    )

    if not os.path.isdir(abs_path):
        raise exception.MigrationNotProvided(sql.__name__, abs_path)

    return abs_path


def _find_migrate_repo(abs_path):
    """Get the project's change script repository

    :param abs_path: Absolute path to migrate repository
    """
    if not os.path.exists(abs_path):
        raise db_exception.DBMigrationError("Path %s not found" % abs_path)
    return migrate_repository.Repository(abs_path)


def _migrate_db_version_control(engine, abs_path, version=None):
    """Mark a database as under this repository's version control.

    Once a database is under version control, schema changes should
    only be done via change scripts in this repository.

    :param engine: SQLAlchemy engine instance for a given database
    :param abs_path: Absolute path to migrate repository
    :param version: Initial database version
    """
    repository = _find_migrate_repo(abs_path)

    try:
        migrate_api.version_control(engine, repository, version)
    except migrate_exceptions.InvalidVersionError as ex:
        raise db_exception.DBMigrationError("Invalid version : %s" % ex)
    except migrate_exceptions.DatabaseAlreadyControlledError:
        raise db_exception.DBMigrationError("Database is already controlled.")

    return version


def _migrate_db_version(engine, abs_path, init_version):
    """Show the current version of the repository.

    :param engine: SQLAlchemy engine instance for a given database
    :param abs_path: Absolute path to migrate repository
    :param init_version: Initial database version
    """
    repository = _find_migrate_repo(abs_path)
    try:
        return migrate_api.db_version(engine, repository)
    except migrate_exceptions.DatabaseNotControlledError:
        pass

    meta = sa.MetaData()
    meta.reflect(bind=engine)
    tables = meta.tables
    if (
        len(tables) == 0 or
        'alembic_version' in tables or
        'migrate_version' in tables
    ):
        _migrate_db_version_control(engine, abs_path, version=init_version)
        return migrate_api.db_version(engine, repository)

    msg = _(
        "The database is not under version control, but has tables. "
        "Please stamp the current version of the schema manually."
    )
    raise db_exception.DBMigrationError(msg)


def _migrate_db_sync(engine, abs_path, version=None, init_version=0):
    """Upgrade or downgrade a database.

    Function runs the upgrade() or downgrade() functions in change scripts.

    :param engine: SQLAlchemy engine instance for a given database
    :param abs_path: Absolute path to migrate repository.
    :param version: Database will upgrade/downgrade until this version.
        If None - database will update to the latest available version.
    :param init_version: Initial database version
    """

    if version is not None:
        try:
            version = int(version)
        except ValueError:
            msg = _("version should be an integer")
            raise db_exception.DBMigrationError(msg)

    current_version = _migrate_db_version(engine, abs_path, init_version)
    repository = _find_migrate_repo(abs_path)

    if version is None or version > current_version:
        try:
            return migrate_api.upgrade(engine, repository, version)
        except Exception as ex:
            raise db_exception.DBMigrationError(ex)
    else:
        return migrate_api.downgrade(engine, repository, version)


def _sync_repo(repo_name):
    abs_path = _get_migrate_repo_path(repo_name)
    with sql.session_for_write() as session:
        engine = session.get_bind()
        _migrate_db_sync(
            engine=engine,
            abs_path=abs_path,
            init_version=INITIAL_VERSION,
        )


def offline_sync_database_to_version(version=None):
    """Perform and off-line sync of the database.

    Migrate the database up to the latest version, doing the equivalent of
    the cycle of --expand, --migrate and --contract, for when an offline
    upgrade is being performed.

    If a version is specified then only migrate the database up to that
    version. Downgrading is not supported. If version is specified, then only
    the main database migration is carried out - and the expand, migration and
    contract phases will NOT be run.
    """
    if version:
        raise Exception('Specifying a version is no longer supported')

    expand_schema()
    migrate_data()
    contract_schema()


def get_db_version(repo=EXPAND_REPO):
    abs_path = _get_migrate_repo_path(repo)
    with sql.session_for_read() as session:
        return _migrate_db_version(
            session.get_bind(),
            abs_path,
            INITIAL_VERSION,
        )


def validate_upgrade_order(repo_name, target_repo_version=None):
    """Validate the state of the migration repositories.

    This is run before allowing the db_sync command to execute. Ensure the
    upgrade step and version specified by the operator remains consistent with
    the upgrade process. I.e. expand's version is greater or equal to
    migrate's, migrate's version is greater or equal to contract's.

    :param repo_name: The name of the repository that the user is trying to
                      upgrade.
    :param target_repo_version: The version to upgrade the repo. Otherwise, the
                                version will be upgraded to the latest version
                                available.
    """
    # Initialize a dict to have each key assigned a repo with their value being
    # the repo that comes before.
    db_sync_order = {
        DATA_MIGRATION_REPO: EXPAND_REPO,
        CONTRACT_REPO: DATA_MIGRATION_REPO,
    }

    if repo_name == EXPAND_REPO:
        return

    # find the latest version that the current command will upgrade to if there
    # wasn't a version specified for upgrade.
    if not target_repo_version:
        abs_path = _get_migrate_repo_path(repo_name)
        repo = _find_migrate_repo(abs_path)
        target_repo_version = int(repo.latest)

    # get current version of the command that runs before the current command.
    dependency_repo_version = get_db_version(repo=db_sync_order[repo_name])

    if dependency_repo_version < target_repo_version:
        raise db_exception.DBMigrationError(
            'You are attempting to upgrade %s ahead of %s. Please refer to '
            'https://docs.openstack.org/keystone/latest/admin/'
            'identity-upgrading.html '
            'to see the proper steps for rolling upgrades.' % (
                repo_name, db_sync_order[repo_name]))


def expand_schema():
    """Expand the database schema ahead of data migration.

    This is run manually by the keystone-manage command before the first
    keystone node is migrated to the latest release.
    """
    validate_upgrade_order(EXPAND_REPO)
    _sync_repo(repo_name=EXPAND_REPO)


def migrate_data():
    """Migrate data to match the new schema.

    This is run manually by the keystone-manage command once the keystone
    schema has been expanded for the new release.
    """
    validate_upgrade_order(DATA_MIGRATION_REPO)
    _sync_repo(repo_name=DATA_MIGRATION_REPO)


def contract_schema():
    """Contract the database.

    This is run manually by the keystone-manage command once the keystone
    nodes have been upgraded to the latest release and will remove any old
    tables/columns that are no longer required.
    """
    validate_upgrade_order(CONTRACT_REPO)
    _sync_repo(repo_name=CONTRACT_REPO)