Debian Codegraph @

cylc/flow/network/server.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 """Server for workflow runtime API."""
17
18 import asyncio
19 from queue import Queue
20 from textwrap import dedent
21 from time import sleep
22 from typing import (
23 TYPE_CHECKING,
24 Any,
25 Dict,
26 Iterable,
27 List,
28 Optional,
29 Union,
30 )
31
32 import zmq
33 from zmq.auth.thread import ThreadAuthenticator
34
35 from cylc.flow import (
36 LOG,
37 __version__ as CYLC_VERSION,
38 workflow_files,
39 )
40 from cylc.flow.cfgspec.glbl_cfg import glbl_cfg
41 from cylc.flow.data_messages_pb2 import PbEntireWorkflow
42 from cylc.flow.data_store_mgr import DELTAS_MAP
43 from cylc.flow.network.graphql import (
44 CylcExecutionContext,
45 IgnoreFieldMiddleware,
46 instantiate_middleware,
47 )
48 from cylc.flow.network.publisher import WorkflowPublisher
49 from cylc.flow.network.replier import WorkflowReplier
50 from cylc.flow.network.resolvers import Resolvers
51 from cylc.flow.network.schema import schema
52
53
54 if TYPE_CHECKING:
55 from threading import Thread
56
57 from cylc.flow.network import ResponseDict
58 from cylc.flow.scheduler import Scheduler
59
60
61 # maps server methods to the protobuf message (for client/UIS import)
62 PB_METHOD_MAP: Dict[str, Any] = {
63 'pb_entire_workflow': PbEntireWorkflow,
64 'pb_data_elements': DELTAS_MAP
65 }
66
67
68 def expose(func=None):
69 """Expose a method on the sever."""
70 func.exposed = True
71 return func
72
73
74 def filter_none(dictionary):
75 """Filter out `None` items from a dictionary:
76
77 Examples:
78 >>> filter_none({
79 ... 'a': 0,
80 ... 'b': '',
81 ... 'c': None
82 ... })
83 {'a': 0, 'b': ''}
84
85 """
86 return {
87 key: value
88 for key, value in dictionary.items()
89 if value is not None
90 }
91
92
93 class WorkflowRuntimeServer:
94 """Workflow runtime service API facade exposed via zmq.
95
96 This class starts and coordinates the publisher and replier, and
97 contains the Cylc endpoints invoked by the receiver to provide a response
98 to incoming messages.
99
100 Args:
101 schd (object): The parent object instantiating the server. In
102 this case, the workflow scheduler.
103
104 Usage:
105 * Define endpoints using the ``expose`` decorator.
106 * Endpoints are called via the receiver using the function name.
107
108 Message interface:
109 * Accepts messages of the format: {"command": CMD, "args": {...}}
110 * Returns responses of the format: {"data": {...}}
111 * Returns error in the format: {"error": {"message": MSG}}
112
113 Common Arguments:
114 Arguments which are shared between multiple commands.
115
116 task identifier (str):
117 A task identifier in the format ``cycle-point/task-name``
118 e.g. ``1/foo`` or ``20000101T0000Z/bar``.
119
120 .. _task globs:
121
122 task globs (list):
123 A list of Cylc IDs relative to the workflow.
124
125 * ``1`` - The cycle point "1".
126 * ``1/foo`` - The task "foo" in the cycle "1".
127 * ``1/foo/01`` - The first job of the task "foo" from the cycle
128 "1".
129
130 Glob-like patterns may be used to match multiple items e.g.
131
132 ``*``
133 Matches everything.
134 ``1/*``
135 Matches everything in cycle ``1``.
136 ``*/*:failed``
137 Matches all failed tasks.
138
139 """
140 endpoints: Dict[str, object]
141 curve_auth: ThreadAuthenticator
142 """The ZMQ authenticator."""
143 client_pub_key_dir: str
144 """Client public key directory, used by the ZMQ authenticator."""
145
146 OPERATE_SLEEP_INTERVAL = 0.2
147
148 def __init__(self, schd):
149
150 self.zmq_context = None
151 self.port = None
152 self.pub_port = None
153 self.replier = None
154 self.publisher = None
155 self.loop = None
156 self.thread: Thread | None = None
157
158 self.schd: 'Scheduler' = schd
159 self.resolvers = Resolvers(
160 self.schd.data_store_mgr,
161 schd=self.schd
162 )
163 self.middleware = [
164 IgnoreFieldMiddleware,
165 ]
166
167 self.publish_queue: 'Queue[Iterable[tuple]]' = Queue()
168 self._waiting_to_stop = False
169
170 self.register_endpoints()
171
172 def start(self, barrier):
173 """Start the TCP servers.
174
175 Note: this method is to be run in a separate thread.
176 """
177 # set asyncio loop on thread
178 try:
179 self.loop = asyncio.get_running_loop()
180 except RuntimeError:
181 self.loop = asyncio.new_event_loop()
182 asyncio.set_event_loop(self.loop)
183
184 # TODO: this in zmq asyncio context?
185 # Requires the scheduler main loop in asyncio first
186 # And use of concurrent.futures.ThreadPoolExecutor?
187 self.zmq_context = zmq.Context()
188 # create an authenticator for the ZMQ context
189 self.curve_auth = ThreadAuthenticator(self.zmq_context, log=LOG)
190 self.curve_auth.start() # start the authentication thread
191
192 # Setting the location means that the CurveZMQ auth will only
193 # accept public client certificates from the given directory, as
194 # generated by a user when they initiate a ZMQ socket ready to
195 # connect to a server.
196 workflow_srv_dir = workflow_files.get_workflow_srv_dir(
197 self.schd.workflow)
198 client_pub_keyinfo = workflow_files.KeyInfo(
199 workflow_files.KeyType.PUBLIC,
200 workflow_files.KeyOwner.CLIENT,
201 workflow_srv_dir=workflow_srv_dir)
202 self.client_pub_key_dir = client_pub_keyinfo.key_path
203
204 # Initial load for the localhost key.
205 self.configure_curve()
206
207 min_, max_ = glbl_cfg().get(['scheduler', 'run hosts', 'ports'])
208 self.replier = WorkflowReplier(self, context=self.zmq_context)
209 self.replier.start(min_, max_)
210 self.publisher = WorkflowPublisher(
211 self.schd.workflow, context=self.zmq_context
212 )
213 self.publisher.start(min_, max_)
214 self.port = self.replier.port
215 self.pub_port = self.publisher.port
216 self.schd.data_store_mgr.delta_workflow_ports()
217
218 # wait for threads to setup socket ports before continuing
219 barrier.wait()
220
221 self.operate()
222
223 def configure_curve(self) -> None:
224 self.curve_auth.configure_curve(
225 domain='*', location=self.client_pub_key_dir
226 )
227
228 async def stop(self, reason: BaseException | str) -> None:
229 """Stop the TCP servers, and clean up authentication.
230
231 This method must be called/awaited from a different thread to the
232 server's self.thread in order to interrupt the self.operate() loop
233 and wait for self.thread to terminate.
234 """
235 if self.thread and self.thread.is_alive():
236 # Tell self.operate() loop to stop:
237 self._waiting_to_stop = True
238 # Wait for the thread to terminate once the loop has stopped:
239 self.thread.join()
240
241 if self.replier:
242 self.replier.stop(stop_loop=False)
243 if self.publisher:
244 await self.publish_queued_items()
245 await self.publisher.publish(
246 (b'shutdown', str(reason).encode('utf-8'))
247 )
248 self.publisher.stop(stop_loop=False)
249 self.publisher = None
250 if self.curve_auth:
251 self.curve_auth.stop() # stop the authentication thread
252 if self.loop and self.loop.is_running():
253 self.loop.stop()
254
255 def operate(self) -> None:
256 """Orchestrate the receive, send, publish of messages."""
257 # Note: this cannot be an async method because the response part
258 # of the listener runs the event loop synchronously
259 # (in graphql schema.execute_async)
260 while not self._waiting_to_stop:
261 # Gather and respond to any requests.
262 self.replier.listener()
263 # Publish all requested/queued.
264 self.loop.run_until_complete(self.publish_queued_items())
265
266 # Yield control to other threads
267 sleep(self.OPERATE_SLEEP_INTERVAL)
268
269 async def publish_queued_items(self) -> None:
270 """Publish all queued items."""
271 while self.publish_queue.qsize():
272 articles = self.publish_queue.get()
273 await self.publisher.publish(*articles)
274
275 def receiver(self, message) -> 'ResponseDict':
276 """Process incoming messages and coordinate response.
277
278 Wrap incoming messages, dispatch them to exposed methods and/or
279 coordinate a publishing stream.
280
281 Args:
282 message (dict): message contents
283 """
284 # TODO: If requested, coordinate publishing response/stream.
285
286 # determine the server method to call
287 try:
288 method = getattr(self, message['command'])
289 args = message['args']
290 if 'meta' in message:
291 args['meta'] = message['meta']
292 except KeyError as exc:
293 # malformed message
294 return {
295 'error': {
296 'message': (
297 f"Request missing field {exc} required for "
298 f"Cylc {CYLC_VERSION}"
299 )
300 },
301 'cylc_version': CYLC_VERSION,
302 }
303 except AttributeError:
304 # no exposed method by that name
305 return {
306 'error': {
307 'message': (
308 f"No method by the name '{message['command']}' "
309 f"at Cylc {CYLC_VERSION}"
310 )
311 },
312 'cylc_version': CYLC_VERSION,
313 }
314
315 # generate response
316 try:
317 data = method(**args)
318 except Exception as exc:
319 # includes incorrect arguments (TypeError)
320 LOG.exception(exc) # log the error server side
321 return {
322 'error': {'message': str(exc)},
323 'cylc_version': CYLC_VERSION,
324 }
325
326 return {
327 'data': data,
328 'cylc_version': CYLC_VERSION,
329 }
330
331 def register_endpoints(self):
332 """Register all exposed methods."""
333 self.endpoints = {name: obj
334 for name, obj in self.__class__.__dict__.items()
335 if hasattr(obj, 'exposed')}
336
337 @expose
338 def api(
339 self,
340 endpoint: Optional[str] = None,
341 **_kwargs
342 ) -> Union[str, List[str]]:
343 """Return information about this API.
344
345 Returns a list of callable endpoints.
346
347 Args:
348 endpoint:
349 If specified the documentation for the endpoint
350 will be returned instead.
351
352 Returns:
353 List of endpoints or string documentation of the
354 requested endpoint.
355
356 """
357 if not endpoint:
358 return [
359 method for method in dir(self)
360 if getattr(getattr(self, method), 'exposed', False)
361 ]
362
363 try:
364 method = getattr(self, endpoint)
365 except AttributeError:
366 return 'No method by name "%s"' % endpoint
367 if method.exposed:
368 head, tail = method.__doc__.split('\n', 1)
369 tail = dedent(tail)
370 return '%s\n%s' % (head, tail)
371 return 'No method by name "%s"' % endpoint
372
373 @expose
374 def graphql(
375 self,
376 request_string: Optional[str] = None,
377 variables: Optional[Dict[str, Any]] = None,
378 meta: Optional[Dict[str, Any]] = None
379 ):
380 """Return the data field of the GraphQL schema execution result.
381
382 Args:
383 request_string: GraphQL request passed to Graphene.
384 variables: Dict of variables passed to Graphene.
385 meta: Dict containing auth user etc.
386
387 Returns:
388 object: Execution result, or a list with errors.
389 """
390 executed = self.loop.run_until_complete(
391 schema.execute_async(
392 request_string,
393 variable_values=variables,
394 context_value={
395 'resolvers': self.resolvers,
396 'meta': meta or {},
397 },
398 middleware=list(instantiate_middleware(self.middleware)),
399 execution_context_class=CylcExecutionContext,
400 )
401 )
402 if executed.errors:
403 for error in executed.errors:
404 LOG.warning(f"GraphQL: {error}")
405 # If there are execution errors, it means there was an unexpected
406 # error, so fail the command.
407 raise Exception(*(error.message for error in executed.errors))
408 return executed.data
409
410 # UIServer Data Commands
411 @expose
412 def pb_entire_workflow(self, **_kwargs) -> bytes:
413 """Send the entire data-store in a single Protobuf message.
414
415 Returns serialised Protobuf message
416
417 """
418 pb_msg = self.schd.data_store_mgr.get_entire_workflow()
419 return pb_msg.SerializeToString()
420
421 @expose
422 def pb_data_elements(self, element_type: str, **_kwargs) -> bytes:
423 """Send the specified data elements in delta form.
424
425 Args:
426 element_type: Key from DELTAS_MAP dictionary.
427
428 Returns serialised Protobuf message
429
430 """
431 pb_msg = self.schd.data_store_mgr.get_data_elements(element_type)
432 return pb_msg.SerializeToString()