Debian Codegraph @

cylc/flow/tui/data.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 from functools import partial
18 from subprocess import Popen, PIPE
19
20 from packaging.specifiers import SpecifierSet
21
22 from cylc.flow.exceptions import (
23 ClientError,
24 ClientTimeout,
25 WorkflowStopped,
26 )
27 from cylc.flow.network.client_factory import get_client
28 from cylc.flow.id import Tokens
29 from cylc.flow.tui.util import (
30 extract_context
31 )
32
33
34 # the GraphQL query which Tui runs against each of the workflows
35 # is is subscribed to
36 _QUERY = '''
37 query cli($taskStates: [String]){
38 workflows {
39 id
40 name
41 port
42 status
43 stateTotals
44 taskProxies(states: $taskStates) {
45 id
46 name
47 cyclePoint
48 state
49 isHeld
50 isQueued
51 isRunahead
52 isRetry
53 isWallclock
54 isXtriggered
55 flowNums
56 firstParent {
57 id
58 name
59 }
60 jobs(sort: { keys: ["submit_num"], reverse: true}) {
61 id
62 submitNum
63 state
64 platform
65 jobRunnerName
66 jobId
67 startedTime
68 estimatedFinishTime
69 finishedTime
70 }
71 task {
72 meanElapsedTime
73 }
74 }
75 familyProxies(exids: ["*/root"]) {
76 id
77 name
78 cyclePoint
79 state
80 isHeld
81 isQueued
82 isRunahead
83 isRetry
84 isWallclock
85 isXtriggered
86 firstParent {
87 id
88 name
89 }
90 }
91 cyclePoints: familyProxies(ids: ["*/root"]) {
92 id
93 name
94 cyclePoint
95 state
96 isHeld
97 isQueued
98 isRunahead
99 isRetry
100 isWallclock
101 isXtriggered
102 firstParent {
103 id
104 name
105 }
106 }
107 }
108 }
109 '''
110
111
112 # graphql queries for every version of Cylc that Tui supports:
113 _COMPAT_QUERIES = (
114 (
115 # regular query for current and future scheduler versions
116 SpecifierSet('>=8.6.dev'), _QUERY
117 ),
118 (
119 # BACK COMPAT
120 # estimatedFinishTime field added at 8.6.0
121 SpecifierSet('>=8.5.0, <8.6'),
122 _QUERY.replace('estimatedFinishTime', '')
123 ),
124 (
125 # BACK COMPAT
126 # isRetry, isWallclock and isXtriggered fields added at 8.5.0
127 SpecifierSet('>=8, <8.5'),
128 _QUERY
129 .replace('isRetry', '')
130 .replace('isWallclock', '')
131 .replace('isXtriggered', '')
132 .replace('estimatedFinishTime', ''),
133 ),
134 )
135
136
137 # the list of mutations we can call on a running scheduler
138 MUTATIONS = {
139 'workflow': [
140 'pause',
141 'reload',
142 'stop',
143 ],
144 'cycle': [
145 'hold',
146 'release',
147 'kill',
148 'trigger',
149 'poll',
150 ],
151 'task': [
152 'hold',
153 'release',
154 'kill',
155 'trigger',
156 'poll',
157 'set',
158 'remove',
159 ],
160 'job': [
161 'kill',
162 ]
163 }
164
165 # mapping of Tui's node types (e.g. workflow) onto GraphQL argument types
166 # (e.g. WorkflowID)
167 ARGUMENT_TYPES = {
168 # <tui-node-type>: <graphql-argument-type>
169 'workflow': '[WorkflowID]!',
170 'task': '[NamespaceIDGlob]!',
171 }
172
173
174 class VersionIncompat(Exception):
175 ...
176
177
178 def get_query(scheduler_version: str) -> str:
179 """Return a GraphQL query compatibile with the provided scheduler version.
180
181 Args:
182 scheduler_version: The version of the scheduler we are connecting to.
183
184 Returns:
185 The GraphQL query string.
186
187 Raises:
188 VersionIncompat:
189 If the scheduler version is not supported.
190
191 """
192 for query_version_range, query in _COMPAT_QUERIES:
193 if scheduler_version in query_version_range:
194 return query
195 raise VersionIncompat(
196 f'Scheduler version {scheduler_version} is not supported'
197 )
198
199
200 def cli_cmd(*cmd, ret=False):
201 """Issue a CLI command.
202
203 Args:
204 cmd:
205 The command without the 'cylc' prefix'.
206 ret:
207 If True, the stdout will be returned.
208
209 Rasies:
210 ClientError:
211 In the event of mishap for consistency with the network
212 client alternative.
213
214 """
215 proc = Popen( # nosec (command constructed internally, no untrusted input)
216 ['cylc', *cmd],
217 stderr=PIPE,
218 stdout=PIPE,
219 text=True,
220 )
221 _out, err = proc.communicate()
222 if proc.returncode != 0:
223 raise ClientError(f'Error in command cylc {" ".join(cmd)}\n{err}')
224 if ret:
225 return _out
226
227
228 def _show(id_):
229 """Special mutation to display cylc show output."""
230 # dynamic import to avoid circular import issues
231 from cylc.flow.tui.overlay import text_box
232 return partial(
233 text_box,
234 text=cli_cmd('show', id_, '--color=never', ret=True),
235 )
236
237
238 def _log(id_):
239 """Special mutation to open the log view."""
240 # dynamic import to avoid circular import issues
241 from cylc.flow.tui.overlay import log
242 return partial(
243 log,
244 id_=id_,
245 list_files=partial(_list_log_files, id_),
246 get_log=partial(_get_log, id_),
247 )
248
249
250 def _parse_log_header(contents):
251 """Parse the cat-log header.
252
253 The "--prepend-path" option to "cat-log" adds a line containing the host
254 and path to the file being viewed in the form:
255
256 # <host>:<path>
257
258 Args:
259 contents:
260 The raw log file contents as returned by "cat-log".
261
262 Returns:
263 tuple - (host, path, text)
264
265 host:
266 The host where the file was retrieved from.
267 path:
268 The absolute path to the log file.
269 text:
270 The log file contents with the header removed.
271
272 """
273 contents, text = contents.split('\n', 1)
274 contents = contents.replace('# ', '')
275 host, path = contents.split(':')
276 return host, path, text
277
278
279 def _get_log(id_, filename=None):
280 """Retrieve the contents of a log file.
281
282 Args:
283 id_:
284 The Cylc universal ID of the thing you want to fetch the log file
285 for.
286 filename:
287 The file name to retrieve (note name not path).
288 If "None", then the default log file will be retrieved.
289
290 """
291 cmd = [
292 'cat-log',
293 '--mode=cat',
294 '--prepend-path',
295 ]
296 if filename:
297 cmd.append(f'--file={filename}')
298 text = cli_cmd(
299 *cmd,
300 id_,
301 ret=True,
302 )
303 return _parse_log_header(text)
304
305
306 def _list_log_files(id_):
307 """Return a list of available log files.
308
309 Args:
310 id_:
311 The Cylc universal ID of the thing you want to fetch the log file
312 for.
313
314 """
315 text = cli_cmd('cat-log', '--mode=list-dir', id_, ret=True)
316 return text.splitlines()
317
318
319 # the mutations we have to go through the CLI to perform
320 OFFLINE_MUTATIONS = {
321 'user': {
322 'stop-all': partial(cli_cmd, 'stop', '*'),
323 },
324 'workflow': {
325 'play': partial(cli_cmd, 'play'),
326 'clean': partial(cli_cmd, 'clean', '--yes'),
327 'reinstall-reload': partial(cli_cmd, 'vr', '--yes'),
328 'log': _log,
329 },
330 'task': {
331 'log': _log,
332 'show': _show,
333 },
334 'job': {
335 'log': _log,
336 },
337 }
338
339
340 def generate_mutation(mutation, arguments):
341 """Return a GraphQL mutation string.
342
343 Args:
344 mutation:
345 The mutation name.
346 Arguments:
347 The arguments to provide to it.
348
349 """
350 arguments.pop('user')
351 graphql_args = ', '.join([
352 f'${argument}: {ARGUMENT_TYPES[argument]}'
353 for argument in arguments
354 ])
355 mutation_args = ', '.join([
356 f'{argument}s: ${argument}'
357 for argument in arguments
358 ])
359
360 return f'''
361 mutation({graphql_args}) {{
362 {mutation} ({mutation_args}) {{
363 result
364 }}
365 }}
366 '''
367
368
369 def list_mutations(selection, is_running=True):
370 """List mutations relevant to the provided selection.
371
372 Args:
373 selection:
374 The user selection.
375 is_running:
376 If False, then mutations which require the scheduler to be
377 running will be omitted.
378
379 Note, this is only relevant for workflow nodes because if a
380 workflow is stopped, then any tasks within it will be removed
381 anyway.
382
383 """
384 context = extract_context(selection)
385 selection_type = list(context)[-1]
386 ret = []
387 if is_running:
388 # add the online mutations
389 ret.extend(MUTATIONS.get(selection_type, []))
390 # add the offline mutations
391 ret.extend(OFFLINE_MUTATIONS.get(selection_type, []))
392 return sorted(ret)
393
394
395 def context_to_variables(context, jobs=False):
396 """Derive multiple selection out of single selection.
397
398 Note, this interface exists with the aim of facilitating the addition of
399 multiple selection at a later date.
400
401 Examples:
402 >>> context_to_variables(extract_context(['~a/b//c/d']))
403 {'user': ['a'], 'workflow': ['b'], 'task': ['c/d']}
404
405 >>> context_to_variables(extract_context(['~a/b//c']))
406 {'user': ['a'], 'workflow': ['b'], 'task': ['c/*']}
407
408 >>> context_to_variables(extract_context(['~a/b']))
409 {'user': ['a'], 'workflow': ['b']}
410
411 # Note, jobs are omitted by default
412 >>> context_to_variables(extract_context(['~a/b//c/d/01']))
413 {'user': ['a'], 'workflow': ['b'], 'task': ['c/d']}
414
415 # This is because Cylc commands cannot generally operate on jobs only
416 # tasks.
417 # To let jobs slide through:
418 >>> context_to_variables(extract_context(['~a/b//c/d/01']), jobs=True)
419 {'user': ['a'], 'workflow': ['b'], 'job': ['c/d/01']}
420
421 """
422 # context_to_variables because it can only handle single-selection ATM
423 variables = {'user': context['user']}
424
425 if 'workflow' in context:
426 variables['workflow'] = context['workflow']
427 if jobs and 'job' in context:
428 variables['job'] = [
429 Tokens(
430 cycle=context['cycle'][0],
431 task=context['task'][0],
432 job=context['job'][0],
433 ).relative_id
434 ]
435 elif 'task' in context:
436 variables['task'] = [
437 Tokens(
438 cycle=context['cycle'][0],
439 task=context['task'][0]
440 ).relative_id
441 ]
442 elif 'cycle' in context:
443 variables['task'] = [
444 Tokens(cycle=context['cycle'][0], task='*').relative_id
445 ]
446 return variables
447
448
449 def mutate(mutation, selection):
450 """Call a mutation.
451
452 Args:
453 mutation:
454 The mutation name (e.g. stop).
455 selection:
456 The Tui selection (i.e. the row(s) selected in Tui).
457
458 """
459 if mutation in {
460 _mutation
461 for section in OFFLINE_MUTATIONS.values()
462 for _mutation in section
463 }:
464 return offline_mutate(mutation, selection)
465 else:
466 online_mutate(mutation, selection)
467 return None
468
469
470 def online_mutate(mutation, selection):
471 """Issue a mutation over a network interface."""
472 context = extract_context(selection)
473 variables = context_to_variables(context)
474
475 # note this only supports single workflow mutations at present
476 workflow = variables['workflow'][0]
477 try:
478 client = get_client(workflow)
479 except WorkflowStopped:
480 raise Exception(
481 f'Cannot peform command {mutation} on a stopped workflow'
482 ) from None
483 except (ClientError, ClientTimeout) as exc:
484 raise Exception(
485 f'Error connecting to workflow: {exc}'
486 ) from None
487
488 request_string = generate_mutation(mutation, variables)
489 client(
490 'graphql',
491 {
492 'request_string': request_string,
493 'variables': variables
494 }
495 )
496
497
498 def offline_mutate(mutation, selection):
499 """Issue a mutation over the CLI or other offline interface."""
500 context = extract_context(selection)
501 variables = context_to_variables(context, jobs=True)
502 if 'job' in variables:
503 for job in variables['job']:
504 id_ = Tokens(job, relative=True).duplicate(
505 workflow=variables['workflow'][0]
506 )
507 return OFFLINE_MUTATIONS['job'][mutation](id_.id)
508 if 'task' in variables:
509 for task in variables['task']:
510 id_ = Tokens(task, relative=True).duplicate(
511 workflow=variables['workflow'][0]
512 )
513 return OFFLINE_MUTATIONS['task'][mutation](id_.id)
514 if 'workflow' in variables:
515 for workflow in variables['workflow']:
516 return OFFLINE_MUTATIONS['workflow'][mutation](workflow)
517 else:
518 return OFFLINE_MUTATIONS['user'][mutation]()