| 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 |
|
| 18 |
"""Contains the logic for updating the Tui app.""" |
| 19 |
|
| 20 |
from asyncio import ( |
| 21 |
run, |
| 22 |
sleep, |
| 23 |
gather, |
| 24 |
) |
| 25 |
from contextlib import suppress |
| 26 |
from copy import deepcopy |
| 27 |
from getpass import getuser |
| 28 |
from multiprocessing import Queue |
| 29 |
from time import time |
| 30 |
|
| 31 |
from zmq.error import ZMQError |
| 32 |
|
| 33 |
from cylc.flow.exceptions import ( |
| 34 |
ClientError, |
| 35 |
ClientTimeout, |
| 36 |
CylcError, |
| 37 |
WorkflowStopped, |
| 38 |
) |
| 39 |
from cylc.flow.id import Tokens |
| 40 |
from cylc.flow.network.client_factory import get_client |
| 41 |
from cylc.flow.network.scan import ( |
| 42 |
filter_name, |
| 43 |
graphql_query, |
| 44 |
is_active, |
| 45 |
scan, |
| 46 |
) |
| 47 |
from cylc.flow.task_state import ( |
| 48 |
TASK_STATUSES_ORDERED, |
| 49 |
) |
| 50 |
from cylc.flow.tui.data import ( |
| 51 |
VersionIncompat, |
| 52 |
get_query, |
| 53 |
) |
| 54 |
from cylc.flow.tui.util import ( |
| 55 |
NaturalSort, |
| 56 |
compute_tree, |
| 57 |
suppress_logging, |
| 58 |
) |
| 59 |
from cylc.flow.workflow_status import ( |
| 60 |
WorkflowStatus, |
| 61 |
) |
| 62 |
|
| 63 |
|
| 64 |
ME = getuser() |
| 65 |
|
| 66 |
|
| 67 |
def get_default_filters(): |
| 68 |
"""Return default task/workflow filters. |
| 69 |
|
| 70 |
These filters show everything. |
| 71 |
""" |
| 72 |
return { |
| 73 |
# filtered task statuses |
| 74 |
'tasks': dict.fromkeys(TASK_STATUSES_ORDERED, True), |
| 75 |
'workflows': { |
| 76 |
# filtered workflow statuses |
| 77 |
**{ |
| 78 |
state.value: True |
| 79 |
for state in WorkflowStatus |
| 80 |
}, |
| 81 |
# filtered workflow ids |
| 82 |
'id': '.*', |
| 83 |
} |
| 84 |
} |
| 85 |
|
| 86 |
|
| 87 |
def set_message(data, workflow_id, message, prefix='Error - '): |
| 88 |
"""Set a message to display instead of the workflow contents. |
| 89 |
|
| 90 |
This is for critical errors that mean we are unable to load a workflow. |
| 91 |
|
| 92 |
Args: |
| 93 |
data: |
| 94 |
The updater data. |
| 95 |
workflow_id: |
| 96 |
The ID of the workflow to set the error for. |
| 97 |
message: |
| 98 |
A message string or an Exception instance to use for the error |
| 99 |
text. If a string is provided, it may not contain newlines. |
| 100 |
prefix: |
| 101 |
A string that will be prepended to the message. |
| 102 |
|
| 103 |
""" |
| 104 |
if isinstance(message, Exception): |
| 105 |
# use the first line of the error message. |
| 106 |
message = str(message).splitlines()[0] |
| 107 |
for workflow in data['workflows']: |
| 108 |
# find the workflow in the data |
| 109 |
if workflow['id'] == workflow_id: |
| 110 |
# use the _tui_data field to hold the message |
| 111 |
workflow['_tui_data'] = ( |
| 112 |
f'{prefix}{message}' |
| 113 |
) |
| 114 |
break |
| 115 |
|
| 116 |
|
| 117 |
class Updater(): |
| 118 |
"""The bit of Tui which provides the data. |
| 119 |
|
| 120 |
It lists workflows using the "scan" interface, and provides detail using |
| 121 |
the "GraphQL" interface. |
| 122 |
|
| 123 |
""" |
| 124 |
|
| 125 |
# the interval between workflow listing scans |
| 126 |
BASE_SCAN_INTERVAL = 20 |
| 127 |
|
| 128 |
# the interval between workflow data updates |
| 129 |
BASE_UPDATE_INTERVAL = 1 |
| 130 |
|
| 131 |
# the command signal used to tell the updater to shut down |
| 132 |
SIGNAL_TERMINATE = 'terminate' |
| 133 |
|
| 134 |
def __init__(self, client_timeout=3): |
| 135 |
# Cylc comms clients for each workflow we're connected to |
| 136 |
self._clients = {} |
| 137 |
|
| 138 |
# iterate over this to get a list of workflows |
| 139 |
self._scan_pipe = None |
| 140 |
# the new pipe if the workflow filter options are changed |
| 141 |
self.__scan_pipe = None |
| 142 |
|
| 143 |
# task/workflow filters |
| 144 |
self.filters = None # note set on self.run() |
| 145 |
# queue for pushing out updates |
| 146 |
self.update_queue = Queue( |
| 147 |
# block the updater if it gets too far ahead of the application |
| 148 |
maxsize=10 |
| 149 |
) |
| 150 |
# queue for commands to the updater |
| 151 |
self._command_queue = Queue() |
| 152 |
|
| 153 |
# the maximum time to wait for a workflow update |
| 154 |
self.client_timeout = client_timeout |
| 155 |
|
| 156 |
def subscribe(self, w_id): |
| 157 |
"""Subscribe to updates from a workflow.""" |
| 158 |
self._command_queue.put((self._subscribe.__name__, w_id)) |
| 159 |
|
| 160 |
def unsubscribe(self, w_id): |
| 161 |
"""Unsubscribe to updates from a workflow.""" |
| 162 |
self._command_queue.put((self._unsubscribe.__name__, w_id)) |
| 163 |
|
| 164 |
def update_filters(self, filters): |
| 165 |
"""Update the task state filter.""" |
| 166 |
self._command_queue.put((self._update_filters.__name__, filters)) |
| 167 |
|
| 168 |
def terminate(self): |
| 169 |
"""Stop the updater.""" |
| 170 |
self._command_queue.put((self.SIGNAL_TERMINATE, None)) |
| 171 |
|
| 172 |
def start(self, filters): |
| 173 |
"""Start the updater in a new asyncio.loop. |
| 174 |
|
| 175 |
The Tui app will call this within a dedicated process. |
| 176 |
""" |
| 177 |
with suppress(KeyboardInterrupt): |
| 178 |
run(self.run(filters)) |
| 179 |
|
| 180 |
async def run(self, filters): |
| 181 |
"""Start the updater in an existing asyncio.loop. |
| 182 |
|
| 183 |
The tests call this within the same process. |
| 184 |
""" |
| 185 |
with suppress_logging(): |
| 186 |
self._update_filters(filters) |
| 187 |
while True: |
| 188 |
ret = await self._update() |
| 189 |
if ret == self.SIGNAL_TERMINATE: |
| 190 |
break |
| 191 |
self.update_queue.put(ret) |
| 192 |
|
| 193 |
def _subscribe(self, w_id): |
| 194 |
if w_id not in self._clients: |
| 195 |
self._clients[w_id] = None |
| 196 |
|
| 197 |
def _unsubscribe(self, w_id): |
| 198 |
if w_id in self._clients: |
| 199 |
self._clients.pop(w_id) |
| 200 |
|
| 201 |
def _update_filters(self, filters): |
| 202 |
if ( |
| 203 |
not self.filters |
| 204 |
or filters['workflows']['id'] != self.filters['workflows']['id'] |
| 205 |
): |
| 206 |
# update the scan pipe |
| 207 |
self.__scan_pipe = ( |
| 208 |
# scan all workflows |
| 209 |
scan |
| 210 |
| filter_name(filters['workflows']['id']) |
| 211 |
# if the workflow is active, retrieve its status |
| 212 |
| is_active(True, filter_stop=False) |
| 213 |
| graphql_query({'status': None}) |
| 214 |
) |
| 215 |
|
| 216 |
self.filters = filters |
| 217 |
|
| 218 |
async def _update(self): |
| 219 |
"""Run one iteration of the updater. |
| 220 |
|
| 221 |
Either returns the next update or "self.SIGNAL_TERMINATE". |
| 222 |
""" |
| 223 |
last_scan_time = 0 |
| 224 |
# process any pending commands |
| 225 |
while not self._command_queue.empty(): |
| 226 |
(command, payload) = self._command_queue.get() |
| 227 |
if command == self.SIGNAL_TERMINATE: |
| 228 |
return command |
| 229 |
getattr(self, command)(payload) |
| 230 |
|
| 231 |
# do a workflow scan if it's due |
| 232 |
update_start_time = time() |
| 233 |
if update_start_time - last_scan_time > self.BASE_SCAN_INTERVAL: |
| 234 |
data = await self._scan() |
| 235 |
|
| 236 |
# get the next snapshot from workflows we are subscribed to |
| 237 |
update = await self._run_update(data) |
| 238 |
|
| 239 |
# schedule the next update |
| 240 |
update_time = time() - update_start_time |
| 241 |
await sleep(self.BASE_UPDATE_INTERVAL - update_time) |
| 242 |
return update |
| 243 |
|
| 244 |
async def _run_update(self, data): |
| 245 |
# copy the scanned data so it can be reused for future updates |
| 246 |
data = deepcopy(data) |
| 247 |
|
| 248 |
# connect to schedulers if needed |
| 249 |
self._connect(data) |
| 250 |
|
| 251 |
# update data with the response from each workflow |
| 252 |
# NOTE: Currently we're bunching these updates together so Tui will |
| 253 |
# only update as fast as the slowest responding workflow. |
| 254 |
# We could run these updates separately if this is an issue. |
| 255 |
await gather( |
| 256 |
*( |
| 257 |
self._update_workflow(w_id, client, data) |
| 258 |
for w_id, client in self._clients.items() |
| 259 |
) |
| 260 |
) |
| 261 |
|
| 262 |
# are any task state filters active? |
| 263 |
task_filters_active = not all(self.filters['tasks'].values()) |
| 264 |
|
| 265 |
return compute_tree(data, prune_families=task_filters_active) |
| 266 |
|
| 267 |
async def _update_workflow(self, w_id, client, data): |
| 268 |
if not client: |
| 269 |
# we could not connect to this workflow |
| 270 |
# e.g. workflow is shut down |
| 271 |
return |
| 272 |
|
| 273 |
try: |
| 274 |
# get a graphql query compatible with this workflow |
| 275 |
query = get_query(client.scheduler_version) |
| 276 |
|
| 277 |
# fetch the data from the workflow |
| 278 |
workflow_update = await client.async_request( |
| 279 |
'graphql', |
| 280 |
{ |
| 281 |
'request_string': query, |
| 282 |
'variables': { |
| 283 |
# list of task states we want to see |
| 284 |
'taskStates': [ |
| 285 |
state |
| 286 |
for state, is_on in self.filters['tasks'].items() |
| 287 |
if is_on |
| 288 |
] |
| 289 |
} |
| 290 |
} |
| 291 |
) |
| 292 |
except WorkflowStopped: |
| 293 |
# remove the client on any error, we'll reconnect next time |
| 294 |
self._clients[w_id] = None |
| 295 |
for workflow in data['workflows']: |
| 296 |
if workflow['id'] == w_id: |
| 297 |
break |
| 298 |
else: |
| 299 |
# there's no entry here, create a stub |
| 300 |
# NOTE: this handles the situation where we've connected to a |
| 301 |
# workflow before it has appeared in a scan which matters to |
| 302 |
# the tests as they use fine timings |
| 303 |
data['workflows'].append({ |
| 304 |
'id': w_id, |
| 305 |
'status': 'stopped', |
| 306 |
}) |
| 307 |
except ClientTimeout: |
| 308 |
self._clients[w_id] = None |
| 309 |
set_message( |
| 310 |
data, |
| 311 |
w_id, |
| 312 |
'Timeout communicating with workflow.' |
| 313 |
' Use "--comms-timeout" to increase the timeout', |
| 314 |
) |
| 315 |
except VersionIncompat as exc: |
| 316 |
set_message( |
| 317 |
data, |
| 318 |
w_id, |
| 319 |
str(exc), |
| 320 |
) |
| 321 |
except (CylcError, ZMQError) as exc: |
| 322 |
# something went wrong :( |
| 323 |
# remove the client on any error, we'll reconnect next time |
| 324 |
self._clients[w_id] = None |
| 325 |
set_message(data, w_id, exc) |
| 326 |
else: |
| 327 |
# the data arrived, add it to the update |
| 328 |
workflow_data = workflow_update['workflows'][0] |
| 329 |
for workflow in data['workflows']: |
| 330 |
if workflow['id'] == workflow_data['id']: |
| 331 |
workflow.update(workflow_data) |
| 332 |
break |
| 333 |
|
| 334 |
def _connect(self, data): |
| 335 |
"""Connect to all subscribed workflows.""" |
| 336 |
for w_id, client in self._clients.items(): |
| 337 |
if not client: |
| 338 |
try: |
| 339 |
self._clients[w_id] = get_client( |
| 340 |
Tokens(w_id)['workflow'], |
| 341 |
timeout=self.client_timeout, |
| 342 |
) |
| 343 |
except WorkflowStopped: |
| 344 |
set_message( |
| 345 |
data, w_id, 'Workflow is not running', prefix='' |
| 346 |
) |
| 347 |
except ClientTimeout: |
| 348 |
set_message( |
| 349 |
data, |
| 350 |
w_id, |
| 351 |
'Timeout connecting to workflow.' |
| 352 |
' Use "--comms-timeout" to increase the timeout', |
| 353 |
) |
| 354 |
except (ZMQError, ClientError) as exc: |
| 355 |
set_message(data, w_id, exc) |
| 356 |
|
| 357 |
async def _scan(self): |
| 358 |
"""Scan for workflows on the filesystem.""" |
| 359 |
data = {'workflows': []} |
| 360 |
workflow_filter_statuses = { |
| 361 |
status |
| 362 |
for status, filtered in self.filters['workflows'].items() |
| 363 |
if filtered |
| 364 |
} |
| 365 |
if self.__scan_pipe: |
| 366 |
# switch to the new pipe if it has been changed |
| 367 |
self._scan_pipe = self.__scan_pipe |
| 368 |
async for workflow in self._scan_pipe: |
| 369 |
status = workflow.get('status', WorkflowStatus.STOPPED.value) |
| 370 |
if status not in workflow_filter_statuses: |
| 371 |
# this workflow is filtered out |
| 372 |
continue |
| 373 |
data['workflows'].append({ |
| 374 |
'id': f'~{ME}/{workflow["name"]}', |
| 375 |
'name': workflow['name'], |
| 376 |
'status': status, |
| 377 |
'stateTotals': {}, |
| 378 |
}) |
| 379 |
|
| 380 |
data['workflows'].sort(key=lambda x: NaturalSort(x['id'])) |
| 381 |
return data |