Debian Codegraph @

cylc/flow/cfgspec/globalcfg.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 """Cylc site and user configuration file spec."""
17
18 from contextlib import suppress
19 import os
20 from pathlib import Path
21 from sys import stderr
22 from textwrap import (
23 dedent,
24 indent,
25 )
26 from typing import (
27 Any,
28 Dict,
29 List,
30 Optional,
31 Tuple,
32 Union,
33 )
34
35 from packaging.version import Version
36
37 from cylc.flow import (
38 LOG,
39 __version__ as CYLC_VERSION,
40 )
41 from cylc.flow.exceptions import GlobalConfigError
42 from cylc.flow.hostuserutil import get_user_home
43 from cylc.flow.network.client_factory import CommsMeth
44 from cylc.flow.parsec.config import (
45 ConfigNode as Conf,
46 ParsecConfig,
47 )
48 from cylc.flow.parsec.exceptions import (
49 ItemNotFoundError,
50 ParsecError,
51 ValidationError,
52 )
53 from cylc.flow.parsec.upgrade import upgrader
54 from cylc.flow.parsec.util import (
55 expand_many_section,
56 printcfg,
57 )
58 from cylc.flow.parsec.validate import (
59 CylcConfigValidator as VDR,
60 DurationFloat,
61 Range,
62 cylc_config_validate,
63 )
64 from cylc.flow.pathutil import SYMLINKABLE_LOCATIONS
65 from cylc.flow.platforms import validate_platforms
66 from cylc.flow.task_events_mgr import TaskEventsManager as TEM
67 from cylc.flow.workflow_events import WorkflowEventHandler
68
69
70 PLATFORM_REGEX_TEXT = '''
71 Configured names are regular expressions; any match is a valid platform.
72 They are searched from the bottom up, until the first match is found.'''
73
74
75 # Nested dict of spec items.
76 # Spec value is [value_type, default, allowed_2, allowed_3, ...]
77 # where:
78 # - value_type: value type (compulsory).
79 # - default: the default value (optional).
80 # - allowed_2, ...: the only other allowed values of this setting (optional).
81
82 # Standard executable search paths to pass to job submission subprocesses.
83 SYSPATH = [
84 '/bin',
85 '/usr/bin',
86 '/usr/local/bin',
87 '/sbin',
88 '/usr/sbin',
89 '/usr/local/sbin'
90 ]
91
92
93 REPLACES = 'This item was previously called '
94 PLATFORM_REPLACES = (
95 "(Replaces the deprecated setting "
96 ":cylc:conf:`flow.cylc[runtime][<namespace>]{}`.)"
97 )
98
99
100 PLATFORM_META_DESCR = '''
101 Metadata for this platform or platform group.
102
103 Allows writers of platform configurations to add information
104 about platform usage. There are no-preset items because
105 Cylc does not use any platform (or group) metadata internally.
106
107 Users can then see information about defined platforms using::
108
109 cylc config -i [platforms]
110 cylc config -i [platform groups]
111
112 .. seealso::
113
114 :ref:`AdminGuide.PlatformConfigs`
115
116 .. versionadded:: 8.0.0
117 '''
118
119 # ----------------------------------------------------------------------------
120 # Config items shared between global and workflow config:
121 SCHEDULER_DESCR = f'''
122 Settings for the scheduler.
123
124 .. note::
125
126 Not to be confused with :cylc:conf:`flow.cylc[scheduling]`.
127
128 .. versionchanged:: 8.0.0
129
130 {REPLACES}``[cylc]``
131 '''
132
133 UTC_MODE_DESCR = '''
134 If ``True``, UTC will be used as the time zone for timestamps in
135 the logs. If ``False``, the local/system time zone will be used.
136
137 .. seealso::
138
139 To set a time zone for cycle points, see
140 :cylc:conf:`flow.cylc[scheduler]cycle point time zone`.
141 '''
142
143 LOG_RETR_SETTINGS = {
144 'retrieve job logs': dedent('''
145 Whether to retrieve job logs from the job platform.
146 '''),
147 'retrieve job logs command': dedent('''
148 The command used to retrieve job logs from the job platform.
149 '''),
150 'retrieve job logs max size': dedent('''
151 The maximum size of job logs to retrieve.
152
153 Can be anything
154 accepted by the ``--max-size=SIZE`` option of ``rsync``.
155 '''),
156 'retrieve job logs retry delays': dedent('''
157 Configure retries for unsuccessful job log retrieval.
158
159 If there is a significant delay between job completion and
160 logs appearing in their final location (due to the job runner)
161 you can configure time intervals here to delay the first and
162 subsequent retrieval attempts.
163 ''')
164 }
165
166 EVENTS_DESCR = '''
167 Configure the workflow event handling system.
168 '''
169
170 EVENTS_SETTINGS: Dict[str, Union[str, Dict[str, Any]]] = { # workflow events
171 'handlers': '''
172 Configure :term:`event handlers` that run when certain workflow
173 events occur.
174
175 .. admonition:: Not to be confused with
176 :class: tip
177
178 For *task* events, see
179 :cylc:conf:`flow.cylc[runtime][<namespace>][events]`.
180
181 Event handlers can be held in the workflow ``bin/`` directory,
182 otherwise it is up to you to ensure their location is in ``$PATH``
183 (in the shell in which the scheduler runs). They should require
184 little resource to run and return quickly.
185
186 Template variables can be used to configure handlers. For a full list
187 of supported variables see :ref:`workflow_event_template_variables`.
188
189 .. seealso::
190
191 :ref:`user_guide.scheduler.workflow_events`
192 ''',
193 'handler events': {
194 'desc': '''
195 Specify the events for which workflow event handlers should be
196 invoked.
197
198 .. seealso::
199
200 :ref:`user_guide.scheduler.workflow_events.list`
201 ''',
202 'options': WorkflowEventHandler.EVENTS.copy(),
203 'depr_options': WorkflowEventHandler.EVENTS_DEPRECATED.copy(),
204 'warn_options': True,
205 },
206 'mail events': {
207 'desc': '''
208 Specify the workflow events for which notification emails should
209 be sent.
210
211 .. seealso::
212
213 :ref:`user_guide.scheduler.workflow_events.list`
214 ''',
215 'options': WorkflowEventHandler.EVENTS.copy(),
216 'depr_options': WorkflowEventHandler.EVENTS_DEPRECATED.copy(),
217 'warn_options': True,
218 },
219 'startup handlers': f'''
220 Handlers to run at scheduler startup.
221
222 .. seealso::
223
224 :ref:`user_guide.scheduler.workflow_events`
225
226 .. versionchanged:: 8.0.0
227
228 {REPLACES}``startup handler``.
229 ''',
230 'shutdown handlers': f'''
231 Handlers to run at scheduler shutdown.
232
233 .. seealso::
234
235 :ref:`user_guide.scheduler.workflow_events`
236
237 .. versionchanged:: 8.0.0
238
239 {REPLACES}``shutdown handler``.
240 ''',
241 'abort handlers': f'''
242 Handlers to run if the scheduler shuts down with error status due to
243 a configured timeout or a fatal error condition.
244
245 .. seealso::
246
247 :ref:`user_guide.scheduler.workflow_events`
248
249 .. versionchanged:: 8.0.0
250
251 {REPLACES}``aborted handler``.
252 ''',
253 'workflow timeout': '''
254 Workflow timeout interval. The timer starts counting down at scheduler
255 startup. It resets on workflow restart.
256
257 When the workflow timeout is reached, any configured
258 `[..]workflow timeout handlers` will be called. Additionally, the
259 workflow will shut down if `[..]abort on workflow timeout` is set.
260
261 .. seealso::
262
263 :ref:`user_guide.scheduler.workflow_events`
264
265 .. versionadded:: 8.0.0
266 ''',
267 'workflow timeout handlers': '''
268 Handlers to run if the `[..]workflow timeout` is reached.
269
270 .. seealso::
271
272 :ref:`user_guide.scheduler.workflow_events`
273
274 .. versionadded:: 8.0.0
275 ''',
276 'abort on workflow timeout': '''
277 Whether the scheduler should shut down immediately with error status if
278 the :cylc:conf:`[..]workflow timeout` is reached.
279
280 .. seealso::
281
282 :ref:`user_guide.scheduler.workflow_events`
283
284 .. versionadded:: 8.0.0
285 ''',
286 'stall handlers': f'''
287 Handlers to run if the scheduler stalls.
288
289 .. seealso::
290
291 :ref:`user_guide.scheduler.workflow_events`
292
293 .. versionchanged:: 8.0.0
294
295 {REPLACES}``stalled handler``.
296 ''',
297 'stall timeout': f'''
298 The length of a timer which starts if the scheduler stalls.
299
300 When the stall timeout is reached, any `[..]stall timeout handlers`
301 will be called. Additionally, the workflow will shut down if
302 `[..]abort on stall timeout` is set.
303
304 .. seealso::
305
306 :ref:`user_guide.scheduler.workflow_events`
307
308 .. versionchanged:: 8.0.0
309
310 {REPLACES}``timeout``.
311 ''',
312 'stall timeout handlers': f'''
313 Handlers to run if the `[..]stall timeout` is reached.
314
315 .. seealso::
316
317 :ref:`user_guide.scheduler.workflow_events`
318
319 .. versionchanged:: 8.0.0
320
321 {REPLACES}``timeout handler``.
322 ''',
323 'abort on stall timeout': f'''
324 Whether the scheduler should shut down immediately with error status if
325 the `[..]stall timeout` is reached.
326
327 .. seealso::
328
329 :ref:`user_guide.scheduler.workflow_events`
330
331 .. versionchanged:: 8.0.0
332
333 {REPLACES}``abort on timeout``.
334 ''',
335 'inactivity timeout': f'''
336 Scheduler inactivity timeout interval. The timer resets when any
337 workflow activity occurs.
338
339 When the inactivity timeout is reached, any
340 `[..]inactivity timeout handlers` will be called. Additionally, the
341 workflow will shut down if `[..]abort on inactivity timeout` is set.
342
343 .. seealso::
344
345 :ref:`user_guide.scheduler.workflow_events`
346
347 .. versionchanged:: 8.0.0
348
349 {REPLACES} ``inactivity``.
350 ''',
351 'inactivity timeout handlers': f'''
352 Handlers to run if the `[..]inactivity timeout` is reached.
353
354 .. seealso::
355
356 :ref:`user_guide.scheduler.workflow_events`
357
358 .. versionchanged:: 8.0.0
359
360 {REPLACES}``inactivity handler``.
361 ''',
362 'abort on inactivity timeout': f'''
363 Whether the scheduler should shut down immediately with error status if
364 the `[..]inactivity timeout` is reached.
365
366 .. seealso::
367
368 :ref:`user_guide.scheduler.workflow_events`
369
370 .. versionchanged:: 8.0.0
371
372 {REPLACES}``abort on inactivity``.
373 ''',
374 'restart timeout': '''
375 How long to wait for intervention on restarting a completed workflow.
376
377 When a workflow reaches the end of the :term:`graph`, it will
378 :term:`shut down <shutdown>` automatically. We call such workflows
379 :ref:`completed <workflow completion>` as there are no more tasks for
380 Cylc to run.
381
382 Completed workflows can be caused by:
383
384 * Cylc reaching the end of the :term:`graph`.
385 * The workflow reaching the
386 :cylc:conf:`flow.cylc[scheduling]final cycle point`.
387 * The workflow reaching the
388 :cylc:conf:`flow.cylc[scheduling]stop after cycle point`.
389 * Tasks being manually removed :ref:`interventions.remove_tasks`.
390
391 When you restart a completed workflow, it will detect that there are no
392 more tasks to run, and shut itself down again. The ``restart timeout``
393 delays this shutdown for a configured period allowing you to trigger
394 more task(s) to run.
395
396 .. seealso::
397
398 * :ref:`user_guide.scheduler.workflow_events`
399 * :ref:`workflow completion`
400 * :ref:`examples.extending-workflow`
401
402 .. versionadded:: 8.2.0
403
404 .. versionchanged:: 8.5.2
405
406 The ``restart timeout`` is now also activated for workflows that
407 have hit the
408 :cylc:conf:`flow.cylc[scheduling]stop after cycle point`.
409
410 '''
411 }
412
413 MAIL_DESCR = '''
414 Settings for the scheduler to send event emails.
415
416 These settings are used for both workflow and task events.
417
418 .. versionadded:: 8.0.0
419 '''
420
421 MAIL_FROM_DESCR = f'''
422 Specify an alternative ``from`` email address for workflow event notifications.
423
424 .. versionchanged:: 8.0.0
425
426 {REPLACES}``[cylc][events]mail from``.
427 '''
428
429 MAIL_TO_DESCR = f'''
430 A list of email addresses that event notifications should be sent to.
431
432 .. versionchanged:: 8.0.0
433
434 {REPLACES}``[cylc][events]mail to``.
435 '''
436
437 MAIL_FOOTER_DESCR = f'''
438 Specify a string or string template for footers of emails sent for both
439 workflow and task events.
440
441 Template variables may be used in the mail footer. For a list of supported
442 variables see :ref:`workflow_event_template_variables`.
443
444 Example::
445
446 footer = see http://ahost/%(owner)s/notes/%(workflow)s``
447
448 .. versionchanged:: 8.0.0
449
450 {REPLACES}``[cylc][events]mail footer``.
451 '''
452
453 MAIL_INTERVAL_DESCR = f'''
454 Gather all task event notifications in the given interval into a single email.
455
456 Useful to prevent being overwhelmed by emails.
457
458 .. versionchanged:: 8.0.0
459
460 {REPLACES}``[cylc]task event mail interval``.
461 '''
462
463 MAIN_LOOP_DESCR = '''
464 Configuration of main loop plugins for the scheduler.
465
466 For a list of built in plugins see :ref:`Main Loop Plugins <BuiltInPlugins>`.
467
468 .. versionadded:: 8.0.0
469 '''
470
471 MAIN_LOOP_PLUGIN_DESCR = '''
472 Configure a main loop plugin.
473
474 .. note::
475
476 Only the configured list of
477 :cylc:conf:`global.cylc[scheduler][main loop]plugins`
478 is loaded when a scheduler is started.
479
480 .. versionadded:: 8.0.0
481 '''
482
483 MAIN_LOOP_PLUGIN_INTERVAL_DESCR = '''
484 Interval at which the plugin is invoked.
485
486 .. versionadded:: 8.0.0
487 '''
488
489 DIRECTIVES_DESCR = '''
490 Job runner (batch scheduler) directives.
491
492 Supported for use with job runners:
493
494 - pbs
495 - slurm
496 - loadleveler
497 - lsf
498 - sge
499 - slurm_packjob
500 - moab
501
502 Directives are written to the top of the job script in the correct format
503 for the job runner.
504
505 Specifying directives individually like this allows use of default directives
506 for task families which can be individually overridden at lower levels of the
507 runtime namespace hierarchy.
508 '''
509
510 DIRECTIVES_ITEM_DESCR = '''
511 Example directives for the built-in job runner handlers are shown in
512 :ref:`AvailableMethods`.
513 '''
514
515 SUBMISSION_POLL_DESCR = f'''
516 List of intervals at which to poll status of job submission.
517
518 Cylc can poll submitted jobs to catch problems that prevent the submitted job
519 from executing at all, such as deletion from an external job runner queue.
520
521 The last value is used repeatedly until the task starts running.
522
523 Multipliers can be used as shorthand as in the example below.
524
525 Example::
526
527 5*PT2M, PT5M
528
529 Note that if the polling
530 :cylc:conf:`global.cylc[platforms][<platform name>]communication method`
531 is used then Cylc relies on polling to detect all task state changes,
532 so you may want to configure more frequent polling.
533
534 .. versionchanged:: 8.0.0
535
536 {REPLACES}``[runtime][<namespace>][job]submission polling intervals``.
537 '''
538
539 SUBMISSION_RETY_DESCR = f'''
540 Cylc can automatically resubmit jobs after submission failures.
541
542 Submission retry delays is a list of ISO 8601 durations which tell Cylc
543 how long to wait before the next try.
544
545 The job environment variable ``$CYLC_TASK_SUBMIT_NUMBER`` increments with each
546 job submission attempt.
547
548 Tasks only go to the ``submit-failed`` state if job submission fails with no
549 retries left.
550
551 .. versionchanged:: 8.0.0
552
553 {REPLACES}``[runtime][<namespace>][job]submission retry delays``.
554 '''
555
556 EXECUTION_POLL_DESCR = f'''
557 List of intervals at which to poll status of job execution.
558
559 Cylc can poll running jobs to catch problems that prevent task messages from
560 being sent back to the workflow, such as hard job kills, network outages, or
561 unplanned job host shutdown.
562
563 The last interval in the list is used repeatedly until the job completes.
564
565 Multipliers can be used as shorthand as in the example below.
566
567 Example::
568
569 5*PT2M, PT5M
570
571 Note that if the polling
572 :cylc:conf:`global.cylc[platforms][<platform name>]communication method` is
573 used then Cylc relies on polling to detect all task state changes, so you may
574 want to configure more frequent polling.
575
576 .. versionchanged:: 8.0.0
577
578 {REPLACES}``[runtime][<namespace>][job]execution polling intervals``.
579 '''
580
581 TASK_EVENTS_DESCR = '''
582 Configure the task event handling system.
583
584 .. admonition:: Not to be confused with
585 :class: tip
586
587 For *workflow* events, see :cylc:conf:`flow.cylc[scheduler][events]`.
588
589 Task :term:`event handlers` are scripts to run when task events occur.
590
591 Event handlers can be stored in the workflow ``bin/`` directory, or
592 anywhere the scheduler environment ``$PATH``. They should return quickly.
593
594 Multiple event handlers can be specified as a list of command line templates.
595 For supported template variables see :ref:`user_guide.runtime.\
596 event_handlers.task_event_handling.template_variables`.
597 Python template substitution syntax is used:
598 `String Formatting Operations in the Python documentation
599 <https://docs.python.org/3/library/stdtypes.html
600 #printf-style-string-formatting>`_.
601 '''
602
603 TASK_EVENTS_SETTINGS = {
604 'handlers': '''
605 Commands to run on task :cylc:conf:`[..]handler events`.
606
607 A command or list of commands to run for each task event handler
608 set in
609 :cylc:conf:`flow.cylc[runtime][<namespace>][events]handler events`.
610
611 Information about the event can be provided to the command
612 using :ref:`user_guide.runtime.event_handlers.\
613 task_event_handling.template_variables`.
614 For more information, see
615 :ref:`user_guide.runtime.task_event_handling`.
616
617 Example::
618
619 echo %(event)s occurred in %(workflow)s >> my-log-file
620
621 ''',
622 'handler events': f'''
623 :Options: ``{"``, ``".join(TEM.STD_EVENTS)}`` & any custom event
624
625 A list of events for which :cylc:conf:`[..]handlers` are run.
626
627 See :ref:`user_guide.runtime.task_event_handling.list` for more
628 information on task events.
629
630 Example::
631
632 submission failed, failed
633 ''',
634 'handler retry delays': '''
635 Specify an initial delay before running an event handler command and
636 any retry delays in case the command returns a non-zero code.
637
638 The default behaviour is to run an event handler command once without
639 any delay.
640
641 Example::
642
643 PT10S, PT1M, PT5M
644 ''',
645 'mail events': f'''
646 :Options: ``{"``, ``".join(TEM.STD_EVENTS)}`` & any custom event
647
648 A list of events for which notification emails should be sent.
649
650 See :ref:`user_guide.runtime.task_event_handling.list` for more
651 information on task events.
652
653 Example::
654
655 submission failed, failed
656 ''',
657 'execution timeout': '''
658 If a task has not finished after the specified interval, any configured
659 execution timeout event handler(s) will be called.
660 ''',
661 'submission timeout': '''
662 If a task has not started after the specified interval, any configured
663 submission timeout event handler(s) will be called.
664 '''
665 }
666
667
668 def comma_sep_section_note(version_changed: str = '') -> str:
669 note_text = "This section can be a comma separated list."
670 if version_changed:
671 note_text = (
672 f".. versionchanged:: {version_changed}\n\n" +
673 indent(note_text, 3 * ' ')
674 )
675
676 example = dedent('''
677
678 .. spoiler:: Example
679
680 For example:
681
682 .. code-block:: cylc
683
684 [a, b]
685 setting = x
686 [a]
687 another_setting = y
688
689 Will become:
690
691 .. code-block:: cylc
692
693 [a]
694 setting = x
695 [b]
696 setting = x
697 [a]
698 another_setting = y
699
700 Which will then be combined according to
701 :ref:`the rules for Cylc config syntax<syntax>`.
702
703 ''')
704
705 return "\n\n.. note::\n\n" + indent(note_text + example, 3 * ' ')
706
707
708 # ----------------------------------------------------------------------------
709
710
711 def short_descr(text: str) -> str:
712 r"""Get dedented one-paragraph description from long description.
713
714 Examples:
715 >>> short_descr('foo\n\nbar')
716 'foo'
717
718 >>> short_descr(':Field: Value\n\nfoo\n\nbar')
719 ':Field: Value\n\nfoo'
720
721 """
722 lines = []
723 for line in dedent(text).splitlines():
724 if not line:
725 continue
726 elif line.startswith(':'):
727 lines.append(line)
728 else:
729 lines.append(line)
730 break
731 return '\n\n'.join(lines)
732
733
734 def default_for(
735 text: str, config_path: str, section: bool = False
736 ) -> str:
737 """Return a ":Default For: field for this config.
738
739 Get dedented short description and insert a 'Default(s) For' field
740 that links to this config item's flow.cylc counterpart.
741 """
742 directive = f":Default{'s' if section else ''} For:"
743 return (
744 f"{directive} :cylc:conf:`flow.cylc{config_path}`.\n\n"
745 f"{short_descr(text)}"
746 )
747
748
749 with Conf('global.cylc', desc='''
750 The global configuration which defines default Cylc Flow settings
751 for a user or site.
752
753 To view your global config, run::
754
755 $ cylc config
756
757 Cylc will attempt to load the global configuration (``global.cylc``) from a
758 hierarchy of locations, including the site directory (defaults to
759 ``/etc/cylc/flow/``) and the user directory (``~/.cylc/flow/``). For
760 example at Cylc version 8.0.1, the hierarchy would be, in order of
761 ascending priority:
762
763 .. code-block:: sub
764
765 <site-conf-path>/flow/global.cylc
766 <site-conf-path>/flow/8/global.cylc
767 <site-conf-path>/flow/8.0/global.cylc
768 <site-conf-path>/flow/8.0.1/global.cylc
769 ~/.cylc/flow/global.cylc
770 ~/.cylc/flow/8/global.cylc
771 ~/.cylc/flow/8.0/global.cylc
772 ~/.cylc/flow/8.0.1/global.cylc
773
774 Where ``<site-conf-path>`` is ``/etc/cylc/flow/`` by default but can be
775 changed by :envvar:`CYLC_SITE_CONF_PATH`.
776
777 A setting in a file lower down in the list will override the same setting
778 from those higher up (but if a setting is present in a file higher up and
779 not in any files lower down, it will not be overridden).
780
781 The following environment variables can change the files which are loaded:
782
783 .. envvar:: CYLC_CONF_PATH
784
785 If set this bypasses the default site/user configuration hierarchy used
786 to load the Cylc Flow global configuration.
787
788 This should be set to a directory containing a :cylc:conf:`global.cylc`
789 file.
790
791 .. envvar:: CYLC_SITE_CONF_PATH
792
793 By default the site configuration is located in ``/etc/cylc/``. For
794 installations where this is not convenient, this path can be overridden
795 by setting ``CYLC_SITE_CONF_PATH`` to point at another location.
796
797 Configuration for different Cylc components should be in sub-directories
798 within this location.
799
800 For example to configure Cylc Flow you could do the following::
801
802 $CYLC_SITE_CONF_PATH/
803 `-- flow/
804 `-- global.cylc
805
806 .. note::
807
808 The ``global.cylc`` file can be templated using Jinja2 variables.
809 See :ref:`Jinja`.
810
811 .. note::
812
813 Most of the global settings can be changed while a workflow is running
814 using ``cylc reload --global``. Exceptions are:
815
816 `[scheduler]`: The majority of these settings affect the server and
817 cannot be reloaded while the server is running. The server must be
818 stopped and restarted for changes to take effect except for the sections
819 `[scheduler][mail]` and `[scheduler][events]` which provide workflow
820 defaults.
821
822 `[install][symlink dirs]`: These settings create files on disk, once a
823 task has started on a remote host these can't be changed for that host.
824
825 .. versionchanged:: 8.0.0
826
827 Prior to Cylc 8, ``global.cylc`` was named ``global.rc``, but that name
828 is no longer supported.
829 ''') as SPEC:
830 with Conf('hub', desc='''
831 Configure the public URL of Jupyter Hub.
832
833 If configured, the ``cylc gui`` command will open a web browser at this
834 location rather than starting a standalone server when called.
835
836
837 .. seealso::
838
839 * The cylc hub :ref:`architecture-reference` for fuller details.
840 * :ref:`UI_Server_config` for practical details.
841
842 '''):
843 Conf('url', VDR.V_STRING, '', desc='''
844 .. versionadded:: 8.3.0
845
846 Where Jupyter Hub is used a url can be provided for routing on
847 execution of ``cylc gui`` command.
848 ''')
849
850 with Conf('scheduler', desc=(
851 default_for(SCHEDULER_DESCR, "[scheduler]", section=True)
852 )):
853 Conf('UTC mode', VDR.V_BOOLEAN, False, desc=(
854 default_for(UTC_MODE_DESCR, "[scheduler]UTC mode")
855 ))
856 Conf('process pool size', VDR.V_INTEGER, 4, desc='''
857 Maximum number of concurrent processes used to execute external job
858 submission, event handlers, and job poll and kill commands
859
860 .. seealso::
861
862 :ref:`Managing External Command Execution`.
863
864 .. versionchanged:: 8.0.0
865
866 Moved into the ``[scheduler]`` section from the top level.
867 ''')
868 Conf('process pool timeout', VDR.V_INTERVAL, DurationFloat(600),
869 desc='''
870 After this interval Cylc will kill long running commands in the
871 process pool.
872
873 .. seealso::
874
875 :ref:`Managing External Command Execution`.
876
877 .. note::
878
879 The default is set quite high to avoid killing important
880 processes when the system is under load.
881
882 .. versionchanged:: 8.0.0
883
884 Moved into the ``[scheduler]`` section from the top level.
885 ''')
886 Conf('auto restart delay', VDR.V_INTERVAL, desc=f'''
887 Maximum number of seconds the auto-restart mechanism will delay
888 before restarting workflows.
889
890 When a host is set to automatically
891 shutdown/restart it waits a random period of time
892 between zero and ``auto restart delay`` seconds before
893 beginning the process. This is to prevent large numbers of
894 workflows from restarting simultaneously.
895
896 .. seealso::
897
898 :ref:`auto-stop-restart`
899
900 .. versionchanged:: 8.0.0
901
902 {REPLACES}``global.rc[suite servers]auto restart delay``.
903 ''')
904 with Conf('run hosts', desc=f'''
905 Configure workflow hosts and ports for starting workflows.
906
907 Additionally configure host selection settings specifying how to
908 determine the most suitable run host at any given time from those
909 configured.
910
911 .. versionchanged:: 8.0.0
912
913 {REPLACES}``[suite servers]``.
914 '''):
915 Conf('available', VDR.V_SPACELESS_STRING_LIST, desc=f'''
916 A list of workflow run hosts.
917
918 Cylc will choose one of these hosts for a workflow to start on.
919 (Unless an explicit host is provided as an option to the
920 ``cylc play --host=<myhost>`` command.)
921
922 .. versionchanged:: 8.0.0
923
924 {REPLACES}``[suite servers]run hosts``.
925 ''')
926 Conf('ports', VDR.V_RANGE, Range((43001, 43101)),
927 desc=f'''
928 The range of ports for Cylc to use to run workflows.
929
930 The minimum and maximum port numbers in the format
931 ``min .. max``.
932
933 .. versionchanged:: 8.0.0
934
935 {REPLACES}``[suite servers]run ports``.
936 It can no longer be used to define a non-contiguous port
937 range.
938 ''')
939 Conf('condemned', VDR.V_ABSOLUTE_HOST_LIST, desc=f'''
940 List run hosts that workflows should *not* run on.
941
942 These hosts will be subtracted from the
943 `available <global.cylc[scheduler][run hosts]>` hosts
944 preventing new workflows from starting on the "condemned" host.
945
946 Any workflows running on these hosts will either migrate
947 to another host, or shut down according to
948 :py:mod:`the configuration <cylc.flow.main_loop.auto_restart>`.
949
950 This feature requires ``auto restart`` to be listed
951 in `global.cylc[scheduler][main loop]plugins`.
952
953 For more information, see the
954 :py:mod:`auto restart <cylc.flow.main_loop.auto_restart>`
955 plugin.
956
957 .. rubric:: Example:
958
959 .. code-block:: cylc
960
961 [scheduler]
962 [[main loop]]
963 # activate the "auto restart" plugin
964 plugins = auto restart
965 [[run hosts]]
966 # there are three hosts in the "pool"
967 available = host1, host2, host3
968
969 # however two have been taken out:
970 # * workflows running on "host1" will attempt to
971 # restart on "host3"
972 # * workflows running on "host2" will shutdown
973 condemned = host1, host2!
974
975 .. seealso::
976
977 :py:mod:`cylc.flow.main_loop.auto_restart`
978 :ref:`auto-stop-restart`
979
980 .. versionchanged:: 8.4.2
981
982 The "force mode" (activated by a "!" suffix) caused issues
983 at workflow startup for Cylc versions between 8.0.0 and
984 8.4.1 inclusive.
985
986 .. versionchanged:: 8.0.0
987
988 {REPLACES}``[suite servers]condemned hosts``.
989 ''')
990 Conf('ranking', VDR.V_STRING, desc=f'''
991 Rank and filter run hosts based on system information.
992
993 By default, when a workflow is started, Cylc will pick a host
994 for it to run on at random from :cylc:conf:`[..]available`.
995 If no hosts are specified in :cylc:conf:`[..]available` it
996 will start the scheduler locally.
997
998 Ranking can be used to provide load balancing to ensure no
999 single run host is overloaded. It also provides thresholds
1000 beyond which Cylc will not attempt to start new schedulers on
1001 a host.
1002
1003 .. _psutil: https://psutil.readthedocs.io/
1004
1005 This should be a multiline string containing Python expressions
1006 to rank and/or filter hosts. All `psutil`_ attributes are
1007 available for use in these expressions, e.g, ``cpu_percent``.
1008 You can supply these with positional arguments e.g,
1009 ``cpu_percent(1)``, however, keyword arguments will not work
1010 e.g, ``cpu_percent(interval=1)``.
1011
1012 .. rubric:: Ranking
1013
1014 Rankings are expressions which return numerical values.
1015 The host which returns the lowest value is chosen. Examples:
1016
1017 .. code-block:: python
1018
1019 # rank hosts by cpu_percent over a 1 second interval
1020 cpu_percent(1) # Note: monitors CPU for 1 second
1021
1022 # rank hosts by 15min average of server load
1023 getloadavg()[2]
1024
1025 # rank hosts by the amount of available RAM (multiply by -1
1026 # to make it choose the host with the most available memory
1027 # rather than the least)
1028 -1 * virtual_memory().available
1029
1030 # rank hosts by the number of cores
1031 # (multiple by -1 because the lowest value is chosen)
1032 -1 * cpu_count()
1033
1034 .. rubric:: Threshold
1035
1036 Thresholds are expressions which return boolean values.
1037 If a host returns a ``False`` value that host will not be
1038 selected. Examples:
1039
1040 .. code-block:: python
1041
1042 # filter out hosts with a CPU utilisation of 70% or above
1043 cpu_percent(1) < 70
1044
1045 # filter out hosts with less than 1GB of RAM available
1046 virtual_memory().available > 1000000000
1047
1048 # filter out hosts with less than 1GB of disk space
1049 # available on the "/" mount
1050 disk_usage('/').free > 1000000000
1051
1052 .. rubric:: Combining
1053
1054 Multiple rankings and thresholds can be combined in this
1055 section e.g:
1056
1057 .. code-block:: python
1058
1059 # filter hosts
1060 cpu_percent(1) < 70
1061 disk_usage('/').free > 1000000000
1062
1063 # rank hosts by CPU count
1064 1 / cpu_count()
1065 # if two hosts have the same CPU count
1066 # then rank them by CPU usage
1067 cpu_percent(1)
1068
1069 .. versionchanged:: 8.0.0
1070
1071 {REPLACES}``[suite servers][run host select]rank``.
1072 ''')
1073 Conf('process check timeout', VDR.V_INTERVAL, DurationFloat(10),
1074 desc='''
1075 Maximum time for the ``cylc play`` and ``cylc vr`` commands
1076 to wait
1077 for a remote process that checks if an unresponsive scheduler
1078 is still alive (for workflows with existing contact files).
1079
1080 .. note::
1081
1082 This check involves running ``cylc psutil`` on the run host.
1083 You may need to increase the timeout if shared filesystem
1084 latency (for example) results in slow Python script startup.
1085 Increasing the timeout unnecessarily, however, will just
1086 cause these commands to hang for an unnecessarily long time
1087 in this circumstance.
1088
1089 .. versionadded:: 8.5.2
1090 ''')
1091 with Conf('host self-identification', desc=f'''
1092 How Cylc determines and shares the identity of the workflow host.
1093
1094 The workflow host's identity must be determined locally by cylc and
1095 passed to running tasks (via ``$CYLC_WORKFLOW_HOST``) so that task
1096 messages can target the right workflow on the right host.
1097
1098 .. versionchanged:: 8.0.0
1099
1100 {REPLACES}``[suite host self-identification]``.
1101 '''):
1102 # TODO
1103 # Is it conceivable that different remote task hosts at the same
1104 # site might see the workflow host differently? If so we'd need to
1105 # be able to override the target in workflow configurations.
1106 Conf(
1107 'method', VDR.V_STRING, 'name',
1108 options=['name', 'address', 'hardwired'],
1109 desc=f'''
1110 Determines how cylc finds the identity of the
1111 workflow host.
1112
1113 Options:
1114
1115 name
1116 (The default method) Self-identified host name.
1117 Cylc asks the workflow host for its host name. This
1118 should resolve on task hosts to the IP address of the
1119 workflow host; if it doesn't, adjust network settings or
1120 use one of the other methods.
1121 address
1122 Automatically determined IP address (requires *target*).
1123 Cylc attempts to use a special external "target address"
1124 to determine the IP address of the workflow host as
1125 seen by remote task hosts.
1126 hardwired
1127 (only to be used as a last resort) Manually specified
1128 host name or IP address (requires *host*) of the
1129 workflow host.
1130
1131 .. versionchanged:: 8.0.0
1132
1133 {REPLACES}``[suite host self-identification]``.
1134 ''')
1135 Conf('target', VDR.V_STRING, 'google.com', desc=f'''
1136 Target for use by the *address* self-identification method.
1137
1138 If your workflow host sees the internet, a common
1139 address such as ``google.com`` will do; otherwise choose a host
1140 visible on your intranet.
1141
1142 .. versionchanged:: 8.0.0
1143
1144 {REPLACES}``[suite host self-identification]``.
1145 ''')
1146 Conf('host', VDR.V_STRING, desc=f'''
1147 The name or IP address of the workflow host used by the
1148 *hardwired* self-identification method.
1149
1150 .. versionchanged:: 8.0.0
1151
1152 {REPLACES}``[suite host self-identification]``.
1153 ''')
1154
1155 with Conf('events',
1156 desc=default_for(EVENTS_DESCR, '[scheduler][events]')):
1157 for item, val in EVENTS_SETTINGS.items():
1158 if isinstance(val, dict):
1159 val = val.copy()
1160 desc: str = val.pop('desc')
1161 else:
1162 desc = val
1163 val = {}
1164 desc = default_for(desc, f"[scheduler][events]{item}")
1165 vdr_type = VDR.V_STRING_LIST
1166 default: Any = Conf.UNSET
1167 if (
1168 item in {'handlers', 'handler events', 'mail events'} or
1169 item.endswith("handlers")
1170 ):
1171 pass
1172 elif item.startswith("abort on"):
1173 vdr_type = VDR.V_BOOLEAN
1174 default = (item == "abort on stall timeout")
1175 elif item.endswith("timeout"):
1176 vdr_type = VDR.V_INTERVAL
1177 if item == "stall timeout":
1178 default = DurationFloat(3600)
1179 elif item == "restart timeout":
1180 default = DurationFloat(300)
1181 else:
1182 default = None
1183 Conf(item, vdr_type, default, desc=desc, **val)
1184
1185 with Conf('mail', desc=(
1186 default_for(MAIL_DESCR, "[scheduler][mail]", section=True)
1187 )):
1188 Conf('from', VDR.V_STRING, desc=(
1189 default_for(MAIL_FROM_DESCR, "[scheduler][mail]from")
1190 ))
1191 Conf('smtp', VDR.V_STRING, desc='''
1192 Specify the SMTP server for sending workflow event email
1193 notifications.
1194
1195 This cannot be configured in ``flow.cylc``.
1196
1197 Example::
1198
1199 smtp.yourorg
1200 ''')
1201 Conf('to', VDR.V_STRING, desc=(
1202 default_for(MAIL_TO_DESCR, "[scheduler][mail]to")
1203 ))
1204 Conf('footer', VDR.V_STRING, desc=(
1205 default_for(MAIL_FOOTER_DESCR, "[scheduler][mail]footer")
1206 ))
1207 Conf(
1208 'task event batch interval',
1209 VDR.V_INTERVAL,
1210 DurationFloat(300),
1211 desc=default_for(
1212 MAIL_INTERVAL_DESCR,
1213 "[scheduler][mail]task event batch interval"
1214 )
1215 )
1216
1217 with Conf('main loop', desc=(
1218 default_for(
1219 MAIN_LOOP_DESCR, "[scheduler][main loop]", section=True
1220 )
1221 )):
1222 Conf(
1223 'plugins',
1224 VDR.V_STRING_LIST,
1225 ['health check', 'reset bad hosts'],
1226 desc='''
1227 Configure the default main loop plugins to use when
1228 starting new workflows.
1229
1230 Only enabled plugins are loaded. Plugins can be enabled
1231 in two ways:
1232
1233 Globally:
1234 To enable a plugin for all workflows add it to this
1235 setting.
1236 Per-Run:
1237 To enable a plugin for a one-off run of a workflow,
1238 specify it on the command line with
1239 ``cylc play --main-loop``.
1240
1241 .. hint::
1242
1243 This *appends* to the configured list of plugins
1244 rather than overriding it.
1245
1246 .. versionadded:: 8.0.0
1247 ''')
1248
1249 with Conf('<plugin name>', desc=(
1250 default_for(
1251 MAIN_LOOP_PLUGIN_DESCR,
1252 "[scheduler][main loop][<plugin name>]",
1253 section=True
1254 )
1255 )) as MainLoopPlugin:
1256 Conf('interval', VDR.V_INTERVAL, DurationFloat(600), desc=(
1257 default_for(
1258 MAIN_LOOP_PLUGIN_INTERVAL_DESCR,
1259 "[scheduler][main loop][<plugin name>]interval"
1260 )
1261 ))
1262
1263 with Conf('health check', meta=MainLoopPlugin, desc='''
1264 Checks the integrity of the workflow run directory.
1265
1266 .. versionadded:: 8.0.0
1267 '''):
1268 Conf('interval', VDR.V_INTERVAL, DurationFloat(600),
1269 desc=MAIN_LOOP_PLUGIN_INTERVAL_DESCR)
1270
1271 with Conf('auto restart', meta=MainLoopPlugin, desc='''
1272 Automatically migrates workflows between servers.
1273
1274 For more information see:
1275
1276 * :ref:`Submitting Workflows To a Pool Of Hosts`.
1277 * :py:mod:`cylc.flow.main_loop.auto_restart`
1278
1279 .. versionadded:: 8.0.0
1280 '''):
1281 Conf('interval', VDR.V_INTERVAL, DurationFloat(600),
1282 desc=MAIN_LOOP_PLUGIN_INTERVAL_DESCR)
1283
1284 with Conf('reset bad hosts', meta=MainLoopPlugin, desc='''
1285 Periodically clear the scheduler list of unreachable (bad)
1286 hosts.
1287
1288 .. versionadded:: 8.0.0
1289 '''):
1290 Conf('interval', VDR.V_INTERVAL, DurationFloat(1800),
1291 desc=MAIN_LOOP_PLUGIN_INTERVAL_DESCR)
1292
1293 with Conf('logging', desc=f'''
1294 Settings for the workflow event log.
1295
1296 The workflow event log, held under the workflow run directory, is
1297 maintained as a rolling archive. Logs are rolled over (backed up
1298 and started anew) when they reach a configurable limit size.
1299
1300 .. versionchanged:: 8.0.0
1301
1302 {REPLACES}``[suite logging]``.
1303 '''):
1304 Conf('rolling archive length', VDR.V_INTEGER, 15, desc='''
1305 How many rolled logs to retain in the archive.
1306 ''')
1307 Conf('maximum size in bytes', VDR.V_INTEGER, 1000000, desc='''
1308 Workflow event logs are rolled over when they reach this
1309 file size.
1310 ''')
1311
1312 with Conf('install', desc='''
1313 Configure directories and files to be installed on remote hosts.
1314
1315 .. versionadded:: 8.0.0
1316 '''):
1317 Conf('max depth', VDR.V_INTEGER, default=4, desc='''
1318 How many directory levels deep Cylc should look for installed
1319 workflows in the :term:`cylc-run directory`.
1320
1321 This also sets the limit on how deep a :term:`workflow ID` can be
1322 before ``cylc install`` will refuse to install it. For example,
1323 if set to 4, ``cylc install one/two/three/four`` will fail,
1324 because the resultant workflow ID would be
1325 ``one/two/three/four/run1``, which is 5 levels deep. (However,
1326 ``cylc install one/two/three/four --no-run-name`` would work.)
1327
1328 .. note::
1329 A high value may cause a slowdown of Cylc commands such
1330 ``install``, ``scan`` and ``clean`` if there are many
1331 :term:`run directories <run directory>` in the
1332 cylc-run directory for Cylc to check, or if the filesystem
1333 is slow (e.g. NFS).
1334
1335 .. versionadded:: 8.0.0
1336 ''')
1337 Conf('source dirs', VDR.V_STRING_LIST, default=['~/cylc-src'], desc='''
1338 List of paths that Cylc searches for workflows to install.
1339
1340 All workflow source directories in these locations will
1341 also show up in the GUI, ready for installation.
1342
1343 .. note::
1344 If workflow source directories of the same name exist in more
1345 than one of these paths, only the first one will be picked up.
1346
1347 .. versionadded:: 8.0.0
1348 ''')
1349 # Symlink Dirs
1350 with Conf('symlink dirs', # noqa: SIM117 (keep same format)
1351 desc="""
1352 Configure alternate workflow run directory locations.
1353
1354 Symlinks from the the standard ``$HOME/cylc-run`` locations will be
1355 created.
1356
1357 .. note::
1358
1359 Once a platform has been installed and symlinks created they
1360 cannot be modified for that run.
1361
1362 .. versionadded:: 8.0.0
1363 """):
1364 with Conf('<install target>', desc=dedent("""
1365 :ref:`Host <Install targets>` on which to create the symlinks.
1366
1367 .. versionadded:: 8.0.0
1368
1369 """) + comma_sep_section_note(version_changed='8.4.0')):
1370 Conf('run', VDR.V_STRING, None, desc="""
1371 Alternative location for the run dir.
1372
1373 If specified, the workflow run directory will
1374 be created in ``<this-path>/cylc-run/<workflow-id>``
1375 and a symbolic link will be created from
1376 ``$HOME/cylc-run/<workflow-id>``.
1377 If not specified, the workflow run directory will be
1378 created in ``$HOME/cylc-run/<workflow-id>``.
1379 All the workflow files and the ``.service`` directory get
1380 installed into this directory.
1381
1382 .. versionadded:: 8.0.0
1383 """)
1384 for folder, versionadded in SYMLINKABLE_LOCATIONS.items():
1385 Conf(folder, VDR.V_STRING, None, desc=f"""
1386 Alternative location for the {folder} dir.
1387
1388 If specified, the workflow {folder} directory will
1389 be created in
1390 ``<this-path>/cylc-run/<workflow-id>/{folder}``
1391 and a symbolic link will be created from
1392 ``$HOME/cylc-run/<workflow-id>/{folder}``.
1393 If not specified, the directory will be created in
1394 ``$HOME/cylc-run/<workflow-id>/{folder}``.
1395
1396 .. versionadded:: {versionadded}
1397 """)
1398 with Conf('platforms', desc='''
1399 Platforms allow you to define compute resources available at your
1400 site.
1401
1402 A platform consists of a group of one or more hosts which share a
1403 file system and a job runner (batch system).
1404
1405 A platform must allow interaction with the same job from *any*
1406 of its hosts.
1407
1408 .. versionadded:: 8.0.0
1409 '''):
1410 with Conf(
1411 '<platform name>',
1412 desc=dedent('''
1413 Configuration defining a platform.
1414
1415 Many of these settings have replaced those of the same name from
1416 the old Cylc 7 ``suite.rc[runtime][<namespace>][job]/[remote]``
1417 and ``global.rc[hosts][<host>]`` sections.
1418
1419 Platform names can be regular expressions: If you have a set of
1420 compute resources such as ``bigmachine1, bigmachine2`` or
1421 ``desktop0000, .., desktop9999`` one would define platforms with
1422 names ``[[bigmachine[12]]]`` and ``[[desktop[0-9]{4}]]``.
1423
1424 Cylc searches for a matching platform in the reverse
1425 of the definition order to allow user defined platforms
1426 to override site defined platforms. This means, for example, that
1427 if ``[[a.*]]`` were set at the bottom of a configuration any
1428 platform name beginning with "a" would return that platform.
1429
1430 .. note::
1431
1432 Each possible match to the definition regular expression is
1433 considered a separate platform.
1434
1435 If you had a supercomputer with multiple login nodes this would
1436 be a single platform with multiple :cylc:conf:`hosts`.
1437
1438 .. warning::
1439
1440 ``[platforms][localhost]`` may be set, to override default
1441 settings, but regular expressions which match "localhost"
1442 may not. Use comma separated lists instead:
1443
1444 .. code-block:: cylc
1445
1446 [platforms]
1447 [[localhost|cylc-server-..]] # error
1448 [[localhost, cylc-server-..]] # ok
1449
1450 .. seealso::
1451
1452 - :ref:`MajorChangesPlatforms` in the Cylc 8 migration guide.
1453 - :ref:`AdminGuide.PlatformConfigs`, an administrator's guide to
1454 platform configurations.
1455
1456 ''')
1457 + comma_sep_section_note()
1458 + ".. versionadded:: 8.0.0",
1459 ) as Platform:
1460 with Conf('meta', desc=PLATFORM_META_DESCR):
1461 Conf('<custom metadata>', VDR.V_STRING, '', desc='''
1462 Any user-defined metadata item.
1463
1464 .. versionadded:: 8.0.0
1465 ''')
1466 Conf('hosts', VDR.V_STRING_LIST, desc='''
1467 A list of hosts from which the job host can be selected using
1468 :cylc:conf:`[..][selection]method`.
1469
1470 All hosts should share a file system.
1471
1472 .. versionadded:: 8.0.0
1473 ''')
1474 Conf('job runner', VDR.V_STRING, 'background', desc=f'''
1475 The system used to run jobs on the platform.
1476
1477 Examples:
1478
1479 * ``background``
1480 * ``slurm``
1481 * ``pbs``
1482
1483 .. seealso::
1484
1485 :ref:`List of built-in Job Runners <AvailableMethods>`
1486
1487 .. versionadded:: 8.0.0
1488
1489 {PLATFORM_REPLACES.format("[job]batch system")}
1490 ''')
1491 replaces = PLATFORM_REPLACES.format(
1492 "[job]batch submit command template"
1493 )
1494 Conf('job runner command template', VDR.V_STRING, desc=f'''
1495 Set the command used by the chosen job runner.
1496
1497 The template's ``%(job)s`` will be
1498 substituted by the job file path.
1499
1500 .. versionadded:: 8.0.0
1501
1502 {replaces}
1503 ''')
1504 Conf('communication method',
1505 VDR.V_STRING, 'zmq',
1506 options=[meth.value for meth in CommsMeth], desc=f'''
1507 The means by which task progress messages are reported back to
1508 the running workflow.
1509
1510 .. rubric:: Options:
1511
1512 zmq
1513 Direct client-server TCP communication via network ports
1514 poll
1515 The workflow polls for task status (no task messaging)
1516 ssh
1517 Use non-interactive ssh for task communications
1518
1519 For more information, see :ref:`TaskComms`.
1520
1521 .. versionchanged:: 8.0.0
1522
1523 {REPLACES}``global.rc[hosts][<host>]task communication
1524 method``.
1525 ''')
1526 Conf(
1527 'submission polling intervals', VDR.V_INTERVAL_LIST,
1528 [DurationFloat(900)], desc=default_for(
1529 SUBMISSION_POLL_DESCR,
1530 "[runtime][<namespace>]submission polling intervals"
1531 )
1532 )
1533 Conf(
1534 'submission retry delays', VDR.V_INTERVAL_LIST, None,
1535 desc=default_for(
1536 SUBMISSION_RETY_DESCR,
1537 "[runtime][<namespace>]submission retry delays"
1538 )
1539 )
1540 Conf(
1541 'execution polling intervals', VDR.V_INTERVAL_LIST,
1542 [DurationFloat(900)], desc=default_for(
1543 EXECUTION_POLL_DESCR,
1544 "[runtime][<namespace>]execution polling intervals"
1545 )
1546 )
1547 Conf('execution time limit polling intervals',
1548 VDR.V_INTERVAL_LIST,
1549 [DurationFloat(60), DurationFloat(120), DurationFloat(420)],
1550 desc=f'''
1551 List of intervals after execution time limit to poll jobs.
1552
1553 If a job exceeds its execution time limit, Cylc can poll
1554 more frequently to detect the expected job completion quickly.
1555 The last interval in the list is used repeatedly until the job
1556 completes.
1557 Multipliers can be used as shorthand as in the example below.
1558
1559 Example::
1560
1561 5*PT2M, PT5M
1562
1563 .. versionchanged:: 8.0.0
1564
1565 {REPLACES}``global.rc[hosts][<host>][batch systems]
1566 [<system>]execution time limit polling``.
1567 ''')
1568 Conf('ssh command',
1569 VDR.V_STRING,
1570 'ssh -oBatchMode=yes -oConnectTimeout=10',
1571 desc=f'''
1572 A communication command used to invoke commands on this
1573 platform.
1574
1575 Not used on the workflow host unless you run local tasks
1576 under another user account. The value is assumed to be ``ssh``
1577 with some initial options or a command that implements a
1578 similar interface to ``ssh``.
1579
1580 .. versionchanged:: 8.0.0
1581
1582 {REPLACES}``global.rc[hosts][<host>]ssh command``.
1583 ''')
1584 Conf('rsync command',
1585 VDR.V_STRING,
1586 'rsync',
1587 desc='''
1588 Command used for file installation.
1589
1590 This supports POSIX compliant rsync implementations e.g. GNU or
1591 BSD.
1592
1593 .. versionadded:: 8.0.0
1594 ''')
1595 Conf('use login shell', VDR.V_BOOLEAN, True, desc=f'''
1596 Whether to use a login shell or not for remote command
1597 invocation.
1598
1599 By default, Cylc runs remote SSH commands using a login shell:
1600
1601 .. code-block:: bash
1602
1603 ssh user@host 'bash --login cylc ...'
1604
1605 which will source the following files (in order):
1606
1607 * ``/etc/profile``
1608 * ``~/.bash_profile``
1609 * ``~/.bash_login``
1610 * ``~/.profile``
1611
1612 .. _Bash man pages: https://linux.die.net/man/1/bash
1613
1614 For more information on login shells see the "Invocation"
1615 section of the `Bash man pages`_.
1616
1617 For security reasons some institutions do not allow unattended
1618 commands to start login shells, so you can turn off this
1619 behaviour to get:
1620
1621 .. code-block:: bash
1622
1623 ssh user@host 'cylc ...'
1624
1625 which will use the default shell on the remote machine,
1626 sourcing ``~/.bashrc`` (or ``~/.cshrc``) to set up the
1627 environment.
1628
1629 .. versionchanged:: 8.0.0
1630
1631 {REPLACES}``global.rc[hosts][<host>]use login shell``.
1632 ''')
1633 Conf('cylc path', VDR.V_STRING, desc='''
1634 The path containing the ``cylc`` executable on a remote
1635 platform.
1636
1637 This may be necessary if the ``cylc`` executable is not in the
1638 ``$PATH`` for an ``ssh`` call.
1639 Test whether this is the case by using
1640 ``ssh <host> command -v cylc``.
1641
1642 This path is used for remote invocations of the ``cylc``
1643 command and is added to the ``$PATH`` in job scripts
1644 for the configured platform.
1645
1646 .. note::
1647
1648 If :cylc:conf:`[..]use login shell = True` (the default)
1649 then an alternative approach is to add ``cylc`` to the
1650 ``$PATH`` in the system or user Bash profile files
1651 (e.g. ``~/.bash_profile``).
1652
1653 .. tip::
1654
1655 For multi-version installations this should point to the
1656 Cylc wrapper script rather than the ``cylc`` executable
1657 itself.
1658
1659 See :ref:`installation.distributed-installation` for more
1660 information on the wrapper script.
1661
1662 .. versionchanged:: 8.0.0
1663
1664 Moved from ``suite.rc[runtime][<namespace>][job]
1665 cylc executable``.
1666 ''')
1667 Conf('global init-script', VDR.V_STRING, desc=f'''
1668 A per-platform script which is run before other job scripts.
1669
1670 This should be used sparingly to perform any shell
1671 configuration that cannot be performed via other means.
1672
1673 .. versionchanged:: 8.0.0
1674
1675 The ``global init-script`` now runs *before* any job
1676 scripting which introduces caveats outlined below.
1677
1678 .. warning::
1679
1680 The ``global init-script`` has the following caveats,
1681 as compared to the other task ``script-*`` items:
1682
1683 * The script is not covered by error trapping.
1684 * The job environment is not available to this script.
1685 * In debug mode this script will not be included in
1686 xtrace output.
1687
1688 .. versionchanged:: 8.0.0
1689
1690 {REPLACES}``global.rc[hosts][<host>]global init-script``.
1691 ''')
1692 Conf('copyable environment variables', VDR.V_STRING_LIST, '',
1693 desc=f'''
1694 A list containing the names of the environment variables to
1695 be copied from the scheduler to a job.
1696
1697 .. versionchanged:: 8.0.0
1698
1699 {REPLACES}``global.rc[hosts][<host>]copyable
1700 environment variables``.
1701 ''')
1702 Conf('retrieve job logs', VDR.V_BOOLEAN,
1703 desc=f'''
1704 {LOG_RETR_SETTINGS['retrieve job logs']}
1705
1706 .. versionchanged:: 8.0.0
1707
1708 {REPLACES}``global.rc[hosts][<host>]retrieve job logs``.
1709 {PLATFORM_REPLACES.format("[remote]retrieve job logs")}
1710 ''')
1711 Conf('retrieve job logs command', VDR.V_STRING, 'rsync -a',
1712 desc=f'''
1713 {LOG_RETR_SETTINGS['retrieve job logs command']}
1714
1715 .. note::
1716 The default command (``rsync -a``) means that the retrieved
1717 files (and the directories above including ``log/job``) get
1718 the same permissions as on the remote host. This can cause
1719 problems if the remote host uses different permissions to
1720 the scheduler host (e.g. no world read access). To avoid
1721 this problem you can set the command to
1722 ``rsync -a --no-p --no-g --chmod=ugo=rwX`` which means the
1723 retrieved files get the default permissions used on the
1724 scheduler host.
1725
1726 .. versionchanged:: 8.0.0
1727
1728 {REPLACES}``global.rc[hosts][<host>]retrieve job logs
1729 command``.
1730 ''')
1731 replaces = PLATFORM_REPLACES.format(
1732 "[remote]retrieve job logs max size")
1733 Conf('retrieve job logs max size', VDR.V_STRING, desc=f'''
1734 {LOG_RETR_SETTINGS['retrieve job logs max size']}
1735
1736 .. versionchanged:: 8.0.0
1737
1738 {REPLACES}``global.rc[hosts][<host>]retrieve job logs
1739 max size``.
1740 {replaces}
1741 ''')
1742 replaces = PLATFORM_REPLACES.format(
1743 "[remote]retrieve job logs retry delays")
1744 Conf('retrieve job logs retry delays', VDR.V_INTERVAL_LIST,
1745 desc=f'''
1746 {LOG_RETR_SETTINGS['retrieve job logs retry delays']}
1747
1748 .. versionchanged:: 8.0.0
1749
1750 {REPLACES}``global.rc[hosts][<host>]retrieve job logs
1751 retry delays``.
1752 {replaces}
1753 ''')
1754 Conf('tail command template',
1755 VDR.V_STRING, 'tail -n +1 --follow=name %(filename)s',
1756 desc=f'''
1757 A command template (with ``%(filename)s`` substitution) to
1758 tail-follow job logs this platform, by ``cylc cat-log``.
1759
1760 .. warning::
1761
1762 You are are unlikely to need to override this. Doing so may
1763 adversely affect the UI log view.
1764
1765 .. versionchanged:: 8.0.0
1766
1767 {REPLACES}``global.rc[hosts][<host>]tail command template``.
1768 ''')
1769 Conf('err tailer', VDR.V_STRING, desc=f'''
1770 A command template (with ``%(job_id)s`` substitution) that can
1771 be used to tail-follow the stderr stream of a running job if
1772 SYSTEM does not use the normal log file location while the job
1773 is running. This setting overrides
1774 :cylc:conf:`[..]tail command template`.
1775
1776 Examples::
1777
1778 # for PBS
1779 qcat -f -e %(job_id)s
1780
1781 .. versionchanged:: 8.0.0
1782
1783 {REPLACES}``global.rc[hosts][<host>][batch systems]
1784 [<system>]err tailer``.
1785 ''')
1786 Conf('out tailer', VDR.V_STRING, desc=f'''
1787 A command template (with ``%(job_id)s`` substitution) that can
1788 be used to tail-follow the stdout stream of a running job if
1789 SYSTEM does not use the normal log file location while the job
1790 is running. This setting overrides
1791 :cylc:conf:`[..]tail command template`.
1792
1793 Examples::
1794
1795 # for PBS
1796 qcat -f -o %(job_id)s
1797
1798 .. versionchanged:: 8.0.0
1799
1800 {REPLACES}``global.rc[hosts][<host>][batch systems]
1801 [<system>]out tailer``.
1802 ''')
1803 Conf('err viewer', VDR.V_STRING, desc=f'''
1804 A command template (with ``%(job_id)s`` substitution) that can
1805 be used to view the stderr stream of a running job if SYSTEM
1806 does not use the normal log file location while the job is
1807 running.
1808
1809 Examples::
1810
1811 # for PBS
1812 qcat -e %(job_id)s
1813
1814 .. versionchanged:: 8.0.0
1815
1816 {REPLACES}``global.rc[hosts][<host>][batch systems]
1817 [<system>]err viewer``.
1818 ''')
1819 Conf('out viewer', VDR.V_STRING, desc=f'''
1820 A command template (with ``%(job_id)s`` substitution) that can
1821 be used to view the stdout stream of a running job if SYSTEM
1822 does not use the normal log file location while the job is
1823 running.
1824
1825 Examples::
1826
1827 # for PBS
1828 qcat -o %(job_id)s
1829
1830 .. versionchanged:: 8.0.0
1831
1832 {REPLACES}``global.rc[hosts][<host>][batch systems]
1833 [<system>]out viewer``.
1834 ''')
1835 Conf('job name length maximum', VDR.V_INTEGER, desc=f'''
1836 The maximum length for job name acceptable by a job runner on
1837 a given host. Currently, this setting is only meaningful for
1838 PBS jobs. For example, PBS 12 or older will fail a job submit
1839 if the job name has more than 15 characters; whereas PBS 13
1840 accepts up to 236 characters.
1841
1842 .. versionchanged:: 8.0.0
1843
1844 {REPLACES}``global.rc[hosts][<host>][batch systems]
1845 [<system>]job name length maximum``.
1846 ''')
1847 Conf('install target', VDR.V_STRING, desc='''
1848 This defaults to the platform name. This will be used as the
1849 target for remote file installation.
1850 For example, if Platform_A shares a file system with localhost:
1851
1852 .. code-block:: cylc
1853
1854 [platforms]
1855 [[Platform_A]]
1856 install target = localhost
1857
1858 .. versionadded:: 8.0.0
1859 ''')
1860
1861 Conf('clean job submission environment', VDR.V_BOOLEAN, False,
1862 desc='''
1863 Job submission subprocesses inherit their parent environment by
1864 default. Remote jobs inherit the default non-interactive shell
1865 environment for their platform. Jobs on the scheduler host
1866 inherit the scheduler environment (unless their job runner
1867 prevents this).
1868
1869 If, for example, the ``$PYTHON`` variable is different on the
1870 scheduler and the remote host the same program may run in
1871 different ways.
1872
1873 We recommend using a clean job submission environment for
1874 consistent handling of local and remote jobs. However,
1875 this is not the default behaviour because it prevents
1876 local jobs from running, unless ``$PATH`` contains the
1877 ``cylc`` wrapper script.
1878
1879 Specific environment variables can be singled out to pass
1880 through to the clean environment, if necessary.
1881
1882 A standard set of executable paths is passed through to clean
1883 environments, and can be added to if necessary.
1884
1885 .. versionadded:: 8.0.0
1886 ''')
1887
1888 Conf('job submission environment pass-through', VDR.V_STRING_LIST,
1889 desc='''
1890 List of environment variable names to pass through to
1891 job submission subprocesses.
1892
1893 ``$HOME`` is passed automatically.
1894
1895 You are unlikely to need this.
1896
1897 .. versionadded:: 8.0.0
1898 ''')
1899 Conf('job submission executable paths', VDR.V_STRING_LIST,
1900 desc=f'''
1901 Additional executable locations to pass to the job
1902 submission subprocess beyond the standard locations
1903 {", ".join(f"``{i}``" for i in SYSPATH)}.
1904 You are unlikely to need this.
1905
1906 .. versionadded:: 8.0.0
1907 ''')
1908 Conf('max batch submit size', VDR.V_INTEGER, default=100, desc='''
1909 Limits the maximum number of jobs that can be submitted at
1910 once.
1911
1912 Where possible Cylc will batch together job submissions to
1913 the same platform for efficiency. Submitting very large
1914 numbers of jobs can cause problems with some submission
1915 systems so for safety there is an upper limit on the number
1916 of job submissions which can be batched together.
1917
1918 .. versionadded:: 8.0.0
1919 ''')
1920 Conf('ssh forward environment variables', VDR.V_STRING_LIST, '',
1921 desc='''
1922 A list containing the names of the environment variables to
1923 forward with SSH connections to the workflow host from
1924 the host running 'cylc play'
1925
1926 .. versionadded:: 8.3.0
1927 ''')
1928 with Conf('selection', desc='''
1929 How to select a host from the list of platform hosts.
1930
1931 .. versionadded:: 8.0.0
1932 ''') as Selection:
1933 Conf('method', VDR.V_STRING, default='random',
1934 options=['random', 'definition order'],
1935 desc='''
1936 Host selection method for the platform.
1937
1938 .. rubric:: Available options
1939
1940 - ``random``: Choose randomly from the list of hosts.
1941 This is suitable for a pool of identical hosts.
1942 - ``definition order``: Take the first host in the list
1943 unless that host was unreachable. In many cases
1944 this is likely to cause load imbalances, but might
1945 be appropriate if following the pattern
1946 ``hosts = main, backup, failsafe``.
1947
1948 .. versionadded:: 8.0.0
1949 ''')
1950 with Conf('directives', desc=(
1951 default_for(
1952 DIRECTIVES_DESCR,
1953 "[runtime][<namespace>][directives]",
1954 section=True
1955 ) + "\n\n" + ".. versionadded:: 8.0.0"
1956 )):
1957 Conf('<directive>', VDR.V_STRING,
1958 desc=short_descr(DIRECTIVES_ITEM_DESCR))
1959
1960 with Conf('localhost', meta=Platform, desc='''
1961 A default platform for running jobs on the the scheduler host.
1962
1963 This platform configures the host on which
1964 :term:`schedulers <scheduler>` run. By default this is the
1965 host where ``cylc play`` is run, however, we often configure
1966 Cylc to start schedulers on dedicated hosts by configuring
1967 :cylc:conf:`global.cylc[scheduler][run hosts]available`.
1968
1969 This platform affects connections made to the scheduler host and
1970 any jobs run on it.
1971
1972 .. versionadded:: 8.0.0
1973 '''):
1974 Conf('hosts', VDR.V_STRING_LIST, ['localhost'], desc='''
1975 List of hosts for the localhost platform. You are unlikely to
1976 need to change this.
1977
1978 The scheduler hosts are configured by
1979 :cylc:conf:`global.cylc[scheduler][run hosts]available`.
1980 See :ref:`Submitting Workflows To a Pool Of Hosts` for
1981 more information.
1982
1983 .. seealso::
1984
1985 :cylc:conf:`global.cylc[platforms][<platform name>]hosts`
1986 ''')
1987 with Conf(
1988 'selection', meta=Selection,
1989 desc=(
1990 'How to select a host on the "localhost" platform.'
1991 'You are unlikely to need to change this.'
1992 ':cylc:conf:`global.cylc[platforms][<platform name>]'
1993 '[selection]`'
1994 )
1995 ):
1996 Conf('method', VDR.V_STRING, default='definition order',
1997 desc='''
1998 Host selection method for the "localhost" platform.
1999
2000 .. seealso::
2001
2002 :cylc:conf:`global.cylc[platforms][<platform name>]
2003 [selection]method`
2004 ''')
2005
2006 # Platform Groups
2007 with Conf('platform groups', desc='''
2008 Platform groups allow you to group together platforms which would
2009 all be suitable for a given job.
2010
2011
2012 When Cylc submits a job it will pick a platform from a group.
2013 Cylc will then use the selected platform for all interactions with
2014 that job.
2015
2016 For example, if you have a group of computers
2017 without a shared file system, but otherwise identical called
2018 ``bigmachine01..02`` you might set up a platform group
2019 ``[[bigmachines]]platforms=bigmachine01, bigmachine02``.
2020
2021 .. seealso::
2022
2023 - :ref:`MajorChangesPlatforms` in the Cylc 8 migration guide.
2024 - :ref:`AdminGuide.PlatformConfigs`, an guide to platform
2025 configurations.
2026
2027 .. versionadded:: 8.0.0
2028 '''): # noqa: SIM117 (keep same format)
2029 with Conf('<group>', desc='''
2030 The name of a :cylc:conf:`platform group
2031 <global.cylc[platform groups]>`.
2032 '''):
2033 with Conf('meta', desc=PLATFORM_META_DESCR):
2034 Conf('<custom metadata>', VDR.V_STRING, '', desc='''
2035 Any user-defined metadata item.
2036
2037 .. versionadded:: 8.0.0
2038 ''')
2039 Conf('platforms', VDR.V_STRING_LIST, desc='''
2040 A list of platforms which can be selected if
2041 :cylc:conf:`flow.cylc[runtime][<namespace>]platform` matches
2042 the name of this platform group.
2043
2044 .. versionadded:: 8.0.0
2045
2046 .. note::
2047
2048 Some job runners ("background", "at") require a single-host
2049 platform, because the job ID is only valid on the submission
2050 host.
2051
2052 ''')
2053 with Conf(
2054 'selection',
2055 desc='Sets how platforms are selected from platform groups.'
2056 ):
2057 Conf(
2058 'method', VDR.V_STRING, default='random',
2059 options=['random', 'definition order'],
2060 desc='''
2061 Method for selecting platform from group.
2062
2063 options:
2064
2065 - random: Suitable for an identical pool of platforms.
2066 - definition order: Pick the first available platform
2067 from the list.
2068
2069 .. versionadded:: 8.0.0
2070 '''
2071 )
2072 # task
2073 with Conf('task events', desc=(
2074 default_for(
2075 TASK_EVENTS_DESCR, "[runtime][<namespace>][events]", section=True
2076 ) + "\n\n" + ".. versionadded:: 8.0.0"
2077 )):
2078 Conf('handlers', VDR.V_STRING_LIST, desc=(
2079 default_for(
2080 TASK_EVENTS_SETTINGS['handlers'],
2081 "[runtime][<namespace>][events]handlers"
2082 )
2083 ))
2084 Conf('handler events', VDR.V_STRING_LIST, desc=(
2085 default_for(
2086 TASK_EVENTS_SETTINGS['handler events'],
2087 "[runtime][<namespace>][events]handler events"
2088 )
2089 ))
2090 Conf('handler retry delays', VDR.V_INTERVAL_LIST, None, desc=(
2091 default_for(
2092 TASK_EVENTS_SETTINGS['handler retry delays'],
2093 "[runtime][<namespace>][events]handler retry delays"
2094 )
2095 ))
2096 Conf('mail events', VDR.V_STRING_LIST, desc=(
2097 default_for(
2098 TASK_EVENTS_SETTINGS['mail events'],
2099 "[runtime][<namespace>][events]mail events"
2100 )
2101 ))
2102 Conf('execution timeout', VDR.V_INTERVAL, desc=(
2103 default_for(
2104 TASK_EVENTS_SETTINGS['execution timeout'],
2105 "[runtime][<namespace>][events]execution timeout"
2106 )
2107 ))
2108 Conf('submission timeout', VDR.V_INTERVAL, desc=(
2109 default_for(
2110 TASK_EVENTS_SETTINGS['submission timeout'],
2111 "[runtime][<namespace>][events]submission timeout"
2112 )
2113 ))
2114
2115
2116 def upg(cfg, descr):
2117 """Upgrader."""
2118 u = upgrader(cfg, descr)
2119 u.upgrade()
2120
2121
2122 def get_version_hierarchy(version: str) -> List[str]:
2123 """Return list of versions whose global configs are compatible, in
2124 ascending priority.
2125
2126 Args:
2127 version: A PEP 440 compliant version tag.
2128
2129 Example:
2130 >>> get_version_hierarchy('8.0.1a2.dev')
2131 ['', '8', '8.0', '8.0.1', '8.0.1a2', '8.0.1a2.dev']
2132
2133 """
2134 smart_ver = Version(version)
2135 base = [str(i) for i in smart_ver.release]
2136 hierarchy = ['']
2137 hierarchy += ['.'.join(base[:i]) for i in range(1, len(base) + 1)]
2138 if smart_ver.pre: # alpha/beta (excluding dev) part of version
2139 pre_ver = ''.join(str(i) for i in smart_ver.pre)
2140 hierarchy.append(f'{hierarchy[-1]}{pre_ver}')
2141 if version not in hierarchy: # catch-all
2142 hierarchy.append(version)
2143 return hierarchy
2144
2145
2146 class GlobalConfig(ParsecConfig):
2147 """
2148 Handle global (all workflows) site and user configuration for cylc.
2149 User file values override site file values.
2150 """
2151
2152 _DEFAULT: Optional['GlobalConfig'] = None
2153 CONF_BASENAME: str = "global.cylc"
2154 DEFAULT_SITE_CONF_PATH: str = os.path.join(os.sep, 'etc', 'cylc')
2155 USER_CONF_PATH: str = os.path.join(
2156 os.getenv('HOME') or get_user_home(), '.cylc', 'flow'
2157 )
2158 VERSION_HIERARCHY: List[str] = get_version_hierarchy(CYLC_VERSION)
2159
2160 def __init__(self, *args, **kwargs) -> None:
2161 site_conf_root = (
2162 os.getenv('CYLC_SITE_CONF_PATH') or self.DEFAULT_SITE_CONF_PATH
2163 )
2164 self.conf_dir_hierarchy: List[Tuple[str, str]] = [
2165 *[
2166 (upgrader.SITE_CONFIG,
2167 os.path.join(site_conf_root, 'flow', ver))
2168 for ver in self.VERSION_HIERARCHY
2169 ],
2170 *[
2171 (upgrader.USER_CONFIG,
2172 os.path.join(self.USER_CONF_PATH, ver))
2173 for ver in self.VERSION_HIERARCHY
2174 ]
2175 ]
2176 super().__init__(*args, **kwargs)
2177
2178 @classmethod
2179 def get_inst(
2180 cls, cached: bool = True, reload: bool = False
2181 ) -> 'GlobalConfig':
2182 """Return a GlobalConfig instance.
2183
2184 Args:
2185 cached:
2186 If True, return a cached instance if present. If False, return
2187 a new instance.
2188 reload:
2189 If true, reload the cached instance (implies cached=True).
2190
2191 """
2192 if cached and cls._DEFAULT and not reload:
2193 return cls._DEFAULT
2194
2195 new_instance = cls(SPEC, upg, validator=cylc_config_validate)
2196 new_instance.load()
2197
2198 if cached or reload:
2199 cls._DEFAULT = new_instance
2200
2201 return new_instance
2202
2203 def _load(self, fname: Union[Path, str], conf_type: str) -> None:
2204 if not os.access(fname, os.F_OK | os.R_OK):
2205 return
2206 try:
2207 self.loadcfg(fname, conf_type)
2208 self._validate_source_dirs()
2209 except ParsecError:
2210 LOG.error(f'bad {conf_type} {fname}')
2211 raise
2212
2213 @classmethod
2214 def set_cache(cls, cfg: "GlobalConfig") -> None:
2215 """Set the cached config"""
2216 cls._DEFAULT = cfg
2217
2218 def load(self) -> None:
2219 """Load configuration from files."""
2220 self.sparse.clear()
2221 self.dense.clear()
2222 LOG.debug("Loading site/user config files")
2223 conf_path_str = os.getenv("CYLC_CONF_PATH")
2224
2225 if conf_path_str:
2226 # Explicit config file override.
2227 fname = os.path.join(conf_path_str, self.CONF_BASENAME)
2228 self._load(fname, upgrader.USER_CONFIG)
2229 else:
2230 # Use default locations.
2231 for conf_type, conf_dir in self.conf_dir_hierarchy:
2232 fname = os.path.join(conf_dir, self.CONF_BASENAME)
2233 self._load(fname, conf_type)
2234
2235 # Expand platforms needs to be performed first because it
2236 # manipulates the sparse config.
2237 self._expand_commas()
2238
2239 # Flesh out with defaults
2240 self.expand()
2241
2242 self._no_platform_group_name_overlap()
2243 with suppress(KeyError):
2244 validate_platforms(self.sparse['platforms'])
2245
2246 def _validate_source_dirs(self) -> None:
2247 """Check source dirs are absolute paths."""
2248 keys = ['install', 'source dirs']
2249 try:
2250 src_dirs: List[str] = self.get(keys, sparse=True)
2251 except ItemNotFoundError:
2252 return
2253 for item in src_dirs:
2254 path = Path(item)
2255 # Do not expand user/env vars - it is ok if they don't exist
2256 if not (
2257 path.is_absolute() or path.parts[0].startswith(('~', '$'))
2258 ):
2259 raise ValidationError(
2260 keys, value=item, msg="must be an absolute path"
2261 )
2262
2263 def _no_platform_group_name_overlap(self):
2264 if (
2265 'platforms' in self.sparse and
2266 'platform groups' in self.sparse
2267 ):
2268 names_in_platforms_and_groups = set(
2269 self.sparse['platforms'].keys()).intersection(
2270 set(self.sparse['platform groups'].keys()))
2271
2272 if names_in_platforms_and_groups:
2273 msg = (
2274 'Platforms and platform groups must not share names. '
2275 'The following are in both sets:'
2276 )
2277 for name in names_in_platforms_and_groups:
2278 msg += f'\n * {name}'
2279 raise GlobalConfigError(msg)
2280
2281 def _expand_commas(self):
2282 """Expand comma separated section headers.
2283
2284 E.G. turn [platforms][foo, bar] into [platforms][foo] and
2285 platforms[bar].
2286 """
2287 if self.sparse.get('platforms'):
2288 self.sparse['platforms'] = expand_many_section(
2289 self.sparse['platforms']
2290 )
2291 if (
2292 self.sparse.get("install", {}).get("symlink dirs")
2293 ):
2294 self.sparse["install"]["symlink dirs"] = expand_many_section(
2295 self.sparse["install"]["symlink dirs"]
2296 )
2297
2298 def platform_dump(
2299 self,
2300 print_platform_names: bool = True,
2301 print_platforms: bool = True
2302 ) -> None:
2303 """Print informations about platforms currently defined.
2304 """
2305 if print_platform_names:
2306 self.dump_platform_names(self)
2307 if print_platforms:
2308 self.dump_platform_details(self)
2309
2310 @staticmethod
2311 def dump_platform_names(cfg) -> None:
2312 """Print a list of defined platforms and groups.
2313 """
2314 # [platforms] is always defined with at least localhost
2315 platforms = '\n'.join(cfg.get(['platforms']).keys())
2316 print(f'{PLATFORM_REGEX_TEXT}\n\nPlatforms\n---------', file=stderr)
2317 print(platforms)
2318 try:
2319 platform_groups = '\n'.join(cfg.get(['platform groups']).keys())
2320 except ItemNotFoundError:
2321 return
2322 print('\nPlatform Groups\n--------------', file=stderr)
2323 print(platform_groups)
2324
2325 @staticmethod
2326 def dump_platform_details(cfg) -> None:
2327 """Print platform and platform group configs.
2328 """
2329 for config in ['platforms', 'platform groups']:
2330 with suppress(ItemNotFoundError):
2331 printcfg({config: cfg.get([config], sparse=True)})