Debian Codegraph @

cylc/flow/main_loop/auto_restart.py

raw
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 """Automatically restart workflows if they are running on bad servers.
17
18 Loads in the global configuration to check if the server a workflow is running
19 on is listed in :cylc:conf:`global.cylc[scheduler][run hosts]condemned`.
20
21 This is useful if a host needs to be taken off-line e.g. for scheduled
22 maintenance.
23
24 This functionality is configured via the following site configuration
25 settings:
26
27 .. cylc-scope:: global.cylc
28
29 - :cylc:conf:`[scheduler]auto restart delay`
30 - :cylc:conf:`[scheduler][run hosts]condemned`
31 - :cylc:conf:`[scheduler][run hosts]available`
32
33
34
35 The auto stop-restart feature has two modes:
36
37 Normal Mode
38 When a host is added to the
39 :cylc:conf:`[scheduler][run hosts]condemned` list, any workflows
40 running on that host will automatically shutdown then restart selecting a
41 new host from :cylc:conf:`[scheduler][run hosts]available`.
42
43 For safety, before attempting to stop the workflow Cylc will first wait
44 for any jobs running locally (under background or at) to complete.
45
46 In order for Cylc to be able to restart workflows the
47 :cylc:conf:`[scheduler][run hosts]available` hosts must all be on a
48 shared filesystem.
49 Force Mode
50 If a host is suffixed with an exclamation mark then Cylc will not attempt
51 to automatically restart the workflow and any local jobs (running under
52 background or at) will be left running.
53
54 For example in the following configuration any workflows running on
55 ``foo`` will attempt to restart on ``pub`` whereas any workflows
56 running on ``bar`` will stop immediately, making no attempt to restart.
57
58 .. code-block:: cylc
59
60 [scheduler]
61 [[run hosts]]
62 available = pub
63 condemned = foo, bar!
64
65 .. warning::
66
67 Cylc will reject hosts with ambiguous names such as ``localhost`` or
68 ``127.0.0.1`` for this configuration as
69 :cylc:conf:`[scheduler][run hosts]condemned`
70 are evaluated on the workflow host server.
71
72 To prevent large numbers of workflows attempting to restart simultaneously the
73 :cylc:conf:`[scheduler]auto restart delay` setting defines a period
74 of time in seconds.
75 Workflows will wait for a random period of time between zero and
76 :cylc:conf:`[scheduler]auto restart delay` seconds before
77 attempting to stop and restart.
78
79 Workflows that are started up in no-detach mode cannot auto stop-restart on a
80 different host - as it will still end up attached to the condemned host.
81 Therefore, a workflow in no-detach mode running on a condemned host will abort
82 with a non-zero return code. The parent process should manually handle the
83 restart of the workflow if desired.
84
85 .. cylc-scope::
86
87 """
88 from random import random
89 from socket import gaierror
90 from time import time
91 import traceback
92
93 from cylc.flow import LOG
94 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
95 from cylc.flow.exceptions import (
96 CylcConfigError,
97 HostSelectException,
98 )
99 from cylc.flow.host_select import select_workflow_host
100 from cylc.flow.hostuserutil import get_fqdn_by_host
101 from cylc.flow.main_loop import periodic
102 from cylc.flow.parsec.exceptions import ParsecError
103 from cylc.flow.scheduler import SchedulerError
104 from cylc.flow.wallclock import get_time_string_from_unix_time as time2str
105 from cylc.flow.workflow_status import AutoRestartMode
106
107
108 @periodic
109 async def auto_restart(scheduler, _):
110 """Automatically restart the workflow if configured to do so."""
111 try:
112 current_glbl_cfg = glbl_cfg(cached=False)
113 except (CylcConfigError, ParsecError) as exc:
114 LOG.error(
115 'auto restart: an error in the global config is preventing it from'
116 f' being reloaded:\n{exc}'
117 )
118 # skip check - we can't do anything until the global config has been
119 # fixed
120 return False # return False to make testing easier
121 mode = _should_auto_restart(scheduler, current_glbl_cfg)
122
123 if mode:
124 LOG.info('The Cylc workflow host will soon become un-available.')
125 _set_auto_restart(
126 scheduler,
127 restart_delay=current_glbl_cfg.get(
128 ['scheduler', 'auto restart delay']
129 ),
130 mode=mode
131 )
132
133
134 def _should_auto_restart(scheduler, current_glbl_cfg):
135 # check if workflow host is condemned - if so auto restart
136 if scheduler.stop_mode is None:
137 for host in current_glbl_cfg.get(
138 ['scheduler', 'run hosts', 'condemned']
139 ):
140 if host.endswith('!'):
141 # host ends in an `!` -> force shutdown mode
142 mode = AutoRestartMode.FORCE_STOP
143 host = host[:-1]
144 else:
145 # normal mode (stop and restart the workflow)
146 mode = AutoRestartMode.RESTART_NORMAL
147 if scheduler.auto_restart_time is not None:
148 # workflow is already scheduled to stop-restart only
149 # AutoRestartMode.FORCE_STOP can override this.
150 continue
151
152 try:
153 fqdn = get_fqdn_by_host(host)
154 except gaierror:
155 # that host is down - can't be the scheduler host
156 continue
157 if fqdn == scheduler.host:
158 # this host is condemned, take the appropriate action
159 return mode
160
161 return False
162
163
164 def _can_auto_restart():
165 """Determine whether this workflow can safely auto stop-restart."""
166 # Check whether there is currently an available host to restart on.
167 err_msg = 'Workflow cannot automatically restart'
168 try:
169 select_workflow_host(cached=False)
170 except HostSelectException as exc:
171 LOG.critical(
172 f"{err_msg}: No alternative host to restart workflow on.\n{exc}"
173 )
174 return False
175 except Exception:
176 # Any unexpected error in host selection shouldn't be able to take
177 # down the workflow.
178 LOG.critical(
179 f"{err_msg}: Error in host selection.\n{traceback.format_exc()}"
180 )
181 return False
182 else:
183 return True
184
185
186 def _set_auto_restart(
187 scheduler,
188 restart_delay=None,
189 mode=AutoRestartMode.RESTART_NORMAL
190 ):
191 """Configure the workflow to automatically stop and restart.
192
193 Restart handled by `workflow_auto_restart`.
194
195 Args:
196 scheduler (cylc.flow.scheduler.Scheduler):
197 Scheduler instance of the running workflow.
198 restart_delay (cylc.flow.parsec.DurationFloat):
199 Workflow will wait a random period between 0 and
200 `restart_delay` seconds before attempting to stop/restart in
201 order to avoid multiple workflows restarting simultaneously.
202 mode (str): Auto stop-restart mode.
203
204 Return:
205 bool: False if it is not possible to automatically stop/restart
206 the workflow due to its configuration/runtime state.
207 """
208 # Check that the workflow isn't already shutting down.
209 if scheduler.stop_mode:
210 return True
211
212 # Force mode, stop the workflow now, don't restart it.
213 if mode == AutoRestartMode.FORCE_STOP:
214 LOG.critical(
215 'This workflow will be shutdown as the workflow '
216 'host is unable to continue running it.\n'
217 'When another workflow host becomes available '
218 'the workflow can be restarted by:\n'
219 f' $ cylc play {scheduler.workflow}')
220 if scheduler.auto_restart_time:
221 LOG.info('Scheduled automatic restart canceled')
222 scheduler.auto_restart_time = time()
223 scheduler.auto_restart_mode = mode
224 return True
225
226 # Check workflow isn't already scheduled to auto-stop.
227 if scheduler.auto_restart_time is not None:
228 return True
229
230 # Workflow host is condemned and workflow running in no detach mode.
231 # Raise an error to cause the workflow to abort.
232 # This should raise an "abort" event and return a non-zero code to the
233 # caller still attached to the workflow process.
234 if scheduler.options.no_detach:
235 raise SchedulerError('Workflow host condemned in no detach mode')
236
237 # Check workflow is able to be safely restarted.
238 if not _can_auto_restart():
239 return False
240
241 LOG.info('Workflow will automatically restart on a new host.')
242 if restart_delay is not None and restart_delay != 0:
243 if restart_delay > 0:
244 # Delay shutdown by a random interval to avoid many
245 # workflows restarting simultaneously.
246 shutdown_delay = int(random() * restart_delay) # nosec
247 else:
248 # Un-documented feature, schedule exact restart interval for
249 # testing purposes.
250 shutdown_delay = abs(int(restart_delay))
251 shutdown_time = time() + shutdown_delay
252 LOG.info('Workflow will restart in %ss (at %s)', shutdown_delay,
253 time2str(shutdown_time))
254 scheduler.auto_restart_time = shutdown_time
255 else:
256 scheduler.auto_restart_time = time()
257
258 scheduler.auto_restart_mode = AutoRestartMode.RESTART_NORMAL
259
260 return True