| 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 |
"""Files which define workflows or are created by Cylc. |
| 18 |
|
| 19 |
See also: |
| 20 |
* cylc.flow.install - for installing files from source dirs into the run dir. |
| 21 |
* cylc.flow.clean - for removing files from the run dir. |
| 22 |
|
| 23 |
""" |
| 24 |
|
| 25 |
from contextlib import suppress |
| 26 |
from enum import Enum |
| 27 |
import errno |
| 28 |
from collections import deque |
| 29 |
import os |
| 30 |
from pathlib import Path |
| 31 |
import re |
| 32 |
import shutil |
| 33 |
from subprocess import ( |
| 34 |
PIPE, |
| 35 |
Popen, |
| 36 |
TimeoutExpired, |
| 37 |
) |
| 38 |
from typing import ( |
| 39 |
Callable, |
| 40 |
Dict, |
| 41 |
Optional, |
| 42 |
Tuple, |
| 43 |
Union, |
| 44 |
NoReturn, |
| 45 |
Type, |
| 46 |
) |
| 47 |
|
| 48 |
import cylc.flow.flags |
| 49 |
from cylc.flow import LOG |
| 50 |
from cylc.flow.async_util import make_async |
| 51 |
from cylc.flow.cfgspec.glbl_cfg import glbl_cfg |
| 52 |
from cylc.flow.exceptions import ( |
| 53 |
SchedulerAlive, |
| 54 |
CylcError, |
| 55 |
InputError, |
| 56 |
ServiceFileError, |
| 57 |
WorkflowFilesError, |
| 58 |
FileRemovalError, |
| 59 |
) |
| 60 |
from cylc.flow.hostuserutil import ( |
| 61 |
get_user, |
| 62 |
is_remote_host, |
| 63 |
) |
| 64 |
from cylc.flow.pathutil import ( |
| 65 |
SYMLINKABLE_LOCATIONS, |
| 66 |
expand_path, |
| 67 |
get_cylc_run_dir, |
| 68 |
get_workflow_run_dir, |
| 69 |
get_alt_workflow_run_dir, |
| 70 |
make_localhost_symlinks, |
| 71 |
) |
| 72 |
from cylc.flow.unicode_rules import WorkflowNameValidator |
| 73 |
from cylc.flow.util import cli_format |
| 74 |
|
| 75 |
|
| 76 |
def handle_rmtree_err( |
| 77 |
function: Callable, |
| 78 |
path: str, |
| 79 |
excinfo: Tuple[Type[Exception], Exception, object] |
| 80 |
) -> NoReturn: |
| 81 |
"""Error handler for shutil.rmtree.""" |
| 82 |
exc = excinfo[1] |
| 83 |
if isinstance(exc, OSError) and exc.errno == errno.ENOTEMPTY: |
| 84 |
# "Directory not empty", likely due to filesystem lag |
| 85 |
raise FileRemovalError(exc) |
| 86 |
raise exc |
| 87 |
|
| 88 |
|
| 89 |
class KeyType(Enum): |
| 90 |
"""Used for authentication keys - public or private""" |
| 91 |
|
| 92 |
PRIVATE = "private" |
| 93 |
PUBLIC = "public" |
| 94 |
|
| 95 |
|
| 96 |
class KeyOwner(Enum): |
| 97 |
"""Used for authentication keys - server or client""" |
| 98 |
|
| 99 |
SERVER = "server" |
| 100 |
CLIENT = "client" |
| 101 |
|
| 102 |
|
| 103 |
class KeyInfo(): # noqa: SIM119 (not really relevant here) |
| 104 |
"""Represents a server or client key file, which can be private or public. |
| 105 |
|
| 106 |
Attributes: |
| 107 |
file_name: The file name of this key object. |
| 108 |
key_type: public or private |
| 109 |
key_owner: server or client |
| 110 |
key_path: The absolute path, not including filename, |
| 111 |
for this key object. |
| 112 |
full_key_path: The absolute path, including filename, |
| 113 |
for this key object. |
| 114 |
|
| 115 |
|
| 116 |
""" |
| 117 |
|
| 118 |
def __init__( |
| 119 |
self, |
| 120 |
key_type: KeyType, |
| 121 |
key_owner: KeyOwner, |
| 122 |
full_key_path: Optional[str] = None, |
| 123 |
workflow_srv_dir: Optional[str] = None, |
| 124 |
install_target: Optional[str] = None, |
| 125 |
server_held: bool = True |
| 126 |
): |
| 127 |
self.key_type = key_type |
| 128 |
self.key_owner = key_owner |
| 129 |
self.workflow_srv_dir = workflow_srv_dir |
| 130 |
self.install_target = install_target |
| 131 |
if full_key_path is not None: |
| 132 |
self.key_path, self.file_name = os.path.split(full_key_path) |
| 133 |
elif self.workflow_srv_dir is not None: # noqa: SIM106 |
| 134 |
# Build key filename |
| 135 |
file_name = key_owner.value |
| 136 |
|
| 137 |
# Add optional install target name |
| 138 |
if (key_owner is KeyOwner.CLIENT |
| 139 |
and key_type is KeyType.PUBLIC |
| 140 |
and self.install_target is not None): |
| 141 |
file_name = f"{file_name}_{self.install_target}" |
| 142 |
|
| 143 |
if key_type is KeyType.PRIVATE: |
| 144 |
file_extension = WorkflowFiles.Service.PRIVATE_FILE_EXTENSION |
| 145 |
else: |
| 146 |
file_extension = WorkflowFiles.Service.PUBLIC_FILE_EXTENSION |
| 147 |
|
| 148 |
self.file_name = f"{file_name}{file_extension}" |
| 149 |
|
| 150 |
# Build key path (without filename) for client public keys |
| 151 |
if (key_owner is KeyOwner.CLIENT |
| 152 |
and key_type is KeyType.PUBLIC and server_held): |
| 153 |
temp = f"{key_owner.value}_{key_type.value}_keys" |
| 154 |
self.key_path = os.path.join( |
| 155 |
os.path.expanduser("~"), |
| 156 |
self.workflow_srv_dir, |
| 157 |
temp) |
| 158 |
elif ( |
| 159 |
(key_owner is KeyOwner.CLIENT |
| 160 |
and key_type is KeyType.PUBLIC |
| 161 |
and server_held is False) |
| 162 |
or |
| 163 |
(key_owner is KeyOwner.SERVER |
| 164 |
and key_type is KeyType.PRIVATE) |
| 165 |
or (key_owner is KeyOwner.CLIENT |
| 166 |
and key_type is KeyType.PRIVATE) |
| 167 |
or (key_owner is KeyOwner.SERVER |
| 168 |
and key_type is KeyType.PUBLIC)): |
| 169 |
self.key_path = os.path.expandvars(self.workflow_srv_dir) |
| 170 |
|
| 171 |
else: |
| 172 |
raise ValueError( |
| 173 |
"Cannot create KeyInfo without workflow path or full path.") |
| 174 |
|
| 175 |
# Build full key path (including file name) |
| 176 |
|
| 177 |
self.full_key_path = os.path.join(self.key_path, self.file_name) |
| 178 |
|
| 179 |
|
| 180 |
class WorkflowFiles: |
| 181 |
"""Names of files and directories located in the workflow directory.""" |
| 182 |
|
| 183 |
FLOW_FILE = 'flow.cylc' |
| 184 |
"""The workflow configuration file.""" |
| 185 |
|
| 186 |
FLOW_FILE_PROCESSED = 'flow-processed.cylc' |
| 187 |
"""The workflow configuration file after processing.""" |
| 188 |
|
| 189 |
SUITE_RC = 'suite.rc' |
| 190 |
"""Deprecated workflow configuration file.""" |
| 191 |
|
| 192 |
RUN_N = 'runN' |
| 193 |
"""Symbolic link for latest run""" |
| 194 |
|
| 195 |
class LogDir: |
| 196 |
"""The directory containing workflow log files""" |
| 197 |
|
| 198 |
DIRNAME = 'log' |
| 199 |
"""Workflow log directory.""" |
| 200 |
|
| 201 |
INSTALL = 'install' |
| 202 |
"""Install log dir""" |
| 203 |
|
| 204 |
VERSION = 'version' |
| 205 |
"""Version control log dir""" |
| 206 |
|
| 207 |
DB = 'db' |
| 208 |
"""The public database""" |
| 209 |
|
| 210 |
JOB = 'job' |
| 211 |
"""The job log directory.""" |
| 212 |
|
| 213 |
LOG_JOB_DIR = os.path.join(LogDir.DIRNAME, LogDir.JOB) |
| 214 |
|
| 215 |
SHARE_DIR = 'share' |
| 216 |
"""Workflow share directory.""" |
| 217 |
|
| 218 |
SHARE_CYCLE_DIR = os.path.join(SHARE_DIR, 'cycle') |
| 219 |
"""Workflow share/cycle directory.""" |
| 220 |
|
| 221 |
WORK_DIR = 'work' |
| 222 |
"""Workflow work directory.""" |
| 223 |
|
| 224 |
RUN_DIR = 'run' |
| 225 |
"""Workflow run directory.""" |
| 226 |
|
| 227 |
class Service: |
| 228 |
"""The directory containing Cylc system files.""" |
| 229 |
|
| 230 |
DIRNAME = '.service' |
| 231 |
"""The name of this directory.""" |
| 232 |
|
| 233 |
CONTACT = 'contact' |
| 234 |
"""Contains settings for the running workflow. |
| 235 |
|
| 236 |
For details of the fields see ``ContactFileFields``. |
| 237 |
""" |
| 238 |
|
| 239 |
DB = 'db' |
| 240 |
"""The workflow database. |
| 241 |
|
| 242 |
Contains information about the execution and status of a workflow. |
| 243 |
""" |
| 244 |
|
| 245 |
PUBLIC_FILE_EXTENSION = '.key' |
| 246 |
PRIVATE_FILE_EXTENSION = '.key_secret' |
| 247 |
"""Keyword identifiers used to form the certificate names. |
| 248 |
Note: the public & private identifiers are set by CurveZMQ, so cannot |
| 249 |
be renamed, but we hard-code them since they can't be extracted easily. |
| 250 |
""" |
| 251 |
|
| 252 |
class Install: |
| 253 |
"""The directory containing install source link.""" |
| 254 |
|
| 255 |
DIRNAME = '_cylc-install' |
| 256 |
"""The name of this directory.""" |
| 257 |
|
| 258 |
SOURCE = 'source' |
| 259 |
"""Symlink to the workflow definition (For run dir).""" |
| 260 |
|
| 261 |
RESERVED_DIRNAMES = frozenset([ |
| 262 |
LogDir.DIRNAME, SHARE_DIR, WORK_DIR, RUN_N, |
| 263 |
Service.DIRNAME, Install.DIRNAME |
| 264 |
]) |
| 265 |
"""Reserved directory names that cannot be present in a source dir.""" |
| 266 |
|
| 267 |
RESERVED_NAMES = frozenset([FLOW_FILE, SUITE_RC, *RESERVED_DIRNAMES]) |
| 268 |
"""Reserved filenames that cannot be used as run names.""" |
| 269 |
|
| 270 |
SYMLINK_DIRS = frozenset(list(SYMLINKABLE_LOCATIONS) + ['']) |
| 271 |
"""The paths of the symlink dirs that may be set in |
| 272 |
global.cylc[install][symlink dirs], relative to the run dir |
| 273 |
('' represents the run dir).""" |
| 274 |
|
| 275 |
|
| 276 |
class ContactFileFields: |
| 277 |
"""Field names present in ``WorkflowFiles.Service.CONTACT``. |
| 278 |
|
| 279 |
These describe properties of a running workflow. |
| 280 |
|
| 281 |
.. note:: |
| 282 |
|
| 283 |
The presence of this file indicates the workflow is running as it is |
| 284 |
removed on shutdown. however, if a workflow is not properly shut down |
| 285 |
this file may be left behind. |
| 286 |
|
| 287 |
""" |
| 288 |
|
| 289 |
API = 'CYLC_API' |
| 290 |
"""The Workflow API version string.""" |
| 291 |
|
| 292 |
HOST = 'CYLC_WORKFLOW_HOST' |
| 293 |
"""The name of the host the scheduler process is running on.""" |
| 294 |
|
| 295 |
NAME = 'CYLC_WORKFLOW_ID' |
| 296 |
"""The name of the workflow.""" |
| 297 |
|
| 298 |
OWNER = 'CYLC_WORKFLOW_OWNER' |
| 299 |
"""The user account under which the scheduler process is running.""" |
| 300 |
|
| 301 |
PID = 'CYLC_WORKFLOW_PID' |
| 302 |
"""The process ID of the running workflow on ``CYLC_WORKFLOW_HOST``.""" |
| 303 |
|
| 304 |
COMMAND = 'CYLC_WORKFLOW_COMMAND' |
| 305 |
"""The command that was used to run the workflow on |
| 306 |
``CYLC_WORKFLOW_HOST```. |
| 307 |
|
| 308 |
Note that this command may be affected by: |
| 309 |
|
| 310 |
* Workflow host selection (this adds the ``--host`` argument). |
| 311 |
* Auto restart (this reconstructs the command and changes the ``--host`` |
| 312 |
argument. |
| 313 |
""" |
| 314 |
|
| 315 |
PORT = 'CYLC_WORKFLOW_PORT' |
| 316 |
"""The port Cylc uses to communicate with this workflow.""" |
| 317 |
|
| 318 |
PUBLISH_PORT = 'CYLC_WORKFLOW_PUBLISH_PORT' |
| 319 |
"""The port Cylc uses to publish data.""" |
| 320 |
|
| 321 |
WORKFLOW_RUN_DIR_ON_WORKFLOW_HOST = ( |
| 322 |
'CYLC_WORKFLOW_RUN_DIR_ON_WORKFLOW_HOST' |
| 323 |
) |
| 324 |
"""The path to the workflow run directory as seen from ``HOST``.""" |
| 325 |
|
| 326 |
UUID = 'CYLC_WORKFLOW_UUID' |
| 327 |
"""Unique ID for this run of the workflow.""" |
| 328 |
|
| 329 |
VERSION = 'CYLC_VERSION' |
| 330 |
"""The Cylc version under which the workflow is running.""" |
| 331 |
|
| 332 |
SCHEDULER_SSH_COMMAND = 'SCHEDULER_SSH_COMMAND' |
| 333 |
|
| 334 |
SCHEDULER_CYLC_PATH = 'SCHEDULER_CYLC_PATH' |
| 335 |
"""The path containing the Cylc executable on a remote host.""" |
| 336 |
|
| 337 |
SCHEDULER_USE_LOGIN_SHELL = 'SCHEDULER_USE_LOGIN_SHELL' |
| 338 |
"""Remote command setting for Scheduler.""" |
| 339 |
|
| 340 |
|
| 341 |
REG_DELIM = "/" |
| 342 |
|
| 343 |
NO_TITLE = "No title provided" |
| 344 |
REC_TITLE = re.compile(r"^\s*title\s*=\s*(.*)\s*$") |
| 345 |
|
| 346 |
CONTACT_FILE_EXISTS_MSG = r"""workflow contact file exists: %(fname)s |
| 347 |
|
| 348 |
Workflow "%(workflow)s" is already running, listening at "%(host)s:%(port)s". |
| 349 |
|
| 350 |
If you like, you can stop it with one or more of the following commands: |
| 351 |
* cylc stop %(workflow)s # wait for active tasks/event handlers |
| 352 |
* cylc stop --kill %(workflow)s # kill active tasks and wait |
| 353 |
* cylc stop --now %(workflow)s # don't wait for active tasks |
| 354 |
* cylc stop --now --now %(workflow)s # don't wait for tasks or handlers |
| 355 |
* ssh -n "%(host)s" kill %(pid)s # final brute force! |
| 356 |
""" |
| 357 |
|
| 358 |
SUITERC_DEPR_MSG = ( |
| 359 |
"Backward compatibility mode ON" |
| 360 |
" - support for suite.rc files will be removed at 8.7.0" |
| 361 |
) |
| 362 |
|
| 363 |
NO_FLOW_FILE_MSG = ( |
| 364 |
f"No {WorkflowFiles.FLOW_FILE} or {WorkflowFiles.SUITE_RC} " |
| 365 |
"in {}" |
| 366 |
) |
| 367 |
|
| 368 |
|
| 369 |
def _is_process_running( |
| 370 |
host: str, |
| 371 |
pid: Union[int, str], |
| 372 |
command: str |
| 373 |
) -> bool: |
| 374 |
"""Check if a workflow process is still running. |
| 375 |
|
| 376 |
Runs `cylc psutil` on the scheduler run host. |
| 377 |
* Returns True if the process is still running. |
| 378 |
* Returns False if it is not. |
| 379 |
* Raises CylcError if we cannot tell (e.g. due to network issues). |
| 380 |
|
| 381 |
Args: |
| 382 |
host: |
| 383 |
The host where you expect it to be running. |
| 384 |
pid: |
| 385 |
The process ID you expect it to be running under. |
| 386 |
command: |
| 387 |
The command you expect to be running as it would appear in `ps` |
| 388 |
output` (e.g. `cylc play <flow> --host=localhost`). |
| 389 |
|
| 390 |
Raises: |
| 391 |
CylcError: |
| 392 |
If it is not possible to tell whether the process is running |
| 393 |
or not. |
| 394 |
|
| 395 |
Returns: |
| 396 |
True if the workflow is running else False. |
| 397 |
|
| 398 |
Examples: |
| 399 |
>>> import psutil; proc = psutil.Process() |
| 400 |
|
| 401 |
# check a process that is running (i.e. this one) |
| 402 |
>>> _is_process_running( |
| 403 |
... 'localhost', |
| 404 |
... proc.pid, |
| 405 |
... cli_format(proc.cmdline()), |
| 406 |
... ) |
| 407 |
True |
| 408 |
|
| 409 |
# check a process that is running but with a command line that |
| 410 |
# doesn't match |
| 411 |
>>> _is_process_running('localhost', proc.pid, 'something-else') |
| 412 |
False |
| 413 |
|
| 414 |
""" |
| 415 |
from cylc.flow.remote import construct_cylc_server_ssh_cmd |
| 416 |
from cylc.flow.terminal import parse_dirty_json |
| 417 |
|
| 418 |
# See if the process is still running or not. |
| 419 |
metric = f'[["Process.cmdline", {pid}]]' |
| 420 |
if is_remote_host(host): |
| 421 |
cmd = ['psutil'] |
| 422 |
cmd = construct_cylc_server_ssh_cmd(cmd, host) |
| 423 |
else: |
| 424 |
cmd = ['cylc', 'psutil'] |
| 425 |
proc = Popen( # nosec |
| 426 |
cmd, |
| 427 |
stdin=PIPE, |
| 428 |
stdout=PIPE, |
| 429 |
stderr=PIPE, |
| 430 |
text=True |
| 431 |
) # * hardcoded command |
| 432 |
try: |
| 433 |
out, err = proc.communicate( |
| 434 |
timeout=( |
| 435 |
glbl_cfg().get( |
| 436 |
['scheduler', 'run hosts', 'process check timeout']) |
| 437 |
), |
| 438 |
input=metric |
| 439 |
) |
| 440 |
except TimeoutExpired: |
| 441 |
raise CylcError( |
| 442 |
f'Attempt to determine whether workflow is running on {host}' |
| 443 |
' timed out after 10 seconds.' |
| 444 |
) from None |
| 445 |
|
| 446 |
if proc.returncode == 2: |
| 447 |
# the psutil call failed to gather metrics on the process |
| 448 |
# because the process does not exist |
| 449 |
return False |
| 450 |
|
| 451 |
error = False |
| 452 |
if proc.returncode: |
| 453 |
# the psutil call failed in some other way e.g. network issues |
| 454 |
LOG.warning( |
| 455 |
f'$ {cli_format(cmd)} # returned {proc.returncode}\n{err}' |
| 456 |
) |
| 457 |
error = True |
| 458 |
else: |
| 459 |
try: |
| 460 |
process = parse_dirty_json(out)[0] |
| 461 |
except ValueError: |
| 462 |
# the JSON cannot be parsed, log it |
| 463 |
LOG.warning(f'Could not parse JSON:\n{out}') |
| 464 |
error = True |
| 465 |
|
| 466 |
if error: |
| 467 |
raise CylcError( |
| 468 |
f'Cannot determine whether workflow is running on {host}.' |
| 469 |
f'\n{command}' |
| 470 |
) |
| 471 |
|
| 472 |
return cli_format(process) == command |
| 473 |
|
| 474 |
|
| 475 |
def detect_old_contact_file( |
| 476 |
id_: str, contact_data=None |
| 477 |
) -> None: |
| 478 |
"""Check if the workflow process is still running. |
| 479 |
|
| 480 |
As a side-effect this should detect and rectify the situation |
| 481 |
where an old contact file is still present from a previous run. This can be |
| 482 |
caused by the uncontrolled teardown of a running Scheduler (e.g. a power |
| 483 |
off). |
| 484 |
|
| 485 |
* If an old contact file does not exist, do nothing. |
| 486 |
* If one does exist but the workflow process is definitely not alive, |
| 487 |
remove it. |
| 488 |
* If one exists and the workflow process is still alive, raise |
| 489 |
SchedulerAlive. |
| 490 |
|
| 491 |
Args: |
| 492 |
id_: workflow ID |
| 493 |
contact_date: |
| 494 |
|
| 495 |
Raises: |
| 496 |
CylcError: |
| 497 |
If it is not possible to tell for sure if the workflow is running |
| 498 |
or not. |
| 499 |
SchedulerAlive: |
| 500 |
If old contact file exists and the workflow process still alive. |
| 501 |
ServiceFileError: |
| 502 |
For corrupt / incompatible contact files. |
| 503 |
|
| 504 |
""" |
| 505 |
# An old workflow of the same name may be running if a contact file exists |
| 506 |
# and can be loaded. |
| 507 |
if not contact_data: |
| 508 |
try: |
| 509 |
contact_data = load_contact_file(id_) |
| 510 |
except (IOError, ValueError, ServiceFileError): |
| 511 |
# Contact file does not exist or corrupted, workflow should be dead |
| 512 |
return |
| 513 |
|
| 514 |
try: |
| 515 |
old_host: str = contact_data[ContactFileFields.HOST] |
| 516 |
old_port: str = contact_data[ContactFileFields.PORT] |
| 517 |
old_pid: str = contact_data[ContactFileFields.PID] |
| 518 |
old_cmd: str = contact_data[ContactFileFields.COMMAND] |
| 519 |
except KeyError as exc: |
| 520 |
# this can happen if contact file is from an outdated version of Cylc |
| 521 |
raise ServiceFileError( |
| 522 |
f'Found contact file with incomplete data:\n{exc}.' |
| 523 |
) from None |
| 524 |
|
| 525 |
# check if the workflow process is running ... |
| 526 |
# NOTE: can raise CylcError |
| 527 |
process_is_running = _is_process_running(old_host, old_pid, old_cmd) |
| 528 |
|
| 529 |
fname = get_contact_file_path(id_) |
| 530 |
if process_is_running: |
| 531 |
# ... the process is running, raise an exception |
| 532 |
raise SchedulerAlive( |
| 533 |
CONTACT_FILE_EXISTS_MSG % { |
| 534 |
"host": old_host, |
| 535 |
"port": old_port, |
| 536 |
"pid": old_pid, |
| 537 |
"fname": fname, |
| 538 |
"workflow": id_, |
| 539 |
} |
| 540 |
) |
| 541 |
else: |
| 542 |
# ... the process isn't running so the contact file is out of date |
| 543 |
# remove it |
| 544 |
try: |
| 545 |
os.unlink(fname) |
| 546 |
except FileNotFoundError: |
| 547 |
# contact file has been removed by another process |
| 548 |
# (likely by another cylc client, no problem, safe to ignore) |
| 549 |
pass |
| 550 |
except OSError as exc: |
| 551 |
# unexpected error removing the contact file |
| 552 |
# (note the FileNotFoundError incorporated errno.ENOENT) |
| 553 |
LOG.error( |
| 554 |
f'Failed to remove contact file for {id_}:\n{exc}' |
| 555 |
) |
| 556 |
else: |
| 557 |
LOG.info( |
| 558 |
f'Removed contact file for {id_}' |
| 559 |
' (workflow no longer running).' |
| 560 |
) |
| 561 |
|
| 562 |
|
| 563 |
def dump_contact_file(id_, data): |
| 564 |
"""Create contact file. Data should be a key=value dict.""" |
| 565 |
# Note: |
| 566 |
# 1st fsync for writing the content of the contact file to disk. |
| 567 |
# 2nd fsync for writing the file metadata of the contact file to disk. |
| 568 |
# The double fsync logic ensures that if the contact file is written to |
| 569 |
# a shared file system e.g. via NFS, it will be immediately visible |
| 570 |
# from by a process on other hosts after the current process returns. |
| 571 |
with open(get_contact_file_path(id_), "wb") as handle: |
| 572 |
for key, value in sorted(data.items()): |
| 573 |
handle.write(("%s=%s\n" % (key, value)).encode()) |
| 574 |
os.fsync(handle.fileno()) |
| 575 |
dir_fileno = os.open(get_workflow_srv_dir(id_), os.O_DIRECTORY) |
| 576 |
os.fsync(dir_fileno) |
| 577 |
os.close(dir_fileno) |
| 578 |
|
| 579 |
|
| 580 |
def get_contact_file_path(id_: str) -> str: |
| 581 |
"""Return name of contact file.""" |
| 582 |
return os.path.join( |
| 583 |
get_workflow_srv_dir(id_), WorkflowFiles.Service.CONTACT) |
| 584 |
|
| 585 |
|
| 586 |
def get_flow_file(id_: str) -> Path: |
| 587 |
"""Return the path of a workflow's flow.cylc file.""" |
| 588 |
run_dir = get_workflow_run_dir(id_) |
| 589 |
path = check_flow_file(run_dir) |
| 590 |
return path |
| 591 |
|
| 592 |
|
| 593 |
def get_workflow_source_dir( |
| 594 |
run_dir: Union[Path, str] |
| 595 |
) -> Union[Tuple[str, Path], Tuple[None, None]]: |
| 596 |
"""Get the source directory path for a given workflow run directory. |
| 597 |
|
| 598 |
Args: |
| 599 |
run_dir: directory to check for an installed flow inside. |
| 600 |
|
| 601 |
Returns (source_dir, symlink) where the latter is the symlink to the source |
| 602 |
dir that exists in the run dir. |
| 603 |
""" |
| 604 |
source_path = Path( |
| 605 |
run_dir, |
| 606 |
WorkflowFiles.Install.DIRNAME, |
| 607 |
WorkflowFiles.Install.SOURCE) |
| 608 |
try: |
| 609 |
source = os.readlink(source_path) |
| 610 |
return source, source_path |
| 611 |
except OSError: |
| 612 |
alt_source_path = Path( |
| 613 |
Path(run_dir).parent, |
| 614 |
WorkflowFiles.Install.DIRNAME, |
| 615 |
WorkflowFiles.Install.SOURCE) |
| 616 |
try: |
| 617 |
source = os.readlink(alt_source_path) |
| 618 |
return source, alt_source_path |
| 619 |
except OSError: |
| 620 |
return None, None |
| 621 |
|
| 622 |
|
| 623 |
def get_workflow_srv_dir(id_): |
| 624 |
"""Return service directory of a workflow.""" |
| 625 |
run_d = os.getenv("CYLC_WORKFLOW_RUN_DIR") |
| 626 |
if ( |
| 627 |
not run_d |
| 628 |
or os.getenv("CYLC_WORKFLOW_ID") != id_ |
| 629 |
or os.getenv("CYLC_WORKFLOW_OWNER") != get_user() |
| 630 |
): |
| 631 |
run_d = get_workflow_run_dir(id_) |
| 632 |
return os.path.join(run_d, WorkflowFiles.Service.DIRNAME) |
| 633 |
|
| 634 |
|
| 635 |
def refresh_nfs_cache(path: Path): |
| 636 |
"""Refresh NFS cache for dirs between ~/cylc-run and <path> inclusive. |
| 637 |
|
| 638 |
On NFS filesystems, the non-existence of files/directories may become |
| 639 |
cashed. To work around this, we can list the contents of these directories |
| 640 |
which refreshes the NFS cache. |
| 641 |
|
| 642 |
See: https://github.com/cylc/cylc-flow/issues/6506 |
| 643 |
|
| 644 |
Arguments: |
| 645 |
path: The directory to refresh. |
| 646 |
|
| 647 |
Raises: |
| 648 |
FileNotFoundError: If any of the directories between ~/cylc-run and |
| 649 |
this directory (inclsive) are not present. |
| 650 |
|
| 651 |
""" |
| 652 |
cylc_run_dir = get_cylc_run_dir() |
| 653 |
for subdir in reversed(path.relative_to(cylc_run_dir).parents): |
| 654 |
deque((cylc_run_dir / subdir).iterdir(), maxlen=0) |
| 655 |
|
| 656 |
|
| 657 |
def load_contact_file(id_: str, run_dir=None) -> Dict[str, str]: |
| 658 |
if not run_dir: |
| 659 |
path = Path(get_contact_file_path(id_)) |
| 660 |
else: |
| 661 |
path = Path( |
| 662 |
run_dir, |
| 663 |
WorkflowFiles.Service.DIRNAME, |
| 664 |
WorkflowFiles.Service.CONTACT |
| 665 |
) |
| 666 |
|
| 667 |
if not path.exists(): |
| 668 |
# work around NFS caching issues |
| 669 |
try: |
| 670 |
refresh_nfs_cache(path) |
| 671 |
except FileNotFoundError as exc: |
| 672 |
raise ServiceFileError("Couldn't load contact file") from exc |
| 673 |
|
| 674 |
try: |
| 675 |
with open(path) as f: |
| 676 |
file_content = f.read() |
| 677 |
except IOError as exc: |
| 678 |
raise ServiceFileError("Couldn't load contact file") from exc |
| 679 |
data: Dict[str, str] = {} |
| 680 |
for line in file_content.splitlines(): |
| 681 |
key, value = [item.strip() for item in line.split("=", 1)] |
| 682 |
# BACK COMPAT: contact pre "suite" to "workflow" conversion. |
| 683 |
# from: |
| 684 |
# Cylc 8 |
| 685 |
# remove at: |
| 686 |
# Cylc 8.x |
| 687 |
data[key.replace('SUITE', 'WORKFLOW')] = value |
| 688 |
return data |
| 689 |
|
| 690 |
|
| 691 |
load_contact_file_async = make_async(load_contact_file) |
| 692 |
|
| 693 |
|
| 694 |
def register( |
| 695 |
workflow_name: str, source: Optional[str] = None |
| 696 |
) -> str: |
| 697 |
"""Set up workflow. |
| 698 |
This completes some of the set up completed by cylc install. |
| 699 |
Called only if running a workflow that has not been installed. |
| 700 |
|
| 701 |
Validates workflow name. |
| 702 |
Validates run directory structure. |
| 703 |
Creates symlinks for localhost symlink dirs. |
| 704 |
Symlinks flow.cylc -> suite.rc. |
| 705 |
Creates the .service directory. |
| 706 |
|
| 707 |
Args: |
| 708 |
workflow_name: workflow name. |
| 709 |
source: directory location of flow.cylc file, default $PWD. |
| 710 |
|
| 711 |
Return: |
| 712 |
The installed workflow name (which may be computed here). |
| 713 |
|
| 714 |
Raise: |
| 715 |
WorkflowFilesError: |
| 716 |
- No flow.cylc or suite.rc file found in source location. |
| 717 |
- Illegal name (can look like a relative path, but not absolute). |
| 718 |
- Nested workflow run directories. |
| 719 |
""" |
| 720 |
validate_workflow_name(workflow_name) |
| 721 |
if source is not None: |
| 722 |
if os.path.basename(source) == WorkflowFiles.FLOW_FILE: |
| 723 |
source = os.path.dirname(source) |
| 724 |
else: |
| 725 |
source = os.getcwd() |
| 726 |
# flow.cylc must exist so we can detect accidentally reversed args. |
| 727 |
source = os.path.abspath(source) |
| 728 |
check_flow_file(source) |
| 729 |
if not is_installed(get_workflow_run_dir(workflow_name)): |
| 730 |
symlinks_created = make_localhost_symlinks( |
| 731 |
get_workflow_run_dir(workflow_name), workflow_name) |
| 732 |
if symlinks_created: |
| 733 |
for target, symlink in symlinks_created.items(): |
| 734 |
LOG.info(f"Symlink created: {symlink} -> {target}") |
| 735 |
# Create service dir if necessary. |
| 736 |
srv_d = get_workflow_srv_dir(workflow_name) |
| 737 |
os.makedirs(srv_d, exist_ok=True) |
| 738 |
return workflow_name |
| 739 |
|
| 740 |
|
| 741 |
def is_installed(rund: Union[Path, str]) -> bool: |
| 742 |
"""Check to see if the path sent contains installed flow. |
| 743 |
|
| 744 |
Checks for valid _cylc-install directory in the two possible locations in |
| 745 |
relation to the run directory. |
| 746 |
|
| 747 |
Args: |
| 748 |
rund: run directory path to check |
| 749 |
|
| 750 |
Returns: |
| 751 |
bool: True if rund belongs to an installed workflow |
| 752 |
""" |
| 753 |
rund = Path(rund) |
| 754 |
cylc_install_dir = Path(rund, WorkflowFiles.Install.DIRNAME) |
| 755 |
alt_cylc_install_dir = Path(rund.parent, WorkflowFiles.Install.DIRNAME) |
| 756 |
return cylc_install_dir.is_dir() or alt_cylc_install_dir.is_dir() |
| 757 |
|
| 758 |
|
| 759 |
def get_symlink_dirs(id_: str, run_dir: Union[Path, str]) -> Dict[str, Path]: |
| 760 |
"""Return the standard symlink dirs and their targets if they exist in |
| 761 |
the workflow run dir. |
| 762 |
|
| 763 |
Note: does not check the global config, only the existing run dir filetree. |
| 764 |
|
| 765 |
Raises WorkflowFilesError if a symlink points to an unexpected place. |
| 766 |
""" |
| 767 |
ret: Dict[str, Path] = {} |
| 768 |
for _dir in sorted(WorkflowFiles.SYMLINK_DIRS, reverse=True): |
| 769 |
# ordered by deepest to shallowest |
| 770 |
path = Path(run_dir, _dir) |
| 771 |
if path.is_symlink(): |
| 772 |
target = path.resolve() |
| 773 |
if target.exists() and not target.is_dir(): |
| 774 |
raise WorkflowFilesError( |
| 775 |
f'Invalid symlink at {path}.\n' |
| 776 |
f'Link target is not a directory: {target}') |
| 777 |
expected_end = str(Path('cylc-run', id_, _dir)) |
| 778 |
if not str(target).endswith(expected_end): |
| 779 |
raise WorkflowFilesError( |
| 780 |
f'Invalid symlink at {path}\n' |
| 781 |
f'The target should end with "{expected_end}"' |
| 782 |
) |
| 783 |
ret[_dir] = target |
| 784 |
return ret |
| 785 |
|
| 786 |
|
| 787 |
def remove_keys_on_server(keys): |
| 788 |
"""Removes server-held authentication keys""" |
| 789 |
# WARNING, DESTRUCTIVE. Removes old keys if they already exist. |
| 790 |
for k in keys.values(): |
| 791 |
if os.path.exists(k.full_key_path): |
| 792 |
os.remove(k.full_key_path) |
| 793 |
# Remove client public key folder |
| 794 |
client_public_key_dir = keys["client_public_key"].key_path |
| 795 |
if os.path.exists(client_public_key_dir): |
| 796 |
shutil.rmtree(client_public_key_dir, onerror=handle_rmtree_err) |
| 797 |
|
| 798 |
|
| 799 |
def create_server_keys(keys, workflow_srv_dir): |
| 800 |
"""Create or renew authentication keys for workflow 'id_' in the .service |
| 801 |
directory. |
| 802 |
Generate a pair of ZMQ authentication keys""" |
| 803 |
import zmq.auth |
| 804 |
|
| 805 |
# ZMQ keys generated in .service directory. |
| 806 |
# .service/client_public_keys will store client public keys generated on |
| 807 |
# platform and sent back. |
| 808 |
# ZMQ keys need to be created with stricter file permissions, changing |
| 809 |
# umask default denials. |
| 810 |
os.makedirs(keys["client_public_key"].key_path, exist_ok=True) |
| 811 |
old_umask = os.umask(0o177) # u=rw only set as default for file creation |
| 812 |
_server_public_full_key_path, _server_private_full_key_path = ( |
| 813 |
zmq.auth.create_certificates( |
| 814 |
workflow_srv_dir, |
| 815 |
KeyOwner.SERVER.value)) |
| 816 |
|
| 817 |
# cylc scan requires host to behave as a client, so copy public server |
| 818 |
# key into client public key folder |
| 819 |
server_pub_in_client_folder = keys["client_public_key"].full_key_path |
| 820 |
client_host_private_key = keys["client_private_key"].full_key_path |
| 821 |
shutil.copyfile(_server_private_full_key_path, client_host_private_key) |
| 822 |
shutil.copyfile(_server_public_full_key_path, server_pub_in_client_folder) |
| 823 |
# Return file permissions to default settings. |
| 824 |
os.umask(old_umask) |
| 825 |
|
| 826 |
|
| 827 |
def get_workflow_title(id_): |
| 828 |
"""Return the the workflow title without a full file parse |
| 829 |
|
| 830 |
Limitations: |
| 831 |
* 1st line of title only. |
| 832 |
* Assume title is not in an include-file. |
| 833 |
""" |
| 834 |
title = NO_TITLE |
| 835 |
with open(get_flow_file(id_), 'r') as handle: |
| 836 |
for line in handle: |
| 837 |
if line.lstrip().startswith("[meta]"): |
| 838 |
# continue : title comes inside [meta] section |
| 839 |
continue |
| 840 |
elif line.lstrip().startswith("["): |
| 841 |
# abort: title comes before first [section] |
| 842 |
break |
| 843 |
match = REC_TITLE.match(line) |
| 844 |
if match: |
| 845 |
title = match.groups()[0].strip('"\'') |
| 846 |
return title |
| 847 |
|
| 848 |
|
| 849 |
def check_deprecation(path, warn=True, force_compat_mode=False): |
| 850 |
"""Warn and turn on back-compat flag if Cylc 7 suite.rc detected. |
| 851 |
|
| 852 |
Path can point to config file or parent directory (i.e. workflow name). |
| 853 |
|
| 854 |
Args: |
| 855 |
warn: |
| 856 |
If True, then a warning will be logged when compatibility |
| 857 |
mode is activated. |
| 858 |
force_compat_mode: |
| 859 |
If True, forces Cylc to use compatibility mode |
| 860 |
overriding compatibility mode checks. |
| 861 |
See https://github.com/cylc/cylc-rose/issues/319 |
| 862 |
""" |
| 863 |
if ( |
| 864 |
# Don't want to log if it's already been set True. |
| 865 |
not cylc.flow.flags.cylc7_back_compat |
| 866 |
and ( |
| 867 |
path.resolve().name == WorkflowFiles.SUITE_RC |
| 868 |
or (path / WorkflowFiles.SUITE_RC).is_file() |
| 869 |
or force_compat_mode |
| 870 |
) |
| 871 |
): |
| 872 |
cylc.flow.flags.cylc7_back_compat = True |
| 873 |
if warn: |
| 874 |
LOG.warning(SUITERC_DEPR_MSG) |
| 875 |
|
| 876 |
|
| 877 |
def validate_workflow_name( |
| 878 |
name: str, check_reserved_names: bool = False |
| 879 |
) -> None: |
| 880 |
"""Check workflow name/ID is valid and not an absolute path. |
| 881 |
|
| 882 |
Args: |
| 883 |
name: Workflow name or ID. |
| 884 |
check_reserved_names: If True, check that the name does not |
| 885 |
contain reserved dir names. |
| 886 |
|
| 887 |
Raise WorkflowFilesError if not valid. |
| 888 |
""" |
| 889 |
is_valid, message = WorkflowNameValidator.validate(name) |
| 890 |
if not is_valid: |
| 891 |
raise WorkflowFilesError( |
| 892 |
f"invalid workflow name '{name}' - {message}" |
| 893 |
) |
| 894 |
if os.path.isabs(name): |
| 895 |
raise WorkflowFilesError( |
| 896 |
f"workflow name cannot be an absolute path: {name}" |
| 897 |
) |
| 898 |
name = os.path.normpath(name) |
| 899 |
if name.startswith(os.curdir): |
| 900 |
raise WorkflowFilesError( |
| 901 |
"Workflow name cannot be a path that points to the cylc-run " |
| 902 |
"directory or above" |
| 903 |
) |
| 904 |
if check_reserved_names: |
| 905 |
check_reserved_dir_names(name) |
| 906 |
|
| 907 |
|
| 908 |
def check_reserved_dir_names(name: Union[Path, str]) -> None: |
| 909 |
"""Check workflow/run name does not contain reserved dir names.""" |
| 910 |
err_msg = ( |
| 911 |
"Workflow/run name cannot contain a directory named '{}' " |
| 912 |
"(that filename is reserved)" |
| 913 |
) |
| 914 |
for dir_name in Path(name).parts: |
| 915 |
if dir_name in WorkflowFiles.RESERVED_NAMES: |
| 916 |
raise WorkflowFilesError(err_msg.format(dir_name)) |
| 917 |
if re.match(r'^run\d+$', dir_name): |
| 918 |
raise WorkflowFilesError(err_msg.format('run<number>')) |
| 919 |
|
| 920 |
|
| 921 |
def infer_latest_run_from_id( |
| 922 |
workflow_id: str, alt_run_dir: Optional[str] = None |
| 923 |
) -> str: |
| 924 |
"""Wrapper to make the workflow run-dir absolute.""" |
| 925 |
if alt_run_dir is not None: |
| 926 |
run_dir = Path(get_alt_workflow_run_dir(alt_run_dir, workflow_id)) |
| 927 |
else: |
| 928 |
run_dir = Path(get_workflow_run_dir(workflow_id)) |
| 929 |
_, id_ = infer_latest_run(run_dir, alt_run_dir=alt_run_dir) |
| 930 |
return id_ |
| 931 |
|
| 932 |
|
| 933 |
def infer_latest_run( |
| 934 |
path: Path, |
| 935 |
implicit_runN: bool = True, |
| 936 |
warn_runN: bool = True, |
| 937 |
alt_run_dir: Optional[str] = None, |
| 938 |
) -> Tuple[Path, str]: |
| 939 |
"""Infer the numbered run dir if the workflow has a runN symlink. |
| 940 |
|
| 941 |
Args: |
| 942 |
path: Absolute path to the workflow dir, run dir or runN dir. |
| 943 |
implicit_runN: If True, add runN on the end of the path if the path |
| 944 |
doesn't include it. |
| 945 |
warn_runN: If True, warn that explicit use of runN is unnecessary. |
| 946 |
alt_run_dir: Path to alternate cylc-run location (e.g. for other user). |
| 947 |
|
| 948 |
Returns: |
| 949 |
path: Absolute path of the numbered run dir if applicable, otherwise |
| 950 |
the input arg path. |
| 951 |
id_: The workflow name (including the numbered run if applicable). |
| 952 |
|
| 953 |
Raises: |
| 954 |
- WorkflowFilesError if the runN symlink is not valid. |
| 955 |
- InputError if the path does not exist. |
| 956 |
""" |
| 957 |
cylc_run_dir = get_cylc_run_dir(alt_run_dir) |
| 958 |
try: |
| 959 |
id_ = str(path.relative_to(cylc_run_dir)) |
| 960 |
except ValueError: |
| 961 |
raise ValueError(f"{path} is not in the cylc-run directory") from None |
| 962 |
|
| 963 |
if not path.exists(): |
| 964 |
# work around NFS caching issues |
| 965 |
with suppress(FileNotFoundError): |
| 966 |
refresh_nfs_cache(path) |
| 967 |
|
| 968 |
if not path.exists(): |
| 969 |
raise InputError( |
| 970 |
f'Workflow ID not found: {id_}\n(Directory not found: {path})' |
| 971 |
) |
| 972 |
|
| 973 |
if path.name == WorkflowFiles.RUN_N: |
| 974 |
runN_path = path |
| 975 |
if warn_runN: |
| 976 |
LOG.warning( |
| 977 |
f"You do not need to include {WorkflowFiles.RUN_N} in the " |
| 978 |
"workflow ID; Cylc will select the latest run if just the " |
| 979 |
"workflow name is used" |
| 980 |
) |
| 981 |
elif implicit_runN: |
| 982 |
runN_path = path / WorkflowFiles.RUN_N |
| 983 |
if not os.path.lexists(runN_path): |
| 984 |
return (path, id_) |
| 985 |
else: |
| 986 |
return (path, id_) |
| 987 |
if not runN_path.is_symlink() or not runN_path.is_dir(): |
| 988 |
raise WorkflowFilesError( |
| 989 |
f"{runN_path} symlink not valid" |
| 990 |
) |
| 991 |
numbered_run = os.readlink(runN_path) |
| 992 |
if not re.match(r'run\d+$', numbered_run): |
| 993 |
# Note: the link should be relative. This means it won't work for |
| 994 |
# cylc 8.0b1 workflows where it was absolute (won't fix). |
| 995 |
raise WorkflowFilesError( |
| 996 |
f"{runN_path} symlink target not valid: {numbered_run}" |
| 997 |
) |
| 998 |
path = runN_path.parent / numbered_run |
| 999 |
id_ = str(path.relative_to(cylc_run_dir)) |
| 1000 |
return (path, id_) |
| 1001 |
|
| 1002 |
|
| 1003 |
def is_valid_run_dir(path: Union[Path, str]) -> bool: |
| 1004 |
"""Return True if path is a valid, existing run directory, else False. |
| 1005 |
|
| 1006 |
Args: |
| 1007 |
path: if this is a relative path, it is taken to be relative to |
| 1008 |
the cylc-run directory. |
| 1009 |
""" |
| 1010 |
path = get_cylc_run_abs_path(path) |
| 1011 |
return ( |
| 1012 |
Path(path, WorkflowFiles.FLOW_FILE).is_file() or |
| 1013 |
Path(path, WorkflowFiles.SUITE_RC).is_file() or |
| 1014 |
Path(path, WorkflowFiles.Service.DIRNAME).is_dir() |
| 1015 |
) |
| 1016 |
|
| 1017 |
|
| 1018 |
def get_cylc_run_abs_path(path: Union[Path, str]) -> Union[Path, str]: |
| 1019 |
"""Return the absolute path under the cylc-run directory for the specified |
| 1020 |
relative path. |
| 1021 |
|
| 1022 |
If the specified path is already absolute, just return it. |
| 1023 |
The path need not exist. |
| 1024 |
""" |
| 1025 |
if os.path.isabs(path): |
| 1026 |
return path |
| 1027 |
return get_workflow_run_dir(path) |
| 1028 |
|
| 1029 |
|
| 1030 |
def detect_both_flow_and_suite(path: Path) -> None: |
| 1031 |
"""Detects if both suite.rc and flow.cylc are in directory. |
| 1032 |
|
| 1033 |
Permits flow.cylc to be a symlink. |
| 1034 |
Return true if present, raises error if flow.cylc path sent is a forbidden |
| 1035 |
symlink. |
| 1036 |
Raises: |
| 1037 |
WorkflowFilesError: If both flow.cylc and suite.rc are in directory |
| 1038 |
""" |
| 1039 |
flow_cylc = None |
| 1040 |
msg = (f"Both {WorkflowFiles.FLOW_FILE} and {WorkflowFiles.SUITE_RC} " |
| 1041 |
f"files are present in {path}. Please remove one and" |
| 1042 |
" try again. For more information visit: https://cylc.github.io/" |
| 1043 |
"cylc-doc/stable/html/7-to-8/summary.html#backward-compatibility") |
| 1044 |
if path.resolve().name == WorkflowFiles.SUITE_RC: |
| 1045 |
flow_cylc = path.parent / WorkflowFiles.FLOW_FILE |
| 1046 |
elif (path / WorkflowFiles.SUITE_RC).is_file(): |
| 1047 |
flow_cylc = path / WorkflowFiles.FLOW_FILE |
| 1048 |
if flow_cylc and flow_cylc.is_file() and is_forbidden(flow_cylc): |
| 1049 |
raise WorkflowFilesError(msg) |
| 1050 |
|
| 1051 |
|
| 1052 |
def is_forbidden(flow_file: Path) -> bool: |
| 1053 |
"""Returns True for a forbidden file structure scenario. |
| 1054 |
|
| 1055 |
Forbidden criteria: |
| 1056 |
A symlink elsewhere on file system but suite.rc also exists in the |
| 1057 |
directory. |
| 1058 |
flow.cylc and suite.rc in same directory but no symlink |
| 1059 |
Args: |
| 1060 |
flow_file : Absolute Path to the flow.cylc file |
| 1061 |
""" |
| 1062 |
if not flow_file.is_symlink(): |
| 1063 |
if flow_file.parent.joinpath(WorkflowFiles.SUITE_RC).exists(): |
| 1064 |
return True |
| 1065 |
return False |
| 1066 |
link = flow_file.resolve() |
| 1067 |
suite_rc = flow_file.parent.resolve() / WorkflowFiles.SUITE_RC |
| 1068 |
if link == suite_rc: |
| 1069 |
# link points within dir to suite.rc (permitted) |
| 1070 |
return False |
| 1071 |
# link points elsewhere, check that suite.rc does not also exist in dir |
| 1072 |
if suite_rc.exists(): |
| 1073 |
return True |
| 1074 |
return False |
| 1075 |
|
| 1076 |
|
| 1077 |
def check_flow_file(path: Union[Path, str]) -> Path: |
| 1078 |
"""Checks the path for a suite.rc or flow.cylc file. |
| 1079 |
|
| 1080 |
Raises: |
| 1081 |
WorkflowFilesError |
| 1082 |
- if no flow file in path sent |
| 1083 |
- both suite.rc and flow.cylc in path sent. |
| 1084 |
|
| 1085 |
Args: |
| 1086 |
path: Absolute path to check for a flow.cylc and/or suite.rc file. |
| 1087 |
|
| 1088 |
Returns the path of the flow file if present. |
| 1089 |
""" |
| 1090 |
flow_file_path = Path(expand_path(path), WorkflowFiles.FLOW_FILE) |
| 1091 |
suite_rc_path = Path(expand_path(path), WorkflowFiles.SUITE_RC) |
| 1092 |
if flow_file_path.is_file(): |
| 1093 |
detect_both_flow_and_suite(Path(path)) |
| 1094 |
return flow_file_path |
| 1095 |
if suite_rc_path.is_file(): |
| 1096 |
return suite_rc_path |
| 1097 |
raise WorkflowFilesError(NO_FLOW_FILE_MSG.format(path)) |
| 1098 |
|
| 1099 |
|
| 1100 |
def abort_if_flow_file_in_path(source: Path) -> None: |
| 1101 |
"""Raise an exception if a flow file is found in a source path. |
| 1102 |
|
| 1103 |
This allows us to avoid seemingly silly warnings that "path/flow.cylc" |
| 1104 |
is not a valid workflow ID, when "path" is valid and the user was just |
| 1105 |
(erroneously) trying to (e.g.) validate the config file directly. |
| 1106 |
|
| 1107 |
""" |
| 1108 |
if source.name in {WorkflowFiles.FLOW_FILE, WorkflowFiles.SUITE_RC}: |
| 1109 |
raise InputError( |
| 1110 |
f"Not a valid workflow ID or source directory: {source}" |
| 1111 |
f"\n(Note you should not include {source.name}" |
| 1112 |
" in the workflow source path)" |
| 1113 |
) |