Debian Codegraph @

cylc/flow/util.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 """Misc functionality."""
17
18 import ast
19 from contextlib import suppress
20 from functools import (
21 lru_cache,
22 partial,
23 )
24 import json
25 import re
26 from textwrap import dedent
27 from typing import (
28 Any,
29 Callable,
30 Dict,
31 Generator,
32 List,
33 Optional,
34 Sequence,
35 Set,
36 Tuple,
37 TypeVar,
38 )
39
40
41 BOOL_SYMBOLS: Dict[bool, str] = {
42 # U+2A2F (vector cross product)
43 False: '⨯',
44 # U+2713 (check)
45 True: '✓'
46 }
47
48 _NAT_SORT_SPLIT = re.compile(r'(\d+(?:\.\d+)?)')
49
50
51 def uniq(iterable):
52 """Return a unique collection of the provided items preserving item order.
53
54 Useful for unhashable things like dicts, relies on __eq__ for testing
55 equality.
56
57 Examples:
58 >>> uniq([1, 1, 2, 3, 5, 8, 1])
59 [1, 2, 3, 5, 8]
60
61 """
62 ret = []
63 for item in iterable:
64 if item not in ret:
65 ret.append(item)
66 return ret
67
68
69 def iter_uniq(iterable):
70 """Iterate over an iterable omitting any duplicate entries.
71
72 Useful for unhashable things like dicts, relies on __eq__ for testing
73 equality.
74
75 Note:
76 More efficient than "uniq" for iteration use cases.
77
78 Examples:
79 >>> list(iter_uniq([1, 1, 2, 3, 5, 8, 1]))
80 [1, 2, 3, 5, 8]
81
82 """
83 cache = set()
84 for item in iterable:
85 if item not in cache:
86 cache.add(item)
87 yield item
88
89
90 def sstrip(text):
91 """Simple function to dedent and strip text.
92
93 Examples:
94 >>> print(sstrip('''
95 ... foo
96 ... bar
97 ... baz
98 ... '''))
99 foo
100 bar
101 baz
102
103 """
104 return dedent(text).strip()
105
106
107 def natural_sort_key(key: str, fcns=(int, str)) -> List[Any]:
108 """Returns a key suitable for sorting.
109
110 Splits the key into sortable chunks to preserve numerical order.
111
112 Examples:
113 >>> natural_sort_key('a1b2c3')
114 ['a', 1, 'b', 2, 'c', 3]
115 >>> natural_sort_key('a123b')
116 ['a', 123, 'b']
117 >>> natural_sort_key('a1.23b', fcns=(float, str))
118 ['a', 1.23, 'b']
119 >>> natural_sort_key('a.b')
120 ['a.b']
121 >>> natural_sort_key('a0.b')
122 ['a', 0, '.b']
123
124 # Default type casting
125 >>> natural_sort_key('a0.1b')
126 ['a', '0.1', 'b']
127
128 # Custom type casting
129 >>> natural_sort_key('a0.1b', fcns=(int, float, str))
130 ['a', 0.1, 'b']
131
132 """
133 ret = []
134 for item in _NAT_SORT_SPLIT.split(key):
135 for fcn in fcns:
136 with suppress(TypeError, ValueError):
137 ret.append(fcn(item))
138 break
139 if ret[-1] == '':
140 ret.pop(-1)
141 return ret
142
143
144 def natural_sort(items: List[str], fcns=(int, str)) -> None:
145 """Sorts a list preserving numerical order.
146
147 Note this is an in-place sort.
148
149 Examples:
150 >>> lst = ['a10', 'a1', 'a2']
151 >>> natural_sort(lst)
152 >>> lst
153 ['a1', 'a2', 'a10']
154
155 >>> lst = ['a1', '1a']
156 >>> natural_sort(lst)
157 >>> lst
158 ['1a', 'a1']
159
160 >>> lst = ['a0.b', 'a0b']
161 >>> natural_sort(lst)
162 >>> lst
163 ['a0.b', 'a0b']
164
165 """
166 items.sort(key=partial(natural_sort_key, fcns=fcns))
167
168
169 def format_cmd(cmd: Sequence[str], maxlen: int = 60) -> str:
170 r"""Convert a shell command list to a user-friendly representation.
171
172 Examples:
173 >>> format_cmd(['echo', 'hello', 'world'])
174 'echo hello world'
175 >>> format_cmd(['echo', 'hello', 'world'], 5)
176 'echo \\ \n hello \\ \n world'
177
178 """
179 ret = []
180 line = cmd[0]
181 for part in cmd[1:]:
182 if line and (len(line) + len(part) + 3) > maxlen:
183 ret.append(line)
184 line = part
185 else:
186 line += f' {part}'
187 if line:
188 ret.append(line)
189 return ' \\ \n '.join(ret)
190
191
192 def cli_format(cmd: List[str]):
193 """Format a command list as it would appear on the command line.
194
195 I.E. put spaces between the items in the list.
196
197 BACK_COMPAT: cli_format
198 From:
199 Python 3.7
200 To:
201 Python 3.8
202 Remedy:
203 Can replace with shlex.join
204
205 Examples:
206 >>> cli_format(['sleep', '10'])
207 'sleep 10'
208
209 """
210 return ' '.join(cmd)
211
212
213 def serialise_set(flow_nums: Optional[set] = None) -> str:
214 """Convert set to json, sorted.
215
216 For use when a sorted result is needed for consistency.
217
218 Examples:
219 >>> serialise_set({'b', 'a'})
220 '["a", "b"]'
221 >>> serialise_set({3, 2})
222 '[2, 3]'
223 >>> serialise_set()
224 '[]'
225
226 """
227 return _serialise_set(tuple(sorted(flow_nums or ())))
228
229
230 @lru_cache(maxsize=100)
231 def _serialise_set(flow_nums: tuple) -> str:
232 return json.dumps(flow_nums)
233
234
235 @lru_cache(maxsize=100)
236 def deserialise_set(flow_num_str: str) -> set:
237 """Convert json string to set.
238
239 Example:
240 >>> deserialise_set('[2, 3]') == {2, 3}
241 True
242 >>> deserialise_set('[]')
243 set()
244
245 """
246 return set(json.loads(flow_num_str))
247
248
249 def restricted_evaluator(
250 *whitelist: type,
251 error_class: Callable = ValueError,
252 ) -> Callable:
253 """Returns a Python eval statement restricted to whitelisted operations.
254
255 The "eval" function can be used to run arbitrary code. This is useful
256 but presents security issues. This returns an "eval" method which will
257 only allow whitelisted operations to be performed allowing it to be used
258 safely with user-provided input.
259
260 The code passed into the evaluator will be parsed into an abstract syntax
261 tree (AST), then that tree will be executed using Python's internal logic.
262 The evaluator will check the type of each node before it is executed and
263 fail with a ValueError if it is not permitted.
264
265 The node types are documented in the ast module:
266 https://docs.python.org/3/library/ast.html
267
268 The evaluator returned is only as safe as the nodes you whitelist, read the
269 docs carefully.
270
271 Note:
272 If you don't need to parse expressions, use ast.literal_eval instead.
273
274 Args:
275 whitelist:
276 Types to permit e.g. `ast.Expression`, see the ast docs for
277 details.
278 error_class:
279 An Exception class or callable which returns an Exception instance.
280 This is called and its result raised in the event that an
281 expression contains non-whitelisted operations. It will be provided
282 with the error message as an argument, additionally the following
283 keyword arguments will be provided if defined:
284 expr:
285 The expression the evaluator was called with.
286 expr_node:
287 The AST node containing the parsed expression.
288 error_node:
289 The first non-whitelisted AST node in the expression.
290 E.G. `<AST.Sub>` for a `-` operator.
291 error_type:
292 error_node.__class__.__name__.
293 E.G. `Sub` for a `-` operator.
294
295 Returns:
296 An "eval" function restricted to the whitelisted nodes.
297
298 Examples:
299 Optionally, provide an error class to be raised in the event of
300 non-whitelisted syntax (or you'll get ValueError):
301 >>> class RestrictedSyntaxError(Exception):
302 ... def __init__(self, message, error_node):
303 ... self.args = (str(error_node.__class__),)
304
305 Create an evaluator, whitelisting allowed node types:
306 >>> evaluator = restricted_evaluator(
307 ... ast.Expression, # required for all uses
308 ... ast.BinOp, # an operation (e.g. addition or division)
309 ... ast.Add, # the "+" operator
310 ... ast.Constant, # required for literals e.g. "1"
311 ... ast.Name, # required for using variables in expressions
312 ... ast.Load, # required for accessing variable values
313 ... error_class=RestrictedSyntaxError, # error to raise
314 ... )
315
316 This will correctly evaluate intended expressions:
317 >>> evaluator('1 + 1')
318 2
319
320 But will fail if a non-whitelisted node type is present:
321 >>> evaluator('1 - 1')
322 Traceback (most recent call last):
323 flow.util.RestrictedSyntaxError: <class ...Sub'>
324 >>> evaluator('my_function()')
325 Traceback (most recent call last):
326 flow.util.RestrictedSyntaxError: <class ...Call'>
327 >>> evaluator('__import__("os")')
328 Traceback (most recent call last):
329 flow.util.RestrictedSyntaxError: <class ...Call'>
330
331 The evaluator cannot see the containing scope:
332 >>> a = b = 1
333 >>> evaluator('a + b')
334 Traceback (most recent call last):
335 NameError: name 'a' is not defined
336
337 To use variables you must explicitly pass them in:
338 >>> evaluator('a + b', a=1, b=2)
339 3
340
341 """
342 # the node visitor is called for each node in the AST,
343 # this is the bit which rejects types which are not whitelisted
344 visitor = RestrictedNodeVisitor(whitelist)
345
346 def _eval(expr, **variables):
347 # parse the expression
348 try:
349 expr_node = ast.parse(expr.strip(), mode='eval')
350 except SyntaxError as exc:
351 raise _get_exception(
352 error_class,
353 f'{exc.msg}: {exc.text}',
354 {'expr': expr}
355 ) from None
356
357 # check against whitelisted types
358 try:
359 visitor.visit(expr_node)
360 except _RestrictedEvalError as exc:
361 # non-whitelisted node detected in expression
362 # => raise exception
363 error_node = exc.args[0]
364 raise _get_exception(
365 error_class,
366 (
367 f'Invalid expression: {expr}'
368 f'\n"{error_node.__class__.__name__}" not permitted'
369 ),
370 {
371 'expr': expr,
372 'expr_node': expr_node,
373 'error_node': error_node,
374 'error_type': error_node.__class__.__name__,
375 },
376 ) from None
377
378 # run the expresion
379 # Note: this may raise runtime errors
380 return eval( # nosec
381 # acceptable use of eval as only whitelisted operations are
382 # permitted
383 compile(expr_node, '<string>', 'eval'),
384 # deny access to builtins
385 {'__builtins__': {}},
386 # provide access to explicitly provided variables
387 variables,
388 )
389
390 return _eval
391
392
393 class RestrictedNodeVisitor(ast.NodeVisitor):
394 """AST node visitor which errors on non-whitelisted syntax.
395
396 Raises _RestrictedEvalError if a non-whitelisted node is visited.
397 """
398
399 def __init__(self, whitelist):
400 super().__init__()
401 self._whitelist: Tuple[type] = whitelist
402
403 def visit(self, node):
404 if not isinstance(node, self._whitelist):
405 # only permit whitelisted operations
406 raise _RestrictedEvalError(node)
407 return super().visit(node)
408
409
410 class _RestrictedEvalError(Exception):
411 """For internal use.
412
413 Raised in the event non-whitelisted syntax is detected in an expression.
414 """
415
416 def __init__(self, node):
417 self.node = node
418
419
420 def _get_exception(
421 error_class: Callable,
422 message: str,
423 context: dict
424 ) -> Exception:
425 """Helper which returns exception instances.
426
427 Filters the arguments in context by the parameters of the error_class.
428
429 This allows the error_class to decide what fields it wants, and for us
430 to add/change these params in the future.
431 """
432 import inspect # no need to import unless errors occur
433 try:
434 params = dict(inspect.signature(error_class).parameters)
435 except ValueError:
436 params = {}
437
438 context = {
439 key: value
440 for key, value in context.items()
441 if key in params
442 }
443
444 return error_class(message, **context)
445
446
447 class NameWalker(ast.NodeVisitor):
448 """AST node visitor which records all variable names in an expression.
449
450 Examples:
451 >>> tree = ast.parse('(foo and bar) or baz or qux')
452 >>> walker = NameWalker()
453 >>> walker.visit(tree)
454 >>> sorted(walker.names)
455 ['bar', 'baz', 'foo', 'qux']
456
457 """
458
459 def __init__(self):
460 super().__init__()
461 self._names = set()
462
463 def visit(self, node):
464 if isinstance(node, ast.Name):
465 self._names.add(node.id)
466 return super().visit(node)
467
468 @property
469 def names(self):
470 return self._names
471
472
473 def get_variable_names(expression):
474 walker = NameWalker()
475 walker.visit(ast.parse(expression))
476 return walker.names
477
478
479 Key = TypeVar('Key')
480
481
482 def get_connected_groups(
483 graph: Dict[Key, Set[Key]],
484 ) -> Generator[Set[Key], None, None]:
485 """Extract connected components in an undirected graph.
486
487 Args:
488 graph:
489 The graph in the form of an adjacency dictionary where each node
490 is listed against its adjacent nodes. Note, this method is for
491 undirected graphs, so this includes both upstream & downstream
492 nodes if you are using this with a directed graph.
493 e.g, {node: {adjacent_node1, adjacent_node2}, ...}
494
495 Yields:
496 Each connected group within the graph.
497
498 Example:
499 # a - b - c - d
500 # b - d
501 # e - f
502 >>> adjacency = {
503 ... 'a': {'b'},
504 ... 'b': {'a', 'c', 'd'},
505 ... 'c': {'b', 'd'},
506 ... 'd': {'c', 'b'},
507 ... 'e': {'f'},
508 ... 'f': {'e'},
509 ... }
510
511 >>> sorted(sorted(group) for group in get_connected_groups(adjacency))
512 [['a', 'b', 'c', 'd'], ['e', 'f']]
513
514 """
515 # track the nodes we have already visited
516 visited: Dict[Key, bool] = dict.fromkeys(graph, False)
517
518 def visit(key: Key, group: Set[Key]) -> Set[Key]:
519 """Visit a node in the graph (recursive)."""
520 visited[key] = True
521 group.add(key)
522 for neighbour in graph[key]:
523 if not visited[neighbour]:
524 visit(neighbour, group)
525 return group
526
527 for key in visited:
528 if not visited[key]:
529 yield visit(key, set())