-
Notifications
You must be signed in to change notification settings - Fork 132
Refactor listen/notify as a pubsub backend #6811
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
Draft
pedro-psb
wants to merge
18
commits into
pulp:main
Choose a base branch
from
pedro-psb:tasking/add-pubsub-interface
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.
Draft
Changes from all commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
04f13cc
Add and test postgres pubsub class implementation
pedro-psb 209b1c1
Refactor listen/notify as a pubsub backend
pedro-psb 45f5ac0
Change PubSub usage and add make use of global connection object
pedro-psb 7aad72d
wip debugging
pedro-psb a7394bd
Wip more debugging
pedro-psb dfc682b
Wip trying a workaround
pedro-psb 20b5e7f
Add inter-process communication tests
pedro-psb 7d3d1eb
New attempt to satisfy both pubsub test and side-effects
pedro-psb 61532fd
Try to turn IpcUtil into a fixture
pedro-psb ea14bc8
Revert "Try to turn IpcUtil into a fixture"
pedro-psb 627c80b
Attempt to fix pytest-django import requirements
pedro-psb 55cbb62
Add better error handling for inter-process comm tests
pedro-psb 9c269ad
Fix wrong test assertion and fix hanging issue
pedro-psb 54ef324
Make pytest-django fixture fix optional
pedro-psb 68720f8
Clean pubsub test and separate ipc utils
pedro-psb a8840c7
More test and test_util cleanup
pedro-psb cecf943
Some adjustments to pubsub module
pedro-psb fd3e32e
Fix linting errors
pedro-psb 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| from typing import NamedTuple | ||
| from pulpcore.constants import TASK_PUBSUB | ||
| import os | ||
| import logging | ||
| import select | ||
| from django.db import connection | ||
| from contextlib import suppress | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
|
|
||
| class BasePubSubBackend: | ||
| # Utils | ||
| @classmethod | ||
| def wakeup_worker(cls, reason="unknown"): | ||
| cls.publish(TASK_PUBSUB.WAKEUP_WORKER, reason) | ||
|
|
||
| @classmethod | ||
| def cancel_task(cls, task_pk): | ||
| cls.publish(TASK_PUBSUB.CANCEL_TASK, str(task_pk)) | ||
|
|
||
| @classmethod | ||
| def record_worker_metrics(cls, now): | ||
| cls.publish(TASK_PUBSUB.WORKER_METRICS, str(now)) | ||
|
|
||
| # Interface | ||
| def subscribe(self, channel): | ||
| raise NotImplementedError() | ||
|
|
||
| def unsubscribe(self, channel): | ||
| raise NotImplementedError() | ||
|
|
||
| def get_subscriptions(self): | ||
| raise NotImplementedError() | ||
|
|
||
| @classmethod | ||
| def publish(cls, channel, payload=None): | ||
| raise NotImplementedError() | ||
|
|
||
| def fileno(self): | ||
| """Add support for being used in select loop.""" | ||
| raise NotImplementedError() | ||
|
|
||
| def fetch(self): | ||
| """Fetch messages new message, if required.""" | ||
| raise NotImplementedError() | ||
|
|
||
| def close(self): | ||
| raise NotImplementedError() | ||
|
|
||
|
|
||
| class PubsubMessage(NamedTuple): | ||
| channel: str | ||
| payload: str | ||
|
|
||
|
|
||
| def drain_non_blocking_fd(fd): | ||
| with suppress(BlockingIOError): | ||
| while True: | ||
| os.read(fd, 256) | ||
|
|
||
|
|
||
| class PostgresPubSub(BasePubSubBackend): | ||
| PID = os.getpid() | ||
|
|
||
| def __init__(self): | ||
| self._subscriptions = set() | ||
| self.message_buffer = [] | ||
| # ensures a connection is initialized | ||
| with connection.cursor() as cursor: | ||
| cursor.execute("select 1") | ||
| self.backend_pid = connection.connection.info.backend_pid | ||
| self.sentinel_r, self.sentinel_w = os.pipe() | ||
| os.set_blocking(self.sentinel_r, False) | ||
| os.set_blocking(self.sentinel_w, False) | ||
| connection.connection.add_notify_handler(self._store_messages) | ||
|
|
||
| @classmethod | ||
| def _debug(cls, message): | ||
| logger.debug(f"[{cls.PID}] {message}") | ||
|
|
||
| def _store_messages(self, notification): | ||
| self.message_buffer.append( | ||
| PubsubMessage(channel=notification.channel, payload=notification.payload) | ||
| ) | ||
| if notification.pid == self.backend_pid: | ||
| os.write(self.sentinel_w, b"1") | ||
| self._debug(f"Received message: {notification}") | ||
|
|
||
| @classmethod | ||
| def publish(cls, channel, payload=""): | ||
| query = ( | ||
| (f"NOTIFY {channel}",) | ||
| if not payload | ||
| else ("SELECT pg_notify(%s, %s)", (channel, str(payload))) | ||
| ) | ||
|
|
||
| with connection.cursor() as cursor: | ||
| cursor.execute(*query) | ||
| cls._debug(f"Sent message: ({channel}, {str(payload)})") | ||
|
|
||
| def subscribe(self, channel): | ||
| self._subscriptions.add(channel) | ||
| with connection.cursor() as cursor: | ||
| cursor.execute(f"LISTEN {channel}") | ||
|
|
||
| def unsubscribe(self, channel): | ||
| self._subscriptions.remove(channel) | ||
| for i in range(0, len(self.message_buffer), -1): | ||
| if self.message_buffer[i].channel == channel: | ||
| self.message_buffer.pop(i) | ||
| with connection.cursor() as cursor: | ||
| cursor.execute(f"UNLISTEN {channel}") | ||
|
|
||
| def get_subscriptions(self): | ||
| return self._subscriptions.copy() | ||
|
|
||
| def fileno(self) -> int: | ||
| # when pub/sub clients are the same, the notification callback may be called | ||
| # asynchronously, making select on connection miss new notifications | ||
| ready, _, _ = select.select([self.sentinel_r], [], [], 0) | ||
| if self.sentinel_r in ready: | ||
| return self.sentinel_r | ||
| return connection.connection.fileno() | ||
|
|
||
| def fetch(self) -> list[PubsubMessage]: | ||
| with connection.cursor() as cursor: | ||
| cursor.execute("SELECT 1").fetchone() | ||
| result = self.message_buffer.copy() | ||
| self.message_buffer.clear() | ||
| drain_non_blocking_fd(self.sentinel_r) | ||
| self._debug(f"Fetched messages: {result}") | ||
| return result | ||
|
|
||
| def close(self): | ||
| self.message_buffer.clear() | ||
| connection.connection.remove_notify_handler(self._store_messages) | ||
| drain_non_blocking_fd(self.sentinel_r) | ||
| os.close(self.sentinel_r) | ||
| os.close(self.sentinel_w) | ||
| for channel in self.get_subscriptions(): | ||
| self.unsubscribe(channel) | ||
|
|
||
| def __enter__(self): | ||
| return self | ||
|
|
||
| def __exit__(self, exc_type, exc_value, traceback): | ||
| self.close() | ||
|
|
||
|
|
||
| backend = PostgresPubSub | ||
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
Oops, something went wrong.
Oops, something went wrong.
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.
Is this really related? I thought this os.pipe was primarily part of the select calls to receive the signals like SIGINT, SIGTERM.
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.
I added this to make the semantics of the PubSub readiness tied to the data it actually stores, which is the
self.message_buffersqueue (not the connection buffer). If I just use connection.connection, test_pubsub:111 fails as the pg_notify_callback is called automatically on same-process connections and is empty at this point.But I don't feel very good about how complex this looks. I think using notifies may make our lives easier