Diagnose camera stream startup failures

This commit is contained in:
Andrei Smaliak 2026-11-08 08:08:44 +01:00
parent ee0c719bee
commit 4f1bc5fe91
8 changed files with 106 additions and 9 deletions

View File

@ -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.

View File

@ -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.

View File

@ -14,7 +14,7 @@
"version": "1.0.1" "version": "1.0.1"
}, },
"stage_ui": { "stage_ui": {
"version": "3.1.38" "version": "3.1.39"
}, },
"stage_avahi": { "stage_avahi": {
"version": "1.0.0" "version": "1.0.0"
@ -31,7 +31,7 @@
}, },
"optional_stages": { "optional_stages": {
"stage_ip_stream": { "stage_ip_stream": {
"version": "1.0.8" "version": "1.0.9"
} }
} }
} }

View File

@ -7,6 +7,7 @@ import signal
import socket import socket
import subprocess import subprocess
import shutil import shutil
import tempfile
import threading import threading
import time import time
from pathlib import Path from pathlib import Path
@ -22,6 +23,7 @@ SUPPORTED_INPUT_SCHEMES = {"rtsp"}
SUPPORTED_OUTPUT_SCHEMES = {"rtsp", "rtmp", "srt", "udp"} SUPPORTED_OUTPUT_SCHEMES = {"rtsp", "rtmp", "srt", "udp"}
MAX_STREAMS = 8 MAX_STREAMS = 8
PREVIEW_TTL_SEC = 10 * 60 PREVIEW_TTL_SEC = 10 * 60
STARTUP_GUARD_SEC = 0.75
FFMPEG_BINARY = "/usr/bin/ffmpeg" FFMPEG_BINARY = "/usr/bin/ffmpeg"
FFPROBE_BINARY = "/usr/bin/ffprobe" 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: class StreamManager:
def __init__(self, device=None, prefix=None): def __init__(self, device=None, prefix=None):
self.device = device or edge_id() self.device = device or edge_id()
@ -122,6 +130,7 @@ class StreamManager:
continue continue
stopped.append({"stream_id": stream_id, "exit_code": code}) stopped.append({"stream_id": stream_id, "exit_code": code})
self.processes.pop(stream_id, None) self.processes.pop(stream_id, None)
self.close_error_log(record)
self.write_status() self.write_status()
return stopped return stopped
@ -177,8 +186,11 @@ class StreamManager:
"-application", "lowdelay", "-frame_duration", "20", "-application", "lowdelay", "-frame_duration", "20",
*output_arguments(output_url), *output_arguments(output_url),
] ]
self.processes[stream_id] = { error_log = tempfile.TemporaryFile(mode="w+b")
"process": self.spawn(command), process = self.spawn(command, stderr=error_log)
record = {
"process": process,
"error_log": error_log,
"kind": "forward", "kind": "forward",
"expires_at": expires_at, "expires_at": expires_at,
"input_url": input_url, "input_url": input_url,
@ -186,18 +198,52 @@ class StreamManager:
"low_latency": low_latency, "low_latency": low_latency,
"profile": profile, "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() self.write_status()
return {"action": "start", "status": "ok", "stream_id": stream_id, "already_running": False} 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( return subprocess.Popen(
command, command,
stdin=subprocess.DEVNULL, stdin=subprocess.DEVNULL,
stdout=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL, stderr=stderr,
start_new_session=True, 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): def preview_start(self, payload):
stream_id = validate_stream_id(payload.get("stream_id")) stream_id = validate_stream_id(payload.get("stream_id"))
expires_at = time.time() + PREVIEW_TTL_SEC expires_at = time.time() + PREVIEW_TTL_SEC
@ -333,6 +379,8 @@ class StreamManager:
except subprocess.TimeoutExpired: except subprocess.TimeoutExpired:
os.killpg(process.pid, signal.SIGKILL) os.killpg(process.pid, signal.SIGKILL)
process.wait(timeout=2) process.wait(timeout=2)
if record is not None:
self.close_error_log(record)
self.write_status() self.write_status()
return {"action": "stop", "status": "ok", "stream_id": stream_id} return {"action": "stop", "status": "ok", "stream_id": stream_id}

View File

@ -92,6 +92,7 @@ class IpStreamTest(unittest.TestCase):
self.assertEqual(command[command.index("-c:a") + 1], "libopus") self.assertEqual(command[command.index("-c:a") + 1], "libopus")
self.assertEqual(command[command.index("-application") + 1], "lowdelay") self.assertEqual(command[command.index("-application") + 1], "lowdelay")
self.assertNotIn(payload["output_url"], json.dumps(manager.status())) 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): def test_forward_low_latency_profile_transcodes_without_b_frames(self):
manager = stream.StreamManager("g-box-test", "it-screen/dev") 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("-profile:v") + 1], "baseline")
self.assertEqual(command[command.index("-g") + 1], "25") self.assertEqual(command[command.index("-g") + 1], "25")
self.assertEqual(command[command.index("-b:v") + 1], "600k") 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): def test_supervisor_reaps_expired_and_dead_processes_without_status_request(self):
manager = stream.StreamManager("g-box-test", "it-screen/dev") manager = stream.StreamManager("g-box-test", "it-screen/dev")

View File

@ -1,3 +1,3 @@
{ {
"version": "1.0.8" "version": "1.0.9"
} }

View File

@ -240,7 +240,8 @@ def publish_camera_preview(payload):
response.extend(chunk) response.extend(chunk)
result = json.loads(response.decode("utf-8")) if response else {} result = json.loads(response.decode("utf-8")) if response else {}
if not isinstance(result, dict) or result.get("status") != "ok": 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 return result

View File

@ -1,3 +1,3 @@
{ {
"version": "3.1.38" "version": "3.1.39"
} }