Compare commits
25 Commits
release/de
...
ci-cd
| Author | SHA1 | Date |
|---|---|---|
|
|
aa2d25a44b | |
|
|
9cab662940 | |
|
|
cb8b4d0ecc | |
|
|
743048ec60 | |
|
|
4e58671b32 | |
|
|
8430b8ddda | |
|
|
d2f96225cb | |
|
|
79204c3502 | |
|
|
4f1bc5fe91 | |
|
|
ee0c719bee | |
|
|
16d0e5959a | |
|
|
3edce30416 | |
|
|
d3c815a4c8 | |
|
|
9491a45864 | |
|
|
a07871f4d7 | |
|
|
cdba25924e | |
|
|
798d3f32d4 | |
|
|
25ce3be6b9 | |
|
|
3e209a492b | |
|
|
2050f141e3 | |
|
|
73fdd0aaee | |
|
|
52e43b9476 | |
|
|
54ea6e3133 | |
|
|
dd52cbe9a3 | |
|
|
1d10037325 |
|
|
@ -635,3 +635,26 @@ journalctl -u iomatex-rt-webui.service -n 80 --no-pager
|
|||
- надо переустановить только одну часть Edge;
|
||||
- надо решить, можно ли ставить стадию поверх уже рабочего устройства;
|
||||
- надо подробно разобраться с `stage_reverse_tunnels`.
|
||||
|
||||
|
||||
## Обновление Console 3.1.42 и stage_itscreen 1.0.41
|
||||
|
||||
### Исправления доставки обновлений
|
||||
|
||||
- Distinguish Cloudflare HTTP 403 / 1010 client-signature rejection from Git credential failures; do not expose HTTP response bodies or secrets.
|
||||
- Publish `stage_itscreen` 1.0.41: the Debian updater reads `latest-iomatex.json`, whose binary URL matches its strict `git.iomatex.com` allowlist. Legacy `latest.json` remains available for old-domain clients.
|
||||
- Preserve checksum/size/embedded-version checks, redirect refusal, installer lock and rollback. No client binary is replaced in the public repository.
|
||||
|
||||
Validation: offline delivery/stage-version tests, Debian updater tests, Console stage-update API/UI contracts, and the active UAE Edge diagnostic recorded separately.
|
||||
|
||||
Переходный снимок оставлен в пределах 1000 Git tree entries, чтобы его мог загрузить старый bootstrap без пагинации. Новый bootstrap загружает все страницы дерева одного commit и проверяет их полноту, отсутствие повторов и неизменность commit. Не добавляйте новые файлы в этот переходный снимок без проверки доступа старого загрузчика. Старую Console, которая показывает Cloudflare 1010, сначала перезапустите: это активирует уже обновлённый HTTP User-Agent; пароль Git менять не требуется, если аутентифицированный запрос возвращает HTTP 200.
|
||||
|
||||
### Проверено на UAE g-box-5e8135fd — 2026-11-19
|
||||
|
||||
- Исходно: Console 3.1.25, stage_itscreen 1.0.27, клиент `it-screen 5.1.23`.
|
||||
- Старый процесс Console был запущен 2026-10-19; новые `git_delivery.py`/`stage_versions.py` появились на диске 2026-11-19 после частичного обновления. Запросы с `Python-urllib/3.9` блокировались Cloudflare: HTTP 403, `error code: 1010`. С `IomatexOS-Updater/1.0` и теми же сохранёнными Git credentials API ветки/каталога вернул HTTP 200. Перезапуск Console активировал новый HTTP-код; проверка версий стала успешной без смены пароля.
|
||||
- Первоначальная установка остановилась в `stage_itscreen` на `ValueError: Untrusted download URL`: новый allowlist домена несовместим с legacy `latest.json`. Канонический `latest-iomatex.json` доступен updater без авторизации и содержит URL того же разрешённого домена.
|
||||
- Переходный commit с 1001 tree entries выявил прежнее ограничение загрузчика. Новый `repository_tree` проверен на реальном двухстраничном ответе Git: все 1001 записи уникальны. Миграционный снимок `cb8b4d0ecc0599b4b3a440ad71e7a1447ede818d` содержит 1000 записей (`truncated=false`), поэтому обновление смог получить и старый загрузчик.
|
||||
- Через штатные `/api/stages/check` и `/api/stages/install` последовательно установлены Console 3.1.42 и stage_itscreen 1.0.41. Обе detached jobs завершились `success` с соответствующими receipts.
|
||||
- Установлен существующий опубликованный Debian client 5.1.62 / build 5010062. SHA-256 бинарника совпал с каноническим манифестом: `5b81e7fa9359c7690630a9d3d98b4e0c6b5db7db3882e8246acb3f4de413a3a8`. Один процесс плеера; itscreen-x11, iomatex-console и iomatex-client-updater активны, NRestarts плеера = 0. Новый бинарный релиз не публиковался.
|
||||
- Автотесты: offline delivery/stage versions — 67 (один platform-specific skip), Debian updater — 21, Console stage-update API — 4, assets — 3; JavaScript stage-update UI contract passed. Визуальная проверка физического экрана и управление аппаратными выходами в эту диагностику не входили.
|
||||
|
|
|
|||
|
|
@ -0,0 +1,12 @@
|
|||
# Optional dashboard bridge offline editing snapshot — 2026-11-15
|
||||
|
||||
Backlog #1 remains WIP. An explicit OFFLINE_HMI_CONFIG enables the isolated SQLite
|
||||
settings/outbox/sync module on a loopback-only bridge. Current default behavior is
|
||||
retained without that setting. Hardware actions are not queued as offline edits.
|
||||
Native MQTT prefix/identity are read from the registered configuration.
|
||||
|
||||
Verified: 15 Python store/runtime tests, including durable restart/retry, transaction
|
||||
interruption, clock trust, grant scope, local-origin/operator guards and rejection of
|
||||
hardware actions. See AITS docs/architecture/offline-irrigation-hmi.md for remaining
|
||||
acceptance gates. This is source synchronization only: no stage version/feed update
|
||||
or OS/bridge installation on physical devices.
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
# Console 3.1.29 — update domain migration
|
||||
|
||||
- Install shared Git delivery with git.iomatex.com as its canonical HTTPS host.
|
||||
- Normalize legacy saved hosts in stage checks and package downloads; retain exact-host trust, TLS verification, pinned commits and checksums.
|
||||
- Bootstrap defaults to git.iomatex.com; legacy installer URLs and virtual APT paths remain accepted.
|
||||
- Identify bootstrap and package requests as IomatexOS-Updater/1.0; avoid the new proxy rejecting the default Python user agent with Cloudflare 1010.
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
# Console 3.1.30 — complete Git update domain audit
|
||||
|
||||
- All ten Console stages use the shared stage_versions/git_delivery owner for
|
||||
catalog checks, individual updates, update-all, snapshots and package delivery.
|
||||
- Bootstrap accepts legacy saved repository URLs but always connects to
|
||||
git.iomatex.com, including network retries; no fallback to git.it-screen.com.
|
||||
- Preserve TLS verification, exact-host validation, commit pinning and checksums.
|
||||
- New snapshots, credentials, stage config and APT sources store the new host.
|
||||
Legacy virtual APT addresses remain readable and resolve through the new host.
|
||||
- Client binaries remain 5.1.44; this release updates Console/delivery only.
|
||||
|
|
@ -0,0 +1,10 @@
|
|||
# Console 3.1.31 — persist migration from old installed bootstrap
|
||||
|
||||
- Bench upgrade through the pre-migration Console revealed that the old running
|
||||
bootstrap writes its old host into snapshot metadata and credentials before
|
||||
invoking the new activator. Requests already normalize it, but stored values
|
||||
must also migrate.
|
||||
- The new activator now persists the canonical host in both source metadata and
|
||||
credentials as well as the derived APT and stage-update configuration.
|
||||
- Preserve credentials and their 0600 permissions; never expose them in logs.
|
||||
- Includes the complete Console 3.1.30 module audit and new-domain-only retries.
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
# Console 3.1.32 — client update control
|
||||
|
||||
- It-Screen shows installed and available native client versions, update availability, progress and errors.
|
||||
- Check and update delegates to the existing Debian updater socket; no duplicate download/install implementation.
|
||||
- Opening the tab performs a check-only request; it never installs or changes automatic updates. Status polling updates only the version panel, preserving registration form edits.
|
||||
- Authenticated API allowlists check-only/update; GET reads local updater state without external network requests.
|
||||
- Requires stage_itscreen 1.0.40 for the snapshot/check-only protocol extension. Older services report an explicit error.
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
# Console 3.1.33 — content-versioned browser resources
|
||||
|
||||
- The existing static file response owner fingerprints Console JS, translations and CSS in served HTML. Changing a file changes its URL even if the release label was reused.
|
||||
- Retain no-store headers and existing asset endpoints. No UI controls or installation logic are duplicated.
|
||||
- This hardens browser refresh after deployment; it does not prove the cause of the reported missing update button in an existing browser session.
|
||||
- Tests verify stable URLs for unchanged content and invalidation for a same-version JavaScript change.
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
# Console 3.1.34 — client update in the IT-Screen profile card
|
||||
|
||||
- Show the shared Debian client update state and action directly in the
|
||||
IT-Screen service profile card on Health: installed version, available
|
||||
version, availability/progress/error status, and Check and update client.
|
||||
- Use the same update controller and authenticated API as the dedicated
|
||||
It-Screen tab. Health performs a check-only request and local status polling;
|
||||
it does not change the automatic-update preference.
|
||||
- Rename the separate stage 1.0.40 presentation to Client update system module
|
||||
and explain that it is the technical updater module, not the application
|
||||
version.
|
||||
- Keep the generic stage renderer as the single owner; the IT-Screen card only
|
||||
supplies contextual labels. No parallel installation path is introduced.
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
# Console 3.1.35 — wide-screen service layout
|
||||
|
||||
- Increase the Console shell ceiling from 1180 px to 1600 px so wide screens
|
||||
use their available horizontal space instead of leaving large empty margins.
|
||||
- Give the Health service list one explicit responsive owner: three wide
|
||||
columns on desktop, two columns at 1100 px and below, and one column at
|
||||
720 px and below.
|
||||
- Preserve all existing service-card content, actions and status semantics.
|
||||
Other Console card families keep their current layout contracts.
|
||||
- Browser verification at 360, 768, 1024, 1440 and 1920 px confirmed 1/2/2/3/3
|
||||
columns, no horizontal overflow, a 1600 px shell and approximately 511 px
|
||||
service cards at 1920 px.
|
||||
|
|
@ -0,0 +1,14 @@
|
|||
# Console 3.1.36 — compact Health service profiles
|
||||
|
||||
- Recompose standard Health service cards around one shared compact summary
|
||||
for ID, state and status, with details, tests, flags, actions and release
|
||||
controls arranged in responsive information columns.
|
||||
- Give the IT-Screen profile two desktop grid columns and three internal zones
|
||||
for registration, client update and system-module information. The existing
|
||||
update actions and status semantics remain owned by the shared release UI.
|
||||
- Keep specialized Display, access-point and reverse-tunnel layouts intact.
|
||||
Standard cards collapse to two and then one internal column as space narrows.
|
||||
- Browser verification at 360, 768, 1024, 1440 and 1920 px confirmed the
|
||||
1/2/2/3/3 outer grid, no horizontal overflow and readable responsive
|
||||
composition. At 1920 px the IT-Screen card height decreased from 921 px to
|
||||
482 px, a reduction of 439 px (47.7%).
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
# Console 3.1.37 — faster navigation and wide technical values
|
||||
|
||||
- Let service details with long values span the complete card width. USB device
|
||||
paths and FFmpeg build strings remain readable without narrow word columns.
|
||||
- Reuse one provider snapshot across Health, Network and G-Box instead of
|
||||
executing the complete system-service diagnostics separately for every tab.
|
||||
- Keep the shared snapshot for 15 seconds during normal navigation. Explicit
|
||||
Refresh bypasses the snapshot, so an operator can still request current data.
|
||||
- Mark SHA-fingerprinted CSS and JavaScript as immutable browser resources while
|
||||
keeping the HTML entry point uncached. A changed asset receives a new URL.
|
||||
- Activate the selected tab immediately before its data request completes, so
|
||||
navigation always gives visible feedback while live diagnostics are loading.
|
||||
- The pre-change browser baseline on the local Edge was 1.7 seconds for initial
|
||||
Health, 6.1 seconds for Network, 1.1 seconds for Modbus and 2.6 seconds for
|
||||
G-Box. These timings identified repeated provider diagnostics as the main
|
||||
avoidable delay.
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
# Console 3.1.38 — parallel service diagnostics
|
||||
|
||||
- Execute independent provider modules concurrently with a maximum of four
|
||||
workers while preserving their canonical card order.
|
||||
- Execute the independent core service checks for It-Screen, MQTT, Zigbee,
|
||||
tunnels, FFmpeg, display and managed system services through the same bounded
|
||||
worker contract.
|
||||
- Keep the shared snapshot, explicit Refresh bypass and wide technical-value
|
||||
layout introduced in Console 3.1.37.
|
||||
- Contract tests verify that provider and core-card checks actually overlap and
|
||||
that the resulting cards remain in the established product order.
|
||||
|
|
@ -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.
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
# Console 3.1.40 — synchronized camera diagnostics release
|
||||
|
||||
- Synchronize the embedded backend version, frontend version, static asset cache keys, stage manifest and release catalog.
|
||||
- Preserve the sanitized FFmpeg startup error added with Console 3.1.39.
|
||||
|
||||
Validation: the complete Console test suite passes and the installed runtime identity reports the same version as the stage updater.
|
||||
|
|
@ -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.
|
||||
|
|
@ -0,0 +1,34 @@
|
|||
# Debian Console update transport audit — 2026-10-29
|
||||
|
||||
Published target: Console 3.1.30, client 5.1.44 unchanged.
|
||||
|
||||
| Entry | Shared owner | Network destination |
|
||||
| --- | --- | --- |
|
||||
| Console version check `/api/stages/check` | stage_versions.refresh → git_delivery.open_git | HTTPS git.iomatex.com |
|
||||
| Single stage `/api/stages/install` | stage_versions.install → git_delivery.bootstrap | HTTPS git.iomatex.com |
|
||||
| Update all `/api/stages/install-all` | same owner, ordered stage queue | HTTPS git.iomatex.com |
|
||||
| Initial installer, including old `--git-url` input | bootstrap then shared delivery owner | HTTPS git.iomatex.com, including retries |
|
||||
| APT packages and native runtime dependencies | custom iomatex APT method → download_object → open_git | HTTPS git.iomatex.com |
|
||||
| Client ELF and Zigbee2MQTT archive | git_delivery fetch → download_object | HTTPS git.iomatex.com |
|
||||
| Snapshot/credential/stage/source persistence | bootstrap/activate/configure | canonical new host |
|
||||
|
||||
Audited stages: environment, Wi-Fi/AP, MQTT, Zigbee2MQTT, Console,
|
||||
Avahi/mDNS, Cockpit, display/client, IP streaming, reverse tunnels.
|
||||
They use offline/require-local.sh (Zigbee2MQTT through its shared library).
|
||||
The optional dashboard bridge installer uses the same delivery owner.
|
||||
The legacy full-clone functions in local_installer.sh are unreachable: its Git
|
||||
entry refuses to run and directs the user to the lightweight bootstrap.
|
||||
|
||||
Old host literals remain only as accepted migration inputs and virtual APT
|
||||
identifiers, test fixtures, or historical documentation. They are not network
|
||||
fallback destinations. Registration servers and local service health URLs are
|
||||
separate contracts and are unchanged. Build-time Debian dependency collection
|
||||
in offline/build.sh is not an Edge updater.
|
||||
|
||||
Security remains: exact allowlisted hosts, TLS verification, redirect refusal,
|
||||
commit-pinned contents and package hashes, authenticated Console actions,
|
||||
explicit installation confirmation and shared installation lock.
|
||||
|
||||
Regression coverage: bootstrap retry with either input alias; stage catalog
|
||||
refresh with legacy/new/missing host; legacy snapshot persistence; package
|
||||
transport; individual/bulk Console API permission and confirmation tests.
|
||||
|
|
@ -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.
|
||||
|
|
@ -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.
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
# stage_itscreen 1.0.34 — EVAx10 5.1.44
|
||||
|
||||
- Publish Debian ARM64 client from the common release source in release-provenance.json.
|
||||
- Shared Git delivery normalizes saved git.it-screen.com sources to git.iomatex.com before HTTPS requests.
|
||||
- Existing virtual APT addresses remain readable; new APT sources use git.iomatex.com.
|
||||
- Registration, device identity, media and schedules are preserved.
|
||||
- If the old domain is already blocked, use the new-domain bootstrap once to install this delivery owner.
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
# stage_itscreen 1.0.35 — EVAx10 5.1.51
|
||||
|
||||
- Publish the synchronized Debian ARM64 Edge Client 5.1.51 build.
|
||||
- Apply live window geometry smoothly and avoid a duplicate redraw after the final coordinate update.
|
||||
- Keep deterministic layout selection, ONVIF verification and existing device registration data.
|
||||
- Preserve the current OS, media cache, schedules and connection settings during the stage update.
|
||||
|
|
@ -0,0 +1,7 @@
|
|||
# stage_itscreen 1.0.36 — EVAx10 5.1.55
|
||||
|
||||
- Publish Debian ARM64 Edge Client 5.1.55 through the Console update channel.
|
||||
- Report the complete previous, current and next-hour generated playback timelines to the server.
|
||||
- Keep device registration, media cache, schedules, connection settings and the existing operating system during the stage update.
|
||||
- Source commit: `47147d767678bcbb19dc48b578b51ff65a2f2278`.
|
||||
- Binary SHA-256: `5e9ab66b072aaa64a1b033992bf6bdc77a1a83c4a35342cbde58f4581753505d`.
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
# stage_itscreen 1.0.37 — EVAx10 5.1.55 revision 2
|
||||
|
||||
- Correct the 1.0.36 publication: its binary actually reported 5.1.54 despite
|
||||
the 5.1.55 manifest. Replace it with a clean ARM64 build reporting 5.1.55 / 5010055.
|
||||
- Advance the stage version so devices with 1.0.36 are offered the correction.
|
||||
- Preserve registration, media and settings; retain the existing stage update contract.
|
||||
- Exact binary digest and source commit are in stage_itscreen/release-provenance.json.
|
||||
- Before replacing the installed binary, execute `--version` and require both version
|
||||
and native build number to match the release provenance; reject mislabeled files.
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
# stage_itscreen 1.0.38 — Debian client automatic updates
|
||||
|
||||
- Install iomatex-client-updater.service; reuse the existing itsupdater Unix
|
||||
socket and active_update flag sent by the device is_check_update setting.
|
||||
- Check the public DOWNLOAD_IOMATEX_APP Debian feed on git.iomatex.com every
|
||||
15 minutes when enabled. Persist the flag; disabled means no automatic installs.
|
||||
- Manual check/install reuse the same owner. Validate host, platform, ELF ABI,
|
||||
size, SHA-256 and embedded version before stopping the client.
|
||||
- Serialize with Console installation, atomically replace the executable, and
|
||||
restore the previous binary after failed startup or interrupted installation.
|
||||
- Keep registration, settings and media. Preserve a newer Download client when
|
||||
installing an older OS stage. System packages remain managed by Console.
|
||||
- Client binary remains verified 5.1.55 / 5010055 revision 2.
|
||||
|
|
@ -0,0 +1,13 @@
|
|||
# stage_itscreen 1.0.39 — First installation from Download
|
||||
|
||||
- First provisioning resolves the same public Debian Download manifest as the
|
||||
automatic updater. OS no longer selects stage_itscreen/itscreen for installation.
|
||||
- Reuse manifest validation, download, ELF/size/SHA-256/embedded-version checks
|
||||
and atomic replacement from the existing updater owner.
|
||||
- Initial provisioning installs a client even when automatic updates are off;
|
||||
preserve that flag, registration, settings and a newer installed client.
|
||||
- Download failure aborts provisioning without falling back to an old bundled
|
||||
executable. Archived files remain available only for legacy URL compatibility.
|
||||
- Use isolated candidate filenames to avoid collisions with a concurrently
|
||||
downloading updater; share the inherited Console installer lock.
|
||||
- Dependencies, Console and service startup remain owned by the OS stages.
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
# It-Screen stage 1.0.40 — Console update adapter
|
||||
|
||||
- Extend the existing updater socket with snapshot and check_only commands for Console.
|
||||
- Check-only never installs, including when automatic updates are enabled; manual update keeps the existing verified download, lock, rollback and startup checks.
|
||||
- Expose queued/running state and errors without changing client version 5.1.55 or update preferences.
|
||||
- Validation: 19 updater tests, frontend state tests and local ARM64 Console API checks.
|
||||
|
|
@ -4,7 +4,7 @@ set -Eeuo pipefail
|
|||
[[ ${EUID:-$(id -u)} -eq 0 ]] || exec sudo -E bash "$0" "$@"
|
||||
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
GIT_URL=${IOMATEX_GIT_URL:-https://git.it-screen.com/An-J/Iomatex_OS.git}
|
||||
GIT_URL=${IOMATEX_GIT_URL:-https://git.iomatex.com/An-J/Iomatex_OS.git}
|
||||
GIT_BRANCH=${IOMATEX_GIT_BRANCH:-ci-cd}
|
||||
CHECKOUT_DIR=${IOMATEX_GIT_DIR:-/userdata/Iomatex_OS}
|
||||
STAGES=stage_env,stage_wifi,stage_mqtt,stage_ui,stage_avahi,stage_cockpit,stage_itscreen,stage_reverse_tunnels
|
||||
|
|
@ -56,11 +56,13 @@ repo = parsed.path.strip('/').removesuffix('.git')
|
|||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, *args, **kwargs):
|
||||
raise RuntimeError('Git download redirect refused')
|
||||
headers = {'Authorization': 'Basic ' + base64.b64encode((os.environ['IOMATEX_GIT_USERNAME'] + ':' + os.environ['IOMATEX_GIT_PASSWORD']).encode()).decode()}
|
||||
headers = {'User-Agent': 'IomatexOS-Updater/1.0', 'Authorization': 'Basic ' + base64.b64encode((os.environ['IOMATEX_GIT_USERNAME'] + ':' + os.environ['IOMATEX_GIT_PASSWORD']).encode()).decode()}
|
||||
opener = urllib.request.build_opener(NoRedirect)
|
||||
hosts = [parsed.netloc] + [h for h in ('git.it-screen.com', 'git.iomatex.com') if h != parsed.netloc]
|
||||
# Accept old saved URLs as input only; never make a request to the blocked host.
|
||||
host = 'git.iomatex.com'
|
||||
attempts = 2
|
||||
commit = None
|
||||
for index, host in enumerate(hosts):
|
||||
for index in range(attempts):
|
||||
base = 'https://' + host + '/api/v1/repos/' + repo + '/'
|
||||
try:
|
||||
if commit is None:
|
||||
|
|
@ -80,9 +82,9 @@ for index, host in enumerate(hosts):
|
|||
raise SystemExit('Git TLS verification/connection failed. No domain switch; check certificates and system time.') from None
|
||||
if not isinstance(reason, OSError):
|
||||
raise SystemExit('Git request failed; no domain switch.') from None
|
||||
if index + 1 == len(hosts):
|
||||
raise SystemExit('Both Git domains are unreachable. Check DNS and Internet connectivity; installation has not started.') from None
|
||||
print('Git network/DNS failure on ' + host + '; trying ' + hosts[index + 1], flush=True)
|
||||
if index + 1 == attempts:
|
||||
raise SystemExit('git.iomatex.com is unreachable. Check DNS and Internet connectivity; installation has not started.') from None
|
||||
print('Git network/DNS failure; retrying ' + host, flush=True)
|
||||
|
||||
PYTHON
|
||||
GIT_URL=$(cat "$work/git_delivery.py.source")
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ POST_REBOOT_UNIT_PATH="/etc/systemd/system/${POST_REBOOT_UNIT}"
|
|||
POST_REBOOT_AUTOSTART="iomatex-local-installer-post-reboot.desktop"
|
||||
POST_REBOOT_AUTOSTART_PATH="/etc/xdg/autostart/${POST_REBOOT_AUTOSTART}"
|
||||
|
||||
IOMATEX_GIT_URL="${IOMATEX_GIT_URL:-https://git.it-screen.com/An-J/Iomatex_OS.git}"
|
||||
IOMATEX_GIT_URL="${IOMATEX_GIT_URL:-https://git.iomatex.com/An-J/Iomatex_OS.git}"
|
||||
IOMATEX_GIT_BRANCH="${IOMATEX_GIT_BRANCH:-ci-cd}"
|
||||
IOMATEX_GIT_DIR="${IOMATEX_GIT_DIR:-/opt/iomatex/Iomatex_OS}"
|
||||
IOMATEX_GIT_TOKEN="${IOMATEX_GIT_TOKEN:-}"
|
||||
|
|
@ -206,7 +206,7 @@ Behavior:
|
|||
- stops on first stage failure
|
||||
|
||||
Git defaults:
|
||||
- IOMATEX_GIT_URL=https://git.it-screen.com/An-J/Iomatex_OS.git
|
||||
- IOMATEX_GIT_URL=https://git.iomatex.com/An-J/Iomatex_OS.git
|
||||
- IOMATEX_GIT_BRANCH=ci-cd
|
||||
- IOMATEX_GIT_DIR=/opt/iomatex/Iomatex_OS
|
||||
EOF
|
||||
|
|
@ -1427,7 +1427,7 @@ else
|
|||
SOURCE_COMMIT=""
|
||||
else
|
||||
if [[ "$USE_GIT_SOURCE" -eq 1 ]]; then
|
||||
[[ "$GIT_URL" == https://git.it-screen.com/* ]] || die "Only our Git is allowed"
|
||||
[[ ( "$GIT_URL" == https://git.iomatex.com/* || "$GIT_URL" == https://git.it-screen.com/* ) && "$GIT_URL" != *'@'* && "$GIT_URL" != *'?'* && "$GIT_URL" != *'#'* ]] || die "Only our Git is allowed"
|
||||
die "Use install_iomatex_edge.sh to update the lightweight snapshot; full Git clones on Edge are disabled"
|
||||
else
|
||||
PROJECT_DIR="$SCRIPT_DIR"
|
||||
|
|
|
|||
|
|
@ -26,13 +26,14 @@ import urllib.error
|
|||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
HOST = 'git.it-screen.com'
|
||||
ALLOWED_HOSTS = (HOST, 'git.iomatex.com')
|
||||
HOST = 'git.iomatex.com'
|
||||
ALLOWED_HOSTS = (HOST, 'git.it-screen.com')
|
||||
|
||||
def git_host(value=HOST):
|
||||
if value not in ALLOWED_HOSTS:
|
||||
raise ValueError('Unsupported Git host')
|
||||
return value
|
||||
# Normalize legacy saved credentials/snapshots before any network request.
|
||||
return HOST
|
||||
|
||||
STATE = Path('/var/lib/iomatex/packages')
|
||||
AUTH = Path('/etc/iomatex/git-credentials.json')
|
||||
|
|
@ -67,7 +68,7 @@ def auth_from_env():
|
|||
def open_git(repo, endpoint, auth, timeout=120):
|
||||
url = 'https://' + git_host(auth.get('host', HOST)) + '/api/v1/repos/' + repo + '/' + endpoint
|
||||
token = base64.b64encode((auth['username'] + ':' + auth['password']).encode()).decode()
|
||||
req = urllib.request.Request(url, headers={'Authorization': 'Basic ' + token})
|
||||
req = urllib.request.Request(url, headers={'Authorization': 'Basic ' + token, 'User-Agent': 'IomatexOS-Updater/1.0'})
|
||||
return urllib.request.build_opener(NoRedirect).open(req, timeout=timeout)
|
||||
|
||||
def raw_endpoint(path, commit):
|
||||
|
|
@ -282,6 +283,44 @@ def recovery_gate(repo, branch, commit, auth, files, stages, job=None):
|
|||
raise RecoveryPending('Offline userdata recovery queued; update is pending, not complete')
|
||||
|
||||
|
||||
def repository_tree(repo, commit, auth):
|
||||
"""Read every Gitea tree page from one immutable commit before changing files."""
|
||||
endpoint = 'git/trees/' + commit + '?recursive=true'
|
||||
with open_git(repo, endpoint, auth) as response:
|
||||
first = json.load(response)
|
||||
entries = first.get('tree')
|
||||
if not isinstance(entries, list):
|
||||
raise ValueError('Invalid Git repository tree')
|
||||
if not first.get('truncated'):
|
||||
return entries
|
||||
total = first.get('total_count')
|
||||
if type(total) is not int or not len(entries) or not len(entries) <= total <= 100000:
|
||||
raise ValueError('Git returned an incomplete repository tree')
|
||||
entries = list(entries)
|
||||
seen = {item['path'] for item in entries}
|
||||
if len(seen) != len(entries):
|
||||
raise ValueError('Duplicate Git tree members')
|
||||
page = 1
|
||||
while len(entries) < total:
|
||||
page += 1
|
||||
if page > 1000:
|
||||
raise ValueError('Git tree pagination limit exceeded')
|
||||
with open_git(repo, endpoint + '&page=' + str(page), auth) as response:
|
||||
part = json.load(response)
|
||||
chunk = part.get('tree')
|
||||
if (not isinstance(chunk, list) or not chunk or part.get('total_count') != total
|
||||
or part.get('sha') != first.get('sha') or part.get('page', page) != page):
|
||||
raise ValueError('Git returned inconsistent repository tree pages')
|
||||
for item in chunk:
|
||||
if item['path'] in seen:
|
||||
raise ValueError('Duplicate Git tree members')
|
||||
seen.add(item['path'])
|
||||
entries.extend(chunk)
|
||||
if len(entries) > total:
|
||||
raise ValueError('Git tree exceeds declared size')
|
||||
return entries
|
||||
|
||||
|
||||
def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery_job=None, preserve_local_changes=False):
|
||||
platform_check()
|
||||
repo = repo_name(url)
|
||||
|
|
@ -295,12 +334,9 @@ def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery
|
|||
commit = json.load(r)['commit']['id']
|
||||
if not re.fullmatch('[a-f0-9]{40}', commit):
|
||||
raise ValueError('Invalid pinned commit')
|
||||
with open_git(repo, 'git/trees/' + commit + '?recursive=true', auth) as r:
|
||||
tree = json.load(r)
|
||||
if tree.get('truncated'):
|
||||
raise ValueError('Git returned an incomplete repository tree')
|
||||
tree = repository_tree(repo, commit, auth)
|
||||
files = []
|
||||
for item in tree['tree']:
|
||||
for item in tree:
|
||||
path = safe_path(item['path'])
|
||||
if item['type'] == 'tree' or is_payload(path):
|
||||
continue
|
||||
|
|
@ -406,8 +442,14 @@ def activate(root):
|
|||
source = json.loads((root / '.iomatex-source.json').read_text())
|
||||
repo_name('https://' + git_host(source.get('host', HOST)) + '/' + source['repo'])
|
||||
raw_endpoint('probe', source['commit'])
|
||||
auth_from_env() # fail before modifying APT if reboot credentials are missing
|
||||
auth = auth_from_env() # fail before modifying APT if reboot credentials are missing
|
||||
auth['host'] = git_host(auth.get('host', HOST))
|
||||
text, objects = catalog(root)
|
||||
# An older bootstrap invokes this NEW activator but may have persisted its old host.
|
||||
# Migrate both durable inputs here, not only the derived APT/stage configuration.
|
||||
source['host'] = HOST
|
||||
write_json(root / '.iomatex-source.json', source)
|
||||
write_json(AUTH, auth, 0o600)
|
||||
STATE.mkdir(parents=True, exist_ok=True)
|
||||
(STATE / 'Packages').write_text(text)
|
||||
(STATE / 'Packages.gz').write_bytes(gzip.compress(text.encode(), mtime=0))
|
||||
|
|
@ -424,7 +466,7 @@ def activate(root):
|
|||
CACHE.mkdir(parents=True, exist_ok=True)
|
||||
(CACHE / 'partial').mkdir(exist_ok=True)
|
||||
apt = Path('/etc/apt')
|
||||
(apt / 'iomatex-offline.list').write_text('deb [trusted=yes] iomatex://git.it-screen.com/ ./\n')
|
||||
(apt / 'iomatex-offline.list').write_text('deb [trusted=yes] iomatex://git.iomatex.com/ ./\n')
|
||||
(apt / 'apt.conf.d/99iomatex-offline').write_text(
|
||||
'Dir::Etc::sourcelist "/etc/apt/iomatex-offline.list";\n'
|
||||
'Dir::Etc::sourceparts "-";\n'
|
||||
|
|
@ -475,7 +517,7 @@ def message(code, fields):
|
|||
|
||||
def apt_key(uri, objects):
|
||||
u = urllib.parse.urlparse(uri)
|
||||
if u.scheme != 'iomatex' or u.netloc != HOST or u.query or u.fragment:
|
||||
if u.scheme != 'iomatex' or u.netloc not in ALLOWED_HOSTS or u.query or u.fragment:
|
||||
raise ValueError('Unsupported APT source')
|
||||
# APT's method protocol may already decode the URI displayed by apt-get.
|
||||
# Preserve literal %3a in Git filenames; never decode it twice into an epoch colon.
|
||||
|
|
|
|||
|
|
@ -16,6 +16,7 @@ lxterminal openbox wmctrl xdotool libqt5serialbus5-bin qml-module-qtmultimedia
|
|||
qml-module-qtpositioning qml-module-qtquick-virtualkeyboard qtvirtualkeyboard-plugin
|
||||
qml-module-qtwebview qml-module-qt-labs-settings qml-module-qtquick-xmllistmodel
|
||||
qml-module-qtquick-controls2 qml-module-qt-websockets qml-module-qt-labs-platform
|
||||
qml-module-qtquick-window2 qml-module-qtquick-layouts qml-module-qtquick-controls
|
||||
# Camera streaming and snapshots (CLI, in addition to multimedia libraries).
|
||||
ffmpeg
|
||||
# Keep installed OpenCV/GStreamer development chains compatible during FFmpeg upgrades.
|
||||
|
|
|
|||
|
|
@ -116,6 +116,14 @@ def refresh():
|
|||
error = 'The stage release catalog has not been published to Git yet.'
|
||||
elif exc.code in (401, 403):
|
||||
error = 'Git access was denied. Check the Edge Git credentials.'
|
||||
# Cloudflare 1010 is a rejected HTTP client signature, not failed Git auth.
|
||||
# Read only a bounded diagnostic marker; never expose the response body.
|
||||
try:
|
||||
blocked_client = exc.code == 403 and b'error code: 1010' in (exc.read(4096) or b'').lower()
|
||||
except (OSError, AttributeError, TypeError):
|
||||
blocked_client = False
|
||||
if blocked_client:
|
||||
error = 'Git network protection blocked this updater (HTTP 403, Cloudflare 1010). Update or restart Edge Console; check server access rules.'
|
||||
# Do not expose credentials, HTTP bodies or private paths in the API.
|
||||
delivery.write_json(STATE / 'available.json', {
|
||||
**previous, 'attempt_at': int(time.time()), 'error': error,
|
||||
|
|
|
|||
|
|
@ -22,23 +22,26 @@ class BootstrapFallbackTest(unittest.TestCase):
|
|||
opener.open.side_effect = responses
|
||||
with patch('urllib.request.build_opener', return_value=opener), patch.dict(os.environ, {'IOMATEX_GIT_USERNAME':'user','IOMATEX_GIT_PASSWORD':'secret'}), patch.object(sys, 'argv', ['-', 'https://'+host+'/An-J/Iomatex_OS.git', 'ci-cd', str(destination)]):
|
||||
exec(compile(SOURCE, 'bootstrap', 'exec'), {})
|
||||
for call in opener.open.call_args_list:
|
||||
self.assertTrue(call.args[0].full_url.startswith('https://git.iomatex.com/'))
|
||||
return destination, opener
|
||||
|
||||
def test_dns_failure_selects_alternative_and_persists_source(self):
|
||||
def test_dns_retry_stays_on_canonical_host_and_persists_source(self):
|
||||
dest, opener = self.run_bootstrap([URLError(socket.gaierror(-3, 'DNS failure')), io.BytesIO(BRANCH), io.BytesIO(b'loader')])
|
||||
self.assertEqual(b'loader', dest.read_bytes())
|
||||
self.assertEqual('https://git.iomatex.com/An-J/Iomatex_OS.git', Path(str(dest)+'.source').read_text())
|
||||
self.assertEqual(3, opener.open.call_count)
|
||||
self.assertIn('git.iomatex.com', opener.open.call_args.args[0].full_url)
|
||||
|
||||
def test_payload_timeout_keeps_same_commit_on_alternate(self):
|
||||
def test_payload_timeout_keeps_same_commit_and_host(self):
|
||||
_, opener = self.run_bootstrap([io.BytesIO(BRANCH), socket.timeout(), io.BytesIO(b'loader')])
|
||||
self.assertIn('git.iomatex.com', opener.open.call_args.args[0].full_url)
|
||||
self.assertTrue(opener.open.call_args.args[0].full_url.endswith('a'*40))
|
||||
|
||||
def test_explicit_alternate_is_tried_first(self):
|
||||
def test_canonical_host_is_used_directly(self):
|
||||
_, opener = self.run_bootstrap([io.BytesIO(BRANCH), io.BytesIO(b'loader')], 'git.iomatex.com')
|
||||
self.assertIn('git.iomatex.com', opener.open.call_args_list[0].args[0].full_url)
|
||||
self.assertEqual('IomatexOS-Updater/1.0', opener.open.call_args_list[0].args[0].get_header('User-agent'))
|
||||
|
||||
def test_auth_and_tls_fail_without_switch(self):
|
||||
for error in [HTTPError('url', 401, 'Unauthorized', {}, None), URLError(ssl.SSLCertVerificationError('invalid certificate'))]:
|
||||
|
|
@ -46,6 +49,12 @@ class BootstrapFallbackTest(unittest.TestCase):
|
|||
with self.assertRaises(SystemExit):
|
||||
self.run_bootstrap([error, AssertionError('Must not switch')])
|
||||
|
||||
def test_both_domains_unreachable_reports_failure(self):
|
||||
with self.assertRaisesRegex(SystemExit, 'Both Git domains are unreachable'):
|
||||
def test_canonical_host_unreachable_reports_failure(self):
|
||||
with self.assertRaisesRegex(SystemExit, 'git.iomatex.com is unreachable'):
|
||||
self.run_bootstrap([URLError(socket.gaierror()), socket.timeout()])
|
||||
|
||||
def test_both_input_aliases_only_use_new_host(self):
|
||||
for host in ('git.it-screen.com', 'git.iomatex.com'):
|
||||
with self.subTest(host=host):
|
||||
_, opener = self.run_bootstrap([io.BytesIO(BRANCH), io.BytesIO(b'loader')], host)
|
||||
self.assertEqual(2, opener.open.call_count)
|
||||
|
|
|
|||
|
|
@ -11,25 +11,66 @@ sys.path.insert(0, str(Path(__file__).parent))
|
|||
import git_delivery as d
|
||||
|
||||
class DeliveryTest(unittest.TestCase):
|
||||
def test_paginated_tree_is_complete_and_pinned_before_bootstrap(self):
|
||||
commit = 'a' * 40
|
||||
first = {'sha':commit, 'truncated':True, 'total_count':3, 'page':1,
|
||||
'tree':[{'path':'a'}, {'path':'b'}]}
|
||||
second = {**first, 'page':2, 'tree':[{'path':'c'}]}
|
||||
with patch.object(d, 'open_git', side_effect=[io.StringIO(json.dumps(first)), io.StringIO(json.dumps(second))]) as request:
|
||||
self.assertEqual(['a','b','c'], [v['path'] for v in d.repository_tree('An-J/Iomatex_OS', commit, {})])
|
||||
self.assertEqual('git/trees/'+commit+'?recursive=true&page=2', request.call_args.args[1])
|
||||
for bad in [{**second, 'tree':[]}, {**second, 'sha':'b'*40},
|
||||
{**second, 'tree':[{'path':'a'}]}, {**second, 'total_count':4},
|
||||
{**second, 'page':1}]:
|
||||
with self.subTest(page=bad), patch.object(d, 'open_git', side_effect=[io.StringIO(json.dumps(first)), io.StringIO(json.dumps(bad))]):
|
||||
with self.assertRaises(ValueError):
|
||||
d.repository_tree('An-J/Iomatex_OS', commit, {})
|
||||
|
||||
def test_only_trusted_git_aliases_receive_credentials(self):
|
||||
for host in d.ALLOWED_HOSTS:
|
||||
self.assertEqual('An-J/Iomatex_OS', d.repo_name('https://' + host + '/An-J/Iomatex_OS.git'))
|
||||
with patch.object(d.urllib.request, 'build_opener') as opener:
|
||||
d.open_git('An-J/Iomatex_OS', 'branches/ci-cd', {'username': 'u', 'password': 'p', 'host': host})
|
||||
request = opener.return_value.open.call_args.args[0]
|
||||
self.assertEqual('https://' + host + '/api/v1/repos/An-J/Iomatex_OS/branches/ci-cd', request.full_url)
|
||||
self.assertEqual('IomatexOS-Updater/1.0', request.get_header('User-agent'))
|
||||
self.assertEqual('https://git.iomatex.com/api/v1/repos/An-J/Iomatex_OS/branches/ci-cd', request.full_url)
|
||||
for host in ['evil.example', 'git.iomatex.com.evil', 'user@git.iomatex.com', 'git.iomatex.com:443']:
|
||||
with self.assertRaises(ValueError):
|
||||
d.open_git('An-J/Iomatex_OS', 'branches/ci-cd', {'username': 'u', 'password': 'p', 'host': host})
|
||||
|
||||
def test_package_download_uses_persisted_host(self):
|
||||
data = b'package'
|
||||
config = {'host': 'git.iomatex.com', 'repo': 'An-J/Iomatex_OS', 'commit': 'a'*40,
|
||||
config = {'host': 'git.it-screen.com', 'repo': 'An-J/Iomatex_OS', 'commit': 'a'*40,
|
||||
'objects': {'debian/a.deb': {'path': 'third_party/a.deb', 'sha256': hashlib.sha256(data).hexdigest()}}}
|
||||
with tempfile.TemporaryDirectory() as folder, patch.object(d, 'open_git', return_value=io.BytesIO(data)) as request:
|
||||
d.download_object(config, 'debian/a.deb', Path(folder)/'a.deb', {'username': 'u', 'password': 'p'})
|
||||
self.assertEqual('git.iomatex.com', request.call_args.args[2]['host'])
|
||||
|
||||
def test_new_activator_migrates_old_bootstrap_persisted_inputs(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
base = Path(folder)
|
||||
root = base/'snapshot'
|
||||
(root/'offline').mkdir(parents=True)
|
||||
(root/'offline/git_delivery.py').write_text('# delivery owner')
|
||||
(root/'.iomatex-source.json').write_text(json.dumps({
|
||||
'host':'git.it-screen.com','repo':'An-J/Iomatex_OS','commit':'a'*40}))
|
||||
(base/'etc/apt/apt.conf.d').mkdir(parents=True)
|
||||
(base/'usr/lib/apt/methods').mkdir(parents=True)
|
||||
auth = base/'auth.json'
|
||||
def mapped(value):
|
||||
return base/str(value).lstrip('/') if str(value).startswith(('/etc/apt','/usr/')) else Path(value)
|
||||
with patch.object(d, 'platform_check'), patch.object(d, 'catalog', return_value=('',{})), \
|
||||
patch.object(d, 'auth_from_env', return_value={'username':'u','password':'p','host':'git.it-screen.com'}), \
|
||||
patch.object(d, 'STATE', base/'state'), patch.object(d, 'AUTH', auth), \
|
||||
patch.object(d, 'CACHE', base/'cache'), patch.object(d, 'Path', side_effect=mapped), \
|
||||
patch.object(d, 'cleanup'):
|
||||
d.activate(root)
|
||||
for path in [auth, root/'.iomatex-source.json', base/'state/source.json']:
|
||||
self.assertEqual('git.iomatex.com', json.loads(path.read_text())['host'])
|
||||
self.assertEqual('p', json.loads(auth.read_text())['password'])
|
||||
self.assertEqual(0o600, auth.stat().st_mode & 0o777)
|
||||
self.assertIn('iomatex://git.iomatex.com/', (base/'etc/apt/iomatex-offline.list').read_text())
|
||||
|
||||
def test_payloads_excluded_from_edge_snapshot(self):
|
||||
for name in ['third_party/debian/bullseye-arm64/repo/a.deb', 'third_party/zigbee2mqtt/z.tar.gz', 'stage_itscreen/itscreen']:
|
||||
self.assertTrue(d.is_payload(name))
|
||||
|
|
@ -130,7 +171,8 @@ class DeliveryTest(unittest.TestCase):
|
|||
key='debian/xserver-common_2%3a1.0+deb11_all.deb'
|
||||
objects={key:{}}
|
||||
for path in [key, 'debian/xserver-common_2%253a1.0%2bdeb11_all.deb']:
|
||||
self.assertEqual(key,d.apt_key('iomatex://git.it-screen.com/'+path,objects))
|
||||
for host in d.ALLOWED_HOSTS:
|
||||
self.assertEqual(key,d.apt_key('iomatex://'+host+'/'+path,objects))
|
||||
|
||||
def test_unchanged_snapshot_file_is_reused_without_network(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
|
|
|
|||
|
|
@ -19,6 +19,7 @@ dpkg-query() {
|
|||
if [[ "$EXISTING" == 1 ]]; then printf 'install ok installed'; else return 1; fi
|
||||
}
|
||||
install_packages_best_effort() { printf '%s\\n' "$*"; }
|
||||
run_long() { printf '%s\\n' "$*"; }
|
||||
'''
|
||||
return subprocess.check_output(['bash', '-ec', stubs + functions + '\nprepare_qt_gles_stack\ninstall_qt_packages'],
|
||||
env={**os.environ, 'EXISTING': str(existing)}, text=True)
|
||||
|
|
@ -32,4 +33,12 @@ install_packages_best_effort() { printf '%s\\n' "$*"; }
|
|||
def test_fresh_image_gets_gles(self):
|
||||
self.assertIn('libqt5gui5-gles libqt5quick5-gles', self.run_selection(0))
|
||||
|
||||
def test_required_player_qml_modules_use_strict_install(self):
|
||||
output = self.run_selection(0)
|
||||
self.assertIn(
|
||||
'apt-get install -y --no-remove qml-module-qtquick-window2 '
|
||||
'qml-module-qtquick-layouts qml-module-qtquick-controls',
|
||||
output,
|
||||
)
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
|
|
|
|||
|
|
@ -34,6 +34,7 @@ class SnapshotUpdateTest(unittest.TestCase):
|
|||
def test_confirmed_update_preserves_hotfix_and_operator_files(self):
|
||||
self.bootstrap()
|
||||
self.assertEqual(b'new release', (self.root/'install.sh').read_bytes())
|
||||
self.assertEqual('git.iomatex.com', json.loads((self.root/'.iomatex-source.json').read_text())['host'])
|
||||
self.assertEqual(b'operator configuration', (self.root/'operator.conf').read_bytes())
|
||||
backup, = self.parent.glob('.installer-local-changes-*')
|
||||
self.assertEqual(0o700, backup.stat().st_mode & 0o777)
|
||||
|
|
|
|||
|
|
@ -37,6 +37,25 @@ class StageVersionsTest(unittest.TestCase):
|
|||
versions.configure(root)
|
||||
self.assertEqual('git.iomatex.com', versions.read_json(versions.CONFIG)['host'])
|
||||
|
||||
def test_all_stage_catalogs_use_new_host_for_legacy_and_missing_config(self):
|
||||
for host in (None, 'git.it-screen.com', 'git.iomatex.com'):
|
||||
with self.subTest(host=host):
|
||||
cfg = {'repo': 'An-J/Iomatex_OS', 'branch': 'ci-cd'}
|
||||
if host is not None:
|
||||
cfg['host'] = host
|
||||
versions.delivery.write_json(versions.CONFIG, cfg)
|
||||
with mock.patch.object(versions.delivery, 'auth_from_env', return_value={'username':'u','password':'p'}), \
|
||||
mock.patch.object(versions.delivery.urllib.request, 'build_opener') as opener:
|
||||
opener.return_value.open.side_effect = [
|
||||
io.BytesIO(json.dumps({'commit': {'id': COMMIT}}).encode()),
|
||||
io.BytesIO(json.dumps(self.catalog).encode())]
|
||||
versions.refresh()
|
||||
result = versions.read_json(versions.STATE / 'available.json')
|
||||
self.assertEqual('', result['error'])
|
||||
self.assertEqual(set(versions.STAGES), set(result['stages']))
|
||||
for call in opener.return_value.open.call_args_list:
|
||||
self.assertTrue(call.args[0].full_url.startswith('https://git.iomatex.com/'))
|
||||
|
||||
def test_published_catalog_is_accepted_by_legacy_console(self):
|
||||
raw = json.loads((ROOT / 'stage-releases.json').read_text())
|
||||
# This is the exact set checked by Console 3.1.2's validator.
|
||||
|
|
@ -256,6 +275,18 @@ class StageVersionsTest(unittest.TestCase):
|
|||
self.assertEqual(expected, versions.read_json(versions.STATE / 'available.json')['error'])
|
||||
self.assertFalse(self.snapshot()['can_install'])
|
||||
|
||||
def test_cloudflare_client_block_is_not_reported_as_bad_git_credentials(self):
|
||||
from urllib.error import HTTPError
|
||||
failure = HTTPError('https://git.iomatex.com/', 403, 'Forbidden', {},
|
||||
io.BytesIO(b'error code: 1010'))
|
||||
with mock.patch.object(versions.delivery, 'open_git', side_effect=failure), \
|
||||
mock.patch.object(versions.delivery, 'auth_from_env', return_value={}):
|
||||
versions.refresh()
|
||||
error = versions.read_json(versions.STATE / 'available.json')['error']
|
||||
self.assertIn('Cloudflare 1010', error)
|
||||
self.assertNotIn('credentials', error)
|
||||
self.assertFalse(self.snapshot()['can_install'])
|
||||
|
||||
def test_release_check_refreshes_after_one_minute(self):
|
||||
for age, expected in [(59, False), (61, True)]:
|
||||
with self.subTest(age=age), mock.patch.object(versions, '_checking', False), \
|
||||
|
|
|
|||
|
|
@ -14,7 +14,7 @@
|
|||
"version": "1.0.1"
|
||||
},
|
||||
"stage_ui": {
|
||||
"version": "3.1.28"
|
||||
"version": "3.1.42"
|
||||
},
|
||||
"stage_avahi": {
|
||||
"version": "1.0.0"
|
||||
|
|
@ -23,7 +23,7 @@
|
|||
"version": "1.0.0"
|
||||
},
|
||||
"stage_itscreen": {
|
||||
"version": "1.0.33"
|
||||
"version": "1.0.42"
|
||||
},
|
||||
"stage_reverse_tunnels": {
|
||||
"version": "1.0.2"
|
||||
|
|
@ -31,7 +31,7 @@
|
|||
},
|
||||
"optional_stages": {
|
||||
"stage_ip_stream": {
|
||||
"version": "1.0.8"
|
||||
"version": "1.0.10"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@ import re
|
|||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
import math
|
||||
from datetime import datetime, timezone
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from urllib.parse import parse_qs, urlparse
|
||||
|
|
@ -63,6 +65,11 @@ class BridgeState:
|
|||
self.last_message_at = ""
|
||||
self.mqtt_connected = False
|
||||
self.mqtt_last_error = ""
|
||||
self.hmi_received = None
|
||||
self.hmi_emitted = None
|
||||
self.hmi_registers = {}
|
||||
self.hmi_components = {}
|
||||
self.hmi_capabilities = {}
|
||||
|
||||
def set_mqtt_connected(self, value):
|
||||
with self.lock:
|
||||
|
|
@ -89,6 +96,36 @@ class BridgeState:
|
|||
self.raw_payload = payload
|
||||
self.last_message_at = utc_timestamp()
|
||||
|
||||
def observe_hmi(self, payload, registers=False):
|
||||
now = time.monotonic()
|
||||
if registers:
|
||||
emitted = payload.get('observed_at_ms')
|
||||
if type(emitted) not in (int, float) or not math.isfinite(emitted) or abs(time.time()*1000-emitted)>5000: return False
|
||||
for item in (payload.get('payload') or payload).get('values', []):
|
||||
if not isinstance(item, dict) or not isinstance(item.get('id'), int): continue
|
||||
with self.lock:
|
||||
previous=self.hmi_registers.get(str(item['id']))
|
||||
if previous and previous[1]['observed_at_ms'] >= emitted: continue
|
||||
self.hmi_registers[str(item['id'])] = (now, dict(item,observed_at_ms=emitted))
|
||||
else:
|
||||
emitted = payload.get('emitted_at')
|
||||
if type(emitted) not in (int, float) or not math.isfinite(emitted) or abs(time.time()*1000-emitted)>5000: return False
|
||||
with self.lock:
|
||||
if self.hmi_emitted is not None and emitted <= self.hmi_emitted: return False
|
||||
self.hmi_emitted, self.hmi_received = emitted, now
|
||||
self.hmi_components = payload.get("components") or {}
|
||||
self.hmi_capabilities = payload.get("capabilities") or {}
|
||||
return True
|
||||
|
||||
def hmi_observation(self, component_id):
|
||||
with self.lock:
|
||||
now = time.monotonic()
|
||||
fresh = self.mqtt_connected and self.hmi_received is not None and 0 <= now-self.hmi_received <= 5
|
||||
return {'fresh': bool(fresh), 'component': dict(self.hmi_components.get(str(component_id), {})) if fresh else {},
|
||||
'observed_at_ms': self.hmi_emitted if fresh else None,
|
||||
'capabilities': dict(self.hmi_capabilities) if fresh else {},
|
||||
'registers': {key:value for key,(received,value) in self.hmi_registers.items() if 0 <= now-received <= 5} if fresh else {}}
|
||||
|
||||
def get_component(self, component_id):
|
||||
with self.lock:
|
||||
component = self.components.get(str(component_id))
|
||||
|
|
@ -104,12 +141,14 @@ class BridgeState:
|
|||
|
||||
|
||||
class MqttBridge:
|
||||
def __init__(self, mqtt_url, device_id, state):
|
||||
def __init__(self, mqtt_url, device_id, state, prefix="it-screen/dev"):
|
||||
self.mqtt_url = mqtt_url
|
||||
self.device_id = device_id
|
||||
self.state = state
|
||||
self.host, self.port = parse_mqtt_url(mqtt_url)
|
||||
self.state_topic = f"it-screen/dev/client/pub/component/plays/{device_id}"
|
||||
self.topic_prefix = prefix
|
||||
self.state_topic = f"{prefix}/client/pub/component/plays/{device_id}"
|
||||
self.register_topic = f"{prefix}/client/pub/interface/values/{device_id}"
|
||||
self._publish_lock = threading.Lock()
|
||||
self._ready = threading.Event()
|
||||
self._client = None
|
||||
|
|
@ -152,10 +191,10 @@ class MqttBridge:
|
|||
def is_connected(self):
|
||||
return self._ready.is_set()
|
||||
|
||||
def publish_event(self, component_id, value, title):
|
||||
def publish_event(self, component_id, value, title, expires_in_ms=None):
|
||||
if self._client is None:
|
||||
raise RuntimeError("MQTT client is unavailable")
|
||||
topic = f"it-screen/dev/client/sub/event/push/{component_id}"
|
||||
topic = f"{self.topic_prefix}/client/sub/event/push/{component_id}"
|
||||
payload = {
|
||||
"action": "push",
|
||||
"value": str(value),
|
||||
|
|
@ -163,7 +202,11 @@ class MqttBridge:
|
|||
"time": utc_timestamp(),
|
||||
"user": "root",
|
||||
"title": str(title),
|
||||
"command_id": uuid.uuid4().hex,
|
||||
}
|
||||
if expires_in_ms is not None:
|
||||
payload['issued_at_ms'] = round(time.time()*1000)
|
||||
payload['expires_at_ms'] = payload['issued_at_ms'] + int(expires_in_ms)
|
||||
serialized = json.dumps(payload, ensure_ascii=True, separators=(",", ":"))
|
||||
with self._publish_lock:
|
||||
if not self.is_connected():
|
||||
|
|
@ -183,7 +226,7 @@ class MqttBridge:
|
|||
self.state.set_mqtt_error(f"connect failed ({rc})")
|
||||
log(f"mqtt connect failed rc={rc}")
|
||||
return
|
||||
result, _ = client.subscribe(self.state_topic, qos=0)
|
||||
result, _ = client.subscribe([(self.state_topic, 0), (self.register_topic, 0)])
|
||||
if result != mqtt_err_success():
|
||||
self._ready.clear()
|
||||
self.state.set_mqtt_error("subscribe failed")
|
||||
|
|
@ -215,6 +258,10 @@ class MqttBridge:
|
|||
log(f"ignored invalid mqtt json topic={msg.topic} error={exc}")
|
||||
return
|
||||
try:
|
||||
if msg.topic == self.register_topic:
|
||||
if not getattr(msg, "retain", False): self.state.observe_hmi(payload, registers=True)
|
||||
return
|
||||
if not getattr(msg, 'retain', False): self.state.observe_hmi(payload)
|
||||
self.state.update_components(payload)
|
||||
except Exception as exc:
|
||||
log(f"ignored invalid mqtt payload topic={msg.topic} error={exc}")
|
||||
|
|
@ -234,7 +281,6 @@ class Handler(BaseHTTPRequestHandler):
|
|||
|
||||
def end_headers(self):
|
||||
self.send_header("Cache-Control", "no-store")
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Access-Control-Allow-Origin", "*")
|
||||
self.send_header("Access-Control-Allow-Headers", "Content-Type")
|
||||
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||||
|
|
@ -243,6 +289,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
def send_json(self, payload, code=200):
|
||||
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
|
@ -273,6 +320,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
self.end_headers()
|
||||
|
||||
def do_GET(self):
|
||||
if self.app.offline_edit and self.app.offline_edit.handle(self): return
|
||||
parsed = urlparse(self.path)
|
||||
if parsed.path == "/api/health":
|
||||
snapshot = self.app.state.health_snapshot()
|
||||
|
|
@ -303,7 +351,11 @@ class Handler(BaseHTTPRequestHandler):
|
|||
self.send_json({"ok": False, "error": "Not found"}, code=404)
|
||||
|
||||
def do_POST(self):
|
||||
if self.app.offline_edit and self.app.offline_edit.handle(self): return
|
||||
parsed = urlparse(self.path)
|
||||
if self.app.offline_edit and parsed.path == '/api/event':
|
||||
self.send_json({'error':'Use the scoped HMI control endpoint'},code=403)
|
||||
return
|
||||
if parsed.path != "/api/event":
|
||||
self.send_json({"ok": False, "error": "Not found"}, code=404)
|
||||
return
|
||||
|
|
@ -357,7 +409,31 @@ class App:
|
|||
self.mqtt_url = os.environ.get("DASHBOARD_BRIDGE_MQTT_URL", DEFAULT_MQTT_URL).strip() or DEFAULT_MQTT_URL
|
||||
self.device_id = os.environ.get("DASHBOARD_BRIDGE_DEVICE_ID", "").strip() or device_id_from_hostname()
|
||||
self.state = BridgeState()
|
||||
self.mqtt_bridge = MqttBridge(self.mqtt_url, self.device_id, self.state)
|
||||
offline_config = os.environ.get('OFFLINE_HMI_CONFIG', '').strip()
|
||||
prefix = 'it-screen/dev' # Compatibility mode; new HMI never guesses this prefix.
|
||||
if offline_config:
|
||||
with open(offline_config) as stream: hmi_config = json.load(stream)
|
||||
with open(hmi_config['native_config_path']) as stream: native_config = json.load(stream)
|
||||
prefix = str(native_config['mqtt']['prefix']).strip('/')
|
||||
if not prefix or len(prefix)>200 or not re.fullmatch(r'[A-Za-z0-9_./-]+',prefix): raise RuntimeError('Invalid native MQTT prefix')
|
||||
self.device_id = str(native_config['username'])
|
||||
self.mqtt_bridge = MqttBridge(self.mqtt_url, self.device_id, self.state, prefix)
|
||||
self.offline_edit = None
|
||||
offline_config = os.environ.get('OFFLINE_HMI_CONFIG', '').strip()
|
||||
if offline_config:
|
||||
if self.bind not in ('127.0.0.1', '::1'):
|
||||
raise RuntimeError('Offline editing requires a loopback-only bridge')
|
||||
from offline_edit.runtime import Runtime
|
||||
def invalidate(topic, payload):
|
||||
if self.mqtt_bridge._client is None or not self.mqtt_bridge.is_connected():
|
||||
raise RuntimeError('Local MQTT is not connected; settings are durable but not applied')
|
||||
result = self.mqtt_bridge._client.publish(topic, json.dumps(payload), qos=1, retain=False)
|
||||
if result.rc != mqtt_err_success(): raise RuntimeError('Local configuration notification failed')
|
||||
deadline=time.monotonic()+2.0
|
||||
while not result.is_published() and time.monotonic()<deadline: time.sleep(0.02)
|
||||
if not result.is_published(): raise RuntimeError('Local broker acknowledgement timed out')
|
||||
from offline_edit.control import Control
|
||||
self.offline_edit = Runtime(offline_config, invalidate, control=Control(self.state, self.mqtt_bridge))
|
||||
self.httpd = ThreadingHTTPServer((self.bind, self.port), Handler)
|
||||
self.httpd.app = self
|
||||
|
||||
|
|
@ -366,9 +442,11 @@ class App:
|
|||
f"starting http bind={self.bind} port={self.port} device_id={self.device_id} mqtt_url={self.mqtt_url}"
|
||||
)
|
||||
self.mqtt_bridge.start()
|
||||
if self.offline_edit: self.offline_edit.start()
|
||||
try:
|
||||
self.httpd.serve_forever()
|
||||
finally:
|
||||
if self.offline_edit: self.offline_edit.stop()
|
||||
self.mqtt_bridge.stop()
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
"""Optional offline settings module; importing the legacy bridge does not enable it."""
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
"""Delegated immediate control adapter. No scheduler, persistence or replay queue."""
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
class Control:
|
||||
def __init__(self, state, bridge, monotonic=time.monotonic):
|
||||
self.state, self.bridge, self.monotonic = state, bridge, monotonic
|
||||
self.lock = threading.Lock()
|
||||
self.last_command = {}
|
||||
|
||||
def observation(self, component):
|
||||
observed = self.state.hmi_observation(int(component['id']))
|
||||
outputs = component.get('hardware_outputs') or []
|
||||
reason = 'unbound_output' if not outputs else None
|
||||
if not reason and not observed['fresh']: reason = 'observation_unavailable'
|
||||
if not reason and observed['capabilities'].get('push_expiry_v1') is not True: reason = 'client_update_required'
|
||||
registers = []
|
||||
for register in outputs:
|
||||
item = dict(register)
|
||||
status = observed['registers'].get(str(register['id']))
|
||||
item['status'] = status
|
||||
registers.append(item)
|
||||
if not reason and (not status or status.get('available') is not True
|
||||
or status.get('error_code', 0) != 0 or status.get('emulated') is True):
|
||||
reason = 'output_unavailable'
|
||||
observed.update(registers=registers, reason=reason,
|
||||
can_start=not reason and component['groups']['active']['value']['active'] == 1,
|
||||
can_stop=not reason)
|
||||
observed.pop('capabilities', None)
|
||||
return observed
|
||||
|
||||
def issue(self, component, action):
|
||||
if action not in ('start', 'stop'): raise ValueError('Only immediate Start/Stop is allowed')
|
||||
with self.lock:
|
||||
# Re-read observations immediately before dispatch; UI readiness is not authority.
|
||||
state = self.observation(component)
|
||||
if not state['can_' + action]: raise PermissionError(state['reason'] or 'component_inactive')
|
||||
key = int(component['id'])
|
||||
now = self.monotonic()
|
||||
if now - self.last_command.get(key, -math.inf) < 1:
|
||||
raise PermissionError('command_pending')
|
||||
self.last_command = {k:stamp for k,stamp in self.last_command.items() if now-stamp < 60}
|
||||
self.last_command[key] = now
|
||||
try:
|
||||
topic, payload = self.bridge.publish_event(key, action, component['title'], expires_in_ms=5000)
|
||||
except RuntimeError as error:
|
||||
raise OSError('Immediate command unavailable; it was not queued') from error
|
||||
return {'status': 'accepted', 'execution_confirmed': False,
|
||||
'command_id': payload['command_id'], 'expires_at_ms': payload['expires_at_ms']}
|
||||
|
|
@ -0,0 +1,201 @@
|
|||
"""Opt-in transport adapter for the existing bridge; no independent scheduler."""
|
||||
import base64
|
||||
import gzip
|
||||
import hmac
|
||||
import json
|
||||
import secrets
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
from .store import Store
|
||||
|
||||
LOCAL_HOSTS = {'localhost', '127.0.0.1', '::1'}
|
||||
NATIVE_PATHS = {'/v2/device': 'native_config', '/v2/device/layout': 'native_frames'}
|
||||
|
||||
|
||||
class Runtime:
|
||||
def __init__(self, config_path, publish_invalidation, control=None):
|
||||
self.control = control
|
||||
self.config = json.loads(Path(config_path).read_text())
|
||||
credentials = json.loads(Path(self.config['native_config_path']).read_text())
|
||||
self.authorization = 'Basic ' + base64.b64encode((credentials['username'] + ':' + credentials['password']).encode()).decode()
|
||||
self.device_id = int(credentials['id'])
|
||||
self.prefix = str(credentials['mqtt']['prefix']).strip('/')
|
||||
self.username = str(credentials['username'])
|
||||
self.publish_invalidation = publish_invalidation
|
||||
self.store = Store(self.config['database'])
|
||||
Path(self.config['database']).chmod(0o600)
|
||||
self.session = secrets.token_urlsafe(32)
|
||||
self.stop_event = threading.Event()
|
||||
self.sync_event = threading.Event()
|
||||
self.online, self.last_error = False, 'not_connected'
|
||||
self.last_invalidated = None
|
||||
self.cloud_api = self._origin(self.config['cloud_api_url'])
|
||||
self.native_base = self._origin(self.config['native_base_url'])
|
||||
self.assets = Path(self.config['assets']).resolve()
|
||||
|
||||
@staticmethod
|
||||
def _origin(value):
|
||||
parsed = urllib.parse.urlsplit(value)
|
||||
if parsed.scheme not in ('http', 'https') or not parsed.hostname or parsed.username or parsed.password or parsed.query or parsed.fragment:
|
||||
raise ValueError('Configure an explicit credential-free upstream URL')
|
||||
# Public transports require TLS; HTTP is limited to private deployment addresses.
|
||||
if parsed.scheme == 'http':
|
||||
import ipaddress
|
||||
try:
|
||||
if not ipaddress.ip_address(parsed.hostname).is_private: raise ValueError('Public upstream requires TLS')
|
||||
except ValueError:
|
||||
if parsed.hostname not in LOCAL_HOSTS: raise ValueError('Public upstream requires TLS')
|
||||
return value.rstrip('/')
|
||||
|
||||
def _request(self, base, path, body=None, headers=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
request = urllib.request.Request(base + path, data=data, headers={'Authorization': self.authorization, 'Content-Type': 'application/json', 'Accept': 'application/json', **(headers or {})})
|
||||
with urllib.request.urlopen(request, timeout=8) as response:
|
||||
if response.status != 200: raise OSError('Unexpected API response')
|
||||
reader=gzip.GzipFile(fileobj=response) if response.headers.get('Content-Encoding','').lower()=='gzip' else response
|
||||
body=reader.read(4*1024*1024+1)
|
||||
if len(body)>4*1024*1024: raise ValueError('Platform response exceeds the snapshot limit')
|
||||
payload = json.loads(body)
|
||||
return payload.get('data', payload) if isinstance(payload, dict) else payload
|
||||
|
||||
def synchronize(self):
|
||||
try:
|
||||
# Refresh grants before sending queued operations. Revoked scope never replays.
|
||||
snapshot = self._request(self.cloud_api, '/offline-edit/snapshot')
|
||||
self.store.ingest(snapshot)
|
||||
for operation in self.store.pending():
|
||||
result = self._request(self.cloud_api, '/offline-edit/operations', operation)
|
||||
self.store.acknowledge(result)
|
||||
self.online, self.last_error = True, ''
|
||||
except (OSError, ValueError, KeyError, urllib.error.HTTPError) as error:
|
||||
self.online = False
|
||||
self.last_error = 'authorization_failed' if getattr(error, 'code', None) in (401, 403) else 'cloud_unavailable'
|
||||
|
||||
def notify_desired(self):
|
||||
try: revision=self._cache('desired_revision')
|
||||
except OSError: return True
|
||||
if revision==self.last_invalidated: return True
|
||||
try:
|
||||
self.publish_invalidation(self.prefix+'/client/sub/action/'+self.username, {'action':'update','model':'config','revision':revision})
|
||||
self.last_invalidated=revision
|
||||
return True
|
||||
except (OSError,RuntimeError):
|
||||
return False # Durable settings remain visible; a later tick retries invalidation only.
|
||||
|
||||
def request_sync(self):
|
||||
self.sync_event.set()
|
||||
|
||||
def start(self):
|
||||
def loop():
|
||||
while not self.stop_event.is_set():
|
||||
self.sync_event.clear()
|
||||
self.synchronize()
|
||||
self.notify_desired()
|
||||
self.sync_event.wait(10 if self.online else 15)
|
||||
self.thread = threading.Thread(target=loop, name='offline-edit-sync', daemon=True)
|
||||
self.thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.stop_event.set()
|
||||
self.sync_event.set()
|
||||
if hasattr(self, 'thread'): self.thread.join(timeout=9)
|
||||
|
||||
def _cache(self, key, value=None):
|
||||
with self.store.transaction() as db:
|
||||
if value is not None:
|
||||
db.execute('INSERT OR REPLACE INTO metadata VALUES(?,?)', (key, json.dumps(value)))
|
||||
return value
|
||||
row = db.execute('SELECT value FROM metadata WHERE key=?', (key,)).fetchone()
|
||||
if row is None: raise OSError('No cached native configuration')
|
||||
return json.loads(row[0])
|
||||
|
||||
def native(self, path, query, headers=None):
|
||||
if path not in NATIVE_PATHS: raise PermissionError('Native route is outside the configuration scope')
|
||||
name = NATIVE_PATHS[path]
|
||||
# The platform's geometry wire contract is version-dependent. Preserve
|
||||
# native capability headers; never reuse a cache from a different one.
|
||||
forwarded={key:str(value)[:512] for key,value in (headers or {}).items() if key in ('User-Agent','X-Edge-Client-Version') and value}
|
||||
if forwarded:
|
||||
try: previous=self._cache('native_contract')
|
||||
except OSError: previous=None
|
||||
if previous!=forwarded:
|
||||
with self.store.transaction() as db: db.execute("DELETE FROM metadata WHERE key IN ('native_config','native_frames')")
|
||||
self._cache('native_contract',forwarded)
|
||||
try:
|
||||
payload = self._request(self.native_base, path + ('?' + query if query else ''), headers=forwarded)
|
||||
self._cache(name, payload)
|
||||
# Native already receives the platform MQTT update channel. Its
|
||||
# configuration fetch also refreshes HMI clocks without another subscriber.
|
||||
self.request_sync()
|
||||
except (OSError, ValueError):
|
||||
payload = self._cache(name)
|
||||
return self.store.overlay(payload) if name == 'native_frames' else payload
|
||||
|
||||
def _local(self, handler):
|
||||
host = urllib.parse.urlsplit('http://' + handler.headers.get('Host', '')).hostname
|
||||
if handler.client_address[0] not in ('127.0.0.1', '::1') or host not in LOCAL_HOSTS:
|
||||
raise PermissionError('HMI is available only on the local kiosk')
|
||||
|
||||
def _write_allowed(self, handler):
|
||||
self._local(handler)
|
||||
origin = urllib.parse.urlsplit(handler.headers.get('Origin', ''))
|
||||
host = urllib.parse.urlsplit('http://' + handler.headers.get('Host', ''))
|
||||
if origin.scheme != 'http' or origin.netloc != host.netloc or origin.hostname not in LOCAL_HOSTS:
|
||||
raise PermissionError('Foreign HMI origin')
|
||||
if not hmac.compare_digest(handler.headers.get('X-HMI-Session', ''), self.session):
|
||||
raise PermissionError('Local operator session required')
|
||||
if handler.headers.get('Content-Type', '').split(';')[0] != 'application/json':
|
||||
raise ValueError('Expected application/json')
|
||||
|
||||
def handle(self, handler):
|
||||
parsed = urllib.parse.urlsplit(handler.path)
|
||||
if not (parsed.path.startswith('/hmi') or parsed.path.startswith('/native/')): return False
|
||||
try:
|
||||
self._local(handler)
|
||||
if parsed.path.startswith('/native/'):
|
||||
if handler.command != 'GET' or not hmac.compare_digest(handler.headers.get('Authorization', ''), self.authorization):
|
||||
handler.send_response(401); handler.send_header('WWW-Authenticate', 'Basic realm="IOMATEX native configuration"'); handler.end_headers(); return True
|
||||
handler.send_json(self.native(parsed.path[len('/native'):], parsed.query, {key:handler.headers.get(key) for key in ('User-Agent','X-Edge-Client-Version')})); return True
|
||||
query = urllib.parse.parse_qs(parsed.query)
|
||||
if handler.command == 'GET' and parsed.path == '/hmi/api/session':
|
||||
handler.send_json({'session': self.session, 'online': self.online, 'error': self.last_error}); return True
|
||||
if handler.command == 'GET' and parsed.path == '/hmi/api/component':
|
||||
handler.send_json(self.store.view(int(query['id'][0]))); return True
|
||||
if handler.command == 'GET' and parsed.path == '/hmi/api/runtime':
|
||||
component = self.store.view(int(query['id'][0]))
|
||||
value = self.control.observation(component) if self.control else {'fresh':False,'component':{},'registers':[],'can_start':False,'can_stop':False,'reason':'control_unavailable'}
|
||||
handler.send_json(value); return True
|
||||
if handler.command == 'POST' and parsed.path == '/hmi/api/event':
|
||||
self._write_allowed(handler)
|
||||
size=int(handler.headers.get('Content-Length','0'))
|
||||
if not 0 < size <= 2048: raise ValueError('Invalid command size')
|
||||
value=json.loads(handler.rfile.read(size))
|
||||
if set(value)!={'component_id','action'} or type(value['component_id']) is not int: raise ValueError('Invalid immediate command')
|
||||
component=self.store.view(value['component_id'])
|
||||
if not self.control: raise PermissionError('Control is not installed')
|
||||
handler.send_json(self.control.issue(component,value['action'])); return True
|
||||
if handler.command == 'POST' and parsed.path == '/hmi/api/settings':
|
||||
self._write_allowed(handler)
|
||||
size = int(handler.headers.get('Content-Length', '0'))
|
||||
if not 0 < size <= 65536: raise ValueError('Settings operation is too large or empty')
|
||||
value = json.loads(handler.rfile.read(size))
|
||||
operation = self.store.edit(int(value['component_id']), str(value['group']), value['value'])
|
||||
# Existing local MQTT subscriber + native configuration application own execution.
|
||||
applied=self.notify_desired()
|
||||
self.request_sync()
|
||||
handler.send_json({'operation': operation, 'status': 'saved_locally', 'application_status':'notification_sent' if applied else 'pending'}); return True
|
||||
if handler.command == 'GET' and parsed.path in ('/hmi', '/hmi/'):
|
||||
body = (self.assets / 'index.html').read_bytes()
|
||||
handler.send_response(200); handler.send_header('Content-Type', 'text/html; charset=utf-8'); handler.send_header('Cache-Control', 'no-store'); handler.send_header('Content-Length', str(len(body))); handler.end_headers(); handler.wfile.write(body); return True
|
||||
handler.send_json({'error': 'not_found'}, code=404)
|
||||
except PermissionError as error:
|
||||
handler.send_json({'error': str(error)}, code=403)
|
||||
except (ValueError, KeyError, TypeError) as error:
|
||||
handler.send_json({'error': str(error)}, code=422)
|
||||
except OSError:
|
||||
handler.send_json({'error': 'local_configuration_unavailable'}, code=503)
|
||||
return True
|
||||
|
|
@ -0,0 +1,256 @@
|
|||
"""Durable desired settings and outbox. Never queues physical Start/Stop actions."""
|
||||
import copy
|
||||
import json
|
||||
import math
|
||||
import sqlite3
|
||||
import time
|
||||
import uuid
|
||||
from contextlib import contextmanager
|
||||
from pathlib import Path
|
||||
|
||||
GROUPS = {
|
||||
'duration': ('duration',), 'active': ('active',),
|
||||
'schedule': ('valid_from', 'valid_to', 'valid_hour_from', 'valid_hour_to', 'days_week'),
|
||||
'conditions': ('triggers', 'start_condition_operator', 'per_hour'),
|
||||
'availability': ('valid_from', 'valid_to', 'valid_hour_from', 'valid_hour_to', 'days_week', 'activity'),
|
||||
}
|
||||
ACTIVITY_KEYS = {'activity_schedules', 'activity_time_ranges', 'activity_date_ranges', 'activity_date_operator'}
|
||||
|
||||
|
||||
def attributes(value):
|
||||
result = copy.deepcopy(value)
|
||||
if 'activity' in result:
|
||||
result.pop('activity')
|
||||
return result
|
||||
|
||||
|
||||
def apply_value(element, value):
|
||||
if 'triggers' in value:
|
||||
current = element.get('triggers') or {}
|
||||
if isinstance(current, str): current = json.loads(current)
|
||||
value = copy.deepcopy(value)
|
||||
value['triggers'] = {**{k:v for k,v in current.items() if k in ACTIVITY_KEYS},
|
||||
**{k:v for k,v in value['triggers'].items() if k not in ACTIVITY_KEYS}}
|
||||
element.update(attributes(value))
|
||||
if 'activity' in value:
|
||||
triggers = element.get('triggers') or {}
|
||||
if isinstance(triggers, str): triggers = json.loads(triggers)
|
||||
element['triggers'] = {k:v for k,v in triggers.items() if k not in ACTIVITY_KEYS}
|
||||
element['triggers'].update(copy.deepcopy(value['activity']))
|
||||
|
||||
|
||||
def boot_id():
|
||||
try:
|
||||
return Path('/proc/sys/kernel/random/boot_id').read_text().strip()
|
||||
except OSError:
|
||||
return None # Unknown continuity must not invent a trusted timestamp.
|
||||
|
||||
|
||||
def validate(group, value, generator='sync'):
|
||||
if group not in GROUPS or not isinstance(value, dict) or set(value) != set(GROUPS[group]):
|
||||
raise ValueError('Unsupported or incomplete atomic settings group')
|
||||
if group == 'duration':
|
||||
number = value['duration']
|
||||
if isinstance(number, bool) or not isinstance(number, (int, float)) or not math.isfinite(number) or not 3 <= number <= (3600 if generator == 'sync' else 86400):
|
||||
raise ValueError('Duration exceeds the generator limit')
|
||||
if group == 'active' and (type(value['active']) is not int or value['active'] not in (0, 1)):
|
||||
raise ValueError('Activity must be 0 or 1')
|
||||
if group == 'schedule' and any(v is not None and not isinstance(v, str) for v in value.values()):
|
||||
raise ValueError('Invalid schedule value')
|
||||
if group == 'availability':
|
||||
if (not isinstance(value['activity'], dict) or set(value['activity']) - ACTIVITY_KEYS
|
||||
or any(v is not None and not isinstance(v, str) for k,v in value.items() if k != 'activity')):
|
||||
raise ValueError('Invalid availability group')
|
||||
if group == 'conditions' and (not isinstance(value['triggers'], dict) or value['start_condition_operator'] not in ('AND', 'OR') or type(value['per_hour']) is not int or value['per_hour'] < 0):
|
||||
raise ValueError('Invalid conditions')
|
||||
return copy.deepcopy(value)
|
||||
|
||||
|
||||
class Store:
|
||||
def __init__(self, path, wall=time.time, monotonic=time.monotonic, boot=boot_id):
|
||||
self.path, self.wall, self.monotonic, self.boot = str(path), wall, monotonic, boot
|
||||
Path(self.path).parent.mkdir(parents=True, exist_ok=True)
|
||||
with self.transaction() as db:
|
||||
db.executescript('''
|
||||
CREATE TABLE IF NOT EXISTS components(id INTEGER PRIMARY KEY, payload TEXT NOT NULL, anchor_monotonic REAL NOT NULL, anchor_wall REAL NOT NULL, boot_id TEXT);
|
||||
CREATE TABLE IF NOT EXISTS outbox(id TEXT PRIMARY KEY, component_id INTEGER NOT NULL, group_name TEXT NOT NULL, payload TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', result TEXT, sequence INTEGER NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS metadata(key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
''')
|
||||
|
||||
@contextmanager
|
||||
def transaction(self):
|
||||
db = sqlite3.connect(self.path, timeout=10, isolation_level=None)
|
||||
db.row_factory = sqlite3.Row
|
||||
try:
|
||||
db.execute('PRAGMA journal_mode=WAL')
|
||||
db.execute('PRAGMA synchronous=FULL')
|
||||
db.execute('BEGIN IMMEDIATE')
|
||||
yield db
|
||||
if db.in_transaction:
|
||||
db.commit()
|
||||
except BaseException:
|
||||
if db.in_transaction:
|
||||
db.rollback()
|
||||
raise
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
def ingest(self, snapshot):
|
||||
if snapshot.get('schema_version') != 1 or not isinstance(snapshot.get('components'), list):
|
||||
raise ValueError('Unsupported snapshot')
|
||||
with self.transaction() as db:
|
||||
device_id = int(snapshot['device_id'])
|
||||
old = db.execute("SELECT value FROM metadata WHERE key='device_id'").fetchone()
|
||||
if old and int(old[0]) != device_id:
|
||||
raise ValueError('Device identity changed; use a separate database')
|
||||
db.execute("INSERT OR REPLACE INTO metadata VALUES('device_id',?)", (str(device_id),))
|
||||
ids = []
|
||||
changed = False
|
||||
for component in snapshot['components']:
|
||||
component_id = int(component['id'])
|
||||
ids.append(component_id)
|
||||
component=copy.deepcopy(component)
|
||||
previous=db.execute('SELECT payload FROM components WHERE id=?',(component_id,)).fetchone()
|
||||
previous=json.loads(previous[0]) if previous else None
|
||||
if previous:
|
||||
# An in-flight older snapshot must not undo an acknowledged edit.
|
||||
for group,canonical in previous['groups'].items():
|
||||
incoming=component['groups'].get(group)
|
||||
if incoming and int(incoming['clock']['revision']) < int(canonical['clock']['revision']):
|
||||
component['groups'][group]=canonical
|
||||
before={k:v['value'] for k,v in (previous or {}).get('groups',{}).items()}
|
||||
after={k:v['value'] for k,v in component['groups'].items()}
|
||||
if before!=after:
|
||||
changed=True
|
||||
self._update_native_cache(db,component_id,{k:v for value in after.values() for k,v in value.items()})
|
||||
db.execute('INSERT OR REPLACE INTO components VALUES(?,?,?,?,?)', (component_id, json.dumps(component), self.monotonic(), self.wall(), self.boot()))
|
||||
# A complete server grant snapshot is authoritative for deletions and revocations.
|
||||
allowed = set(ids)
|
||||
for row in db.execute('SELECT id FROM components').fetchall():
|
||||
if row['id'] not in allowed:
|
||||
changed=True
|
||||
db.execute('DELETE FROM components WHERE id=?', (row['id'],))
|
||||
db.execute("UPDATE outbox SET status='scope_removed' WHERE component_id=? AND status='pending'", (row['id'],))
|
||||
|
||||
if changed:
|
||||
db.execute("INSERT OR REPLACE INTO metadata VALUES('desired_revision',?)",(json.dumps('server-'+uuid.uuid4().hex),))
|
||||
|
||||
@staticmethod
|
||||
def _update_native_cache(db,component_id,value):
|
||||
cached=db.execute("SELECT value FROM metadata WHERE key='native_frames'").fetchone()
|
||||
if not cached:return
|
||||
document=json.loads(cached[0])
|
||||
for layout in document.get('layouts',[]):
|
||||
for frame in layout.get('frames',[]):
|
||||
for model in frame.get('playlists',[]):
|
||||
for key in ('elements','diagnostic_elements'):
|
||||
for element in model.get(key,[]):
|
||||
if int(element['id'])!=component_id:continue
|
||||
apply_value(element,value)
|
||||
if element.get('execution_eligibility',{}).get('eligible') is False:element['active']=0
|
||||
db.execute("UPDATE metadata SET value=? WHERE key='native_frames'",(json.dumps(document),))
|
||||
|
||||
def _component(self, db, component_id):
|
||||
row = db.execute('SELECT * FROM components WHERE id=?', (component_id,)).fetchone()
|
||||
if not row:
|
||||
raise PermissionError('Component is not granted')
|
||||
data = json.loads(row['payload'])
|
||||
# Use the advancing server anchor when OS monotonic continuity is intact.
|
||||
elapsed = self.monotonic() - row['anchor_monotonic']
|
||||
anchored = data['anchor']['server_time_ms'] / 1000 + elapsed
|
||||
now = max(self.wall(), anchored) if row['boot_id'] == self.boot() else self.wall()
|
||||
if now >= int(data['grant_expires_at']):
|
||||
raise PermissionError('Editing grant expired')
|
||||
return row, data
|
||||
|
||||
def view(self, component_id):
|
||||
with self.transaction() as db:
|
||||
_, data = self._component(db, component_id)
|
||||
pending = db.execute("SELECT * FROM outbox WHERE component_id=? AND status IN ('pending','clock_conflict','revision_conflict') ORDER BY sequence", (component_id,)).fetchall()
|
||||
data['pending'] = []
|
||||
for row in pending:
|
||||
op = json.loads(row['payload'])
|
||||
data['groups'][row['group_name']]['value'] = op['value']
|
||||
data['pending'].append({'operation_id': row['id'], 'group': row['group_name'], 'status': row['status']})
|
||||
return data
|
||||
|
||||
def edit(self, component_id, group, value):
|
||||
with self.transaction() as db:
|
||||
row, component = self._component(db, component_id)
|
||||
value = validate(group, value, component.get('generator_type', 'sync'))
|
||||
elapsed = self.monotonic() - row['anchor_monotonic']
|
||||
continuity = self.boot() is not None and row['boot_id'] == self.boot() and elapsed >= 0
|
||||
wall_elapsed = self.wall() - row['anchor_wall']
|
||||
trusted = continuity and abs(wall_elapsed - elapsed) <= 300
|
||||
elapsed_ms = max(0, round(elapsed * 1000))
|
||||
sequence = db.execute('SELECT COALESCE(MAX(sequence),0)+1 FROM outbox').fetchone()[0]
|
||||
operation = {
|
||||
'schema_version': 1, 'operation_id': uuid.uuid4().hex,
|
||||
'device_id': int(db.execute("SELECT value FROM metadata WHERE key='device_id'").fetchone()[0]),
|
||||
'component_id': component_id, 'grant_id': component['grant_id'],
|
||||
'group': group, 'value': value,
|
||||
'base_revision': int(component['groups'][group]['clock']['revision']),
|
||||
'anchor_id': component['anchor']['id'], 'elapsed_ms': elapsed_ms,
|
||||
'created_at_ms': int(component['anchor']['server_time_ms']) + elapsed_ms,
|
||||
'clock_trusted': trusted,
|
||||
}
|
||||
# One transaction owns both the desired overlay and the retryable operation.
|
||||
db.execute('INSERT INTO outbox(id,component_id,group_name,payload,sequence) VALUES(?,?,?,?,?)',
|
||||
(operation['operation_id'], component_id, group, json.dumps(operation), sequence))
|
||||
db.execute("INSERT OR REPLACE INTO metadata VALUES('desired_revision',?)", (json.dumps('offline-'+operation['operation_id']),))
|
||||
return operation
|
||||
|
||||
def pending(self, limit=32):
|
||||
with self.transaction() as db:
|
||||
return [json.loads(r[0]) for r in db.execute("SELECT payload FROM outbox WHERE status='pending' ORDER BY sequence LIMIT ?", (min(32, max(1, limit)),))]
|
||||
|
||||
def acknowledge(self, result):
|
||||
with self.transaction() as db:
|
||||
row = db.execute('SELECT * FROM outbox WHERE id=?', (result['operation_id'],)).fetchone()
|
||||
if not row:
|
||||
raise ValueError('Unknown operation receipt')
|
||||
op = json.loads(row['payload'])
|
||||
if int(result['component_id']) != row['component_id'] or result['group'] != row['group_name']:
|
||||
raise ValueError('Receipt identity mismatch')
|
||||
if row['status'] != 'pending':
|
||||
return # Repeated network acknowledgement is inert.
|
||||
status = result['status']
|
||||
if status not in ('accepted', 'superseded', 'clock_conflict', 'revision_conflict'):
|
||||
raise ValueError('Unknown receipt status')
|
||||
component_row = db.execute('SELECT payload FROM components WHERE id=?', (row['component_id'],)).fetchone()
|
||||
if component_row and status in ('accepted', 'superseded'):
|
||||
data = json.loads(component_row[0]); group = row['group_name']
|
||||
canonical = result['canonical']
|
||||
if int(canonical['clock']['revision']) >= int(data['groups'][group]['clock']['revision']):
|
||||
data['groups'][group] = canonical
|
||||
db.execute('UPDATE components SET payload=? WHERE id=?', (json.dumps(data), row['component_id']))
|
||||
# ACK, canonical settings and the native fallback document are one
|
||||
# durable commit. A power loss must not restore a pre-ACK duration.
|
||||
self._update_native_cache(db,row['component_id'],canonical['value'])
|
||||
db.execute('UPDATE outbox SET status=?,result=? WHERE id=?', (status, json.dumps(result), row['id']))
|
||||
if status in ('accepted','superseded'):
|
||||
db.execute("INSERT OR REPLACE INTO metadata VALUES('desired_revision',?)", (json.dumps('offline-ack-'+row['id']),))
|
||||
|
||||
def overlay(self, canonical):
|
||||
payload = copy.deepcopy(canonical)
|
||||
with self.transaction() as db:
|
||||
ids = [r[0] for r in db.execute('SELECT id FROM components')]
|
||||
values = {}
|
||||
for component_id in ids:
|
||||
try:
|
||||
component = self.view(component_id)
|
||||
dirty = {entry['group'] for entry in component['pending']}
|
||||
values[component_id] = {k: v for name, group in component['groups'].items() if name in dirty for k, v in group['value'].items()}
|
||||
except PermissionError:
|
||||
continue
|
||||
# No new component, runtime, model or hardware binding is invented here.
|
||||
for layout in payload.get('layouts', []):
|
||||
for frame in layout.get('frames', []):
|
||||
for model in frame.get('playlists', []):
|
||||
for key in ('elements', 'diagnostic_elements'):
|
||||
for element in model.get(key, []):
|
||||
if int(element['id']) in values:
|
||||
apply_value(element, values[int(element['id'])])
|
||||
if element.get('execution_eligibility', {}).get('eligible') is False:
|
||||
element['active'] = 0 # Never bypass the platform's unbound-output guard.
|
||||
return payload
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
"""Exercise the real HTTP handler, not a browser route interception."""
|
||||
import sys,threading,unittest,urllib.request
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
from http.server import ThreadingHTTPServer
|
||||
sys.path.insert(0,str(Path(__file__).parents[1]/'dashboard_bridge_core/backend'))
|
||||
from bridge import Handler
|
||||
|
||||
class HttpTest(unittest.TestCase):
|
||||
def test_hmi_html_has_one_html_mime_and_json_stays_json(self):
|
||||
class Offline:
|
||||
def handle(self,handler):
|
||||
if handler.path!='/hmi/':return False
|
||||
body=b'<!doctype html><title>HMI</title>'
|
||||
handler.send_response(200);handler.send_header('Content-Type','text/html; charset=utf-8');handler.send_header('Content-Length',str(len(body)));handler.end_headers();handler.wfile.write(body);return True
|
||||
server=ThreadingHTTPServer(('127.0.0.1',0),Handler)
|
||||
server.app=SimpleNamespace(offline_edit=Offline())
|
||||
thread=threading.Thread(target=server.serve_forever,daemon=True);thread.start()
|
||||
try:
|
||||
with urllib.request.urlopen('http://127.0.0.1:%s/hmi/'%server.server_port) as response:
|
||||
self.assertEqual(response.headers.get_all('Content-Type'),['text/html; charset=utf-8'])
|
||||
self.assertTrue(response.read().startswith(b'<!doctype html>'))
|
||||
with self.assertRaises(urllib.error.HTTPError) as context:urllib.request.urlopen('http://127.0.0.1:%s/unknown'%server.server_port)
|
||||
self.assertEqual(context.exception.headers.get_all('Content-Type'),['application/json; charset=utf-8'])
|
||||
finally:server.shutdown();server.server_close();thread.join()
|
||||
|
|
@ -0,0 +1,72 @@
|
|||
import copy
|
||||
import sys
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest.mock import Mock
|
||||
sys.path.insert(0,str(Path(__file__).parents[1]/'dashboard_bridge_core/backend'))
|
||||
from offline_edit.control import Control
|
||||
from offline_edit.store import apply_value
|
||||
|
||||
class ControlTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.state=Mock();self.bridge=Mock();self.now=10
|
||||
self.observed={'fresh':True,'capabilities':{'push_expiry_v1':True},'registers':{'8':{'available':True,'error_code':0,'value':0}},'component':{}}
|
||||
self.state.hmi_observation.side_effect=lambda _:copy.deepcopy(self.observed)
|
||||
self.component={'id':22,'title':'Fixture','hardware_outputs':[{'id':8}], 'groups':{'active':{'value':{'active':1}}}}
|
||||
self.control=Control(self.state,self.bridge,lambda:self.now)
|
||||
self.bridge.publish_event.return_value=('fixture',{'command_id':'test-command-0001','expires_at_ms':5000})
|
||||
def test_fail_closed_for_unbound_stale_legacy_and_bad_output(self):
|
||||
for patch,reason in [({'fresh':False},'observation_unavailable'),({'capabilities':{}},'client_update_required'),({'registers':{}},'output_unavailable'),({'registers':{'8':{'available':True,'emulated':True}}},'output_unavailable')]:
|
||||
baseline=copy.deepcopy(self.observed);self.observed.update(patch)
|
||||
self.assertEqual(self.control.observation(self.component)['reason'],reason)
|
||||
with self.assertRaises(PermissionError):self.control.issue(self.component,'start')
|
||||
self.observed=baseline
|
||||
self.component['hardware_outputs']=[]
|
||||
with self.assertRaises(PermissionError):self.control.issue(self.component,'stop')
|
||||
self.bridge.publish_event.assert_not_called()
|
||||
def test_dispatch_once_with_deadline_and_no_optimistic_confirmation(self):
|
||||
result=self.control.issue(self.component,'start')
|
||||
self.assertFalse(result['execution_confirmed'])
|
||||
self.bridge.publish_event.assert_called_once_with(22,'start','Fixture',expires_in_ms=5000)
|
||||
with self.assertRaises(PermissionError):self.control.issue(self.component,'start')
|
||||
self.now+=2;self.component['groups']['active']['value']['active']=0
|
||||
with self.assertRaises(PermissionError):self.control.issue(self.component,'start')
|
||||
self.control.issue(self.component,'stop')
|
||||
def test_schedule_and_conditions_preserve_each_other(self):
|
||||
element={'triggers':{'start':{'type':'push'},'activity_schedules':[{'days_week':[1]}]}}
|
||||
apply_value(element,{'activity':{'activity_schedules':[{'days_week':[2]}]}})
|
||||
self.assertEqual(element['triggers']['start'],{'type':'push'})
|
||||
apply_value(element,{'triggers':{'stop':{'type':'push'}}})
|
||||
self.assertEqual(element['triggers']['activity_schedules'],[{'days_week':[2]}])
|
||||
self.assertEqual(element['triggers']['stop'],{'type':'push'})
|
||||
|
||||
class ObservationTest(unittest.TestCase):
|
||||
def test_old_observations_cannot_replace_fresh_hmi_state(self):
|
||||
import time
|
||||
from bridge import BridgeState
|
||||
state=BridgeState();state.set_mqtt_connected(True)
|
||||
now=int(time.time()*1000)
|
||||
payload={'emitted_at':now,'components':{'22':{'rest_duration':10}},'capabilities':{'push_expiry_v1':True}}
|
||||
self.assertTrue(state.observe_hmi(payload))
|
||||
self.assertFalse(state.observe_hmi(dict(payload,emitted_at=now-1)))
|
||||
# Compatibility updates are deliberately separate from HMI authority.
|
||||
state.update_components({'components':{'22':{'rest_duration':999}}})
|
||||
self.assertEqual(state.hmi_observation(22)['component']['rest_duration'],10)
|
||||
self.assertFalse(state.observe_hmi(dict(payload,emitted_at=float('nan'))))
|
||||
self.assertTrue(state.observe_hmi({'observed_at_ms':now,'payload':{'values':[{'id':8,'available':True}]}},registers=True))
|
||||
state.observe_hmi({'observed_at_ms':now-1,'payload':{'values':[{'id':8,'available':False}]}},registers=True)
|
||||
self.assertTrue(state.hmi_observation(22)['registers']['8']['available'])
|
||||
state.set_mqtt_connected(False)
|
||||
self.assertFalse(state.hmi_observation(22)['fresh'])
|
||||
self.assertEqual(state.hmi_observation(22)['registers'],{})
|
||||
|
||||
def test_retained_packet_does_not_authorize_control(self):
|
||||
import json,time
|
||||
from types import SimpleNamespace
|
||||
from bridge import BridgeState,MqttBridge
|
||||
state=BridgeState();state.set_mqtt_connected(True)
|
||||
bridge=MqttBridge.__new__(MqttBridge);bridge.state=state;bridge.register_topic='fixture/registers'
|
||||
packet={'components':{'22':{'rest_duration':15}},'emitted_at':int(time.time()*1000),'capabilities':{'push_expiry_v1':True}}
|
||||
bridge._on_message(None,None,SimpleNamespace(topic='fixture/plays',retain=True,payload=json.dumps(packet).encode()))
|
||||
self.assertFalse(state.hmi_observation(22)['fresh'])
|
||||
self.assertEqual(state.get_component(22)['rest_duration'],15)
|
||||
|
|
@ -0,0 +1,131 @@
|
|||
import io
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).parents[1] / 'dashboard_bridge_core/backend'))
|
||||
from offline_edit.runtime import Runtime
|
||||
|
||||
|
||||
class Handler:
|
||||
def __init__(self, path, method='GET', value=None, headers=None):
|
||||
self.path, self.command = path, method
|
||||
body = json.dumps(value).encode() if value is not None else b''
|
||||
self.rfile = io.BytesIO(body)
|
||||
self.client_address = ('127.0.0.1', 12345)
|
||||
self.headers = {'Host':'127.0.0.1:8787', 'Origin':'http://127.0.0.1:8787',
|
||||
'Content-Type':'application/json', 'Content-Length':str(len(body))}
|
||||
self.headers.update(headers or {})
|
||||
self.result, self.code = None, None
|
||||
def send_json(self, value, code=200): self.result, self.code = value, code
|
||||
|
||||
|
||||
class RuntimeTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory(); root = Path(self.tmp.name)
|
||||
native = root / 'native.json'; native.write_text(json.dumps({'id':109,'username':'fixture-edge','password':'fixture-only','mqtt':{'prefix':'tenant/fixture'}}))
|
||||
config = {'native_config_path':str(native),'database':str(root/'edits.sqlite3'),
|
||||
'cloud_api_url':'http://127.0.0.1:8000/api','native_base_url':'http://127.0.0.1:8000','assets':str(root)}
|
||||
self.config_path = root/'config.json'; self.config_path.write_text(json.dumps(config))
|
||||
self.notifications=[]; self.runtime=Runtime(self.config_path,lambda *args,**kwargs:self.notifications.append(args))
|
||||
now=int(time.time()*1000)
|
||||
self.runtime.store.ingest({'schema_version':1,'device_id':109,'components':[{'id':22,'title':'Fixture','grant_id':'grant','grant_expires_at':now//1000+3600,'generator_type':'sync',
|
||||
'anchor':{'id':'anchor','server_time_ms':now},'groups':{'duration':{'value':{'duration':15},'clock':{'revision':1}},'active':{'value':{'active':1},'clock':{'revision':1}}}}]})
|
||||
|
||||
def tearDown(self): self.tmp.cleanup()
|
||||
|
||||
def test_write_requires_local_host_origin_and_operator_session(self):
|
||||
for headers in [{'Host':'attacker.example:8787'}, {'Origin':'http://attacker.example'}, {'X-HMI-Session':'wrong'}]:
|
||||
h=Handler('/hmi/api/settings','POST',{'component_id':22,'group':'duration','value':{'duration':60}},headers)
|
||||
self.runtime.handle(h); self.assertEqual(h.code,403)
|
||||
self.assertEqual(self.runtime.store.pending(),[])
|
||||
|
||||
def test_native_proxy_preserves_geometry_capability_and_separates_cache(self):
|
||||
from unittest.mock import Mock
|
||||
self.runtime._request=Mock(return_value={'layouts':[]})
|
||||
headers={'User-Agent':'it-screen/5.1.60','X-Edge-Client-Version':'5.1.60','Authorization':'must-not-forward'}
|
||||
self.runtime.native('/v2/device/layout','',headers)
|
||||
self.assertEqual(self.runtime._request.call_args.kwargs['headers'],{'User-Agent':'it-screen/5.1.60','X-Edge-Client-Version':'5.1.60'})
|
||||
self.runtime._request.side_effect=OSError('offline')
|
||||
self.assertEqual(self.runtime.native('/v2/device/layout','',headers),{'layouts':[]})
|
||||
with self.assertRaises(OSError):self.runtime.native('/v2/device/layout','',dict(headers,**{'X-Edge-Client-Version':'5.1.61'}))
|
||||
|
||||
def test_immediate_route_checks_grant_session_and_never_queues(self):
|
||||
from unittest.mock import Mock
|
||||
self.runtime.control=Mock()
|
||||
self.runtime.control.issue.return_value={'status':'accepted','execution_confirmed':False}
|
||||
for component_id,headers in [(22,{}),(999,{'X-HMI-Session':self.runtime.session})]:
|
||||
handler=Handler('/hmi/api/event','POST',{'component_id':component_id,'action':'start'},headers)
|
||||
self.runtime.handle(handler)
|
||||
self.assertEqual(handler.code,403)
|
||||
self.runtime.control.issue.assert_not_called()
|
||||
handler=Handler('/hmi/api/event','POST',{'component_id':22,'action':'start'},{'X-HMI-Session':self.runtime.session})
|
||||
self.runtime.handle(handler);self.assertEqual(handler.code,200)
|
||||
self.assertFalse(handler.result['execution_confirmed'])
|
||||
self.assertEqual(self.runtime.store.pending(),[])
|
||||
|
||||
def test_hardware_actions_are_not_settings_or_retryable(self):
|
||||
h=Handler('/hmi/api/settings','POST',{'component_id':22,'group':'start','value':{'active':1}}, {'X-HMI-Session':self.runtime.session})
|
||||
self.runtime.handle(h);self.assertEqual(h.code,422);self.assertEqual(self.notifications,[])
|
||||
|
||||
def test_offline_native_document_uses_only_pending_overlay(self):
|
||||
canonical={'layouts':[{'frames':[{'playlists':[{'elements':[{'id':22,'duration':15,'active':0}]}]}]}]}
|
||||
self.runtime._cache('native_frames',canonical)
|
||||
self.runtime._request=lambda *args,**kwargs: (_ for _ in ()).throw(OSError('offline'))
|
||||
self.runtime.store.edit(22,'duration',{'duration':120})
|
||||
result=self.runtime.native('/v2/device/layout','')
|
||||
self.assertEqual(result['layouts'][0]['frames'][0]['playlists'][0]['elements'][0],{'id':22,'duration':120,'active':0})
|
||||
with self.assertRaises(PermissionError):self.runtime.native('/v2/device/reboot','')
|
||||
|
||||
def test_durable_save_survives_broker_outage_and_notifies_on_restart(self):
|
||||
self.runtime.publish_invalidation=lambda *args,**kwargs: (_ for _ in ()).throw(RuntimeError('broker offline'))
|
||||
h=Handler('/hmi/api/settings','POST',{'component_id':22,'group':'duration','value':{'duration':120}}, {'X-HMI-Session':self.runtime.session})
|
||||
self.runtime.handle(h);self.assertEqual(h.code,200);self.assertEqual(h.result['application_status'],'pending');self.assertTrue(self.runtime.sync_event.is_set())
|
||||
restarted=Runtime(self.config_path,lambda *args,**kwargs:self.notifications.append(args))
|
||||
self.assertEqual(len(restarted.store.pending()),1)
|
||||
self.assertTrue(restarted.notify_desired())
|
||||
self.assertEqual(self.notifications[0][0],'tenant/fixture/client/sub/action/fixture-edge')
|
||||
self.assertEqual(self.notifications[0][1]['model'],'config')
|
||||
self.assertTrue(restarted.notify_desired());self.assertEqual(len(self.notifications),1)
|
||||
|
||||
def test_ack_and_native_fallback_commit_together(self):
|
||||
document={'layouts':[{'frames':[{'playlists':[{'elements':[{'id':22,'duration':15,'active':0,'execution_eligibility':{'eligible':False}}]}]}]}]}
|
||||
self.runtime._cache('native_frames',document)
|
||||
operation=self.runtime.store.edit(22,'duration',{'duration':120})
|
||||
self.runtime.store.acknowledge({'operation_id':operation['operation_id'],'component_id':22,'group':'duration','status':'accepted',
|
||||
'canonical':{'value':{'duration':120},'clock':{'revision':2}}})
|
||||
restarted=Runtime(self.config_path,lambda *args,**kwargs:None)
|
||||
restarted._request=lambda *args,**kwargs: (_ for _ in ()).throw(OSError('offline'))
|
||||
value=restarted.native('/v2/device/layout','')['layouts'][0]['frames'][0]['playlists'][0]['elements'][0]
|
||||
self.assertEqual(restarted.store.pending(),[])
|
||||
self.assertEqual(value['duration'],120)
|
||||
self.assertEqual(value['active'],0)
|
||||
|
||||
def test_remote_duration_refreshes_native_cache_and_notifies_once(self):
|
||||
import copy
|
||||
document={'layouts':[{'frames':[{'playlists':[{'elements':[{'id':22,'duration':15,'active':0,'execution_eligibility':{'eligible':False}}]}]}]}]}
|
||||
self.runtime._cache('native_frames',document)
|
||||
self.runtime.notify_desired();self.notifications.clear()
|
||||
component=copy.deepcopy(self.runtime.store.view(22));component.pop('pending')
|
||||
component['groups']['duration']={'value':{'duration':77},'clock':{'revision':2}}
|
||||
snapshot={'schema_version':1,'device_id':109,'components':[component]}
|
||||
self.runtime._request=lambda *args,**kwargs:snapshot
|
||||
self.runtime.synchronize();self.assertTrue(self.runtime.notify_desired())
|
||||
self.assertEqual(len(self.notifications),1)
|
||||
self.runtime.synchronize();self.runtime.notify_desired();self.assertEqual(len(self.notifications),1)
|
||||
self.runtime._request=lambda *args,**kwargs:(_ for _ in ()).throw(OSError('offline'))
|
||||
element=self.runtime.native('/v2/device/layout','')['layouts'][0]['frames'][0]['playlists'][0]['elements'][0]
|
||||
self.assertEqual(element['duration'],77);self.assertEqual(element['active'],0)
|
||||
older=copy.deepcopy(snapshot);older['components'][0]['groups']['duration']={'value':{'duration':15},'clock':{'revision':1}}
|
||||
self.runtime.store.ingest(older)
|
||||
self.assertEqual(self.runtime.store.view(22)['groups']['duration']['value']['duration'],77)
|
||||
|
||||
def test_plaintext_public_upstream_is_rejected(self):
|
||||
for url in ['http://public.example','http://8.8.8.8','https://user:secret@example.test','file:///etc/passwd']:
|
||||
with self.assertRaises(ValueError):Runtime._origin(url)
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
|
|
@ -0,0 +1,120 @@
|
|||
import copy
|
||||
import importlib.util
|
||||
import sqlite3
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).parents[1] / 'dashboard_bridge_core/backend/offline_edit/store.py'
|
||||
spec = importlib.util.spec_from_file_location('offline_store', ROOT)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
|
||||
|
||||
def snapshot():
|
||||
groups = {'duration': {'duration': 15}, 'active': {'active': 1},
|
||||
'schedule': {key: None for key in module.GROUPS['schedule']},
|
||||
'conditions': {'triggers': {}, 'start_condition_operator': 'AND', 'per_hour': 0}}
|
||||
return {'schema_version': 1, 'device_id': 109, 'components': [{
|
||||
'id': 22, 'title': 'Fixture command, no hardware', 'grant_id': 'grant-fixture',
|
||||
'grant_expires_at': 200000, 'generator_type': 'sync',
|
||||
'anchor': {'id': 'anchor-fixture', 'server_time_ms': 100000000},
|
||||
'groups': {name: {'value': value, 'clock': {'revision': 1}} for name, value in groups.items()}
|
||||
}]}
|
||||
|
||||
|
||||
class OfflineStoreTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.path = Path(self.tmp.name) / 'edits.sqlite3'
|
||||
self.wall, self.mono, self.boot = 100000., 500., 'boot-a'
|
||||
self.store = self.reopen()
|
||||
self.store.ingest(snapshot())
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def reopen(self):
|
||||
return module.Store(self.path, lambda: self.wall, lambda: self.mono, lambda: self.boot)
|
||||
|
||||
def receipt(self, operation, revision=2, status='accepted'):
|
||||
return {'operation_id': operation['operation_id'], 'component_id': 22, 'group': operation['group'],
|
||||
'status': status, 'canonical': {'value': operation['value'], 'clock': {'revision': revision}}}
|
||||
|
||||
def test_offline_commit_and_process_restart_preserve_outbox(self):
|
||||
self.mono += 10; self.wall += 10
|
||||
op = self.store.edit(22, 'duration', {'duration': 120})
|
||||
self.assertTrue(op['clock_trusted'])
|
||||
self.assertEqual(op['created_at_ms'], 100010000)
|
||||
restarted = self.reopen()
|
||||
self.assertEqual(restarted.pending(), [op])
|
||||
self.assertEqual(restarted.view(22)['groups']['duration']['value'], {'duration': 120})
|
||||
restarted.acknowledge(self.receipt(op))
|
||||
restarted.acknowledge(self.receipt(op))
|
||||
self.assertEqual(restarted.pending(), [])
|
||||
self.assertEqual(restarted.view(22)['groups']['duration']['clock']['revision'], 2)
|
||||
|
||||
def test_snapshot_does_not_clobber_independent_or_newer_pending_edits(self):
|
||||
first = self.store.edit(22, 'duration', {'duration': 120})
|
||||
second = self.store.edit(22, 'duration', {'duration': 240})
|
||||
incoming = snapshot(); incoming['components'][0]['groups']['active']['value']['active'] = 0
|
||||
self.store.ingest(incoming)
|
||||
self.store.acknowledge(self.receipt(first))
|
||||
view = self.store.view(22)
|
||||
self.assertEqual(view['groups']['duration']['value']['duration'], 240)
|
||||
self.assertEqual(view['groups']['active']['value']['active'], 0)
|
||||
self.assertEqual(self.store.pending(), [second])
|
||||
self.store.acknowledge(self.receipt(second, 3))
|
||||
self.assertEqual(self.store.view(22)['groups']['duration']['value']['duration'], 240)
|
||||
|
||||
def test_device_change_and_removed_scope_do_not_resurrect_operations(self):
|
||||
self.store.edit(22, 'active', {'active': 0})
|
||||
incoming = snapshot(); incoming['device_id'] = 999
|
||||
with self.assertRaises(ValueError): self.store.ingest(incoming)
|
||||
incoming = snapshot(); incoming['components'] = []
|
||||
self.store.ingest(incoming)
|
||||
self.assertEqual(self.store.pending(), [])
|
||||
with self.assertRaises(PermissionError): self.store.view(22)
|
||||
|
||||
def test_clock_jump_or_reboot_is_explicitly_untrusted(self):
|
||||
self.wall += 1000
|
||||
op = self.store.edit(22, 'duration', {'duration': 20})
|
||||
self.assertFalse(op['clock_trusted'])
|
||||
self.store.acknowledge(self.receipt(op, status='clock_conflict'))
|
||||
self.assertEqual(self.store.pending(), [])
|
||||
self.assertEqual(self.store.view(22)['pending'][0]['status'], 'clock_conflict')
|
||||
self.boot = 'boot-b'; self.mono = 1
|
||||
self.assertFalse(self.reopen().edit(22, 'active', {'active': 0})['clock_trusted'])
|
||||
|
||||
def test_invalid_edits_cannot_enter_outbox(self):
|
||||
for group, value in [('duration', {'duration': 3601}), ('active', {'active': True}),
|
||||
('start', {'value': True}), ('duration', {'duration': 20, 'id': 999})]:
|
||||
with self.assertRaises(ValueError): self.store.edit(22, group, value)
|
||||
self.assertEqual(self.store.pending(), [])
|
||||
|
||||
def test_overlay_changes_only_existing_target_and_pending_group(self):
|
||||
self.store.edit(22, 'duration', {'duration': 120})
|
||||
canonical = {'layouts': [{'frames': [{'playlists': [{'elements': [{'id': 22, 'duration': 15, 'active': 0}, {'id': 99, 'duration': 5}]}]}]}]}
|
||||
result = self.store.overlay(canonical)
|
||||
items = result['layouts'][0]['frames'][0]['playlists'][0]['elements']
|
||||
self.assertEqual(items, [{'id': 22, 'duration': 120, 'active': 0}, {'id': 99, 'duration': 5}])
|
||||
self.assertEqual(canonical['layouts'][0]['frames'][0]['playlists'][0]['elements'][0]['duration'], 15)
|
||||
|
||||
def test_interrupted_sql_write_does_not_apply_half_an_edit(self):
|
||||
with sqlite3.connect(self.path) as db:
|
||||
db.execute("CREATE TRIGGER fail_outbox BEFORE INSERT ON outbox BEGIN SELECT RAISE(ABORT,'fixture interruption'); END")
|
||||
with self.assertRaises(sqlite3.IntegrityError): self.store.edit(22, 'duration', {'duration': 120})
|
||||
self.assertEqual(self.reopen().view(22)['groups']['duration']['value']['duration'], 15)
|
||||
|
||||
def test_local_activity_cannot_bypass_output_eligibility(self):
|
||||
self.store.edit(22, 'active', {'active': 1})
|
||||
native = {'layouts': [{'frames': [{'playlists': [{'elements': [{'id': 22, 'active': 0, 'execution_eligibility': {'eligible': False, 'reason': 'command_output_unbound'}}]}]}]}]}
|
||||
result = self.store.overlay(native)
|
||||
self.assertEqual(result['layouts'][0]['frames'][0]['playlists'][0]['elements'][0]['active'], 0)
|
||||
|
||||
def test_expired_grant_is_not_a_local_permission(self):
|
||||
self.wall = 200001
|
||||
with self.assertRaises(PermissionError): self.store.edit(22, 'active', {'active': 0})
|
||||
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
|
|
@ -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,8 @@ SUPPORTED_INPUT_SCHEMES = {"rtsp"}
|
|||
SUPPORTED_OUTPUT_SCHEMES = {"rtsp", "rtmp", "srt", "udp"}
|
||||
MAX_STREAMS = 8
|
||||
PREVIEW_TTL_SEC = 10 * 60
|
||||
STARTUP_GUARD_SEC = 0.75
|
||||
MAX_FORWARD_RESTARTS = 2
|
||||
FFMPEG_BINARY = "/usr/bin/ffmpeg"
|
||||
FFPROBE_BINARY = "/usr/bin/ffprobe"
|
||||
|
||||
|
|
@ -88,6 +91,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()
|
||||
|
|
@ -100,6 +109,7 @@ class StreamManager:
|
|||
self.operation_lock = threading.RLock()
|
||||
self.control_socket = None
|
||||
self.supervisor_stop = threading.Event()
|
||||
self.last_failure = None
|
||||
|
||||
def publish(self, payload):
|
||||
subprocess.run([
|
||||
|
|
@ -120,8 +130,19 @@ class StreamManager:
|
|||
code = process.poll()
|
||||
if code is None:
|
||||
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.close_error_log(record)
|
||||
self.write_status()
|
||||
return stopped
|
||||
|
||||
|
|
@ -142,11 +163,13 @@ class StreamManager:
|
|||
stream_id: {
|
||||
"kind": record.get("kind", "forward"),
|
||||
"expires_at": int(record.get("expires_at", 0)),
|
||||
"restart_count": int(record.get("restart_count", 0)),
|
||||
}
|
||||
for stream_id, record in self.processes.items()
|
||||
},
|
||||
"active_count": len(self.processes),
|
||||
"max_streams": MAX_STREAMS,
|
||||
"last_failure": self.last_failure,
|
||||
}), encoding="utf-8")
|
||||
os.replace(temporary, STATUS_PATH)
|
||||
|
||||
|
|
@ -177,27 +200,76 @@ 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,
|
||||
"output_url": output_url,
|
||||
"low_latency": low_latency,
|
||||
"profile": profile,
|
||||
"command": command,
|
||||
"restart_count": 0,
|
||||
}
|
||||
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.remember_failure(stream_id, process.returncode, error)
|
||||
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 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):
|
||||
stream_id = validate_stream_id(payload.get("stream_id"))
|
||||
expires_at = time.time() + PREVIEW_TTL_SEC
|
||||
|
|
@ -333,6 +405,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}
|
||||
|
||||
|
|
|
|||
|
|
@ -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,40 @@ 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)
|
||||
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):
|
||||
manager = stream.StreamManager("g-box-test", "it-screen/dev")
|
||||
|
|
@ -125,7 +160,7 @@ class IpStreamTest(unittest.TestCase):
|
|||
dead.poll.return_value = 7
|
||||
manager.processes = {
|
||||
"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()
|
||||
|
||||
|
|
@ -134,8 +169,39 @@ class IpStreamTest(unittest.TestCase):
|
|||
|
||||
self.assertEqual(manager.processes, {})
|
||||
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)
|
||||
|
||||
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):
|
||||
source = MODULE_PATH.read_text(encoding="utf-8")
|
||||
self.assertIn('target=self.supervise, name="ip-stream-supervisor"', source)
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
{
|
||||
"version": "1.0.8"
|
||||
"version": "1.0.10"
|
||||
}
|
||||
|
|
|
|||
Binary file not shown.
|
|
@ -1 +1 @@
|
|||
52d018fe3580f903d7b46fd94bb22d8c88aa321156107eb66998926a218ffcc1 itscreen
|
||||
5e14d2cabd2821620e03467bc5d8bc98d87895d3f6f22c3f82a9cf414c6d13d0 itscreen
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
5.1.42
|
||||
5.1.55
|
||||
|
|
|
|||
|
|
@ -1,14 +1,18 @@
|
|||
{
|
||||
"schema_version": 1,
|
||||
"client_version": "5.1.42",
|
||||
"stage_version": "1.0.33",
|
||||
"client_version": "5.1.55",
|
||||
"stage_version": "1.0.40",
|
||||
"platform": "linux",
|
||||
"architecture": "arm64",
|
||||
"source_repository": "https://git.it-screen.com/Development/It-screenClient.git",
|
||||
"source_repository": "https://git.iomatex.com/Development/It-screenClient.git",
|
||||
"source_branch": "iomatex_dev",
|
||||
"source_commit": "c75170b64ccff88b0a80edf9e21d1382960c9834",
|
||||
"source_commit": "c4739d5dd87ba43c94578af0c6745b0086829175",
|
||||
"binary": "itscreen",
|
||||
"sha256": "52d018fe3580f903d7b46fd94bb22d8c88aa321156107eb66998926a218ffcc1",
|
||||
"assembly_method": "Clean release cross-build from git archive; Debian 11 ARM64 Qt 5.15.2 sysroot; ldd and executable version verified on ARM64 bench",
|
||||
"native_version_code": 5010042
|
||||
"sha256": "5e14d2cabd2821620e03467bc5d8bc98d87895d3f6f22c3f82a9cf414c6d13d0",
|
||||
"assembly_method": "Clean isolated release build from git archive using iomatex-debian-dev:local; --version and linked libraries verified on Debian 11 ARM64",
|
||||
"native_version_code": 5010055,
|
||||
"release_revision": 2,
|
||||
"verified_version_output": "5.1.55 5010055",
|
||||
"artifact_role": "legacy archive only; first installation resolves Download manifest",
|
||||
"installation_feed": "https://git.iomatex.com/An-J/DOWNLOAD_IOMATEX_APP/raw/branch/main/edge-client/debian/latest.json"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -442,6 +442,11 @@ install_qt_packages() {
|
|||
libqt5texttospeech5 \
|
||||
libqt5serialbus5
|
||||
|
||||
# The Player cannot finish loading its QML settings or answer registration
|
||||
# requests without these modules.
|
||||
run_long "Install required Player QML modules" 1800 apt-get install -y --no-remove \
|
||||
qml-module-qtquick-window2 qml-module-qtquick-layouts qml-module-qtquick-controls
|
||||
|
||||
install_packages_best_effort "Install Qt extras" 1800 \
|
||||
lxterminal openbox wmctrl xdotool \
|
||||
libqt5serialbus5-bin \
|
||||
|
|
@ -513,11 +518,9 @@ cleanup_legacy_x11_hacks() {
|
|||
install_itscreen_binary() (
|
||||
set -e
|
||||
step "Install itscreen binary"
|
||||
local src
|
||||
src=$(mktemp /userdata/.iomatex-client.XXXXXX)
|
||||
trap 'rm -f "$src"' EXIT
|
||||
python3 "$IOMATEX_PROJECT_ROOT/offline/git_delivery.py" fetch stage_itscreen/itscreen "$src"
|
||||
install -m 0755 -o "$ITS_USER" -g "$ITS_GROUP" "$src" "$ITS_BINARY"
|
||||
# One Download owner for initial provisioning and subsequent automatic updates.
|
||||
# A failed download aborts the stage; never silently install the bundled legacy ELF.
|
||||
python3 "$SCRIPT_DIR/updater/client_updater.py" --bootstrap
|
||||
)
|
||||
|
||||
install_sudoers() {
|
||||
|
|
@ -1566,6 +1569,7 @@ POWER_WAKE
|
|||
install_x11_session_scripts
|
||||
install_recovery_assets
|
||||
install_systemd_unit
|
||||
bash "$SCRIPT_DIR/updater/install.sh"
|
||||
enable_managed_services
|
||||
post_install_self_test
|
||||
flush_filesystems
|
||||
|
|
|
|||
|
|
@ -0,0 +1,23 @@
|
|||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from verify_client_release import verify
|
||||
|
||||
|
||||
class EmbeddedReleaseTest(unittest.TestCase):
|
||||
def test_matching_and_mislabeled_binaries(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
manifest = root / 'release.json'
|
||||
manifest.write_text(json.dumps({'client_version': '5.1.55', 'native_version_code': 5010055}))
|
||||
binary = root / 'client'
|
||||
for output, accepted in [('5.1.55 5010055', True), ('5.1.54 5010054', False), ('5.1.55 5010054', False), ('', False)]:
|
||||
with self.subTest(output=output):
|
||||
binary.write_text('#!/bin/sh\nprintf "%s\\n" "' + output + '"\n')
|
||||
binary.chmod(0o755)
|
||||
if accepted:
|
||||
self.assertEqual(verify(binary, manifest), output)
|
||||
else:
|
||||
with self.assertRaises(ValueError):
|
||||
verify(binary, manifest)
|
||||
|
|
@ -0,0 +1,51 @@
|
|||
# Debian client updater
|
||||
|
||||
One privileged owner implements the existing AppUpdater newline JSON contract
|
||||
on /tmp/itsupdater. Only root and the itscreen UID can connect. No client
|
||||
credentials are sent to Download. Endpoint is fixed to the public Debian feed
|
||||
on git.iomatex.com; redirects and arbitrary download hosts are rejected.
|
||||
|
||||
The platform checkbox is_check_update calls Updater.setActiveUpdate(0|1),
|
||||
which sends set/active_update. The service saves it under
|
||||
/var/lib/iomatex/client-update/settings.json (default off until configured).
|
||||
Enabling triggers a check; recurring interval is 900 seconds. Disabling before
|
||||
installation begins prevents replacement even after a download. Once the client
|
||||
has been stopped, installation or rollback completes regardless of later changes.
|
||||
|
||||
get returns link, period, active_update, installed_version, ready_version,
|
||||
device_id, state_update and progress_download. download_update checks; update
|
||||
manually installs even with automatic updates off. quit cannot terminate the
|
||||
privileged system service. Caller-supplied installed versions are ignored.
|
||||
|
||||
Compare native build first, then release_revision for same-version corrections.
|
||||
If the current binary hash already matches the feed, record provenance without
|
||||
reinstalling. Candidate must have exact size/hash, ARM64 ELF header and matching
|
||||
--version output. /userdata stores candidate/rollback files. Replacement uses a
|
||||
temporary file on the destination filesystem and os.replace. The Console shared
|
||||
installer lock serializes replacement. A stopped/maintenance client is not started.
|
||||
|
||||
Readiness requires the new executable and an X11 client window within 90 seconds.
|
||||
This is a startup check, not a proof of all media playback. Failed startup restores
|
||||
the previous binary. An on-disk transaction also restores it after daemon/OS
|
||||
interruption. The service never reboots the operating system.
|
||||
|
||||
Install: bash stage_itscreen/updater/install.sh (also part of stage_itscreen).
|
||||
Tests: python3 -m unittest discover -s stage_itscreen/updater -p test_client_updater.py
|
||||
State/diagnostics: status.json, installed.json in /var/lib/iomatex/client-update;
|
||||
journalctl -u iomatex-client-updater. Existing Console cloud-registration status
|
||||
continues to query the running client over its existing MQTT contract.
|
||||
|
||||
First deployment requires Console stage 1.0.38; subsequent client updates come
|
||||
from Download. OS/Console updates remain separate. Do not publish an artifact
|
||||
without a successful native --version check. Stage version is not client version.
|
||||
|
||||
## Initial provisioning (OS stage 1.0.39+)
|
||||
|
||||
The stage calls this same owner with `--bootstrap` after installing dependencies
|
||||
and creating the client account/directories. It resolves the public manifest,
|
||||
downloads/validates the current ELF and atomically installs it, even with automatic
|
||||
updates off. It records the actual Download provenance in installed.json; a
|
||||
matching/newer existing client is preserved. The stage retains ownership of
|
||||
service startup and inherits the shared installer lock into this command.
|
||||
Failure aborts the stage; no legacy repository binary is substituted. Historical
|
||||
stage_itscreen/itscreen and provenance are archives only, preserved for old URLs.
|
||||
|
|
@ -0,0 +1,462 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Debian Download channel; existing AppUpdater newline-JSON socket contract."""
|
||||
import fcntl
|
||||
import grp
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
from pathlib import Path
|
||||
import pwd
|
||||
import queue
|
||||
import re
|
||||
import shutil
|
||||
import socket
|
||||
import socketserver
|
||||
import struct
|
||||
import sys
|
||||
import subprocess
|
||||
import tempfile
|
||||
import threading
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
FEED = 'https://git.iomatex.com/An-J/DOWNLOAD_IOMATEX_APP/raw/branch/main/edge-client/debian/latest-iomatex.json'
|
||||
PREFIX = 'https://git.iomatex.com/An-J/DOWNLOAD_IOMATEX_APP/raw/branch/main/edge-client/debian/releases/'
|
||||
BINARY = Path('/opt/itscreen/bin/itscreen')
|
||||
STATE = Path('/var/lib/iomatex/client-update')
|
||||
CACHE = Path('/userdata/iomatex-client-update')
|
||||
LOCK = Path('/run/lock/iomatex-installer.lock')
|
||||
SOCKET = '/tmp/itsupdater'
|
||||
PERIOD = 900
|
||||
|
||||
|
||||
def sync_directory(path):
|
||||
fd = os.open(path, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(fd)
|
||||
finally:
|
||||
os.close(fd)
|
||||
|
||||
|
||||
def write_json(path, data):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
tmp = path.with_suffix('.tmp')
|
||||
with tmp.open('w') as stream:
|
||||
json.dump(data, stream)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(tmp, 0o600)
|
||||
os.replace(tmp, path)
|
||||
sync_directory(path.parent)
|
||||
|
||||
|
||||
def read_json(path):
|
||||
try:
|
||||
return json.loads(path.read_text())
|
||||
except FileNotFoundError:
|
||||
return {}
|
||||
|
||||
|
||||
def digest(path):
|
||||
with path.open('rb') as stream:
|
||||
return hashlib.sha256(stream.read()).hexdigest()
|
||||
|
||||
|
||||
def version_code(version):
|
||||
if not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', version):
|
||||
raise ValueError('Invalid client version')
|
||||
major, minor, patch = map(int, version.split('.'))
|
||||
if major < 5 or minor >= 100 or patch >= 10000:
|
||||
raise ValueError('Unsupported client version')
|
||||
return major * 1000000 + minor * 10000 + patch
|
||||
|
||||
|
||||
def inspect_binary(path):
|
||||
result = subprocess.run([str(path), '--version'], check=True, capture_output=True,
|
||||
text=True, timeout=10)
|
||||
parts = result.stdout.strip().split()
|
||||
if len(parts) != 2 or int(parts[1]) != version_code(parts[0]):
|
||||
raise ValueError('Invalid embedded client version')
|
||||
return parts[0], int(parts[1])
|
||||
|
||||
|
||||
def validate_manifest(data):
|
||||
if (data.get('schema_version') != 1 or data.get('platform') != 'debian'
|
||||
or data.get('architecture') != 'arm64' or data.get('artifact_type') != 'elf'
|
||||
or type(data.get('build_number')) is not int
|
||||
or data['build_number'] != version_code(data.get('version', ''))):
|
||||
raise ValueError('Unsupported release manifest')
|
||||
url = data.get('download_url', '')
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
if (not url.startswith(PREFIX) or parsed.query or parsed.fragment
|
||||
or not re.fullmatch(re.escape(data['version']) + r'(?:-[A-Za-z0-9._-]+)?/itscreen', url[len(PREFIX):])):
|
||||
raise ValueError('Untrusted download URL')
|
||||
if not re.fullmatch(r'[0-9a-f]{64}', data.get('sha256', '')):
|
||||
raise ValueError('Invalid checksum')
|
||||
if type(data.get('size_bytes')) is not int or not 100000 <= data['size_bytes'] <= 128*1024*1024:
|
||||
raise ValueError('Invalid download size')
|
||||
revision = data.get('release_revision', 1)
|
||||
if type(revision) is not int or revision < 1:
|
||||
raise ValueError('Invalid release revision')
|
||||
return dict(data, release_revision=revision)
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
raise ValueError('Update redirect refused')
|
||||
|
||||
|
||||
def open_url(url):
|
||||
req = urllib.request.Request(url, headers={'User-Agent': 'IomatexOS-Updater/1.0'})
|
||||
return urllib.request.build_opener(NoRedirect()).open(req, timeout=30)
|
||||
|
||||
|
||||
class Updater:
|
||||
def __init__(self, binary=BINARY, state=STATE, cache=CACHE, bootstrap=False):
|
||||
self.binary, self.state, self.cache = Path(binary), Path(state), Path(cache)
|
||||
self.state.mkdir(parents=True, exist_ok=True)
|
||||
self.cache.mkdir(parents=True, exist_ok=True)
|
||||
self.mutex = threading.RLock()
|
||||
self.automatic = read_json(self.state/'settings.json').get('active_update', 0) == 1
|
||||
self.pending = queue.Queue(maxsize=1)
|
||||
self.listeners = set()
|
||||
self.phase, self.progress, self.ready = 'init', 0, 0
|
||||
self.busy = False
|
||||
self.error = ''
|
||||
self.device_id = ''
|
||||
if read_json(self.state/'transaction.json'):
|
||||
self.version, self.installed = '', 0
|
||||
else:
|
||||
try:
|
||||
self.version, self.installed = inspect_binary(self.binary)
|
||||
except (OSError, ValueError, subprocess.SubprocessError):
|
||||
if not bootstrap:
|
||||
raise
|
||||
self.version, self.installed = '', 0
|
||||
|
||||
def emit(self, key, value):
|
||||
for handler in list(self.listeners):
|
||||
handler.send(key, value)
|
||||
|
||||
def status(self, phase, error=''):
|
||||
self.phase, self.error = phase, error
|
||||
write_json(self.state/'status.json', {'state_update': phase, 'error': error,
|
||||
'installed_version': self.installed, 'ready_version': self.ready,
|
||||
'checked_at': int(time.time())})
|
||||
self.emit('state_update', phase)
|
||||
|
||||
def set_automatic(self, value):
|
||||
if type(value) is not int or value not in (0, 1):
|
||||
raise ValueError('active_update must be 0 or 1')
|
||||
with self.mutex:
|
||||
self.automatic = bool(value)
|
||||
write_json(self.state/'settings.json', {'active_update': value})
|
||||
self.emit('active_update', value)
|
||||
if value:
|
||||
self.request(False)
|
||||
|
||||
def request(self, manual):
|
||||
if not self.busy:
|
||||
try:
|
||||
self.pending.put_nowait(manual)
|
||||
except queue.Full:
|
||||
pass
|
||||
|
||||
def values(self):
|
||||
return {'link': FEED, 'period': PERIOD, 'installed_version': self.installed,
|
||||
'ready_version': self.ready, 'device_id': self.device_id,
|
||||
'active_update': int(self.automatic), 'state_update': self.phase,
|
||||
'progress_download': self.progress, 'error': self.error, 'busy': self.busy or not self.pending.empty()}
|
||||
|
||||
def newer(self, data):
|
||||
if data['build_number'] != self.installed:
|
||||
return data['build_number'] > self.installed
|
||||
receipt = read_json(self.state/'installed.json')
|
||||
installed_hash = digest(self.binary)
|
||||
revision = receipt.get('release_revision', 0) if (
|
||||
receipt.get('build_number') == self.installed
|
||||
and receipt.get('sha256') == installed_hash) else 0
|
||||
return data['release_revision'] > revision and installed_hash != data['sha256']
|
||||
|
||||
def download(self, data):
|
||||
fd, name = tempfile.mkstemp(prefix='candidate-', dir=self.cache)
|
||||
os.close(fd)
|
||||
target = Path(name)
|
||||
try:
|
||||
with open_url(data['download_url']) as response, target.open('wb') as output:
|
||||
count, checksum = 0, hashlib.sha256()
|
||||
while True:
|
||||
block = response.read(256*1024)
|
||||
if not block:
|
||||
break
|
||||
count += len(block)
|
||||
if count > data['size_bytes']:
|
||||
raise ValueError('Download exceeds expected size')
|
||||
output.write(block)
|
||||
checksum.update(block)
|
||||
self.progress = int(count * 100 / data['size_bytes'])
|
||||
self.emit('progress_download', self.progress)
|
||||
output.flush()
|
||||
os.fsync(output.fileno())
|
||||
if count != data['size_bytes'] or checksum.hexdigest() != data['sha256']:
|
||||
raise ValueError('Download checksum/size mismatch')
|
||||
with target.open('rb') as stream:
|
||||
elf = stream.read(20)
|
||||
if elf[:6] != b'\x7fELF\x02\x01' or elf[18:20] != b'\xb7\x00':
|
||||
raise ValueError('Downloaded file is not ARM64 ELF')
|
||||
target.chmod(0o755)
|
||||
if inspect_binary(target) != (data['version'], data['build_number']):
|
||||
raise ValueError('Embedded version differs from manifest')
|
||||
return target
|
||||
except Exception:
|
||||
target.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
def replace(self, source):
|
||||
# Candidate and destination can be on different filesystems.
|
||||
fd, name = tempfile.mkstemp(prefix='.client-update-', dir=self.binary.parent)
|
||||
try:
|
||||
with os.fdopen(fd, 'wb') as out, source.open('rb') as inp:
|
||||
shutil.copyfileobj(inp, out)
|
||||
out.flush()
|
||||
os.fsync(out.fileno())
|
||||
original = self.binary.stat() if self.binary.exists() else self.binary.parent.stat()
|
||||
os.chown(name, original.st_uid, original.st_gid)
|
||||
os.chmod(name, 0o755)
|
||||
os.replace(name, self.binary)
|
||||
sync_directory(self.binary.parent)
|
||||
finally:
|
||||
Path(name).unlink(missing_ok=True)
|
||||
|
||||
def service(self, action):
|
||||
subprocess.run(['systemctl', action, 'itscreen-x11.service'], check=True,
|
||||
capture_output=True, timeout=90)
|
||||
|
||||
def healthy(self):
|
||||
# Cover the normal X11/Qt startup period and verify this executable is running.
|
||||
expected = digest(self.binary)
|
||||
for _ in range(45):
|
||||
time.sleep(2)
|
||||
for executable in Path('/proc').glob('[0-9]*/exe'):
|
||||
try:
|
||||
if executable.resolve() == self.binary and digest(executable) == expected:
|
||||
# Require a mapped playback window, not just a surviving launcher.
|
||||
result = subprocess.run(['runuser', '-u', 'itscreen', '--', 'env',
|
||||
'DISPLAY=:0', 'XAUTHORITY=/var/lib/itscreen/.Xauthority',
|
||||
'xwininfo', '-root', '-tree'], capture_output=True, text=True, timeout=5)
|
||||
if re.search(r'"it-screen".*\s[1-9][0-9]{2,}x[1-9][0-9]{2,}', result.stdout):
|
||||
return True
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
continue
|
||||
return False
|
||||
|
||||
def recover(self):
|
||||
transaction = read_json(self.state/'transaction.json')
|
||||
if not transaction:
|
||||
return
|
||||
backup = self.cache/'previous'
|
||||
if digest(backup) != transaction['previous_sha256']:
|
||||
raise ValueError('Rollback backup checksum mismatch')
|
||||
self.service('stop')
|
||||
self.replace(backup)
|
||||
self.service('start')
|
||||
(self.state/'transaction.json').unlink()
|
||||
sync_directory(self.state)
|
||||
self.version, self.installed = inspect_binary(self.binary)
|
||||
|
||||
def install(self, candidate, data, manual):
|
||||
with LOCK.open('a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
with self.mutex:
|
||||
if not manual and not self.automatic:
|
||||
self.status('not_permitted')
|
||||
return
|
||||
self.version, self.installed = inspect_binary(self.binary)
|
||||
if not self.newer(data):
|
||||
self.status('not_required')
|
||||
return
|
||||
# Do not start a stopped client (e.g. maintenance desktop mode).
|
||||
if subprocess.run(['systemctl','is-active','--quiet','itscreen-x11']).returncode:
|
||||
self.status('ready')
|
||||
return
|
||||
backup = self.cache/'previous'
|
||||
shutil.copy2(self.binary, backup)
|
||||
with backup.open('rb') as stream:
|
||||
os.fsync(stream.fileno())
|
||||
sync_directory(backup.parent)
|
||||
write_json(self.state/'transaction.json', {'previous_sha256': digest(backup)})
|
||||
self.status('updating')
|
||||
try:
|
||||
self.service('stop')
|
||||
self.replace(candidate)
|
||||
self.service('start')
|
||||
if not self.healthy():
|
||||
raise RuntimeError('Client did not become ready; rolling back')
|
||||
write_json(self.state/'installed.json', data)
|
||||
(self.state/'transaction.json').unlink()
|
||||
sync_directory(self.state)
|
||||
self.version, self.installed = inspect_binary(self.binary)
|
||||
self.emit('installed_version', self.installed)
|
||||
self.status('updated')
|
||||
except Exception:
|
||||
self.recover()
|
||||
raise
|
||||
|
||||
def manifest(self):
|
||||
with open_url(FEED) as response:
|
||||
raw = response.read(65537)
|
||||
if len(raw) > 65536:
|
||||
raise ValueError('Manifest too large')
|
||||
return validate_manifest(json.loads(raw))
|
||||
|
||||
def bootstrap(self):
|
||||
"""Stage owns the installer lock and service lifecycle, regardless of auto flag."""
|
||||
if read_json(self.state/'transaction.json'):
|
||||
raise RuntimeError('Recover interrupted client update before provisioning')
|
||||
data = self.manifest()
|
||||
if self.binary.exists() and not self.newer(data):
|
||||
if digest(self.binary) == data['sha256']:
|
||||
write_json(self.state/'installed.json', data)
|
||||
return {'result': 'preserved', 'version': self.version,
|
||||
'build_number': self.installed, 'feed': FEED}
|
||||
candidate = self.download(data)
|
||||
try:
|
||||
self.replace(candidate)
|
||||
write_json(self.state/'installed.json', data)
|
||||
return {'result': 'installed', 'version': data['version'],
|
||||
'build_number': data['build_number'], 'sha256': data['sha256'],
|
||||
'download_url': data['download_url'], 'feed': FEED}
|
||||
finally:
|
||||
candidate.unlink(missing_ok=True)
|
||||
|
||||
def check(self, install=False, check_only=False):
|
||||
self.busy = True
|
||||
candidate = None
|
||||
try:
|
||||
self.status('check')
|
||||
data = self.manifest()
|
||||
self.ready = data['build_number']
|
||||
self.emit('ready_version', self.ready)
|
||||
self.version, self.installed = inspect_binary(self.binary)
|
||||
if not self.newer(data):
|
||||
if data['build_number'] == self.installed and digest(self.binary) == data['sha256']:
|
||||
write_json(self.state/'installed.json', data)
|
||||
self.status('not_required')
|
||||
return
|
||||
self.status('ready')
|
||||
if check_only or not (install or self.automatic):
|
||||
return
|
||||
self.status('downloading')
|
||||
candidate = self.download(data)
|
||||
self.install(candidate, data, manual=install)
|
||||
except Exception as exc:
|
||||
logging.exception('Client update failed')
|
||||
self.status('error', str(exc))
|
||||
finally:
|
||||
if candidate is not None:
|
||||
candidate.unlink(missing_ok=True)
|
||||
self.busy = False
|
||||
|
||||
def worker(self):
|
||||
while True:
|
||||
try:
|
||||
manual_install = self.pending.get(timeout=PERIOD)
|
||||
self.check(install=manual_install is True, check_only=manual_install == "check_only")
|
||||
except queue.Empty:
|
||||
if self.automatic:
|
||||
self.check()
|
||||
|
||||
|
||||
class Handler(socketserver.StreamRequestHandler):
|
||||
def send(self, key, value):
|
||||
try:
|
||||
with self.write_lock:
|
||||
self.wfile.write((json.dumps({key: value})+'\n').encode())
|
||||
self.wfile.flush()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def handle(self):
|
||||
_, uid, _ = struct.unpack('3i', self.request.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))
|
||||
if uid not in (0, pwd.getpwnam('itscreen').pw_uid):
|
||||
return
|
||||
self.write_lock = threading.Lock()
|
||||
updater = self.server.updater
|
||||
updater.listeners.add(self)
|
||||
try:
|
||||
for key, value in updater.values().items():
|
||||
self.send(key, value)
|
||||
while True:
|
||||
line = self.rfile.readline(65537)
|
||||
if not line or len(line) > 65536:
|
||||
break
|
||||
try:
|
||||
data = json.loads(line)
|
||||
action, key = data.get('action'), data.get('key')
|
||||
if action == 'get' and key == 'snapshot':
|
||||
self.send('snapshot', updater.values())
|
||||
elif action == 'check_only':
|
||||
updater.request('check_only')
|
||||
elif action == 'get' and key in updater.values():
|
||||
self.send(key, updater.values()[key])
|
||||
elif action == 'set' and key == 'active_update':
|
||||
updater.set_automatic(data.get('value'))
|
||||
elif action == 'set' and key == 'device_id':
|
||||
updater.device_id = str(data.get('value', ''))[:128]
|
||||
self.send(key, updater.device_id)
|
||||
elif action == 'set' and key == 'installed_version':
|
||||
# Executable is version authority; never accept caller's version.
|
||||
self.send(key, updater.installed)
|
||||
elif action in ('download_update', 'update'):
|
||||
updater.request(action == 'update')
|
||||
elif action == 'quit':
|
||||
self.send('state_update', updater.phase)
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
self.send('state_update', 'error_info')
|
||||
finally:
|
||||
updater.listeners.discard(self)
|
||||
|
||||
|
||||
class Server(socketserver.ThreadingUnixStreamServer):
|
||||
daemon_threads = True
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
STATE.mkdir(parents=True, exist_ok=True)
|
||||
CACHE.mkdir(parents=True, exist_ok=True)
|
||||
os.chmod(STATE, 0o700)
|
||||
os.chmod(CACHE, 0o700)
|
||||
if sys.argv[1:] == ['--bootstrap']:
|
||||
# Nested stages inherit the existing flock file description. Standalone
|
||||
# invocations acquire the same lock rather than bypassing Console.
|
||||
inherited = os.environ.get('IOMATEX_INSTALL_LOCK_FD', '')
|
||||
if inherited.isdigit() and Path('/proc/self/fd/'+inherited).resolve() == LOCK:
|
||||
fcntl.flock(int(inherited), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
print(json.dumps(Updater(bootstrap=True).bootstrap()))
|
||||
else:
|
||||
with LOCK.open('a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
print(json.dumps(Updater(bootstrap=True).bootstrap()))
|
||||
return
|
||||
if len(sys.argv) != 1:
|
||||
raise ValueError('Usage: client_updater.py [--bootstrap]')
|
||||
updater = Updater()
|
||||
with LOCK.open('a') as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX)
|
||||
updater.recover()
|
||||
Path(SOCKET).unlink(missing_ok=True)
|
||||
with Server(SOCKET, Handler) as server:
|
||||
server.updater = updater
|
||||
os.chown(SOCKET, 0, grp.getgrnam('itscreen').gr_gid)
|
||||
os.chmod(SOCKET, 0o660)
|
||||
threading.Thread(target=updater.worker, daemon=True).start()
|
||||
if updater.automatic:
|
||||
updater.request(False)
|
||||
server.serve_forever()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
updater_source=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
|
||||
install -d -m 0755 -o root -g root /usr/local/lib/iomatex/client-updater
|
||||
install -m 0644 -o root -g root "$updater_source/client_updater.py" /usr/local/lib/iomatex/client-updater/
|
||||
install -m 0644 -o root -g root "$updater_source/iomatex-client-updater.service" /etc/systemd/system/
|
||||
install -d -m 0700 -o root -g root /var/lib/iomatex/client-update /userdata/iomatex-client-update
|
||||
systemctl daemon-reload
|
||||
systemctl enable iomatex-client-updater.service
|
||||
# Installer holds the shared lock. Starting asynchronously lets the daemon wait
|
||||
# for that lock without deadlocking the stage installer.
|
||||
systemctl restart --no-block iomatex-client-updater.service
|
||||
|
|
@ -0,0 +1,18 @@
|
|||
[Unit]
|
||||
Description=EVAx10 Debian client updates from Download
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
RequiresMountsFor=/userdata /opt/itscreen
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/bin/python3 /usr/local/lib/iomatex/client-updater/client_updater.py
|
||||
Restart=on-failure
|
||||
RestartSec=15
|
||||
UMask=0077
|
||||
# QLocalSocket's existing relative itsupdater name resolves in shared /tmp.
|
||||
PrivateTmp=false
|
||||
TimeoutStopSec=120
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
|
|
@ -0,0 +1,238 @@
|
|||
import io
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
import client_updater as c
|
||||
|
||||
|
||||
def executable(path, version):
|
||||
path.write_text('#!/bin/sh\necho "'+version+' '+str(c.version_code(version))+'"\n')
|
||||
path.chmod(0o755)
|
||||
|
||||
|
||||
def manifest():
|
||||
return {'schema_version':1, 'platform':'debian','architecture':'arm64',
|
||||
'artifact_type':'elf','version':'5.1.55','build_number':5010055,
|
||||
'release_revision':2,'size_bytes':100000,'sha256':'a'*64,
|
||||
'download_url':c.PREFIX+'5.1.55-r2/itscreen'}
|
||||
|
||||
|
||||
class TestUpdater(unittest.TestCase):
|
||||
def test_manifest_requests_use_updater_user_agent(self):
|
||||
opener = unittest.mock.Mock()
|
||||
opener.open.return_value = io.BytesIO(json.dumps(manifest()).encode())
|
||||
with patch.object(c.urllib.request, 'build_opener', return_value=opener):
|
||||
data = self.u.manifest()
|
||||
request = opener.open.call_args.args[0]
|
||||
self.assertEqual(c.FEED, request.full_url)
|
||||
self.assertEqual('IomatexOS-Updater/1.0', request.get_header('User-agent'))
|
||||
self.assertTrue(data['download_url'].startswith(c.PREFIX))
|
||||
|
||||
def test_feed_matches_strict_canonical_download_host(self):
|
||||
# Legacy latest.json intentionally keeps git.it-screen.com URLs.
|
||||
self.assertEqual(c.PREFIX.rsplit('/releases/', 1)[0] + '/latest-iomatex.json', c.FEED)
|
||||
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.tmp.cleanup)
|
||||
self.root = Path(self.tmp.name)
|
||||
self.binary = self.root/'itscreen'
|
||||
executable(self.binary, '5.1.54')
|
||||
self.u = c.Updater(self.binary,self.root/'state',self.root/'cache')
|
||||
|
||||
def test_console_check_never_installs_even_with_automatic_enabled(self):
|
||||
self.u.automatic = True
|
||||
with patch.object(self.u, 'manifest', return_value=manifest()), patch.object(self.u, 'download') as download:
|
||||
self.u.check(check_only=True)
|
||||
download.assert_not_called()
|
||||
self.assertEqual(self.u.phase, 'ready')
|
||||
self.assertTrue(self.u.automatic)
|
||||
self.assertEqual(self.u.values()['ready_version'], 5010055)
|
||||
|
||||
def test_console_pending_request_is_busy(self):
|
||||
self.u.request('check_only')
|
||||
self.assertTrue(self.u.values()['busy'])
|
||||
self.assertEqual(self.u.pending.get_nowait(), 'check_only')
|
||||
self.assertFalse(self.u.values()['busy'])
|
||||
|
||||
def test_socket_checkbox_and_fragmented_frames(self):
|
||||
import os
|
||||
import socket
|
||||
import threading
|
||||
from types import SimpleNamespace
|
||||
path = str(self.root/'socket')
|
||||
with patch.object(c.pwd,'getpwnam',return_value=SimpleNamespace(pw_uid=os.getuid())):
|
||||
with c.Server(path,c.Handler) as server:
|
||||
server.updater=self.u
|
||||
thread=threading.Thread(target=server.serve_forever,daemon=True)
|
||||
thread.start()
|
||||
try:
|
||||
with socket.socket(socket.AF_UNIX) as client:
|
||||
client.settimeout(3);client.connect(path)
|
||||
stream=client.makefile('rwb',buffering=0)
|
||||
initial={}
|
||||
for _ in range(len(self.u.values())):initial.update(json.loads(stream.readline()))
|
||||
self.assertEqual(initial['active_update'],0)
|
||||
stream.write(b'{"action":"get","key":"snapshot"}\n')
|
||||
self.assertEqual(json.loads(stream.readline())['snapshot']['installed_version'],5010054)
|
||||
stream.write(b'{"action":"set","key":"active_')
|
||||
stream.write(b'update","value":1}\n')
|
||||
self.assertEqual(json.loads(stream.readline()),{'active_update':1})
|
||||
self.assertTrue(c.Updater(self.binary,self.u.state,self.u.cache).automatic)
|
||||
stream.write(b'{"action":"set","key":"active_update","value":0}\n')
|
||||
self.assertEqual(json.loads(stream.readline()),{'active_update':0})
|
||||
self.assertFalse(c.Updater(self.binary,self.u.state,self.u.cache).automatic)
|
||||
finally:
|
||||
server.shutdown();thread.join()
|
||||
|
||||
def test_first_install_from_download_even_with_automatic_off(self):
|
||||
self.binary.unlink()
|
||||
u=c.Updater(self.binary,self.u.state,self.u.cache,bootstrap=True)
|
||||
candidate=self.root/'new';executable(candidate,'5.1.55')
|
||||
data=manifest();data['sha256']=c.digest(candidate)
|
||||
with patch.object(u,'manifest',return_value=data),patch.object(u,'download',return_value=candidate):
|
||||
self.assertEqual(u.bootstrap()['result'],'installed')
|
||||
self.assertEqual(c.inspect_binary(self.binary),('5.1.55',5010055))
|
||||
self.assertFalse(u.automatic)
|
||||
self.assertEqual(c.read_json(u.state/'installed.json')['sha256'],c.digest(self.binary))
|
||||
self.assertFalse(candidate.exists())
|
||||
|
||||
def test_bootstrap_preserves_newer_and_matching_install(self):
|
||||
for version in ['5.1.55','5.1.56']:
|
||||
executable(self.binary,version)
|
||||
u=c.Updater(self.binary,self.u.state,self.u.cache,bootstrap=True)
|
||||
data=manifest();data['sha256']=c.digest(self.binary)
|
||||
with patch.object(u,'manifest',return_value=data),patch.object(u,'download') as download:
|
||||
self.assertEqual(u.bootstrap()['result'],'preserved')
|
||||
download.assert_not_called()
|
||||
self.assertEqual(c.inspect_binary(self.binary)[0],version)
|
||||
|
||||
def test_bootstrap_network_failure_preserves_existing_or_absent_binary(self):
|
||||
before=self.binary.read_bytes()
|
||||
with patch.object(self.u,'manifest',side_effect=OSError('offline')):
|
||||
with self.assertRaises(OSError):self.u.bootstrap()
|
||||
self.assertEqual(self.binary.read_bytes(),before)
|
||||
self.binary.unlink()
|
||||
u=c.Updater(self.binary,self.u.state,self.u.cache,bootstrap=True)
|
||||
with patch.object(u,'manifest',side_effect=OSError('offline')):
|
||||
with self.assertRaises(OSError):u.bootstrap()
|
||||
self.assertFalse(self.binary.exists())
|
||||
|
||||
def test_bootstrap_rejects_bad_binary_before_replacement(self):
|
||||
before=self.binary.read_bytes()
|
||||
with patch.object(self.u,'manifest',return_value=manifest()),patch.object(c,'open_url',return_value=io.BytesIO(b'bad')):
|
||||
with self.assertRaises(ValueError):self.u.bootstrap()
|
||||
self.assertEqual(self.binary.read_bytes(),before)
|
||||
|
||||
def test_bootstrap_stage_uses_shared_download_owner(self):
|
||||
stage=Path(__file__).resolve().parents[1]/'stage_itscreen_install.sh'
|
||||
if not stage.exists():self.skipTest('source contract runs in full checkout')
|
||||
source=stage.read_text().split('install_itscreen_binary() (',1)[1].split('\n)',1)[0]
|
||||
self.assertIn('updater/client_updater.py" --bootstrap',source)
|
||||
self.assertNotIn('git_delivery.py',source)
|
||||
self.assertNotIn('verify_client_release.py',source)
|
||||
|
||||
def test_manifest_rejects_untrusted_or_wrong_platform(self):
|
||||
self.assertEqual(c.validate_manifest(manifest())['build_number'],5010055)
|
||||
for key,value in [('download_url',c.PREFIX+'../itscreen'),
|
||||
('download_url','https://git.it-screen.com/a'),
|
||||
('download_url',c.PREFIX+'ok/itscreen?redirect=x'),
|
||||
('architecture','x86_64'),('build_number',5010054),
|
||||
('size_bytes',True),('sha256','bad'),('release_revision',0)]:
|
||||
with self.subTest(key=key,value=value):
|
||||
data=manifest();data[key]=value
|
||||
with self.assertRaises(ValueError): c.validate_manifest(data)
|
||||
|
||||
def test_redirect_refused(self):
|
||||
with self.assertRaises(ValueError):
|
||||
c.NoRedirect().redirect_request(None,None,302,'',{},'https://git.it-screen.com')
|
||||
|
||||
def test_flag_persists_and_does_not_accept_other_values(self):
|
||||
self.u.set_automatic(1)
|
||||
self.assertTrue(c.Updater(self.binary,self.u.state,self.u.cache).automatic)
|
||||
self.u.set_automatic(0)
|
||||
self.assertFalse(c.Updater(self.binary,self.u.state,self.u.cache).automatic)
|
||||
for v in [True,2,'1',None]:
|
||||
with self.assertRaises(ValueError):self.u.set_automatic(v)
|
||||
|
||||
def test_check_only_when_off_and_auto_when_on(self):
|
||||
with patch.object(c,'open_url',return_value=io.BytesIO(json.dumps(manifest()).encode())), patch.object(self.u,'download') as download:
|
||||
self.u.check()
|
||||
download.assert_not_called()
|
||||
self.assertEqual(self.u.phase,'ready')
|
||||
self.u.automatic=True
|
||||
with patch.object(c,'open_url',return_value=io.BytesIO(json.dumps(manifest()).encode())), patch.object(self.u,'download',return_value=self.binary), patch.object(self.u,'install') as install:
|
||||
self.u.check();install.assert_called_once()
|
||||
|
||||
def test_no_downgrade_or_repeat_and_revision_correction(self):
|
||||
data=manifest();self.u.installed=5010056
|
||||
self.assertFalse(self.u.newer(data))
|
||||
self.u.installed=5010055
|
||||
self.assertTrue(self.u.newer(data))
|
||||
c.write_json(self.u.state/'installed.json',dict(data,sha256=c.digest(self.binary)))
|
||||
self.assertFalse(self.u.newer(data))
|
||||
data['release_revision']=3
|
||||
self.assertTrue(self.u.newer(data))
|
||||
data['sha256']=c.digest(self.binary)
|
||||
self.assertFalse(self.u.newer(data))
|
||||
|
||||
def test_bad_download_leaves_installed_binary(self):
|
||||
before=self.binary.read_bytes()
|
||||
with patch.object(c,'open_url',return_value=io.BytesIO(b'bad')):
|
||||
with self.assertRaises(ValueError):self.u.download(manifest())
|
||||
self.assertEqual(self.binary.read_bytes(),before)
|
||||
self.assertFalse((self.u.cache/'candidate').exists())
|
||||
|
||||
def test_verified_elf_and_embedded_version(self):
|
||||
data=manifest();content=bytearray(data['size_bytes'])
|
||||
content[:6]=b'\x7fELF\x02\x01';content[18:20]=b'\xb7\x00'
|
||||
data['sha256']=c.hashlib.sha256(content).hexdigest()
|
||||
with patch.object(c,'open_url',return_value=io.BytesIO(content)),patch.object(c,'inspect_binary',return_value=('5.1.55',5010055)):
|
||||
self.assertEqual(self.u.download(data).read_bytes(),content)
|
||||
with patch.object(c,'open_url',return_value=io.BytesIO(content)),patch.object(c,'inspect_binary',return_value=('5.1.54',5010054)):
|
||||
with self.assertRaises(ValueError):self.u.download(data)
|
||||
|
||||
def test_disabling_after_download_prevents_install(self):
|
||||
with patch.object(c,'LOCK',self.root/'lock'),patch.object(self.u,'service') as service:
|
||||
self.u.install(self.binary,manifest(),False)
|
||||
service.assert_not_called()
|
||||
self.assertEqual(self.u.phase,'not_permitted')
|
||||
|
||||
def perform_install(self, healthy):
|
||||
candidate=self.root/'candidate';executable(candidate,'5.1.55')
|
||||
data=manifest();data['sha256']=c.digest(candidate)
|
||||
run=subprocess.run
|
||||
def local_run(args,**kwargs):
|
||||
if args[0]=='systemctl':return subprocess.CompletedProcess(args,0)
|
||||
return run(args,**kwargs)
|
||||
with patch.object(c,'LOCK',self.root/'lock'),patch.object(c.subprocess,'run',side_effect=local_run),patch.object(self.u,'service') as service,patch.object(self.u,'healthy',return_value=healthy):
|
||||
if healthy:self.u.install(candidate,data,True)
|
||||
else:
|
||||
with self.assertRaises(RuntimeError):self.u.install(candidate,data,True)
|
||||
return service.call_args_list
|
||||
|
||||
def test_manual_install_when_off(self):
|
||||
self.perform_install(True)
|
||||
self.assertEqual(c.inspect_binary(self.binary),('5.1.55',5010055))
|
||||
self.assertEqual(self.u.phase,'updated')
|
||||
self.assertFalse((self.u.state/'transaction.json').exists())
|
||||
|
||||
def test_failed_health_rolls_back(self):
|
||||
before=self.binary.read_bytes();self.perform_install(False)
|
||||
self.assertEqual(self.binary.read_bytes(),before)
|
||||
self.assertEqual(c.inspect_binary(self.binary),('5.1.54',5010054))
|
||||
self.assertFalse((self.u.state/'transaction.json').exists())
|
||||
|
||||
def test_recovery_after_interruption(self):
|
||||
backup=self.u.cache/'previous';executable(backup,'5.1.54')
|
||||
c.write_json(self.u.state/'transaction.json',{'previous_sha256':c.digest(backup)})
|
||||
executable(self.binary,'5.1.55')
|
||||
u=c.Updater(self.binary,self.u.state,self.u.cache)
|
||||
with patch.object(u,'service'):u.recover()
|
||||
self.assertEqual(c.inspect_binary(self.binary),('5.1.54',5010054))
|
||||
|
||||
|
||||
if __name__=='__main__':unittest.main()
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Embedded-version check for archived release provenance."""
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from updater.client_updater import inspect_binary, read_json
|
||||
|
||||
|
||||
def verify(binary, provenance):
|
||||
metadata = read_json(Path(provenance))
|
||||
actual = inspect_binary(Path(binary))
|
||||
expected = (metadata['client_version'], metadata['native_version_code'])
|
||||
if actual != expected:
|
||||
raise ValueError(f'Client release mismatch: expected {expected!r}, got {actual!r}')
|
||||
return f'{actual[0]} {actual[1]}'
|
||||
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(verify(sys.argv[1], sys.argv[2]))
|
||||
|
|
@ -1,3 +1,3 @@
|
|||
{
|
||||
"version": "1.0.33"
|
||||
"version": "1.0.42"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -65,3 +65,14 @@ never reports success. The firmware's power-cycle persistence is not asserted.
|
|||
|
||||
UI uses existing field/select/actionRow/card classes and the shared body-mounted
|
||||
confirmation dialog. No new CSS or independent modal/serial transport is added.
|
||||
|
||||
## Debian client updates (Console 3.1.32)
|
||||
|
||||
The It-Screen panel uses authenticated GET/POST `/api/itscreen/update`.
|
||||
`client_update_request` only adapts the existing `/tmp/itsupdater` socket;
|
||||
`stage_itscreen/updater/client_updater.py` remains the single owner for feed
|
||||
validation, version comparison, download, install locking and rollback.
|
||||
GET reads a local snapshot; POST allowlists `check_only` and `update`.
|
||||
Opening the tab checks without installation or changing the automatic flag.
|
||||
The panel polls local state and replaces only its own markup, preserving form
|
||||
focus and edits elsewhere. Stage 1.0.40 supplies the extended socket contract.
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
#!/usr/bin/env python3
|
||||
import glob
|
||||
import hashlib
|
||||
import base64
|
||||
import importlib.util
|
||||
import ipaddress
|
||||
|
|
@ -21,6 +22,7 @@ import time
|
|||
import wave
|
||||
import crypt
|
||||
import spwd
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from datetime import datetime
|
||||
from http.cookies import SimpleCookie
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
|
@ -60,7 +62,7 @@ APP_DIR = "/opt/iomatex-console"
|
|||
PUBLIC_DIR = os.path.join(APP_DIR, "public")
|
||||
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
|
||||
CONFIG_PATH = "/etc/iomatex/console.json"
|
||||
UI_VERSION = "V 3.1.28"
|
||||
UI_VERSION = "V 3.1.42"
|
||||
STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health"
|
||||
ZONEINFO_ROOT = "/usr/share/zoneinfo"
|
||||
|
||||
|
|
@ -68,13 +70,11 @@ DEFAULT_CONFIG = {
|
|||
"bind": "0.0.0.0",
|
||||
"port": 80,
|
||||
"extra_ports": [],
|
||||
"cache_ttl_sec": 3,
|
||||
"cache_ttl_sec": 15,
|
||||
}
|
||||
|
||||
_CACHE = {"expires_at": 0.0, "payload": None}
|
||||
_HEALTH_SERVICES_CACHE = {"expires_at": 0.0, "payload": None}
|
||||
_CACHE_LOCK = threading.Lock()
|
||||
_HEALTH_SERVICES_CACHE_LOCK = threading.Lock()
|
||||
_CPU_SAMPLE = {"total": None, "idle": None}
|
||||
_NET_SAMPLE = {}
|
||||
_WIFI_SCAN_CACHE = {"expires_at": 0.0, "payload": None}
|
||||
|
|
@ -168,6 +168,9 @@ STATIC_NO_CACHE_HEADERS = {
|
|||
"Cache-Control": "no-store, no-cache, must-revalidate",
|
||||
"Pragma": "no-cache",
|
||||
}
|
||||
STATIC_ASSET_CACHE_HEADERS = {
|
||||
"Cache-Control": "public, max-age=31536000, immutable",
|
||||
}
|
||||
_AUTH_SESSIONS = {}
|
||||
_AUTH_SESSIONS_LOCK = threading.Lock()
|
||||
CAMERA_PREVIEW_PATH_RE = re.compile(
|
||||
|
|
@ -237,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
|
||||
|
||||
|
||||
|
|
@ -1529,8 +1533,6 @@ def ap_status_card():
|
|||
def invalidate_cache():
|
||||
_CACHE["payload"] = None
|
||||
_CACHE["expires_at"] = 0.0
|
||||
_HEALTH_SERVICES_CACHE["payload"] = None
|
||||
_HEALTH_SERVICES_CACHE["expires_at"] = 0.0
|
||||
_ITSCREEN_STATUS_CACHE["payload"] = None
|
||||
_ITSCREEN_STATUS_CACHE["expires_at"] = 0.0
|
||||
|
||||
|
|
@ -2048,7 +2050,7 @@ def summarize_interface(iface, kind="ethernet"):
|
|||
}
|
||||
|
||||
|
||||
def get_network_summary(include_service_cards=True):
|
||||
def get_network_summary(include_service_cards=True, force_provider_refresh=False):
|
||||
iface = get_primary_interface()
|
||||
profile = read_wifi_profile_state()
|
||||
script_status = parse_wifi_status_script()
|
||||
|
|
@ -2075,7 +2077,7 @@ def get_network_summary(include_service_cards=True):
|
|||
}
|
||||
avahi_card = None
|
||||
if include_service_cards:
|
||||
cards, _ = collect_provider_cards(build_provider_context())
|
||||
cards = build_status_payload(force=force_provider_refresh).get("services", [])
|
||||
avahi_card = next((card for card in cards if card.get("id") == "avahi"), None)
|
||||
return {
|
||||
"ok": True,
|
||||
|
|
@ -2526,9 +2528,11 @@ def build_provider_context():
|
|||
|
||||
def collect_provider_cards(context, entrypoint="get_cards"):
|
||||
cards = []
|
||||
provider_names = []
|
||||
for path, provider in load_providers(entrypoint):
|
||||
provider_names.append(os.path.basename(path))
|
||||
providers = load_providers(entrypoint)
|
||||
provider_names = [os.path.basename(path) for path, _provider in providers]
|
||||
|
||||
def collect(item):
|
||||
path, provider = item
|
||||
try:
|
||||
result = provider(context)
|
||||
except Exception as exc:
|
||||
|
|
@ -2545,20 +2549,24 @@ def collect_provider_cards(context, entrypoint="get_cards"):
|
|||
}]
|
||||
if isinstance(result, dict):
|
||||
result = [result]
|
||||
for card in result or []:
|
||||
cards.append(normalize_card(card))
|
||||
return [normalize_card(card) for card in result or []]
|
||||
|
||||
if providers:
|
||||
with ThreadPoolExecutor(max_workers=min(4, len(providers)), thread_name_prefix="console-provider") as executor:
|
||||
for result in executor.map(collect, providers):
|
||||
cards.extend(result)
|
||||
return cards, provider_names
|
||||
|
||||
|
||||
def build_status_payload():
|
||||
def build_status_payload(force=False):
|
||||
now = time.time()
|
||||
cfg = load_config()
|
||||
if _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
|
||||
if not force and _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
|
||||
return _CACHE["payload"]
|
||||
|
||||
with _CACHE_LOCK:
|
||||
now = time.time()
|
||||
if _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
|
||||
if not force and _CACHE["payload"] is not None and now < _CACHE["expires_at"]:
|
||||
return _CACHE["payload"]
|
||||
|
||||
cards, provider_names = collect_provider_cards(build_provider_context())
|
||||
|
|
@ -2570,7 +2578,7 @@ def build_status_payload():
|
|||
"providers": provider_names,
|
||||
}
|
||||
_CACHE["payload"] = payload
|
||||
_CACHE["expires_at"] = time.time() + max(1, int(cfg.get("cache_ttl_sec", 3)))
|
||||
_CACHE["expires_at"] = time.time() + max(1, int(cfg.get("cache_ttl_sec", 15)))
|
||||
return payload
|
||||
|
||||
|
||||
|
|
@ -2694,40 +2702,27 @@ def build_runtime_profile_payload():
|
|||
}
|
||||
|
||||
|
||||
def build_health_services_payload():
|
||||
now = time.time()
|
||||
cfg = load_config()
|
||||
if _HEALTH_SERVICES_CACHE["payload"] is not None and now < _HEALTH_SERVICES_CACHE["expires_at"]:
|
||||
return _HEALTH_SERVICES_CACHE["payload"]
|
||||
|
||||
with _HEALTH_SERVICES_CACHE_LOCK:
|
||||
now = time.time()
|
||||
if _HEALTH_SERVICES_CACHE["payload"] is not None and now < _HEALTH_SERVICES_CACHE["expires_at"]:
|
||||
return _HEALTH_SERVICES_CACHE["payload"]
|
||||
|
||||
allowed_ids = {
|
||||
"itscreen",
|
||||
"mosquitto",
|
||||
"mqtt_bridge",
|
||||
"zigbee2mqtt",
|
||||
"cockpit",
|
||||
"reverse_tunnel",
|
||||
"display",
|
||||
"edge_api",
|
||||
"ip_stream",
|
||||
"environment",
|
||||
"console",
|
||||
}
|
||||
cards, _ = collect_provider_cards(build_provider_context())
|
||||
payload = {
|
||||
"ok": True,
|
||||
"generated_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),
|
||||
"identity": get_identity_payload(),
|
||||
"services": [card for card in cards if card.get("id") in allowed_ids],
|
||||
}
|
||||
_HEALTH_SERVICES_CACHE["payload"] = payload
|
||||
_HEALTH_SERVICES_CACHE["expires_at"] = time.time() + max(1, int(cfg.get("cache_ttl_sec", 3)))
|
||||
return payload
|
||||
def build_health_services_payload(force=False):
|
||||
allowed_ids = {
|
||||
"itscreen",
|
||||
"mosquitto",
|
||||
"mqtt_bridge",
|
||||
"zigbee2mqtt",
|
||||
"cockpit",
|
||||
"reverse_tunnel",
|
||||
"display",
|
||||
"edge_api",
|
||||
"ip_stream",
|
||||
"environment",
|
||||
"console",
|
||||
}
|
||||
status = build_status_payload(force=force)
|
||||
return {
|
||||
"ok": True,
|
||||
"generated_at": status.get("generated_at", ""),
|
||||
"identity": status.get("identity", {}),
|
||||
"services": [card for card in status.get("services", []) if card.get("id") in allowed_ids],
|
||||
}
|
||||
|
||||
|
||||
def find_service_card(service_id):
|
||||
|
|
@ -2977,6 +2972,38 @@ def get_itscreen_binary_candidates():
|
|||
return [path for path in candidates if os.path.exists(path)]
|
||||
|
||||
|
||||
def fingerprint_console_assets(html, directory):
|
||||
"""Invalidate browser assets on content changes, including same-version deploys."""
|
||||
text = html.decode("utf-8")
|
||||
for name in ("console.js", "console.i18n.js", "console.css"):
|
||||
with open(os.path.join(directory, name), "rb") as stream:
|
||||
fingerprint = hashlib.sha256(stream.read()).hexdigest()[:16]
|
||||
pattern = r'(["\'])/' + re.escape(name) + r'(?:\?[^"\']*)?(["\'])'
|
||||
text = re.sub(pattern, lambda match: match[1] + "/" + name + "?sha=" + fingerprint + match[2], text)
|
||||
return text.encode("utf-8")
|
||||
|
||||
|
||||
def client_update_request(action=None):
|
||||
"""Console adapter only: the privileged updater owns feeds and installation."""
|
||||
if action not in (None, "check_only", "update"):
|
||||
raise ValueError("Invalid client update action")
|
||||
with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as connection:
|
||||
connection.settimeout(3)
|
||||
connection.connect("/tmp/itsupdater")
|
||||
if action:
|
||||
connection.sendall((json.dumps({"action": action}) + "\n").encode())
|
||||
connection.sendall(b'{"action":"get","key":"snapshot"}\n')
|
||||
with connection.makefile("rb") as stream:
|
||||
for _ in range(32):
|
||||
line = stream.readline(65537)
|
||||
if not line or len(line) > 65536:
|
||||
break
|
||||
payload = json.loads(line)
|
||||
if "snapshot" in payload:
|
||||
return {"ok": True, **payload["snapshot"]}
|
||||
raise RuntimeError("Client updater is unavailable; update the It-Screen system stage")
|
||||
|
||||
|
||||
def get_itscreen_app_version():
|
||||
version_re = re.compile(r"\b(\d+\.\d+\.\d+(?:\.\d+)?)\b")
|
||||
for binary_path in get_itscreen_binary_candidates():
|
||||
|
|
@ -3453,6 +3480,8 @@ class Handler(BaseHTTPRequestHandler):
|
|||
except FileNotFoundError:
|
||||
self.send_error(404)
|
||||
return
|
||||
if os.path.basename(path) == "index.html":
|
||||
data = fingerprint_console_assets(data, os.path.dirname(path))
|
||||
self.send_response(200)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
|
|
@ -3623,7 +3652,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
)
|
||||
return
|
||||
if parsed.path == "/api/status":
|
||||
self.send_json(build_status_payload())
|
||||
self.send_json(build_status_payload(force=query.get("refresh", ["0"])[0] == "1"))
|
||||
return
|
||||
if parsed.path == "/api/display":
|
||||
payload = find_service_card("display")
|
||||
|
|
@ -3634,7 +3663,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
return
|
||||
if parsed.path == "/api/health/services":
|
||||
try:
|
||||
payload = build_health_services_payload()
|
||||
payload = build_health_services_payload(force=query.get("refresh", ["0"])[0] == "1")
|
||||
cards = [dict(card) for card in payload["services"]]
|
||||
updates = stage_versions.snapshot(cards)
|
||||
for card in cards:
|
||||
|
|
@ -3683,7 +3712,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
if parsed.path == "/api/network/summary":
|
||||
try:
|
||||
self.send_json({
|
||||
**get_network_summary(),
|
||||
**get_network_summary(force_provider_refresh=query.get("refresh", ["0"])[0] == "1"),
|
||||
"identity": get_identity_payload(),
|
||||
})
|
||||
except Exception as exc:
|
||||
|
|
@ -3729,6 +3758,12 @@ class Handler(BaseHTTPRequestHandler):
|
|||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=500)
|
||||
return
|
||||
if parsed.path == "/api/itscreen/update":
|
||||
try:
|
||||
self.send_json(client_update_request())
|
||||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=503)
|
||||
return
|
||||
if parsed.path == "/api/itscreen/status":
|
||||
try:
|
||||
self.send_json(build_itscreen_status_payload())
|
||||
|
|
@ -3778,13 +3813,13 @@ class Handler(BaseHTTPRequestHandler):
|
|||
self.send_file(os.path.join(PUBLIC_DIR, "index.html"), "text/html; charset=utf-8", extra_headers=STATIC_NO_CACHE_HEADERS)
|
||||
return
|
||||
if parsed.path == "/console.css":
|
||||
self.send_file(os.path.join(PUBLIC_DIR, "console.css"), "text/css; charset=utf-8", extra_headers=STATIC_NO_CACHE_HEADERS)
|
||||
self.send_file(os.path.join(PUBLIC_DIR, "console.css"), "text/css; charset=utf-8", extra_headers=STATIC_ASSET_CACHE_HEADERS if "sha" in query else STATIC_NO_CACHE_HEADERS)
|
||||
return
|
||||
if parsed.path == "/console.i18n.js":
|
||||
self.send_file(os.path.join(PUBLIC_DIR, "console.i18n.js"), "application/javascript; charset=utf-8", extra_headers=STATIC_NO_CACHE_HEADERS)
|
||||
self.send_file(os.path.join(PUBLIC_DIR, "console.i18n.js"), "application/javascript; charset=utf-8", extra_headers=STATIC_ASSET_CACHE_HEADERS if "sha" in query else STATIC_NO_CACHE_HEADERS)
|
||||
return
|
||||
if parsed.path == "/console.js":
|
||||
self.send_file(os.path.join(PUBLIC_DIR, "console.js"), "application/javascript; charset=utf-8", extra_headers=STATIC_NO_CACHE_HEADERS)
|
||||
self.send_file(os.path.join(PUBLIC_DIR, "console.js"), "application/javascript; charset=utf-8", extra_headers=STATIC_ASSET_CACHE_HEADERS if "sha" in query else STATIC_NO_CACHE_HEADERS)
|
||||
return
|
||||
if parsed.path == "/logo.png":
|
||||
self.send_file(os.path.join(PUBLIC_DIR, "logo.png"), "image/png")
|
||||
|
|
@ -3827,6 +3862,16 @@ class Handler(BaseHTTPRequestHandler):
|
|||
return
|
||||
if not self.require_auth(parsed):
|
||||
return
|
||||
if parsed.path == "/api/itscreen/update":
|
||||
payload = self.read_json_body()
|
||||
if not isinstance(payload, dict) or payload.get("action") not in ("check_only", "update"):
|
||||
self.send_json({"ok": False, "error": "Invalid update action"}, code=400)
|
||||
return
|
||||
try:
|
||||
self.send_json(client_update_request(payload["action"]))
|
||||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=503)
|
||||
return
|
||||
if parsed.path == "/api/onvif/probe":
|
||||
payload = self.read_json_body()
|
||||
if payload is None:
|
||||
|
|
@ -3949,6 +3994,18 @@ class Handler(BaseHTTPRequestHandler):
|
|||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=503)
|
||||
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":
|
||||
payload = self.read_json_body()
|
||||
stream_id = str((payload or {}).get("stream_id", ""))
|
||||
|
|
|
|||
|
|
@ -0,0 +1,21 @@
|
|||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const vm = require('node:vm');
|
||||
const source = fs.readFileSync(__dirname + '/../frontend/console.js', 'utf8');
|
||||
const ctx = {state: {itscreen: {}}, t: s => s, esc: s => String(s).replaceAll('<', '<')};
|
||||
vm.createContext(ctx);
|
||||
vm.runInContext(source.slice(source.indexOf(' function clientVersion('), source.indexOf(' async function loadClientUpdate(')), ctx);
|
||||
for (const [phase, label] of [['ready', 'A new client version'], ['not_required', 'latest client version'], ['updating', 'Installing client'], ['error', 'Client update failed']]) {
|
||||
ctx.state.itscreen.update = {state_update: phase, installed_version: 5010055, ready_version: 5010056, error: phase === 'error' ? '<error>' : '', busy: phase === 'updating'};
|
||||
const html = ctx.renderClientUpdate();
|
||||
assert.ok(html.includes(label));
|
||||
assert.ok(html.includes('5.1.55'));
|
||||
assert.ok(html.includes('5.1.56'));
|
||||
assert.equal(html.includes(' disabled '), phase === 'updating');
|
||||
assert.ok(!html.includes('<error>'));
|
||||
}
|
||||
assert.ok(source.includes('panel.innerHTML = renderClientUpdate()'), 'Polling updates only the updater panel, preserving form edits');
|
||||
assert.ok(source.includes('["health", "tscreen"].includes(state.activeTab)'), 'Health profile and It-Screen tab share the update owner');
|
||||
assert.equal((source.match(/id="itscreenClientUpdate"/g) || []).length, 2, 'Both views expose the shared client update panel');
|
||||
assert.ok(source.includes('Client update system module'), 'Technical stage is explicitly distinguished from the client version');
|
||||
console.log('Client update versions, available/current/error/busy states and local panel rendering passed');
|
||||
|
|
@ -0,0 +1,39 @@
|
|||
import ast
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
source = Path(__file__).with_name('app.py').read_text()
|
||||
node = next(n for n in ast.parse(source).body if isinstance(n, ast.FunctionDef) and n.name == 'fingerprint_console_assets')
|
||||
namespace = dict(hashlib=hashlib, os=os, re=re)
|
||||
exec(compile(ast.Module(body=[node], type_ignores=[]), '<asset-owner>', 'exec'), namespace)
|
||||
|
||||
class AssetVersionTest(unittest.TestCase):
|
||||
def test_same_release_changed_content_gets_new_url(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
for name in ('console.js', 'console.i18n.js', 'console.css'):
|
||||
Path(directory, name).write_text('original')
|
||||
html = b'<script src="/console.js?v=3.1.32&rev=old"></script><link href="/console.css?v=3.1.32">'
|
||||
render = lambda: namespace['fingerprint_console_assets'](html, directory)
|
||||
first = render()
|
||||
self.assertIn(b'?sha=', first)
|
||||
self.assertNotIn(b'rev=old', first)
|
||||
self.assertEqual(first, render())
|
||||
Path(directory, 'console.js').write_text('new same-version bundle')
|
||||
self.assertNotEqual(first, render())
|
||||
self.assertEqual(first.split(b'<link')[1], render().split(b'<link')[1])
|
||||
|
||||
def test_html_response_uses_shared_asset_owner(self):
|
||||
handler = source.split(' def send_file(', 1)[1].split(' def send_sse_headers', 1)[0]
|
||||
self.assertIn('fingerprint_console_assets(data, os.path.dirname(path))', handler)
|
||||
self.assertLess(handler.index('fingerprint_console_assets'), handler.index('Content-Length'))
|
||||
|
||||
def test_fingerprinted_assets_are_immutable(self):
|
||||
self.assertIn('"Cache-Control": "public, max-age=31536000, immutable"', source)
|
||||
route = source.split('if parsed.path == "/console.css":', 1)[1].split('if parsed.path == "/logo.png":', 1)[0]
|
||||
self.assertEqual(3, route.count('STATIC_ASSET_CACHE_HEADERS if "sha" in query else STATIC_NO_CACHE_HEADERS'))
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
|
|
@ -1,6 +1,8 @@
|
|||
import importlib.util
|
||||
import pathlib
|
||||
import threading
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
|
||||
PROVIDER_PATH = pathlib.Path(__file__).resolve().parents[1] / "providers" / "00_core_services.py"
|
||||
|
|
@ -10,6 +12,26 @@ SPEC.loader.exec_module(provider)
|
|||
|
||||
|
||||
class ReverseTunnelBootstrapTest(unittest.TestCase):
|
||||
def test_core_cards_run_in_parallel_and_keep_product_order(self):
|
||||
barrier = threading.Barrier(4)
|
||||
names = [
|
||||
"itscreen_card", "mosquitto_card", "mqtt_bridge_card", "zigbee_card",
|
||||
"reverse_tunnel_card", "ip_stream_card", "display_card", "managed_system_cards",
|
||||
]
|
||||
patches = {}
|
||||
for index, name in enumerate(names):
|
||||
def build(_context, card_id=name, wait=index < 4):
|
||||
if wait:
|
||||
barrier.wait(1)
|
||||
card = {"id": card_id}
|
||||
return [card] if card_id == "managed_system_cards" else card
|
||||
patches[name] = build
|
||||
|
||||
with mock.patch.multiple(provider, **patches):
|
||||
cards = provider.get_cards({})
|
||||
|
||||
self.assertEqual(names, [card["id"] for card in cards])
|
||||
|
||||
def test_tunnel_is_active_only_when_ssh_child_has_established_connection(self):
|
||||
unit = {"active": True, "active_state": "active", "main_pid": 100}
|
||||
responses = {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,24 @@
|
|||
const assert = require('node:assert/strict');
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
|
||||
const js = fs.readFileSync(path.join(__dirname, '../frontend/console.js'), 'utf8');
|
||||
const css = fs.readFileSync(path.join(__dirname, '../frontend/console.css'), 'utf8');
|
||||
|
||||
assert.match(js, /class="cards healthServiceGrid"/);
|
||||
assert.equal((js.match(/serviceCard serviceProfileCard/g) || []).length, 2);
|
||||
assert.match(js, /function renderServiceSummary\(card\)/);
|
||||
assert.match(js, /serviceCard serviceProfileCard itscreenServiceCard/);
|
||||
assert.match(js, /if \(card\.id === "itscreen"\) return content/);
|
||||
assert.match(js, /serviceDetailsWide/);
|
||||
assert.match(js, /state\.activeTab = nextTab;\s+renderActiveTab\(\);\s+await loadForActiveTab\(\)/);
|
||||
assert.match(css, /\.shell\{max-width:1600px/);
|
||||
assert.match(css, /\.healthServiceGrid\{\s*grid-template-columns:repeat\(3,minmax\(0,1fr\)\)/);
|
||||
assert.match(css, /@media \(max-width:1100px\)[\s\S]*?\.healthServiceGrid\{grid-template-columns:repeat\(2,minmax\(0,1fr\)\)\}/);
|
||||
assert.match(css, /@media \(max-width:720px\)[\s\S]*?\.healthServiceGrid\{grid-template-columns:1fr\}/);
|
||||
assert.match(css, /\.healthServiceGrid \.serviceProfileCard\{[\s\S]*?grid-template-columns:repeat\(2,minmax\(0,1fr\)\)/);
|
||||
assert.match(css, /\.healthServiceGrid \.itscreenServiceCard\{[\s\S]*?grid-column:span 2;[\s\S]*?grid-template-columns:repeat\(3,minmax\(0,1fr\)\)/);
|
||||
assert.match(css, /\.serviceDetailsWide \.compactMeta\{grid-template-columns:minmax\(90px,24%\) minmax\(0,1fr\)\}/);
|
||||
assert.match(css, /@media \(max-width:940px\)[\s\S]*?\.healthServiceGrid \.serviceProfileCard\{grid-template-columns:1fr\}/);
|
||||
|
||||
console.log('Health layout owner: 1600px shell and 3/2/1 service columns passed');
|
||||
|
|
@ -16,7 +16,7 @@ SPEC.loader.exec_module(app)
|
|||
|
||||
class HealthServicesCacheTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
app._HEALTH_SERVICES_CACHE.update({"expires_at": 0.0, "payload": None})
|
||||
app._CACHE.update({"expires_at": 0.0, "payload": None})
|
||||
|
||||
def test_ttl_starts_after_slow_collection_finishes(self):
|
||||
clock = iter([100.0, 100.0, 110.0, 110.0])
|
||||
|
|
@ -26,7 +26,24 @@ class HealthServicesCacheTest(unittest.TestCase):
|
|||
mock.patch.object(app, "get_identity_payload", return_value={}):
|
||||
app.build_health_services_payload()
|
||||
|
||||
self.assertEqual(113.0, app._HEALTH_SERVICES_CACHE["expires_at"])
|
||||
self.assertEqual(113.0, app._CACHE["expires_at"])
|
||||
|
||||
def test_status_and_health_share_one_provider_collection(self):
|
||||
calls = []
|
||||
|
||||
def collect(_context):
|
||||
calls.append(True)
|
||||
return [{"id": "edge_api"}], ["core.py"]
|
||||
|
||||
with mock.patch.object(app, "load_config", return_value={"cache_ttl_sec": 15}), \
|
||||
mock.patch.object(app, "collect_provider_cards", side_effect=collect), \
|
||||
mock.patch.object(app, "get_identity_payload", return_value={}):
|
||||
health = app.build_health_services_payload()
|
||||
status = app.build_status_payload()
|
||||
|
||||
self.assertEqual([{"id": "edge_api"}], health["services"])
|
||||
self.assertEqual([{"id": "edge_api"}], status["services"])
|
||||
self.assertEqual(1, len(calls))
|
||||
|
||||
def test_concurrent_requests_share_one_collection(self):
|
||||
started = threading.Event()
|
||||
|
|
@ -53,6 +70,25 @@ class HealthServicesCacheTest(unittest.TestCase):
|
|||
|
||||
self.assertEqual(1, len(calls))
|
||||
|
||||
def test_provider_modules_run_in_parallel_and_keep_order(self):
|
||||
barrier = threading.Barrier(2)
|
||||
|
||||
def provider(service_id):
|
||||
def collect(_context):
|
||||
barrier.wait(1)
|
||||
return {"id": service_id}
|
||||
return collect
|
||||
|
||||
providers = [
|
||||
("/providers/first.py", provider("first")),
|
||||
("/providers/second.py", provider("second")),
|
||||
]
|
||||
with mock.patch.object(app, "load_providers", return_value=providers):
|
||||
cards, names = app.collect_provider_cards({})
|
||||
|
||||
self.assertEqual(["first", "second"], [card["id"] for card in cards])
|
||||
self.assertEqual(["first.py", "second.py"], names)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
|
|
@ -75,7 +75,7 @@ html[dir="rtl"] .emptyInline,
|
|||
html[dir="rtl"] .banner{
|
||||
text-align:right;
|
||||
}
|
||||
.shell{max-width:1180px;margin:0 auto;padding:28px 18px 40px}
|
||||
.shell{max-width:1600px;margin:0 auto;padding:28px 18px 40px}
|
||||
.hero{
|
||||
display:grid;grid-template-columns:minmax(0,1fr) auto auto;gap:16px;align-items:center;
|
||||
margin-bottom:18px;
|
||||
|
|
@ -378,6 +378,10 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.cards{
|
||||
display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px;
|
||||
}
|
||||
.healthServiceGrid{
|
||||
grid-template-columns:repeat(3,minmax(0,1fr));
|
||||
align-items:start;
|
||||
}
|
||||
.itscreenCards{
|
||||
grid-template-columns:repeat(2,minmax(0,1fr));
|
||||
align-items:start;
|
||||
|
|
@ -387,6 +391,40 @@ h1{margin:0;font-size:34px;line-height:1.02;font-weight:650;letter-spacing:-.03e
|
|||
.cards > .card{height:100%}
|
||||
.cardTop{display:flex;justify-content:space-between;gap:12px;align-items:flex-start}
|
||||
.serviceCard{display:flex;flex-direction:column}
|
||||
.healthServiceGrid .serviceProfileCard{
|
||||
display:grid;
|
||||
grid-template-columns:repeat(2,minmax(0,1fr));
|
||||
column-gap:20px;
|
||||
align-content:start;
|
||||
}
|
||||
.healthServiceGrid .itscreenServiceCard{
|
||||
grid-column:span 2;
|
||||
grid-template-columns:repeat(3,minmax(0,1fr));
|
||||
}
|
||||
.healthServiceGrid .serviceProfileCard > .cardTop,
|
||||
.healthServiceGrid .serviceProfileCard > .serviceSummary,
|
||||
.healthServiceGrid .serviceProfileCard > .banner,
|
||||
.healthServiceGrid .serviceProfileCard > .emptyInline,
|
||||
.healthServiceGrid .serviceProfileCard > .serviceAlertSection{
|
||||
grid-column:1 / -1;
|
||||
}
|
||||
.serviceSummary{
|
||||
display:grid;
|
||||
grid-template-columns:repeat(3,minmax(0,1fr));
|
||||
gap:10px;
|
||||
margin-top:14px;
|
||||
padding:10px 12px;
|
||||
border:1px solid var(--line);
|
||||
border-radius:12px;
|
||||
background:var(--surface-soft);
|
||||
}
|
||||
.serviceSummaryItem{display:grid;gap:3px;min-width:0}
|
||||
.serviceSummaryItem .key{color:var(--muted);font-size:11px;text-transform:uppercase;letter-spacing:.06em}
|
||||
.serviceSummaryValue{min-width:0;overflow-wrap:anywhere;font-size:13px}
|
||||
.healthServiceGrid .serviceProfileCard > .list{min-width:0;align-self:start}
|
||||
.healthServiceGrid .serviceProfileCard > .serviceDetailsWide{grid-column:1 / -1}
|
||||
.serviceDetailsWide .compactMeta{grid-template-columns:minmax(90px,24%) minmax(0,1fr)}
|
||||
.serviceProfileAside{min-width:0}
|
||||
.card h2{margin:0;font-size:19px}
|
||||
.cardSubtitle{margin:6px 0 0;color:var(--muted);font-size:13px}
|
||||
.badge{
|
||||
|
|
@ -1626,11 +1664,17 @@ html[dir="rtl"] .timezoneOption{text-align:right}
|
|||
0%,100%{opacity:.35;transform:scale(.9)}
|
||||
50%{opacity:1;transform:scale(1)}
|
||||
}
|
||||
@media (max-width:1100px){
|
||||
.healthServiceGrid{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
}
|
||||
@media (max-width:940px){
|
||||
.hero{grid-template-columns:1fr}
|
||||
.identityPanel{min-width:0}
|
||||
.gboxHero{grid-template-columns:1fr}
|
||||
.itscreenCards{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
.healthServiceGrid .serviceProfileCard{grid-template-columns:1fr}
|
||||
.healthServiceGrid .itscreenServiceCard{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
.serviceSummary{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
}
|
||||
@media (max-width:720px){
|
||||
.brand{flex-direction:column;align-items:flex-start}
|
||||
|
|
@ -1642,6 +1686,7 @@ html[dir="rtl"] .timezoneOption{text-align:right}
|
|||
.tunnelSummaryGrid{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
.brandDevice{width:min(70vw, 260px);max-height:180px}
|
||||
.wideCard,.displayCard,.accessPointCard{grid-column:auto}
|
||||
.healthServiceGrid .itscreenServiceCard{grid-column:auto;grid-template-columns:1fr}
|
||||
.audioDeviceGrid{grid-template-columns:1fr}
|
||||
.displayDetailsRow{grid-template-columns:1fr;align-items:start}
|
||||
.displayModePanel{
|
||||
|
|
@ -1652,6 +1697,7 @@ html[dir="rtl"] .timezoneOption{text-align:right}
|
|||
}
|
||||
.displayHeroText{font-size:18px}
|
||||
.itscreenCards{grid-template-columns:1fr}
|
||||
.healthServiceGrid{grid-template-columns:1fr}
|
||||
.itscreenLogsToolbar{grid-template-columns:1fr}
|
||||
.itscreenLogsActions{justify-content:flex-start}
|
||||
.modbusLayout{grid-template-columns:1fr}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,22 @@
|
|||
],
|
||||
translations: {
|
||||
ru: {
|
||||
"Check and update client": "Проверить и обновить версию",
|
||||
"Installed client": "Установленная версия клиента",
|
||||
"Available client": "Доступная версия клиента",
|
||||
"Checking client version...": "Проверяем версию клиента…",
|
||||
"A new client version is available": "Доступна новая версия клиента",
|
||||
"The latest client version is installed": "Установлена актуальная версия клиента",
|
||||
"Downloading client update...": "Загрузка обновления клиента…",
|
||||
"Installing client update...": "Установка обновления клиента…",
|
||||
"Client updated": "Клиент обновлён",
|
||||
"Client update failed": "Не удалось обновить клиент",
|
||||
"Updates come from git.iomatex.com. The client restarts; registration and settings are preserved.": "Обновления загружаются с git.iomatex.com. Клиент перезапустится; регистрация и настройки сохранятся.",
|
||||
"Client update": "Обновление клиента",
|
||||
"Client update system module": "Системный модуль обновления клиента",
|
||||
"System module": "Системный модуль",
|
||||
"Technical module that checks, verifies and safely installs client releases.": "Технический модуль, который проверяет, валидирует и безопасно устанавливает версии клиента.",
|
||||
|
||||
"Input/output relationship": "Связь входов и реле",
|
||||
"Independent inputs and outputs": "Независимые входы и выходы",
|
||||
"Toggle with memory": "Переключение с фиксацией",
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@
|
|||
{ mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" },
|
||||
{ mode: "custom", label: "Custom", host: "" }
|
||||
];
|
||||
const UI_VERSION = "V 3.1.28";
|
||||
const UI_VERSION = "V 3.1.42";
|
||||
const ITSCREEN_LOG_INITIAL_LINES = 50;
|
||||
const ITSCREEN_LOG_BUFFER_LIMIT = 300;
|
||||
const ITSCREEN_LOG_BATCH_MS = 250;
|
||||
|
|
@ -167,6 +167,9 @@
|
|||
networkRequest: null,
|
||||
network: null,
|
||||
itscreen: {
|
||||
update: null,
|
||||
updateLoading: false,
|
||||
updateCheckedAt: 0,
|
||||
loading: false,
|
||||
busyAction: "",
|
||||
data: null,
|
||||
|
|
@ -1825,6 +1828,20 @@
|
|||
]);
|
||||
}
|
||||
|
||||
function renderServiceSummary(card) {
|
||||
const items = [
|
||||
{ label: t("ID"), value: card.id },
|
||||
{ label: t("State"), value: displayValue(card.state, "-") },
|
||||
{ label: t("Status"), value: displayValue(card.status_text, "-") }
|
||||
];
|
||||
return `<div class="serviceSummary">${items.map(item => `
|
||||
<div class="serviceSummaryItem">
|
||||
<span class="key">${esc(item.label)}</span>
|
||||
<strong class="serviceSummaryValue">${esc(item.value)}</strong>
|
||||
</div>
|
||||
`).join("")}</div>`;
|
||||
}
|
||||
|
||||
function renderItscreenServiceCard(card) {
|
||||
const payload = itscreenRegistration();
|
||||
const tone = statusTone(card);
|
||||
|
|
@ -1834,18 +1851,14 @@
|
|||
const registrationRequired = !!(state.itscreen.registrationLoadedAt && payload && !payload.registered && !state.itscreen.error);
|
||||
|
||||
return `
|
||||
<article class="panel card serviceCard">
|
||||
<article class="panel card serviceCard serviceProfileCard itscreenServiceCard">
|
||||
<div class="cardTop">
|
||||
<div>
|
||||
${renderPanelTitle(t(card.title), `service:${card.id}`, card.subtitle ? translateUiText(card.subtitle) : "")}
|
||||
<div class="badge"><span class="dot ${tone}"></span>${esc(translateStatusValue(card.status_text || card.state || "Unknown"))}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="meta">
|
||||
<div class="key">${esc(t("ID"))}</div><div>${esc(card.id)}</div>
|
||||
<div class="key">${esc(t("State"))}</div><div>${esc(displayValue(card.state, "-"))}</div>
|
||||
<div class="key">${esc(t("Status"))}</div><div>${esc(displayValue(card.status_text, "-"))}</div>
|
||||
</div>
|
||||
${renderServiceSummary(card)}
|
||||
${state.itscreen.error ? `<div class="banner error">${esc(state.itscreen.error)}${itscreenResponseDetails() ? `: ${esc(itscreenResponseDetails())}` : ""}</div>` : ""}
|
||||
${!state.itscreen.registrationLoadedAt && !state.itscreen.error ? `<div class="emptyInline">${esc(t("Loading It-screen status..."))}</div>` : `
|
||||
<div class="list">
|
||||
|
|
@ -1855,16 +1868,27 @@
|
|||
</div>
|
||||
`}
|
||||
<div class="list">
|
||||
<div class="listTitle">${esc(t("Flags"))}</div>
|
||||
<div class="pillRow">
|
||||
${boolPill("Installed", !!card.installed)}
|
||||
${boolPill("Configured", !!card.configured)}
|
||||
${boolPill("Active", !!card.active)}
|
||||
<div class="listTitle">${esc(t("Client update"))}</div>
|
||||
<div id="itscreenClientUpdate">${renderClientUpdate()}</div>
|
||||
</div>
|
||||
<div class="serviceProfileAside">
|
||||
<div class="list">
|
||||
<div class="listTitle">${esc(t("Flags"))}</div>
|
||||
<div class="pillRow">
|
||||
${boolPill("Installed", !!card.installed)}
|
||||
${boolPill("Configured", !!card.configured)}
|
||||
${boolPill("Active", !!card.active)}
|
||||
</div>
|
||||
</div>
|
||||
${renderStageVersion(card, false, {
|
||||
section: t("Client update system module"),
|
||||
button: t("System module"),
|
||||
hint: t("Technical module that checks, verifies and safely installs client releases.")
|
||||
})}
|
||||
</div>
|
||||
${renderServiceActions(card)}
|
||||
${warnings.length ? `<div class="list"><div class="listTitle">${esc(t("Warnings"))}</div><ul class="msgList">${warnings.map((x) => `<li>${esc(translateUiText(x))}</li>`).join("")}</ul></div>` : ""}
|
||||
${errors.length ? `<div class="list"><div class="listTitle">${esc(t("Errors"))}</div><ul class="msgList">${errors.map((x) => `<li>${esc(translateUiText(x))}</li>`).join("")}</ul></div>` : ""}
|
||||
${warnings.length ? `<div class="list serviceAlertSection"><div class="listTitle">${esc(t("Warnings"))}</div><ul class="msgList">${warnings.map((x) => `<li>${esc(translateUiText(x))}</li>`).join("")}</ul></div>` : ""}
|
||||
${errors.length ? `<div class="list serviceAlertSection"><div class="listTitle">${esc(t("Errors"))}</div><ul class="msgList">${errors.map((x) => `<li>${esc(translateUiText(x))}</li>`).join("")}</ul></div>` : ""}
|
||||
</article>
|
||||
`;
|
||||
}
|
||||
|
|
@ -2451,7 +2475,7 @@
|
|||
return (job.stages || [job.stage]).includes(stage);
|
||||
}
|
||||
|
||||
function renderStageVersion(card, compact = false) {
|
||||
function renderStageVersion(card, compact = false, labels = {}) {
|
||||
const release = card.release;
|
||||
if (!release) return "";
|
||||
const updates = (state.healthServices && state.healthServices.updates) || {};
|
||||
|
|
@ -2463,9 +2487,11 @@
|
|||
: updates.checking ? t("Checking versions...")
|
||||
: updates.error ? t(updates.error)
|
||||
: needsCheck ? t("Check available versions before installing.") : "";
|
||||
const versionButton = `<button class="actionBtn secondary" type="button" onclick="window.__stageVersion('${esc(card.id)}')">${esc(t("Version"))}: ${esc(release.current || t("Unknown"))}</button>`;
|
||||
return `<div class="list">
|
||||
${compact ? renderPanelTitle(t(card.title), `service:${card.id}`, "", versionButton) : `<div class="listTitle">${esc(t("Stage version"))}</div>
|
||||
const versionLabel = labels.button || t("Version");
|
||||
const sectionLabel = labels.section || t("Stage version");
|
||||
const versionButton = `<button class="actionBtn secondary" type="button" onclick="window.__stageVersion('${esc(card.id)}')">${esc(versionLabel)}: ${esc(release.current || t("Unknown"))}</button>`;
|
||||
return `<div class="list serviceReleaseSection">
|
||||
${compact ? renderPanelTitle(t(card.title), `service:${card.id}`, "", versionButton) : `<div class="listTitle">${esc(sectionLabel)}</div>
|
||||
<div class="meta compactMeta">${renderKeyValueRows([
|
||||
{ label: t("Installed"), value: release.current || t("Unknown") },
|
||||
{ label: t("Available"), value: release.latest || t("Not checked") },
|
||||
|
|
@ -2478,6 +2504,7 @@
|
|||
${!needsCheck && release.status !== "latest" && release.status !== "ahead" ? `<button class="actionBtn" type="button" ${release.can_install ? "" : "disabled"} onclick="window.__stageVersion('${esc(card.id)}')">${esc(running ? t("Installing...") : `${action}${release.latest ? ` ${release.latest}` : ""}`)}</button>` : ""}
|
||||
${stageInJob(job, release.stage) && job.state ? `<button class="actionBtn secondary" type="button" onclick="window.__stageInstallLog('${esc(release.stage)}', '${esc(job.unit || "")}')">${esc(t("Installation log"))}</button>` : ""}
|
||||
</div>
|
||||
${labels.hint ? `<div class="formHint">${esc(labels.hint)}</div>` : ""}
|
||||
${stageInJob(job, release.stage) && ["failed", "interrupted"].includes(job.state) ? `<div class="banner warn" role="status">${esc(t(job.reason || "Installation did not complete. Open the installation log for details."))}</div>` : ""}
|
||||
${!release.can_install && reason ? `<div class="formHint" role="status">${esc(reason)}</div>` : ""}
|
||||
</div>`;
|
||||
|
|
@ -2492,6 +2519,7 @@
|
|||
|
||||
function renderServiceCard(card) {
|
||||
const content = renderServiceCardContent(card);
|
||||
if (card.id === "itscreen") return content;
|
||||
// All specialized cards retain their existing renderer and share one release control.
|
||||
const end = content.lastIndexOf("</article>");
|
||||
return end < 0 ? content : content.slice(0, end) + renderStageVersion(card) + content.slice(end);
|
||||
|
|
@ -2507,24 +2535,21 @@
|
|||
const warnings = Array.isArray(card.warnings) ? card.warnings : [];
|
||||
const errors = Array.isArray(card.errors) ? card.errors : [];
|
||||
const details = Array.isArray(card.details) ? card.details : [];
|
||||
const wideDetails = details.some((detail) => textValue(detail && detail.value, "").length > 32);
|
||||
const mqttSelfTest = state.mqttSelfTest || {};
|
||||
const showMqttSelfTest = card.id === "mosquitto";
|
||||
const showMqttBridgeTest = card.id === "mqtt_bridge";
|
||||
|
||||
return `
|
||||
<article class="panel card serviceCard">
|
||||
<article class="panel card serviceCard serviceProfileCard">
|
||||
<div class="cardTop">
|
||||
<div>
|
||||
${renderPanelTitle(t(card.title), `service:${card.id}`, card.subtitle ? translateUiText(card.subtitle) : "")}
|
||||
<div class="badge"><span class="dot ${tone}"></span>${esc(translateStatusValue(card.status_text || card.state || "Unknown"))}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="meta">
|
||||
<div class="key">${esc(t("ID"))}</div><div>${esc(card.id)}</div>
|
||||
<div class="key">${esc(t("State"))}</div><div>${esc(displayValue(card.state, "-"))}</div>
|
||||
<div class="key">${esc(t("Status"))}</div><div>${esc(displayValue(card.status_text, "-"))}</div>
|
||||
</div>
|
||||
${details.length ? `<div class="list"><div class="listTitle">${esc(t("Details"))}</div><div class="meta compactMeta">${renderKeyValueRows(details)}</div></div>` : ""}
|
||||
${renderServiceSummary(card)}
|
||||
${details.length ? `<div class="list serviceDetailsSection${wideDetails ? " serviceDetailsWide" : ""}"><div class="listTitle">${esc(t("Details"))}</div><div class="meta compactMeta">${renderKeyValueRows(details)}</div></div>` : ""}
|
||||
${showMqttSelfTest ? renderMqttSelfTestPanel() : ""}
|
||||
${showMqttBridgeTest ? renderMqttBridgeTestPanel() : ""}
|
||||
<div class="list">
|
||||
|
|
@ -2536,8 +2561,8 @@
|
|||
</div>
|
||||
</div>
|
||||
${renderServiceActions(card)}
|
||||
${warnings.length ? `<div class="list"><div class="listTitle">${esc(t("Warnings"))}</div><ul class="msgList">${warnings.map((x) => `<li>${esc(translateUiText(x))}</li>`).join("")}</ul></div>` : ""}
|
||||
${errors.length ? `<div class="list"><div class="listTitle">${esc(t("Errors"))}</div><ul class="msgList">${errors.map((x) => `<li>${esc(translateUiText(x))}</li>`).join("")}</ul></div>` : ""}
|
||||
${warnings.length ? `<div class="list serviceAlertSection"><div class="listTitle">${esc(t("Warnings"))}</div><ul class="msgList">${warnings.map((x) => `<li>${esc(translateUiText(x))}</li>`).join("")}</ul></div>` : ""}
|
||||
${errors.length ? `<div class="list serviceAlertSection"><div class="listTitle">${esc(t("Errors"))}</div><ul class="msgList">${errors.map((x) => `<li>${esc(translateUiText(x))}</li>`).join("")}</ul></div>` : ""}
|
||||
</article>
|
||||
`;
|
||||
}
|
||||
|
|
@ -2790,7 +2815,7 @@
|
|||
${updates.error ? `<div class="banner warn">${esc(t(updates.error))}</div>` : ""}
|
||||
${updateJob.state ? `<div class="banner ${["failed", "interrupted"].includes(updateJob.state) ? "warn" : ""}" role="status">${esc(t(jobLabels[updateJob.state] || updateJob.state))} · ${esc(updateJob.current_stage || updateJob.stage)} ${esc(updateJob.stages ? `${(updateJob.completed || []).length}/${updateJob.stages.length}` : (updateJob.version || ""))}${["failed", "interrupted"].includes(updateJob.state) ? ` · ${esc(t(updateJob.reason || "Installation did not complete. Open the installation log for details."))}` : ""}</div>` : ""}
|
||||
</div>
|
||||
<div class="cards">${serviceCards.map(renderServiceCard).join("") || `<div class="empty">${esc(t("No service cards available."))}</div>`}</div>
|
||||
<div class="cards healthServiceGrid">${serviceCards.map(renderServiceCard).join("") || `<div class="empty">${esc(t("No service cards available."))}</div>`}</div>
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
|
@ -3084,6 +3109,7 @@
|
|||
<button class="actionBtn secondary" type="button" ${canStopService ? "" : "disabled"} onclick="window.__itscreenServiceAction('stop')">${esc(busy === "service_stop" ? t("Stopping...") : t("Stop Service"))}</button>
|
||||
<button class="actionBtn secondary" type="button" ${busy ? "disabled" : ""} onclick="window.__itscreenRefresh()">${esc(state.itscreen.loading ? t("Refreshing...") : t("Refresh Status"))}</button>
|
||||
</div>
|
||||
<div id="itscreenClientUpdate">${renderClientUpdate()}</div>
|
||||
${serviceWarnings.length ? `<div class="list"><div class="listTitle">${esc(t("Warnings"))}</div><ul class="msgList">${serviceWarnings.map((x) => `<li>${esc(translateUiText(x))}</li>`).join("")}</ul></div>` : ""}
|
||||
${serviceErrors.length ? `<div class="list"><div class="listTitle">${esc(t("Errors"))}</div><ul class="msgList">${serviceErrors.map((x) => `<li>${esc(translateUiText(x))}</li>`).join("")}</ul></div>` : ""}
|
||||
${service && service.status === "not_installed" ? `<div class="formHint">${esc(t("It-screen service is not installed on this device."))}</div>` : ""}
|
||||
|
|
@ -4963,8 +4989,8 @@
|
|||
state.healthServices.services = state.healthServices.services.map((card) => (card && card.id === nextCard.id ? nextCard : card));
|
||||
}
|
||||
|
||||
async function loadStatus() {
|
||||
state.status = await fetchJson("/api/status", { cache: "no-store" });
|
||||
async function loadStatus(options = {}) {
|
||||
state.status = await fetchJson(`/api/status${options.force ? "?refresh=1" : ""}`, { cache: "no-store" });
|
||||
updateIdentity(state.status.identity || {});
|
||||
updateHeaderMeta(state.status);
|
||||
}
|
||||
|
|
@ -4983,13 +5009,13 @@
|
|||
requestController.abort();
|
||||
}
|
||||
|
||||
async function loadHealth() {
|
||||
async function loadHealth(options = {}) {
|
||||
const generation = state.sessionGeneration;
|
||||
if (state.healthRequest) return state.healthRequest;
|
||||
state.healthRequest = (async () => {
|
||||
const [summary, services] = await Promise.all([
|
||||
fetchJson("/api/health/summary", { cache: "no-store" }),
|
||||
fetchJson("/api/health/services", { cache: "no-store" })
|
||||
fetchJson(`/api/health/services${options.force ? "?refresh=1" : ""}`, { cache: "no-store" })
|
||||
]);
|
||||
state.health = summary;
|
||||
state.healthServices = services;
|
||||
|
|
@ -5021,10 +5047,10 @@
|
|||
}
|
||||
}
|
||||
|
||||
async function loadNetwork() {
|
||||
async function loadNetwork(options = {}) {
|
||||
if (state.networkRequest) return state.networkRequest;
|
||||
state.networkRequest = (async () => {
|
||||
state.network = await fetchJson("/api/network/summary", { cache: "no-store" });
|
||||
state.network = await fetchJson(`/api/network/summary${options.force ? "?refresh=1" : ""}`, { cache: "no-store" });
|
||||
updateIdentity(state.network.identity || state.identity || {});
|
||||
updateHeaderMeta(state.network);
|
||||
syncNetworkFormFromBackend();
|
||||
|
|
@ -5199,6 +5225,7 @@
|
|||
}
|
||||
|
||||
async function loadItscreenInitialData(options = {}) {
|
||||
if (["health", "tscreen"].includes(state.activeTab)) loadClientUpdate(Date.now() - state.itscreen.updateCheckedAt > 900000 ? "check_only" : null);
|
||||
const force = !!options.force;
|
||||
const maxAgeMs = Number.isFinite(options.maxAgeMs) ? options.maxAgeMs : 10000;
|
||||
if (!force && state.itscreen.request) return state.itscreen.request;
|
||||
|
|
@ -5304,22 +5331,23 @@
|
|||
return;
|
||||
}
|
||||
const generation = state.sessionGeneration;
|
||||
const force = !!options.force;
|
||||
const preserveEditing = !!options.preserveEditing;
|
||||
nodes.refreshBtn.disabled = true;
|
||||
if (nodes.rebootBtn) nodes.rebootBtn.disabled = state.rebootPending;
|
||||
try {
|
||||
if (state.activeTab === "health") {
|
||||
await Promise.all([loadHealth(), loadItscreenInitialData()]);
|
||||
await Promise.all([loadHealth({ force }), loadItscreenInitialData({ force })]);
|
||||
} else if (state.activeTab === "security") {
|
||||
await loadTimezone();
|
||||
} else if (state.activeTab === "network") {
|
||||
await loadNetwork();
|
||||
await loadNetwork({ force });
|
||||
} else if (state.activeTab === "modbus") {
|
||||
await loadModbus();
|
||||
await loadModbus({ force });
|
||||
} else if (state.activeTab === "tscreen") {
|
||||
await loadItscreenInitialData();
|
||||
await loadItscreenInitialData({ force });
|
||||
} else {
|
||||
await loadStatus();
|
||||
await loadStatus({ force });
|
||||
}
|
||||
if (generation !== state.sessionGeneration) return;
|
||||
if (!(preserveEditing && state.activeTab === "network" && networkFormIsInteractive()) && !(preserveEditing && state.activeTab === "tscreen" && itscreenFormIsInteractive()) && !(preserveEditing && state.activeTab === "security" && timezoneFormIsInteractive())) {
|
||||
|
|
@ -5832,6 +5860,58 @@
|
|||
state.itscreen.focused = !!focused;
|
||||
};
|
||||
|
||||
function clientVersion(code) {
|
||||
const n = Number(code);
|
||||
return n > 0 ? `${Math.floor(n / 1000000)}.${Math.floor(n / 10000) % 100}.${n % 10000}` : "—";
|
||||
}
|
||||
|
||||
function renderClientUpdate() {
|
||||
const u = state.itscreen.update || {};
|
||||
const phase = u.state_update || "init";
|
||||
const labels = {init: "Checking client version...", check: "Checking client version...",
|
||||
ready: "A new client version is available", not_required: "The latest client version is installed",
|
||||
downloading: "Downloading client update...", updating: "Installing client update...", not_permitted: "Automatic updates are disabled",
|
||||
updated: "Client updated", error: "Client update failed"};
|
||||
const busy = state.itscreen.updateLoading || u.busy;
|
||||
return `<div class="meta"><div class="key">${esc(t("Installed client"))}</div><div>${esc(clientVersion(u.installed_version))}</div>
|
||||
<div class="key">${esc(t("Available client"))}</div><div>${esc(clientVersion(u.ready_version))}</div></div>
|
||||
<div class="banner ${u.error ? "error" : phase === "ready" ? "warn" : ""}" role="status" aria-live="polite">${esc(t(labels[phase] || phase))}${phase === "downloading" ? ` ${Number(u.progress_download) || 0}%` : ""}${u.error ? `: ${esc(u.error)}` : ""}</div>
|
||||
<div class="actionColumn"><button class="actionBtn" type="button" ${busy || state.itscreen.busyAction ? "disabled" : ""} onclick="window.__clientUpdate()">${esc(t("Check and update client"))}</button></div>
|
||||
<div class="formHint">${esc(t("Updates come from git.iomatex.com. The client restarts; registration and settings are preserved."))}</div>`;
|
||||
}
|
||||
|
||||
async function loadClientUpdate(action = null) {
|
||||
if (state.itscreen.updateLoading) return;
|
||||
const generation = state.sessionGeneration;
|
||||
state.itscreen.updateLoading = true;
|
||||
if (action) renderClientUpdateStatus();
|
||||
try {
|
||||
const data = await fetchJson("/api/itscreen/update", action ? {
|
||||
method: "POST", headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify({action})
|
||||
} : {cache: "no-store"});
|
||||
if (generation !== state.sessionGeneration) return;
|
||||
state.itscreen.update = data;
|
||||
if (action) state.itscreen.updateCheckedAt = Date.now();
|
||||
} catch (error) {
|
||||
if (generation !== state.sessionGeneration) return;
|
||||
state.itscreen.update = {state_update: "error", error: error.message};
|
||||
} finally {
|
||||
state.itscreen.updateLoading = false;
|
||||
if (generation === state.sessionGeneration) renderClientUpdateStatus();
|
||||
}
|
||||
}
|
||||
|
||||
function renderClientUpdateStatus() {
|
||||
const panel = document.getElementById("itscreenClientUpdate");
|
||||
if (panel && ["health", "tscreen"].includes(state.activeTab)) panel.innerHTML = renderClientUpdate();
|
||||
}
|
||||
|
||||
window.__clientUpdate = async function () {
|
||||
if (state.itscreen.updateLoading || state.itscreen.busyAction || (state.itscreen.update || {}).busy) return;
|
||||
await loadClientUpdate("update");
|
||||
};
|
||||
|
||||
window.__itscreenRefresh = async function () {
|
||||
state.itscreen.busyAction = "refresh";
|
||||
if (state.activeTab === "tscreen") renderActiveTab();
|
||||
|
|
@ -6935,6 +7015,7 @@
|
|||
await releaseModbusLeaseSilently();
|
||||
}
|
||||
state.activeTab = nextTab;
|
||||
renderActiveTab();
|
||||
await loadForActiveTab();
|
||||
if (state.activeTab === "tscreen") {
|
||||
activateItscreenLogs().catch(() => {});
|
||||
|
|
@ -6946,7 +7027,7 @@
|
|||
nodes.refreshBtn.addEventListener("click", async () => {
|
||||
if (!state.auth.authenticated) return;
|
||||
closeActionMenu();
|
||||
await loadForActiveTab();
|
||||
await loadForActiveTab({ force: true });
|
||||
});
|
||||
}
|
||||
if (nodes.rebootBtn) nodes.rebootBtn.addEventListener("click", window.__rebootDevice);
|
||||
|
|
@ -7040,5 +7121,8 @@
|
|||
if (state.activeTab === "tscreen") return;
|
||||
loadForActiveTab({ preserveEditing: true }).catch(() => {});
|
||||
}, 15000);
|
||||
setInterval(() => {
|
||||
if (state.auth.authenticated && ["health", "tscreen"].includes(state.activeTab)) loadClientUpdate();
|
||||
}, 3000);
|
||||
setInterval(updateSessionMeter, 30000);
|
||||
})();
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@
|
|||
} catch (error) {}
|
||||
})();
|
||||
</script>
|
||||
<link rel="stylesheet" href="/console.css?v=3.1.28&rev=edge-runtime-profile-1">
|
||||
<link rel="stylesheet" href="/console.css?v=3.1.42&rev=edge-runtime-profile-1">
|
||||
</head>
|
||||
<body>
|
||||
<main class="shell">
|
||||
|
|
@ -109,7 +109,7 @@
|
|||
</main>
|
||||
<div id="menuBackdrop" class="menuBackdrop" hidden></div>
|
||||
<div id="toastStack" class="toastStack" aria-live="polite" aria-atomic="true"></div>
|
||||
<script src="/console.i18n.js?v=3.1.28&rev=edge-runtime-profile-1"></script>
|
||||
<script src="/console.js?v=3.1.28&rev=edge-runtime-profile-1"></script>
|
||||
<script src="/console.i18n.js?v=3.1.42&rev=edge-runtime-profile-1"></script>
|
||||
<script src="/console.js?v=3.1.42&rev=edge-runtime-profile-1"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import os
|
|||
import re
|
||||
import shlex
|
||||
import shutil
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
|
||||
DRM_ROOT = "/sys/class/drm"
|
||||
|
|
@ -1046,16 +1047,21 @@ def managed_system_cards(ctx):
|
|||
|
||||
|
||||
def get_cards(ctx):
|
||||
return [
|
||||
itscreen_card(ctx),
|
||||
mosquitto_card(ctx),
|
||||
mqtt_bridge_card(ctx),
|
||||
zigbee_card(ctx),
|
||||
reverse_tunnel_card(ctx),
|
||||
ip_stream_card(ctx),
|
||||
display_card(ctx),
|
||||
*managed_system_cards(ctx),
|
||||
]
|
||||
builders = (
|
||||
itscreen_card,
|
||||
mosquitto_card,
|
||||
mqtt_bridge_card,
|
||||
zigbee_card,
|
||||
reverse_tunnel_card,
|
||||
ip_stream_card,
|
||||
display_card,
|
||||
managed_system_cards,
|
||||
)
|
||||
cards = []
|
||||
with ThreadPoolExecutor(max_workers=4, thread_name_prefix="console-card") as executor:
|
||||
for result in executor.map(lambda builder: builder(ctx), builders):
|
||||
cards.extend(result if isinstance(result, list) else [result])
|
||||
return cards
|
||||
|
||||
|
||||
def get_runtime_cards(ctx):
|
||||
|
|
|
|||
|
|
@ -255,7 +255,7 @@ cat > "$CFG_PATH" <<JSON
|
|||
"bind": "${APP_BIND}",
|
||||
"port": ${APP_PORT},
|
||||
"extra_ports": [${APP_EXTRA_PORT}],
|
||||
"cache_ttl_sec": 3
|
||||
"cache_ttl_sec": 15
|
||||
}
|
||||
JSON
|
||||
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
{
|
||||
"version": "3.1.28"
|
||||
"version": "3.1.42"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
1e1b51d15f768bace20725d1358393808cd70f1719cb4d542846603c42fd9826 repo/Packages
|
||||
e4f033d9027634b3b40e938abe202e5ea4cdfc2e1eb63c48f27c8c077a2c1c36 repo/Packages.gz
|
||||
672914a50e5061cd2784e9914bcdeb940ac2f74098a24b150d5504eaa6d3129a repo/Packages
|
||||
8544bea5895d3819b3759a19c8c9734fcc75c7c6f6ed4a71eac42c38c483d7c7 repo/Packages.gz
|
||||
1478a610fd50e190882ff41e16c57b628a508bcf5b5ac5313affb49d20818e0a repo/adduser_3.118+deb11u1_all.deb
|
||||
2046876c82fc1c342b38ace9aa0661bcb3e167837c984b4bdc89702bc78df5ac repo/adwaita-icon-theme_3.38.0-1_all.deb
|
||||
e8a1ef315c0218763de6031fca33e74b6b38c749aba148a0fa272cb5ea03a87f repo/alsa-utils_1.2.4-1_arm64.deb
|
||||
|
|
@ -576,11 +576,17 @@ c393d7ed557168d965747eebeae6d552342d4a5cb0a5944bf1f8bb6e290bc9c6 repo/python3-d
|
|||
8a6dacda656a2e783b35a0126091cb7f837eb36dd2300a7e1f95a310f48e700c repo/qml-module-qt-labs-platform_5.15.2+dfsg-2_arm64.deb
|
||||
cb242544571c337949e75292f4edc51d71a49c03496a37c09f3d41f72163db4f repo/qml-module-qt-labs-settings_5.15.2+dfsg-6_arm64.deb
|
||||
fc7e8ea12dde85bdf4368417b6af7e65a68c3a653cf158b6ea1692d4acb1f2a3 repo/qml-module-qt-websockets_5.15.2-2_arm64.deb
|
||||
3447873093494164126ffbefa77729cde0719f37e88f31e92ab997fc47096be6 repo/qml-module-qtgraphicaleffects_5.15.2-2_arm64.deb
|
||||
eed1fe02fcff7b8637c53a8d4d7f12b6fa9dd489205832e036fa7a39d8da83d6 repo/qml-module-qtmultimedia_5.15.2-3_arm64.deb
|
||||
4ac78a560ddde2de0748b2f8bfae25f05ce8518c1e5aff8e4eb7c39f57c2a483 repo/qml-module-qtpositioning_5.15.2+dfsg-2_arm64.deb
|
||||
55f4a8e20d4106354626553bc263fdef17565e00a64cc02fe8862f0ad3c77273 repo/qml-module-qtqml-models2_5.15.2+dfsg-6_arm64.deb
|
||||
919ccd7611ef0e28401c423f81d69debeda9f83fb4e11f135aac7740c39dc12d repo/qml-module-qtqml_5.15.2+dfsg-6_arm64.deb
|
||||
f8c25aa3ecdc04d26875308acf247e1dcbdeaa0ef5cd781229145b96873aa31c repo/qml-module-qtquick-controls2_5.15.2+dfsg-2_arm64.deb
|
||||
c489b997db7121be3e2a90b062d282a12703fd711d0528108939d38820cca9c1 repo/qml-module-qtquick-controls_5.15.2-2_arm64.deb
|
||||
568e4f7cd87e7cab7fe187890aa84afd82cf739c51e4a5b6af7d8bf9c67c0198 repo/qml-module-qtquick-layouts_5.15.2+dfsg-6_arm64.deb
|
||||
5000cb0b941e9d4318243cf9b6079610c8cf95093ce7279f2c533baad2f88d47 repo/qml-module-qtquick-templates2_5.15.2+dfsg-2_arm64.deb
|
||||
96942d9baca62b40c91a801a90c8475486188e2e28c4d801f9f7f1a56dec5155 repo/qml-module-qtquick-virtualkeyboard_5.15.2+dfsg-2_arm64.deb
|
||||
6704425a99db956035c91614d117bcf50ab8f2de7be60c8b291836009f4a984c repo/qml-module-qtquick-window2_5.15.2+dfsg-6_arm64.deb
|
||||
6d83ed5d96a047ac8644063ed758bdc57b6bfad40fb99aa894bf3e9ed4d569a6 repo/qml-module-qtquick-xmllistmodel_5.15.2-3_arm64.deb
|
||||
29edbc060b52853af7a3feb34d4844db73562626915ed302a876a57d61f1cc58 repo/qml-module-qtquick2_5.15.2+dfsg-6_arm64.deb
|
||||
9a180f44d6e48bf89eddd76531399963c6bb60507a3beaebc81024d8a16fea2d repo/qml-module-qtwebengine_5.15.2+dfsg-3_arm64.deb
|
||||
|
|
@ -622,5 +628,5 @@ ad0798e2279831853ca1f737e75460c879845f2ede3b9a2df5590cbb3491042e repo/xserver-x
|
|||
624bf3c6d8088493c2429596995d4efdc4c642c1e7bc9ef2fa31118f780b19f4 repo/xz-utils_5.2.5-2.1~deb11u2_arm64.deb
|
||||
e3963985d1a020d67ffd4180e6f9c4b5c600b515f0c9d8fda513d7a0e48e63a1 repo/zlib1g_1%3a1.2.11.dfsg-2+deb11u2_arm64.deb
|
||||
488878a149bd33605f6a85520edd7aa54610eb5980fec5d9f48ec7b0b874e0f2 platform
|
||||
adbe212466cfc6ddac37022e7643a7b9096972b75459e3826528cf9d4b638d3e package-versions.txt
|
||||
f87c03541a49e54376b91f4c85084dfdf5f07361e839d345b763ba683cf85280 requested-packages.txt
|
||||
c11e149bf3d57f023eaabd48c7478a5bb7be9aede51608081421320c0cf165b9 package-versions.txt
|
||||
aec1bbb7cf79fdef7d0998571006fbb16daf92fb84793d1d6f89b53c40d76aa8 requested-packages.txt
|
||||
|
|
|
|||
|
|
@ -1726,21 +1726,39 @@ Architecture: arm64
|
|||
Package: qml-module-qt-websockets
|
||||
Version: 5.15.2-2
|
||||
Architecture: arm64
|
||||
Package: qml-module-qtgraphicaleffects
|
||||
Version: 5.15.2-2
|
||||
Architecture: arm64
|
||||
Package: qml-module-qtmultimedia
|
||||
Version: 5.15.2-3
|
||||
Architecture: arm64
|
||||
Package: qml-module-qtpositioning
|
||||
Version: 5.15.2+dfsg-2
|
||||
Architecture: arm64
|
||||
Package: qml-module-qtqml
|
||||
Version: 5.15.2+dfsg-6
|
||||
Architecture: arm64
|
||||
Package: qml-module-qtqml-models2
|
||||
Version: 5.15.2+dfsg-6
|
||||
Architecture: arm64
|
||||
Package: qml-module-qtquick-controls
|
||||
Version: 5.15.2-2
|
||||
Architecture: arm64
|
||||
Package: qml-module-qtquick-controls2
|
||||
Version: 5.15.2+dfsg-2
|
||||
Architecture: arm64
|
||||
Package: qml-module-qtquick-layouts
|
||||
Version: 5.15.2+dfsg-6
|
||||
Architecture: arm64
|
||||
Package: qml-module-qtquick-templates2
|
||||
Version: 5.15.2+dfsg-2
|
||||
Architecture: arm64
|
||||
Package: qml-module-qtquick-virtualkeyboard
|
||||
Version: 5.15.2+dfsg-2
|
||||
Architecture: arm64
|
||||
Package: qml-module-qtquick-window2
|
||||
Version: 5.15.2+dfsg-6
|
||||
Architecture: arm64
|
||||
Package: qml-module-qtquick-xmllistmodel
|
||||
Version: 5.15.2-3
|
||||
Architecture: arm64
|
||||
|
|
|
|||
|
|
@ -15205,6 +15205,30 @@ Description: Qt 5 Web Sockets compatibility QML module
|
|||
not use it, use QtWebSockets module instead (in qml-module-qtwebsockets
|
||||
package).
|
||||
|
||||
Package: qml-module-qtgraphicaleffects
|
||||
Source: qtgraphicaleffects-opensource-src
|
||||
Version: 5.15.2-2
|
||||
Architecture: arm64
|
||||
Maintainer: Debian Qt/KDE Maintainers <debian-qt-kde@lists.debian.org>
|
||||
Installed-Size: 578
|
||||
Pre-Depends: dpkg (>= 1.15.6~)
|
||||
Depends: qml-module-qtquick-window2, qml-module-qtquick2, libqt5qml5 (<< 5.15.3~), libqt5qml5 (>= 5.15.2+dfsg~), libc6 (>= 2.29), libqt5core5a (>= 5.15.2+dfsg~), libqt5gui5 (>= 5.15.2+dfsg~) | libqt5gui5-gles (>= 5.15.2+dfsg~), libqt5quick5 (>= 5.15.2+dfsg~) | libqt5quick5-gles (>= 5.15.2+dfsg~), libstdc++6 (>= 5), qtdeclarative-abi-5-15-2
|
||||
Filename: ./qml-module-qtgraphicaleffects_5.15.2-2_arm64.deb
|
||||
Size: 69984
|
||||
MD5sum: 1e0bcb506e82ae5a36dad34b337837ff
|
||||
SHA1: e02f3e7fc96aef1f1d354113e25a41355ce509ac
|
||||
SHA256: 3447873093494164126ffbefa77729cde0719f37e88f31e92ab997fc47096be6
|
||||
Section: libs
|
||||
Priority: optional
|
||||
Multi-Arch: same
|
||||
Homepage: https://doc.qt.io/qt-5/qtgraphicaleffects-index.html
|
||||
Description: Qt 5 Graphical Effects module
|
||||
Qt is a cross-platform C++ application framework. Qt's primary feature
|
||||
is its rich set of widgets that provide standard GUI functionality.
|
||||
.
|
||||
Qt Graphical Effects contains ready to use visual effects for OpenGL
|
||||
QML applications.
|
||||
|
||||
Package: qml-module-qtmultimedia
|
||||
Source: qtmultimedia-opensource-src
|
||||
Version: 5.15.2-3
|
||||
|
|
@ -15249,6 +15273,76 @@ Description: Qt Positioning QML module
|
|||
.
|
||||
This package contains the Qt Positioning QML plugin for Qt Declarative.
|
||||
|
||||
Package: qml-module-qtqml
|
||||
Source: qtdeclarative-opensource-src
|
||||
Version: 5.15.2+dfsg-6
|
||||
Architecture: arm64
|
||||
Maintainer: Debian Qt/KDE Maintainers <debian-qt-kde@lists.debian.org>
|
||||
Installed-Size: 91
|
||||
Depends: libc6 (>= 2.17), libqt5core5a (>= 5.0.2), libqt5qml5 (>= 5.15.1), libqt5qmlmodels5 (>= 5.14.1), libstdc++6 (>= 5), qtdeclarative-abi-5-15-2
|
||||
Breaks: libqt5qml5 (<< 5.14.1+dfsg-1~)
|
||||
Replaces: libqt5qml5 (<< 5.14.1+dfsg-1~)
|
||||
Filename: ./qml-module-qtqml_5.15.2+dfsg-6_arm64.deb
|
||||
Size: 29892
|
||||
MD5sum: e074d1765e5eb80909c3b9538b64e8e7
|
||||
SHA1: 9939d50aed9e134c6f04527e67ac7f3d9c78e7b7
|
||||
SHA256: 919ccd7611ef0e28401c423f81d69debeda9f83fb4e11f135aac7740c39dc12d
|
||||
Section: libs
|
||||
Priority: optional
|
||||
Multi-Arch: same
|
||||
Homepage: https://doc.qt.io/qt-5/qmlapplications.html
|
||||
Description: Qt 5 QtQml QML module
|
||||
Qt is a cross-platform C++ application framework. Qt's primary feature
|
||||
is its rich set of widgets that provide standard GUI functionality.
|
||||
.
|
||||
This QML module contains basic QML types.
|
||||
|
||||
Package: qml-module-qtqml-models2
|
||||
Source: qtdeclarative-opensource-src
|
||||
Version: 5.15.2+dfsg-6
|
||||
Architecture: arm64
|
||||
Maintainer: Debian Qt/KDE Maintainers <debian-qt-kde@lists.debian.org>
|
||||
Installed-Size: 110
|
||||
Depends: libc6 (>= 2.17), libqt5core5a (>= 5.0.2), libqt5qml5 (>= 5.15.1), libqt5qmlmodels5 (>= 5.15.1), libstdc++6 (>= 5)
|
||||
Filename: ./qml-module-qtqml-models2_5.15.2+dfsg-6_arm64.deb
|
||||
Size: 30764
|
||||
MD5sum: bce839c759bae1cbb0eba71f403ff43c
|
||||
SHA1: e8336dddb3229e9cc7fc97e3edd097cfbd9111c2
|
||||
SHA256: 55f4a8e20d4106354626553bc263fdef17565e00a64cc02fe8862f0ad3c77273
|
||||
Section: libs
|
||||
Priority: optional
|
||||
Multi-Arch: same
|
||||
Homepage: https://doc.qt.io/qt-5/qmlapplications.html
|
||||
Description: Qt 5 Models2 QML module
|
||||
Qt is a cross-platform C++ application framework. Qt's primary feature
|
||||
is its rich set of widgets that provide standard GUI functionality.
|
||||
.
|
||||
The Models provides types previously found in Qt Quick module.
|
||||
|
||||
Package: qml-module-qtquick-controls
|
||||
Source: qtquickcontrols-opensource-src
|
||||
Version: 5.15.2-2
|
||||
Architecture: arm64
|
||||
Maintainer: Debian Qt/KDE Maintainers <debian-qt-kde@lists.debian.org>
|
||||
Installed-Size: 3292
|
||||
Pre-Depends: dpkg (>= 1.15.6~)
|
||||
Depends: qml-module-qtgraphicaleffects, qml-module-qtqml, qml-module-qtqml-models2, qml-module-qtquick-layouts, qml-module-qtquick-window2, qml-module-qtquick2, libqt5qml5 (<< 5.15.3~), libqt5qml5 (>= 5.15.2+dfsg~), libc6 (>= 2.17), libqt5core5a (>= 5.15.2+dfsg~), libqt5gui5 (>= 5.15.2+dfsg~) | libqt5gui5-gles (>= 5.15.2+dfsg~), libqt5quick5 (>= 5.15.2+dfsg~) | libqt5quick5-gles (>= 5.15.2+dfsg~), libqt5widgets5 (>= 5.15.2+dfsg~), libstdc++6 (>= 5), qtbase-abi-5-15-2, qtdeclarative-abi-5-15-2
|
||||
Filename: ./qml-module-qtquick-controls_5.15.2-2_arm64.deb
|
||||
Size: 519132
|
||||
MD5sum: 4fb9ffc6a767c0cb4ec54f07b7146159
|
||||
SHA1: 1c00d6f505c6d8c2ba149a9d97c02734c33430ba
|
||||
SHA256: c489b997db7121be3e2a90b062d282a12703fd711d0528108939d38820cca9c1
|
||||
Section: libs
|
||||
Priority: optional
|
||||
Multi-Arch: same
|
||||
Homepage: https://doc.qt.io/qt-5/qtquickcontrols1-index.html
|
||||
Description: Qt 5 Quick Controls QML module
|
||||
Qt is a cross-platform C++ application framework. Qt's primary feature
|
||||
is its rich set of widgets that provide standard GUI functionality.
|
||||
.
|
||||
The Qt Quick Controls module provides a set of controls that can be used to
|
||||
build complete interfaces in Qt Quick.
|
||||
|
||||
Package: qml-module-qtquick-controls2
|
||||
Source: qtquickcontrols2-opensource-src
|
||||
Version: 5.15.2+dfsg-2
|
||||
|
|
@ -15271,6 +15365,29 @@ Description: Qt 5 Qt Quick Controls 2 QML module
|
|||
.
|
||||
This package contains the Qt Quick Controls 2 QML module.
|
||||
|
||||
Package: qml-module-qtquick-layouts
|
||||
Source: qtdeclarative-opensource-src
|
||||
Version: 5.15.2+dfsg-6
|
||||
Architecture: arm64
|
||||
Maintainer: Debian Qt/KDE Maintainers <debian-qt-kde@lists.debian.org>
|
||||
Installed-Size: 228
|
||||
Depends: libc6 (>= 2.17), libqt5core5a (>= 5.10.0), libqt5gui5 (>= 5.5.0) | libqt5gui5-gles (>= 5.5.0), libqt5qml5 (>= 5.15.1), libqt5quick5 (>= 5.12.2) | libqt5quick5-gles (>= 5.12.2), libstdc++6 (>= 5), qtbase-abi-5-15-2, qtdeclarative-abi-5-15-2
|
||||
Filename: ./qml-module-qtquick-layouts_5.15.2+dfsg-6_arm64.deb
|
||||
Size: 61164
|
||||
MD5sum: e1ba6a1dbd0d5fe373e62f78307aba2a
|
||||
SHA1: 6a9ef0d3f8a7d9373c018c16ba4b86d02e7ea8de
|
||||
SHA256: 568e4f7cd87e7cab7fe187890aa84afd82cf739c51e4a5b6af7d8bf9c67c0198
|
||||
Section: libs
|
||||
Priority: optional
|
||||
Multi-Arch: same
|
||||
Homepage: https://doc.qt.io/qt-5/qmlapplications.html
|
||||
Description: Qt 5 Quick Layouts QML module
|
||||
Qt is a cross-platform C++ application framework. Qt's primary feature
|
||||
is its rich set of widgets that provide standard GUI functionality.
|
||||
.
|
||||
The Qt Quick Layouts modules provides a set of layouts that can be used to
|
||||
build complete interfaces in Qt Quick.
|
||||
|
||||
Package: qml-module-qtquick-templates2
|
||||
Source: qtquickcontrols2-opensource-src
|
||||
Version: 5.15.2+dfsg-2
|
||||
|
|
@ -15316,6 +15433,29 @@ Description: Qt virtual keyboard - QML module
|
|||
.
|
||||
This package contains the QML module.
|
||||
|
||||
Package: qml-module-qtquick-window2
|
||||
Source: qtdeclarative-opensource-src
|
||||
Version: 5.15.2+dfsg-6
|
||||
Architecture: arm64
|
||||
Maintainer: Debian Qt/KDE Maintainers <debian-qt-kde@lists.debian.org>
|
||||
Installed-Size: 138
|
||||
Depends: libc6 (>= 2.17), libqt5core5a (>= 5.5.0), libqt5gui5 (>= 5.2.0) | libqt5gui5-gles (>= 5.2.0), libqt5qml5 (>= 5.15.1), libqt5quick5 (>= 5.15.1) | libqt5quick5-gles (>= 5.15.1), libstdc++6 (>= 5), qtdeclarative-abi-5-15-2
|
||||
Filename: ./qml-module-qtquick-window2_5.15.2+dfsg-6_arm64.deb
|
||||
Size: 37456
|
||||
MD5sum: 77034df8c15be723f250797c2516f4ad
|
||||
SHA1: 0d94d8333aadbf3ce836babd530780f3ea3a176e
|
||||
SHA256: 6704425a99db956035c91614d117bcf50ab8f2de7be60c8b291836009f4a984c
|
||||
Section: libs
|
||||
Priority: optional
|
||||
Multi-Arch: same
|
||||
Homepage: https://doc.qt.io/qt-5/qmlapplications.html
|
||||
Description: Qt 5 window 2 QML module
|
||||
Qt is a cross-platform C++ application framework. Qt's primary feature
|
||||
is its rich set of widgets that provide standard GUI functionality.
|
||||
.
|
||||
This QML module contains types for creating top-level windows and
|
||||
accessing screen information.
|
||||
|
||||
Package: qml-module-qtquick-xmllistmodel
|
||||
Source: qtxmlpatterns-opensource-src
|
||||
Version: 5.15.2-3
|
||||
|
|
|
|||
Binary file not shown.
BIN
third_party/debian/bullseye-arm64/repo/qml-module-qtgraphicaleffects_5.15.2-2_arm64.deb
vendored
Normal file
BIN
third_party/debian/bullseye-arm64/repo/qml-module-qtgraphicaleffects_5.15.2-2_arm64.deb
vendored
Normal file
Binary file not shown.
BIN
third_party/debian/bullseye-arm64/repo/qml-module-qtqml-models2_5.15.2+dfsg-6_arm64.deb
vendored
Normal file
BIN
third_party/debian/bullseye-arm64/repo/qml-module-qtqml-models2_5.15.2+dfsg-6_arm64.deb
vendored
Normal file
Binary file not shown.
BIN
third_party/debian/bullseye-arm64/repo/qml-module-qtqml_5.15.2+dfsg-6_arm64.deb
vendored
Normal file
BIN
third_party/debian/bullseye-arm64/repo/qml-module-qtqml_5.15.2+dfsg-6_arm64.deb
vendored
Normal file
Binary file not shown.
BIN
third_party/debian/bullseye-arm64/repo/qml-module-qtquick-controls_5.15.2-2_arm64.deb
vendored
Normal file
BIN
third_party/debian/bullseye-arm64/repo/qml-module-qtquick-controls_5.15.2-2_arm64.deb
vendored
Normal file
Binary file not shown.
BIN
third_party/debian/bullseye-arm64/repo/qml-module-qtquick-layouts_5.15.2+dfsg-6_arm64.deb
vendored
Normal file
BIN
third_party/debian/bullseye-arm64/repo/qml-module-qtquick-layouts_5.15.2+dfsg-6_arm64.deb
vendored
Normal file
Binary file not shown.
BIN
third_party/debian/bullseye-arm64/repo/qml-module-qtquick-window2_5.15.2+dfsg-6_arm64.deb
vendored
Normal file
BIN
third_party/debian/bullseye-arm64/repo/qml-module-qtquick-window2_5.15.2+dfsg-6_arm64.deb
vendored
Normal file
Binary file not shown.
|
|
@ -16,6 +16,7 @@ lxterminal openbox wmctrl xdotool libqt5serialbus5-bin qml-module-qtmultimedia
|
|||
qml-module-qtpositioning qml-module-qtquick-virtualkeyboard qtvirtualkeyboard-plugin
|
||||
qml-module-qtwebview qml-module-qt-labs-settings qml-module-qtquick-xmllistmodel
|
||||
qml-module-qtquick-controls2 qml-module-qt-websockets qml-module-qt-labs-platform
|
||||
qml-module-qtquick-window2 qml-module-qtquick-layouts qml-module-qtquick-controls
|
||||
# Camera streaming and snapshots (CLI, in addition to multimedia libraries).
|
||||
ffmpeg
|
||||
# Keep installed OpenCV/GStreamer development chains compatible during FFmpeg upgrades.
|
||||
|
|
|
|||
Loading…
Reference in New Issue