Debian Codegraph @

cylc/flow/host_select.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 """Functionality for selecting a host from pre-defined list.
18
19 Ranking/filtering hosts can be achieved using Python expressions which work
20 with the `psutil` interfaces.
21
22 These expressions are used-defined, buy run a restricted evluation environment
23 where only certain whitelisted operations are permitted.
24
25 Examples:
26 >>> RankingExpressionEvaluator('1 + 1')
27 2
28 >>> RankingExpressionEvaluator('1 * -1')
29 -1
30 >>> RankingExpressionEvaluator('1 < a', a=2)
31 True
32 >>> RankingExpressionEvaluator('1 in (1, 2, 3)')
33 True
34 >>> RankingExpressionEvaluator('[1,2,3][-1] ** 2')
35 9
36 >>> import psutil
37 >>> RankingExpressionEvaluator(
38 ... 'a.available > 0',
39 ... a=psutil.virtual_memory()
40 ... )
41 True
42
43 If you try to get it to do something you're not allowed to:
44 >>> RankingExpressionEvaluator('open("foo")')
45 Traceback (most recent call last):
46 ValueError: Invalid expression: open("foo")
47 "Call" not permitted
48
49 >>> RankingExpressionEvaluator('import sys')
50 Traceback (most recent call last):
51 ValueError: invalid syntax: import sys
52
53 If you try to get hold of something you aren't supposed to:
54 >>> answer = 42 # only variables explicitly passed in should work
55 >>> RankingExpressionEvaluator('answer')
56 Traceback (most recent call last):
57 NameError: name 'answer' is not defined
58
59 If you try to do something which doesn't make sense:
60 >>> RankingExpressionEvaluator('a.b.c') # no value "a.b.c"
61 Traceback (most recent call last):
62 NameError: name 'a' is not defined
63
64 """
65
66 import ast
67 from collections import namedtuple
68 from functools import lru_cache
69 from io import BytesIO
70 import json
71 import random
72 from socket import gaierror
73 from time import sleep
74 import token
75 from tokenize import tokenize
76 from typing import (
77 Dict,
78 Iterable,
79 List,
80 Optional,
81 Set,
82 Tuple,
83 )
84
85 from cylc.flow import LOG
86 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
87 from cylc.flow.exceptions import (
88 GlobalConfigError,
89 HostSelectException,
90 NoHostsError,
91 )
92 from cylc.flow.hostuserutil import (
93 get_fqdn_by_host,
94 is_remote_host,
95 )
96 from cylc.flow.remote import (
97 cylc_server_cmd,
98 run_cmd,
99 )
100 from cylc.flow.terminal import parse_dirty_json
101 from cylc.flow.util import restricted_evaluator
102
103
104 # evaluates ranking expressions
105 # (see module docstring for examples)
106 RankingExpressionEvaluator = restricted_evaluator(
107 ast.Expression,
108 # variables
109 ast.Name, ast.Load, ast.Attribute, ast.Subscript,
110 # opers
111 ast.BinOp, ast.operator, ast.UnaryOp, ast.unaryop,
112 # types
113 ast.Constant,
114 # comparisons
115 ast.Compare, ast.cmpop, ast.List, ast.Tuple,
116 )
117
118
119 GLBL_CFG_STR = 'global.cylc[scheduler][run hosts]ranking'
120
121
122 def select_workflow_host(cached=True):
123 """Return a host as specified in `[workflow hosts]`.
124
125 * Condemned hosts are filtered out.
126 * Filters out hosts excluded by ranking (if defined).
127 * Ranks by ranking (if defined).
128
129 Args:
130 cached (bool):
131 Use a cached version of the global configuration if True
132 else reload from the filesystem.
133
134 Returns:
135 tuple - See `select_host` for details.
136
137 Raises:
138 HostSelectException:
139 See `select_host` for details.
140
141 """
142 # get the global config, if cached = False a new config instance will
143 # be returned with the up-to-date configuration.
144 global_config = glbl_cfg(cached=cached)
145
146 # condemned hosts may be suffixed with an "!" to activate "force mode"
147 blacklist = []
148 for host in global_config.get(['scheduler', 'run hosts', 'condemned'], []):
149 if host.endswith('!'):
150 host = host[:-1]
151 blacklist.append(host)
152
153 return select_host(
154 # list of workflow hosts
155 global_config.get([
156 'scheduler', 'run hosts', 'available'
157 ]) or ['localhost'],
158 # rankings to apply
159 ranking_string=global_config.get([
160 'scheduler', 'run hosts', 'ranking'
161 ]),
162 # list of condemned hosts
163 blacklist=blacklist,
164 blacklist_name='condemned host'
165 )
166
167
168 def select_host(
169 hosts: List[str],
170 ranking_string: Optional[str] = None,
171 blacklist: Optional[Iterable[str]] = None,
172 blacklist_name: Optional[str] = None,
173 ) -> Tuple[str, str]:
174 """Select a host from the provided list.
175
176 If no ranking is provided (in `ranking_string`) then random selection
177 is used.
178
179 Args:
180 hosts (list):
181 List of host names to choose from.
182 NOTE: Host names must be identifiable from the host where the
183 call is executed.
184 ranking_string (str):
185 A multiline string containing Python expressions to filter
186 hosts by e.g::
187
188 # only consider hosts with less than 70% cpu usage
189 # and a server load of less than 5
190 cpu_percent(1) < 70
191 getloadavg()[0] < 5
192
193 And or Python statements to rank hosts by e.g::
194
195 # rank by used cpu, then by load average as a tie-break
196 # (lower scores are better)
197 cpu_percent(1)
198 getloadavg()
199
200 Comments are allowed using `#` but not inline comments.
201 blacklist:
202 List of host names to filter out.
203 Can be short host names (do not have to be fqdn values)
204 blacklist_name:
205 The reason for blacklisting these hosts
206 (used for exceptions).
207
208 Raises:
209 HostSelectException:
210 In the event that no hosts are available / meet the specified
211 criterion.
212 This may also be raised in the event of unknown host names.
213
214 Returns:
215 tuple - (hostname, fqdn) the chosen host
216
217 hostname:
218 The hostname as provided to this function.
219 fqdn:
220 The fully qualified domain name of this host.
221
222 """
223 # dict of conditions and whether they have been met (for error reporting)
224 data: Dict[str, dict] = {}
225
226 # standardise host names - remove duplicate items
227 hostname_map = {} # note dictionary keys filter out duplicates
228 for host in hosts:
229 try:
230 hostname_map[get_fqdn_by_host(host)] = host
231 except gaierror as exc:
232 data.setdefault(host, {})[type(exc).__name__] = str(exc)
233 hosts = list(hostname_map)
234
235 # filter out `filter_hosts` if provided
236 if blacklist:
237 blacklist_fqdns: Set[str] = set()
238 for host in blacklist:
239 try:
240 blacklist_fqdns.add(get_fqdn_by_host(host))
241 except gaierror as exc:
242 LOG.warning(
243 f'Could not resolve blacklisted host {host}: {exc}'
244 )
245 hosts = _filter_by_hostname(
246 hosts,
247 blacklist_fqdns,
248 blacklist_name,
249 data=data
250 )
251
252 if not hosts:
253 # no hosts provided / left after filtering
254 raise HostSelectException(data)
255
256 rankings = []
257 if ranking_string:
258 # parse rankings
259 rankings = list(_get_rankings(ranking_string))
260
261 if not rankings:
262 # no metrics or ranking required, pick host at random
263 random.shuffle(hosts)
264 for host in hosts:
265 if (not is_remote_host(host)) or (
266 # check host is contactable
267 _get_metrics([host], [], data)
268 ):
269 return hostname_map[host], host
270 raise HostSelectException(data)
271
272 # filter and sort by rankings
273 metrics = list({x for x, _ in rankings}) # required metrics
274 # get data from each host
275 results = _get_metrics(hosts, metrics, data)
276 hosts = list(results) # some hosts might not be contactable
277
278 # stop here if we don't need to proceed
279 if not hosts:
280 # no hosts provided / left after filtering
281 raise HostSelectException(data, ranking_string)
282 if not rankings and len(hosts) == 1:
283 return hostname_map[hosts[0]], hosts[0]
284
285 hosts = _filter_by_ranking(
286 # filter by rankings, sort by ranking
287 hosts,
288 rankings,
289 results,
290 data=data
291 )
292
293 if not hosts:
294 # no hosts provided / left after filtering
295 raise HostSelectException(data, ranking_string)
296
297 return hostname_map[hosts[0]], hosts[0]
298
299
300 def _filter_by_hostname(
301 hosts: Iterable[str],
302 blacklist: Iterable[str],
303 blacklist_name: Optional[str],
304 data: Dict[str, dict],
305 ) -> List[str]:
306 """Return hosts, having filtered out any present in `blacklist`.
307
308 Args:
309 hosts:
310 List of host fqdns.
311 blacklist:
312 List of blacklisted host fqdns.
313 data:
314 Dict of the form {host: {}}
315 (used for exceptions).
316 blacklist_name:
317 The reason for blacklisting these hosts
318 (used for exceptions).
319
320 Examples
321 >>> hosts, data = ['a'], {}
322 >>> _filter_by_hostname(hosts, [], 'meh', data)
323 ['a']
324 >>> data
325 {'a': {'blacklisted(meh)': False}}
326
327 >>> hosts, data = ['a', 'b'], {}
328 >>> _filter_by_hostname(hosts, ['a'], None, data)
329 ['b']
330 >>> data
331 {'a': {'blacklisted': True}, 'b': {'blacklisted': False}}
332
333 """
334 key = 'blacklisted'
335 if blacklist_name:
336 key = f'{key}({blacklist_name})'
337
338 ret = []
339 for host in hosts:
340 data.setdefault(host, {})
341 if host in blacklist:
342 data[host][key] = True
343 else:
344 ret.append(host)
345 data[host][key] = False
346 return ret
347
348
349 def _filter_by_ranking(hosts, rankings, results, data):
350 """Filter and rank by the provided rankings.
351
352 Args:
353 hosts (list):
354 List of host fqdns.
355 rankings (list):
356 Thresholds which must be met.
357 List of rankings as returned by `get_rankings`.
358 results (dict):
359 Nested dictionary as returned by `get_metrics` of the form:
360 `{host: {value: result, ...}, ...}`.
361 data (dict):
362 Dict of the form {host: {}}
363 (used for exceptions).
364
365 Examples:
366 # ranking
367 >>> data = {}
368 >>> _filter_by_ranking(
369 ... ['a', 'b'],
370 ... [('X', 'RESULT')],
371 ... {'a': {'X': 123}, 'b': {'X': 234}},
372 ... data,
373 ... )
374 ['a', 'b']
375 >>> data
376 {}
377
378 # rankings
379 >>> data = {}
380 >>> _filter_by_ranking(
381 ... ['a', 'b'],
382 ... [('X', 'RESULT < 200')],
383 ... {'a': {'X': 123}, 'b': {'X': 234}},
384 ... data,
385 ... )
386 ['a']
387 >>> data
388 {'a': {'X() < 200': True}, 'b': {'X() < 200': False}}
389
390 # no matching hosts
391 >>> data = {}
392 >>> _filter_by_ranking(
393 ... ['a'],
394 ... [('X', 'RESULT > 1')],
395 ... {'a': {'X': 0}},
396 ... data,
397 ... )
398 []
399 >>> data
400 {'a': {'X() > 1': False}}
401
402 """
403 good = []
404 for host in hosts:
405 host_rankings = {}
406 host_rank = []
407 for key, expression in rankings:
408 item = _reformat_expr(key, expression)
409 try:
410 result = RankingExpressionEvaluator(
411 expression,
412 RESULT=results[host][key],
413 )
414 except Exception as exc:
415 raise GlobalConfigError(
416 'Invalid host ranking expression'
417 f'\n Expression: {item}'
418 f'\n Configuration: {GLBL_CFG_STR}'
419 f'\n Error: {exc}'
420 ) from None
421 if isinstance(result, bool):
422 host_rankings[item] = result
423 data.setdefault(host, {})[item] = result
424 else:
425 host_rank.append(result)
426 if all(host_rankings.values()):
427 good.append((host_rank, host))
428
429 if not good:
430 pass
431 elif good[0][0]:
432 # there is a ranking to sort by, use it
433 good.sort()
434 else:
435 # no ranking, randomise
436 random.shuffle(good)
437
438 # list of all hosts which passed rankings (sorted by ranking)
439 return [host for _, host in good]
440
441
442 def _get_rankings(string):
443 """Yield parsed ranking expressions.
444
445 Examples:
446 The first ``token.NAME`` encountered is returned as the query:
447 >>> _get_rankings('foo() == 123').__next__()
448 (('foo',), 'RESULT == 123')
449
450 If multiple are present they will not get parsed:
451 >>> _get_rankings('foo() in bar()').__next__()
452 (('foo',), 'RESULT in bar()')
453
454 Positional arguments are added to the query tuple:
455 >>> _get_rankings('1 in foo("a")').__next__()
456 (('foo', 'a'), '1 in RESULT')
457
458 Comments (not in-line) and multi-line strings are permitted:
459 >>> _get_rankings('''
460 ... # earl of sandwhich
461 ... foo() == 123
462 ... # beef wellington
463 ... ''').__next__()
464 (('foo',), 'RESULT == 123')
465
466 Yields:
467 tuple - (query, expression)
468 query (tuple):
469 The method to call followed by any positional arguments.
470 expression (str):
471 The expression with the method call replaced by `RESULT`
472
473 """
474 for line in string.splitlines():
475 # parse the string one line at a time
476 # purposefully don't support multi-line expressions
477 line = line.strip()
478
479 if not line or line.startswith('#'):
480 # skip blank lines
481 continue
482
483 query = []
484 start = None
485 in_args = False
486
487 line_feed = BytesIO(line.encode())
488 for item in tokenize(line_feed.readline):
489 if item.type == token.ENCODING:
490 # encoding tag, not of interest
491 pass
492 elif not query:
493 # the first token.NAME has not yet been encountered
494 if item.type == token.NAME and item.string != 'in':
495 # this is the first token.NAME, assume it it the method
496 start = item.start[1]
497 query.append(item.string)
498 elif item.string == '(':
499 # positional arguments follow this
500 in_args = True
501 elif item.string == ')':
502 # end of positional arguments
503 in_args = False
504 break
505 elif in_args:
506 # literal eval each argument
507 query.append(ast.literal_eval(item.string))
508 end = item.end[1]
509
510 yield (
511 tuple(query),
512 line[:start] + 'RESULT' + line[end:]
513 )
514
515
516 @lru_cache()
517 def _tuple_factory(name, params):
518 """Wrapper to namedtuple which caches results to prevent duplicates."""
519 return namedtuple(name, params)
520
521
522 def _deserialise(metrics, data):
523 """Convert dict to named tuples.
524
525 Examples:
526 >>> _deserialise(
527 ... [
528 ... ['foo', 'bar'],
529 ... ['baz']
530 ... ],
531 ... [
532 ... {'a': 1, 'b': 2, 'c': 3},
533 ... [1, 2, 3]
534 ... ]
535 ... )
536 [foo(a=1, b=2, c=3), [1, 2, 3]]
537
538 """
539 for index, (metric, datum) in enumerate(zip(metrics, data)):
540 if isinstance(datum, dict):
541 data[index] = _tuple_factory(
542 metric[0],
543 tuple(datum.keys())
544 )(
545 *datum.values()
546 )
547 return data
548
549
550 def _get_metrics(hosts, metrics, data):
551 """Retrieve host metrics using SSH if necessary.
552
553 Note hosts will not appear in the returned results if:
554 * They are not contactable.
555 * There is an error in the command which returns the results.
556
557 Args:
558 hosts (list):
559 List of host fqdns.
560 metrics (list):
561 List in the form [(function, arg1, arg2, ...), ...]
562 data (dict):
563 Used for logging success/fail outcomes of the form {host: {}}
564
565 Examples:
566 Command failure (no such attribute of psutil):
567 >>> data = {}
568 >>> _get_metrics(['localhost'], [['elephant']], data)
569 {}
570 >>> data
571 {'localhost': {'returncode': 2}}
572
573 Returns:
574 dict - {host: {(function, arg1, arg2, ...): result}}
575
576 """
577 host_stats = {}
578 proc_map = {}
579
580 # Start up commands on hosts
581 cmd = ['psutil']
582 kwargs = {
583 'stdin_str': json.dumps(metrics),
584 'capture_process': True
585 }
586 for host in hosts:
587 if is_remote_host(host):
588 try:
589 proc_map[host] = cylc_server_cmd(cmd, host=host, **kwargs)
590 except NoHostsError:
591 LOG.warning(f'Could not contact {host}')
592 continue
593 else:
594 proc_map[host] = run_cmd(['cylc'] + cmd, **kwargs)
595
596 # Collect results from commands
597 while proc_map:
598 for host, proc in list(proc_map.copy().items()):
599 if proc.poll() is None:
600 continue
601 del proc_map[host]
602 out, err = (stream.strip() for stream in proc.communicate())
603 if proc.wait():
604 # Command failed
605 msg = (
606 'Could not contact' if proc.returncode == 255
607 else 'Error evaluating ranking expression on'
608 )
609 LOG.warning(f'{msg} {host}:\n{err}')
610 else:
611 host_stats[host] = dict(zip(
612 metrics,
613 # convert JSON dicts -> namedtuples
614 _deserialise(metrics, parse_dirty_json(out))
615 ))
616 data.setdefault(host, {})['returncode'] = proc.returncode
617 sleep(0.01)
618 return host_stats
619
620
621 def _reformat_expr(key, expression):
622 """Convert a ranking tuple back into an expression.
623
624 Examples:
625 >>> ranking = 'a().b < c'
626 >>> _reformat_expr(
627 ... *[x for x in _get_rankings(ranking)][0]
628 ... ) == ranking
629 True
630
631 """
632 return expression.replace(
633 'RESULT',
634 f'{key[0]}({", ".join(map(repr, key[1:]))})'
635 )