Debian Codegraph @

cylc/flow/id_cli.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 import asyncio
18 import fnmatch
19 from pathlib import Path
20 import re
21 from typing import Optional, Dict, List, Tuple, Any
22
23 from metomi.isodatetime.parsers import TimePointParser
24 from metomi.isodatetime.exceptions import ISO8601SyntaxError
25
26 from cylc.flow import LOG
27 from cylc.flow.exceptions import (
28 InputError,
29 )
30 from cylc.flow.hostuserutil import get_user
31 from cylc.flow.id import (
32 Tokens,
33 contains_multiple_workflows,
34 tokenise,
35 upgrade_legacy_ids,
36 )
37 from cylc.flow.pathutil import EXPLICIT_RELATIVE_PATH_REGEX
38 from cylc.flow.workflow_files import (
39 check_flow_file,
40 detect_both_flow_and_suite,
41 get_flow_file,
42 get_workflow_run_dir,
43 infer_latest_run_from_id,
44 validate_workflow_name,
45 abort_if_flow_file_in_path
46 )
47
48
49 FN_CHARS = re.compile(r'[\*\?\[\]\!]')
50 TP_PARSER = TimePointParser()
51
52
53 def cli_tokenise(id_: str) -> Tokens:
54 """Tokenise with support for long-format datetimes.
55
56 If a cycle selector is present, it could be part of a long-format
57 ISO 8601 datetime that was erroneously split. Re-attach it if it
58 results in a valid datetime.
59
60 Examples:
61 >>> f = lambda t: {k: v for k, v in t.items() if v is not None}
62 >>> f(cli_tokenise('foo//2021-01-01T00:00Z'))
63 {'workflow': 'foo', 'cycle': '2021-01-01T00:00Z'}
64 >>> f(cli_tokenise('foo//2021-01-01T00:horse'))
65 {'workflow': 'foo', 'cycle': '2021-01-01T00', 'cycle_sel': 'horse'}
66 """
67 tokens = tokenise(id_)
68 cycle = tokens['cycle']
69 cycle_sel = tokens['cycle_sel']
70 if not (cycle and cycle_sel) or '-' not in cycle:
71 return tokens
72 cycle = f'{cycle}:{cycle_sel}'
73 try:
74 TP_PARSER.parse(cycle)
75 except ISO8601SyntaxError:
76 return tokens
77 dict.__setitem__(tokens, 'cycle', cycle)
78 del tokens['cycle_sel']
79 return tokens
80
81
82 def _parse_cli(*ids: str) -> List[Tokens]:
83 """Parse a list of Cylc identifiers as provided on the CLI.
84
85 * Validates identifiers.
86 * Expands relative references to absolute ones.
87 * Handles legacy Cylc7 syntax.
88
89 Args:
90 *ids (tuple): Identifier list.
91
92 Raises:
93 ValueError - For invalid identifiers or identifier lists.
94
95 Returns:
96 list - List of tokens dictionaries.
97
98 Examples:
99 # parse to tokens then detokenise back
100 >>> from cylc.flow.id import detokenise
101 >>> parse_back = lambda *ids: list(map(detokenise, _parse_cli(*ids)))
102
103 # list of workflows:
104 >>> parse_back('workworkflow')
105 ['workworkflow']
106 >>> parse_back('workworkflow/')
107 ['workworkflow']
108
109 >>> parse_back('workworkflow1', 'workworkflow2')
110 ['workworkflow1', 'workworkflow2']
111
112 # absolute references
113 >>> parse_back('workworkflow1//cycle1', 'workworkflow2//cycle2')
114 ['workworkflow1//cycle1', 'workworkflow2//cycle2']
115
116 # relative references:
117 >>> parse_back('workworkflow', '//cycle1', '//cycle2')
118 ['workworkflow//cycle1', 'workworkflow//cycle2']
119
120 # mixed references
121 >>> parse_back(
122 ... 'workworkflow1', '//cycle', 'workworkflow2',
123 ... '//cycle', 'workworkflow3//cycle'
124 ... )
125 ['workworkflow1//cycle',
126 'workworkflow2//cycle', 'workworkflow3//cycle']
127
128 # legacy ids:
129 >>> parse_back('workworkflow', 'task.123', 'a.b.c.234', '345/task')
130 ['workworkflow//123/task',
131 'workworkflow//234/a.b.c', 'workworkflow//345/task']
132
133 # errors:
134 >>> _parse_cli('////')
135 Traceback (most recent call last):
136 cylc.flow.exceptions.InputError: Invalid ID: ////
137
138 >>> parse_back('//cycle')
139 Traceback (most recent call last):
140 cylc.flow.exceptions.InputError: Relative reference must follow an
141 incomplete one...
142
143 >>> parse_back('workflow//cycle', '//cycle')
144 Traceback (most recent call last):
145 cylc.flow.exceptions.InputError: Relative reference must follow an
146 incomplete one...
147
148 >>> parse_back('workflow///cycle/')
149 Traceback (most recent call last):
150 cylc.flow.exceptions.InputError: Invalid ID: workflow///cycle/
151
152 """
153 # upgrade legacy ids if required
154 ids = upgrade_legacy_ids(*ids)
155
156 partials: Optional[Tokens] = None
157 partials_expended: bool = False
158 tokens_list: List[Tokens] = []
159 for id_ in ids:
160 try:
161 tokens = cli_tokenise(id_)
162 except ValueError:
163 if id_.endswith('/') and not id_.endswith('//'): # noqa: SIM106
164 # tolerate IDs that end in a single slash on the CLI
165 # (e.g. CLI auto completion)
166 try:
167 # this ID is invalid with or without the trailing slash
168 tokens = cli_tokenise(id_[:-1])
169 except ValueError:
170 raise InputError(f'Invalid ID: {id_}') from None
171 else:
172 raise InputError(f'Invalid ID: {id_}') from None
173 is_partial = tokens.get('workflow') and not tokens.get('cycle')
174 is_relative = not tokens.get('workflow')
175
176 if partials:
177 # we previously encountered a workflow ID which did not specify a
178 # cycle
179 if is_partial:
180 # this is an absolute ID
181 if not partials_expended:
182 # no relative references were made to the previous ID
183 # so add the whole workflow to the tokens list
184 tokens_list.append(partials)
185 partials = tokens
186 partials_expended = False
187 elif is_relative:
188 # this is a relative reference => expand it using the context
189 # of the partial ID
190 tokens_list.append(Tokens(
191 **{
192 **partials,
193 **tokens,
194 },
195 ))
196 partials_expended = True
197 else:
198 # this is a fully expanded reference
199 tokens_list.append(tokens)
200 partials = None
201 partials_expended = False
202 else:
203 # there was no previous reference that a relative reference
204 # could apply to
205 if is_partial:
206 partials = tokens
207 partials_expended = False
208 elif is_relative:
209 # so a relative reference is an error
210 raise InputError(
211 'Relative reference must follow an incomplete one.'
212 '\nE.G: workflow //cycle/task'
213 )
214 else:
215 tokens_list.append(tokens)
216
217 if partials and not partials_expended:
218 # if the last ID was a "partial" but not expanded add it to the list
219 tokens_list.append(tokens)
220
221 return tokens_list
222
223
224 def parse_ids(*args, **kwargs):
225 return asyncio.run(parse_ids_async(*args, **kwargs))
226
227
228 async def parse_ids_async(
229 *ids: str,
230 src: bool = False,
231 match_workflows: bool = False,
232 match_active: Optional[bool] = True,
233 infer_latest_runs: bool = True,
234 constraint: str = 'tasks',
235 max_workflows: Optional[int] = None,
236 max_tasks: Optional[int] = None,
237 alt_run_dir: Optional[str] = None,
238 ) -> Tuple[Dict[str, List[Tokens]], Any]:
239 """Parse IDs from the command line.
240
241 Args:
242 ids:
243 Collection of IDs to parse.
244 src:
245 If True then source workflows can be provided via an absolute
246 path or a relative path starting "./".
247 Infers max_workflows = 1.
248 match_workflows:
249 If True workflows can be globs.
250 match_active:
251 If match_workflows is True this determines the wokflow state
252 filter.
253
254 True - running & paused
255 False - stopped
256 None - any
257 infer_latest_runs:
258 If true infer the latest run for a workflow when applicable
259 (allows 'cylc play one' rather than 'cylc play one/run1').
260 constraint:
261 Constrain the types of objects the IDs should relate to.
262
263 workflows - only allow workflows.
264 tasks - require tasks to be defined.
265 mixed - permit tasks not to be defined.
266 max_workflows:
267 Specify the maximum number of workflows permitted to be specified
268 in the ids.
269 max_tasks:
270 Specify the maximum number of tasks permitted to be specified
271 in the ids.
272 alt_run_dir:
273 Specify a non-standard cylc-run location, e.g. for another user.
274
275 Returns:
276 With src=True":
277 (workflows, flow_file_path)
278 Else:
279 (workflow, multi_mode)
280 Where:
281 workflows:
282 Dictionary containing workflow ID strings against lists of
283 relative tokens specified on that workflow.
284 {workflow_id: [relative_tokens]}
285 flow_file_path:
286 Path to the flow.cylc (or suite.rc in Cylc 7 compat mode)
287 multi_mode:
288 True if multiple workflows selected or if globs were provided
289 in the IDs.
290
291 """
292 if constraint not in {'tasks', 'workflows', 'mixed'}:
293 raise ValueError(f'Invalid constraint: {constraint}')
294
295 tokens_list = []
296 src_path = None
297 flow_file_path = None
298 multi_mode = False
299
300 if src:
301 # can only have one workflow if permitting source workflows
302 max_workflows = 1
303 ret = _parse_src_path(ids[0])
304 if ret:
305 # yes, replace the path with an ID and continue
306 workflow_id, src_path, flow_file_path = ret
307 ids = (
308 Tokens(
309 user=None,
310 workflow=workflow_id,
311 ).id + '//',
312 *ids[1:]
313 )
314 tokens_list.extend(_parse_cli(*ids))
315
316 # ensure the IDS are compatible with the constraint
317 _validate_constraint(*tokens_list, constraint=constraint)
318
319 if match_workflows:
320 # match workflow IDs via cylc-scan
321 # if any patterns are present switch to multi_mode for clarity
322 multi_mode = await _expand_workflow_tokens(
323 tokens_list,
324 match_active=match_active,
325 )
326
327 # check the workflow part of the IDs are valid
328 _validate_workflow_ids(*tokens_list, src_path=src_path)
329
330 if not multi_mode:
331 # check how many workflows we are working on
332 multi_mode = contains_multiple_workflows(tokens_list)
333
334 # infer the run number if not specified the ID (and if possible)
335 if infer_latest_runs:
336 _infer_latest_runs(
337 tokens_list, src_path=src_path, alt_run_dir=alt_run_dir)
338
339 _validate_number(
340 *tokens_list,
341 max_workflows=max_workflows,
342 max_tasks=max_tasks,
343 )
344
345 workflows = _batch_tokens_by_workflow(*tokens_list, constraint=constraint)
346
347 if src:
348 if not flow_file_path:
349 # get the workflow file path from the run dir
350 flow_file_path = get_flow_file(next(iter(workflows)))
351 return workflows, flow_file_path
352 return workflows, multi_mode
353
354
355 def parse_id(*args, **kwargs) -> Tuple[str, Optional[Tokens], Any]:
356 return asyncio.run(parse_id_async(*args, **kwargs))
357
358
359 async def parse_id_async(
360 *args,
361 **kwargs,
362 ) -> Tuple[str, Optional[Tokens], Any]:
363 """Special case of parse_ids with a more convenient return format.
364
365 Infers:
366 max_workflows: 1
367 max_tasks: 1
368
369 """
370 workflows, ret = await parse_ids_async(
371 *args,
372 **{ # type: ignore
373 **kwargs,
374 'max_workflows': 1,
375 'max_tasks': 1,
376 },
377 )
378 workflow_id = next(iter(workflows))
379 tokens_list = workflows[workflow_id]
380 tokens: Optional[Tokens]
381 if tokens_list:
382 tokens = tokens_list[0]
383 else:
384 tokens = None
385 return workflow_id, tokens, ret
386
387
388 def contains_fnmatch(string: str) -> bool:
389 """Return True if a string contains filename match chars.
390
391 Examples:
392 >>> contains_fnmatch('a')
393 False
394 >>> contains_fnmatch('*')
395 True
396 >>> contains_fnmatch('abc')
397 False
398 >>> contains_fnmatch('a*c')
399 True
400 """
401 return bool(FN_CHARS.search(string))
402
403
404 def _validate_constraint(*tokens_list, constraint=None):
405 if constraint == 'workflows':
406 for tokens in tokens_list:
407 if tokens.is_null or tokens.is_task_like:
408 raise InputError('IDs must be workflows')
409 return
410 if constraint == 'tasks':
411 for tokens in tokens_list:
412 if tokens.is_null or not tokens.is_task_like:
413 raise InputError('IDs must be tasks')
414 return
415 if constraint == 'mixed':
416 for tokens in tokens_list:
417 if tokens.is_null:
418 raise InputError('IDs cannot be null.')
419 return
420
421
422 def _validate_workflow_ids(*tokens_list, src_path):
423 for ind, tokens in enumerate(tokens_list):
424 if tokens['user'] and (tokens['user'] != get_user()):
425 raise InputError(
426 "Operating on other users' workflows is not supported"
427 )
428 if not src_path:
429 validate_workflow_name(tokens['workflow'])
430 if ind == 0 and src_path:
431 # source workflow passed in as a path
432 pass
433 else:
434 src_path = Path(get_workflow_run_dir(tokens['workflow']))
435 if src_path.is_file():
436 raise InputError(
437 f'Workflow ID cannot be a file: {tokens["workflow"]}'
438 )
439 if tokens['cycle'] and tokens['cycle'].startswith('run'):
440 # issue a warning if the run number is provided after the //
441 # separator e.g. workflow//run1 rather than workflow/run1//
442 suggested = Tokens(
443 user=tokens['user'],
444 workflow=f'{tokens["workflow"]}/{tokens["cycle"]}',
445 cycle=tokens['task'],
446 task=tokens['job'],
447 )
448 LOG.warning(f'Did you mean: {suggested.id}')
449 detect_both_flow_and_suite(src_path)
450
451
452 def _infer_latest_runs(tokens_list, src_path, alt_run_dir=None):
453 for ind, tokens in enumerate(tokens_list):
454 if ind == 0 and src_path:
455 # source workflow passed in as a path
456 continue
457 tokens_list[ind] = tokens.duplicate(
458 workflow=infer_latest_run_from_id(
459 tokens['workflow'], alt_run_dir
460 )
461 )
462 pass
463
464
465 def _validate_number(*tokens_list, max_workflows=None, max_tasks=None):
466 if not max_workflows and not max_tasks:
467 return
468 workflows_seen = set()
469 tasks_count = 0
470 for tokens in tokens_list:
471 if tokens.is_task_like:
472 tasks_count += 1
473 if tokens["workflow"] is not None:
474 workflows_seen.add(tokens["workflow"])
475 if max_workflows and len(workflows_seen) > max_workflows:
476 raise InputError(
477 f'IDs contain too many workflows (max {max_workflows})'
478 )
479 if max_tasks and tasks_count > max_tasks:
480 raise InputError(
481 f'IDs contain too many cycles/tasks/jobs (max {max_tasks})'
482 )
483
484
485 def _batch_tokens_by_workflow(*tokens_list, constraint=None):
486 """Sorts tokens into lists by workflow ID.
487
488 Example:
489 >>> _batch_tokens_by_workflow(
490 ... Tokens(workflow='x', cycle='1'),
491 ... Tokens(workflow='x', cycle='2'),
492 ... )
493 {'x': [<id: //1>, <id: //2>]}
494
495 """
496 workflow_tokens = {}
497 for tokens in tokens_list:
498 w_tokens = workflow_tokens.setdefault(tokens['workflow'], [])
499 relative_tokens = tokens.task
500 if constraint in {'mixed', 'workflows'} and relative_tokens.is_null:
501 continue
502 w_tokens.append(relative_tokens)
503 return workflow_tokens
504
505
506 async def _expand_workflow_tokens(tokens_list, match_active=True):
507 multi_mode = False
508 for tokens in list(tokens_list):
509 workflow = tokens['workflow']
510 if not contains_fnmatch(workflow):
511 # no expansion to perform
512 continue
513 else:
514 # remove the original entry
515 multi_mode = True
516 tokens_list.remove(tokens)
517 async for tokens in _expand_workflow_tokens_impl(
518 tokens,
519 match_active=match_active,
520 ):
521 # add the expanded tokens back onto the list
522 tokens_list.append(tokens)
523 return multi_mode
524
525
526 async def _expand_workflow_tokens_impl(tokens, match_active=True):
527 """Use "cylc scan" to expand workflow patterns."""
528 workflow_sel = tokens['workflow_sel']
529 if workflow_sel and workflow_sel != 'running':
530 raise InputError(
531 f'The workflow selector :{workflow_sel} is not'
532 'currently supported.'
533 )
534
535 # import only when needed to avoid slowing CLI unnecessarily
536 from cylc.flow.network.scan import (
537 filter_name,
538 is_active,
539 scan,
540 )
541 # construct the pipe
542 pipe = scan | filter_name(fnmatch.translate(tokens['workflow']))
543 if match_active is not None:
544 pipe |= is_active(match_active)
545
546 # iter the results
547 async for workflow in pipe:
548 yield tokens.duplicate(workflow=workflow['name'])
549
550
551 def _parse_src_path(id_):
552 """Parse CLI workflow arg to find a valid source directory.
553
554 Returns:
555 - (dir name, dir path, config file path) if id_ is a valid src dir.
556 - or None, if id_ could be a workflow ID
557
558 A valid source directory is:
559 - an existing directory that contains a worklow config file
560 and not a relative path (which could be a workflow ID), i.e. it must be:
561 - the current directory (".")
562 - or a directory path that starts with "./"
563 - or an absolute directory path
564
565 It's OK if id_ happens to match a relative path to an existing directory or
566 file (other than a workflow config file) because there could be a workflow
567 ID with the same name.
568
569 """
570 abort_if_flow_file_in_path(Path(id_))
571 src_path = Path(id_)
572 if (
573 not EXPLICIT_RELATIVE_PATH_REGEX.match(id_)
574 and not src_path.is_absolute()
575 ):
576 # Not a valid source path, but it could be a workflow ID.
577 return None
578
579 src_dir_path = src_path.resolve()
580 if not src_dir_path.exists():
581 raise InputError(f'Source directory not found: {src_dir_path}')
582
583 if not src_dir_path.is_dir():
584 raise InputError(f'Path is not a source directory: {src_dir_path}')
585
586 src_file_path = check_flow_file(src_dir_path)
587
588 return src_dir_path.name, src_dir_path, src_file_path