| 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 |
from queue import Queue |
| 19 |
from typing import ( |
| 20 |
TYPE_CHECKING, |
| 21 |
Optional, |
| 22 |
) |
| 23 |
|
| 24 |
import zmq |
| 25 |
|
| 26 |
from cylc.flow import ( |
| 27 |
LOG, |
| 28 |
__version__ as CYLC_VERSION, |
| 29 |
) |
| 30 |
from cylc.flow.network import ( |
| 31 |
ZMQSocketBase, |
| 32 |
deserialize, |
| 33 |
serialize, |
| 34 |
) |
| 35 |
|
| 36 |
|
| 37 |
if TYPE_CHECKING: |
| 38 |
from cylc.flow.network import ResponseDict |
| 39 |
from cylc.flow.network.server import WorkflowRuntimeServer |
| 40 |
from zmq.asyncio import Context |
| 41 |
|
| 42 |
|
| 43 |
class WorkflowReplier(ZMQSocketBase): |
| 44 |
"""Initiate the REP part of a ZMQ REQ-REP pattern. |
| 45 |
|
| 46 |
This class contains the logic for the ZMQ message replier. The REQ/REP |
| 47 |
pattern is serial, in that it cannot REQ or REP twice in a row. After |
| 48 |
receiving you must send a response. |
| 49 |
|
| 50 |
Usage: |
| 51 |
* Start the replier. |
| 52 |
* Call the listener to process incoming REQ and send the REP. |
| 53 |
|
| 54 |
Message Processing: |
| 55 |
* Calls the server's receiver to process the command and |
| 56 |
obtain a response. |
| 57 |
|
| 58 |
Message interface: |
| 59 |
* Expects requests of the format: {"command": CMD, "args": {...}} |
| 60 |
* Sends responses of the format: {"data": {...}} |
| 61 |
* Sends errors in the format: {"error": {"message": MSG}} |
| 62 |
|
| 63 |
""" |
| 64 |
|
| 65 |
def __init__( |
| 66 |
self, |
| 67 |
server: 'WorkflowRuntimeServer', |
| 68 |
context: 'Optional[Context]' = None |
| 69 |
): |
| 70 |
super().__init__( |
| 71 |
zmq.REP, server.schd.workflow, bind=True, context=context |
| 72 |
) |
| 73 |
self.server = server |
| 74 |
self.queue: 'Queue[str]' = Queue() |
| 75 |
|
| 76 |
def _bespoke_stop(self) -> None: |
| 77 |
"""Stop the listener and Authenticator. |
| 78 |
|
| 79 |
Overwrites Base method. |
| 80 |
|
| 81 |
""" |
| 82 |
LOG.debug('stopping zmq replier...') |
| 83 |
self.queue.put('STOP') |
| 84 |
|
| 85 |
def listener(self) -> None: |
| 86 |
"""The server main loop, listen for and serve requests. |
| 87 |
|
| 88 |
When called, this method will receive and respond until there are no |
| 89 |
more messages then break to the caller. |
| 90 |
|
| 91 |
""" |
| 92 |
# Note: we are using CurveZMQ to secure the messages (see |
| 93 |
# self.curve_auth, self.socket.curve_...key etc.). We have set up |
| 94 |
# public-key cryptography on the ZMQ messaging and sockets, so |
| 95 |
# there is no need to encrypt messages ourselves before sending. |
| 96 |
while True: |
| 97 |
# process any commands passed to the listener by its parent process |
| 98 |
if self.queue.qsize(): |
| 99 |
command = self.queue.get() |
| 100 |
if command == 'STOP': |
| 101 |
break |
| 102 |
raise ValueError('Unknown command "%s"' % command) |
| 103 |
|
| 104 |
try: |
| 105 |
# Check for messages |
| 106 |
msg = self.socket.recv_string( # type: ignore[union-attr] |
| 107 |
zmq.NOBLOCK |
| 108 |
) |
| 109 |
except zmq.error.Again: |
| 110 |
# No messages, break to parent loop/caller. |
| 111 |
break |
| 112 |
except zmq.error.ZMQError as exc: |
| 113 |
LOG.exception('unexpected error: %s', exc) |
| 114 |
continue |
| 115 |
# attempt to decode the message, authenticating the user in the |
| 116 |
# process |
| 117 |
res: ResponseDict |
| 118 |
response: bytes |
| 119 |
try: |
| 120 |
message = deserialize(msg) |
| 121 |
except Exception as exc: # purposefully catch generic exception |
| 122 |
# failed to decode message, possibly resulting from failed |
| 123 |
# authentication |
| 124 |
LOG.exception(exc) |
| 125 |
LOG.error(f'failed to decode message: "{msg}"') |
| 126 |
res = { |
| 127 |
'error': {'message': str(exc)}, |
| 128 |
'cylc_version': CYLC_VERSION, |
| 129 |
} |
| 130 |
response = serialize(res).encode() |
| 131 |
else: |
| 132 |
# success case - serve the request |
| 133 |
res = self.server.receiver(message) |
| 134 |
data = res.get('data') |
| 135 |
# send back the string to bytes response |
| 136 |
if isinstance(data, bytes): |
| 137 |
response = data |
| 138 |
else: |
| 139 |
response = serialize(res).encode() |
| 140 |
self.socket.send(response) # type: ignore[union-attr] |