| 1 |
# THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE. |
| 2 |
# Copyright (C) NIWA & British Crown (Met Office) & Contributors. |
| 3 |
# |
| 4 |
# This program is free software: you can redistribute it and/or modify |
| 5 |
# it under the terms of the GNU General Public License as published by |
| 6 |
# the Free Software Foundation, either version 3 of the License, or |
| 7 |
# (at your option) any later version. |
| 8 |
# |
| 9 |
# This program is distributed in the hope that it will be useful, |
| 10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 12 |
# GNU General Public License for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU General Public License |
| 15 |
# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 16 |
|
| 17 |
"""Functionality for (local) workflow installation.""" |
| 18 |
|
| 19 |
import logging |
| 20 |
import os |
| 21 |
import re |
| 22 |
import shlex |
| 23 |
from contextlib import suppress |
| 24 |
from pathlib import Path |
| 25 |
from subprocess import ( |
| 26 |
PIPE, |
| 27 |
Popen, |
| 28 |
) |
| 29 |
from typing import ( |
| 30 |
Any, |
| 31 |
Dict, |
| 32 |
List, |
| 33 |
Optional, |
| 34 |
Tuple, |
| 35 |
Union, |
| 36 |
) |
| 37 |
|
| 38 |
from cylc.flow import LOG |
| 39 |
from cylc.flow.cfgspec.glbl_cfg import glbl_cfg |
| 40 |
from cylc.flow.exceptions import ( |
| 41 |
InputError, |
| 42 |
WorkflowFilesError, |
| 43 |
) |
| 44 |
from cylc.flow.loggingutil import ( |
| 45 |
CylcLogFormatter, |
| 46 |
close_log, |
| 47 |
get_next_log_number, |
| 48 |
get_sorted_logs_by_time, |
| 49 |
) |
| 50 |
from cylc.flow.pathutil import ( |
| 51 |
expand_path, |
| 52 |
get_cylc_run_dir, |
| 53 |
get_next_rundir_number, |
| 54 |
get_workflow_run_dir, |
| 55 |
make_localhost_symlinks, |
| 56 |
) |
| 57 |
from cylc.flow.remote import ( |
| 58 |
DEFAULT_RSYNC_OPTS, |
| 59 |
) |
| 60 |
from cylc.flow.util import cli_format |
| 61 |
from cylc.flow.workflow_files import ( |
| 62 |
WorkflowFiles, |
| 63 |
abort_if_flow_file_in_path, |
| 64 |
check_deprecation, |
| 65 |
check_flow_file, |
| 66 |
get_cylc_run_abs_path, |
| 67 |
is_valid_run_dir, |
| 68 |
validate_workflow_name, |
| 69 |
) |
| 70 |
|
| 71 |
|
| 72 |
NESTED_DIRS_MSG = ( |
| 73 |
"Nested {dir_type} directories not allowed - cannot install workflow" |
| 74 |
" in '{dest}' as '{existing}' is already a valid {dir_type} directory." |
| 75 |
) |
| 76 |
|
| 77 |
|
| 78 |
def _get_logger(rund, log_name, open_file=True): |
| 79 |
"""Get log and create and open if necessary. |
| 80 |
|
| 81 |
Args: |
| 82 |
rund: |
| 83 |
The workflow run directory of the associated workflow. |
| 84 |
log_name: |
| 85 |
The name of the log to open. |
| 86 |
open_file: |
| 87 |
Open the appropriate log file and add it as a file handler to |
| 88 |
the logger. I.E. Start writing the log to a file if not already |
| 89 |
doing so. |
| 90 |
|
| 91 |
""" |
| 92 |
logger = logging.getLogger(log_name) |
| 93 |
logger.setLevel(logging.INFO) |
| 94 |
if open_file and not logger.hasHandlers(): |
| 95 |
_open_install_log(rund, logger) |
| 96 |
return logger |
| 97 |
|
| 98 |
|
| 99 |
def _open_install_log(rund, logger): |
| 100 |
"""Open Cylc log handlers for install/reinstall.""" |
| 101 |
rund = Path(rund).expanduser() |
| 102 |
log_type = logger.name[logger.name.startswith('cylc-') and len('cylc-'):] |
| 103 |
log_dir = Path( |
| 104 |
rund, WorkflowFiles.LogDir.DIRNAME, WorkflowFiles.LogDir.INSTALL) |
| 105 |
log_files = get_sorted_logs_by_time(log_dir, '*.log') |
| 106 |
log_num = get_next_log_number(log_files[-1]) if log_files else 1 |
| 107 |
log_path = Path(log_dir, f"{log_num:02d}-{log_type}.log") |
| 108 |
log_parent_dir = log_path.parent |
| 109 |
log_parent_dir.mkdir(exist_ok=True, parents=True) |
| 110 |
handler = logging.FileHandler(log_path) |
| 111 |
handler.setFormatter(CylcLogFormatter()) |
| 112 |
logger.addHandler(handler) |
| 113 |
|
| 114 |
|
| 115 |
def get_rsync_rund_cmd(src, dst, reinstall=False, dry_run=False): |
| 116 |
"""Create and return the rsync command used for cylc install/re-install. |
| 117 |
|
| 118 |
Args: |
| 119 |
src (str): |
| 120 |
file path location of source directory |
| 121 |
dst (str): |
| 122 |
file path location of destination directory |
| 123 |
reinstall (bool): |
| 124 |
indicate reinstall (--delete option added) |
| 125 |
dry-run (bool): |
| 126 |
indicate dry-run, rsync will not take place but report output if a |
| 127 |
real run were to be executed |
| 128 |
|
| 129 |
Return: |
| 130 |
list: command to use for rsync. |
| 131 |
|
| 132 |
""" |
| 133 |
rsync_cmd = shlex.split( |
| 134 |
glbl_cfg().get(['platforms', 'localhost', 'rsync command']) |
| 135 |
) |
| 136 |
rsync_cmd += DEFAULT_RSYNC_OPTS |
| 137 |
if dry_run: |
| 138 |
rsync_cmd.append("--dry-run") |
| 139 |
if reinstall: |
| 140 |
rsync_cmd.append('--delete') |
| 141 |
|
| 142 |
exclusions = [ |
| 143 |
'.git', |
| 144 |
'.svn', |
| 145 |
'.cylcignore', |
| 146 |
'opt/rose-suite-cylc-install.conf', |
| 147 |
WorkflowFiles.LogDir.DIRNAME, |
| 148 |
WorkflowFiles.WORK_DIR, |
| 149 |
WorkflowFiles.SHARE_DIR, |
| 150 |
WorkflowFiles.Install.DIRNAME, |
| 151 |
WorkflowFiles.Service.DIRNAME |
| 152 |
] |
| 153 |
|
| 154 |
# This is a hack to make sure that changes to rose-suite.conf |
| 155 |
# are considered when re-installing. |
| 156 |
# It should be removed after https://github.com/cylc/cylc-rose/issues/149 |
| 157 |
if not dry_run: |
| 158 |
exclusions.append('rose-suite.conf') |
| 159 |
|
| 160 |
for exclude in exclusions: |
| 161 |
if ( |
| 162 |
Path(src).joinpath(exclude).exists() or |
| 163 |
Path(dst).joinpath(exclude).exists() |
| 164 |
): |
| 165 |
# Note '/' is the rsync "anchor" to the top level: |
| 166 |
rsync_cmd.append(f"--exclude=/{exclude}") |
| 167 |
cylcignore_file = Path(src).joinpath('.cylcignore') |
| 168 |
if cylcignore_file.exists(): |
| 169 |
rsync_cmd.append(f"--exclude-from={cylcignore_file}") |
| 170 |
rsync_cmd.append(f"{src}/") |
| 171 |
rsync_cmd.append(f"{dst}/") |
| 172 |
|
| 173 |
return rsync_cmd |
| 174 |
|
| 175 |
|
| 176 |
def reinstall_workflow( |
| 177 |
source: Path, |
| 178 |
named_run: str, |
| 179 |
rundir: Path, |
| 180 |
dry_run: bool = False |
| 181 |
) -> str: |
| 182 |
"""Reinstall workflow. |
| 183 |
|
| 184 |
Args: |
| 185 |
source: source directory |
| 186 |
named_run: name of the run e.g. my-flow/run1 |
| 187 |
rundir: run directory |
| 188 |
dry_run: if True, will not execute the file transfer but report what |
| 189 |
would be changed. |
| 190 |
|
| 191 |
Raises: |
| 192 |
WorkflowFilesError: |
| 193 |
If rsync returns non-zero. |
| 194 |
|
| 195 |
Returns: |
| 196 |
Stdout from the rsync command. |
| 197 |
|
| 198 |
""" |
| 199 |
validate_source_dir(source, named_run) |
| 200 |
check_nested_dirs(rundir) |
| 201 |
reinstall_log = _get_logger( |
| 202 |
rundir, |
| 203 |
'cylc-reinstall', |
| 204 |
open_file=not dry_run, # don't open the log file for --dry-run |
| 205 |
) |
| 206 |
reinstall_log.info( |
| 207 |
f'Reinstalling "{named_run}", from "{source}" to "{rundir}"' |
| 208 |
) |
| 209 |
rsync_cmd = get_rsync_rund_cmd( |
| 210 |
source, |
| 211 |
rundir, |
| 212 |
reinstall=True, |
| 213 |
dry_run=dry_run, |
| 214 |
) |
| 215 |
|
| 216 |
rsync_cmd.append('--out-format=%i %o %n%L') |
| 217 |
# %i: itemized changes - needed for rsync to report files with |
| 218 |
# changed permissions |
| 219 |
|
| 220 |
# Run rsync command: |
| 221 |
reinstall_log.info(cli_format(rsync_cmd)) |
| 222 |
LOG.debug(cli_format(rsync_cmd)) |
| 223 |
proc = Popen(rsync_cmd, stdout=PIPE, stderr=PIPE, text=True) # nosec |
| 224 |
# * command is constructed via internal interface |
| 225 |
stdout, stderr = (i.strip() for i in proc.communicate()) |
| 226 |
|
| 227 |
reinstall_log.info( |
| 228 |
f"Copying files from {source} to {rundir}" |
| 229 |
f"\n{stdout}" |
| 230 |
) |
| 231 |
if proc.returncode != 0: |
| 232 |
raise WorkflowFilesError( |
| 233 |
f'An error occurred reinstalling from {source} to {rundir}' |
| 234 |
f'\n{stderr}' |
| 235 |
) |
| 236 |
|
| 237 |
check_flow_file(rundir) |
| 238 |
reinstall_log.info(f'REINSTALLED {named_run} from {source}') |
| 239 |
print( |
| 240 |
f'REINSTALL{"ED" if not dry_run else ""} {named_run} from {source}' |
| 241 |
) |
| 242 |
close_log(reinstall_log) |
| 243 |
return stdout |
| 244 |
|
| 245 |
|
| 246 |
def install_workflow( |
| 247 |
source: Path, |
| 248 |
workflow_name: Optional[str] = None, |
| 249 |
run_name: Optional[str] = None, |
| 250 |
no_run_name: bool = False, |
| 251 |
cli_symlink_dirs: Optional[Dict[str, Dict[str, Any]]] = None |
| 252 |
) -> Tuple[Path, Path, str, str]: |
| 253 |
"""Install a workflow, or renew its installation. |
| 254 |
|
| 255 |
Install workflow into new run directory. |
| 256 |
Create symlink to workflow source location, creating any symlinks for run, |
| 257 |
work, log, share, share/cycle directories. |
| 258 |
|
| 259 |
Args: |
| 260 |
source: absolute path to workflow source directory. |
| 261 |
workflow_name: workflow name, default basename($PWD). |
| 262 |
run_name: name of the run, overrides run1, run2, run 3 etc... |
| 263 |
If specified, cylc install will not create runN symlink. |
| 264 |
rundir: for overriding the default cylc-run directory. |
| 265 |
no_run_name: Flag as True to install workflow into |
| 266 |
~/cylc-run/<workflow_name> |
| 267 |
cli_symlink_dirs: Symlink dirs, if entered on the cli. |
| 268 |
|
| 269 |
Return: |
| 270 |
source: absolute path to source directory. |
| 271 |
rundir: absolute path to run directory, where the workflow has been |
| 272 |
installed into. |
| 273 |
workflow_name: installed workflow name (which may be computed here). |
| 274 |
named_run: Name of the run. |
| 275 |
|
| 276 |
Raise: |
| 277 |
WorkflowFilesError: |
| 278 |
No flow.cylc file found in source location. |
| 279 |
Illegal name (can look like a relative path, but not absolute). |
| 280 |
Another workflow already has this name. |
| 281 |
Trying to install a workflow that is nested inside of another. |
| 282 |
""" |
| 283 |
abort_if_flow_file_in_path(source) |
| 284 |
source = Path(expand_path(source)).resolve() |
| 285 |
if not workflow_name: |
| 286 |
workflow_name = get_source_workflow_name(source) |
| 287 |
if run_name is not None: |
| 288 |
if len(Path(run_name).parts) != 1: |
| 289 |
raise WorkflowFilesError( |
| 290 |
f'Run name cannot be a path. (You used {run_name})' |
| 291 |
) |
| 292 |
validate_workflow_name( |
| 293 |
os.path.join(workflow_name, run_name), |
| 294 |
check_reserved_names=True |
| 295 |
) |
| 296 |
else: |
| 297 |
validate_workflow_name(workflow_name, check_reserved_names=True) |
| 298 |
validate_source_dir(source, workflow_name) |
| 299 |
run_path_base = Path(get_workflow_run_dir(workflow_name)) |
| 300 |
relink, run_num, rundir = get_run_dir_info( |
| 301 |
run_path_base, run_name, no_run_name |
| 302 |
) |
| 303 |
max_scan_depth = glbl_cfg().get(['install', 'max depth']) |
| 304 |
workflow_id = rundir.relative_to(get_cylc_run_dir()) |
| 305 |
if len(workflow_id.parts) > max_scan_depth: |
| 306 |
raise WorkflowFilesError( |
| 307 |
f"Cannot install: workflow ID '{workflow_id}' would exceed " |
| 308 |
f"global.cylc[install]max depth = {max_scan_depth}" |
| 309 |
) |
| 310 |
check_nested_dirs(rundir, run_path_base) |
| 311 |
if rundir.exists(): |
| 312 |
raise WorkflowFilesError( |
| 313 |
f"'{rundir}' already exists\n" |
| 314 |
"To reinstall, use `cylc reinstall`" |
| 315 |
) |
| 316 |
symlinks_created = {} |
| 317 |
named_run = workflow_name |
| 318 |
if run_name: |
| 319 |
named_run = os.path.join(named_run, run_name) |
| 320 |
elif run_num: |
| 321 |
named_run = os.path.join(named_run, f'run{run_num}') |
| 322 |
symlinks_created = make_localhost_symlinks( |
| 323 |
rundir, named_run, symlink_conf=cli_symlink_dirs) |
| 324 |
install_log = _get_logger(rundir, 'cylc-install') |
| 325 |
if symlinks_created: |
| 326 |
for target, symlink in symlinks_created.items(): |
| 327 |
install_log.info(f"Symlink created: {symlink} -> {target}") |
| 328 |
try: |
| 329 |
rundir.mkdir(exist_ok=True, parents=True) |
| 330 |
except FileExistsError: |
| 331 |
# This occurs when the file exists but is _not_ a directory. |
| 332 |
raise WorkflowFilesError( |
| 333 |
f"Cannot install as there is an existing file at {rundir}." |
| 334 |
) from None |
| 335 |
if relink: |
| 336 |
link_runN(rundir) |
| 337 |
rsync_cmd = get_rsync_rund_cmd(source, rundir) |
| 338 |
proc = Popen(rsync_cmd, stdout=PIPE, stderr=PIPE, text=True) # nosec |
| 339 |
# * command is constructed via internal interface |
| 340 |
stdout, stderr = proc.communicate() |
| 341 |
install_log.info( |
| 342 |
f"Copying files from {source} to {rundir}" |
| 343 |
f"\n{stdout}" |
| 344 |
) |
| 345 |
if proc.returncode != 0: |
| 346 |
install_log.warning( |
| 347 |
f"An error occurred when copying files from {source} to {rundir}") |
| 348 |
install_log.warning(f" Warning: {stderr}") |
| 349 |
cylc_install = Path(rundir.parent, WorkflowFiles.Install.DIRNAME) |
| 350 |
check_deprecation(check_flow_file(rundir)) |
| 351 |
if no_run_name: |
| 352 |
cylc_install = Path(rundir, WorkflowFiles.Install.DIRNAME) |
| 353 |
source_link = cylc_install.joinpath(WorkflowFiles.Install.SOURCE) |
| 354 |
# check source link matches the source symlink from workflow dir. |
| 355 |
cylc_install.mkdir(parents=True, exist_ok=True) |
| 356 |
if not source_link.exists(): |
| 357 |
if source_link.is_symlink(): |
| 358 |
# Condition represents a broken symlink. |
| 359 |
raise WorkflowFilesError( |
| 360 |
f'Symlink broken: {source_link} -> {source_link.resolve()}.' |
| 361 |
) |
| 362 |
install_log.info(f"Creating symlink from {source_link}") |
| 363 |
source_link.symlink_to(source.resolve()) |
| 364 |
else: |
| 365 |
if source_link.resolve() != source.resolve(): |
| 366 |
raise WorkflowFilesError( |
| 367 |
f"Failed to install from {source.resolve()}: " |
| 368 |
f"previous installations were from {source_link.resolve()}" |
| 369 |
) |
| 370 |
install_log.info( |
| 371 |
f'Symlink from "{source_link}" to "{source}" in place.') |
| 372 |
install_log.info(f'INSTALLED {named_run} from {source}') |
| 373 |
close_log(install_log) |
| 374 |
return source, rundir, workflow_name, named_run |
| 375 |
|
| 376 |
|
| 377 |
def get_run_dir_info( |
| 378 |
run_path_base: Path, run_name: Optional[str], no_run_name: bool |
| 379 |
) -> Tuple[bool, Optional[int], Path]: |
| 380 |
"""Get (numbered, named or unnamed) run directory info for current install. |
| 381 |
|
| 382 |
Args: |
| 383 |
run_path_base: The workflow directory absolute path. |
| 384 |
run_name: Name of the run. |
| 385 |
no_run_name: Flag as True to indicate no run name - workflow installed |
| 386 |
into ~/cylc-run/<run_path_base>. |
| 387 |
|
| 388 |
Returns: |
| 389 |
relink: True if runN symlink needs updating. |
| 390 |
run_num: Run number of the current install, if using numbered runs. |
| 391 |
rundir: Run directory absolute path. |
| 392 |
""" |
| 393 |
relink = False |
| 394 |
run_num = None |
| 395 |
if no_run_name: |
| 396 |
rundir = run_path_base |
| 397 |
elif run_name: |
| 398 |
rundir = run_path_base.joinpath(run_name) |
| 399 |
if run_path_base.exists() and detect_flow_exists(run_path_base, True): |
| 400 |
raise WorkflowFilesError( |
| 401 |
f"--run-name option not allowed as '{run_path_base}' contains " |
| 402 |
"installed numbered runs." |
| 403 |
) |
| 404 |
else: |
| 405 |
run_num = get_next_rundir_number(run_path_base) |
| 406 |
rundir = Path(run_path_base, f'run{run_num}') |
| 407 |
if run_path_base.exists() and detect_flow_exists(run_path_base, False): |
| 408 |
raise WorkflowFilesError( |
| 409 |
f"Path: \"{run_path_base}\" contains an installed" |
| 410 |
" workflow. Use --run-name to create a new run." |
| 411 |
) |
| 412 |
unlink_runN(run_path_base) |
| 413 |
relink = True |
| 414 |
return relink, run_num, rundir |
| 415 |
|
| 416 |
|
| 417 |
def get_source_dirs() -> List[str]: |
| 418 |
return glbl_cfg().get(['install', 'source dirs']) |
| 419 |
|
| 420 |
|
| 421 |
def search_install_source_dirs(workflow_name: Union[Path, str]) -> Path: |
| 422 |
"""Return the path of a workflow source dir if it is present in the |
| 423 |
'global.cylc[install]source dirs' search path.""" |
| 424 |
abort_if_flow_file_in_path(Path(workflow_name)) |
| 425 |
search_path: List[str] = get_source_dirs() |
| 426 |
if not search_path: |
| 427 |
raise WorkflowFilesError( |
| 428 |
"Cannot find workflow as 'global.cylc[install]source dirs' " |
| 429 |
"does not contain any paths") |
| 430 |
for path in search_path: |
| 431 |
try: |
| 432 |
return check_flow_file(Path(path, workflow_name)).parent |
| 433 |
except WorkflowFilesError: |
| 434 |
continue |
| 435 |
raise WorkflowFilesError( |
| 436 |
f"Could not find workflow '{workflow_name}' in: " |
| 437 |
f"{', '.join(search_path)}") |
| 438 |
|
| 439 |
|
| 440 |
def get_source_workflow_name(source: Path) -> str: |
| 441 |
"""Return workflow name relative to configured source dirs if possible, |
| 442 |
else the basename of the given path. |
| 443 |
Note the source path provided should be fully expanded (user and env vars) |
| 444 |
and normalised. |
| 445 |
""" |
| 446 |
for dir_ in get_source_dirs(): |
| 447 |
try: |
| 448 |
return str(source.relative_to(Path(expand_path(dir_)).resolve())) |
| 449 |
except ValueError: |
| 450 |
continue |
| 451 |
return source.name |
| 452 |
|
| 453 |
|
| 454 |
def unlink_runN(path: Union[Path, str]) -> bool: |
| 455 |
"""Remove symlink runN if it exists. |
| 456 |
|
| 457 |
Args: |
| 458 |
path: Absolute path to workflow dir containing runN. |
| 459 |
""" |
| 460 |
try: |
| 461 |
Path(expand_path(path, WorkflowFiles.RUN_N)).unlink() |
| 462 |
except OSError: |
| 463 |
return False |
| 464 |
return True |
| 465 |
|
| 466 |
|
| 467 |
def link_runN(latest_run: Union[Path, str]): |
| 468 |
"""Create symlink runN, pointing at the latest run""" |
| 469 |
latest_run = Path(latest_run) |
| 470 |
run_n = Path(latest_run.parent, WorkflowFiles.RUN_N) |
| 471 |
with suppress(OSError): |
| 472 |
run_n.symlink_to(latest_run.name) |
| 473 |
|
| 474 |
|
| 475 |
def validate_source_dir( |
| 476 |
source: Union[Path, str], workflow_name: str |
| 477 |
) -> None: |
| 478 |
"""Ensure the source directory is valid: |
| 479 |
- has flow file |
| 480 |
- does not contain reserved dir names |
| 481 |
|
| 482 |
Args: |
| 483 |
source: Path to source directory |
| 484 |
Raises: |
| 485 |
WorkflowFilesError: |
| 486 |
If log, share, work or _cylc-install directories exist in the |
| 487 |
source directory. |
| 488 |
""" |
| 489 |
# Source dir must not contain reserved run dir names (as file or dir). |
| 490 |
for dir_ in WorkflowFiles.RESERVED_DIRNAMES: |
| 491 |
if Path(source, dir_).exists(): |
| 492 |
raise WorkflowFilesError( |
| 493 |
f"{workflow_name} installation failed " |
| 494 |
f"- {dir_} exists in source directory." |
| 495 |
) |
| 496 |
check_flow_file(source) |
| 497 |
|
| 498 |
|
| 499 |
def parse_cli_sym_dirs(symlink_dirs: str) -> Dict[str, Dict[str, Any]]: |
| 500 |
"""Converts command line entered symlink dirs to a dictionary. |
| 501 |
|
| 502 |
Args: |
| 503 |
symlink_dirs: As entered by user on cli, |
| 504 |
e.g. "log=$DIR, share=$DIR2". |
| 505 |
|
| 506 |
Raises: |
| 507 |
WorkflowFilesError: If directory to be symlinked is not in permitted |
| 508 |
dirs: run, log, share, work, share/cycle |
| 509 |
|
| 510 |
Returns: |
| 511 |
dict: In the same form as would be returned by global config. |
| 512 |
e.g. {'localhost': {'log': '$DIR', |
| 513 |
'share': '$DIR2' |
| 514 |
} |
| 515 |
} |
| 516 |
""" |
| 517 |
# Ensures the same nested dict format which is returned by the glb cfg |
| 518 |
symdict: Dict[str, Dict[str, Any]] = {'localhost': {'run': None}} |
| 519 |
if symlink_dirs == "": |
| 520 |
return symdict |
| 521 |
symlist = symlink_dirs.strip(',').split(',') |
| 522 |
possible_symlink_dirs = set(WorkflowFiles.SYMLINK_DIRS.union( |
| 523 |
{WorkflowFiles.RUN_DIR}) |
| 524 |
) |
| 525 |
possible_symlink_dirs.remove('') |
| 526 |
for pair in symlist: |
| 527 |
try: |
| 528 |
key, val = pair.split("=") |
| 529 |
key = key.strip() |
| 530 |
except ValueError: |
| 531 |
raise InputError( |
| 532 |
'There is an error in --symlink-dirs option:' |
| 533 |
f' {pair}. Try entering option in the form ' |
| 534 |
'--symlink-dirs=\'log=$DIR, share=$DIR2, ...\'' |
| 535 |
) from None |
| 536 |
if key not in possible_symlink_dirs: |
| 537 |
dirs = ', '.join(possible_symlink_dirs) |
| 538 |
raise InputError( |
| 539 |
f"{key} not a valid entry for --symlink-dirs. " |
| 540 |
f"Configurable symlink dirs are: {dirs}" |
| 541 |
) |
| 542 |
symdict['localhost'][key] = val.strip() or None |
| 543 |
|
| 544 |
return symdict |
| 545 |
|
| 546 |
|
| 547 |
def detect_flow_exists( |
| 548 |
run_path_base: Union[Path, str], numbered: bool |
| 549 |
) -> bool: |
| 550 |
"""Returns True if installed flow already exists. |
| 551 |
|
| 552 |
Args: |
| 553 |
run_path_base: Absolute path of the parent of the workflow's run dir, |
| 554 |
i.e ~/cylc-run/<workflow_name> |
| 555 |
numbered: If True, will detect if numbered runs exist. If False, will |
| 556 |
detect if non-numbered runs exist, i.e. runs installed |
| 557 |
by --run-name. |
| 558 |
""" |
| 559 |
for entry in Path(run_path_base).iterdir(): |
| 560 |
is_numbered = bool(re.search(r'^run\d+$', entry.name)) |
| 561 |
if ( |
| 562 |
entry.is_dir() |
| 563 |
and entry.name not in { |
| 564 |
WorkflowFiles.Install.DIRNAME, WorkflowFiles.RUN_N |
| 565 |
} |
| 566 |
and Path(entry, WorkflowFiles.FLOW_FILE).exists() |
| 567 |
and is_numbered == numbered |
| 568 |
): |
| 569 |
return True |
| 570 |
return False |
| 571 |
|
| 572 |
|
| 573 |
def check_nested_dirs( |
| 574 |
run_dir: Path, |
| 575 |
install_dir: Optional[Path] = None |
| 576 |
) -> None: |
| 577 |
"""Disallow nested dirs: |
| 578 |
|
| 579 |
- Nested installed run dirs |
| 580 |
- Nested installed workflow dirs |
| 581 |
|
| 582 |
Args: |
| 583 |
run_dir: Absolute workflow run directory path. |
| 584 |
install_dir: Absolute workflow install directory path |
| 585 |
(contains _cylc-install). If None, will not check for nested |
| 586 |
install dirs. |
| 587 |
|
| 588 |
Raises: |
| 589 |
WorkflowFilesError if run_dir is nested inside an existing run dir, |
| 590 |
or install dirs are nested. |
| 591 |
""" |
| 592 |
if install_dir is not None: |
| 593 |
install_dir = Path(os.path.normpath(install_dir)) |
| 594 |
# Check parents: |
| 595 |
for parent_dir in run_dir.parents: |
| 596 |
# Stop searching at ~/cylc-run |
| 597 |
if parent_dir == Path(get_cylc_run_dir()): |
| 598 |
break |
| 599 |
# check for run directories: |
| 600 |
if is_valid_run_dir(parent_dir): |
| 601 |
raise WorkflowFilesError( |
| 602 |
NESTED_DIRS_MSG.format( |
| 603 |
dir_type='run', |
| 604 |
dest=run_dir, |
| 605 |
existing=get_cylc_run_abs_path(parent_dir) |
| 606 |
) |
| 607 |
) |
| 608 |
# Check for install directories: |
| 609 |
if ( |
| 610 |
install_dir |
| 611 |
and parent_dir in install_dir.parents |
| 612 |
and (parent_dir / WorkflowFiles.Install.DIRNAME).is_dir() |
| 613 |
): |
| 614 |
raise WorkflowFilesError( |
| 615 |
NESTED_DIRS_MSG.format( |
| 616 |
dir_type='install', |
| 617 |
dest=run_dir, |
| 618 |
existing=get_cylc_run_abs_path(parent_dir) |
| 619 |
) |
| 620 |
) |
| 621 |
|
| 622 |
if install_dir: |
| 623 |
# Search child tree for install directories: |
| 624 |
for depth in range(glbl_cfg().get(['install', 'max depth'])): |
| 625 |
search_pattern = f'*/{"*/" * depth}{WorkflowFiles.Install.DIRNAME}' |
| 626 |
for result in install_dir.glob(search_pattern): |
| 627 |
raise WorkflowFilesError( |
| 628 |
NESTED_DIRS_MSG.format( |
| 629 |
dir_type='install', |
| 630 |
dest=run_dir, |
| 631 |
existing=get_cylc_run_abs_path(result.parent) |
| 632 |
) |
| 633 |
) |