-
Notifications
You must be signed in to change notification settings - Fork 0
Use own kafka callback (drop dependency on bluesky-kafka)
#300
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Tom-Willemsen
wants to merge
3
commits into
main
Choose a base branch
from
use_own_kafka_callback
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,80 @@ | ||
| import logging | ||
| import os | ||
| import socket | ||
| from typing import Any | ||
|
|
||
| import msgpack_numpy | ||
| from bluesky.callbacks import CallbackBase | ||
| from confluent_kafka import Producer | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| DEFAULT_KAFKA_BROKER = "livedata.isis.cclrc.ac.uk:31092" | ||
|
|
||
|
|
||
| def get_kafka_topic_name() -> str: | ||
| """Get the name of the bluesky Kafka topic for this machine.""" | ||
| computer_name = os.environ.get("COMPUTERNAME", socket.gethostname()).upper() | ||
| computer_name = computer_name.upper() | ||
| if computer_name.startswith(("NDX", "NDH")): | ||
| name = computer_name[3:] | ||
| else: | ||
| name = computer_name | ||
|
|
||
| return f"{name}_bluesky" | ||
|
|
||
|
|
||
| class KafkaCallback(CallbackBase): | ||
| """Forward all bluesky documents to Kafka. | ||
|
|
||
| Documents are sent to Kafka encoded using the MsgPack format with | ||
| the ``msgpack_numpy`` extension to allow efficiently encoding arrays. | ||
|
|
||
| .. note:: | ||
|
|
||
| This callback is automatically configured by | ||
| :py:obj:`ibex_bluesky_core.run_engine.get_run_engine`, and does not need | ||
| to be configured manually. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| *, | ||
| bootstrap_servers: list[str] | None = None, | ||
| topic: str | None = None, | ||
| key: str, | ||
| kafka_config: dict[str, Any], | ||
| ) -> None: | ||
| super().__init__() | ||
|
|
||
| self._topic = topic or get_kafka_topic_name() | ||
| self._key = msgpack_numpy.dumps(key) | ||
|
|
||
| if "bootstrap.servers" in kafka_config: | ||
| raise ValueError( | ||
| "Do not specify bootstrap.servers in kafka config, use bootstrap_servers argument." | ||
| ) | ||
|
|
||
| if bootstrap_servers is None: | ||
| bootstrap_servers = [ | ||
| os.environ.get("IBEX_BLUESKY_CORE_KAFKA_BROKER", DEFAULT_KAFKA_BROKER) | ||
| ] | ||
|
|
||
| kafka_config["bootstrap.servers"] = ",".join(bootstrap_servers) | ||
|
|
||
| self._producer = Producer(kafka_config) | ||
|
|
||
| def __call__( | ||
| self, name: str, doc: dict[str, Any], validate: bool = False | ||
| ) -> tuple[str, dict[str, Any]]: | ||
| try: | ||
| data = msgpack_numpy.dumps([name, doc]) | ||
| self._producer.produce(topic=self._topic, key=self._key, value=data) | ||
| except Exception: | ||
| # If we can't produce to kafka, log and carry on. We don't want | ||
| # kafka failures to kill a scan - kafka is currently considered | ||
| # 'non-critical'. | ||
| logger.exception("Failed to publish Kafka message") | ||
rerpha marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| return name, doc | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| import re | ||
| from unittest import mock | ||
|
|
||
| import pytest | ||
|
|
||
| from ibex_bluesky_core.callbacks._kafka import KafkaCallback, get_kafka_topic_name | ||
|
|
||
|
|
||
| def test_get_kafka_topic_name(): | ||
| with mock.patch("ibex_bluesky_core.callbacks._kafka.os.environ.get", return_value="FOO"): | ||
| assert get_kafka_topic_name() == "FOO_bluesky" | ||
|
|
||
| with mock.patch("ibex_bluesky_core.callbacks._kafka.os.environ.get", return_value="NDXBAR"): | ||
| assert get_kafka_topic_name() == "BAR_bluesky" | ||
|
|
||
| with mock.patch("ibex_bluesky_core.callbacks._kafka.os.environ.get", return_value="NDHBAZ"): | ||
| assert get_kafka_topic_name() == "BAZ_bluesky" | ||
|
|
||
|
|
||
| def test_init_kafka_callback_with_duplicate_bootstrap_servers(): | ||
| with pytest.raises( | ||
| ValueError, | ||
| match=re.escape( | ||
| "Do not specify bootstrap.servers in kafka config, use bootstrap_servers argument." | ||
| ), | ||
| ): | ||
| KafkaCallback(bootstrap_servers=["abc"], kafka_config={"bootstrap.servers": "foo"}, key="") | ||
|
|
||
|
|
||
| def test_exceptions_suppressed(): | ||
| cb = KafkaCallback(bootstrap_servers=["abc"], kafka_config={}, key="") | ||
| with mock.patch( | ||
| "ibex_bluesky_core.callbacks._kafka.msgpack_numpy.dumps", side_effect=ValueError | ||
| ): | ||
| cb("start", {}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
just thinking - we don't want to flush here (to make the producer synchronous) but we could flush the producer in a
__del__()function.Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm, I don't think
__del__works as this callback will always be subsribed (so never deleted).We could flush after a stop document. Do you think that's better? Still need to test how that would interact with network loss/broker being down/broker being borked.