From 4f1bc5fe91f32d8b6dd8263566d9ec43277fadca Mon Sep 17 00:00:00 2001 From: Andrei Smaliak Date: Sun, 8 Nov 2026 08:08:44 +0100 Subject: [PATCH] Diagnose camera stream startup failures --- docs/releases/console-3.1.39.md | 6 +++ docs/releases/ip-stream-1.0.9.md | 9 +++++ stage-releases.json | 4 +- stage_ip_stream/ip-stream.py | 56 ++++++++++++++++++++++++++-- stage_ip_stream/test_ip_stream.py | 33 ++++++++++++++++ stage_ip_stream/version.json | 2 +- stage_ui/console_core/backend/app.py | 3 +- stage_ui/version.json | 2 +- 8 files changed, 106 insertions(+), 9 deletions(-) create mode 100644 docs/releases/console-3.1.39.md create mode 100644 docs/releases/ip-stream-1.0.9.md diff --git a/docs/releases/console-3.1.39.md b/docs/releases/console-3.1.39.md new file mode 100644 index 0000000..c3f9403 --- /dev/null +++ b/docs/releases/console-3.1.39.md @@ -0,0 +1,6 @@ +# Console 3.1.39 — camera stream startup diagnostics + +- Preserve the sanitized error returned by the IP Camera Streaming service instead of replacing every startup failure with a generic message. +- Keep the existing local control socket and camera-preview API contracts unchanged. + +Validation: contract coverage verifies that safe service errors reach the camera gateway response. diff --git a/docs/releases/ip-stream-1.0.9.md b/docs/releases/ip-stream-1.0.9.md new file mode 100644 index 0000000..a6cd8fc --- /dev/null +++ b/docs/releases/ip-stream-1.0.9.md @@ -0,0 +1,9 @@ +# IP Camera Streaming 1.0.9 + +Release date: 2026-11-08. + +- Verify that FFmpeg remains alive during the initial stream startup window before reporting success. +- Capture and sanitize early FFmpeg failures so camera credentials and CDN publication tokens never appear in Console responses. +- Close diagnostic handles when a stream stops or is reaped, while retaining the existing forwarding and preview contracts. + +Validation: unit coverage verifies early process failure, secret redaction, lifecycle cleanup and the existing H.264 forwarding profiles. diff --git a/stage-releases.json b/stage-releases.json index 97e503e..e769105 100644 --- a/stage-releases.json +++ b/stage-releases.json @@ -14,7 +14,7 @@ "version": "1.0.1" }, "stage_ui": { - "version": "3.1.38" + "version": "3.1.39" }, "stage_avahi": { "version": "1.0.0" @@ -31,7 +31,7 @@ }, "optional_stages": { "stage_ip_stream": { - "version": "1.0.8" + "version": "1.0.9" } } } diff --git a/stage_ip_stream/ip-stream.py b/stage_ip_stream/ip-stream.py index c00d969..677b175 100644 --- a/stage_ip_stream/ip-stream.py +++ b/stage_ip_stream/ip-stream.py @@ -7,6 +7,7 @@ import signal import socket import subprocess import shutil +import tempfile import threading import time from pathlib import Path @@ -22,6 +23,7 @@ SUPPORTED_INPUT_SCHEMES = {"rtsp"} SUPPORTED_OUTPUT_SCHEMES = {"rtsp", "rtmp", "srt", "udp"} MAX_STREAMS = 8 PREVIEW_TTL_SEC = 10 * 60 +STARTUP_GUARD_SEC = 0.75 FFMPEG_BINARY = "/usr/bin/ffmpeg" FFPROBE_BINARY = "/usr/bin/ffprobe" @@ -88,6 +90,12 @@ def video_arguments(payload): ] +def sanitize_process_error(value): + value = re.sub(r"([a-z][a-z0-9+.-]*://)[^/@\s]+@", r"\1[redacted]@", str(value or ""), flags=re.I) + value = re.sub(r"(srt://[^?\s]+)\?[^\s]+", r"\1?[redacted]", value, flags=re.I) + return value.strip()[-2048:] + + class StreamManager: def __init__(self, device=None, prefix=None): self.device = device or edge_id() @@ -122,6 +130,7 @@ class StreamManager: continue stopped.append({"stream_id": stream_id, "exit_code": code}) self.processes.pop(stream_id, None) + self.close_error_log(record) self.write_status() return stopped @@ -177,8 +186,11 @@ class StreamManager: "-application", "lowdelay", "-frame_duration", "20", *output_arguments(output_url), ] - self.processes[stream_id] = { - "process": self.spawn(command), + error_log = tempfile.TemporaryFile(mode="w+b") + process = self.spawn(command, stderr=error_log) + record = { + "process": process, + "error_log": error_log, "kind": "forward", "expires_at": expires_at, "input_url": input_url, @@ -186,18 +198,52 @@ class StreamManager: "low_latency": low_latency, "profile": profile, } + self.processes[stream_id] = record + deadline = time.monotonic() + STARTUP_GUARD_SEC + while process.poll() is None and time.monotonic() < deadline: + time.sleep(0.05) + if process.poll() is not None: + self.processes.pop(stream_id, None) + error = self.read_error_log(record) + self.close_error_log(record) + self.write_status() + message = f"Camera stream process exited during startup (code {process.returncode})" + if error: + message += f": {error}" + raise RuntimeError(message) self.write_status() return {"action": "start", "status": "ok", "stream_id": stream_id, "already_running": False} - def spawn(self, command): + def spawn(self, command, stderr=subprocess.DEVNULL): return subprocess.Popen( command, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, - stderr=subprocess.DEVNULL, + stderr=stderr, start_new_session=True, ) + @staticmethod + def read_error_log(record): + error_log = record.get("error_log") + if error_log is None: + return "" + try: + error_log.flush() + error_log.seek(0) + return sanitize_process_error(error_log.read().decode("utf-8", errors="replace")) + except (OSError, ValueError): + return "" + + @staticmethod + def close_error_log(record): + error_log = record.pop("error_log", None) + if error_log is not None: + try: + error_log.close() + except OSError: + pass + def preview_start(self, payload): stream_id = validate_stream_id(payload.get("stream_id")) expires_at = time.time() + PREVIEW_TTL_SEC @@ -333,6 +379,8 @@ class StreamManager: except subprocess.TimeoutExpired: os.killpg(process.pid, signal.SIGKILL) process.wait(timeout=2) + if record is not None: + self.close_error_log(record) self.write_status() return {"action": "stop", "status": "ok", "stream_id": stream_id} diff --git a/stage_ip_stream/test_ip_stream.py b/stage_ip_stream/test_ip_stream.py index 1a8c34d..98179d2 100644 --- a/stage_ip_stream/test_ip_stream.py +++ b/stage_ip_stream/test_ip_stream.py @@ -92,6 +92,7 @@ class IpStreamTest(unittest.TestCase): self.assertEqual(command[command.index("-c:a") + 1], "libopus") self.assertEqual(command[command.index("-application") + 1], "lowdelay") self.assertNotIn(payload["output_url"], json.dumps(manager.status())) + manager.close_error_log(manager.processes["cdn-camera-a1b2"]) def test_forward_low_latency_profile_transcodes_without_b_frames(self): manager = stream.StreamManager("g-box-test", "it-screen/dev") @@ -115,6 +116,38 @@ class IpStreamTest(unittest.TestCase): self.assertEqual(command[command.index("-profile:v") + 1], "baseline") self.assertEqual(command[command.index("-g") + 1], "25") self.assertEqual(command[command.index("-b:v") + 1], "600k") + manager.close_error_log(manager.processes["cdn-camera-a1b2"]) + + def test_forward_rejects_an_ffmpeg_process_that_exits_during_startup(self): + manager = stream.StreamManager("g-box-test", "it-screen/dev") + process = MagicMock(returncode=1) + process.poll.return_value = 1 + manager.spawn = MagicMock(return_value=process) + manager.write_status = MagicMock() + + def write_error(command, stderr=stream.subprocess.DEVNULL): + stderr.write(b"Failed to open rtsp://camera-user:camera-password@camera.local/stream2\n") + stderr.flush() + return process + + manager.spawn.side_effect = write_error + with self.assertRaisesRegex(RuntimeError, "Camera stream process exited during startup") as error: + manager.start({ + "stream_id": "cdn-camera-a1b2", + "input_url": "rtsp://camera-user:camera-password@camera.local/stream2", + "output_url": "srt://cdn.dev.iomatex.com:8890?streamid=publish:edge/device/camera:user:secret", + "ttl_sec": 600, + }) + + self.assertNotIn("camera-password", str(error.exception)) + self.assertNotIn("user:secret", str(error.exception)) + self.assertEqual(manager.processes, {}) + + def test_console_returns_the_sanitized_stream_service_error(self): + console = MODULE_PATH.parents[1] / "stage_ui" / "console_core" / "backend" / "app.py" + source = console.read_text(encoding="utf-8") + self.assertIn('error = str(result.get("error") or "").strip()', source) + self.assertIn('raise RuntimeError(error or "Unable to start camera media operation")', source) def test_supervisor_reaps_expired_and_dead_processes_without_status_request(self): manager = stream.StreamManager("g-box-test", "it-screen/dev") diff --git a/stage_ip_stream/version.json b/stage_ip_stream/version.json index 0852922..5d945d2 100644 --- a/stage_ip_stream/version.json +++ b/stage_ip_stream/version.json @@ -1,3 +1,3 @@ { - "version": "1.0.8" + "version": "1.0.9" } diff --git a/stage_ui/console_core/backend/app.py b/stage_ui/console_core/backend/app.py index 996039a..14b0605 100644 --- a/stage_ui/console_core/backend/app.py +++ b/stage_ui/console_core/backend/app.py @@ -240,7 +240,8 @@ def publish_camera_preview(payload): response.extend(chunk) result = json.loads(response.decode("utf-8")) if response else {} if not isinstance(result, dict) or result.get("status") != "ok": - raise RuntimeError("Unable to start camera media operation") + error = str(result.get("error") or "").strip() if isinstance(result, dict) else "" + raise RuntimeError(error or "Unable to start camera media operation") return result diff --git a/stage_ui/version.json b/stage_ui/version.json index 94bc735..9c8cd58 100644 --- a/stage_ui/version.json +++ b/stage_ui/version.json @@ -1,3 +1,3 @@ { - "version": "3.1.38" + "version": "3.1.39" }