Debian Codegraph @

cylc/flow/network/client.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 """Client for workflow runtime API."""
17
18 from abc import (
19 ABCMeta,
20 abstractmethod,
21 )
22 import asyncio
23 import os
24 from shutil import which
25 import socket
26 import sys
27 from typing import (
28 TYPE_CHECKING,
29 Any,
30 Dict,
31 Optional,
32 Union,
33 )
34
35 import zmq
36 import zmq.asyncio
37
38 from cylc.flow import (
39 LOG,
40 __version__ as CYLC_VERSION,
41 )
42 from cylc.flow.exceptions import (
43 ClientTimeout,
44 SchedulerAlive,
45 CylcError,
46 RequestError,
47 WorkflowStopped,
48 )
49 from cylc.flow.hostuserutil import get_fqdn_by_host
50 from cylc.flow.network import (
51 ZMQSocketBase,
52 deserialize,
53 get_location,
54 serialize,
55 )
56 from cylc.flow.network.client_factory import CommsMeth
57 from cylc.flow.network.server import PB_METHOD_MAP
58 from cylc.flow.workflow_files import detect_old_contact_file
59
60
61 if TYPE_CHECKING:
62 from cylc.flow.network import ResponseDict
63
64
65 class WorkflowRuntimeClientBase(metaclass=ABCMeta):
66 """Base class for WorkflowRuntimeClients.
67
68 WorkflowRuntimeClients that inherit from this must implement an async
69 method ``async_request()``. This base class provides a ``serial_request()``
70 method based on the ``async_request()`` method, callable by ``__call__``.
71 It also provides a comms timeout handler method.
72
73 Attributes:
74 workflow: Workflow ID as a string.
75 host: Scheduler host.
76 port: The port being used by this client.
77 timeout: Round trip call-response timeout in seconds.
78 scheduler_version: The Cylc version used by the scheduler.
79
80 """
81
82 DEFAULT_TIMEOUT = 5 # seconds
83
84 def __init__(
85 self,
86 workflow: str,
87 host: Optional[str] = None,
88 port: Union[int, str, None] = None,
89 scheduler_version: Optional[str] = None,
90 timeout: Union[float, str, None] = None
91 ):
92 self.workflow = workflow
93 if not host or not port or not scheduler_version:
94 host, port, _, scheduler_version = get_location(workflow)
95 else:
96 # optimisation: don't need to load the contact file if we
97 # already know all the required information
98 port = int(port)
99 self.host = self._orig_host = host
100 self.port = self._orig_port = port
101 self.scheduler_version = scheduler_version
102 self.timeout = (
103 float(timeout) if timeout is not None else self.DEFAULT_TIMEOUT
104 )
105
106 @abstractmethod
107 async def async_request(
108 self,
109 command: str,
110 args: Optional[Dict[str, Any]] = None,
111 timeout: Optional[float] = None,
112 req_meta: Optional[Dict[str, Any]] = None
113 ) -> object:
114 """Send an asynchronous request."""
115 ...
116
117 def serial_request(
118 self,
119 command: str,
120 args: Optional[Dict[str, Any]] = None,
121 timeout: Optional[float] = None,
122 req_meta: Optional[Dict[str, Any]] = None
123 ) -> object:
124 """Send a request.
125
126 For convenience use ``__call__`` to call this method.
127
128 Args:
129 command: The name of the endpoint to call.
130 args: Arguments to pass to the endpoint function.
131 timeout: Override the default timeout (seconds).
132
133 Raises:
134 ClientTimeout: If a response takes longer than timeout to arrive.
135 ClientError: Coverall for all other issues including failed auth.
136
137 Returns:
138 object: The data exactly as returned from the endpoint function,
139 nothing more, nothing less.
140
141 """
142 loop = getattr(self, 'loop', asyncio.new_event_loop())
143 task = loop.create_task(
144 self.async_request(command, args, timeout, req_meta)
145 )
146 loop.run_until_complete(task)
147 if not hasattr(self, 'loop'):
148 # (If inheriting class does have an event loop, don't mess with it)
149 loop.close()
150 return task.result()
151
152 __call__ = serial_request
153
154 def timeout_handler(self) -> None:
155 """Handle the eventuality of a communication timeout with the workflow.
156
157 Raises:
158 WorkflowStopped: if the workflow has already stopped.
159 CyclError: if the workflow has moved to different host/port.
160 """
161 LOG.warning(
162 f"{self.workflow} {self.host}:{self.port}:"
163 f" Connection timed out ({self.timeout} ms)"
164 )
165 contact_host, contact_port, *_ = get_location(self.workflow)
166 if (
167 contact_host != get_fqdn_by_host(self._orig_host)
168 or contact_port != self._orig_port
169 ):
170 raise CylcError(
171 'The workflow is no longer running at '
172 f'{self._orig_host}:{self._orig_port}\n'
173 f'It has moved to {contact_host}:{contact_port}'
174 )
175
176 if os.getenv('CYLC_TASK_COMMS_METHOD'):
177 # don't attempt to clean up old contact files in task messages
178 return
179
180 # Cannot connect, perhaps workflow is no longer running and is leaving
181 # behind a contact file?
182 try:
183 detect_old_contact_file(self.workflow)
184 except SchedulerAlive:
185 # old contact file exists and the workflow process still alive
186 return
187 else:
188 # the workflow has stopped
189 raise WorkflowStopped(self.workflow)
190
191
192 class WorkflowRuntimeClient( # type: ignore[misc]
193 ZMQSocketBase, WorkflowRuntimeClientBase
194 ):
195 # (Ignoring mypy 'definition of "host" in base class "ZMQSocketBase" is
196 # incompatible with definition in base class "WorkflowRuntimeClientBase"')
197 """Initiate a client to the scheduler API.
198
199 Initiates the REQ part of a ZMQ REQ-REP pair.
200
201 This class contains the logic for the ZMQ message interface and client -
202 server communication.
203
204 Determine host and port from the contact file unless provided.
205
206 If there is no socket bound to the specified host/port the client will
207 bail after ``timeout`` seconds.
208
209 Args:
210 workflow:
211 Name of the workflow to connect to.
212 timeout:
213 Set the default timeout in seconds. The default is
214 ``ZMQClient.DEFAULT_TIMEOUT``.
215 Note the default timeout can be overridden for individual requests.
216 host:
217 The host where the flow is running if known.
218
219 If both host and port are provided it is not necessary to load
220 the contact file.
221 port:
222 The port on which the REQ-REP TCP server is listening.
223
224 If both host and port are provided it is not necessary to load
225 the contact file.
226
227 Attributes:
228 host:
229 Workflow host name.
230 port:
231 Workflow host port.
232 timeout_handler:
233 Optional function which runs before ClientTimeout is raised.
234 This provides an interface for raising more specific exceptions in
235 the event of a communication timeout.
236 header:
237 Request "header" data to attach to each request.
238
239 Usage:
240 Call endpoints using ``ZMQClient.__call__``.
241
242 Message interface:
243 * Accepts responses of the format: {"data": {...}}
244 * Accepts error in the format: {"error": {"message": MSG}}
245 * Returns requests of the format: {"command": CMD,
246 "args": {...}}
247
248 Raises:
249 WorkflowStopped: if the workflow is not running.
250
251 Call server "endpoints" using:
252 ``__call__``, ``serial_request``
253 .. automethod::
254 cylc.flow.network.client.WorkflowRuntimeClient.serial_request
255
256 ``async_request``
257 .. automethod::
258 cylc.flow.network.client.WorkflowRuntimeClient.async_request
259
260 """
261 # socket & event loop not None - get assigned on init by self.start():
262 socket: zmq.asyncio.Socket
263 loop: asyncio.AbstractEventLoop
264
265 def __init__(
266 self,
267 workflow: str,
268 host: Optional[str] = None,
269 port: Union[int, str, None] = None,
270 timeout: Union[float, str, None] = None,
271 scheduler_version: Optional[str] = None,
272 context: Optional[zmq.asyncio.Context] = None,
273 srv_public_key_loc: Optional[str] = None
274 ):
275 ZMQSocketBase.__init__(self, zmq.REQ, workflow, context=context)
276 WorkflowRuntimeClientBase.__init__(
277 self,
278 workflow,
279 host,
280 port,
281 scheduler_version,
282 timeout
283 )
284 # convert to milliseconds:
285 self.timeout *= 1000
286 self.poller: Any = None
287 # Connect the ZMQ socket on instantiation
288 self.start(self.host, self.port, srv_public_key_loc)
289 # gather header info post start
290 self.header = self.get_header()
291
292 def _socket_options(self):
293 """Set socket options after socket instantiation before connect.
294
295 Overwrites Base method.
296
297 """
298 # if there is no server don't keep the client hanging around
299 self.socket.setsockopt(zmq.LINGER, int(self.DEFAULT_TIMEOUT))
300
301 # create a poller to handle timeouts
302 self.poller = zmq.Poller()
303 self.poller.register(self.socket, zmq.POLLIN)
304
305 async def async_request(
306 self,
307 command: str,
308 args: Optional[Dict[str, Any]] = None,
309 timeout: Optional[float] = None,
310 req_meta: Optional[Dict[str, Any]] = None
311 ) -> object:
312 """Send an asynchronous request using asyncio.
313
314 Has the same arguments and return values as ``serial_request``.
315
316 """
317 timeout = (float(timeout) * 1000 if timeout else None) or self.timeout
318 if not args:
319 args = {}
320
321 # Note: we are using CurveZMQ to secure the messages (see
322 # self.curve_auth, self.socket.curve_...key etc.). We have set up
323 # public-key cryptography on the ZMQ messaging and sockets, so
324 # there is no need to encrypt messages ourselves before sending.
325
326 # send message
327 msg: Dict[str, Any] = {'command': command, 'args': args}
328 msg.update(self.header)
329 # add the request metadata
330 if req_meta:
331 msg['meta'].update(req_meta)
332 LOG.debug('zmq:send %s', msg)
333 message = serialize(msg)
334 self.socket.send_string(message)
335
336 # receive response
337 if self.poller.poll(timeout):
338 res: bytes = await self.socket.recv()
339 else:
340 self.timeout_handler()
341 raise ClientTimeout(
342 'Timeout waiting for server response.'
343 ' This could be due to network or server issues.'
344 '\n* You might want to increase the timeout using the'
345 ' --comms-timeout option;'
346 '\n* or check the workflow log.'
347 )
348 LOG.debug('zmq:recv %s', res)
349
350 if command in PB_METHOD_MAP:
351 return res
352
353 response: ResponseDict = deserialize(res.decode())
354
355 try:
356 return response['data']
357 except KeyError:
358 error = response.get('error')
359 if isinstance(error, dict):
360 error = error.get('message', error)
361 if not error:
362 error = (
363 f"Received invalid response for Cylc {CYLC_VERSION}: "
364 f"{response}"
365 )
366 raise RequestError(
367 str(error), response.get('cylc_version')
368 ) from None
369
370 def get_header(self) -> dict:
371 """Return "header" data to attach to each request for traceability.
372
373 Returns:
374 dict: dictionary with the header information, such as
375 program and hostname.
376 """
377 host = socket.gethostname()
378 if len(sys.argv) > 1:
379 cmd = sys.argv[1]
380 else:
381 cmd = sys.argv[0]
382
383 cylc_executable_location = which("cylc")
384 if cylc_executable_location:
385 cylc_bin_dir = os.path.abspath(
386 os.path.join(cylc_executable_location, os.pardir)
387 )
388 if not cylc_bin_dir.endswith("/"):
389 cylc_bin_dir = f"{cylc_bin_dir}/"
390
391 if cmd.startswith(cylc_bin_dir):
392 cmd = cmd.replace(cylc_bin_dir, '')
393 return {
394 'meta': {
395 'prog': cmd,
396 'host': host,
397 'comms_method':
398 os.getenv(
399 "CLIENT_COMMS_METH",
400 default=CommsMeth.ZMQ.value
401 )
402 }
403 }