Debian Codegraph @

cylc/flow/pathutil.py

raw
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 """Functions to return paths to common workflow files and directories."""
17
18 import errno
19 import os
20 from pathlib import Path
21 import re
22 from shutil import rmtree
23 from time import sleep
24 from typing import (
25 Any,
26 Dict,
27 Iterable,
28 Optional,
29 Set,
30 Union,
31 )
32
33 from cylc.flow import LOG
34 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
35 from cylc.flow.exceptions import (
36 FileRemovalError,
37 InputError,
38 WorkflowFilesError,
39 )
40 from cylc.flow.platforms import get_localhost_install_target
41
42
43 # Note: do not import this elsewhere, as it might bypass unit test
44 # monkeypatching:
45 _CYLC_RUN_DIR = os.path.join('$HOME', 'cylc-run')
46
47 EXPLICIT_RELATIVE_PATH_REGEX = re.compile(
48 rf'''
49 ^({re.escape(os.curdir)}|{re.escape(os.pardir)})
50 ({re.escape(os.sep)}|$)
51 ''',
52 re.VERBOSE,
53 )
54 """Matches relative paths that are explicit (starts with ./)"""
55
56 SHELL_ENV_VARS = re.compile(r'\$[^$/]*')
57 SYMLINKABLE_LOCATIONS: Dict[str, str] = {
58 # Location: Version Added
59 'share': '8.0.0',
60 'share/cycle': '8.0.0',
61 'log': '8.0.0',
62 'log/job': '8.4.0',
63 'work': '8.0.0',
64 }
65
66
67 def expand_path(*args: Union[Path, str]) -> str:
68 """Expand both vars and user in path and normalise it, joining any
69 extra args."""
70 return os.path.normpath(
71 os.path.expanduser(os.path.expandvars(os.path.join(*args)))
72 )
73
74
75 def get_remote_workflow_run_dir(
76 workflow_id: Union[Path, str], *args: Union[Path, str]
77 ) -> str:
78 """Return remote workflow run directory, joining any extra args,
79 NOT expanding vars or user."""
80 return os.path.join(_CYLC_RUN_DIR, workflow_id, *args)
81
82
83 def get_remote_workflow_run_job_dir(
84 workflow_id: Union[Path, str], *args: Union[Path, str]
85 ) -> str:
86 """Return remote workflow job log directory, joining any extra args,
87 NOT expanding vars or user."""
88 return get_remote_workflow_run_dir(workflow_id, 'log', 'job', *args)
89
90
91 def get_cylc_run_dir(alt_run_dir: Optional[str] = None) -> str:
92 """Return the cylc-run dir, or alt path, with vars/user expanded."""
93 return expand_path(alt_run_dir or _CYLC_RUN_DIR)
94
95
96 def get_alt_workflow_run_dir(
97 alt_run_dir: Union[Path, str],
98 workflow_id: Union[Path, str],
99 *args: Union[Path, str],
100 ) -> str:
101 """Return alternate workflow run directory.
102
103 Join any extra args, and expand vars and user.
104 Does not check that the directory exists.
105 """
106 return expand_path(alt_run_dir, workflow_id, *args)
107
108
109 def get_workflow_run_dir(
110 workflow_id: Union[Path, str], *args: Union[Path, str]
111 ) -> str:
112 """Return local workflow run directory.
113
114 Join any extra args, and expand vars and user.
115 Does not check that the directory exists.
116 """
117 return expand_path(_CYLC_RUN_DIR, workflow_id, *args)
118
119
120 def get_workflow_run_job_dir(workflow, *args):
121 """Return workflow run job (log) directory, join any extra args."""
122 return get_workflow_run_dir(workflow, 'log', 'job', *args)
123
124
125 def get_workflow_run_scheduler_log_dir(workflow, *args):
126 """Return workflow run log directory, join any extra args."""
127 return get_workflow_run_dir(workflow, 'log', 'scheduler', *args)
128
129
130 def get_workflow_run_scheduler_log_path(workflow):
131 """Return workflow run log file path."""
132 return get_workflow_run_scheduler_log_dir(workflow, 'log')
133
134
135 def get_workflow_file_install_log_dir(workflow, *args):
136 """Return workflow file install log file dir, join any extra args."""
137 return get_workflow_run_dir(workflow, 'log', 'remote-install', *args)
138
139
140 def get_workflow_run_config_log_dir(workflow, *args):
141 """Return workflow run flow.cylc log directory, join any extra args."""
142 return get_workflow_run_dir(workflow, 'log', 'config', *args)
143
144
145 def get_workflow_run_pub_db_path(workflow):
146 """Return workflow run public database file path."""
147 return get_workflow_run_dir(workflow, 'log', 'db')
148
149
150 def get_workflow_run_share_dir(workflow, *args):
151 """Return local workflow work/share directory, join any extra args."""
152 return get_workflow_run_dir(workflow, 'share', *args)
153
154
155 def get_workflow_run_work_dir(workflow, *args):
156 """Return local workflow work/work directory, join any extra args."""
157 return get_workflow_run_dir(workflow, 'work', *args)
158
159
160 def get_workflow_test_log_path(workflow):
161 """Return workflow run ref test log file path."""
162 return get_workflow_run_scheduler_log_dir(workflow, 'reftest.log')
163
164
165 def make_workflow_run_tree(workflow):
166 """Create all top-level cylc-run output dirs on the workflow host."""
167 for dir_ in (
168 get_workflow_run_dir(workflow),
169 get_workflow_run_scheduler_log_dir(workflow),
170 get_workflow_run_job_dir(workflow),
171 get_workflow_run_config_log_dir(workflow),
172 get_workflow_run_share_dir(workflow),
173 get_workflow_run_work_dir(workflow),
174 ):
175 if not Path(dir_).is_dir():
176 os.makedirs(dir_)
177 LOG.debug(f'{dir_}: directory created')
178
179
180 def make_localhost_symlinks(
181 rund: Union[Path, str],
182 named_sub_dir: str,
183 symlink_conf: Optional[Dict[str, Dict[str, str]]] = None,
184 ) -> Dict[str, Union[Path, str]]:
185 """Creates symlinks for any configured symlink dirs from glbl_cfg.
186 Args:
187 rund: the entire run directory path
188 named_sub_dir: e.g workflow_name/run1
189 symlink_conf: Symlinks dirs configuration passed from cli
190
191 Returns:
192 Dictionary of symlinks with sources as keys and
193 destinations as values: ``{target: symlink}``
194
195 """
196 symlinks_created = {}
197 dirs_to_symlink = get_dirs_to_symlink(
198 get_localhost_install_target(),
199 named_sub_dir,
200 symlink_conf=symlink_conf,
201 )
202 for key, value in dirs_to_symlink.items():
203 if value is None:
204 continue
205 if key == 'run':
206 symlink_path = rund
207 else:
208 symlink_path = os.path.join(rund, key)
209 target = expand_path(value)
210 env_vars = SHELL_ENV_VARS.findall(target)
211 if env_vars:
212 raise WorkflowFilesError(
213 f"Can't symlink to {target}\n"
214 "Undefined variables, check "
215 f"global config: {', '.join(env_vars)}"
216 )
217
218 symlink_success = make_symlink_dir(symlink_path, target)
219 # Symlink info returned for logging purposes. Symlinks should be
220 # created before logs as the log dir may be a symlink.
221 if symlink_success:
222 symlinks_created[target] = symlink_path
223 return symlinks_created
224
225
226 def get_dirs_to_symlink(
227 install_target: str,
228 workflow_id: str,
229 symlink_conf: Optional[Dict[str, Dict[str, Any]]] = None,
230 ) -> Dict[str, str]:
231 """Returns dictionary of directories to symlink.
232
233 Note the paths should remain unexpanded, to be expanded on the remote.
234
235 Args:
236 install_target: Symlinks to be created on this install target
237 workflow_id: full id of the run, e.g. myflow/run1
238 symlink_conf: Symlink dirs, if sent on the cli.
239 Defaults to None, in which case global config symlink dirs will
240 be applied.
241
242 Returns:
243 dirs_to_symlink: [directory: symlink_path]
244 """
245 dirs_to_symlink: Dict[str, str] = {}
246 if symlink_conf is None:
247 symlink_conf = glbl_cfg().get(['install', 'symlink dirs'])
248 if install_target not in symlink_conf.keys():
249 return dirs_to_symlink
250 base_dir = symlink_conf[install_target]['run']
251 if base_dir:
252 dirs_to_symlink['run'] = os.path.join(
253 base_dir, 'cylc-run', workflow_id
254 )
255 for dir_ in SYMLINKABLE_LOCATIONS:
256 link = symlink_conf[install_target].get(dir_, None)
257 if (not link) or link == base_dir:
258 continue
259 dirs_to_symlink[dir_] = os.path.join(
260 link, 'cylc-run', workflow_id, dir_
261 )
262 return dirs_to_symlink
263
264
265 def make_symlink_dir(path: Union[Path, str], target: Union[Path, str]) -> bool:
266 """Makes symlinks for directories.
267
268 Args:
269 path: Absolute path of the desired symlink.
270 target: Absolute path of the symlink's target directory.
271
272 Returns True if symlink created, or False if skipped.
273 """
274 path = Path(path)
275 target = Path(target)
276 if path.exists():
277 # note all three checks are needed here due to case where user has set
278 # their own symlink which does not match the global config set one.
279 if path.is_symlink() and target.exists() and path.samefile(target):
280 # correct symlink already exists
281 return False
282 # symlink name is in use by a physical file or directory
283 LOG.warning(
284 f"Path {path} already exists. Cannot create symlink to {target}."
285 )
286 return False
287 elif path.is_symlink():
288 # remove a bad symlink.
289 try:
290 path.unlink()
291 except OSError as exc:
292 raise WorkflowFilesError(
293 f"Failed to remove broken symlink {path}\n{exc}"
294 ) from None
295 try:
296 target.mkdir(parents=True, exist_ok=False)
297 except FileExistsError:
298 raise WorkflowFilesError(
299 f"Symlink dir target already exists: ({path} ->) {target}\n"
300 "Tip: in future, use 'cylc clean' instead of manually deleting "
301 "workflow run dirs."
302 ) from None
303
304 # This is needed in case share and share/cycle have the same symlink dir:
305 if path.exists():
306 return False
307
308 path.parent.mkdir(parents=True, exist_ok=True)
309 try:
310 path.symlink_to(target)
311 return True
312 except OSError as exc:
313 raise WorkflowFilesError(f"Error when symlinking\n{exc}") from None
314
315
316 def remove_dir_and_target(path: Union[Path, str]) -> None:
317 """Delete a directory tree (i.e. including contents), as well as the
318 target directory tree if the specified path is a symlink.
319
320 Args:
321 path: the absolute path of the directory to delete.
322 """
323 if not os.path.isabs(path):
324 raise ValueError('Path must be absolute')
325 if os.path.exists(path) and not os.path.isdir(path):
326 raise NotADirectoryError(path)
327 if os.path.islink(path):
328 if os.path.exists(path):
329 target = os.path.realpath(path)
330 LOG.info(
331 "Removing symlink and its target directory: "
332 f"{path} -> {target}"
333 )
334 _rmtree(target)
335 else:
336 LOG.info(f'Removing broken symlink: {path}')
337 os.remove(path)
338 elif not os.path.exists(path):
339 raise FileNotFoundError(path)
340 else:
341 LOG.info(f'Removing directory: {path}')
342 _rmtree(path)
343
344
345 def _rmtree(
346 target: Union[Path, str],
347 retries: int = 10,
348 sleep_time: float = 1,
349 ):
350 """Make rmtree more robust to nfs issues.
351
352 If a file is deleted which is being held open for reading by
353 another process. NFS will create a ".nfs" file in the
354 containing directory to handle this.
355
356 If you try to delete the directory which contains these
357 files you will get either a ENOTEMPTY or EBUSY error.
358
359 A likely cause of open file handles in cylc-run directories
360 is `cylc cat-log -m t`. If the file being cat-log'ged is removed,
361 the command will fail on its next poll. The default poll
362 interval is one second, so if we wait a couple of seconds and
363 retry the removal it will likely work.
364
365 This command retries removal a specified number
366 of times at a specified interval before failing to
367 give cat-log process a chance to die gracefully and
368 release their filesystem locks. For more info see:
369 https://github.com/cylc/cylc-flow/pull/5359#issuecomment-1479989975
370 """
371 for _try_num in range(retries):
372 try:
373 rmtree(target)
374 return
375 except OSError as exc:
376 if exc.errno in {errno.ENOTEMPTY, errno.EBUSY}:
377 err = exc
378 sleep(sleep_time)
379 else:
380 raise
381 raise FileRemovalError(err)
382
383
384 def remove_dir_or_file(path: Union[Path, str]) -> None:
385 """Delete a directory tree, or a file, or a symlink.
386 Does not follow symlinks.
387
388 Args:
389 path: the absolute path of the directory/file/symlink to delete.
390 """
391 if not os.path.isabs(path):
392 raise ValueError("Path must be absolute")
393 if os.path.islink(path):
394 LOG.info(f"Removing symlink: {path}")
395 os.remove(path)
396 elif os.path.isfile(path):
397 LOG.info(f"Removing file: {path}")
398 os.remove(path)
399 else:
400 LOG.info(f"Removing directory: {path}")
401 _rmtree(path)
402
403
404 def remove_empty_parents(
405 path: Union[Path, str], tail: Union[Path, str]
406 ) -> None:
407 """Work our way up the tail of path, removing empty dirs only.
408
409 Args:
410 path: Absolute path to the directory, e.g. /foo/bar/a/b/c
411 tail: The tail of the path to work our way up, e.g. a/b/c
412
413 Example:
414 remove_empty_parents('/foo/bar/a/b/c', 'a/b/c') would remove
415 /foo/bar/a/b (assuming it's empty), then /foo/bar/a (assuming it's
416 empty).
417 """
418 path = Path(path)
419 if not path.is_absolute():
420 raise ValueError('path must be absolute')
421 tail = Path(tail)
422 if tail.is_absolute():
423 raise ValueError('tail must not be an absolute path')
424 if not str(path).endswith(str(tail)):
425 raise ValueError(f"path '{path}' does not end with '{tail}'")
426 depth = len(tail.parts) - 1
427 for i in range(depth):
428 parent = path.parents[i]
429 if not parent.is_dir():
430 continue
431 try:
432 parent.rmdir()
433 LOG.info(f'Removing directory: {parent}')
434 except OSError:
435 break
436
437
438 def get_next_rundir_number(run_path: Union[str, Path]) -> int:
439 """Return the next run number for a new install.
440
441 Args:
442 run_path: Top level installed workflow dir
443 (often ``~/cylc-run/workflow``).
444
445 """
446 re_runX = re.compile(r'run(\d+)$')
447 run_n_path = Path(os.path.expanduser(os.path.join(run_path, "runN")))
448 if run_n_path.exists() and run_n_path.is_symlink():
449 old_run_path = os.readlink(run_n_path)
450 # Line below could in theory not return a match group, so mypy objects.
451 # This function unlikely to be called in circumstances where this will
452 # be a problem.
453 last_run_num = re_runX.search( # type: ignore
454 old_run_path
455 ).group(1)
456 last_run_num = int(last_run_num)
457 else:
458 # If the ``runN`` symlink has been removed, get next numbered run from
459 # file names:
460 paths = Path(run_path).glob('run[0-9]*')
461 run_numbers = (
462 int(m.group(1))
463 for m in (re_runX.search(i.name) for i in paths)
464 if m
465 )
466 last_run_num = max(run_numbers, default=0)
467
468 return last_run_num + 1
469
470
471 def parse_rm_dirs(rm_dirs: Iterable[str]) -> Set[str]:
472 """Parse a list of possibly colon-separated dirs (or files or globs).
473 Return the set of all the dirs.
474
475 Used by cylc clean with the --rm option.
476 """
477 result: Set[str] = set()
478 for item in rm_dirs:
479 for part in item.split(':'):
480 part = part.strip()
481 if not part:
482 continue
483 is_dir = part.endswith(os.sep)
484 part = os.path.normpath(part)
485 if os.path.isabs(part):
486 raise InputError("--rm option cannot take absolute paths")
487 if (
488 part in {os.curdir, os.pardir}
489 or part.startswith(f"{os.pardir}{os.sep}") # '../'
490 ):
491 raise InputError(
492 "--rm option cannot take paths that point to the "
493 "run directory or above"
494 )
495 if is_dir:
496 # Preserve trailing slash to ensure it only matches dirs,
497 # not files, when globbing
498 part += os.sep
499 result.add(part)
500 return result
501
502
503 def is_relative_to(path1: Union[Path, str], path2: Union[Path, str]) -> bool:
504 """Return whether or not path1 is relative to path2 (including if they are
505 the same path).
506
507 Normalizes both paths to avoid trickery with paths containing `..`
508 somewhere in them.
509 """
510 # In future, we can just use pathlib.Path.is_relative_to()
511 # when Python 3.9 becomes the minimum supported version
512 try:
513 Path(os.path.normpath(path1)).relative_to(os.path.normpath(path2))
514 except ValueError:
515 return False
516 return True
517
518
519 def get_workflow_name_from_id(workflow_id: str) -> str:
520 """Workflow name is the ID shorn of the runN directory name."""
521 cylc_run_dir = Path(get_cylc_run_dir())
522 if Path(workflow_id).is_absolute():
523 # this is a source directory, not an install dir:
524 return workflow_id
525 else:
526 id_path = cylc_run_dir / workflow_id
527 name_path = id_path
528
529 # Look for ``id_path.parent/_cylc_install`` first because expected to
530 # be most common:
531 if (id_path.parent / '_cylc-install').is_dir():
532 name_path = Path(id_path).parent
533 elif (id_path / '_cylc-install').is_dir():
534 name_path = id_path
535
536 return str(name_path.relative_to(cylc_run_dir))