Repository navigation
Persist proxy flows off the event loop #8492
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
Show all changes
13 commits
Select commit
Hold shift + click to select a range
689bb62
Persist proxy flows off the event loop
estringana 5af4989
Merge branch 'main' into estringana/proxy-async-flow-writer
estringana 6f6f51d
Merge branch 'main' into estringana/proxy-async-flow-writer
cbeauchesne a283947
Merge branch 'main' into estringana/proxy-async-flow-writer
estringana 87457f4
Merge branch 'main' into estringana/proxy-async-flow-writer
cbeauchesne 4fc94a9
Merge branch 'main' into estringana/proxy-async-flow-writer
estringana 5d07c6b
Merge branch 'main' into estringana/proxy-async-flow-writer
estringana 4942ed2
Merge branch 'main' into estringana/proxy-async-flow-writer
estringana 729c7ec
Merge branch 'main' into estringana/proxy-async-flow-writer
cbeauchesne 154ec91
Merge branch 'main' into estringana/proxy-async-flow-writer
estringana 7894b98
Merge branch 'main' into estringana/proxy-async-flow-writer
estringana dd2a76f
Merge branch 'main' into estringana/proxy-async-flow-writer
estringana 1ee5c6e
Merge branch 'main' into estringana/proxy-async-flow-writer
estringana 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,141 @@ | ||
| """The proxy must keep serving flows while the disk is slow (APPSEC-71652). | ||
|
|
||
| mitmproxy only sends a response to the client once the response hook returns. When that hook wrote the flow | ||
| file synchronously, a ~14s I/O stall on a CI runner froze the whole proxy, the PHP sidecar's trace submission | ||
| timed out, and the trace never reached the test. | ||
| """ | ||
|
|
||
| from collections.abc import Iterator | ||
| import json | ||
| from pathlib import Path | ||
| import threading | ||
| import time | ||
| from typing import Any | ||
|
|
||
| from utils import pytest, scenarios | ||
| from utils.proxy import _flow_writer | ||
| from utils.proxy._flow_writer import FlowWriter | ||
|
|
||
|
|
||
| @pytest.fixture | ||
| def writer() -> Iterator[FlowWriter]: | ||
| result = FlowWriter() | ||
| try: | ||
| yield result | ||
| finally: | ||
| result.close() | ||
|
|
||
|
|
||
| def _data(folder: Path, name: str, path: str) -> dict[str, Any]: | ||
| return { | ||
| "log_filename": str(folder / name), | ||
| "path": path, | ||
| "query": "", | ||
| "request": {"headers": [("content-type", "application/json")], "length": 0}, | ||
| "response": {"status_code": 200, "headers": [("content-type", "application/json")], "length": 0}, | ||
| } | ||
|
|
||
|
|
||
| def _submit(writer: FlowWriter, folder: Path, name: str, path: str) -> None: | ||
| writer.submit( | ||
| "flow-id", | ||
| _data(folder, name, path), | ||
| "library", | ||
| json.dumps({"path": path}).encode(), | ||
| b'{"ok": true}', | ||
| str(folder / "files"), | ||
| response_killed=False, | ||
| ) | ||
|
|
||
|
|
||
| @scenarios.test_the_test | ||
| def test_submit_does_not_wait_for_the_disk(writer: FlowWriter, tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: | ||
| disk_released = threading.Event() | ||
| original_deserialize = _flow_writer.deserialize | ||
|
|
||
| def stalled_deserialize(*args: Any, **kwargs: Any) -> None: # noqa: ANN401 | ||
| # stands for the slow disk: everything the writer thread does happens after this | ||
| disk_released.wait(timeout=30) | ||
| original_deserialize(*args, **kwargs) | ||
|
|
||
| monkeypatch.setattr(_flow_writer, "deserialize", stalled_deserialize) | ||
|
|
||
| start = time.monotonic() | ||
| _submit(writer, tmp_path, "00000__v0.4_traces.json", "/v0.4/traces") | ||
| _submit(writer, tmp_path, "00001__v0.7_config.json", "/v0.7/config") | ||
| elapsed = time.monotonic() - start | ||
|
|
||
| # the response hook can return, so mitmproxy answers the tracer, while the flows are not on disk yet | ||
| assert elapsed < 1, f"submit blocked for {elapsed:.1f}s on a stalled disk" | ||
| assert not list(tmp_path.glob("*.json")) | ||
|
|
||
| disk_released.set() | ||
| writer.close() # flushes the pending writes, as on proxy shutdown | ||
|
|
||
| assert sorted(p.name for p in tmp_path.glob("*.json")) == ["00000__v0.4_traces.json", "00001__v0.7_config.json"] | ||
|
|
||
| data = json.loads((tmp_path / "00001__v0.7_config.json").read_text()) | ||
| assert data["path"] == "/v0.7/config" | ||
| assert data["request"]["content"] == {"path": "/v0.7/config"} | ||
| assert data["response"]["content"] == {"ok": True} | ||
|
|
||
|
|
||
| @scenarios.test_the_test | ||
| def test_flows_are_written_in_submission_order( | ||
| writer: FlowWriter, tmp_path: Path, monkeypatch: pytest.MonkeyPatch | ||
| ) -> None: | ||
| written: list[str] = [] | ||
| original_persist_flow = _flow_writer.persist_flow | ||
|
|
||
| def recording_persist_flow(data: dict[str, Any], *args: Any, **kwargs: Any) -> None: # noqa: ANN401 | ||
| original_persist_flow(data, *args, **kwargs) | ||
| written.append(Path(data["log_filename"]).name) | ||
|
|
||
| monkeypatch.setattr(_flow_writer, "persist_flow", recording_persist_flow) | ||
|
|
||
| names = [f"{i:05d}__v0.4_traces.json" for i in range(50)] | ||
| for name in names: | ||
| _submit(writer, tmp_path, name, "/v0.4/traces") | ||
| writer.close() | ||
|
|
||
| assert written == names | ||
|
|
||
|
|
||
| @scenarios.test_the_test | ||
| def test_killed_response_is_saved_as_none(writer: FlowWriter, tmp_path: Path) -> None: | ||
| writer.submit( | ||
| "flow-id", | ||
| _data(tmp_path, "00000__v0.4_traces.json", "/v0.4/traces"), | ||
| "library", | ||
| b'{"a": 1}', | ||
| b'{"b": 2}', | ||
| str(tmp_path / "files"), | ||
| response_killed=True, | ||
| ) | ||
| writer.close() | ||
|
|
||
| data = json.loads((tmp_path / "00000__v0.4_traces.json").read_text()) | ||
| assert data["request"]["content"] == {"a": 1} | ||
| assert data["response"] is None | ||
|
|
||
|
|
||
| @scenarios.test_the_test | ||
| def test_failed_write_does_not_stop_the_writer( | ||
| writer: FlowWriter, tmp_path: Path, monkeypatch: pytest.MonkeyPatch | ||
| ) -> None: | ||
| original_dump = json.dump | ||
| calls = {"count": 0} | ||
|
|
||
| def flaky_dump(*args: Any, **kwargs: Any) -> None: # noqa: ANN401 | ||
| calls["count"] += 1 | ||
| if calls["count"] == 1: | ||
| raise OSError("No space left on device") | ||
| original_dump(*args, **kwargs) | ||
|
|
||
| monkeypatch.setattr(_flow_writer.json, "dump", flaky_dump) | ||
|
|
||
| _submit(writer, tmp_path, "00000__v0.7_config.json", "/v0.7/config") | ||
| _submit(writer, tmp_path, "00001__v0.7_config.json", "/v0.7/config") | ||
| writer.close() | ||
|
|
||
| assert json.loads((tmp_path / "00001__v0.7_config.json").read_text())["path"] == "/v0.7/config" |
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,119 @@ | ||
| """Persists the flows seen by the proxy, without blocking its event loop. | ||
|
|
||
| mitmproxy runs every hook on a single event loop, and sends the response to the client only once the response | ||
| hook returns. When that hook wrote the flow file synchronously, a slow disk stalled the whole proxy: during a | ||
| ~14s I/O stall on a CI runner no flow was served, the PHP sidecar's trace submission timed out, and the trace | ||
| was dropped (APPSEC-71652). | ||
|
|
||
| This module does not depend on mitmproxy, so it can be tested from the runner. | ||
| """ | ||
|
|
||
| from concurrent.futures import Future, ThreadPoolExecutor | ||
| import json | ||
| import os | ||
| from typing import Any | ||
|
|
||
| from ._deserializer import deserialize, Interface | ||
| from .utils import logger | ||
|
|
||
|
|
||
| class ObjectDumpEncoder(json.JSONEncoder): | ||
| def default(self, o: Any) -> Any: # noqa: ANN401 | ||
| if isinstance(o, bytes): | ||
| return str(o) | ||
| return json.JSONEncoder.default(self, o) | ||
|
|
||
|
|
||
| def persist_flow( | ||
| data: dict[str, Any], | ||
| interface: Interface, | ||
| request_content: bytes | None, | ||
| response_content: bytes | None, | ||
| export_content_files_to: str, | ||
| *, | ||
| response_killed: bool, | ||
| ) -> None: | ||
| """Deserialize the request and response content into data, and write it to data["log_filename"]""" | ||
|
|
||
| deserialize( | ||
| data, | ||
| key="request", | ||
| content=request_content, | ||
| interface=interface, | ||
| export_content_files_to=export_content_files_to, | ||
| ) | ||
|
|
||
| if response_killed: | ||
| data["response"] = None | ||
| else: | ||
| deserialize( | ||
| data, | ||
| key="response", | ||
| content=response_content, | ||
| interface=interface, | ||
| export_content_files_to=export_content_files_to, | ||
| ) | ||
|
|
||
| with open(data["log_filename"], "w", encoding="utf-8", opener=lambda path, flags: os.open(path, flags, 0o777)) as f: | ||
| json.dump(data, f, indent=2, cls=ObjectDumpEncoder) | ||
|
|
||
|
|
||
| class FlowWriter: | ||
| """Runs persist_flow on a background thread. | ||
|
|
||
| A single worker keeps the files written in the order their numbers were assigned. | ||
| """ | ||
|
|
||
| def __init__(self) -> None: | ||
| self._executor = ThreadPoolExecutor(max_workers=1, thread_name_prefix="proxy-writer") | ||
|
|
||
| def submit( | ||
| self, | ||
| flow_id: str, | ||
| data: dict[str, Any], | ||
| interface: Interface, | ||
| request_content: bytes | None, | ||
| response_content: bytes | None, | ||
| export_content_files_to: str, | ||
| *, | ||
| response_killed: bool, | ||
| ) -> Future[None]: | ||
| """Queue the flow and return immediately. data must not be modified by the caller afterwards""" | ||
| return self._executor.submit( | ||
| self._persist_flow, | ||
| flow_id, | ||
| data, | ||
| interface, | ||
| request_content, | ||
| response_content, | ||
| export_content_files_to, | ||
| response_killed=response_killed, | ||
| ) | ||
|
|
||
| def close(self) -> None: | ||
| """Wait for all queued flows to be written""" | ||
| self._executor.shutdown(wait=True) | ||
|
|
||
| @staticmethod | ||
| def _persist_flow( | ||
| flow_id: str, | ||
| data: dict[str, Any], | ||
| interface: Interface, | ||
| request_content: bytes | None, | ||
| response_content: bytes | None, | ||
| export_content_files_to: str, | ||
| *, | ||
| response_killed: bool, | ||
| ) -> None: | ||
| # the executor would silently keep the exception in a future nobody reads: log it instead | ||
| try: | ||
| persist_flow( | ||
| data, | ||
| interface, | ||
| request_content, | ||
| response_content, | ||
| export_content_files_to, | ||
| response_killed=response_killed, | ||
| ) | ||
| except Exception: | ||
| logger.exception(f"Flow {flow_id}: failed to save {data.get('log_filename')}") |
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.
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.