author | Aurelien Campeas <aurelien.campeas@logilab.fr> |
Mon, 22 Jun 2009 11:53:59 +0200 | |
branch | stable |
changeset 2131 | 00e6d1cb18ea |
parent 2124 | 5a0b02f37b23 |
child 2275 | bc0bed0616a3 |
permissions | -rw-r--r-- |
0 | 1 |
"""utility to ease migration of application version to newly installed |
2 |
version |
|
3 |
||
4 |
:organization: Logilab |
|
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1802
diff
changeset
|
5 |
:copyright: 2001-2009 LOGILAB S.A. (Paris, FRANCE), license is LGPL v2. |
0 | 6 |
:contact: http://www.logilab.fr/ -- mailto:contact@logilab.fr |
1977
606923dff11b
big bunch of copyright / docstring update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
1802
diff
changeset
|
7 |
:license: GNU Lesser General Public License, v2.1 - http://www.gnu.org/licenses |
0 | 8 |
""" |
9 |
__docformat__ = "restructuredtext en" |
|
10 |
||
11 |
import sys |
|
12 |
import os |
|
13 |
import logging |
|
14 |
from tempfile import mktemp |
|
15 |
from os.path import exists, join, basename, splitext |
|
16 |
||
17 |
from logilab.common.decorators import cached |
|
18 |
from logilab.common.configuration import REQUIRED, read_old_config |
|
19 |
||
2124
5a0b02f37b23
set removedeps to False by default, raise an exception instead of a simple assertion for error, more remove_cube tests
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2122
diff
changeset
|
20 |
from cubicweb import ConfigurationError |
5a0b02f37b23
set removedeps to False by default, raise an exception instead of a simple assertion for error, more remove_cube tests
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2122
diff
changeset
|
21 |
|
0 | 22 |
|
23 |
def migration_files(config, toupgrade): |
|
24 |
"""return an orderer list of path of scripts to execute to upgrade |
|
25 |
an installed application according to installed cube and cubicweb versions |
|
26 |
""" |
|
27 |
merged = [] |
|
28 |
for cube, fromversion, toversion in toupgrade: |
|
29 |
if cube == 'cubicweb': |
|
30 |
migrdir = config.migration_scripts_dir() |
|
31 |
else: |
|
32 |
migrdir = config.cube_migration_scripts_dir(cube) |
|
33 |
scripts = filter_scripts(config, migrdir, fromversion, toversion) |
|
34 |
merged += [s[1] for s in scripts] |
|
35 |
if config.accept_mode('Any'): |
|
36 |
migrdir = config.migration_scripts_dir() |
|
37 |
merged.insert(0, join(migrdir, 'bootstrapmigration_repository.py')) |
|
38 |
return merged |
|
39 |
||
40 |
||
41 |
def filter_scripts(config, directory, fromversion, toversion, quiet=True): |
|
42 |
"""return a list of paths of migration files to consider to upgrade |
|
43 |
from a version to a greater one |
|
44 |
""" |
|
45 |
from logilab.common.changelog import Version # doesn't work with appengine |
|
46 |
assert fromversion |
|
47 |
assert toversion |
|
48 |
assert isinstance(fromversion, tuple), fromversion.__class__ |
|
49 |
assert isinstance(toversion, tuple), toversion.__class__ |
|
50 |
assert fromversion <= toversion, (fromversion, toversion) |
|
51 |
if not exists(directory): |
|
52 |
if not quiet: |
|
53 |
print directory, "doesn't exists, no migration path" |
|
54 |
return [] |
|
55 |
if fromversion == toversion: |
|
56 |
return [] |
|
57 |
result = [] |
|
58 |
for fname in os.listdir(directory): |
|
59 |
if fname.endswith('.pyc') or fname.endswith('.pyo') \ |
|
60 |
or fname.endswith('~'): |
|
61 |
continue |
|
62 |
fpath = join(directory, fname) |
|
63 |
try: |
|
64 |
tver, mode = fname.split('_', 1) |
|
65 |
except ValueError: |
|
66 |
continue |
|
67 |
mode = mode.split('.', 1)[0] |
|
68 |
if not config.accept_mode(mode): |
|
69 |
continue |
|
70 |
try: |
|
71 |
tver = Version(tver) |
|
72 |
except ValueError: |
|
73 |
continue |
|
74 |
if tver <= fromversion: |
|
75 |
continue |
|
76 |
if tver > toversion: |
|
77 |
continue |
|
78 |
result.append((tver, fpath)) |
|
79 |
# be sure scripts are executed in order |
|
80 |
return sorted(result) |
|
81 |
||
82 |
||
83 |
IGNORED_EXTENSIONS = ('.swp', '~') |
|
84 |
||
85 |
||
86 |
def execscript_confirm(scriptpath): |
|
87 |
"""asks for confirmation before executing a script and provides the |
|
88 |
ability to show the script's content |
|
89 |
""" |
|
90 |
while True: |
|
91 |
confirm = raw_input('** execute %r (Y/n/s[how]) ?' % scriptpath) |
|
92 |
confirm = confirm.strip().lower() |
|
93 |
if confirm in ('n', 'no'): |
|
94 |
return False |
|
95 |
elif confirm in ('s', 'show'): |
|
96 |
stream = open(scriptpath) |
|
97 |
scriptcontent = stream.read() |
|
98 |
stream.close() |
|
99 |
print |
|
100 |
print scriptcontent |
|
101 |
print |
|
102 |
else: |
|
103 |
return True |
|
104 |
||
105 |
def yes(*args, **kwargs): |
|
106 |
return True |
|
107 |
||
108 |
||
109 |
class MigrationHelper(object): |
|
110 |
"""class holding CubicWeb Migration Actions used by migration scripts""" |
|
111 |
||
112 |
def __init__(self, config, interactive=True, verbosity=1): |
|
113 |
self.config = config |
|
114 |
self.config.init_log(logthreshold=logging.ERROR, debug=True) |
|
115 |
# 0: no confirmation, 1: only main commands confirmed, 2 ask for everything |
|
116 |
self.verbosity = verbosity |
|
117 |
self.need_wrap = True |
|
118 |
if not interactive or not verbosity: |
|
119 |
self.confirm = yes |
|
120 |
self.execscript_confirm = yes |
|
121 |
else: |
|
122 |
self.execscript_confirm = execscript_confirm |
|
123 |
self._option_changes = [] |
|
124 |
self.__context = {'confirm': self.confirm, |
|
125 |
'config': self.config, |
|
126 |
'interactive_mode': interactive, |
|
127 |
} |
|
128 |
||
129 |
def repo_connect(self): |
|
130 |
return self.config.repository() |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
676
diff
changeset
|
131 |
|
0 | 132 |
def migrate(self, vcconf, toupgrade, options): |
133 |
"""upgrade the given set of cubes |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
676
diff
changeset
|
134 |
|
0 | 135 |
`cubes` is an ordered list of 3-uple: |
136 |
(cube, fromversion, toversion) |
|
137 |
""" |
|
138 |
if options.fs_only: |
|
139 |
# monkey path configuration.accept_mode so database mode (e.g. Any) |
|
140 |
# won't be accepted |
|
141 |
orig_accept_mode = self.config.accept_mode |
|
142 |
def accept_mode(mode): |
|
143 |
if mode == 'Any': |
|
144 |
return False |
|
145 |
return orig_accept_mode(mode) |
|
146 |
self.config.accept_mode = accept_mode |
|
147 |
scripts = migration_files(self.config, toupgrade) |
|
148 |
if scripts: |
|
149 |
vmap = dict( (pname, (fromver, tover)) for pname, fromver, tover in toupgrade) |
|
150 |
self.__context.update({'applcubicwebversion': vcconf['cubicweb'], |
|
151 |
'cubicwebversion': self.config.cubicweb_version(), |
|
152 |
'versions_map': vmap}) |
|
153 |
self.scripts_session(scripts) |
|
154 |
else: |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
676
diff
changeset
|
155 |
print 'no migration script to execute' |
0 | 156 |
|
157 |
def shutdown(self): |
|
158 |
pass |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
676
diff
changeset
|
159 |
|
0 | 160 |
def __getattribute__(self, name): |
161 |
try: |
|
162 |
return object.__getattribute__(self, name) |
|
163 |
except AttributeError: |
|
164 |
cmd = 'cmd_%s' % name |
|
165 |
if hasattr(self, cmd): |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
676
diff
changeset
|
166 |
meth = getattr(self, cmd) |
0 | 167 |
return lambda *args, **kwargs: self.interact(args, kwargs, |
168 |
meth=meth) |
|
169 |
raise |
|
170 |
raise AttributeError(name) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
676
diff
changeset
|
171 |
|
0 | 172 |
def interact(self, args, kwargs, meth): |
173 |
"""execute the given method according to user's confirmation""" |
|
174 |
msg = 'execute command: %s(%s) ?' % ( |
|
175 |
meth.__name__[4:], |
|
176 |
', '.join([repr(arg) for arg in args] + |
|
177 |
['%s=%r' % (n,v) for n,v in kwargs.items()])) |
|
178 |
if 'ask_confirm' in kwargs: |
|
179 |
ask_confirm = kwargs.pop('ask_confirm') |
|
180 |
else: |
|
181 |
ask_confirm = True |
|
182 |
if not ask_confirm or self.confirm(msg): |
|
183 |
return meth(*args, **kwargs) |
|
184 |
||
185 |
def confirm(self, question, shell=True, abort=True, retry=False): |
|
186 |
"""ask for confirmation and return true on positive answer |
|
187 |
||
188 |
if `retry` is true the r[etry] answer may return 2 |
|
189 |
""" |
|
190 |
print question, |
|
191 |
possibleanswers = 'Y/n' |
|
192 |
if abort: |
|
193 |
possibleanswers += '/a[bort]' |
|
194 |
if shell: |
|
195 |
possibleanswers += '/s[hell]' |
|
196 |
if retry: |
|
197 |
possibleanswers += '/r[etry]' |
|
198 |
try: |
|
199 |
confirm = raw_input('(%s): ' % ( possibleanswers, )) |
|
200 |
answer = confirm.strip().lower() |
|
201 |
except (EOFError, KeyboardInterrupt): |
|
202 |
answer = 'abort' |
|
203 |
if answer in ('n', 'no'): |
|
204 |
return False |
|
205 |
if answer in ('r', 'retry'): |
|
206 |
return 2 |
|
207 |
if answer in ('a', 'abort'): |
|
208 |
self.rollback() |
|
209 |
raise SystemExit(1) |
|
210 |
if shell and answer in ('s', 'shell'): |
|
211 |
self.interactive_shell() |
|
212 |
return self.confirm(question) |
|
213 |
return True |
|
214 |
||
215 |
def interactive_shell(self): |
|
216 |
self.confirm = yes |
|
217 |
self.need_wrap = False |
|
218 |
# avoid '_' to be added to builtins by sys.display_hook |
|
219 |
def do_not_add___to_builtins(obj): |
|
220 |
if obj is not None: |
|
221 |
print repr(obj) |
|
222 |
sys.displayhook = do_not_add___to_builtins |
|
223 |
local_ctx = self._create_context() |
|
224 |
try: |
|
225 |
import readline |
|
226 |
from rlcompleter import Completer |
|
227 |
except ImportError: |
|
228 |
# readline not available |
|
229 |
pass |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
676
diff
changeset
|
230 |
else: |
0 | 231 |
readline.set_completer(Completer(local_ctx).complete) |
232 |
readline.parse_and_bind('tab: complete') |
|
233 |
histfile = os.path.join(os.environ["HOME"], ".eshellhist") |
|
234 |
try: |
|
235 |
readline.read_history_file(histfile) |
|
236 |
except IOError: |
|
237 |
pass |
|
238 |
from code import interact |
|
239 |
banner = """entering the migration python shell |
|
240 |
just type migration commands or arbitrary python code and type ENTER to execute it |
|
241 |
type "exit" or Ctrl-D to quit the shell and resume operation""" |
|
242 |
# give custom readfunc to avoid http://bugs.python.org/issue1288615 |
|
243 |
def unicode_raw_input(prompt): |
|
244 |
return unicode(raw_input(prompt), sys.stdin.encoding) |
|
245 |
interact(banner, readfunc=unicode_raw_input, local=local_ctx) |
|
246 |
readline.write_history_file(histfile) |
|
247 |
# delete instance's confirm attribute to avoid questions |
|
248 |
del self.confirm |
|
249 |
self.need_wrap = True |
|
250 |
||
251 |
@cached |
|
252 |
def _create_context(self): |
|
253 |
"""return a dictionary to use as migration script execution context""" |
|
254 |
context = self.__context |
|
255 |
for attr in dir(self): |
|
256 |
if attr.startswith('cmd_'): |
|
257 |
if self.need_wrap: |
|
258 |
context[attr[4:]] = getattr(self, attr[4:]) |
|
259 |
else: |
|
260 |
context[attr[4:]] = getattr(self, attr) |
|
261 |
return context |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
676
diff
changeset
|
262 |
|
0 | 263 |
def process_script(self, migrscript, funcname=None, *args, **kwargs): |
264 |
"""execute a migration script |
|
265 |
in interactive mode, display the migration script path, ask for |
|
266 |
confirmation and execute it if confirmed |
|
267 |
""" |
|
268 |
assert migrscript.endswith('.py'), migrscript |
|
269 |
if self.execscript_confirm(migrscript): |
|
270 |
scriptlocals = self._create_context().copy() |
|
271 |
if funcname is None: |
|
272 |
pyname = '__main__' |
|
273 |
else: |
|
274 |
pyname = splitext(basename(migrscript))[0] |
|
275 |
scriptlocals.update({'__file__': migrscript, '__name__': pyname}) |
|
276 |
execfile(migrscript, scriptlocals) |
|
277 |
if funcname is not None: |
|
278 |
try: |
|
279 |
func = scriptlocals[funcname] |
|
280 |
self.info('found %s in locals', funcname) |
|
281 |
assert callable(func), '%s (%s) is not callable' % (func, funcname) |
|
282 |
except KeyError: |
|
283 |
self.critical('no %s in script %s', funcname, migrscript) |
|
284 |
return None |
|
285 |
return func(*args, **kwargs) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
676
diff
changeset
|
286 |
|
0 | 287 |
def scripts_session(self, migrscripts): |
288 |
"""execute some scripts in a transaction""" |
|
289 |
try: |
|
290 |
for migrscript in migrscripts: |
|
291 |
self.process_script(migrscript) |
|
292 |
self.commit() |
|
293 |
except: |
|
294 |
self.rollback() |
|
295 |
raise |
|
296 |
||
297 |
def cmd_option_renamed(self, oldname, newname): |
|
298 |
"""a configuration option has been renamed""" |
|
299 |
self._option_changes.append(('renamed', oldname, newname)) |
|
300 |
||
301 |
def cmd_option_group_change(self, option, oldgroup, newgroup): |
|
302 |
"""a configuration option has been moved in another group""" |
|
303 |
self._option_changes.append(('moved', option, oldgroup, newgroup)) |
|
304 |
||
305 |
def cmd_option_added(self, optname): |
|
306 |
"""a configuration option has been added""" |
|
307 |
self._option_changes.append(('added', optname)) |
|
308 |
||
309 |
def cmd_option_removed(self, optname): |
|
310 |
"""a configuration option has been removed""" |
|
311 |
# can safely be ignored |
|
312 |
#self._option_changes.append(('removed', optname)) |
|
313 |
||
314 |
def cmd_option_type_changed(self, optname, oldtype, newvalue): |
|
315 |
"""a configuration option's type has changed""" |
|
316 |
self._option_changes.append(('typechanged', optname, oldtype, newvalue)) |
|
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
676
diff
changeset
|
317 |
|
676
270eb87a768a
provide a new add_cubes() migration function for cases where the new cubes are linked together by new relations
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
447
diff
changeset
|
318 |
def cmd_add_cubes(self, cubes): |
270eb87a768a
provide a new add_cubes() migration function for cases where the new cubes are linked together by new relations
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
447
diff
changeset
|
319 |
"""modify the list of used cubes in the in-memory config |
270eb87a768a
provide a new add_cubes() migration function for cases where the new cubes are linked together by new relations
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
447
diff
changeset
|
320 |
returns newly inserted cubes, including dependencies |
270eb87a768a
provide a new add_cubes() migration function for cases where the new cubes are linked together by new relations
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
447
diff
changeset
|
321 |
""" |
270eb87a768a
provide a new add_cubes() migration function for cases where the new cubes are linked together by new relations
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
447
diff
changeset
|
322 |
if isinstance(cubes, basestring): |
270eb87a768a
provide a new add_cubes() migration function for cases where the new cubes are linked together by new relations
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
447
diff
changeset
|
323 |
cubes = (cubes,) |
0 | 324 |
origcubes = self.config.cubes() |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
676
diff
changeset
|
325 |
newcubes = [p for p in self.config.expand_cubes(cubes) |
0 | 326 |
if not p in origcubes] |
327 |
if newcubes: |
|
676
270eb87a768a
provide a new add_cubes() migration function for cases where the new cubes are linked together by new relations
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
447
diff
changeset
|
328 |
for cube in cubes: |
270eb87a768a
provide a new add_cubes() migration function for cases where the new cubes are linked together by new relations
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
447
diff
changeset
|
329 |
assert cube in newcubes |
0 | 330 |
self.config.add_cubes(newcubes) |
331 |
return newcubes |
|
332 |
||
2124
5a0b02f37b23
set removedeps to False by default, raise an exception instead of a simple assertion for error, more remove_cube tests
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2122
diff
changeset
|
333 |
def cmd_remove_cube(self, cube, removedeps=False): |
2122
4ea13a828513
add removedeps option to remove_cube to control wether a cube's dependencies should be removed as well or not
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
334 |
if removedeps: |
4ea13a828513
add removedeps option to remove_cube to control wether a cube's dependencies should be removed as well or not
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
335 |
toremove = self.config.expand_cubes([cube]) |
4ea13a828513
add removedeps option to remove_cube to control wether a cube's dependencies should be removed as well or not
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
336 |
else: |
4ea13a828513
add removedeps option to remove_cube to control wether a cube's dependencies should be removed as well or not
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
337 |
toremove = (cube,) |
0 | 338 |
origcubes = self.config._cubes |
2122
4ea13a828513
add removedeps option to remove_cube to control wether a cube's dependencies should be removed as well or not
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
1977
diff
changeset
|
339 |
basecubes = [c for c in origcubes if not c in toremove] |
0 | 340 |
self.config._cubes = tuple(self.config.expand_cubes(basecubes)) |
341 |
removed = [p for p in origcubes if not p in self.config._cubes] |
|
2124
5a0b02f37b23
set removedeps to False by default, raise an exception instead of a simple assertion for error, more remove_cube tests
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2122
diff
changeset
|
342 |
if not cube in removed: |
5a0b02f37b23
set removedeps to False by default, raise an exception instead of a simple assertion for error, more remove_cube tests
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2122
diff
changeset
|
343 |
raise ConfigurationError("can't remove cube %s, " |
5a0b02f37b23
set removedeps to False by default, raise an exception instead of a simple assertion for error, more remove_cube tests
Sylvain Thénault <sylvain.thenault@logilab.fr>
parents:
2122
diff
changeset
|
344 |
"used as a dependency" % cube) |
0 | 345 |
return removed |
1802
d628defebc17
delete-trailing-whitespace + some copyright update
Adrien Di Mascio <Adrien.DiMascio@logilab.fr>
parents:
676
diff
changeset
|
346 |
|
0 | 347 |
def rewrite_configuration(self): |
348 |
# import locally, show_diffs unavailable in gae environment |
|
349 |
from cubicweb.toolsutils import show_diffs |
|
350 |
configfile = self.config.main_config_file() |
|
351 |
if self._option_changes: |
|
352 |
read_old_config(self.config, self._option_changes, configfile) |
|
353 |
newconfig = mktemp() |
|
354 |
for optdescr in self._option_changes: |
|
355 |
if optdescr[0] == 'added': |
|
356 |
optdict = self.config.get_option_def(optdescr[1]) |
|
357 |
if optdict.get('default') is REQUIRED: |
|
447 | 358 |
self.config.input_option(optdescr[1], optdict) |
0 | 359 |
self.config.generate_config(open(newconfig, 'w')) |
360 |
show_diffs(configfile, newconfig) |
|
361 |
if exists(newconfig): |
|
362 |
os.unlink(newconfig) |
|
363 |
||
364 |
||
365 |
from logging import getLogger |
|
366 |
from cubicweb import set_log_methods |
|
367 |
set_log_methods(MigrationHelper, getLogger('cubicweb.migration')) |