| 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 |
import asyncio |
| 18 |
import sys |
| 19 |
from typing import ( |
| 20 |
Callable, |
| 21 |
Dict, |
| 22 |
List, |
| 23 |
Optional, |
| 24 |
Tuple, |
| 25 |
Type, |
| 26 |
Union, |
| 27 |
) |
| 28 |
|
| 29 |
from ansimarkup import ansiprint |
| 30 |
|
| 31 |
from cylc.flow import __version__ as CYLC_VERSION |
| 32 |
from cylc.flow.async_util import unordered_map |
| 33 |
from cylc.flow.exceptions import ( |
| 34 |
CylcError, |
| 35 |
WorkflowStopped, |
| 36 |
) |
| 37 |
import cylc.flow.flags |
| 38 |
from cylc.flow.id_cli import parse_ids_async |
| 39 |
from cylc.flow.terminal import DIM |
| 40 |
|
| 41 |
|
| 42 |
# Known error messages for incompatibilites between this version of Cylc (that |
| 43 |
# is running the command) and the version of Cylc running the workflow: |
| 44 |
KNOWN_INCOMPAT = { |
| 45 |
'Unknown argument "onResume" on field "trigger" of type "Mutations".', |
| 46 |
} |
| 47 |
|
| 48 |
|
| 49 |
def call_multi(*args, **kwargs): |
| 50 |
"""Call a function for each workflow in a list of IDs. |
| 51 |
|
| 52 |
See call_multi_async for arg docs. |
| 53 |
""" |
| 54 |
return asyncio.run(call_multi_async(*args, **kwargs)) |
| 55 |
|
| 56 |
|
| 57 |
async def call_multi_async( |
| 58 |
fcn, |
| 59 |
*ids, |
| 60 |
constraint='tasks', |
| 61 |
report: Optional[ |
| 62 |
# report(response: dict) -> (stdout, stderr, success) |
| 63 |
Callable[[dict], Tuple[Optional[str], Optional[str], bool]] |
| 64 |
] = None, |
| 65 |
max_workflows=None, |
| 66 |
max_tasks=None, |
| 67 |
success_exceptions: Optional[Tuple[Type]] = None, |
| 68 |
) -> Dict[str, bool]: |
| 69 |
"""Call a function for each workflow in a list of IDs. |
| 70 |
|
| 71 |
Args: |
| 72 |
fcn: |
| 73 |
The function to call for each workflow. |
| 74 |
ids: |
| 75 |
The list of universal identifiers to parse. |
| 76 |
constraint: |
| 77 |
The type of objects IDs must identify. |
| 78 |
|
| 79 |
tasks: |
| 80 |
For task-like objects i.e. cycles/tasks/jobs. |
| 81 |
workflow: |
| 82 |
For workflow-like objects i.e. [user/]workflows. |
| 83 |
mixed: |
| 84 |
No constraint. |
| 85 |
report: |
| 86 |
The default reporter inspects the returned GraphQL status |
| 87 |
extracting command outcome from the "response" field. |
| 88 |
This reporter can be overwritten using the report kwarg. |
| 89 |
|
| 90 |
Reporter functions are provided with the "response". They must |
| 91 |
return the outcome of the operation and may also return stdout/err |
| 92 |
text which will be written to the terminal. |
| 93 |
success_exceptions: |
| 94 |
An optional tuple of exceptions that can convey success outcomes. |
| 95 |
E.G. a "WorkflowStopped" exception indicates an error state for |
| 96 |
"cylc broadcast" but a success state for "cylc stop". |
| 97 |
|
| 98 |
Returns: |
| 99 |
{workflow_id: outcome} |
| 100 |
|
| 101 |
""" |
| 102 |
# parse ids |
| 103 |
workflow_args, multi_mode = await parse_ids_async( |
| 104 |
*ids, |
| 105 |
src=False, |
| 106 |
constraint=constraint, |
| 107 |
max_workflows=max_workflows, |
| 108 |
max_tasks=max_tasks, |
| 109 |
match_workflows=True, |
| 110 |
) |
| 111 |
|
| 112 |
# configure reporting |
| 113 |
if not report: |
| 114 |
report = _report |
| 115 |
if multi_mode: |
| 116 |
reporter = _report_multi |
| 117 |
else: |
| 118 |
reporter = _report_single |
| 119 |
|
| 120 |
if constraint == 'workflows': |
| 121 |
workflow_args = { |
| 122 |
workflow_id: [] |
| 123 |
for workflow_id in workflow_args |
| 124 |
} |
| 125 |
|
| 126 |
# run coros |
| 127 |
results: Dict[str, bool] = {} |
| 128 |
async for (workflow_id, *args), response in unordered_map( |
| 129 |
fcn, |
| 130 |
( |
| 131 |
(workflow_id, *args) |
| 132 |
for workflow_id, args in workflow_args.items() |
| 133 |
), |
| 134 |
# return exceptions rather than raising them |
| 135 |
# (this way if one command errors, others may still run) |
| 136 |
wrap_exceptions=True, |
| 137 |
): |
| 138 |
# get outcome |
| 139 |
out, err, outcome = _process_response( |
| 140 |
report, response, success_exceptions |
| 141 |
) |
| 142 |
# report outcome |
| 143 |
reporter(workflow_id, out, err) |
| 144 |
results[workflow_id] = outcome |
| 145 |
|
| 146 |
return results |
| 147 |
|
| 148 |
|
| 149 |
def _report_multi( |
| 150 |
workflow: str, out: Optional[str], err: Optional[str] |
| 151 |
) -> None: |
| 152 |
"""Report a response for a multi-workflow operation. |
| 153 |
|
| 154 |
This is called once for each workflow the operation is called against. |
| 155 |
""" |
| 156 |
msg = f'<b>{workflow}</b>:' |
| 157 |
if out: |
| 158 |
out = out.replace('\n', '\n ') # indent |
| 159 |
msg += ' ' + out |
| 160 |
ansiprint(msg) |
| 161 |
|
| 162 |
if err: |
| 163 |
err = err.replace('\n', '\n ') # indent |
| 164 |
if not out: |
| 165 |
err = f'{msg} {err}' |
| 166 |
ansiprint(err, file=sys.stdout) |
| 167 |
|
| 168 |
|
| 169 |
def _report_single( |
| 170 |
workflow: str, out: Optional[str], err: Optional[str] |
| 171 |
) -> None: |
| 172 |
"""Report the response for a single-workflow operation.""" |
| 173 |
if out: |
| 174 |
ansiprint(out) |
| 175 |
if err: |
| 176 |
ansiprint(err, file=sys.stderr) |
| 177 |
|
| 178 |
|
| 179 |
def _process_response( |
| 180 |
report: Callable, |
| 181 |
response: Union[dict, Exception], |
| 182 |
success_exceptions: Optional[Tuple[Type]] = None, |
| 183 |
) -> Tuple[Optional[str], Optional[str], bool]: |
| 184 |
"""Handle exceptions and return processed results. |
| 185 |
|
| 186 |
If the response is an exception, return an appropriate error message, |
| 187 |
otherwise run the reporter and return the result. |
| 188 |
|
| 189 |
Args: |
| 190 |
response: |
| 191 |
The GraphQL response. |
| 192 |
report: |
| 193 |
The reporter function for extracting the result from the provided |
| 194 |
response. |
| 195 |
success_exceptions: |
| 196 |
An optional tuple of exceptions that can convey success outcomes. |
| 197 |
E.G. a "WorkflowStopped" exception indicates an error state for |
| 198 |
"cylc broadcast" but a success state for "cylc stop". |
| 199 |
|
| 200 |
Returns: |
| 201 |
(stdout, stderr, outcome) |
| 202 |
|
| 203 |
""" |
| 204 |
if success_exceptions and isinstance(response, success_exceptions): |
| 205 |
# an exception was raised, however, that exception indicates a success |
| 206 |
# outcome in this case |
| 207 |
out = f'<green>{response.__class__.__name__}: {response}</green>' |
| 208 |
err = None |
| 209 |
outcome = True |
| 210 |
|
| 211 |
elif isinstance(response, WorkflowStopped): |
| 212 |
# workflow stopped -> report differently to other CylcErrors |
| 213 |
out = None |
| 214 |
err = f'<yellow>{response.__class__.__name__}: {response}</yellow>' |
| 215 |
outcome = False |
| 216 |
|
| 217 |
elif isinstance(response, CylcError): |
| 218 |
# exception -> report error |
| 219 |
if cylc.flow.flags.verbosity > 1: # debug mode |
| 220 |
raise response from None |
| 221 |
out = None |
| 222 |
err = f'<red>{response.__class__.__name__}: {response}</red>' |
| 223 |
outcome = False |
| 224 |
|
| 225 |
elif isinstance(response, Exception): |
| 226 |
# unexpected error -> raise |
| 227 |
raise response |
| 228 |
|
| 229 |
else: |
| 230 |
try: |
| 231 |
# run the reporter to extract the operation outcome |
| 232 |
out, err, outcome = report(response) |
| 233 |
except Exception as exc: |
| 234 |
# an exception was raised in the reporter -> report this error the |
| 235 |
# same was as an error in the response |
| 236 |
return _process_response(report, exc, success_exceptions) |
| 237 |
|
| 238 |
return out, err, outcome |
| 239 |
|
| 240 |
|
| 241 |
def _report( |
| 242 |
response: Union[dict, list], |
| 243 |
) -> Tuple[Optional[str], Optional[str], bool]: |
| 244 |
"""Report the result of a GraphQL operation. |
| 245 |
|
| 246 |
This analyses GraphQL mutation responses to determine the outcome. |
| 247 |
|
| 248 |
Args: |
| 249 |
response: The workflow server response (NOT necessarily conforming to |
| 250 |
GraphQL execution result spec). |
| 251 |
|
| 252 |
Returns: |
| 253 |
(stdout, stderr, outcome) |
| 254 |
|
| 255 |
""" |
| 256 |
try: |
| 257 |
ret: List[Tuple[Optional[str], Optional[str], bool]] = [] |
| 258 |
if not isinstance(response, dict): |
| 259 |
if isinstance(response, list) and response[0].get('error'): |
| 260 |
# If operating on workflow running in older Cylc version, |
| 261 |
# may get a error response like [{'error': '...'}] |
| 262 |
if response[0]['error'].get('message') in KNOWN_INCOMPAT: |
| 263 |
raise Exception( |
| 264 |
"This command is no longer compatible with the " |
| 265 |
"version of Cylc running the workflow. Please stop & " |
| 266 |
f"restart the workflow with Cylc {CYLC_VERSION} " |
| 267 |
"or higher." |
| 268 |
f"\n\n{response}" |
| 269 |
) |
| 270 |
raise Exception(response) |
| 271 |
raise Exception(f"Unexpected response: {response}") |
| 272 |
for mutation_response in response.values(): |
| 273 |
# extract the result of each mutation result in the response |
| 274 |
success, msg = mutation_response['result'][0]['response'] |
| 275 |
out = None |
| 276 |
err = None |
| 277 |
if success: |
| 278 |
# mutation succeeded |
| 279 |
out = '<green>Command queued</green>' |
| 280 |
if cylc.flow.flags.verbosity > 0: # verbose mode |
| 281 |
out += f' <{DIM}>id={msg}</{DIM}>' |
| 282 |
else: |
| 283 |
# mutation failed |
| 284 |
err = f'<red>{msg}</red>' |
| 285 |
ret.append((out, err, success)) |
| 286 |
|
| 287 |
if len(ret) > 1: |
| 288 |
# NOTE: at present we only support one mutation per operation at |
| 289 |
# cylc-flow, however, multi-mutation operations can be actioned via |
| 290 |
# cylc-uiserver |
| 291 |
raise NotImplementedError( |
| 292 |
'Cannot process multiple mutations in one operation.' |
| 293 |
) |
| 294 |
|
| 295 |
if len(ret) == 1: |
| 296 |
return ret[0] |
| 297 |
|
| 298 |
# error extracting result from GraphQL response |
| 299 |
raise Exception(response) |
| 300 |
|
| 301 |
except Exception as exc: |
| 302 |
# response returned is not in the expected format - this shouldn't |
| 303 |
# happen but we need to protect against it |
| 304 |
err_msg = '' |
| 305 |
if cylc.flow.flags.verbosity > 0: # verbose mode |
| 306 |
# print the full result to stderr |
| 307 |
err_msg += f'\n <{DIM}>response={response}</{DIM}>' |
| 308 |
return ( |
| 309 |
None, |
| 310 |
( |
| 311 |
'<red>Error processing command:\n' |
| 312 |
+ f' {exc.__class__.__name__}: {exc}</red>' |
| 313 |
+ err_msg |
| 314 |
), |
| 315 |
False, |
| 316 |
) |