Debian Codegraph @

cylc/flow/network/scan.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 """Functionality for searching for workflows running as the current user.
17
18 The :py:func:`scan` asynchronous generator yields workflows. Iterate
19 over them using an ``async for`` statement::
20
21 async for flow in scan():
22 print(flow['name'])
23
24 For further functionality construct a pipe::
25
26 pipe = scan | is_active(True) | contact_info
27 async for flow in pipe:
28 print(f'{flow["name"]} {flow["CYLC_WORKFLOW_HOST"]}')
29
30 There are filters which you can you to omit workflows e.g.
31 :py:func:`cylc_version` and transformers which acquire more information
32 e.g. :py:func:`contact_info`.
33
34 .. note: we must manually list functions so they get built into the docs
35
36 .. autofunction:: scan
37 .. autofunction:: filter_name
38 .. autofunction:: is_active
39 .. autofunction:: contact_info
40 .. autofunction:: cylc_version
41 .. autofunction:: api_version
42 .. autofunction:: graphql_query
43 .. autofunction:: title
44 .. autofunction:: workflow_params
45
46 """
47
48 import asyncio
49 from pathlib import Path
50 import re
51 from typing import (
52 AsyncGenerator,
53 Dict,
54 Iterable,
55 List,
56 Optional,
57 Tuple,
58 Union,
59 cast,
60 )
61
62 from packaging.specifiers import SpecifierSet
63 from packaging.version import parse as parse_version
64
65 from cylc.flow import LOG
66 from cylc.flow.async_util import (
67 pipe,
68 scandir,
69 )
70 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
71 from cylc.flow.exceptions import (
72 ClientError,
73 ClientTimeout,
74 WorkflowStopped,
75 )
76 from cylc.flow.network.client import WorkflowRuntimeClient
77 from cylc.flow.pathutil import (
78 get_cylc_run_dir,
79 get_workflow_run_dir,
80 )
81 from cylc.flow.rundb import CylcWorkflowDAO
82 from cylc.flow.workflow_files import (
83 ContactFileFields,
84 WorkflowFiles,
85 get_workflow_title,
86 load_contact_file_async,
87 )
88
89
90 SERVICE = Path(WorkflowFiles.Service.DIRNAME)
91 CONTACT = Path(WorkflowFiles.Service.CONTACT)
92
93 EXCLUDE_FILES = {
94 WorkflowFiles.RUN_N,
95 WorkflowFiles.Install.SOURCE
96 }
97
98
99 REQUIRED_FIELDS = [
100 ContactFileFields.API,
101 ContactFileFields.HOST,
102 ContactFileFields.NAME
103 ]
104
105
106 def dir_is_flow(listing: Iterable[Path]) -> Optional[bool]:
107 """Return True if a Path contains a flow at the top level.
108
109 Args:
110 listing:
111 A listing of the directory in question as a list of
112 ``pathlib.Path`` objects.
113
114 Returns:
115 - True if the directory:
116 - Is a Cylc 8 workflow.
117 - Is a Cylc 7 workflow that has not yet been run.
118 - Is a Cylc 7 workflow running under Cylc 8 in compatibility mode.
119 - False if the directory:
120 - Is not a workflow.
121 - None if the directory:
122 - Is an incompatible workflow (e.g. a Cylc 7 workflow running under
123 Cylc 7).
124
125 """
126 names = {path.name for path in listing}
127
128 # Cylc 8:
129 # - "cylc install" creates a source dir link and a "log' directory as
130 # well as installing the flow.cylc or suite.rc, but only the workflow
131 # definition is needed for it to be runnable by Cylc 8.
132
133 # Cylc 7:
134 # - suites manually registered in-place do not have a suite.rc in the run
135 # directory and cannot be run by Cylc 8
136 # - suites installed (manually or by "rose suite-run") can be run by Cylc 8
137 # if not already run by Cylc 7
138 # - "rose suite-run --install-only" creates a "log/suite" directory
139 # - running with Cylc 7 creates "log/suite/log"
140
141 if WorkflowFiles.FLOW_FILE in names:
142 # A Cylc 8 workflow.
143 return True
144
145 elif WorkflowFiles.SUITE_RC in names:
146 # An installed Cylc 7 workflow ...
147 for path in listing:
148 if path.name == WorkflowFiles.LogDir.DIRNAME:
149 if (
150 (path / 'suite' / 'log').exists()
151 and not (path / 'scheduler').exists()
152 ):
153 # ... already run by Cylc 7 (and not re-run by Cylc 8 after
154 # removing the DB)
155 return None
156 else:
157 # ... can be run by Cylc 8
158 return True
159
160 # Has not been run (and not installed by "rose suite-run" or
161 # "cylc install"). Can be run by Cylc 8.
162 return True
163
164 else:
165 # A random directory
166 return False
167
168
169 @pipe
170 async def scan_multi(
171 dirs: Iterable[Path],
172 max_depth: Optional[int] = None
173 ) -> AsyncGenerator[dict, None]:
174 """List flows from multiple directories.
175
176 This is intended for listing uninstalled flows though will work for
177 installed ones.
178
179 Args:
180 dirs
181 """
182 if max_depth is None:
183 max_depth = glbl_cfg().get(['install', 'max depth'])
184 for dir_ in dirs:
185 async for flow in scan(
186 run_dir=dir_,
187 scan_dir=dir_,
188 max_depth=max_depth
189 ):
190 # set the flow name as the full path
191 flow['name'] = dir_ / flow['name']
192 yield flow
193
194
195 @pipe
196 async def scan(
197 run_dir: Optional[Path] = None,
198 scan_dir: Optional[Path] = None,
199 max_depth: Optional[int] = None
200 ) -> AsyncGenerator[Dict[str, Union[str, Path]], None]:
201 """List flows installed on the filesystem.
202
203 Args:
204 run_dir:
205 The run dir to look for workflows in, defaults to ~/cylc-run.
206
207 All workflow registrations will be given relative to this path.
208 scan_dir:
209 The directory to scan for workflows in.
210
211 Use in combination with run_dir if you want to scan a subdir
212 within the run_dir.
213 max_depth:
214 The maximum number of levels to descend before bailing.
215
216 * ``max_depth=1`` will pick up top-level workflows (e.g. ``foo``).
217 * ``max_depth=2`` will pick up nested workflows (e.g. ``foo/bar``).
218
219 Yields:
220 dict - Dictionary containing information about the flow.
221
222 """
223 cylc_run_dir = Path(get_cylc_run_dir())
224 if not run_dir:
225 run_dir = cylc_run_dir
226 if not scan_dir:
227 scan_dir = run_dir
228 if max_depth is None:
229 max_depth = glbl_cfg().get(['install', 'max depth'])
230
231 running: List[asyncio.tasks.Task] = []
232
233 # wrapper for scandir to preserve context
234 async def _scandir(path: Path, depth: int) -> Tuple[Path, int, List[Path]]:
235 contents = await scandir(path)
236 return path, depth, contents
237
238 def _scan_subdirs(listing: List[Path], depth: int) -> None:
239 for subdir in listing:
240 if subdir.is_dir() and subdir.stem not in EXCLUDE_FILES:
241 running.append(
242 asyncio.create_task(
243 _scandir(subdir, depth + 1)
244 )
245 )
246
247 # perform the first directory listing
248 try:
249 scan_dir_listing = await scandir(scan_dir)
250 except FileNotFoundError:
251 return
252 if scan_dir != cylc_run_dir and dir_is_flow(scan_dir_listing):
253 # If the scan_dir itself is a workflow run dir, yield nothing
254 return
255
256 _scan_subdirs(scan_dir_listing, depth=0)
257
258 # perform all further directory listings
259 while running:
260 # wait here until there's something to do
261 done, _ = await asyncio.wait(
262 running,
263 return_when=asyncio.FIRST_COMPLETED
264 )
265 for task in done:
266 try:
267 path, depth, contents = task.result()
268 except FileNotFoundError:
269 # directory has been removed since the scan was scheduled
270 running.remove(task)
271 continue
272 running.remove(task)
273 is_flow = dir_is_flow(contents)
274 if is_flow:
275 # this is a flow directory
276 yield {
277 'name': str(path.relative_to(run_dir)),
278 'path': path,
279 }
280 elif is_flow is False and depth < max_depth:
281 # we may have a nested flow, lets see...
282 _scan_subdirs(contents, depth)
283 # don't allow this to become blocking
284 await asyncio.sleep(0)
285
286
287 def join_regexes(*patterns):
288 """Combine multiple regexes using OR logic."""
289 return (re.compile(rf'({"|".join(patterns)})'),), {}
290
291
292 @pipe(preproc=join_regexes)
293 async def filter_name(flow, pattern):
294 """Filter flows by name.
295
296 Args:
297 flow (dict):
298 Flow information dictionary, provided by scan through the pipe.
299 pattern (re.Pattern):
300 One or more regex patterns as strings.
301 This will return True if any of the patterns match.
302
303 """
304 return bool(pattern.match(flow['name']))
305
306
307 @pipe
308 async def is_active(flow, is_active):
309 """Filter flows by the presence of a contact file.
310
311 Args:
312 flow (dict):
313 Flow information dictionary, provided by scan through the pipe.
314 is_active (bool):
315 True to filter for running flows.
316 False to filter for stopped and unregistered flows.
317
318 """
319 service = flow['path'] / SERVICE
320 # NOTE: We must list the service directory contents rather than checking
321 # for the existence of the contact file directly, because listing the
322 # directory forces NFS filesystems to recompute their local cache.
323 # See https://github.com/cylc/cylc-flow/issues/6506
324 try:
325 contents = await scandir(service)
326 except FileNotFoundError:
327 _is_active = False
328 else:
329 _is_active = any(
330 path.name == WorkflowFiles.Service.CONTACT for path in contents
331 )
332 if _is_active:
333 flow['contact'] = service / CONTACT
334 return _is_active == is_active
335
336
337 @pipe
338 async def contact_info(flow):
339 """Read information from the contact file.
340
341 Requires:
342 * is_active(True)
343
344 Args:
345 flow (dict):
346 Flow information dictionary, provided by scan through the pipe.
347
348 """
349 flow.update(
350 await load_contact_file_async(flow['name'], run_dir=flow['path'])
351 )
352 return flow
353
354
355 @pipe
356 async def validate_contact_info(flow):
357 """Return flow if contact file is valid.
358
359 This checks that the contact file contains the minimal set of fields
360 required for most purposes.
361
362 This helps to protect against blank or corrupted (yet valid) contact files
363 which would otherwise pass through without raising errors.
364 """
365 for contact_field in REQUIRED_FIELDS:
366 try:
367 flow[contact_field]
368 except KeyError:
369 return False
370 return flow
371
372
373 def parse_requirement(requirement_string):
374 """Parse a requirement from a requirement string."""
375 return (SpecifierSet(requirement_string),), {}
376
377
378 @pipe(preproc=parse_requirement)
379 async def cylc_version(flow, requirement):
380 """Filter by cylc version.
381
382 Requires:
383 * is_active(True)
384 * contact_info
385
386 Args:
387 flow (dict):
388 Flow information dictionary, provided by scan through the pipe.
389 requirement (str):
390 Requirement specifier in PEP 440 format e.g. ``> 8, < 9``
391
392 """
393 return parse_version(flow[ContactFileFields.VERSION]) in requirement
394
395
396 @pipe(preproc=parse_requirement)
397 async def api_version(flow, requirement):
398 """Filter by the cylc API version.
399
400 Requires:
401 * is_active(True)
402 * contact_info
403
404 Args:
405 flow (dict):
406 Flow information dictionary, provided by scan through the pipe.
407 requirement (str):
408 Requirement specifier in PEP 440 format e.g. ``> 8, < 9``
409
410 """
411 return parse_version(flow[ContactFileFields.API]) in requirement
412
413
414 def format_query(fields, filters=None):
415 ret = ''
416 stack = [(None, fields)]
417 while stack:
418 path, fields = stack.pop()
419 if isinstance(fields, dict):
420 leftover_fields = []
421 for key, value in fields.items():
422 if value:
423 stack.append((
424 key,
425 value
426 ))
427 else:
428 leftover_fields.append(key)
429 if leftover_fields:
430 fields = leftover_fields
431 else:
432 continue
433 if path:
434 ret += '\n' + f'{path} {{'
435 for field in fields:
436 ret += f'\n {field}'
437 ret += '\n}'
438 else:
439 for field in fields:
440 ret += f'\n{field}'
441 return (ret + '\n',), {'filters': filters}
442
443
444 @pipe(preproc=format_query)
445 async def graphql_query(flow: dict, fields: Iterable, filters=None):
446 """Obtain information from a GraphQL request to the flow.
447
448 Requires:
449 * is_active(True)
450 * contact_info
451
452 Args:
453 flow:
454 Flow information dictionary, provided by scan through the pipe.
455 fields:
456 Iterable containing the fields to request e.g::
457
458 ['id', 'name']
459
460 One level of nesting is supported e.g::
461
462 {'name': None, 'meta': ['title']}
463 filters (list):
464 Filter by the data returned from the query.
465 List in the form ``[(key, ...), value]``, e.g::
466
467 # state must be running
468 [('state',), 'running']
469
470 # state must be running or paused
471 [('state',), ('running', 'paused')]
472
473 """
474 query = f'query {{ workflows(ids: ["{flow["name"]}"]) {{ {fields} }} }}'
475 try:
476
477 client = WorkflowRuntimeClient(
478 flow['name'],
479 # use contact_info data if present for efficiency
480 host=flow.get('CYLC_WORKFLOW_HOST'),
481 port=flow.get('CYLC_WORKFLOW_PORT'),
482 scheduler_version=flow.get('CYLC_VERSION'),
483 )
484 except WorkflowStopped:
485 LOG.warning(f'Workflow not running: {flow["name"]}')
486 return False
487 try:
488 ret = cast(
489 'dict',
490 await client.async_request(
491 'graphql',
492 {
493 'request_string': query,
494 'variables': {}
495 }
496 )
497 )
498 except WorkflowStopped:
499 LOG.warning(f'Workflow not running: {flow["name"]}')
500 return False
501 except ClientTimeout:
502 LOG.exception(
503 f'Timeout: name: {flow["name"]}, '
504 f'host: {client.host}, '
505 f'port: {client.port}'
506 )
507 return False
508 except ClientError as exc:
509 LOG.exception(exc)
510 return False
511 else:
512 # stick the result into the flow object
513 for item in ret:
514 if 'error' in item:
515 LOG.exception(item['error']['message'])
516 return False
517 for workflow in ret.get('workflows', []):
518 flow.update(workflow)
519
520 # process filters
521 for field, value in filters or []:
522 for field_ in field:
523 value_ = flow[field_]
524 if isinstance(value, Iterable):
525 if value_ not in value:
526 return False
527 else:
528 if value_ != value:
529 return False
530
531 return flow
532
533
534 @pipe
535 async def title(flow):
536 """Attempt to parse the workflow title out of the flow config file.
537
538 .. warning::
539 This uses a fast but dumb method which may fail to extract the workflow
540 title.
541
542 Obtaining the workflow title via :py:func:`graphql_query` is preferable
543 for running flows.
544
545 """
546 flow['title'] = get_workflow_title(flow['name'])
547 return flow
548
549
550 @pipe
551 async def workflow_params(flow):
552 """Extract workflow parameter entries from the workflow database.
553
554 Requires:
555 * is_active(True)
556 """
557 # NOTE: use the public DB for reading
558 # (only the scheduler process/thread should access the private database)
559 db_file = Path(get_workflow_run_dir(
560 flow['name'], WorkflowFiles.LogDir.DIRNAME, WorkflowFiles.LogDir.DB
561 ))
562 if db_file.exists():
563 with CylcWorkflowDAO(db_file, is_public=True) as dao:
564 flow['workflow_params'] = dict(dao.select_workflow_params())
565
566 return flow