/
engine.py
178 lines (144 loc) · 6.13 KB
/
engine.py
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
###############################################################################
#
# Copyright 2014 by Shoobx, Inc.
#
###############################################################################
import logging
import multiprocessing
import functools
log = logging.getLogger(__name__)
from migrant import exceptions
class MigrantEngine:
def __init__(self, backend, repository, config, dry_run=False):
self.backend = backend
self.repository = repository
self.script_ids = ["INITIAL"] + repository.list_script_ids()
self.dry_run = dry_run
self.config = config
def status(self, target_id=None):
"""Return number of migration actions to be performed to
upgrade to target_id"""
target_id = self.pick_rev_id(target_id)
conns = self.backend.generate_connections()
total_actions = 0
for db in self.initialized_dbs(conns):
actions = self.calc_actions(db, target_id)
total_actions += len(actions)
return total_actions
def _update(self, db, target_id=None):
log.info("Starting migration for %s" % db)
actions = self.calc_actions(db, target_id)
self.execute_actions(db, actions)
log.info("Migration completed for %s" % db)
def update(self, target_id=None):
target_id = self.pick_rev_id(target_id)
conns = self.backend.generate_connections()
f = functools.partial(self._update, target_id=target_id)
with multiprocessing.Pool() as pool:
pool.map(f, self.initialized_dbs(conns))
def test(self, target_id=None):
target_id = self.pick_rev_id(target_id)
conns = self.backend.generate_test_connections()
for db in self.initialized_dbs(conns):
actions = self.calc_actions(db, target_id)
# Perform 2 passes of up/down to make sure database is still
# upgradeable after being downgraded.
for testpass in range(1, 3):
log.info(f"PASS {testpass}. Testing upgrade for {db}")
self.execute_actions(db, actions, strict=True)
log.info(f"PASS {testpass}. Testing downgrade for {db}")
reverted_actions = self.revert_actions(actions)
self.execute_actions(db, reverted_actions, strict=True)
log.info("Testing completed for %s" % db)
def initialized_dbs(self, conns):
for db in conns:
log.info("Preparing migrations for %s" % db)
migrations = self.backend.list_migrations(db)
if not migrations:
latest_revid = self.pick_rev_id(None)
self.initialize_db(db, latest_revid)
continue
yield db
def initialize_db(self, db, initial_revid):
for sid in self.script_ids:
if sid != "INITIAL":
# Try to resolve into proper script name
script = self.repository.load_script(sid)
sid = script.name
self.backend.push_migration(db, sid)
log.info(f"Initializing migrations for {db}. Assuming database is at {sid}")
def pick_rev_id(self, rev_id=None):
if rev_id is None:
# Pick latest one
rev_id = self.script_ids[-1]
if canonical_rev_id(rev_id) not in self.script_ids:
raise exceptions.ScriptNotFoundError(rev_id)
return rev_id
def calc_actions(self, db, target_revid):
"""Caclulate actions, required to update to revision `target_revid`
"""
target_revid = canonical_rev_id(target_revid)
assert target_revid in self.script_ids
migrations = self.list_backend_migrations(db)
assert len(migrations) > 0, "Migrations are initialized"
script_idx = {v: idx for idx, v in enumerate(self.script_ids)}
migrations = [m for m in migrations if m in script_idx]
migrations = sorted(migrations, key=lambda m: script_idx[m])
if not migrations:
log.warning(
"No common revision between repository and "
"database %s. Running all migrations up to %s",
db,
target_revid,
)
base_revid = "INITIAL"
else:
base_revid = migrations[0]
base_idx = script_idx[base_revid]
target_idx = script_idx[target_revid]
toremove = [m for m in reversed(migrations) if script_idx[m] > target_idx]
toadd = [
s
for s in self.script_ids
if base_idx < script_idx[s] <= target_idx and s not in migrations
]
return [("-", rid) for rid in toremove] + [("+", rid) for rid in toadd]
def revert_actions(self, actions):
reverts = [("+" if a == "-" else "-", script) for a, script in actions]
return list(reversed(reverts))
def list_backend_migrations(self, db):
return [canonical_rev_id(revid) for revid in self.backend.list_migrations(db)]
def execute_actions(self, db, actions, strict=False):
for action, revid in actions:
script = self.repository.load_script(revid)
assert action in ("+", "-")
if action == "+":
after = script.test_after_up
before = script.test_before_up
during = script.up
end = self.backend.push_migration
infinitive = "Upgrading"
elif action == "-":
after = script.test_after_down
before = script.test_before_down
during = script.down
end = self.backend.pop_migration
infinitive = "Reverting"
log.info(
"%s to %s%s",
infinitive,
script.name,
" (not really)" if self.dry_run else "",
)
if not self.dry_run:
if strict:
before(db)
during(db)
if strict:
after(db)
end(db, script.name)
def canonical_rev_id(migration_name):
if "_" in migration_name:
return migration_name.split("_", 1)[0]
else:
return migration_name