Debian Codegraph @

cylc/flow/platforms.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 #
17 """Functions relating to (job) platforms."""
18
19 from copy import deepcopy
20 import random
21 import re
22 from typing import (
23 TYPE_CHECKING,
24 Any,
25 Dict,
26 Iterable,
27 List,
28 Optional,
29 Set,
30 Union,
31 overload,
32 )
33
34 from cylc.flow import LOG
35 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
36 from cylc.flow.exceptions import (
37 CylcError,
38 GlobalConfigError,
39 NoHostsError,
40 NoPlatformsError,
41 PlatformLookupError,
42 )
43 from cylc.flow.hostuserutil import is_remote_host
44 from cylc.flow.run_modes import JOBLESS_MODES
45
46
47 if TYPE_CHECKING:
48 from cylc.flow.parsec.OrderedDict import OrderedDictWithDefaults
49
50 UNKNOWN_TASK = 'unknown task'
51
52 FORBIDDEN_WITH_PLATFORM: Dict[str, Dict[str, Set[Optional[str]]]] = {
53 'remote': {
54 # setting: exclusions
55 'host': {'localhost', None},
56 'retrieve job logs': {None},
57 'retrieve job logs max size': {None},
58 'retrieve job logs retry delays': {None},
59 },
60 'job': {
61 'batch system': {None},
62 'batch submit command template': {None}
63 }
64 }
65
66 DEFAULT_JOB_RUNNER = 'background'
67 SINGLE_HOST_JOB_RUNNERS = ['background', 'at']
68
69 # Regex to check whether a string is a command
70 HOST_REC_COMMAND = re.compile(r'(`|\$\()\s*(.*)\s*([`)])$')
71 PLATFORM_REC_COMMAND = re.compile(r'(\$\()\s*(.*)\s*(\))')
72
73 HOST_SELECTION_METHODS = {
74 'definition order': lambda goodhosts: goodhosts[0],
75 'random': random.choice
76 }
77
78
79 def log_platform_event(
80 event: str,
81 platform: dict,
82 host: Optional[str] = None,
83 level: str = 'info'
84 ):
85 """Log a simple platform event."""
86 # matches cylc.flow.exceptions.PlatformError format
87 getattr(LOG, level)(
88 f'platform: {platform["name"]} - {event}'
89 + (f' (on {host})' if host else '')
90 )
91
92
93 @overload
94 def get_platform(
95 task_conf: Optional[str] = None,
96 task_name: str = UNKNOWN_TASK,
97 bad_hosts: Optional[Set[str]] = None,
98 evaluated_host: Optional[str] = None,
99 ) -> Dict[str, Any]:
100 ...
101
102
103 @overload
104 def get_platform(
105 task_conf: Union[dict, 'OrderedDictWithDefaults'],
106 task_name: str = UNKNOWN_TASK,
107 bad_hosts: Optional[Set[str]] = None,
108 evaluated_host: Optional[str] = None,
109 ) -> Optional[Dict[str, Any]]:
110 ...
111
112
113 # BACK COMPAT: get_platform
114 # At Cylc 8.x remove all Cylc7 upgrade logic.
115 # from:
116 # Cylc8
117 # to:
118 # Cylc8.x
119 # remove at:
120 # Cylc8.x
121 def get_platform(
122 task_conf: Union[str, dict, 'OrderedDictWithDefaults', None] = None,
123 task_name: str = UNKNOWN_TASK,
124 bad_hosts: Optional[Set[str]] = None,
125 evaluated_host: Optional[str] = None,
126 ) -> Optional[Dict[str, Any]]:
127 """Get a platform.
128
129 Looking at a task config this method decides whether to get platform from
130 name, or Cylc7 config items.
131
132 Args:
133 task_conf: If str this is assumed to be the platform name, otherwise
134 this should be a configuration for a task.
135 task_name: Help produce more helpful error messages.
136 bad_hosts: A set of hosts known to be unreachable (had an ssh 255
137 error)
138 evaluated_host: Host name evaluated from platform subshell.
139
140 Returns:
141 platform: A platform definition dictionary. Uses either
142 get_platform() or _platform_name_from_job_info(), but to the
143 user these look the same. This will be None if the platform
144 definition uses a subshell.
145
146 Raises:
147 NoPlatformsError:
148 Platform group has no platforms with usable hosts.
149 This should be caught if this function is used on a raw config,
150 or in any other context where a platform group might be selected.
151 PlatformLookupError:
152 Raised if the name of a platform cannot be selected based on the
153 information given.
154 """
155 if task_conf is None or isinstance(task_conf, str): # noqa: SIM 114
156 # task_conf is a platform name, or get localhost if None
157 return platform_from_name(task_conf, bad_hosts=bad_hosts)
158
159 # NOTE: Do NOT use .get() on OrderedDictWithDefaults -
160 # https://github.com/cylc/cylc-flow/pull/4975
161 if 'platform' in task_conf and task_conf['platform']:
162 # Check whether task has conflicting Cylc7 items.
163 fail_if_platform_and_host_conflict(task_conf, task_name)
164
165 if is_platform_definition_subshell(task_conf['platform']):
166 # Platform definition is using subshell e.g. platform = $(foo);
167 # won't be evaluated until job submit so cannot get or
168 # validate platform
169 return None
170
171 # If platform name exists and doesn't clash with Cylc7 Config items.
172 return platform_from_name(task_conf['platform'], bad_hosts=bad_hosts)
173
174 if get_platform_deprecated_settings(task_conf) == []:
175 # No deprecated items; platform is localhost
176 return platform_from_name()
177
178 # Need to calculate platform
179 # NOTE: Do NOT use .get() on OrderedDictWithDefaults - see above
180 task_job_section = task_conf['job'] if 'job' in task_conf else {}
181 task_remote_section = task_conf['remote'] if 'remote' in task_conf else {}
182 return platform_from_name(
183 _platform_name_from_job_info(
184 glbl_cfg().get(['platforms']),
185 task_job_section,
186 task_remote_section,
187 evaluated_host,
188 ),
189 bad_hosts=bad_hosts,
190 )
191
192
193 def platform_from_name(
194 platform_name: Optional[str] = None,
195 platforms: Optional[Dict[str, Dict[str, Any]]] = None,
196 bad_hosts: Optional[Set[str]] = None
197 ) -> Dict[str, Any]:
198 """
199 Find out which job platform to use given a list of possible platforms and
200 a task platform string.
201
202 Verifies selected platform is present in global.cylc file and returns it,
203 raises error if platform is not in global.cylc or returns 'localhost' if
204 no platform is initially selected.
205
206 Args:
207 platform_name: name of platform to be retrieved.
208 platforms: global.cylc platforms given as a dict.
209 bad_hosts: A set of hosts known to be unreachable (had an ssh 255
210 error)
211
212 Returns:
213 platform: object containing settings for a platform, loaded from
214 Global Config.
215
216 Raises:
217 NoPlatformsError: Platform group has no platforms with usable hosts.
218 """
219 if platforms is None:
220 platforms = glbl_cfg().get(['platforms'])
221 platform_groups = glbl_cfg().get(['platform groups'])
222
223 if platform_name is None:
224 platform_name = 'localhost'
225
226 # The list is reversed to allow user-set platform groups (which are
227 # appended to site set platform groups) to be matched first and override
228 # site defined platform groups.
229 for platform_name_re in reversed(list(platform_groups)):
230 # Platform is member of a group.
231 if re.fullmatch(platform_name_re, platform_name):
232 platform_name = get_platform_from_group(
233 platform_groups[platform_name_re], group_name=platform_name,
234 bad_hosts=bad_hosts
235 )
236 break
237
238 for platform_name_re in platforms:
239 if (
240 # If the platform_name_re contains special regex chars
241 re.escape(platform_name_re) != platform_name_re
242 and re.match(platform_name_re, 'localhost')
243 ):
244 raise PlatformLookupError(
245 'The "localhost" platform cannot be defined using a '
246 'regular expression. See the documentation for '
247 '"global.cylc[platforms][localhost]" for more information.'
248 )
249
250 # The list is reversed to allow user-set platforms (which are appended to
251 # than site set platforms) to be matched first and override site defined
252 # platforms.
253 for platform_name_re in reversed(list(platforms)):
254 # We substitute commas with or without spaces to
255 # allow lists of platforms
256 if re.fullmatch(
257 re.sub(
258 r'\s*(?!{[\s\d]*),(?![\s\d]*})\s*',
259 '|',
260 platform_name_re
261 ),
262 platform_name
263 ):
264 # Deepcopy prevents contaminating platforms with data
265 # from other platforms matching platform_name_re
266 platform_data = deepcopy(platforms[platform_name_re])
267
268 # If hosts are not filled in make remote
269 # hosts the platform name.
270 # Example: `[platforms][workplace_vm_123]<nothing>`
271 # should create a platform where
272 # `hosts = ['workplace_vm_123']`
273 # NOTE: Probably don't use .get() due to OrderedDictWithDefaults -
274 # see https://github.com/cylc/cylc-flow/pull/4975
275 if (
276 'hosts' not in platform_data or
277 not platform_data['hosts']
278 ):
279 platform_data['hosts'] = [platform_name]
280 # Fill in the "private" name field.
281 platform_data['name'] = platform_name
282 return platform_data
283
284 # If platform name in run mode and not otherwise defined:
285 if platform_name in JOBLESS_MODES:
286 platform_data = deepcopy(platforms['localhost'])
287 platform_data['name'] = 'localhost'
288 return platform_data
289
290 raise PlatformLookupError(
291 f"No matching platform \"{platform_name}\" found")
292
293
294 def get_platform_from_group(
295 group: Union[dict, 'OrderedDictWithDefaults'],
296 group_name: str,
297 bad_hosts: Optional[Set[str]] = None
298 ) -> str:
299 """Get platform name from group, according to the selection method.
300
301 Args:
302 group: A platform group dictionary.
303 group_name: Name of the group.
304 bad_hosts: The set of hosts found to be unreachable.
305
306 Returns:
307 Name of platform selected, or False if all hosts on all platforms are
308 in bad_hosts.
309
310 Raises:
311 NoPlatformsError: If there are no platforms with any usable
312 hosts in the platform group.
313
314 TODO: Uses host_selection methods; should also allow custom select methods.
315 """
316 if bad_hosts:
317 platform_names = [
318 platform for platform in group['platforms']
319 if not bad_hosts.issuperset(platform_from_name(platform)['hosts'])
320 ]
321 else:
322 platform_names = group['platforms']
323
324 # If there are no platforms available to be selected:
325 if not platform_names:
326 hosts_consumed = {
327 host
328 for platform in group['platforms']
329 for host in platform_from_name(platform)['hosts']}
330 raise NoPlatformsError(
331 group_name, hosts_consumed)
332
333 # Get the selection method
334 method = group['selection']['method']
335 if method not in HOST_SELECTION_METHODS:
336 raise CylcError(
337 f'\"{method}\" is not a supported platform selection method.'
338 )
339 else:
340 return HOST_SELECTION_METHODS[method](platform_names)
341
342
343 def _platform_name_from_job_info(
344 platforms: Union[dict, 'OrderedDictWithDefaults'],
345 job: Dict[str, Any],
346 remote: Dict[str, Any],
347 evaluated_host: Optional[str] = None,
348 ) -> str:
349 """
350 Find out which job platform to use given a list of possible platforms
351 and the task dictionary with cylc 7 definitions in it.
352
353 (Note: "batch system" (Cylc 7) and "job runner" (Cylc 8)
354 mean the same thing)
355
356 +------------+ Yes +-----------------------+
357 +-----> Tried all +------->+ RAISE |
358 | | platforms? | | PlatformNotFoundError |
359 | +------------+ +-----------------------+
360 | No|
361 | +----------v---+
362 | | Examine next |
363 | | platform |
364 | +--------------+
365 | |
366 | +----------v----------------+
367 | | Do all items other than |
368 +<----+ "host" and "batch system" |
369 | No| match for this plaform |
370 | +---------------------------+
371 | |Yes
372 | +----------v----------------+ No
373 | | Task host is 'localhost'? +--+
374 | +---------------------------+ |
375 | |Yes |
376 | No+----------v----------------+ |
377 | +---+ Task batch system is | |
378 | | | 'background'? | |
379 | | +---------------------------+ |
380 | | |Yes |
381 | | +----------v----------------+ |
382 | | | RETURN 'localhost' | |
383 | | +---------------------------+ |
384 | | |
385 | +-------v-------------+ +--------------v-------+
386 | No| batch systems match | Yes| batch system and |
387 +<---+ and 'localhost' in | +--+ host both match |
388 | | platform hosts? | | +----------------------+
389 +---------------------+ | |No
390 | |Yes | +--------------v-------+
391 | +-------v--------------+ | | batch system match |
392 | | RETURN this platform <-+--+ and regex of platform|
393 | +----------------------+ Yes| name matches host |
394 | +----------------------+
395 | |No
396 +<---------------------------------+
397
398 Args:
399 job: Workflow config [runtime][TASK][job] section.
400 remote: Workflow config [runtime][TASK][remote] section.
401 platforms: Dictionary containing platform definitions.
402 evaluated_host: Host is the result of evaluating a subshell.
403
404 Returns:
405 platform: string representing a platform from the global config.
406
407 Raises:
408 PlatformLookupError:
409 If no matching platform can be a found an error is raised.
410
411 Example:
412 >>> platforms = {
413 ... 'desktop[0-9][0-9]|laptop[0-9][0-9]': {},
414 ... 'sugar': {
415 ... 'hosts': 'localhost',
416 ... 'job runner': 'slurm'
417 ... }
418 ... }
419 >>> job = {'batch system': 'slurm'}
420 >>> remote = {'host': 'localhost'}
421 >>> _platform_name_from_job_info(platforms, job, remote)
422 'sugar'
423 >>> remote = {}
424 >>> _platform_name_from_job_info(platforms, job, remote)
425 'sugar'
426 >>> remote ={'host': 'desktop92'}
427 >>> job = {}
428 >>> _platform_name_from_job_info(platforms, job, remote)
429 'desktop92'
430 """
431
432 # These settings are removed from the incoming dictionaries for special
433 # handling later - we want more than a simple match:
434 # - In the case of "host" we also want a regex match to the platform name
435 # - In the case of "batch system" we want to match the name of the
436 # system/job runner to a platform when host is localhost.
437
438 # NOTE: Do NOT use .get() on OrderedDictWithDefaults -
439 # https://github.com/cylc/cylc-flow/pull/4975
440 if evaluated_host:
441 task_host = evaluated_host
442 elif 'host' in remote and remote['host']:
443 task_host = remote['host']
444 else:
445 task_host = 'localhost'
446 if 'batch system' in job and job['batch system']:
447 task_job_runner = job['batch system']
448 else:
449 # Necessary? Perhaps not if batch system default is 'background'
450 task_job_runner = 'background'
451
452 # Riffle through the platforms looking for a match to our task settings.
453 # reverse dict order so that user config platforms added last are examined
454 # before site config platforms.
455 for platform_name, platform_spec in reversed(list(platforms.items())):
456 # Handle all the items requiring an exact match.
457 # All items other than batch system and host must be an exact match
458 if not generic_items_match(platform_spec, job, remote):
459 continue
460 # We have some special logic to identify whether task host and task
461 # batch system match the platform in question.
462 if (
463 not is_remote_host(task_host) and
464 task_job_runner == 'background'
465 ):
466 return 'localhost'
467
468 elif (
469 'hosts' in platform_spec and
470 task_host in platform_spec['hosts'] and
471 task_job_runner == platform_spec['job runner']
472 ):
473 # If we have localhost with a non-background batch system we
474 # use the batch system to give a sensible guess at the platform
475 return platform_name
476
477 elif (
478 re.fullmatch(platform_name, task_host) and (
479 (
480 task_job_runner == 'background' and
481 'job runner' not in platform_spec
482 ) or
483 task_job_runner == platform_spec['job runner']
484 )
485 ):
486 return task_host
487
488 raise PlatformLookupError('No platform found matching your task')
489
490
491 def generic_items_match(
492 platform_spec: Dict[str, Any],
493 job: Dict[str, Any],
494 remote: Dict[str, Any]
495 ) -> bool:
496 """Checks generic items from job/remote against a platform.
497
498 We carry out extra checks on ``[remote]host`` and ``[job]batch system``
499 but all other set config items must match between a platform and old
500 settings for that platform to match the legacy settings.
501
502 Args:
503 platform_spec: Dictionary of platform spec.
504 job: Dictionary of config spec section ``[runtime][TASK][job]``
505 remote: Dictionary of config spec section ``[runtime][TASK][remote]``
506
507 Returns:
508 Does this platform have generic items (not ``[job]batch system``
509 or ``[remote]host`` which are treated specially) that are the same.
510 """
511 # Don't check Host and batch system - they have their own logic.
512 if 'host' in remote:
513 remote_generic = {
514 k: v for k, v in remote.items()
515 if k != 'host' and v is not None
516 }
517 else:
518 remote_generic = remote
519 if 'batch system' in job:
520 job_generic = {
521 k: v for k, v in job.items()
522 if k != 'batch system' and v is not None
523 }
524 else:
525 job_generic = job
526
527 for task_section in [job_generic, remote_generic]:
528 # Get a set of items actually set in both platform and task_section.
529 shared_items = set(task_section).intersection(set(platform_spec))
530 # If any set items do not match, we can't use this platform.
531 if not all(
532 platform_spec[item] == task_section[item]
533 for item in shared_items
534 ):
535 return False
536 return True
537
538
539 def get_host_from_platform(
540 platform: Dict[str, Any], bad_hosts: Optional[Set[str]] = None
541 ) -> str:
542 """Placeholder for a more sophisticated function which returns a host
543 given a platform dictionary.
544
545 Args:
546 platform: A dict representing a platform.
547 bad_hosts: A set of hosts Cylc knows to be unreachable.
548
549 Returns:
550 hostname: The name of a host.
551
552 Raises:
553 NoHostsError:
554 This error should be caught by caller to prevent workflow shutdown.
555 """
556 # Get list of goodhosts:
557 if bad_hosts:
558 goodhosts = [i for i in platform['hosts'] if i not in bad_hosts]
559 else:
560 goodhosts = platform['hosts']
561
562 # Get the selection method
563 method = platform['selection']['method']
564 if not goodhosts:
565 raise NoHostsError(platform)
566 else:
567 if method not in HOST_SELECTION_METHODS:
568 raise CylcError(
569 f'method \"{method}\" is not a supported host '
570 'selection method.'
571 )
572 else:
573 return HOST_SELECTION_METHODS[method](goodhosts)
574
575
576 def fail_if_platform_and_host_conflict(
577 task_conf: Union[dict, 'OrderedDictWithDefaults'], task_name: str
578 ) -> None:
579 """Raise an error if [runtime][<task>] spec contains platform and
580 forbidden host items.
581
582 Args:
583 task_conf: A specification to be checked.
584 task_name: A name to be given in an error.
585
586 Raises:
587 PlatformLookupError - if platform and host items conflict
588
589 """
590 # NOTE: Do NOT use .get() on OrderedDictWithDefaults -
591 # https://github.com/cylc/cylc-flow/pull/4975
592 if 'platform' in task_conf and task_conf['platform']:
593 fail_items = [
594 f'\n * [{section}]{key}'
595 for section, settings in FORBIDDEN_WITH_PLATFORM.items()
596 if section in task_conf
597 for key in settings.keys()
598 if (
599 key in task_conf[section] and
600 task_conf[section][key] is not None
601 )
602 ]
603 if fail_items:
604 raise PlatformLookupError(
605 f"Task '{task_name}' has the following deprecated '[runtime]' "
606 "setting(s) which cannot be used with "
607 f"'platform = {task_conf['platform']}':{''.join(fail_items)}"
608 )
609
610
611 def get_platform_deprecated_settings(
612 task_conf: Union[dict, 'OrderedDictWithDefaults'],
613 task_name: str = UNKNOWN_TASK
614 ) -> List[str]:
615 """Return deprecated [runtime][<task_name>] settings that should be
616 upgraded to platforms.
617
618 Args:
619 task_conf: Runtime configuration for the task.
620 task_name: The task name.
621 """
622 return [
623 f'[runtime][{task_name}][{section}]{key} = {task_conf[section][key]}'
624 for section, keys in FORBIDDEN_WITH_PLATFORM.items()
625 if section in task_conf
626 for key, exclusions in keys.items()
627 if (
628 key in task_conf[section] and
629 task_conf[section][key] not in exclusions
630 )
631 ]
632
633
634 def is_platform_definition_subshell(value: str) -> bool:
635 """Is the platform definition using subshell? E.g. platform = $(foo)
636
637 Raise PlatformLookupError if using backticks.
638 """
639 if PLATFORM_REC_COMMAND.match(value):
640 return True
641 if HOST_REC_COMMAND.match(value):
642 raise PlatformLookupError(
643 f"platform = {value}: backticks are not supported; please use $()"
644 )
645 return False
646
647
648 def get_install_target_from_platform(platform: Dict[str, Any]) -> str:
649 """Sets install target to configured or default platform name.
650
651 Returns install target.
652 """
653 if not platform['install target']:
654 platform['install target'] = platform['name']
655
656 return platform['install target']
657
658
659 def get_install_target_to_platforms_map(
660 platform_names: Iterable[str],
661 ) -> dict[str, list[dict[str, Any]]]:
662 """Get a dictionary of unique install targets and the platforms which use
663 them.
664
665 Ignores PlatformLookupErrors.
666
667 Args:
668 platform_names: List of platform names to look up in the global config.
669
670 Return {install_target_1: [platform_1_dict, platform_2_dict, ...], ...}
671 """
672 ret: Dict[str, List[Dict[str, Any]]] = {}
673 for p_name in set(platform_names):
674 try:
675 platform = platform_from_name(p_name)
676 except PlatformLookupError:
677 continue
678 install_target = get_install_target_from_platform(platform)
679 ret.setdefault(install_target, []).append(platform)
680
681 return ret
682
683
684 def is_platform_with_target_in_list(
685 install_target: str,
686 distinct_platforms_list: Iterable[Dict[str, Any]]
687 ) -> bool:
688 """Determines whether install target is in the list of platforms"""
689 return any(
690 install_target == distinct_platform['install target']
691 for distinct_platform in distinct_platforms_list
692 )
693
694
695 def get_localhost_install_target() -> str:
696 """Returns the install target of localhost platform"""
697 localhost = get_platform()
698 return get_install_target_from_platform(localhost)
699
700
701 def _validate_single_host(
702 platforms_cfg: Union[dict, 'OrderedDictWithDefaults']
703 ) -> None:
704 """Check that single-host platforms only specify a single host.
705
706 Some job runners don't work across multiple hosts; the job ID is only valid
707 on the specific submission host.
708 """
709 bad_platforms = []
710 runners = set()
711 name: str
712 config: dict
713 for name, config in platforms_cfg.items():
714 runner = config.get('job runner', DEFAULT_JOB_RUNNER)
715 hosts = config.get('hosts', [])
716 if runner in SINGLE_HOST_JOB_RUNNERS and len(hosts) > 1:
717 bad_platforms.append((name, runner, hosts))
718 runners.add(runner)
719 if bad_platforms:
720 if len(runners) > 1:
721 grammar = ["are", "s"]
722 else:
723 grammar = ["is a", ""]
724 msg = (
725 f"{', '.join(runners)} {grammar[0]} single-host"
726 f" job runner{grammar[1]}:"
727 )
728 for name, runner, hosts in bad_platforms:
729 msg += f'\n * Platform {name} ({runner}) hosts: {", ".join(hosts)}'
730 raise GlobalConfigError(msg)
731
732
733 def validate_platforms(platforms_cfg: Dict[str, Any]) -> None:
734 """Check for invalid or inconsistent platforms config."""
735 _validate_single_host(platforms_cfg)