Debian Codegraph @

cylc/flow/tui/app.py

raw
1 #!/usr/bin/env python3
2 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
3 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
4 #
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with this program. If not, see <http://www.gnu.org/licenses/>.
17 """The application control logic for Tui."""
18
19 from copy import deepcopy
20 from contextlib import contextmanager
21 from multiprocessing import Process
22 import re
23
24 import urwid
25 from urwid.canvas import CanvasCache
26 from urwid.widget import SelectableIcon
27
28 from cylc.flow import __version__ as CYLC_VERSION
29 from cylc.flow.id import Tokens
30 from cylc.flow.task_state import (
31 TASK_STATUS_SUBMITTED,
32 TASK_STATUS_RUNNING,
33 TASK_STATUS_FAILED,
34 )
35 import cylc.flow.tui.overlay as overlay
36 from cylc.flow.tui import (
37 Bindings,
38 FORE,
39 BACK,
40 JOB_COLOURS,
41 WORKFLOW_COLOURS,
42 )
43 from cylc.flow.tui.tree import (
44 find_closest_focus,
45 translate_collapsing,
46 expand_tree,
47 )
48 from cylc.flow.tui.updater import (
49 Updater,
50 get_default_filters,
51 )
52 from cylc.flow.tui.util import (
53 dummy_flow,
54 render_node
55 )
56 from cylc.flow.workflow_status import (
57 WorkflowStatus,
58 )
59
60
61 # default workflow / task filters
62 # (i.e. show everything)
63 DEFAULT_FILTERS = get_default_filters()
64
65
66 urwid.set_encoding('utf8') # required for unicode task icons
67
68
69 class TuiWidget(urwid.TreeWidget):
70 """Display widget for tree nodes.
71
72 Arguments:
73 app (TuiApp):
74 Reference to the application.
75 node (TuiNode):
76 The root tree node.
77
78 """
79
80 # allows leaf nodes to be selectable, otherwise the cursor
81 # will skip rows when the user navigates
82 unexpandable_icon = SelectableIcon(' ', 0)
83
84 def __init__(self, app, node):
85 self.app = app
86 self._node = node
87 self._innerwidget = None
88 self.is_leaf = not node.get_child_keys()
89 self.expanded = False
90 widget = self.get_indented_widget()
91 urwid.WidgetWrap.__init__(self, widget)
92
93 def selectable(self):
94 """Return True if this node is selectable.
95
96 Allow all nodes to be selectable apart from job information nodes.
97
98 """
99 return self.get_node().get_value()['type_'] != 'job_info'
100
101 def get_display_text(self):
102 """Compute the text to display for a given node.
103
104 Returns:
105 (object) - Text content for the urwid.Text widget,
106 may be a string, tuple or list, see urwid docs.
107
108 """
109 node = self.get_node()
110 value = node.get_value()
111 data = value['data']
112 type_ = value['type_']
113 return render_node(node, data, type_)
114
115 def keypress(self, size, key):
116 """Handle expand & collapse requests.
117
118 Overridden from urwid.TreeWidget to change the behaviour
119 of the left arrow key which urwid uses for navigation
120 but which we think should be used for collapsing.
121
122 """
123 ret = super().keypress(size, key)
124 if ret in ('left',):
125 self.expanded = False
126 self.update_expanded_icon()
127 # return None so that this keypress is not allowed to
128 # propagate up the tree
129 return
130 return key
131
132 def get_indented_widget(self):
133 """Override the Urwid method to handle leaf nodes differently."""
134 if self.is_leaf:
135 self._innerwidget = urwid.Columns(
136 [
137 ('fixed', 1, self.unexpandable_icon),
138 self.get_inner_widget()
139 ],
140 dividechars=1
141 )
142 return super().get_indented_widget()
143
144 def update_expanded_icon(self, subscribe=True):
145 """Update the +/- icon.
146
147 This method overrides the built-in urwid update_expanded_icon method
148 in order to add logic for subscribing and unsubscribing to workflows.
149
150 Args:
151 subscribe:
152 If True, then we will [un]subscribe to workflows when workflow
153 nodes are expanded/collapsed. If False, then these events will
154 be ignored. Note we set subscribe=False when we are translating
155 the expand/collapse status when rebuilding the tree after an
156 update.
157
158 """
159 if subscribe:
160 node = self.get_node()
161 value = node.get_value()
162 data = value['data']
163 type_ = value['type_']
164 if type_ == 'workflow':
165 if self.expanded:
166 self.app.updater.subscribe(data['id'])
167 self.app.expand_on_load.add(data['id'])
168 else:
169 self.app.updater.unsubscribe(data['id'])
170 return urwid.TreeWidget.update_expanded_icon(self)
171
172
173 class TuiNode(urwid.ParentNode):
174 """Data storage object for Tui tree nodes."""
175
176 def __init__(self, app, *args, **kwargs):
177 self.app = app
178 urwid.ParentNode.__init__(self, *args, **kwargs)
179
180 def load_widget(self):
181 return TuiWidget(self.app, self)
182
183 def load_child_keys(self):
184 # Note: keys are really indices.
185 return range(len(self.get_value()['children']))
186
187 def load_child_node(self, key):
188 """Return a TuiNode instance for child "key"."""
189 return TuiNode(
190 self.app,
191 self.get_value()['children'][key],
192 parent=self,
193 key=key,
194 depth=self.get_depth() + 1
195 )
196
197
198 @contextmanager
199 def updater_subproc(filters, client_timeout):
200 """Runs the Updater in its own process.
201
202 The updater provides the data for Tui to render. Running the updater
203 in its own process removes its CPU load from the Tui app allowing
204 it to remain responsive whilst updates are being gathered as well as
205 decoupling the application update logic from the data update logic.
206 """
207 # start the updater
208 updater = Updater(client_timeout=client_timeout)
209 p = Process(target=updater.start, args=(filters,))
210 try:
211 p.start()
212 yield updater
213 finally:
214 updater.terminate()
215 p.join(4) # timeout of 4 seconds
216 if p.exitcode is None:
217 # updater did not exit within timeout -> kill it
218 p.terminate()
219
220
221 class TuiApp:
222 """An application to display a single Cylc workflow.
223
224 This is a single workflow view component (purposefully).
225
226 Multi-workflow functionality can be achieved via a GScan-esque
227 tab/selection panel.
228
229 Arguments:
230 id_ (str):
231 Workflow registration
232
233 """
234
235 # the UI update interval
236 # NOTE: this is different from the data update interval
237 UPDATE_INTERVAL = 0.1
238
239 # colours to be used throughout the application
240 palette = [
241 ('head', FORE, BACK),
242 ('body', FORE, BACK),
243 ('foot', 'white', 'dark blue'),
244 ('key', 'light cyan', 'dark blue'),
245 ('title', 'default, bold', BACK),
246 ('header', 'dark gray', BACK),
247 ('header_key', 'dark gray, bold', BACK),
248 ('overlay', 'black', 'light gray'),
249 ('diminished', 'dark gray', BACK),
250 # cylc logo colours
251 ('R', 'light red, bold', BACK),
252 ('Y', 'yellow, bold', BACK),
253 ('G', 'light green, bold', BACK),
254 ('B', 'light blue, bold', BACK),
255 ] + [ # job colours
256 (f'job_{status}', colour, BACK)
257 for status, colour in JOB_COLOURS.items()
258 ] + [ # job colours for help screen
259 (f'overlay_job_{status}', colour, 'light gray')
260 for status, colour in JOB_COLOURS.items()
261 ] + [ # workflow state colours
262 (f'workflow_{status}',) + spec
263 for status, spec in WORKFLOW_COLOURS.items()
264 ]
265
266 def __init__(self, screen=None):
267 self.loop = None
268 self.screen = screen
269 self.stack = 0
270 self.tree_walker = None
271
272 # store a reference to the bindings on the app to avoid cicular import
273 self.bindings = BINDINGS
274
275 # create the template
276 topnode = TuiNode(self, dummy_flow({'id': 'Loading...'}))
277 self.listbox = urwid.TreeListBox(urwid.TreeWalker(topnode))
278 header = urwid.Text('\n')
279 footer = urwid.AttrMap(urwid.Text(list_bindings()), 'foot')
280 self.view = urwid.Frame(
281 urwid.AttrMap(self.listbox, 'body'),
282 header=urwid.AttrMap(header, 'head'),
283 footer=footer
284 )
285 self.filters = get_default_filters()
286
287 @contextmanager
288 def main(
289 self,
290 w_id=None,
291 id_filter=None,
292 interactive=True,
293 client_timeout=3,
294 ):
295 """Start the Tui app.
296
297 With interactive=False, this does not start the urwid event loop to
298 make testing more deterministic. If you want Tui to update (i.e.
299 display the latest data), you must call the update method manually.
300
301 Note, we still run the updater asynchronously in a subprocess so that
302 we can test the interactions between the Tui application and the
303 updater processes.
304
305 """
306 self.set_initial_filters(w_id, id_filter)
307
308 with updater_subproc(self.filters, client_timeout) as updater:
309 self.updater = updater
310
311 # pre-subscribe to the provided workflow if requested
312 self.expand_on_load = {w_id or 'root'}
313 if w_id:
314 self.updater.subscribe(w_id)
315
316 # configure the urwid main loop
317 self.loop = urwid.MainLoop(
318 self.view,
319 self.palette,
320 unhandled_input=self.unhandled_input,
321 screen=self.screen
322 )
323
324 if interactive:
325 # Tui is being run normally as an interactive application
326 # schedule the first update
327 self.loop.set_alarm_in(0, self.update)
328
329 # start the urwid main loop
330 try:
331 self.loop.run()
332 except KeyboardInterrupt:
333 yield
334 return
335 else:
336 # wait for the first full update
337 self.wait_until_loaded(w_id or 'root')
338
339 yield self
340
341 def set_initial_filters(self, w_id, id_filter):
342 """Set the default workflow/task filters on startup."""
343 if w_id:
344 # Tui has been configured to look at a single workflow
345 # => filter everything else out
346 workflow = str(Tokens(w_id)['workflow'])
347 self.filters['workflows']['id'] = rf'^{re.escape(workflow)}$'
348 elif id_filter:
349 # a custom workflow ID filter has been provided
350 self.filters['workflows']['id'] = id_filter
351
352 def wait_until_loaded(self, *ids, retries=None, max_fails=50):
353 """Wait for any requested nodes to be created.
354
355 Warning:
356 This method is blocking! It's for HTML / testing purposes only!
357
358 Args:
359 ids:
360 Iterable containing the node IDs you want to wait for.
361 Note, these should be full IDs i.e. they should include the
362 user.
363 To wait for the root node to load, use "root".
364 retries:
365 The maximum number of updates to perform whilst waiting
366 for the specified IDs to appear in the tree.
367 max_fails:
368 If there is no update received from the updater, then we call
369 it a failed attempt. This isn't necessarily an issue, the
370 updater might be running a little slow. But if there are a
371 large number of fails, it likely means the condition won't be
372 satisfied.
373
374 Returns:
375 A list of the IDs which NOT not appear in the store.
376
377 Raises:
378 Exception:
379 If the "max_fails" are exhausted.
380
381 """
382 from time import sleep
383 ids = set(ids)
384 self.expand_on_load.update(ids)
385 successful_updates = 0
386 failed_updates = 0
387 while ids & self.expand_on_load:
388 if self.update():
389 successful_updates += 1
390 if retries is not None and successful_updates > retries:
391 return list(self.expand_on_load)
392 else:
393 failed_updates += 1
394 if failed_updates > max_fails:
395 raise Exception(
396 f'No update was received after {max_fails} attempts.'
397 f'\nThere were {successful_updates} successful'
398 ' updates.'
399 )
400
401 sleep(0.15) # blocking to Tui but not to the updater process
402 return None
403
404 def unhandled_input(self, key):
405 """Catch key presses, uncaught events are passed down the chain."""
406 if key in ('ctrl d',):
407 raise urwid.ExitMainLoop()
408 for binding in BINDINGS:
409 # iterate through key bindings in order
410 if key in binding['keys'] and binding['callback']:
411 # if we get a match execute the callback
412 # NOTE: if there is no callback then this binding is
413 # for documentation purposes only so we ignore it
414 meth, *args = binding['callback']
415 meth(self, *args)
416 return
417
418 @staticmethod
419 def get_node_id(node):
420 """Return a unique identifier for a node.
421
422 Arguments:
423 node (TuiNode): The node.
424
425 Returns:
426 str - Unique identifier
427
428 """
429 return node.get_value()['id_']
430
431 def update_header(self):
432 """Update the application header."""
433 header = [
434 # the Cylc Tui logo
435 ('R', 'C'),
436 ('Y', 'y'),
437 ('G', 'l'),
438 ('B', 'c'),
439 ('title', ' Tui '),
440 ('diminished', CYLC_VERSION),
441 ]
442 if self.filters['tasks'] != DEFAULT_FILTERS['tasks']:
443 # if task filters are active, display short help
444 header.extend([
445 ('header', ' tasks filtered ('),
446 ('header_key', 'T'),
447 ('header', ' - edit, '),
448 ('header_key', 'R'),
449 ('header', ' - reset)'),
450 ])
451 if self.filters['workflows'] != DEFAULT_FILTERS['workflows']:
452 # if workflow filters are active, display short help
453 header.extend([
454 ('header', ' workflows filtered ('),
455 ('header_key', 'W'),
456 ('header', ' - edit, '),
457 ('header_key', 'E'),
458 ('header', ' - reset)'),
459 ])
460 elif self.filters == DEFAULT_FILTERS:
461 # if not filters are available show application help
462 header.extend([
463 ('header', ' '),
464 ('header_key', 'h'),
465 ('header', ' to show help, '),
466 ('header_key', 'q'),
467 ('header', ' to quit'),
468 ])
469
470 # put in a one line gap
471 header.append('\n')
472
473 # replace the previous header
474 self.view.header = urwid.Text(header)
475
476 def get_update(self):
477 """Fetch the most recent update.
478
479 Returns the update, or False if there is no update queued.
480 """
481 update = False
482 while not self.updater.update_queue.empty():
483 # fetch the most recent update
484 update = self.updater.update_queue.get()
485 return update
486
487 def update(self, *_):
488 """Refresh the data and redraw this widget.
489
490 Preserves the current focus and collapse/expand state.
491
492 """
493 # attempt to fetch an update
494 update = self.get_update()
495 if update is False:
496 # there was no update, try again later
497 if self.loop:
498 self.loop.set_alarm_in(self.UPDATE_INTERVAL, self.update)
499 return False
500
501 # update the application header
502 self.update_header()
503
504 # global update - the nuclear option - slow but simple
505 # TODO: this can be done incrementally by adding and
506 # removing nodes from the existing tree
507 topnode = TuiNode(self, update)
508
509 # NOTE: because we are nuking the tree we need to manually
510 # preserve the focus and collapse status of tree nodes
511
512 # record the old focus
513 _, old_node = self.listbox.body.get_focus()
514
515 # nuke the tree
516 if not (self.tree_walker):
517 self.tree_walker = urwid.TreeWalker(topnode)
518 self.listbox.body = self.tree_walker
519 else:
520 self.tree_walker.set_focus(topnode)
521
522 # get the new focus
523 _, new_node = self.listbox.body.get_focus()
524
525 # preserve the focus or walk to the nearest parent
526 closest_focus = find_closest_focus(self, old_node, new_node)
527 self.listbox.body.set_focus(closest_focus)
528
529 # preserve the collapse/expand status of all nodes
530 translate_collapsing(self, old_node, new_node)
531
532 # expand any nodes which have been requested
533 for id_ in list(self.expand_on_load):
534 depth = 1 if id_ == 'root' else None
535 if expand_tree(self, new_node, id_, depth):
536 self.expand_on_load.remove(id_)
537
538 # schedule the next run of this update method
539 if self.loop:
540 self.loop.set_alarm_in(self.UPDATE_INTERVAL, self.update)
541
542 # NOTE: prevent a memory leak by clearing out any caches that urwid
543 # may have accumulated for the previous TuiNode instance
544 # (and its child widgets)
545 CanvasCache.clear()
546
547 return True
548
549 def filter_by_task_state(self, filtered_state=None):
550 """Filter tasks.
551
552 Args:
553 filtered_state (str):
554 A task state to filter by or None.
555
556 """
557 self.filters['tasks'] = {
558 state: (state == filtered_state) or not filtered_state
559 for state in self.filters['tasks']
560 }
561 self.updater.update_filters(self.filters)
562
563 def reset_workflow_filters(self):
564 """Reset workflow state/id filters."""
565 self.filters['workflows'] = deepcopy(DEFAULT_FILTERS['workflows'])
566 self.updater.update_filters(self.filters)
567
568 def filter_by_workflow_state(self, *filtered_states):
569 """Filter workflows.
570
571 Args:
572 filtered_state (str):
573 A task state to filter by or None.
574
575 """
576 for state in self.filters['workflows']:
577 if state != 'id':
578 self.filters['workflows'][state] = (
579 (state in filtered_states) or not filtered_states
580 )
581 self.updater.update_filters(self.filters)
582
583 def open_overlay(self, fcn):
584 """Open an overlay over the application.
585
586 Args:
587 fcn: A function which returns an urwid widget to overlay.
588
589 """
590 self.create_overlay(*fcn(app=self))
591
592 def create_overlay(self, widget, kwargs):
593 """Open an overlay over the monitor.
594
595 Args:
596 widget (urwid.Widget):
597 Widget to be placed inside the overlay.
598 kwargs (dict):
599 Dictionary of arguments to pass to the `urwid.Overlay`
600 constructor.
601
602 You will likely need to set `width` and `height` here.
603
604 See `urwid` docs for details.
605
606 """
607 # create the overlay
608 kwargs = {'width': 'pack', 'height': 'pack', **kwargs}
609 overlay = urwid.Overlay(
610 urwid.LineBox(
611 urwid.AttrMap(
612 urwid.Frame(
613 urwid.Padding(
614 widget,
615 left=2,
616 right=2
617 ),
618 footer=urwid.Text('\n q to close')
619 ),
620 'overlay',
621 )
622 ),
623 self.loop.widget,
624 align='center',
625 valign='middle',
626 left=self.stack * 5,
627 top=self.stack * 5,
628 **kwargs,
629 )
630
631 # add it into the overlay stack
632 self.loop.widget = overlay
633 self.stack += 1
634
635 # force urwid to render the overlay now rather than waiting until the
636 # event loop becomes idle
637 self.loop.draw_screen()
638
639 def close_topmost(self):
640 """Remove the topmost frame or uit the app if none present."""
641 if self.stack <= 0:
642 raise urwid.ExitMainLoop()
643 self.loop.widget = self.loop.widget[0]
644 self.stack -= 1
645
646
647 # register key bindings
648 # * all bindings must belong to a group
649 # * all keys are auto-documented in the help screen and application footer
650 BINDINGS = Bindings()
651 BINDINGS.add_group(
652 '',
653 'Application Controls'
654 )
655 BINDINGS.bind(
656 ('q',),
657 '',
658 'Quit',
659 (TuiApp.close_topmost,)
660 )
661 BINDINGS.bind(
662 ('h',),
663 '',
664 'Help',
665 (TuiApp.open_overlay, overlay.help_info)
666 )
667 BINDINGS.bind(
668 ('enter',),
669 '',
670 'Context',
671 (TuiApp.open_overlay, overlay.context)
672 )
673
674 BINDINGS.add_group(
675 'tree',
676 'Expand/Collapse nodes',
677 )
678 BINDINGS.bind(
679 ('-', '\u2190'),
680 'tree',
681 'Collapse',
682 None # this binding is for documentation only - handled by urwid
683 )
684 BINDINGS.bind(
685 ('+', '\u2192'),
686 'tree',
687 'Expand',
688 None # this binding is for documentation only - handled by urwid
689 )
690
691 BINDINGS.add_group(
692 'navigation',
693 'Move within the tree'
694 )
695 BINDINGS.bind(
696 ('\u2191',),
697 'navigation',
698 'Up',
699 None # this binding is for documentation only - handled by urwid
700 )
701 BINDINGS.bind(
702 ('\u2193',),
703 'navigation',
704 'Down',
705 None # this binding is for documentation only - handled by urwid
706 )
707 BINDINGS.bind(
708 ('\u21a5',),
709 'navigation',
710 'PageUp',
711 None # this binding is for documentation only - handled by urwid
712 )
713 BINDINGS.bind(
714 ('\u21a7',),
715 'navigation',
716 'PageDown',
717 None # this binding is for documentation only - handled by urwid
718 )
719 BINDINGS.bind(
720 ('Home',),
721 'navigation',
722 'Top',
723 None # this binding is for documentation only - handled by urwid
724 )
725 BINDINGS.bind(
726 ('End',),
727 'navigation',
728 'Bottom',
729 None # this binding is for documentation only - handled by urwid
730 )
731
732 BINDINGS.add_group(
733 'filter tasks',
734 'Filter by task state'
735 )
736 BINDINGS.bind(
737 ('T',),
738 'filter tasks',
739 'Select task states to filter by',
740 (TuiApp.open_overlay, overlay.filter_task_state)
741 )
742 BINDINGS.bind(
743 ('f',),
744 'filter tasks',
745 'Show only failed tasks',
746 (TuiApp.filter_by_task_state, TASK_STATUS_FAILED)
747 )
748 BINDINGS.bind(
749 ('s',),
750 'filter tasks',
751 'Show only submitted tasks',
752 (TuiApp.filter_by_task_state, TASK_STATUS_SUBMITTED)
753 )
754 BINDINGS.bind(
755 ('r',),
756 'filter tasks',
757 'Show only running tasks',
758 (TuiApp.filter_by_task_state, TASK_STATUS_RUNNING)
759 )
760 BINDINGS.bind(
761 ('R',),
762 'filter tasks',
763 'Reset task state filtering',
764 (TuiApp.filter_by_task_state,)
765 )
766
767 BINDINGS.add_group(
768 'filter workflows',
769 'Filter by workflow state'
770 )
771 BINDINGS.bind(
772 ('W',),
773 'filter workflows',
774 'Select workflow states to filter by',
775 (TuiApp.open_overlay, overlay.filter_workflow_state)
776 )
777 BINDINGS.bind(
778 ('E',),
779 'filter workflows',
780 'Reset workflow filtering',
781 (TuiApp.reset_workflow_filters,)
782 )
783 BINDINGS.bind(
784 ('p',),
785 'filter workflows',
786 'Show only running workflows',
787 (
788 TuiApp.filter_by_workflow_state,
789 WorkflowStatus.RUNNING.value,
790 WorkflowStatus.PAUSED.value,
791 WorkflowStatus.STOPPING.value
792 )
793 )
794
795
796 def list_bindings():
797 """Write out an in-line list of the key bindings."""
798 ret = []
799 for group, bindings in BINDINGS.list_groups():
800 if group['name']:
801 ret.append(f' {group["name"]}: ')
802 for binding in bindings:
803 for key in binding['keys']:
804 ret.append(('key', f'{key} '))
805 else:
806 # list each option in the default group individually
807 for binding in bindings:
808 ret.append(f'{binding["desc"].lower()}: ')
809 ret.append(('key', binding["keys"][0]))
810 ret.append(' ')
811 ret.append(' ')
812 ret.pop() # remove surplus space
813 return ret