| 1 |
#!/usr/bin/env python3 |
| 2 |
|
| 3 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 4 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 5 |
# |
| 6 |
# This program is free software: you can redistribute it and/or modify |
| 7 |
# it under the terms of the GNU General Public License as published by |
| 8 |
# the Free Software Foundation, either version 3 of the License, or |
| 9 |
# (at your option) any later version. |
| 10 |
# |
| 11 |
# This program is distributed in the hope that it will be useful, |
| 12 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 14 |
# GNU General Public License for more details. |
| 15 |
# |
| 16 |
# You should have received a copy of the GNU General Public License |
| 17 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 18 |
|
| 19 |
"""cylc reinstall [OPTIONS] ARGS |
| 20 |
|
| 21 |
Reinstall a previously installed workflow. |
| 22 |
|
| 23 |
Examples: |
| 24 |
# Having previously installed: |
| 25 |
$ cylc install myflow |
| 26 |
|
| 27 |
# To reinstall the latest run: |
| 28 |
$ cylc reinstall myflow |
| 29 |
|
| 30 |
# Or, to reinstall a specific run: |
| 31 |
$ cylc reinstall myflow/run2 |
| 32 |
|
| 33 |
# If the workflow is running: |
| 34 |
$ cylc reinstall myflow # reinstall as usual |
| 35 |
$ cylc reload myflow # pick up changes in the workflow config |
| 36 |
|
| 37 |
What reinstall does: |
| 38 |
Reinstall synchronises files between the workflow source and the specified |
| 39 |
run directory. |
| 40 |
|
| 41 |
Any files which have been added, updated or removed in the source directory |
| 42 |
will be added, updated or removed in the run directory. Cylc uses "rsync" |
| 43 |
to do this (run in "--debug" mode to see the exact command used). |
| 44 |
|
| 45 |
How changes are displayed: |
| 46 |
Reinstall will first perform a dry run showing the files it would change. |
| 47 |
This is displayed in "rsync" format e.g: |
| 48 |
|
| 49 |
<g>send foo</g> # this means the file "foo" would be added/updated |
| 50 |
<r>del. bar</r> # this means the file "bar" would be deleted |
| 51 |
|
| 52 |
How to prevent reinstall deleting files: |
| 53 |
Reinstall will delete any files which are not present in the source directory |
| 54 |
(i.e. if you delete a file from the source directory, a reinstall would |
| 55 |
remove the file from the run directory too). The "work/" and "share/" |
| 56 |
directory are excluded from this. These are the recommended locations for any |
| 57 |
files created at runtime. |
| 58 |
|
| 59 |
You can extend the list of "excluded" paths by creating a ".cylcignore" file. |
| 60 |
For example the following file would exclude "data/" and any ".csv" files |
| 61 |
from being overwritten by a reinstallation: |
| 62 |
|
| 63 |
$ cat .cylcignore |
| 64 |
data |
| 65 |
*.csv |
| 66 |
|
| 67 |
Note any paths listed in ".cylcignore" will not be installed by |
| 68 |
"cylc install" even if present in the source directory. |
| 69 |
""" |
| 70 |
|
| 71 |
from functools import partial |
| 72 |
from pathlib import Path |
| 73 |
import re |
| 74 |
import sys |
| 75 |
from typing import ( |
| 76 |
TYPE_CHECKING, |
| 77 |
Callable, |
| 78 |
List, |
| 79 |
Optional, |
| 80 |
) |
| 81 |
|
| 82 |
from ansimarkup import parse as cparse |
| 83 |
|
| 84 |
from cylc.flow.exceptions import ( |
| 85 |
ServiceFileError, |
| 86 |
WorkflowFilesError, |
| 87 |
) |
| 88 |
import cylc.flow.flags |
| 89 |
from cylc.flow.install import reinstall_workflow |
| 90 |
from cylc.flow.network.multi import call_multi |
| 91 |
from cylc.flow.option_parsers import ( |
| 92 |
ID_MULTI_ARG_DOC, |
| 93 |
CylcOptionParser as COP, |
| 94 |
OptionSettings, |
| 95 |
) |
| 96 |
from cylc.flow.pathutil import get_workflow_run_dir |
| 97 |
from cylc.flow.plugins import run_plugins_async |
| 98 |
from cylc.flow.terminal import ( |
| 99 |
DIM, |
| 100 |
cli_function, |
| 101 |
is_terminal, |
| 102 |
) |
| 103 |
from cylc.flow.workflow_files import ( |
| 104 |
get_workflow_source_dir, |
| 105 |
load_contact_file, |
| 106 |
) |
| 107 |
|
| 108 |
|
| 109 |
if TYPE_CHECKING: |
| 110 |
from optparse import Values |
| 111 |
|
| 112 |
_input = input # to enable testing |
| 113 |
|
| 114 |
REINSTALL_CYLC_ROSE_OPTIONS = [ |
| 115 |
OptionSettings( |
| 116 |
['--clear-rose-install-options'], |
| 117 |
help="Clear options previously set by cylc-rose.", |
| 118 |
action='store_true', |
| 119 |
default=False, |
| 120 |
dest="clear_rose_install_opts", |
| 121 |
sources={'reinstall'} |
| 122 |
) |
| 123 |
] |
| 124 |
|
| 125 |
REINSTALL_OPTIONS = [ |
| 126 |
OptionSettings( |
| 127 |
["--yes"], |
| 128 |
help='Skip interactive prompts.', |
| 129 |
action="store_true", |
| 130 |
default=False, |
| 131 |
dest="skip_interactive", |
| 132 |
sources={'reinstall'} |
| 133 |
), |
| 134 |
] |
| 135 |
|
| 136 |
|
| 137 |
def get_option_parser() -> COP: |
| 138 |
parser = COP( |
| 139 |
__doc__, |
| 140 |
comms=True, |
| 141 |
multiworkflow=True, |
| 142 |
argdoc=[ |
| 143 |
ID_MULTI_ARG_DOC, |
| 144 |
], |
| 145 |
) |
| 146 |
|
| 147 |
try: |
| 148 |
# If cylc-rose plugin is available |
| 149 |
__import__('cylc.rose') |
| 150 |
except ImportError: |
| 151 |
options = REINSTALL_OPTIONS |
| 152 |
else: |
| 153 |
parser.add_cylc_rose_options() |
| 154 |
options = REINSTALL_CYLC_ROSE_OPTIONS + REINSTALL_OPTIONS |
| 155 |
|
| 156 |
for option in options: |
| 157 |
parser.add_option(*option.args, **option.kwargs) |
| 158 |
|
| 159 |
return parser |
| 160 |
|
| 161 |
|
| 162 |
@cli_function(get_option_parser) |
| 163 |
def main( |
| 164 |
_parser: COP, |
| 165 |
opts: 'Values', |
| 166 |
*ids: str |
| 167 |
) -> None: |
| 168 |
"""CLI wrapper.""" |
| 169 |
rets = call_multi( |
| 170 |
partial(reinstall_cli, opts), |
| 171 |
*ids, |
| 172 |
constraint='workflows', |
| 173 |
report=lambda x: ('<green>Done</green>', None, True), |
| 174 |
) |
| 175 |
sys.exit(all(rets.values()) is False) |
| 176 |
|
| 177 |
|
| 178 |
async def reinstall_cli( |
| 179 |
opts: 'Values', |
| 180 |
workflow_id, |
| 181 |
*tokens_list, |
| 182 |
print_reload_tip: bool = True |
| 183 |
) -> bool: |
| 184 |
"""Implement cylc reinstall. |
| 185 |
|
| 186 |
This is the bit which contains all the CLI logic. |
| 187 |
""" |
| 188 |
run_dir: Optional[Path] |
| 189 |
run_dir = Path(get_workflow_run_dir(workflow_id)) |
| 190 |
if not run_dir.is_dir(): |
| 191 |
raise WorkflowFilesError( |
| 192 |
f'"{workflow_id}" is not an installed workflow.') |
| 193 |
source, source_symlink = get_workflow_source_dir(run_dir) |
| 194 |
if not source: |
| 195 |
raise WorkflowFilesError( |
| 196 |
f'"{workflow_id}" was not installed with cylc install.') |
| 197 |
source_: Path = Path(source) |
| 198 |
if not source_.is_dir(): |
| 199 |
raise WorkflowFilesError( |
| 200 |
f'Workflow source dir is not accessible: "{source_}".\n' |
| 201 |
f'Restore the source or modify the "{source_symlink}"' |
| 202 |
' symlink to continue.' |
| 203 |
) |
| 204 |
|
| 205 |
usr: str = '' |
| 206 |
try: |
| 207 |
if is_terminal() and not opts.skip_interactive: |
| 208 |
# interactive mode - perform dry-run and prompt |
| 209 |
# dry-mode reinstall |
| 210 |
if not await reinstall( |
| 211 |
opts, |
| 212 |
workflow_id, |
| 213 |
source_, |
| 214 |
run_dir, |
| 215 |
dry_run=True, |
| 216 |
): |
| 217 |
# no rsync output == no changes => exit |
| 218 |
print(cparse( |
| 219 |
'<magenta>' |
| 220 |
'No changes made:' |
| 221 |
f' {workflow_id} is up to date with {source_}' |
| 222 |
'</magenta>' |
| 223 |
)) |
| 224 |
return False |
| 225 |
|
| 226 |
display_rose_warning(source_) |
| 227 |
display_cylcignore_tip() |
| 228 |
# prompt for permission to continue |
| 229 |
while usr not in ['y', 'n']: |
| 230 |
usr = _input( |
| 231 |
cparse('<bold>Continue [y/n]: </bold>') |
| 232 |
).lower() |
| 233 |
|
| 234 |
else: # non interactive-mode - no dry-run, no prompt |
| 235 |
usr = 'y' |
| 236 |
|
| 237 |
except KeyboardInterrupt: |
| 238 |
# ensure the "reinstall canceled" message shows for ctrl+c |
| 239 |
usr = 'n' # cancel the reinstall |
| 240 |
print() # clear the traceback line |
| 241 |
|
| 242 |
if usr == 'y': |
| 243 |
# reinstall for real |
| 244 |
await reinstall(opts, workflow_id, source_, run_dir, dry_run=False) |
| 245 |
print(cparse('<green>Successfully reinstalled.</green>')) |
| 246 |
if print_reload_tip: |
| 247 |
display_cylc_reload_tip(workflow_id) |
| 248 |
return True |
| 249 |
|
| 250 |
else: |
| 251 |
# no reinstall |
| 252 |
print( |
| 253 |
cparse('<magenta>No changes made: reinstall cancelled.</magenta>') |
| 254 |
) |
| 255 |
return False |
| 256 |
|
| 257 |
|
| 258 |
async def reinstall( |
| 259 |
opts: 'Values', |
| 260 |
workflow_id: str, |
| 261 |
src_dir: Path, |
| 262 |
run_dir: Path, |
| 263 |
dry_run: bool = False, |
| 264 |
write: Callable = print, |
| 265 |
) -> bool: |
| 266 |
"""Perform reinstallation. |
| 267 |
|
| 268 |
This is the purely functional bit without the CLI logic. |
| 269 |
|
| 270 |
Args: |
| 271 |
opts: CLI options. |
| 272 |
workflow_id: Workflow ID as a string. |
| 273 |
src_dir: Workflow source directory path. |
| 274 |
run_dir: Installed workflow run directory path. |
| 275 |
dry_run: If True perform a "dry run" which doesn't change anything. |
| 276 |
write: Used to display dry_run output. |
| 277 |
|
| 278 |
Returns: |
| 279 |
reinstall_needed - In dry_run mode returns False if rsync *would* |
| 280 |
update anything, else returns True. |
| 281 |
|
| 282 |
""" |
| 283 |
if not dry_run: |
| 284 |
# run pre_configure plugins |
| 285 |
async for _entry_point, _plugin_result in run_plugins_async( |
| 286 |
'cylc.pre_configure', |
| 287 |
srcdir=src_dir, |
| 288 |
opts=opts, |
| 289 |
): |
| 290 |
pass |
| 291 |
|
| 292 |
# reinstall from src_dir (will raise WorkflowFilesError on error) |
| 293 |
stdout: str = reinstall_workflow( |
| 294 |
source=src_dir, |
| 295 |
named_run=workflow_id, |
| 296 |
rundir=run_dir, |
| 297 |
dry_run=dry_run, |
| 298 |
) |
| 299 |
|
| 300 |
if dry_run: |
| 301 |
# display changes |
| 302 |
changes = format_reinstall_output(stdout) |
| 303 |
if not changes: |
| 304 |
return False |
| 305 |
|
| 306 |
# display rsync output |
| 307 |
write('\n'.join(changes), file=sys.stdout) |
| 308 |
|
| 309 |
if not dry_run: |
| 310 |
# run post_install plugins |
| 311 |
async for _entry_point, _plugin_result in run_plugins_async( |
| 312 |
'cylc.post_install', |
| 313 |
srcdir=src_dir, |
| 314 |
opts=opts, |
| 315 |
rundir=str(run_dir), |
| 316 |
async_block=True, |
| 317 |
): |
| 318 |
pass |
| 319 |
|
| 320 |
return True |
| 321 |
|
| 322 |
|
| 323 |
def format_reinstall_output(out: str) -> List[str]: |
| 324 |
r"""Format rsync stdout for presenting to users. |
| 325 |
|
| 326 |
Note: Output formats of different rsync implementations may differ so keep |
| 327 |
this code simple and robust. |
| 328 |
|
| 329 |
Example: |
| 330 |
>>> format_reinstall_output( |
| 331 |
... '>f+++++++++ send foo\n*deleting del. bar\nbaz' |
| 332 |
... '\ncannot delete non-empty directory: opt' |
| 333 |
... ) == [ |
| 334 |
... cparse('<green>send foo</green>'), |
| 335 |
... cparse('<red>del. bar</red>'), |
| 336 |
... 'baz', |
| 337 |
... ] |
| 338 |
True |
| 339 |
|
| 340 |
""" |
| 341 |
lines = [] |
| 342 |
for line in out.splitlines(): |
| 343 |
if not line or line.startswith('cannot delete non-empty directory:'): |
| 344 |
# This can arise as a result of deleting a subdir when we are |
| 345 |
# excluding files within the subdir. |
| 346 |
# This is likely to occur for the opt dir when a rose-suite.conf |
| 347 |
# file is present. |
| 348 |
# Skip this line as nothing will happen to this dir. |
| 349 |
continue |
| 350 |
match = re.match(r'^(.{11}) (send|del\.|recv) (.*)$', line) |
| 351 |
# (On some systems, may get "recv" instead of "send") |
| 352 |
if match: |
| 353 |
summary, operation, file = match.groups() |
| 354 |
color = 'green' if operation == 'send' else 'red' |
| 355 |
formatted_line = f"<{color}>{operation} {file}</{color}>" |
| 356 |
if cylc.flow.flags.verbosity > 0: |
| 357 |
formatted_line = f"<{DIM}>{summary}</{DIM}> {formatted_line}" |
| 358 |
lines.append(cparse(formatted_line)) |
| 359 |
else: |
| 360 |
# tolerate unknown output from different rsync implementations |
| 361 |
lines.append(line) |
| 362 |
return lines |
| 363 |
|
| 364 |
|
| 365 |
def display_rose_warning(src_dir: Path) -> None: |
| 366 |
"""Explain why rose installed files are marked as deleted.""" |
| 367 |
if (src_dir / 'rose-suite.conf').is_file(): |
| 368 |
# TODO: remove this in combination with |
| 369 |
# https://github.com/cylc/cylc-rose/issues/149 |
| 370 |
print( |
| 371 |
cparse( |
| 372 |
f'\n<{DIM}>' |
| 373 |
'NOTE: Files created by Rose file installation will show' |
| 374 |
' as deleted.' |
| 375 |
'\n They will be re-created during the reinstall' |
| 376 |
' process.' |
| 377 |
f'</{DIM}>', |
| 378 |
), |
| 379 |
file=sys.stderr, |
| 380 |
) |
| 381 |
|
| 382 |
|
| 383 |
def display_cylcignore_tip(): |
| 384 |
print( |
| 385 |
cparse( |
| 386 |
f'\n<{DIM}>TIP: You can "exclude" files/dirs to prevent' |
| 387 |
' Cylc from installing or overwriting\n them by adding' |
| 388 |
' them to the .cylcignore file. See cylc reinstall --help.' |
| 389 |
f'</{DIM}>\n' |
| 390 |
'\n<bold>Reinstall would make the above changes.</bold>' |
| 391 |
) |
| 392 |
) |
| 393 |
|
| 394 |
|
| 395 |
def display_cylc_reload_tip(workflow_id: str) -> None: |
| 396 |
"""Recommend use of "cylc reload" if applicable. |
| 397 |
|
| 398 |
Uses a quick and simple way to tell if a workflow is running. |
| 399 |
|
| 400 |
It would be better to "ping" the workflow, however, this is sufficient |
| 401 |
for our purposes. |
| 402 |
""" |
| 403 |
try: |
| 404 |
load_contact_file(workflow_id) |
| 405 |
except ServiceFileError: |
| 406 |
return |
| 407 |
print(cparse( |
| 408 |
'\n<blue>' |
| 409 |
f'Run "cylc reload {workflow_id}" to pick up changes.' |
| 410 |
'</blue>' |
| 411 |
)) |