Repository navigation
Send events asynchronously #758
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
Merged
Merged
Changes from all commits
Commits
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
96 changes: 96 additions & 0 deletions
96
aikido_zen/background_process/aikido_background_process_test.py
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,96 @@ | ||
| import importlib | ||
| import socket | ||
| from multiprocessing import connection | ||
| from types import SimpleNamespace | ||
| from unittest.mock import Mock | ||
|
|
||
| import pytest | ||
|
|
||
| from aikido_zen.background_process.commands import process_incoming_command | ||
| from aikido_zen.background_process.commands.put_event import PutEventReq | ||
|
|
||
|
|
||
| def test_event_is_acknowledged_after_enqueueing(): | ||
| operations = [] | ||
| events = Mock() | ||
| events.put.side_effect = lambda event: operations.append(("queued", event)) | ||
| connection = Mock() | ||
| connection.send.side_effect = lambda value: operations.append(("reply", value)) | ||
| event = {"name": "login.failed"} | ||
|
|
||
| process_incoming_command( | ||
| None, ("PUT_EVENT", PutEventReq(event)), connection, events | ||
| ) | ||
|
|
||
| assert operations == [("queued", event), ("reply", None)] | ||
| connection.send.assert_called_once_with(None) | ||
|
|
||
|
|
||
| def test_event_is_not_acknowledged_when_enqueueing_fails(): | ||
| events = Mock() | ||
| events.put.side_effect = RuntimeError("Queue unavailable") | ||
| connection = Mock() | ||
|
|
||
| with pytest.raises(RuntimeError, match="Queue unavailable"): | ||
| process_incoming_command( | ||
| None, | ||
| ("PUT_EVENT", PutEventReq({"name": "login.failed"})), | ||
| connection, | ||
| events, | ||
| ) | ||
|
|
||
| connection.send.assert_not_called() | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("failure", ["receive", "reply", "command"]) | ||
| def test_receiver_closes_failed_connection_before_accepting_next(monkeypatch, failure): | ||
| background = importlib.import_module( | ||
| "aikido_zen.background_process.aikido_background_process" | ||
| ) | ||
|
|
||
| class ListenerFinished(Exception): | ||
| pass | ||
|
|
||
| failed_socket, failed_client_socket = socket.socketpair() | ||
| next_socket, next_client_socket = socket.socketpair() | ||
| failed = connection.Connection(failed_socket.detach()) | ||
| failed_client = connection.Connection(failed_client_socket.detach()) | ||
| next_peer = connection.Connection(next_socket.detach()) | ||
| next_client = connection.Connection(next_client_socket.detach()) | ||
| accepted = [] | ||
|
|
||
| def accept(): | ||
| if accepted: | ||
| assert accepted[-1].closed | ||
| if len(accepted) == 2: | ||
| raise ListenerFinished | ||
| peer = (failed, next_peer)[len(accepted)] | ||
| accepted.append(peer) | ||
| return peer | ||
|
|
||
| monkeypatch.setattr( | ||
| background.con, | ||
| "Listener", | ||
| lambda *args, **kwargs: SimpleNamespace(accept=accept), | ||
| ) | ||
| monkeypatch.setattr( | ||
| background, | ||
| "Thread", | ||
| lambda *args, **kwargs: SimpleNamespace(start=lambda: None), | ||
| ) | ||
| monkeypatch.setattr(background, "add_exit_handlers", lambda: None) | ||
| monkeypatch.setattr(background, "set_agent_session_id", lambda value: None) | ||
| try: | ||
| if failure != "receive": | ||
| failed_client.send(None if failure == "command" else ("PING", ())) | ||
| failed_client.close() | ||
| next_client.send(("PING", ())) | ||
|
|
||
| with pytest.raises(ListenerFinished): | ||
| background.AikidoBackgroundProcess(("127.0.0.1", 0), b"fixture", "fixture") | ||
|
|
||
| assert next_client.recv() == "Received" | ||
| assert failed.closed and next_peer.closed | ||
| finally: | ||
| for peer in (failed, failed_client, next_peer, next_client): | ||
| peer.close() |
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 |
|---|---|---|
| @@ -1,34 +1,29 @@ | ||
| from aikido_zen.helpers.logging import logger | ||
| from aikido_zen.helpers.ipc.command_types import CommandContext | ||
| from .put_event import PutEventCommand | ||
| from .check_firewall_lists import process_check_firewall_lists | ||
| from .read_property import process_read_property | ||
| from .should_ratelimit import process_should_ratelimit | ||
| from .ping import process_ping | ||
| from .sync_data import process_sync_data | ||
| from . import ( | ||
| check_firewall_lists, | ||
| ping, | ||
| put_event, | ||
| read_property, | ||
| should_ratelimit, | ||
| sync_data, | ||
| ) | ||
|
|
||
| commands_map = { | ||
| "SYNC_DATA": process_sync_data, | ||
| "READ_PROPERTY": process_read_property, | ||
| "SHOULD_RATELIMIT": process_should_ratelimit, | ||
| "PING": process_ping, | ||
| "CHECK_FIREWALL_LISTS": process_check_firewall_lists, | ||
| check_firewall_lists.IDENTIFIER: check_firewall_lists.process, | ||
| ping.IDENTIFIER: ping.process, | ||
| put_event.IDENTIFIER: put_event.process, | ||
| read_property.IDENTIFIER: read_property.process, | ||
| should_ratelimit.IDENTIFIER: should_ratelimit.process, | ||
| sync_data.IDENTIFIER: sync_data.process, | ||
| } | ||
|
|
||
| modern_commands = [PutEventCommand] | ||
|
|
||
|
|
||
| def process_incoming_command(connection_manager, obj, conn, queue): | ||
| inbound_identifier = obj[0] | ||
| inbound_request = obj[1] | ||
| if inbound_identifier in commands_map: | ||
| func = commands_map[inbound_identifier] | ||
| return conn.send(func(connection_manager, inbound_request)) | ||
|
|
||
| for cmd in modern_commands: | ||
| if cmd.identifier() == inbound_identifier: | ||
| cmd.run(CommandContext(connection_manager, queue, conn), inbound_request) | ||
| return None | ||
| return conn.send(func(connection_manager, inbound_request, queue)) | ||
|
|
||
| logger.debug("Command : `%s` not found - did not execute", inbound_identifier) | ||
| return None |
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 |
|---|---|---|
| @@ -1,6 +1,11 @@ | ||
| """exports `process_ping`""" | ||
| from aikido_zen.helpers.ipc.command_types import Payload | ||
|
|
||
| IDENTIFIER = "PING" | ||
|
|
||
| def process_ping(connection_manager, data): | ||
| """when main process quits , or during testing etc""" | ||
|
|
||
| def generate(timeout_in_sec=0.1) -> Payload: | ||
| return Payload(IDENTIFIER, (), timeout_in_sec) | ||
|
|
||
|
|
||
| def process(connection_manager, request, queue): | ||
| return "Received" |
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 |
|---|---|---|
| @@ -1,27 +1,18 @@ | ||
| from aikido_zen.helpers.ipc.command_types import Command, CommandContext, Payload | ||
| from aikido_zen.helpers.ipc.command_types import Payload | ||
|
|
||
| IDENTIFIER = "PUT_EVENT" | ||
|
|
||
| class PutEventReq: | ||
| def __init__(self, event): | ||
| # Event is a dictionary containing data that is going to be reported to core | ||
| # The CloudConnectionManager adds the "agent" field | ||
| self.event = event | ||
|
|
||
| def generate(event, timeout_in_sec=5) -> Payload: | ||
| return Payload(IDENTIFIER, PutEventReq(event), timeout_in_sec) | ||
|
|
||
| class PutEventCommand(Command): | ||
| @classmethod | ||
| def identifier(cls) -> str: | ||
| return "put_event" | ||
|
|
||
| @classmethod | ||
| def returns_data(cls) -> bool: | ||
| return False | ||
| def process(connection_manager, request, queue): | ||
| queue.put(request.event) | ||
|
aikido-autofix[bot] marked this conversation as resolved.
|
||
|
|
||
| @classmethod | ||
| def run(cls, context: CommandContext, request: PutEventReq): | ||
| # Events sent here get put in the event queue so that they are processed in the background | ||
| context.queue.put(request.event) | ||
|
|
||
| @classmethod | ||
| def generate(cls, request) -> Payload: | ||
| return Payload(cls, PutEventReq(request)) | ||
| # IPC uses pickle, so this request class must keep its import path. | ||
| class PutEventReq: | ||
| def __init__(self, event): | ||
| # The CloudConnectionManager adds the "agent" field. | ||
| self.event = event | ||
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.
Uh oh!
There was an error while loading. Please reload this page.