Retry transient camera publisher failures

This commit is contained in:
Andrei Smaliak 2026-11-08 08:22:31 +01:00
parent 79204c3502
commit d2f96225cb
10 changed files with 97 additions and 11 deletions

View File

@ -0,0 +1,6 @@
# Console 3.1.41 — camera stream cleanup
- Add the authenticated camera-stream stop operation used by AITS when CDN readiness cannot be confirmed.
- Retain synchronized runtime, frontend, asset and stage version metadata.
Validation: the complete Console suite and camera streaming contract tests pass.

View File

@ -0,0 +1,9 @@
# IP Camera Streaming 1.0.10
Release date: 2026-11-08.
- Retry a failed forwarding FFmpeg process up to two times while its requested TTL remains active.
- Preserve the last sanitized FFmpeg failure in local status and systemd logs for field diagnostics.
- Report retry count without exposing RTSP credentials or SRT publication tokens.
Validation: reproduced the intermittent SRT `Input/output error` on `g-box-c453df5f`; unit coverage verifies bounded restart, expiry and secret redaction.

View File

@ -14,7 +14,7 @@
"version": "1.0.1" "version": "1.0.1"
}, },
"stage_ui": { "stage_ui": {
"version": "3.1.40" "version": "3.1.41"
}, },
"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.9" "version": "1.0.10"
} }
} }
} }

View File

@ -24,6 +24,7 @@ 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 STARTUP_GUARD_SEC = 0.75
MAX_FORWARD_RESTARTS = 2
FFMPEG_BINARY = "/usr/bin/ffmpeg" FFMPEG_BINARY = "/usr/bin/ffmpeg"
FFPROBE_BINARY = "/usr/bin/ffprobe" FFPROBE_BINARY = "/usr/bin/ffprobe"
@ -108,6 +109,7 @@ class StreamManager:
self.operation_lock = threading.RLock() self.operation_lock = threading.RLock()
self.control_socket = None self.control_socket = None
self.supervisor_stop = threading.Event() self.supervisor_stop = threading.Event()
self.last_failure = None
def publish(self, payload): def publish(self, payload):
subprocess.run([ subprocess.run([
@ -128,7 +130,17 @@ class StreamManager:
code = process.poll() code = process.poll()
if code is None: if code is None:
continue continue
stopped.append({"stream_id": stream_id, "exit_code": code}) error = self.read_error_log(record)
stopped.append({"stream_id": stream_id, "exit_code": code, "error": error})
self.remember_failure(stream_id, code, error)
if (record.get("kind") == "forward" and record.get("expires_at", 0) > now
and record.get("restart_count", 0) < MAX_FORWARD_RESTARTS):
self.close_error_log(record)
record["restart_count"] = record.get("restart_count", 0) + 1
record["error_log"] = tempfile.TemporaryFile(mode="w+b")
record["process"] = self.spawn(record["command"], stderr=record["error_log"])
stopped[-1]["restarted"] = True
continue
self.processes.pop(stream_id, None) self.processes.pop(stream_id, None)
self.close_error_log(record) self.close_error_log(record)
self.write_status() self.write_status()
@ -151,11 +163,13 @@ class StreamManager:
stream_id: { stream_id: {
"kind": record.get("kind", "forward"), "kind": record.get("kind", "forward"),
"expires_at": int(record.get("expires_at", 0)), "expires_at": int(record.get("expires_at", 0)),
"restart_count": int(record.get("restart_count", 0)),
} }
for stream_id, record in self.processes.items() for stream_id, record in self.processes.items()
}, },
"active_count": len(self.processes), "active_count": len(self.processes),
"max_streams": MAX_STREAMS, "max_streams": MAX_STREAMS,
"last_failure": self.last_failure,
}), encoding="utf-8") }), encoding="utf-8")
os.replace(temporary, STATUS_PATH) os.replace(temporary, STATUS_PATH)
@ -197,6 +211,8 @@ class StreamManager:
"output_url": output_url, "output_url": output_url,
"low_latency": low_latency, "low_latency": low_latency,
"profile": profile, "profile": profile,
"command": command,
"restart_count": 0,
} }
self.processes[stream_id] = record self.processes[stream_id] = record
deadline = time.monotonic() + STARTUP_GUARD_SEC deadline = time.monotonic() + STARTUP_GUARD_SEC
@ -205,6 +221,7 @@ class StreamManager:
if process.poll() is not None: if process.poll() is not None:
self.processes.pop(stream_id, None) self.processes.pop(stream_id, None)
error = self.read_error_log(record) error = self.read_error_log(record)
self.remember_failure(stream_id, process.returncode, error)
self.close_error_log(record) self.close_error_log(record)
self.write_status() self.write_status()
message = f"Camera stream process exited during startup (code {process.returncode})" message = f"Camera stream process exited during startup (code {process.returncode})"
@ -244,6 +261,15 @@ class StreamManager:
except OSError: except OSError:
pass pass
def remember_failure(self, stream_id, exit_code, error):
self.last_failure = {
"stream_id": stream_id,
"exit_code": exit_code,
"error": error,
"at": int(time.time()),
}
print(json.dumps({"event": "camera_stream_process_failed", **self.last_failure}, separators=(",", ":")), flush=True)
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

View File

@ -148,6 +148,8 @@ class IpStreamTest(unittest.TestCase):
source = console.read_text(encoding="utf-8") source = console.read_text(encoding="utf-8")
self.assertIn('error = str(result.get("error") or "").strip()', source) self.assertIn('error = str(result.get("error") or "").strip()', source)
self.assertIn('raise RuntimeError(error or "Unable to start camera media operation")', source) self.assertIn('raise RuntimeError(error or "Unable to start camera media operation")', source)
self.assertIn('if parsed.path == "/api/camera-stream/stop":', source)
self.assertIn('publish_camera_preview({"action": "stop", "stream_id": stream_id})', 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")
@ -158,7 +160,7 @@ class IpStreamTest(unittest.TestCase):
dead.poll.return_value = 7 dead.poll.return_value = 7
manager.processes = { manager.processes = {
"expired": {"process": expired, "kind": "forward", "expires_at": 1}, "expired": {"process": expired, "kind": "forward", "expires_at": 1},
"dead": {"process": dead, "kind": "forward", "expires_at": 0}, "dead": {"process": dead, "kind": "preview", "expires_at": 0},
} }
manager.write_status = MagicMock() manager.write_status = MagicMock()
@ -167,8 +169,39 @@ class IpStreamTest(unittest.TestCase):
self.assertEqual(manager.processes, {}) self.assertEqual(manager.processes, {})
self.assertEqual({item["stream_id"] for item in stopped}, {"expired", "dead"}) self.assertEqual({item["stream_id"] for item in stopped}, {"expired", "dead"})
self.assertEqual(manager.last_failure["stream_id"], "dead")
self.assertEqual(manager.last_failure["exit_code"], 7)
killpg.assert_called_once_with(1001, stream.signal.SIGTERM) killpg.assert_called_once_with(1001, stream.signal.SIGTERM)
def test_supervisor_restarts_a_failed_forward_within_its_ttl(self):
manager = stream.StreamManager("g-box-test", "it-screen/dev")
dead = MagicMock(pid=1002)
dead.poll.return_value = 1
replacement = MagicMock(pid=1003)
replacement.poll.return_value = None
error_log = tempfile.TemporaryFile(mode="w+b")
error_log.write(b"srt://cdn.example:8891?streamid=secret Input/output error")
manager.processes = {
"camera": {
"process": dead,
"error_log": error_log,
"kind": "forward",
"expires_at": stream.time.time() + 60,
"restart_count": 0,
"command": [stream.FFMPEG_BINARY, "-i", "rtsp://camera/stream2"],
},
}
manager.spawn = MagicMock(return_value=replacement)
manager.write_status = MagicMock()
stopped = manager.reap()
self.assertTrue(stopped[0]["restarted"])
self.assertEqual(manager.processes["camera"]["restart_count"], 1)
self.assertIs(manager.processes["camera"]["process"], replacement)
self.assertNotIn("streamid=secret", manager.last_failure["error"])
manager.close_error_log(manager.processes["camera"])
def test_run_starts_periodic_supervisor(self): def test_run_starts_periodic_supervisor(self):
source = MODULE_PATH.read_text(encoding="utf-8") source = MODULE_PATH.read_text(encoding="utf-8")
self.assertIn('target=self.supervise, name="ip-stream-supervisor"', source) self.assertIn('target=self.supervise, name="ip-stream-supervisor"', source)

View File

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

View File

@ -62,7 +62,7 @@ APP_DIR = "/opt/iomatex-console"
PUBLIC_DIR = os.path.join(APP_DIR, "public") PUBLIC_DIR = os.path.join(APP_DIR, "public")
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d") PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
CONFIG_PATH = "/etc/iomatex/console.json" CONFIG_PATH = "/etc/iomatex/console.json"
UI_VERSION = "V 3.1.40" UI_VERSION = "V 3.1.41"
STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health" STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health"
ZONEINFO_ROOT = "/usr/share/zoneinfo" ZONEINFO_ROOT = "/usr/share/zoneinfo"
@ -3994,6 +3994,18 @@ class Handler(BaseHTTPRequestHandler):
except Exception as exc: except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=503) self.send_json({"ok": False, "error": str(exc)}, code=503)
return return
if parsed.path == "/api/camera-stream/stop":
payload = self.read_json_body()
stream_id = str((payload or {}).get("stream_id", ""))
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,63}", stream_id):
self.send_json({"ok": False, "error": "Invalid camera stream request"}, code=400)
return
try:
publish_camera_preview({"action": "stop", "stream_id": stream_id})
self.send_json({"ok": True, "stream_id": stream_id})
except Exception as exc:
self.send_json({"ok": False, "error": str(exc)}, code=503)
return
if parsed.path == "/api/camera-preview/snapshot": if parsed.path == "/api/camera-preview/snapshot":
payload = self.read_json_body() payload = self.read_json_body()
stream_id = str((payload or {}).get("stream_id", "")) stream_id = str((payload or {}).get("stream_id", ""))

View File

@ -49,7 +49,7 @@
{ mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" }, { mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" },
{ mode: "custom", label: "Custom", host: "" } { mode: "custom", label: "Custom", host: "" }
]; ];
const UI_VERSION = "V 3.1.40"; const UI_VERSION = "V 3.1.41";
const ITSCREEN_LOG_INITIAL_LINES = 50; const ITSCREEN_LOG_INITIAL_LINES = 50;
const ITSCREEN_LOG_BUFFER_LIMIT = 300; const ITSCREEN_LOG_BUFFER_LIMIT = 300;
const ITSCREEN_LOG_BATCH_MS = 250; const ITSCREEN_LOG_BATCH_MS = 250;

View File

@ -23,7 +23,7 @@
} catch (error) {} } catch (error) {}
})(); })();
</script> </script>
<link rel="stylesheet" href="/console.css?v=3.1.40&amp;rev=edge-runtime-profile-1"> <link rel="stylesheet" href="/console.css?v=3.1.41&amp;rev=edge-runtime-profile-1">
</head> </head>
<body> <body>
<main class="shell"> <main class="shell">
@ -109,7 +109,7 @@
</main> </main>
<div id="menuBackdrop" class="menuBackdrop" hidden></div> <div id="menuBackdrop" class="menuBackdrop" hidden></div>
<div id="toastStack" class="toastStack" aria-live="polite" aria-atomic="true"></div> <div id="toastStack" class="toastStack" aria-live="polite" aria-atomic="true"></div>
<script src="/console.i18n.js?v=3.1.40&amp;rev=edge-runtime-profile-1"></script> <script src="/console.i18n.js?v=3.1.41&amp;rev=edge-runtime-profile-1"></script>
<script src="/console.js?v=3.1.40&amp;rev=edge-runtime-profile-1"></script> <script src="/console.js?v=3.1.41&amp;rev=edge-runtime-profile-1"></script>
</body> </body>
</html> </html>

View File

@ -1,3 +1,3 @@
{ {
"version": "3.1.40" "version": "3.1.41"
} }