| 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 |
"""Subscriber for published workflow output.""" |
| 17 |
|
| 18 |
import asyncio |
| 19 |
import json |
| 20 |
import sys |
| 21 |
from typing import TYPE_CHECKING, Iterable, Optional, Set, Union |
| 22 |
|
| 23 |
import zmq |
| 24 |
|
| 25 |
from cylc.flow.network import ZMQSocketBase, get_location |
| 26 |
from cylc.flow.data_store_mgr import DELTAS_MAP |
| 27 |
|
| 28 |
if TYPE_CHECKING: |
| 29 |
import zmq.asyncio |
| 30 |
|
| 31 |
NO_RECEIVE_INTERVAL = 0.5 |
| 32 |
|
| 33 |
|
| 34 |
def process_delta_msg(btopic, delta_msg, func, *args, **kwargs): |
| 35 |
"""Utility for processing serialised data-store deltas.""" |
| 36 |
topic = btopic.decode('utf-8') |
| 37 |
try: |
| 38 |
delta = DELTAS_MAP[topic]() |
| 39 |
delta.ParseFromString(delta_msg) |
| 40 |
except KeyError: |
| 41 |
delta = delta_msg |
| 42 |
if callable(func): |
| 43 |
return func(topic, delta, *args, **kwargs) |
| 44 |
return (topic, delta) |
| 45 |
|
| 46 |
|
| 47 |
class WorkflowSubscriber(ZMQSocketBase): |
| 48 |
"""Initiate the SUB part of a ZMQ PUB-SUB pair. |
| 49 |
|
| 50 |
This class contains the logic for the ZMQ message Subscriber. |
| 51 |
|
| 52 |
NOTE: Security to be provided by zmq.auth |
| 53 |
|
| 54 |
Args: |
| 55 |
host: The host to connect to. |
| 56 |
port: The port on the aforementioned host to connect to. |
| 57 |
|
| 58 |
Usage: |
| 59 |
* Subscribe to Publisher socket using ``WorkflowSubscriber.__call__``. |
| 60 |
|
| 61 |
""" |
| 62 |
# socket & event loop not None - get assigned on init by self.start(): |
| 63 |
socket: 'zmq.asyncio.Socket' |
| 64 |
loop: asyncio.AbstractEventLoop |
| 65 |
|
| 66 |
def __init__( |
| 67 |
self, |
| 68 |
workflow: str, |
| 69 |
host: Optional[str] = None, |
| 70 |
port: Union[int, str, None] = None, |
| 71 |
context: Optional['zmq.asyncio.Context'] = None, |
| 72 |
srv_public_key_loc: Optional[str] = None, |
| 73 |
topics: Optional[Iterable[bytes]] = None |
| 74 |
): |
| 75 |
super().__init__(zmq.SUB, workflow, context=context) |
| 76 |
if port: |
| 77 |
port = int(port) |
| 78 |
if not (host and port): |
| 79 |
host, _, port, _ = get_location(workflow) |
| 80 |
if topics is None: |
| 81 |
topics = {b''} |
| 82 |
self.topics: Set[bytes] = set(topics) |
| 83 |
# Connect the ZMQ socket on instantiation |
| 84 |
self.start(host, port, srv_public_key_loc) |
| 85 |
|
| 86 |
def _socket_options(self) -> None: |
| 87 |
"""Set options after socket instantiation and before connect. |
| 88 |
|
| 89 |
Overwrites Base method. |
| 90 |
|
| 91 |
""" |
| 92 |
# setup topics to receive. |
| 93 |
for topic in self.topics: |
| 94 |
self.socket.setsockopt(zmq.SUBSCRIBE, topic) |
| 95 |
|
| 96 |
async def subscribe(self, msg_handler, *args, **kwargs): |
| 97 |
"""Subscribe to updates from the provided socket.""" |
| 98 |
while True: |
| 99 |
if self.stopping: |
| 100 |
break |
| 101 |
try: |
| 102 |
[topic, msg] = await self.socket.recv_multipart( |
| 103 |
flags=zmq.NOBLOCK) |
| 104 |
except zmq.ZMQError: |
| 105 |
await asyncio.sleep(NO_RECEIVE_INTERVAL) |
| 106 |
continue |
| 107 |
if callable(msg_handler): |
| 108 |
msg_handler(topic, msg, *args, **kwargs) |
| 109 |
else: |
| 110 |
data = json.loads(msg) |
| 111 |
sys.stdout.write( |
| 112 |
json.dumps(data, indent=4) + '\n') |