| 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 workflow removal.""" |
| 18 |
|
| 19 |
from collections import deque |
| 20 |
from contextlib import suppress |
| 21 |
from functools import partial |
| 22 |
import glob |
| 23 |
import os |
| 24 |
from pathlib import Path |
| 25 |
from random import shuffle |
| 26 |
import sqlite3 |
| 27 |
from subprocess import ( |
| 28 |
DEVNULL, |
| 29 |
PIPE, |
| 30 |
Popen, |
| 31 |
) |
| 32 |
from time import sleep |
| 33 |
from typing import ( |
| 34 |
TYPE_CHECKING, |
| 35 |
Any, |
| 36 |
Container, |
| 37 |
Deque, |
| 38 |
Dict, |
| 39 |
Iterable, |
| 40 |
List, |
| 41 |
NamedTuple, |
| 42 |
Optional, |
| 43 |
Set, |
| 44 |
Union, |
| 45 |
cast, |
| 46 |
) |
| 47 |
|
| 48 |
from cylc.flow import LOG |
| 49 |
from cylc.flow.cfgspec.glbl_cfg import glbl_cfg |
| 50 |
from cylc.flow.exceptions import ( |
| 51 |
CylcError, |
| 52 |
InputError, |
| 53 |
PlatformError, |
| 54 |
PlatformLookupError, |
| 55 |
SchedulerAlive, |
| 56 |
ServiceFileError, |
| 57 |
) |
| 58 |
from cylc.flow.pathutil import ( |
| 59 |
get_workflow_run_dir, |
| 60 |
is_relative_to, |
| 61 |
parse_rm_dirs, |
| 62 |
remove_dir_and_target, |
| 63 |
remove_dir_or_file, |
| 64 |
remove_empty_parents, |
| 65 |
) |
| 66 |
from cylc.flow.platforms import ( |
| 67 |
get_host_from_platform, |
| 68 |
get_install_target_from_platform, |
| 69 |
get_localhost_install_target, |
| 70 |
platform_from_name, |
| 71 |
) |
| 72 |
from cylc.flow.remote import construct_ssh_cmd |
| 73 |
from cylc.flow.rundb import CylcWorkflowDAO |
| 74 |
from cylc.flow.workflow_files import ( |
| 75 |
WorkflowFiles, |
| 76 |
detect_old_contact_file, |
| 77 |
get_symlink_dirs, |
| 78 |
get_workflow_srv_dir, |
| 79 |
infer_latest_run, |
| 80 |
validate_workflow_name, |
| 81 |
) |
| 82 |
|
| 83 |
|
| 84 |
if TYPE_CHECKING: |
| 85 |
from optparse import Values |
| 86 |
|
| 87 |
|
| 88 |
class RemoteCleanQueueTuple(NamedTuple): |
| 89 |
proc: 'Popen[str]' |
| 90 |
install_target: str |
| 91 |
platforms: List[Dict[str, Any]] |
| 92 |
|
| 93 |
|
| 94 |
class RemoteTimeoutErr(CylcError): |
| 95 |
"""Exception for when a remote clean times out.""" |
| 96 |
ret_code = 124 |
| 97 |
|
| 98 |
def __init__(self, timeout: str) -> None: |
| 99 |
self.timeout = timeout |
| 100 |
|
| 101 |
def __str__(self) -> str: |
| 102 |
return ( |
| 103 |
f"cylc clean timed out after {self.timeout}s. You can increase " |
| 104 |
"this timeout using the --timeout option." |
| 105 |
) |
| 106 |
|
| 107 |
|
| 108 |
async def get_contained_workflows(partial_id) -> List[str]: |
| 109 |
"""Return the sorted names of any workflows in a directory. |
| 110 |
|
| 111 |
Args: |
| 112 |
path: Absolute path to the dir. |
| 113 |
scan_depth: How many levels deep to look inside the dir. |
| 114 |
""" |
| 115 |
from cylc.flow.network.scan import scan |
| 116 |
run_dir = Path(get_workflow_run_dir(partial_id)) |
| 117 |
# Note: increased scan depth for safety |
| 118 |
scan_depth = glbl_cfg().get(['install', 'max depth']) + 1 |
| 119 |
return sorted( |
| 120 |
[i['name'] async for i in scan(scan_dir=run_dir, max_depth=scan_depth)] |
| 121 |
) |
| 122 |
|
| 123 |
|
| 124 |
def _clean_check(opts: 'Values', id_: str, run_dir: Path) -> None: |
| 125 |
"""Check whether a workflow can be cleaned. |
| 126 |
|
| 127 |
Args: |
| 128 |
id_: Workflow name. |
| 129 |
run_dir: Path to the workflow run dir on the filesystem. |
| 130 |
""" |
| 131 |
validate_workflow_name(id_) |
| 132 |
id_ = os.path.normpath(id_) |
| 133 |
# Thing to clean must be a dir or broken symlink: |
| 134 |
if not run_dir.is_dir() and not run_dir.is_symlink(): |
| 135 |
raise FileNotFoundError(f"No directory to clean at {run_dir}") |
| 136 |
if opts.no_scan: |
| 137 |
# This is cylc clean re-invoked on remote host; don't need to worry |
| 138 |
# about contact file. |
| 139 |
return |
| 140 |
try: |
| 141 |
detect_old_contact_file(id_) |
| 142 |
except SchedulerAlive as exc: |
| 143 |
raise ServiceFileError( |
| 144 |
f"Cannot clean running workflow {id_}.\n\n{exc}" |
| 145 |
) from None |
| 146 |
|
| 147 |
|
| 148 |
def init_clean(id_: str, opts: 'Values') -> None: |
| 149 |
"""Initiate the process of removing a stopped workflow from the local |
| 150 |
scheduler filesystem and remote hosts. |
| 151 |
|
| 152 |
Args: |
| 153 |
id_: Workflow ID. |
| 154 |
opts: CLI options object for cylc clean. |
| 155 |
|
| 156 |
""" |
| 157 |
local_run_dir = Path(get_workflow_run_dir(id_)) |
| 158 |
with suppress(InputError): |
| 159 |
local_run_dir, id_ = infer_latest_run( |
| 160 |
local_run_dir, implicit_runN=False, warn_runN=False |
| 161 |
) |
| 162 |
try: |
| 163 |
_clean_check(opts, id_, local_run_dir) |
| 164 |
except FileNotFoundError as exc: |
| 165 |
LOG.info(exc) |
| 166 |
return |
| 167 |
|
| 168 |
# Parse --rm option to make sure it's valid |
| 169 |
rm_dirs = parse_rm_dirs(opts.rm_dirs) if opts.rm_dirs else None |
| 170 |
|
| 171 |
if not opts.local_only: |
| 172 |
platform_names = None |
| 173 |
db_file = Path(get_workflow_srv_dir(id_), 'db') |
| 174 |
if not db_file.is_file(): |
| 175 |
# no DB -> do nothing |
| 176 |
if opts.remote_only: |
| 177 |
raise ServiceFileError( |
| 178 |
f"No workflow database for {id_} - cannot perform " |
| 179 |
"remote clean" |
| 180 |
) |
| 181 |
LOG.info( |
| 182 |
f"No workflow database for {id_} - will only clean locally" |
| 183 |
) |
| 184 |
else: |
| 185 |
# DB present -> load platforms |
| 186 |
try: |
| 187 |
platform_names = get_platforms_from_db(local_run_dir) |
| 188 |
except ServiceFileError as exc: |
| 189 |
raise ServiceFileError(f"Cannot clean {id_} - {exc}") from None |
| 190 |
except sqlite3.OperationalError as exc: |
| 191 |
# something went wrong with the query |
| 192 |
# e.g. the table/field we need isn't there |
| 193 |
LOG.warning( |
| 194 |
'This database is either corrupted or not compatible with' |
| 195 |
' this version of "cylc clean".' |
| 196 |
'\nTry using the version of Cylc the workflow was last ran' |
| 197 |
' with to remove it.' |
| 198 |
'\nOtherwise, use the "--local-only" option to remove' |
| 199 |
' local files (you may need to remove files on other' |
| 200 |
' platforms manually).' |
| 201 |
) |
| 202 |
raise ServiceFileError(f"Cannot clean {id_} - {exc}") from exc |
| 203 |
|
| 204 |
if platform_names and platform_names != {'localhost'}: |
| 205 |
remote_clean( |
| 206 |
id_, platform_names, opts.remote_timeout, opts.rm_dirs |
| 207 |
) |
| 208 |
|
| 209 |
if not opts.remote_only: |
| 210 |
# Must be after remote clean |
| 211 |
clean(id_, local_run_dir, rm_dirs) |
| 212 |
|
| 213 |
|
| 214 |
def clean(id_: str, run_dir: Path, rm_dirs: Optional[Set[str]] = None) -> None: |
| 215 |
"""Remove a stopped workflow from the local filesystem only. |
| 216 |
|
| 217 |
Deletes the workflow run directory and any symlink dirs, or just the |
| 218 |
specified sub dirs if rm_dirs is specified. |
| 219 |
|
| 220 |
Note: if the run dir has already been manually deleted, it will not be |
| 221 |
possible to clean any symlink dirs. |
| 222 |
|
| 223 |
Args: |
| 224 |
id_: Workflow ID. |
| 225 |
run_dir: Absolute path of the workflow's run dir. |
| 226 |
rm_dirs: Set of sub dirs to remove instead of the whole run dir. |
| 227 |
|
| 228 |
""" |
| 229 |
symlink_dirs = get_symlink_dirs(id_, run_dir) |
| 230 |
if rm_dirs is not None: |
| 231 |
# Targeted clean |
| 232 |
for pattern in rm_dirs: |
| 233 |
_clean_using_glob(run_dir, pattern, symlink_dirs) |
| 234 |
else: |
| 235 |
# Wholesale clean |
| 236 |
LOG.debug(f"Cleaning {run_dir}") |
| 237 |
for symlink in symlink_dirs: |
| 238 |
# Remove <symlink_dir>/cylc-run/<id>/<symlink> |
| 239 |
remove_dir_and_target(run_dir / symlink) |
| 240 |
if '' not in symlink_dirs: |
| 241 |
# if run dir isn't a symlink dir and hasn't been deleted yet |
| 242 |
remove_dir_and_target(run_dir) |
| 243 |
|
| 244 |
# Tidy up if necessary |
| 245 |
# Remove `runN` symlink if it's now broken |
| 246 |
runN = run_dir.parent / WorkflowFiles.RUN_N |
| 247 |
if ( |
| 248 |
runN.is_symlink() and |
| 249 |
not run_dir.exists() and |
| 250 |
os.readlink(str(runN)) == run_dir.name |
| 251 |
): |
| 252 |
runN.unlink() |
| 253 |
# Remove _cylc-install if it's the only thing left |
| 254 |
cylc_install_dir = run_dir.parent / WorkflowFiles.Install.DIRNAME |
| 255 |
for entry in run_dir.parent.iterdir(): |
| 256 |
if entry == cylc_install_dir: |
| 257 |
continue |
| 258 |
break |
| 259 |
else: # no break |
| 260 |
if cylc_install_dir.is_dir(): |
| 261 |
remove_dir_or_file(cylc_install_dir) |
| 262 |
# Remove any empty parents of run dir up to ~/cylc-run/ |
| 263 |
remove_empty_parents(run_dir, id_) |
| 264 |
for symlink, target in symlink_dirs.items(): |
| 265 |
# Remove empty parents of symlink target up to <symlink_dir>/cylc-run/ |
| 266 |
remove_empty_parents(target, Path(id_, symlink)) |
| 267 |
|
| 268 |
|
| 269 |
def glob_in_run_dir( |
| 270 |
run_dir: Union[Path, str], pattern: str, symlink_dirs: Container[Path] |
| 271 |
) -> List[Path]: |
| 272 |
"""Execute a (recursive) glob search in the given run directory. |
| 273 |
|
| 274 |
Returns list of any absolute paths that match the pattern. However: |
| 275 |
* Does not follow symlinks (apart from the specified symlink dirs). |
| 276 |
* Also does not return matching subpaths of matching directories (because |
| 277 |
that would be redundant). |
| 278 |
|
| 279 |
Args: |
| 280 |
run_dir: Absolute path of the workflow run dir. |
| 281 |
pattern: The glob pattern. |
| 282 |
symlink_dirs: Absolute paths to the workflow's symlink dirs. |
| 283 |
""" |
| 284 |
# Note: use os.path.join, not pathlib, to preserve trailing slash if |
| 285 |
# present in pattern |
| 286 |
pattern = os.path.join(glob.escape(str(run_dir)), pattern) |
| 287 |
# Note: don't use pathlib.Path.glob() because when you give it an exact |
| 288 |
# filename instead of pattern, it doesn't return broken symlinks |
| 289 |
matches = sorted(Path(i) for i in glob.iglob(pattern, recursive=True)) |
| 290 |
# sort guarantees parents come before their children |
| 291 |
if len(matches) == 1 and not os.path.lexists(matches[0]): |
| 292 |
# https://bugs.python.org/issue35201 |
| 293 |
return [] |
| 294 |
results: List[Path] = [] |
| 295 |
subpath_excludes: Set[Path] = set() |
| 296 |
for path in matches: |
| 297 |
# Iterate down through ancestors (starting at the run dir) to |
| 298 |
# weed out redundant subpaths of matched directories and subpaths of |
| 299 |
# non-standard symlinks |
| 300 |
for rel_ancestor in reversed(path.relative_to(run_dir).parents): |
| 301 |
ancestor = run_dir / rel_ancestor |
| 302 |
if ancestor in subpath_excludes: |
| 303 |
break |
| 304 |
if ancestor.is_symlink() and ancestor not in symlink_dirs: |
| 305 |
# Do not follow non-standard symlinks |
| 306 |
subpath_excludes.add(ancestor) |
| 307 |
break |
| 308 |
if not symlink_dirs and (ancestor in results): |
| 309 |
# We can be sure all subpaths of this ancestor are redundant |
| 310 |
subpath_excludes.add(ancestor) |
| 311 |
break |
| 312 |
if ancestor == path.parent: # noqa: SIM102 |
| 313 |
# Final iteration over ancestors |
| 314 |
if ancestor in matches and path not in symlink_dirs: |
| 315 |
# Redundant (but don't exclude subpaths in case any of the |
| 316 |
# subpaths are std symlink dirs) |
| 317 |
break |
| 318 |
else: # No break |
| 319 |
results.append(path) |
| 320 |
return results |
| 321 |
|
| 322 |
|
| 323 |
def _clean_using_glob( |
| 324 |
run_dir: Path, pattern: str, symlink_dirs: Iterable[str] |
| 325 |
) -> None: |
| 326 |
"""Delete the files/dirs in the run dir that match the pattern. |
| 327 |
|
| 328 |
Does not follow symlinks (apart from the standard symlink dirs). |
| 329 |
|
| 330 |
Args: |
| 331 |
run_dir: Absolute path of workflow run dir. |
| 332 |
pattern: The glob pattern. |
| 333 |
symlink_dirs: Paths of the workflow's symlink dirs relative to |
| 334 |
the run dir. |
| 335 |
""" |
| 336 |
abs_symlink_dirs = tuple(sorted( |
| 337 |
(run_dir / d for d in symlink_dirs), |
| 338 |
reverse=True # ordered by deepest to shallowest |
| 339 |
)) |
| 340 |
matches = glob_in_run_dir(run_dir, pattern, abs_symlink_dirs) |
| 341 |
if not matches: |
| 342 |
LOG.info(f"No files matching '{pattern}' in {run_dir}") |
| 343 |
return |
| 344 |
# First clean any matching symlink dirs |
| 345 |
for symlink_dir in abs_symlink_dirs: |
| 346 |
# Note: must clean e.g. share/cycle/ before share/ if the former |
| 347 |
# is a symlink even if only the latter was specified. |
| 348 |
if ( |
| 349 |
any(is_relative_to(symlink_dir, path) for path in matches) |
| 350 |
and symlink_dir.is_symlink() |
| 351 |
): |
| 352 |
remove_dir_and_target(symlink_dir) |
| 353 |
if symlink_dir == run_dir: |
| 354 |
# We have deleted the run dir |
| 355 |
return |
| 356 |
if symlink_dir in matches: |
| 357 |
matches.remove(symlink_dir) |
| 358 |
# Now clean the rest |
| 359 |
for path in matches: |
| 360 |
remove_dir_or_file(path) |
| 361 |
|
| 362 |
|
| 363 |
def remote_clean( |
| 364 |
id_: str, |
| 365 |
platform_names: Iterable[str], |
| 366 |
timeout: str, |
| 367 |
rm_dirs: list[str] | None = None, |
| 368 |
) -> None: |
| 369 |
"""Run subprocesses to clean a workflow on its remote install targets |
| 370 |
(skip localhost), given a set of platform names to look up. |
| 371 |
|
| 372 |
Args: |
| 373 |
id_: Workflow name. |
| 374 |
platform_names: List of platform names to look up in the global |
| 375 |
config, in order to determine the install targets to clean on. |
| 376 |
timeout: Number of seconds to wait before cancelling. |
| 377 |
rm_dirs: Sub dirs to remove instead of the whole run dir. |
| 378 |
""" |
| 379 |
install_targets_map: dict[str, list[dict]] = {} |
| 380 |
for platform_name in platform_names: |
| 381 |
try: |
| 382 |
platform = platform_from_name(platform_name) |
| 383 |
except PlatformLookupError as exc: |
| 384 |
LOG.warning(exc) |
| 385 |
continue |
| 386 |
target = get_install_target_from_platform(platform) |
| 387 |
if target != get_localhost_install_target(): |
| 388 |
install_targets_map.setdefault(target, []).append(platform) |
| 389 |
|
| 390 |
queue: Deque[RemoteCleanQueueTuple] = deque() |
| 391 |
remote_clean_cmd = partial( |
| 392 |
_remote_clean_cmd, id_=id_, rm_dirs=rm_dirs, timeout=timeout |
| 393 |
) |
| 394 |
for target, platforms in install_targets_map.items(): |
| 395 |
shuffle(platforms) |
| 396 |
LOG.info(f"Cleaning {id_} on install target: {target}") |
| 397 |
# Issue ssh command: |
| 398 |
queue.append( |
| 399 |
RemoteCleanQueueTuple( |
| 400 |
remote_clean_cmd(platform=platforms[0]), target, platforms |
| 401 |
) |
| 402 |
) |
| 403 |
failed_targets: dict[str, PlatformError | RemoteTimeoutErr] = {} |
| 404 |
# Handle subproc pool results almost concurrently: |
| 405 |
while queue: |
| 406 |
item = queue.popleft() |
| 407 |
ret_code = item.proc.poll() |
| 408 |
if ret_code is None: # proc still running |
| 409 |
queue.append(item) |
| 410 |
continue |
| 411 |
out, err = item.proc.communicate() |
| 412 |
if out: |
| 413 |
LOG.info(f"[{item.install_target}]\n{out}") |
| 414 |
if ret_code == RemoteTimeoutErr.ret_code: |
| 415 |
failed_targets[item.install_target] = RemoteTimeoutErr(timeout) |
| 416 |
elif ret_code: |
| 417 |
this_platform = item.platforms.pop(0) |
| 418 |
excp = PlatformError( |
| 419 |
PlatformError.MSG_TIDY, |
| 420 |
this_platform['name'], |
| 421 |
cmd=cast('list[str]', item.proc.args), |
| 422 |
ret_code=ret_code, |
| 423 |
out=out, |
| 424 |
err=err, |
| 425 |
) |
| 426 |
if ret_code == 255 and item.platforms: |
| 427 |
# SSH error; try again using the next platform for this |
| 428 |
# install target |
| 429 |
LOG.debug(excp) |
| 430 |
queue.append( |
| 431 |
item._replace( |
| 432 |
proc=remote_clean_cmd(platform=item.platforms[0]) |
| 433 |
) |
| 434 |
) |
| 435 |
else: # Exhausted list of platforms |
| 436 |
failed_targets[item.install_target] = excp |
| 437 |
elif err: |
| 438 |
# Only show stderr from remote host in debug mode if ret code 0 |
| 439 |
# because stderr often contains useless stuff like ssh login |
| 440 |
# messages |
| 441 |
LOG.debug(f"[{item.install_target}]\n{err}") |
| 442 |
sleep(0.2) |
| 443 |
|
| 444 |
if failed_targets: |
| 445 |
msg = ( |
| 446 |
f"Remote clean failed for {id_} - could not clean on these " |
| 447 |
"install target(s):" |
| 448 |
) |
| 449 |
for target, excep in failed_targets.items(): |
| 450 |
msg += f"\n[{target}]\n{excep}" |
| 451 |
raise CylcError(msg) |
| 452 |
|
| 453 |
|
| 454 |
def _remote_clean_cmd( |
| 455 |
id_: str, |
| 456 |
platform: Dict[str, Any], |
| 457 |
rm_dirs: Optional[List[str]], |
| 458 |
timeout: str |
| 459 |
) -> 'Popen[str]': |
| 460 |
"""Remove a stopped workflow on a remote host. |
| 461 |
|
| 462 |
Call "cylc clean --local-only" over ssh and return the subprocess. |
| 463 |
|
| 464 |
Args: |
| 465 |
id_: Workflow name. |
| 466 |
platform: Config for the platform on which to remove the workflow. |
| 467 |
rm_dirs: Sub dirs to remove instead of the whole run dir. |
| 468 |
timeout: Number of seconds to wait before cancelling the command. |
| 469 |
|
| 470 |
Raises: |
| 471 |
NoHostsError: If the platform is not contactable. |
| 472 |
|
| 473 |
""" |
| 474 |
LOG.debug( |
| 475 |
f"Cleaning {id_} on install target: {platform['install target']} " |
| 476 |
f"(using platform: {platform['name']})" |
| 477 |
) |
| 478 |
cmd = ['clean', '--local-only', '--no-scan', id_] |
| 479 |
if rm_dirs is not None: |
| 480 |
for item in rm_dirs: |
| 481 |
cmd.extend(['--rm', item]) |
| 482 |
cmd = construct_ssh_cmd( |
| 483 |
cmd, |
| 484 |
platform, |
| 485 |
get_host_from_platform(platform), |
| 486 |
timeout=timeout, |
| 487 |
set_verbosity=True, |
| 488 |
) |
| 489 |
LOG.debug(" ".join(cmd)) |
| 490 |
return Popen( # nosec |
| 491 |
cmd, |
| 492 |
stdin=DEVNULL, |
| 493 |
stdout=PIPE, |
| 494 |
stderr=PIPE, |
| 495 |
text=True, |
| 496 |
) |
| 497 |
# * command constructed by internal interface |
| 498 |
|
| 499 |
|
| 500 |
def get_platforms_from_db(run_dir: Path) -> Set[str]: |
| 501 |
"""Return the set of names of platforms (that jobs ran on) from the DB. |
| 502 |
|
| 503 |
Warning: |
| 504 |
This does NOT upgrade the workflow database! |
| 505 |
|
| 506 |
We could upgrade the DB for backward compatiblity, but we haven't |
| 507 |
got any upgraders for this table yet so there's no point. |
| 508 |
|
| 509 |
Note that upgrading the DB here would not help with forward |
| 510 |
compatibility. We can't apply upgraders which don't exist yet. |
| 511 |
|
| 512 |
Args: |
| 513 |
run_dir: The workflow run directory. |
| 514 |
|
| 515 |
Raises: |
| 516 |
sqlite3.OperationalError: in the event the table/field required for |
| 517 |
cleaning is not present. |
| 518 |
|
| 519 |
""" |
| 520 |
with CylcWorkflowDAO( |
| 521 |
run_dir / WorkflowFiles.Service.DIRNAME / WorkflowFiles.Service.DB |
| 522 |
) as pri_dao: |
| 523 |
platform_names = pri_dao.select_task_job_platforms() |
| 524 |
|
| 525 |
return platform_names |