| 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 stop [OPTIONS] ARGS |
| 20 |
|
| 21 |
Tell a workflow to shut down. |
| 22 |
|
| 23 |
Examples: |
| 24 |
# wait for active tasks to finish, then shut down |
| 25 |
$ cylc stop my_workflow |
| 26 |
|
| 27 |
# kill active tasks, then shut down |
| 28 |
$ cylc stop my_workflow --kill |
| 29 |
|
| 30 |
# shut down immediately, leave active tasks alone |
| 31 |
$ cylc stop my_workflow --now |
| 32 |
|
| 33 |
# shut down all workflows |
| 34 |
$ cylc stop '*' |
| 35 |
|
| 36 |
# shut down after the cycle 1234 has been passed |
| 37 |
$ cylc stop my_workflow//1234 |
| 38 |
|
| 39 |
# shut down after the task foo in cycle 1234 has succeeded |
| 40 |
$ cylc stop my_workflow//1234/foo |
| 41 |
|
| 42 |
By default stopping workflows wait for submitted and running tasks to complete |
| 43 |
before shutting down. You can change this behaviour with the --now or |
| 44 |
--kill options. |
| 45 |
|
| 46 |
There are several shutdown methods: |
| 47 |
|
| 48 |
1. (default) stop after current active tasks finish |
| 49 |
2. (--now) stop immediately, orphaning current active tasks |
| 50 |
3. (--kill) stop after killing current active tasks |
| 51 |
4. (if ID specifies a cycle point) stop after the cycle point |
| 52 |
5. (if ID specifies a task ID) stop after the task has succeeded |
| 53 |
6. (--wall-clock=T) stop after time T (an ISO 8601 date-time format e.g. |
| 54 |
CCYYMMDDThh:mm, CCYY-MM-DDThh, etc). |
| 55 |
|
| 56 |
Tasks that become ready after the shutdown is ordered will be submitted |
| 57 |
immediately if the workflow is restarted. Remaining task event handlers and |
| 58 |
job poll and kill commands will be executed prior to shutdown, unless |
| 59 |
--now is used twice. |
| 60 |
|
| 61 |
This command exits immediately unless --max-polls is greater than zero, in |
| 62 |
which case it polls to wait for workflow shutdown. |
| 63 |
""" |
| 64 |
|
| 65 |
from functools import partial |
| 66 |
import sys |
| 67 |
from typing import TYPE_CHECKING, Optional |
| 68 |
|
| 69 |
from cylc.flow.command_polling import Poller |
| 70 |
from cylc.flow.exceptions import ( |
| 71 |
ClientError, |
| 72 |
ClientTimeout, |
| 73 |
CylcError, |
| 74 |
InputError, |
| 75 |
WorkflowStopped, |
| 76 |
) |
| 77 |
from cylc.flow.network.client_factory import get_client |
| 78 |
from cylc.flow.network.multi import call_multi |
| 79 |
from cylc.flow.network.schema import WorkflowStopMode |
| 80 |
from cylc.flow.option_parsers import ( |
| 81 |
CylcOptionParser as COP, |
| 82 |
ID_MULTI_ARG_DOC, |
| 83 |
) |
| 84 |
from cylc.flow.terminal import cli_function |
| 85 |
|
| 86 |
if TYPE_CHECKING: |
| 87 |
from optparse import Values |
| 88 |
|
| 89 |
|
| 90 |
MUTATION = ''' |
| 91 |
mutation ( |
| 92 |
$wFlows: [WorkflowID]!, |
| 93 |
$stopMode: WorkflowStopMode, |
| 94 |
$cyclePoint: CyclePoint, |
| 95 |
$clockTime: TimePoint, |
| 96 |
$task: TaskID, |
| 97 |
$flowNum: Int, |
| 98 |
) { |
| 99 |
stop ( |
| 100 |
workflows: $wFlows, |
| 101 |
mode: $stopMode, |
| 102 |
cyclePoint: $cyclePoint, |
| 103 |
clockTime: $clockTime, |
| 104 |
task: $task, |
| 105 |
flowNum: $flowNum |
| 106 |
) { |
| 107 |
result |
| 108 |
} |
| 109 |
} |
| 110 |
''' |
| 111 |
|
| 112 |
POLLER_QUERY = ''' |
| 113 |
query ($wFlows: [ID]) { |
| 114 |
workflows(ids: $wFlows) { |
| 115 |
id |
| 116 |
} |
| 117 |
} |
| 118 |
''' |
| 119 |
|
| 120 |
|
| 121 |
class StopPoller(Poller): |
| 122 |
"""A polling object that checks if a workflow has stopped yet.""" |
| 123 |
|
| 124 |
def __init__(self, pclient, condition, interval, max_polls): |
| 125 |
Poller.__init__(self, condition, interval, max_polls, None) |
| 126 |
self.pclient = pclient |
| 127 |
self.query = { |
| 128 |
'request_string': POLLER_QUERY, |
| 129 |
'variables': {'wFlows': [self.pclient.workflow]} |
| 130 |
} |
| 131 |
|
| 132 |
async def check(self): |
| 133 |
"""Return True if workflow has stopped (success) else False""" |
| 134 |
try: |
| 135 |
await self.pclient.async_request('graphql', self.query) |
| 136 |
except (ClientError, ClientTimeout, CylcError): |
| 137 |
# failed to ping - workflow stopped or (CylcError) restarted on |
| 138 |
# another host:port (in which case it must have stopped first). |
| 139 |
return True |
| 140 |
else: |
| 141 |
# pinged - workflow must be alive |
| 142 |
return False |
| 143 |
|
| 144 |
|
| 145 |
def get_option_parser() -> COP: |
| 146 |
parser = COP( |
| 147 |
__doc__, |
| 148 |
comms=True, |
| 149 |
multiworkflow=True, |
| 150 |
argdoc=[ |
| 151 |
ID_MULTI_ARG_DOC, |
| 152 |
], |
| 153 |
) |
| 154 |
|
| 155 |
parser.add_option( |
| 156 |
"-k", "--kill", |
| 157 |
help="Shut down after killing currently active tasks.", |
| 158 |
action="store_true", default=False, dest="kill") |
| 159 |
|
| 160 |
parser.add_option( |
| 161 |
"--flow", metavar="INT", |
| 162 |
help="Stop flow number INT from spawning more tasks. " |
| 163 |
"The scheduler will shut down if it is the only flow.", |
| 164 |
action="store", dest="flow_num") |
| 165 |
|
| 166 |
parser.add_option( |
| 167 |
"-n", "--now", |
| 168 |
help=( |
| 169 |
"Shut down without waiting for active tasks to complete." + |
| 170 |
" If this option is specified once," + |
| 171 |
" wait for task event handler, job poll/kill to complete." + |
| 172 |
" If this option is specified more than once," + |
| 173 |
" tell the workflow to terminate immediately."), |
| 174 |
action="count", default=0, dest="now") |
| 175 |
|
| 176 |
parser.add_option( |
| 177 |
"-w", "--wall-clock", metavar="STOP", |
| 178 |
help="Shut down after time STOP (ISO 8601 formatted)", |
| 179 |
action="store", dest="wall_clock") |
| 180 |
|
| 181 |
StopPoller.add_to_cmd_options(parser, d_max_polls=0) |
| 182 |
|
| 183 |
return parser |
| 184 |
|
| 185 |
|
| 186 |
def _validate( |
| 187 |
options: 'Values', |
| 188 |
stop_task: Optional[str], |
| 189 |
stop_cycle: Optional[str], |
| 190 |
*globs: str |
| 191 |
) -> None: |
| 192 |
"""Check option choices are valid.""" |
| 193 |
if stop_task is not None and options.kill: |
| 194 |
raise InputError("--kill is not compatible with stop-task") |
| 195 |
if stop_cycle is not None and options.kill: |
| 196 |
raise InputError("--kill is not compatible with stop-cycle") |
| 197 |
if stop_task and stop_cycle: |
| 198 |
raise InputError('stop-task is not compatible with stop-cycle') |
| 199 |
if options.kill and options.now: |
| 200 |
raise InputError("--kill is not compatible with --now") |
| 201 |
if options.flow_num and int(options.max_polls) > 0: |
| 202 |
raise InputError("--flow is not compatible with --max-polls") |
| 203 |
if options.flow_num and globs: |
| 204 |
raise InputError("--flow is not compatible with task IDs") |
| 205 |
|
| 206 |
|
| 207 |
async def run( |
| 208 |
options: 'Values', |
| 209 |
workflow_id, |
| 210 |
*tokens_list, |
| 211 |
) -> object: |
| 212 |
return await _run(options, workflow_id, *tokens_list) |
| 213 |
|
| 214 |
|
| 215 |
async def _run( |
| 216 |
options: 'Values', |
| 217 |
workflow_id, |
| 218 |
*tokens_list, |
| 219 |
) -> object: |
| 220 |
# parse the stop-task or stop-cycle if provided |
| 221 |
stop_task = stop_cycle = None |
| 222 |
if tokens_list: |
| 223 |
tokens = tokens_list[0] |
| 224 |
if tokens['task']: |
| 225 |
stop_task = tokens.relative_id |
| 226 |
elif tokens['cycle']: |
| 227 |
stop_cycle = tokens['cycle'] |
| 228 |
|
| 229 |
_validate(options, stop_task, stop_cycle, *tokens_list) |
| 230 |
|
| 231 |
pclient = get_client(workflow_id, timeout=options.comms_timeout) |
| 232 |
|
| 233 |
if int(options.max_polls) > 0: |
| 234 |
# (test to avoid the "nothing to do" warning for # --max-polls=0) |
| 235 |
|
| 236 |
spoller = StopPoller( |
| 237 |
pclient, |
| 238 |
"workflow stopped", |
| 239 |
options.interval, |
| 240 |
options.max_polls, |
| 241 |
) |
| 242 |
|
| 243 |
if stop_task or stop_cycle: |
| 244 |
mode: Optional[str] = None |
| 245 |
elif options.kill: |
| 246 |
mode = WorkflowStopMode.Kill.name |
| 247 |
elif options.now > 1: |
| 248 |
mode = WorkflowStopMode.NowNow.name |
| 249 |
elif options.now: |
| 250 |
mode = WorkflowStopMode.Now.name |
| 251 |
else: |
| 252 |
mode = WorkflowStopMode.Clean.name |
| 253 |
|
| 254 |
if ( |
| 255 |
options.flow_num is not None |
| 256 |
and hasattr(options.flow_num, 'isdigit') |
| 257 |
and options.flow_num.isdigit() |
| 258 |
): |
| 259 |
# flow num gql type is int |
| 260 |
options.flow_num = int(options.flow_num) |
| 261 |
|
| 262 |
mutation_kwargs = { |
| 263 |
'request_string': MUTATION, |
| 264 |
'variables': { |
| 265 |
'wFlows': [workflow_id], |
| 266 |
'stopMode': mode, |
| 267 |
'cyclePoint': stop_cycle, |
| 268 |
'clockTime': options.wall_clock, |
| 269 |
'task': stop_task, |
| 270 |
'flowNum': options.flow_num |
| 271 |
}, |
| 272 |
} |
| 273 |
|
| 274 |
ret = await pclient.async_request('graphql', mutation_kwargs) |
| 275 |
|
| 276 |
if int(options.max_polls) > 0 and not await spoller.poll(): |
| 277 |
# (test to avoid the "nothing to do" warning for # --max-polls=0) |
| 278 |
raise CylcError( |
| 279 |
f'Workflow did not shut down after {options.max_polls} polls' |
| 280 |
) |
| 281 |
return ret |
| 282 |
|
| 283 |
|
| 284 |
@cli_function(get_option_parser) |
| 285 |
def main( |
| 286 |
parser: COP, |
| 287 |
options: 'Values', |
| 288 |
*ids, |
| 289 |
) -> None: |
| 290 |
rets = call_multi( |
| 291 |
partial(run, options), |
| 292 |
*ids, |
| 293 |
constraint='mixed', |
| 294 |
max_tasks=1, |
| 295 |
success_exceptions=(WorkflowStopped,), |
| 296 |
) |
| 297 |
sys.exit(all(rets.values()) is False) |