Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 141 additions & 0 deletions tests/test_the_test/test_proxy_writer.py
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"
12 changes: 12 additions & 0 deletions utils/_context/containers.py
Original file line number Diff line number Diff line change
Expand Up @@ -780,6 +780,18 @@ def configure(self, *, host_log_folder: str, replay: bool):
# mount mocked responses valid for the entire scenario
self.volumes[tracer_mocks_path] = {"bind": f"/app/logs/{MockedTracerResponse.internal_filename}", "mode": "ro"}

def remove(self):
# Proxy writes flows on a background thread (see utils/proxy/_flow_writer.py). Its response hook
# acknowledges the tracer as soon as a flow is queued, so writes may still be in flight at teardown.
# TestedContainer.remove() calls docker rm --force which sends SIGKILL and skips the proxy's done
# hook, losing queued flows. Pre-stop so docker sends SIGTERM first and the done hook flushes.
if self._container:
try:
self._container.stop(timeout=30)
except APIError as e:
logger.info(f"Fail to stop container {self.name} before remove ({e})")
super().remove()


class MockedBackendContainer(TestedContainer):
"""The mocked backend (utils/mocked_backend), standing in for the Datadog backend in its own container.
Expand Down
119 changes: 119 additions & 0 deletions utils/proxy/_flow_writer.py
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')}")
61 changes: 31 additions & 30 deletions utils/proxy/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
import json
import logging
import os
from typing import Any, cast
import signal
from typing import TYPE_CHECKING, cast
from datetime import datetime, UTC

import zstandard
Expand All @@ -17,11 +18,14 @@
from mitmproxy.flow import Error as FlowError
from mitmproxy.http import HTTPFlow, Request

from ._deserializer import deserialize, Interface
from ._flow_writer import FlowWriter
from .ports import ProxyPorts
from .mocked_response import MOCKED_TRACER_RESPONSES_PATH, MockedTracerResponse
from .utils import logger

if TYPE_CHECKING:
from ._deserializer import Interface

# prevent permission issues on file created by the proxy when the host is linux
os.umask(0)

Expand Down Expand Up @@ -93,13 +97,6 @@ def get_decoded_content(message: http.Message) -> bytes | None:
return message.content


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)


class _RequestLogger:
def __init__(self) -> None:
handler = logging.StreamHandler()
Expand All @@ -121,6 +118,13 @@ def __init__(self) -> None:
self.internal_mocked_tracer_responses = MockedTracerResponse.many_from_file()
"""Tracer mocked responses valid for the entire session, controlled by scenarios"""

self._writer = FlowWriter()
"""Persists flows off the event loop, so a slow disk does not stall the proxy (see _flow_writer.py)"""

def done(self) -> None:
"""Shutdown hook called by mitmproxy: flush the flows still waiting to be written"""
self._writer.close()
Comment thread
estringana marked this conversation as resolved.
Resolved

@staticmethod
def get_error_response(message: bytes) -> http.Response:
logger.error(message)
Expand Down Expand Up @@ -273,29 +277,21 @@ def response(self, flow: HTTPFlow):
},
}

deserialize(
data,
key="request",
content=request_content,
interface=interface,
export_content_files_to=export_content_files_to,
)

if flow.error and flow.error.msg == FlowError.KILLED_MESSAGE:
data["response"] = None
else:
deserialize(
data,
key="response",
content=response_content,
interface=interface,
export_content_files_to=export_content_files_to,
)
response_killed = bool(flow.error and flow.error.msg == FlowError.KILLED_MESSAGE)

# Everything the file needs has been captured from the flow. Deserializing and writing (which may also
# export multipart files) happen on the writer thread, so the client gets its response right away
# even if the disk is slow.
logger.info(f"Flow {flow.id}: Saving as {log_filename}")

with open(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)
self._writer.submit(
flow.id,
data,
interface,
request_content,
response_content,
export_content_files_to,
response_killed=response_killed,
)

def _modify_response(self, flow: HTTPFlow):
if self.request_is_from_tracer(flow.request):
Expand Down Expand Up @@ -337,6 +333,11 @@ def start_proxy() -> None:
proxy.addons.add(_RequestLogger())

async def _run() -> None:
# The proxy runs as PID 1, which ignores SIGTERM without a handler: `docker stop` would end with a
# SIGKILL, losing the flows still queued on the writer thread. Shut down gracefully instead, so that
# the addons' done hook runs and flushes them.
asyncio.get_running_loop().add_signal_handler(signal.SIGTERM, proxy.shutdown)

await _start_udp_forwarder(
listen_host=listen_host,
listen_port=ProxyPorts.dogstatsd_weblog,
Expand Down
Loading