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