Debian Codegraph @

cylc/flow/network/__init__.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 """Package for network interfaces to Cylc scheduler objects."""
17
18 import asyncio
19 import json
20 from typing import (
21 TYPE_CHECKING,
22 Optional,
23 Tuple,
24 TypedDict,
25 Union,
26 )
27
28 import zmq
29 import zmq.asyncio
30 import zmq.auth
31
32 from cylc.flow import LOG
33 from cylc.flow.exceptions import (
34 ClientError,
35 CylcError,
36 CylcVersionError,
37 ServiceFileError,
38 WorkflowStopped,
39 )
40 from cylc.flow.hostuserutil import get_fqdn_by_host
41 from cylc.flow.workflow_files import (
42 ContactFileFields,
43 KeyInfo,
44 KeyOwner,
45 KeyType,
46 get_workflow_srv_dir,
47 load_contact_file,
48 )
49
50
51 if TYPE_CHECKING:
52 from zmq.asyncio import Context
53
54
55 API = 5 # cylc API version
56 MSG_TIMEOUT = "TIMEOUT"
57
58 if TYPE_CHECKING:
59 class ResponseDict(TypedDict, total=False):
60 """Structure of server response messages.
61
62 Confusingly, has similar format to GraphQL execution result.
63 But if we change this now we could break compatibility for
64 issuing commands to/receiving responses from workflows running in
65 different versions of Cylc 8.
66 """
67 data: object
68 """For most Cylc commands that issue GraphQL mutations, the data field
69 will look like:
70 data: {
71 <mutationName1>: {
72 result: [
73 {
74 id: <workflow/task ID>,
75 response: [<success_bool>, <message>]
76 },
77 ...
78 ]
79 }
80 }
81 but this is not 100% consistent unfortunately
82 """
83 error: Union[Exception, str, dict]
84 """If an error occurred that could not be handled.
85 (usually a dict {message: str, traceback?: str}).
86 """
87 user: str
88 cylc_version: str
89 """Server (i.e. running workflow) Cylc version.
90
91 Going forward, we include this so we can more easily handle any future
92 back-compat issues."""
93
94
95 def serialize(data: object) -> str:
96 """Convert the structure holding a message to a JSON message string."""
97 # Abstract out the transport format in order to allow it to be changed
98 # in future.
99 return json.dumps(data)
100
101
102 def deserialize(message: str) -> 'ResponseDict':
103 """Convert a JSON message string to dict with an added 'user' field."""
104 # Abstract out the transport format in order to allow it to be changed
105 # in future.
106 return json.loads(message)
107
108
109 def get_location(workflow: str) -> Tuple[str, int, int, str]:
110 """Extract host and port from a workflow's contact file.
111
112 NB: if it fails to load the workflow contact file, it will exit.
113
114 Args:
115 workflow: workflow ID
116 Returns:
117 Tuple (host name, port number, publish port number, scheduler version)
118 Raises:
119 WorkflowStopped: if the workflow is not running.
120 CylcVersionError: if target is a Cylc 7 (or earlier) workflow.
121 """
122 try:
123 contact = load_contact_file(workflow)
124 except (IOError, ValueError, ServiceFileError):
125 # Contact file does not exist or corrupted, workflow should be dead
126 raise WorkflowStopped(workflow) from None
127
128 host = contact[ContactFileFields.HOST]
129 host = get_fqdn_by_host(host)
130 port = int(contact[ContactFileFields.PORT])
131 version = contact[ContactFileFields.VERSION]
132 if ContactFileFields.PUBLISH_PORT in contact:
133 pub_port = int(contact[ContactFileFields.PUBLISH_PORT])
134 else:
135 raise CylcVersionError(version=version)
136 return host, port, pub_port, version
137
138
139 class ZMQSocketBase:
140 """Initiate the ZMQ socket bind for specified pattern.
141
142 NOTE: Security to be provided via zmq.auth (see PR #3359).
143
144 Args:
145 pattern (enum): ZeroMQ message pattern (zmq.PATTERN).
146
147 context (object, optional): instantiated ZeroMQ context, defaults
148 to zmq.asyncio.Context().
149
150 This class is designed to be inherited by REP Server (REQ/REP)
151 and by PUB Publisher (PUB/SUB), as the start-up logic is similar.
152
153
154 To tailor this class overwrite it's method on inheritance.
155
156 """
157
158 def __init__(
159 self,
160 pattern,
161 workflow: str,
162 bind: bool = False,
163 context: 'Optional[Context]' = None,
164 ):
165 self.bind = bind
166 if context is None:
167 self.context: 'Context' = zmq.asyncio.Context()
168 else:
169 self.context = context
170 self.pattern = pattern
171 self.workflow = workflow
172 self.host: Optional[str] = None
173 self.port: Optional[int] = None
174 self.socket: Optional[zmq.Socket] = None
175 self.loop: Optional[asyncio.AbstractEventLoop] = None
176 self.stopping = False
177
178 def start(self, *args, **kwargs):
179 """Create the async loop, and bind socket."""
180 # set asyncio loop
181 try:
182 self.loop = asyncio.get_running_loop()
183 except RuntimeError:
184 self.loop = asyncio.new_event_loop()
185 asyncio.set_event_loop(self.loop)
186
187 if self.bind:
188 self._socket_bind(*args, **kwargs)
189 else:
190 self._socket_connect(*args, **kwargs)
191
192 # initiate bespoke items
193 self._bespoke_start()
194
195 # Keeping srv_prv_key_loc as optional arg so as to not break interface
196 def _socket_bind(self, min_port, max_port, srv_prv_key_loc=None):
197 """Bind socket.
198
199 Will use a port range provided to select random ports.
200
201 """
202 if srv_prv_key_loc is None:
203 # Create new KeyInfo object for the server private key
204 workflow_srv_dir = get_workflow_srv_dir(self.workflow)
205 srv_prv_key_info = KeyInfo(
206 KeyType.PRIVATE,
207 KeyOwner.SERVER,
208 workflow_srv_dir=workflow_srv_dir)
209 else:
210 srv_prv_key_info = KeyInfo(
211 KeyType.PRIVATE,
212 KeyOwner.SERVER,
213 full_key_path=srv_prv_key_loc)
214
215 # create socket
216 self.socket = self.context.socket(self.pattern)
217 self._socket_options()
218
219 try:
220 server_public_key, server_private_key = zmq.auth.load_certificate(
221 srv_prv_key_info.full_key_path)
222 except ValueError:
223 raise ServiceFileError(
224 "Failed to find server's public key in "
225 f"{srv_prv_key_info.full_key_path}."
226 ) from None
227 except OSError as exc:
228 raise ServiceFileError(
229 "IO error opening server's private key from "
230 f"{srv_prv_key_info.full_key_path}."
231 ) from exc
232 if server_private_key is None: # this can't be caught by exception
233 raise ServiceFileError(
234 f"Failed to find server's private "
235 f"key in "
236 f"{srv_prv_key_info.full_key_path}."
237 )
238 self.socket.curve_publickey = server_public_key
239 self.socket.curve_secretkey = server_private_key
240 self.socket.curve_server = True
241
242 try:
243 if min_port == max_port:
244 self.port = min_port
245 self.socket.bind(f'tcp://*:{min_port}')
246 else:
247 self.port = self.socket.bind_to_random_port(
248 'tcp://*', min_port, max_port)
249 except (zmq.error.ZMQError, zmq.error.ZMQBindError) as exc:
250 raise CylcError(
251 f'could not start Cylc ZMQ server: {exc}'
252 ) from None
253
254 # Keeping srv_public_key_loc as optional arg so as to not break interface
255 def _socket_connect(self, host, port, srv_public_key_loc=None):
256 """Connect socket to stub."""
257 workflow_srv_dir = get_workflow_srv_dir(self.workflow)
258 if srv_public_key_loc is None:
259 # Create new KeyInfo object for the server public key
260 srv_pub_key_info = KeyInfo(
261 KeyType.PUBLIC,
262 KeyOwner.SERVER,
263 workflow_srv_dir=workflow_srv_dir)
264
265 else:
266 srv_pub_key_info = KeyInfo(
267 KeyType.PUBLIC,
268 KeyOwner.SERVER,
269 full_key_path=srv_public_key_loc)
270
271 self.host = host
272 self.port = port
273 self.socket = self.context.socket(self.pattern)
274 self._socket_options()
275
276 client_priv_key_info = KeyInfo(
277 KeyType.PRIVATE,
278 KeyOwner.CLIENT,
279 workflow_srv_dir=workflow_srv_dir)
280 error_msg = "Failed to find user's private key, so cannot connect."
281 try:
282 client_public_key, client_priv_key = zmq.auth.load_certificate(
283 client_priv_key_info.full_key_path)
284 except ValueError:
285 raise ClientError(error_msg) from None
286 except OSError as exc:
287 raise ClientError(error_msg) from exc
288 if client_priv_key is None: # this can't be caught by exception
289 raise ClientError(error_msg)
290 self.socket.curve_publickey = client_public_key
291 self.socket.curve_secretkey = client_priv_key
292
293 # A client can only connect to the server if it knows its public key,
294 # so we grab this from the location it was created on the filesystem:
295 error_msg = (
296 "Failed to load the workflow's public key, so cannot connect."
297 )
298 try:
299 # 'load_certificate' will try to load both public & private keys
300 # from a provided file but will return None, not throw an error,
301 # for the latter item if not there (as for all public key files)
302 # so it is OK to use; there is no method to load only the
303 # public key.
304 server_public_key = zmq.auth.load_certificate(
305 srv_pub_key_info.full_key_path)[0]
306 self.socket.curve_serverkey = server_public_key
307 except ValueError: # ValueError raised w/ no public key
308 raise ClientError(error_msg) from None
309 except OSError as exc:
310 raise ClientError(error_msg) from exc
311
312 self.socket.connect(f'tcp://{host}:{port}')
313
314 def _socket_options(self):
315 """Set socket options.
316
317 i.e. self.socket.sndhwm
318 """
319 self.socket.sndhwm = 10000
320
321 def _bespoke_start(self):
322 """Initiate bespoke items at start."""
323 self.stopping = False
324
325 def stop(self, stop_loop=True):
326 """Stop the server.
327
328 Args:
329 stop_loop (Boolean): Stop running IOLoop.
330
331 """
332 self._bespoke_stop()
333 if stop_loop and self.loop and self.loop.is_running():
334 self.loop.stop()
335 if self.socket and not self.socket.closed:
336 self.socket.close()
337 LOG.debug('...stopped')
338
339 def _bespoke_stop(self):
340 """Bespoke stop items."""
341 LOG.debug('stopping zmq socket...')
342 self.stopping = True