Debian Codegraph @

cylc/flow/scripts/dump.py

raw
1 #!/usr/bin/env python3
2
3 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
4 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
5 #
6 # This program is free software: you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation, either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19 """cylc dump [OPTIONS] ARGS
20
21 Print state of a running workflow including tasks in the active (n=0) window.
22
23 For a more detailed view of the workflow see `cylc tui` or `cylc gui`.
24
25 For more information about a specific task, such as the current state of
26 its prerequisites and outputs, see 'cylc show'.
27
28 For command line monitoring:
29 * `cylc tui`
30 * `watch cylc dump -t WORKFLOW_ID` works for small simple workflows
31
32 Examples:
33 # Display the state of all active tasks, sorted by cycle point:
34 $ cylc dump --tasks --sort WORKFLOW_ID | grep running
35
36 # Display the state of all active tasks in a particular cycle point:
37 $ cylc dump -t WORKFLOW_ID | grep 2010082406
38 """
39
40 import asyncio
41 import json
42 from typing import TYPE_CHECKING
43
44 from graphene.utils.str_converters import to_snake_case
45
46 from cylc.flow.exceptions import CylcError
47 from cylc.flow.id_cli import parse_id_async
48 from cylc.flow.option_parsers import (
49 WORKFLOW_ID_ARG_DOC,
50 CylcOptionParser as COP,
51 )
52 from cylc.flow.network.client_factory import get_client
53 from cylc.flow.terminal import cli_function
54
55 if TYPE_CHECKING:
56 from optparse import Values
57
58
59 TASK_SUMMARY_FRAGMENT = '''
60 fragment tProxy on TaskProxy {
61 id
62 name
63 cyclePoint
64 state
65 graphDepth
66 isHeld
67 isQueued
68 isRunahead
69 flowNums
70 firstParent {
71 id
72 }
73 jobSubmits
74 jobs(sort: {keys: ["submitNum"], reverse: true}) {
75 id
76 state
77 submitNum
78 submittedTime
79 startedTime
80 finishedTime
81 jobLogDir
82 platform
83 executionTimeLimit
84 jobRunnerName
85 jobId
86 }
87 }
88 '''
89
90 FAMILY_SUMMARY_FRAGMENT = '''
91 fragment fProxy on FamilyProxy {
92 id
93 name
94 cyclePoint
95 state
96 }
97 '''
98
99 WORKFLOW_SUMMARY_FRAGMENT = '''
100 fragment wFlow on Workflow {
101 name
102 oldestActiveCyclePoint
103 newestActiveCyclePoint
104 timeZoneInfo {
105 hours
106 minutes
107 stringBasic
108 stringExtended
109 }
110 lastUpdated
111 runMode
112 states
113 namespaceDefinitionOrder: nsDefOrder
114 reloaded
115 stateTotals
116 meta {
117 title
118 description
119 URL
120 userDefined
121 }
122 status
123 statusMsg
124 families {
125 name
126 meta {
127 title
128 description
129 URL
130 userDefined
131 }
132 firstParent {
133 name
134 }
135 }
136 tasks {
137 name
138 meta {
139 title
140 description
141 URL
142 userDefined
143 }
144 meanElapsedTime
145 firstParent {
146 name
147 }
148 }
149 }
150 '''
151
152
153 def get_option_parser():
154 parser = COP(
155 __doc__,
156 comms=True,
157 argdoc=[WORKFLOW_ID_ARG_DOC],
158 )
159 parser.add_option(
160 "-g", "--global", help="Global information only.",
161 action="store_const", const="global", dest="disp_form")
162 parser.add_option(
163 "-t", "--tasks", help="Task states only.",
164 action="store_const", const="tasks", dest="disp_form")
165 parser.add_option(
166 "-l", "--legacy", help="Tasks states only; use legacy format.",
167 action="store_true", default=False, dest="legacy_format")
168 parser.add_option(
169 "-f", "--flows", help="Print flow numbers with tasks.",
170 action="store_true", default=False, dest="show_flows")
171 parser.add_option(
172 "-r", "--raw", "--raw-format",
173 help='Display raw format.',
174 action="store_const", const="raw", dest="disp_form")
175 parser.add_option(
176 "-p", "--pretty", "--pretty-print",
177 help='Display raw format with indents and newlines.',
178 action="store_true", default=False, dest="pretty")
179 parser.add_option(
180 "-s", "--sort",
181 help="Task states only; sort by cycle point instead of name.",
182 action="store_true", default=False, dest="sort_by_cycle")
183
184 return parser
185
186
187 @cli_function(get_option_parser)
188 def main(_, options: 'Values', workflow_id: str) -> None:
189 asyncio.run(dump(workflow_id, options))
190
191
192 async def dump(workflow_id, options, write=print):
193 workflow_id, *_ = await parse_id_async(
194 workflow_id,
195 constraint='workflows',
196 )
197 pclient = get_client(
198 workflow_id,
199 # set the default timeout a bit higher for "cylc dump" as it can
200 # take a little while for Cylc to formulate the response
201 timeout=options.comms_timeout or 15,
202 )
203
204 if options.sort_by_cycle:
205 sort_args = {'keys': ['cyclePoint', 'name']}
206 else:
207 sort_args = {'keys': ['name', 'cyclePoint']}
208
209 # retrict to the n=0 window
210 graph_depth = 0
211
212 if options.disp_form == "raw":
213 query = f'''
214 {TASK_SUMMARY_FRAGMENT}
215 {FAMILY_SUMMARY_FRAGMENT}
216 {WORKFLOW_SUMMARY_FRAGMENT}
217 query ($wFlows: [ID]!, $sortBy: SortArgs) {{
218 workflows (ids: $wFlows, stripNull: false) {{
219 ...wFlow
220 taskProxies (sort: $sortBy, graphDepth: {graph_depth}) {{
221 ...tProxy
222 }}
223 familyProxies (sort: $sortBy, graphDepth: {graph_depth}) {{
224 ...fProxy
225 }}
226 }}
227 }}'''
228 elif options.disp_form != "tasks":
229 query = f'''
230 {WORKFLOW_SUMMARY_FRAGMENT}
231 query ($wFlows: [ID]!) {{
232 workflows (ids: $wFlows, stripNull: false) {{
233 ...wFlow
234 }}
235 }}'''
236 else:
237 query = f'''
238 {TASK_SUMMARY_FRAGMENT}
239 query ($wFlows: [ID]!, $sortBy: SortArgs) {{
240 workflows (ids: $wFlows, stripNull: false) {{
241 taskProxies (sort: $sortBy, graphDepth: {graph_depth}) {{
242 ...tProxy
243 }}
244 }}
245 }}'''
246
247 query_kwargs = {
248 'request_string': query,
249 'variables': {'wFlows': [workflow_id], 'sortBy': sort_args}
250 }
251
252 workflows = await pclient.async_request('graphql', query_kwargs)
253
254 try:
255 for summary in workflows['workflows']:
256 if options.disp_form == "raw":
257 if options.pretty:
258 write(json.dumps(summary, indent=4))
259 else:
260 write(summary)
261 else:
262 if options.disp_form != "tasks":
263 node_urls = {
264 node['name']: node['meta']['URL']
265 for node in summary['tasks'] + summary['families']
266 }
267 summary['workflowUrls'] = {
268 node_name: node_urls[node_name]
269 for node_name in summary['namespaceDefinitionOrder']
270 if node_name in node_urls
271 }
272 summary['workflowUrls']['workflow_id'] = (
273 summary['meta']['URL'])
274 del summary['tasks']
275 del summary['families']
276 del summary['meta']
277 for key, value in sorted(summary.items()):
278 write(
279 f'{to_snake_case(key).replace("_", " ")}={value}')
280 elif options.legacy_format:
281 for item in summary['taskProxies']:
282 if options.sort_by_cycle:
283 values = [
284 item['cyclePoint'],
285 item['name'],
286 item['state']]
287 else:
288 values = [
289 item['name'],
290 item['cyclePoint'],
291 item['state']]
292 values.append('held' if item['isHeld'] else 'not-held')
293 values.append('queued' if item['isQueued']
294 else 'not-queued')
295 values.append('runahead' if item['isRunahead']
296 else 'not-runahead')
297 if options.show_flows:
298 values.append(item['flowNums'])
299 write(', '.join(values))
300 else:
301 for item in summary['taskProxies']:
302 result = (
303 f"{item['cyclePoint']}/{item['name']}"
304 f":{item['state']}"
305 )
306 attrs = []
307 if item['isHeld']:
308 attrs.append("held")
309 if item['isQueued']:
310 attrs.append("queued")
311 if item['isRunahead']:
312 attrs.append("runahead")
313 if attrs:
314 result += " (" + ",".join(attrs) + ")"
315 if options.show_flows:
316 result += (
317 f" flows={item['flowNums'].replace(' ', '')}"
318 )
319 write(result)
320
321 except Exception as exc:
322 raise CylcError(
323 json.dumps(workflows, indent=4) + '\n' + str(exc) + '\n'
324 ) from None