Compare commits
33 Commits
autodetect
...
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 | |
|
|
6831198f88 | |
|
|
4dc02de4a2 | |
|
|
9036a5ad7f | |
|
|
fd957c4ccc | |
|
|
783b911664 | |
|
|
041db9086f | |
|
|
8c6fadf7ea | |
|
|
8a0eb6eb39 |
|
|
@ -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,11 @@
|
|||
# Edge Console 3.1.28
|
||||
|
||||
- Replace the browser-native Modbus conflict confirmation with the shared
|
||||
centered Console dialog when an active it-screen service must be paused.
|
||||
- Present an explicit warning with Continue and Cancel actions, and preserve
|
||||
the shared modal behavior for backdrop clicks, Escape and stacked layers.
|
||||
- Add localized confirmation copy for Russian, Polish, Arabic and Hindi.
|
||||
- Add a regression contract that prevents this flow from returning to
|
||||
`window.confirm`.
|
||||
- Validation: all 128 Console backend tests and all 24 stage catalog tests pass;
|
||||
JavaScript syntax checks and release diff checks pass.
|
||||
|
|
@ -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,51 @@
|
|||
# stage_env 1.0.5
|
||||
|
||||
- Adds iOmatex wallpaper and EVAx10 launchers to the existing Debian LXDE
|
||||
desktop, application menu and bottom panel. Uses the existing iOmatex logo
|
||||
and EVAx10 launcher artwork from the shared client source.
|
||||
- Calculates desktop launcher position at X11 login; preserves other desktop
|
||||
entries and panel plugins, with backups outside LXPanel's panels directory.
|
||||
- Starts the existing `itscreen-x11.service` via a narrowly scoped sudo rule.
|
||||
Opening EVAx10 leaves the desktop for the dedicated client session; it does
|
||||
not launch a competing player or change the next-boot service policy.
|
||||
- Brands LightDM GTK greeter when installed. Other desktop environments receive
|
||||
the application menu entry only. Does not change bootloader/Plymouth artwork.
|
||||
- Apply by updating stage_env and logging into the desktop again. Runtime visual
|
||||
verification on Debian hardware is still required before deployment.
|
||||
|
||||
- Bench follow-up: adds Debian 11 XFCE support after detecting the actual desktop
|
||||
on g-box-8e6af561. Reuses the existing `evax10-return.desktop` identity and
|
||||
`/usr/local/sbin/iomatex-desktop return` transition where available. The branding
|
||||
helper is named `iomatex-desktop-branding` to avoid shadowing that owner.
|
||||
- XFCE preserves the existing panel, adds one launcher, disables bottom-panel
|
||||
autohide, and uses readable dark desktop labels on the light wallpaper.
|
||||
- Five automated tests pass. On 192.168.0.109 the branded greeter and XFCE desktop
|
||||
were visually inspected, and clicking the bottom-panel EVAx10 launcher returned
|
||||
to the existing client service. This was a targeted branding installation, not
|
||||
a full stage_env upgrade or a reboot test.
|
||||
|
||||
- User reference revision: purple wave wallpaper, rounded vector tiles, a
|
||||
two-row launcher layout and compact dock replace the initial light desktop.
|
||||
LightDM and Debian startup now use the supplied IOMATEX BRAIN artwork.
|
||||
- Adds a bounded framebuffer preloader before the graphical session, with
|
||||
explicit shutdown before LightDM or the client X11 service. Firmware/U-Boot
|
||||
FIT contents are not modified. This supersedes the earlier no-splash scope.
|
||||
- Actual reboot validated on g-box-8e6af561: framebuffer artwork rendered at
|
||||
1920x1080 and stopped before the client; EVAx10 and all three reverse tunnels
|
||||
restarted. This validates the userspace boot path, not firmware splash changes.
|
||||
- Replaces the provisional io artwork with the canonical IOMATEX_APP
|
||||
`assets/icon/play_store_512.png`, copied unchanged. Desktop, dock and menu
|
||||
entries are named EVAx10 and share that icon.
|
||||
- Field terminal: LXTerminal replaces the XTerm default through one shared
|
||||
launcher. Initial settings use DejaVu Sans Mono 18, a high-contrast dark theme,
|
||||
10,000 scrollback lines and Ctrl+= / Ctrl+- / Ctrl+0 font zoom shortcuts.
|
||||
Interactive local Bash sessions show a Russian engineer quick reference;
|
||||
`edge-help` repeats it. User font changes survive subsequent branding runs.
|
||||
- Corrects the preceding icon-source entry: uses the dark EVAx10 launcher from
|
||||
the published Edge installer 5.1.42 source commit c75170b6, shared with Windows
|
||||
and Android. The older IOMATEX_APP IO icon is superseded. The exact source and
|
||||
checksum are recorded in stage_env/desktop/app-icon-source.json.
|
||||
|
||||
- Final branding correction: the engineer terminal and its startup help use
|
||||
iOmatex; EVAx10 names only the client application. Six desktop/terminal
|
||||
regression tests pass. Release preserves stage_itscreen 1.0.33 (client 5.1.42).
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
# stage_itscreen 1.0.29 — Debian ARM64 client 5.1.30
|
||||
|
||||
- Publish the native Debian 11 ARM64 / Qt 5.15.2 binary verified on
|
||||
g-box-a77923b4 and g-box-8e6af561.
|
||||
- Preserve newly started event components during unchanged configuration
|
||||
reconciliation, including zero elapsed time. Keep existing live timers and
|
||||
retain rule-change, duration and schedule safety checks.
|
||||
- Complete unchanged-configuration acknowledgements after parallel workers
|
||||
settle, so subsequent configuration updates do not remain queued.
|
||||
- Include the 5.1.29 configuration application fixes. Remove credential values
|
||||
from client diagnostics.
|
||||
- Native client version: 5.1.30 (5010030); installer stage: 1.0.29.
|
||||
- Validation: 33 JavaScript suites and 61 Python tests (2 environment skips)
|
||||
recorded for the client build; on-Edge Qt regression simulations passed.
|
||||
Two real config acknowledgements completed in 2.69/2.73 seconds. Local Edge
|
||||
startup, MQTT connection and playback were verified. Full scheduled pump
|
||||
operation over five hours has not been verified.
|
||||
|
||||
Source commit and build provenance: stage_itscreen/release-provenance.json.
|
||||
SHA256: 4d2d55b00b259d582c004cc0096e3a480394c53299dcfb42ec6cda66643100d6.
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
# stage_itscreen 1.0.30 — Debian ARM64 client 5.1.31
|
||||
|
||||
- Publish Client 5.1.31 with deterministic RS485 model classification.
|
||||
- Keep an explicit `IOMATEX ExBd NANO` identity mapped to ExBd Nano instead of
|
||||
reclassifying it as SNG-500 from ambiguous readable registers.
|
||||
- Recognize explicit SNG-500 and PT-100 identities and use their canonical
|
||||
catalogue types.
|
||||
- Preserve the configuration acknowledgement and fresh-event reconciliation
|
||||
fixes from Client 5.1.30.
|
||||
- Native client version: 5.1.31 (5010031); installer stage: 1.0.30.
|
||||
- Validation: all 33 JavaScript files and 62 Python tests passed (2
|
||||
environment-dependent skips). Clean Debian 11 ARM64 / Qt 5.15.2 release
|
||||
compilation passed; the AArch64 ELF embeds the expected version and type
|
||||
identities and retains the 5.1.30 runtime dependency set.
|
||||
|
||||
Source commit and build provenance: `stage_itscreen/release-provenance.json`.
|
||||
SHA-256: `c3488ebce78fe3c43a66f9a578774501c2b826a4798b316c40bdadafbce414f0`.
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
# stage_itscreen 1.0.31 — Debian client 5.1.33
|
||||
|
||||
- Publish the tested ARM64 binary from client commit
|
||||
`32a404bfe04e06e4649692e8c131a9bbfe3b1906` (autodetect_revision).
|
||||
- Fix scanner/transport timeout ordering, validate scan requests, apply baud
|
||||
changes, reserve the runtime port during scanning and cancel stale reconnects.
|
||||
- Preserve identified modules when optional metadata fails; do not classify
|
||||
generic register replies as ExBD hardware.
|
||||
- Verified Nano discovery and restored runtime polling on local Edge.
|
||||
- Python contracts, 35 JavaScript test files, native scanner/dispatcher/recovery
|
||||
tests passed; image/video playback and corrected URL transitions were observed.
|
||||
- This release does not claim to fix the separate intermittent video stream
|
||||
error observed on the earlier client. WebView lazy creation is not included.
|
||||
|
||||
Checksum and build/source provenance are recorded in stage_itscreen.
|
||||
The installer and Console implementation are unchanged.
|
||||
|
|
@ -0,0 +1,5 @@
|
|||
# stage_itscreen 1.0.32 — EVAx10 5.1.37
|
||||
|
||||
Shared persistent fullscreen setting, default enabled. Desktop windowed mode supports moving and resizing; saved preference overrides legacy launcher flags. EGLFS/LinuxFB remain fullscreen.
|
||||
|
||||
Source: 37d311c4fa67bcfbf5df7acb8573fb092963abc2. Native ARM64 build and window controller tests passed. Physical playback of this release has not been revalidated. Installer unchanged. See release-provenance.json and itscreen.sha256.
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
# stage_itscreen 1.0.33 — EVAx10 Client 5.1.42
|
||||
|
||||
- Update Debian ARM64 client from the common iomatex_dev release source recorded
|
||||
in stage_itscreen/release-provenance.json. The client version is shared with
|
||||
Android and Windows; the OS stage revision is an independent installer version.
|
||||
- Install the restricted YF MCU wake adapter and sudo rule with the client.
|
||||
- Install Debian password-protected LightDM maintenance entry and return launcher
|
||||
on systems with LightDM. System PAM requires a nonempty Unix password; guest
|
||||
and autologin are disabled. The app never reads/stores the OS password.
|
||||
- Permit the client to enable/disable only its own OS autostart service.
|
||||
- Keep updater URLs, registration, media and existing desktop runtime intact.
|
||||
This stage does not publish changes from other OS stage work in progress.
|
||||
|
||||
Validation: stage version tests and display/fullscreen contracts pass. Previous
|
||||
bench validation includes MCU timed wake, reboot, mandatory-password XFCE login
|
||||
and return to client. Android automatic wake is not implied by this Debian test.
|
||||
|
|
@ -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), \
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"schema": 1,
|
||||
"stages": {
|
||||
"stage_env": {
|
||||
"version": "1.0.4"
|
||||
"version": "1.0.5"
|
||||
},
|
||||
"stage_wifi": {
|
||||
"version": "1.0.0"
|
||||
|
|
@ -14,7 +14,7 @@
|
|||
"version": "1.0.1"
|
||||
},
|
||||
"stage_ui": {
|
||||
"version": "3.1.27"
|
||||
"version": "3.1.42"
|
||||
},
|
||||
"stage_avahi": {
|
||||
"version": "1.0.0"
|
||||
|
|
@ -23,7 +23,7 @@
|
|||
"version": "1.0.0"
|
||||
},
|
||||
"stage_itscreen": {
|
||||
"version": "1.0.28"
|
||||
"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()
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
# Desktop artwork
|
||||
|
||||
- Reference: `desktop-reference.png`, supplied by user as `Descktop style for Debian .png`.
|
||||
- `transition.png`: unchanged copy of user-supplied `new logo 2.png`.
|
||||
- `wallpaper-purple.png`: generated with the built-in image_gen tool from the
|
||||
desktop reference, then copied into this directory. Original output:
|
||||
`/home/andrei/.codex/generated_images/01a0898f-efc3-71e2-b4ca-2d98847887ed/exec-d32123cd-51c2-4e23-959e-08d188a2d7cb.png`.
|
||||
- `iomatex-io.svg` and `icons/*.svg`: editable vector launch icons matching the
|
||||
reference's rounded tiles; native icons, not screenshots of controls.
|
||||
|
||||
Image generation prompt:
|
||||
|
||||
> Edit target: attached desktop reference. Produce ONLY the clean wallpaper
|
||||
> background for a real Linux desktop, 1920x1080 landscape. Preserve the dark
|
||||
> navy/black and purple flowing luminous wave design, bright lavender upper right
|
||||
> glow and sweeping blue-white/lavender light ribbons across the lower half.
|
||||
> Remove ALL icons, labels, text, status bar, bottom dock, avatar, plus buttons,
|
||||
> and the black exterior frame. Extend the background naturally to fill a full
|
||||
> 16:9 image. No text, no symbols, no UI, no logo. Keep the upper middle relatively
|
||||
> dark and calm so actual desktop launcher icons will be readable.
|
||||
|
||||
The generated image is 1672x941; XFCE scales/crops it to the monitor resolution.
|
||||
|
||||
Application icon correction: `evax10.png` is now an unchanged copy of
|
||||
`IOMATEX_APP/assets/icon/play_store_512.png`, selected by that project's
|
||||
`pubspec.yaml` flutter_icons.image_path. The custom `iomatex-io.svg` was removed.
|
||||
All desktop, dock and menu launchers display the name EVAx10 and the same PNG.
|
||||
|
||||
Superseding correction: the IOMATEX_APP icon above was an obsolete product
|
||||
asset. The canonical Edge installer icon is `evax10_launcher.png`, copied
|
||||
unchanged from `Development/It-screenClient`, source commit
|
||||
`c75170b64ccff88b0a80edf9e21d1382960c9834`, as named by the published Windows
|
||||
5.1.42 channel manifest. `packaging/windows/client.iss` uses `images/evax10.ico`;
|
||||
`admonclient.pro` embeds it into the executable used by Windows shortcuts.
|
||||
Android's generator copies `images/evax10_launcher.png` unchanged. Provenance and
|
||||
the PNG checksum are recorded in `app-icon-source.json` beside the asset.
|
||||
|
|
@ -0,0 +1,87 @@
|
|||
# Debian desktop branding
|
||||
|
||||
Owned by stage_env 1.0.5. Supports Debian 11 XFCE and LXDE/PCManFM/LXPanel;
|
||||
does not install or switch the desktop environment, restart X11, or change
|
||||
the client auto-start policy. LightDM GTK greeter receives the same wallpaper.
|
||||
The bootloader and Plymouth splash are separate and unchanged.
|
||||
|
||||
The desktop and panel both use `evax10-return.desktop`. Its launcher starts
|
||||
`itscreen-x11.service`, whose existing Conflicts stops LightDM. Save desktop
|
||||
work before opening EVAx10. Before stage_itscreen is installed it displays an
|
||||
installation message. Service failure details remain in Edge Console/journal.
|
||||
|
||||
Where the client maintenance helper `/usr/local/sbin/iomatex-desktop` exists,
|
||||
the launcher delegates to its `return` command. The branding helper deliberately
|
||||
uses the distinct name `iomatex-desktop-branding`.
|
||||
|
||||
XFCE uses its existing xfconf XML and panel launcher directories. The helper
|
||||
adds a launcher to the bottom panel and makes that panel permanently visible.
|
||||
Desktop position uses the XFCE 4.16 row/column grid near the screen center;
|
||||
GTK labels use dark text for contrast against the light background. The GTK
|
||||
block has managed markers; other user GTK styles are retained. Apply while the
|
||||
desktop is logged out, or at the next X11 login, so xfconfd cannot overwrite
|
||||
offline changes. XFCE 4.20's YAML icon position format is not supported yet.
|
||||
|
||||
`~/.xsessionrc` runs the helper before PCManFM/LXPanel start. XRandR supplies
|
||||
the screen dimensions; headless installation uses a temporary 1280x720 layout,
|
||||
recomputed at desktop login. Hot-plugging a display requires a new login to
|
||||
recenter the shortcut. The helper respects XDG_DESKTOP_DIR and keeps existing
|
||||
desktop items and panel plugins. It adds a compact bottom panel only if none
|
||||
exists. Initial files are backed up under `.iomatex-backups` beside the modified
|
||||
configuration directories, never inside the LXPanel panels directory.
|
||||
|
||||
Artwork: `stage_ui/iomatex_logo_source.png` is the canonical iOmatex logo.
|
||||
`evax10.png` is copied unchanged from It-screenClient's
|
||||
`iomatex_dev:images/evax10_launcher.png`; no client build is included.
|
||||
|
||||
Configuration references:
|
||||
- https://github.com/lxde/pcmanfm/blob/master/src/desktop.c
|
||||
- https://github.com/lxde/lxpanel (launchbar plugin)
|
||||
|
||||
Validation: `python3 -m unittest discover -s stage_env/desktop -p 'test_*.py'`.
|
||||
On a Debian bench, additionally verify login, icon placement, bottom panel,
|
||||
EVAx10 launch, subsequent return to desktop, and a repeated stage_env run.
|
||||
|
||||
## Purple desktop revision
|
||||
|
||||
The user-supplied reference supersedes the original light desktop. XFCE now
|
||||
uses `wallpaper-purple.png`, rounded SVG tiles, six launchers on the first row,
|
||||
Trash and four add-shortcut actions on the second row, and a compact dark dock.
|
||||
Panel definitions are preserved in XML, but the visible plugin ordering is
|
||||
intentionally changed to match the reference. Home opens local Edge Console;
|
||||
Light opens display/power settings; Terminal uses Debian's x-terminal-emulator
|
||||
alternative. Plus buttons open XFCE's native launcher editor.
|
||||
|
||||
`transition.png` is used by LightDM and the bounded Debian userspace preloader.
|
||||
`iomatex-boot-splash.service` paints the existing 32-bit Rockchip DRM framebuffer
|
||||
after local filesystems are available. It exits within 90 seconds and is stopped
|
||||
by display-service ExecStartPre hooks before X11 starts. Unsupported framebuffer
|
||||
layouts fail without blocking the display services. The installer enables the
|
||||
service but never starts it over a running X session.
|
||||
|
||||
The bench's vendor bootanim hook directory is absent, so that service currently
|
||||
draws nothing. The new service owns the Debian userspace preloader. It does not
|
||||
rewrite the U-Boot FIT image, its signature, kernel, DTB or firmware logo.bmp.
|
||||
The very first firmware frame remains outside this userspace customization.
|
||||
|
||||
Bench backups live in `/userdata/iomatex-dev/backups/desktop-before-purple-20261029.tar.gz`.
|
||||
To disable the preloader: `sudo systemctl disable --now iomatex-boot-splash`.
|
||||
Restore the desktop/LightDM files from the backup while logged out, and remove
|
||||
the branding hook from `.xsessionrc` when rolling the customization back.
|
||||
|
||||
## Field terminal
|
||||
|
||||
`iomatex-terminal` delegates to the packaged LXTerminal GTK/VTE terminal. It is
|
||||
the desktop/dock launcher and Debian x-terminal-emulator alternative. stage_env
|
||||
ensures lxterminal and fonts-dejavu-core from the existing offline package set.
|
||||
No client or desktop restart is needed for installation; open a new terminal.
|
||||
|
||||
The first configuration sets DejaVu Sans Mono 18, dark colors, scrollback and
|
||||
font shortcuts. `.config/iomatex/field-terminal-v1` prevents later logins/updates
|
||||
from overwriting engineer preferences. Edit → Preferences → Style → Font saves
|
||||
a permanent font choice; Ctrl+=, Ctrl+- and Ctrl+0 change temporary zoom.
|
||||
|
||||
The managed `.bashrc` hook runs only for interactive local graphical shells;
|
||||
SSH/noninteractive commands receive no startup output. `edge-help` is available
|
||||
in interactive Bash. Original `.bashrc` is backed up inside the user's home at
|
||||
`.local/state/iomatex-desktop/backups/bashrc`.
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
{
|
||||
"repository": "Development/It-screenClient",
|
||||
"source_commit": "c75170b64ccff88b0a80edf9e21d1382960c9834",
|
||||
"source_path": "images/evax10_launcher.png",
|
||||
"windows_icon": "images/evax10.ico",
|
||||
"release_manifest": "An-J/DOWNLOAD_IOMATEX_APP:Windows_Client:edge-client/windows/latest.json",
|
||||
"release_version": "5.1.42",
|
||||
"sha256": "6292d9350b503d66ad975ce003242284f59039af6d2407d2d617e39005b58578"
|
||||
}
|
||||
|
After Width: | Height: | Size: 845 KiB |
|
|
@ -0,0 +1,10 @@
|
|||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=EVAx10
|
||||
Comment=Switch from the desktop to the EVAx10 client
|
||||
Comment[ru]=Перейти с рабочего стола в приложение EVAx10
|
||||
Exec=/usr/local/bin/iomatex-open-evax10
|
||||
Icon=/usr/local/share/iomatex/desktop/evax10_launcher.png
|
||||
Terminal=false
|
||||
Categories=Utility;
|
||||
StartupNotify=false
|
||||
|
After Width: | Height: | Size: 1.8 MiB |
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128"><defs><linearGradient id="tile" x2="0" y2="1"><stop stop-color="#a68edb"/><stop offset="1" stop-color="#514a78"/></linearGradient></defs><rect x="4" y="4" width="120" height="120" rx="28" fill="url(#tile)" fill-opacity=".6" stroke="#e8e1ff" stroke-opacity=".5"/><path d="M64 42v44M42 64h44" stroke="#c4bce2" stroke-opacity=".7" stroke-width="3"/></svg>
|
||||
|
After Width: | Height: | Size: 440 B |
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128"><defs><linearGradient id="tile" x2="0" y2="1"><stop stop-color="#ffffff"/><stop offset="1" stop-color="#ddd9e8"/></linearGradient></defs><rect x="4" y="4" width="120" height="120" rx="28" fill="url(#tile)" fill-opacity="1" stroke="#e8e1ff" stroke-opacity=".5"/><path d="M21 38h32l9 10h45v55H21Z" fill="#ddb26b" stroke="#c79e5d" stroke-width="3"/><rect x="26" y="49" width="75" height="40" rx="5" fill="#81b9b5"/><rect x="29" y="58" width="71" height="35" rx="5" fill="#e9e7d9"/><path d="M18 70h92l-9 36H26Z" fill="#efc986" stroke="#dab578" stroke-width="2"/></svg>
|
||||
|
After Width: | Height: | Size: 652 B |
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128"><defs><linearGradient id="tile" x2="0" y2="1"><stop stop-color="#ffffff"/><stop offset="1" stop-color="#ddd9e8"/></linearGradient></defs><rect x="4" y="4" width="120" height="120" rx="28" fill="url(#tile)" fill-opacity="1" stroke="#e8e1ff" stroke-opacity=".5"/><path d="M27 61L64 28 101 61" fill="none" stroke="#ed8078" stroke-width="12" stroke-linecap="round" stroke-linejoin="round"/><path d="M37 59v42h54V59" fill="#d9f0f1" stroke="#b6cdce" stroke-width="4"/><path d="M56 101V74h17v27" fill="#f3c4bc"/></svg>
|
||||
|
After Width: | Height: | Size: 599 B |
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128"><defs><linearGradient id="tile" x2="0" y2="1"><stop stop-color="#ffffff"/><stop offset="1" stop-color="#ddd9e8"/></linearGradient></defs><rect x="4" y="4" width="120" height="120" rx="28" fill="url(#tile)" fill-opacity="1" stroke="#e8e1ff" stroke-opacity=".5"/><path d="M46 65a26 26 0 1 1 36 0L77 87H51Z" fill="#fff8dc" stroke="#ceced8" stroke-width="3"/><path d="M53 88h22m-20 7h18m-16 7h14" stroke="#96949c" stroke-width="5" stroke-linecap="round"/><path d="M59 84l-5-30 10 9 10-9-5 30" fill="none" stroke="#ddc58a" stroke-width="2"/></svg>
|
||||
|
After Width: | Height: | Size: 630 B |
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128"><defs><linearGradient id="tile" x2="0" y2="1"><stop stop-color="#ffffff"/><stop offset="1" stop-color="#ddd9e8"/></linearGradient></defs><rect x="4" y="4" width="120" height="120" rx="28" fill="url(#tile)" fill-opacity="1" stroke="#e8e1ff" stroke-opacity=".5"/><g fill="none" stroke="#62616c" stroke-width="9"><circle cx="64" cy="64" r="26"/><circle cx="64" cy="64" r="10"/><path d="M64 23v12" transform="rotate(0 64 64)"/><path d="M64 23v12" transform="rotate(45 64 64)"/><path d="M64 23v12" transform="rotate(90 64 64)"/><path d="M64 23v12" transform="rotate(135 64 64)"/><path d="M64 23v12" transform="rotate(180 64 64)"/><path d="M64 23v12" transform="rotate(225 64 64)"/><path d="M64 23v12" transform="rotate(270 64 64)"/><path d="M64 23v12" transform="rotate(315 64 64)"/></g></svg>
|
||||
|
After Width: | Height: | Size: 876 B |
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128"><defs><linearGradient id="tile" x2="0" y2="1"><stop stop-color="#ffffff"/><stop offset="1" stop-color="#ddd9e8"/></linearGradient></defs><rect x="4" y="4" width="120" height="120" rx="28" fill="url(#tile)" fill-opacity="1" stroke="#e8e1ff" stroke-opacity=".5"/><rect x="16" y="22" width="96" height="84" rx="12" fill="#20252b" stroke="#afb8ba" stroke-width="3"/><path d="M29 43l11 8-11 8m22 4h13" fill="none" stroke="#8ade84" stroke-width="4"/></svg>
|
||||
|
After Width: | Height: | Size: 538 B |
|
|
@ -0,0 +1 @@
|
|||
<svg xmlns="http://www.w3.org/2000/svg" width="128" height="128" viewBox="0 0 128 128"><defs><linearGradient id="tile" x2="0" y2="1"><stop stop-color="#a68edb"/><stop offset="1" stop-color="#514a78"/></linearGradient></defs><rect x="4" y="4" width="120" height="120" rx="28" fill="url(#tile)" fill-opacity="1" stroke="#e8e1ff" stroke-opacity=".5"/><path d="M39 41l6 62h38l6-62Z" fill="#ddd3f3" fill-opacity=".55" stroke="#eee7ff" stroke-width="3"/><ellipse cx="64" cy="40" rx="27" ry="7" fill="#a499bb" stroke="#eee7ff" stroke-width="3"/><path d="M51 52l3 39m10-39v39m13-39-3 39" stroke="#f0ebff" stroke-width="2"/></svg>
|
||||
|
After Width: | Height: | Size: 622 B |
|
|
@ -0,0 +1,81 @@
|
|||
#!/usr/bin/python3
|
||||
"""Bounded userspace splash for the Rockchip DRM framebuffer; never writes firmware."""
|
||||
import ctypes as c
|
||||
import fcntl
|
||||
import mmap
|
||||
from pathlib import Path
|
||||
import signal
|
||||
import struct
|
||||
import time
|
||||
|
||||
running = True
|
||||
|
||||
|
||||
def stop(*unused):
|
||||
global running
|
||||
running = False
|
||||
|
||||
|
||||
def load_pixels(filename, width, height):
|
||||
lib = c.CDLL('libgdk_pixbuf-2.0.so.0')
|
||||
lib.gdk_pixbuf_new_from_file_at_scale.argtypes = [c.c_char_p, c.c_int, c.c_int, c.c_int, c.c_void_p]
|
||||
lib.gdk_pixbuf_new_from_file_at_scale.restype = c.c_void_p
|
||||
ptr = lib.gdk_pixbuf_new_from_file_at_scale(str(filename).encode(), width, height, 1, None)
|
||||
if not ptr:
|
||||
raise RuntimeError('Unable to decode splash artwork')
|
||||
values = []
|
||||
for name in ('width', 'height', 'rowstride', 'n_channels'):
|
||||
fn = getattr(lib, 'gdk_pixbuf_get_' + name)
|
||||
fn.argtypes = [c.c_void_p]
|
||||
fn.restype = c.c_int
|
||||
values.append(fn(ptr))
|
||||
w, h, stride, channels = values
|
||||
lib.gdk_pixbuf_get_pixels.argtypes = [c.c_void_p]
|
||||
lib.gdk_pixbuf_get_pixels.restype = c.c_void_p
|
||||
data = c.string_at(lib.gdk_pixbuf_get_pixels(ptr), (h - 1) * stride + w * channels)
|
||||
return w, h, stride, channels, data
|
||||
|
||||
|
||||
def main():
|
||||
# This service is ordered before display managers and stopped before X starts.
|
||||
if Path('/tmp/.X0-lock').exists():
|
||||
raise RuntimeError('X display already owns the framebuffer')
|
||||
with open('/dev/fb0', 'r+b', buffering=0) as fb:
|
||||
info = bytearray(160)
|
||||
fcntl.ioctl(fb, 0x4600, info, True) # FBIOGET_VSCREENINFO
|
||||
width, height = struct.unpack_from('II', info)
|
||||
bpp = struct.unpack_from('I', info, 24)[0]
|
||||
offsets = tuple(struct.unpack_from('I', info, i)[0] for i in (32, 44, 56))
|
||||
if bpp != 32 or offsets != (16, 8, 0) or not (320 <= width <= 7680 and 200 <= height <= 4320):
|
||||
raise RuntimeError('Unsupported framebuffer pixel layout')
|
||||
stride = int(Path('/sys/class/graphics/fb0/stride').read_text())
|
||||
w, h, source_stride, channels, data = load_pixels(
|
||||
'/usr/local/share/iomatex/desktop/transition.png', width, int(height * .9))
|
||||
frame = bytearray(stride * height)
|
||||
left, top = (width - w) // 2, (height - h) // 2
|
||||
for y in range(h):
|
||||
row = data[y * source_stride:y * source_stride + w * channels]
|
||||
pixels = bytearray(w * 4)
|
||||
pixels[0::4], pixels[1::4], pixels[2::4] = row[2::channels], row[1::channels], row[0::channels]
|
||||
start = (top + y) * stride + left * 4
|
||||
frame[start:start + len(pixels)] = pixels
|
||||
signal.signal(signal.SIGTERM, stop)
|
||||
signal.signal(signal.SIGINT, stop)
|
||||
with mmap.mmap(fb.fileno(), len(frame)) as screen:
|
||||
screen[:] = frame
|
||||
print('iOmatex splash rendered: %dx%d' % (width, height), flush=True)
|
||||
deadline = time.monotonic() + 90
|
||||
tick = 0
|
||||
while running and time.monotonic() < deadline:
|
||||
for dot in range(3):
|
||||
color = bytes((255, 194, 68, 0)) if dot == tick % 3 else bytes((65, 47, 27, 0))
|
||||
for y in range(height - 35, height - 29):
|
||||
start = y * stride + (width // 2 - 20 + dot * 18) * 4
|
||||
screen[start:start + 24] = color * 6
|
||||
tick += 1
|
||||
time.sleep(.3)
|
||||
print('iOmatex splash stopped', flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
|
|
@ -0,0 +1,17 @@
|
|||
[Unit]
|
||||
Description=iOmatex Debian startup splash
|
||||
DefaultDependencies=no
|
||||
After=local-fs.target
|
||||
Before=basic.target shutdown.target
|
||||
Conflicts=shutdown.target
|
||||
ConditionPathExists=/dev/fb0
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
ExecStart=/usr/local/bin/iomatex-boot-splash
|
||||
TimeoutStopSec=2
|
||||
RuntimeMaxSec=95
|
||||
Nice=10
|
||||
|
||||
[Install]
|
||||
WantedBy=sysinit.target
|
||||
|
|
@ -0,0 +1,356 @@
|
|||
#!/usr/bin/python3
|
||||
"""Configure the existing LXDE desktop before session startup, without restarting it."""
|
||||
import base64
|
||||
import configparser
|
||||
import io
|
||||
from pathlib import Path
|
||||
import re
|
||||
import shutil
|
||||
import subprocess
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
ASSETS = Path('/usr/local/share/iomatex/desktop')
|
||||
APP = 'evax10-return.desktop'
|
||||
SHORTCUTS = [
|
||||
(APP, 'EVAx10', '/usr/local/bin/iomatex-open-evax10', str(ASSETS / 'evax10_launcher.png')),
|
||||
('iomatex-settings.desktop', 'Settings', 'xfce4-settings-manager', str(ASSETS / 'icons/settings.svg')),
|
||||
('iomatex-home.desktop', 'Home', 'xdg-open http://127.0.0.1/', str(ASSETS / 'icons/home.svg')),
|
||||
('iomatex-light.desktop', 'Light', 'xfce4-power-manager-settings', str(ASSETS / 'icons/light.svg')),
|
||||
('iomatex-terminal.desktop', 'Terminal', '/usr/local/bin/iomatex-terminal', str(ASSETS / 'icons/terminal.svg')),
|
||||
('iomatex-files.desktop', 'Files', 'thunar', str(ASSETS / 'icons/files.svg')),
|
||||
('iomatex-trash.desktop', 'Trash', 'thunar trash:///', str(ASSETS / 'icons/trash.svg')),
|
||||
]
|
||||
|
||||
|
||||
def write(path, content, mode=0o644):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
if path.exists() and path.read_text() == content:
|
||||
path.chmod(mode)
|
||||
return
|
||||
# Backups must be outside panels/: LXPanel loads every file in that folder.
|
||||
backup = path.parent.parent / '.iomatex-backups' / path.parent.name / path.name
|
||||
if path.name == '.bashrc':
|
||||
backup = path.parent / '.local/state/iomatex-desktop/backups/bashrc'
|
||||
if path.exists() and not backup.exists():
|
||||
backup.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(path, backup)
|
||||
tmp = path.with_name(path.name + '.iomatex-tmp')
|
||||
tmp.write_text(content)
|
||||
tmp.chmod(mode)
|
||||
tmp.replace(path)
|
||||
|
||||
|
||||
def ini(path, updates):
|
||||
cfg = configparser.ConfigParser(interpolation=None, strict=False)
|
||||
cfg.optionxform = str
|
||||
if path.exists():
|
||||
cfg.read(path)
|
||||
for section, values in updates.items():
|
||||
if not cfg.has_section(section):
|
||||
cfg.add_section(section)
|
||||
cfg[section].update({k: str(v) for k, v in values.items()})
|
||||
out = io.StringIO()
|
||||
cfg.write(out, space_around_delimiters=False)
|
||||
write(path, out.getvalue())
|
||||
|
||||
|
||||
def monitors():
|
||||
try:
|
||||
output = subprocess.check_output(['xrandr', '--query'], text=True,
|
||||
stderr=subprocess.DEVNULL, timeout=5)
|
||||
# Preserve XRandR monitor order, which PCManFM uses for desktop-items-N.
|
||||
return [tuple(map(int, m)) for m in re.findall(
|
||||
r' connected (?:primary )?(\d+)x(\d+)\+(\d+)\+(\d+)', output)] or [(1280, 720, 0, 0)]
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
return [(1280, 720, 0, 0)]
|
||||
|
||||
|
||||
def prop(parent, name, kind='empty', value=None):
|
||||
node = parent.find("property[@name='%s']" % name)
|
||||
if node is None:
|
||||
node = ET.SubElement(parent, 'property', name=name, type=kind)
|
||||
if value is not None:
|
||||
node.set('type', kind)
|
||||
node.set('value', str(value))
|
||||
return node
|
||||
|
||||
|
||||
def configure_xfce(home, desktop, assets, screens, system):
|
||||
config = home / '.config/xfce4'
|
||||
for filename, label, command, icon in SHORTCUTS:
|
||||
if filename == APP:
|
||||
continue
|
||||
write(desktop / filename, '[Desktop Entry]\nType=Application\nName=%s\nExec=%s\nIcon=%s\nTerminal=false\n' %
|
||||
(label, command, icon), 0o755)
|
||||
for i in range(4):
|
||||
write(desktop / ('iomatex-add-%d.desktop' % i),
|
||||
'[Desktop Entry]\nType=Application\nName=+\nExec=exo-desktop-item-edit --create-new "%s"\nIcon=%s\nTerminal=false\n' % (desktop, assets / 'icons/add.svg'),
|
||||
0o755)
|
||||
css = home / '.config/gtk-3.0/gtk.css'
|
||||
existing = css.read_text() if css.exists() else ''
|
||||
existing = re.sub(r'/\* iOmatex desktop begin \*/.*?/\* iOmatex desktop end \*/\n?',
|
||||
'', existing, flags=re.S).rstrip()
|
||||
write(css, existing + '''
|
||||
/* iOmatex desktop begin */
|
||||
XfdesktopIconView.view, XfdesktopIconView.view .label,
|
||||
XfdesktopIconView.view.label {
|
||||
color: #e8e4fc;
|
||||
text-shadow: 0 1px 2px #08031a;
|
||||
}
|
||||
XfdesktopIconView.view:active, XfdesktopIconView.view:selected,
|
||||
XfdesktopIconView.view .label:active, XfdesktopIconView.view.label:selected {
|
||||
color: #e8e4fc;
|
||||
background-color: rgba(128, 108, 200, 0.35);
|
||||
}
|
||||
XfdesktopIconView.view {
|
||||
-XfdesktopIconView-cell-text-width-proportion: 1.5;
|
||||
-XfdesktopIconView-cell-padding: 8;
|
||||
-XfdesktopIconView-cell-spacing: 8;
|
||||
}
|
||||
.xfce4-panel.background {
|
||||
background-color: rgba(35, 28, 70, 0.90);
|
||||
color: #e8e4fc;
|
||||
border-radius: 12px;
|
||||
}
|
||||
.xfce4-panel button { color: #e8e4fc; }
|
||||
.xfce4-panel button:hover { background-color: rgba(128, 108, 200, 0.35); }
|
||||
.xfce4-panel button:active { background-color: rgba(128, 108, 200, 0.5); }
|
||||
.xfce4-panel button:checked { background-color: rgba(128, 108, 200, 0.5); }
|
||||
.xfce4-panel button:hover, .xfce4-panel button:active, .xfce4-panel button:checked {
|
||||
color: #e8e4fc;
|
||||
}
|
||||
/* iOmatex desktop end */
|
||||
''')
|
||||
channels = config / 'xfconf/xfce-perchannel-xml'
|
||||
background = channels / 'xfce4-desktop.xml'
|
||||
tree = ET.parse(background).getroot() if background.exists() else ET.Element(
|
||||
'channel', name='xfce4-desktop', version='1.0')
|
||||
screen = prop(prop(tree, 'backdrop'), 'screen0')
|
||||
# Keep existing connector names, and seed newly connected monitors at login.
|
||||
names = {'monitor0'}
|
||||
try:
|
||||
out = subprocess.check_output(['xrandr', '--query'], text=True,
|
||||
stderr=subprocess.DEVNULL, timeout=5)
|
||||
names.update('monitor' + name for name in re.findall(r'^(\S+) connected', out, re.M))
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass
|
||||
names.update(n.get('name') for n in screen.findall('property'))
|
||||
for name in names:
|
||||
monitor = prop(screen, name)
|
||||
for workspace in range(4):
|
||||
node = prop(monitor, 'workspace%d' % workspace)
|
||||
prop(node, 'last-image', 'string', str(assets / 'wallpaper-purple.png'))
|
||||
prop(node, 'image-style', 'int', 5)
|
||||
prop(node, 'backdrop-cycle-enable', 'bool', 'false')
|
||||
icons = prop(tree, 'desktop-icons')
|
||||
icon_size = max(48, min(128, round(screens[0][0] / 15)))
|
||||
prop(icons, 'icon-size', 'uint', icon_size)
|
||||
prop(icons, 'use-custom-font-size', 'bool', 'true')
|
||||
prop(icons, 'font-size', 'double', 12)
|
||||
files = prop(icons, 'file-icons')
|
||||
for special in ('show-home', 'show-filesystem', 'show-trash', 'show-removable'):
|
||||
prop(files, special, 'bool', 'false')
|
||||
write(background, ET.tostring(tree, encoding='unicode') + '\n')
|
||||
|
||||
panel_file = channels / 'xfce4-panel.xml'
|
||||
source = panel_file if panel_file.exists() else system / 'xfce4/panel/default.xml'
|
||||
tree = ET.parse(source).getroot() if source.exists() else ET.Element(
|
||||
'channel', name='xfce4-panel', version='1.0')
|
||||
panels = prop(tree, 'panels', 'array')
|
||||
plugins = prop(tree, 'plugins')
|
||||
bottom = next((p for p in panels.findall('property')
|
||||
if p.find("property[@name='position']") is not None and
|
||||
p.find("property[@name='position']").get('value', '').startswith('p=10;')), None)
|
||||
if bottom is None:
|
||||
ids = [int(v.get('value')) for v in panels.findall('value')]
|
||||
number = max(ids + [0]) + 1
|
||||
ET.SubElement(panels, 'value', type='int', value=str(number))
|
||||
bottom = prop(panels, 'panel-%d' % number)
|
||||
prop(bottom, 'position', 'string', 'p=10;x=0;y=0')
|
||||
prop(bottom, 'size', 'uint', 48)
|
||||
prop(bottom, 'position-locked', 'bool', 'true')
|
||||
prop(bottom, 'autohide-behavior', 'uint', 0)
|
||||
launcher = next((p for p in plugins.findall('property')
|
||||
if any(v.get('value', '').endswith(APP) for v in p.findall('./property/value'))), None)
|
||||
if launcher is None:
|
||||
ids = [int(p.get('name').split('-')[1]) for p in plugins.findall('property')]
|
||||
number = max(ids + [0]) + 1
|
||||
launcher = prop(plugins, 'plugin-%d' % number, 'string', 'launcher')
|
||||
items = prop(launcher, 'items', 'array')
|
||||
ET.SubElement(items, 'value', type='string', value=APP)
|
||||
number = launcher.get('name').split('-')[1]
|
||||
ids = prop(bottom, 'plugin-ids', 'array')
|
||||
if not any(v.get('value') == number for v in ids.findall('value')):
|
||||
ids.insert(0, ET.Element('value', type='int', value=number))
|
||||
write(config / ('panel/launcher-%s/%s' % (number, APP)), (assets / APP).read_text())
|
||||
# The reference explicitly defines a new dock arrangement. Preserve plugin
|
||||
# definitions for rollback, while selecting the requested visible launchers.
|
||||
dock_ids = [number]
|
||||
for filename in ('iomatex-settings.desktop', 'iomatex-terminal.desktop', 'iomatex-home.desktop', 'iomatex-files.desktop', 'iomatex-trash.desktop'):
|
||||
item = next((p for p in plugins.findall('property')
|
||||
if any(v.get('value', '').endswith(filename) for v in p.findall('./property/value'))), None)
|
||||
if item is None:
|
||||
next_id = max([int(p.get('name').split('-')[1]) for p in plugins.findall('property')] + [0]) + 1
|
||||
item = prop(plugins, 'plugin-%d' % next_id, 'string', 'launcher')
|
||||
ET.SubElement(prop(item, 'items', 'array'), 'value', type='string', value=filename)
|
||||
pid = item.get('name').split('-')[1]
|
||||
dock_ids.append(pid)
|
||||
write(config / ('panel/launcher-%s/%s' % (pid, filename)), (desktop / filename).read_text())
|
||||
ids[:] = [ET.Element('value', type='int', value=i) for i in dock_ids]
|
||||
prop(bottom, 'size', 'uint', 56)
|
||||
prop(bottom, 'length', 'uint', 1)
|
||||
prop(bottom, 'length-adjust', 'bool', 'true')
|
||||
prop(bottom, 'position-locked', 'bool', 'true')
|
||||
for panel in panels.findall('property'):
|
||||
position = panel.find("property[@name='position']")
|
||||
if position is not None and position.get('value', '').startswith('p=6;'):
|
||||
top_ids = panel.find("property[@name='plugin-ids']")
|
||||
if top_ids is not None:
|
||||
retained = []
|
||||
for value in top_ids.findall('value'):
|
||||
plugin = plugins.find("property[@name='plugin-%s']" % value.get('value'))
|
||||
if plugin is not None and plugin.get('value') in ('separator', 'systray', 'clock', 'actions', 'pulseaudio', 'power-manager-plugin'):
|
||||
retained.append(value)
|
||||
top_ids[:] = retained
|
||||
write(panel_file, ET.tostring(tree, encoding='unicode') + '\n')
|
||||
|
||||
# XFCE 4.16 (Debian 11) stores desktop positions as grid row/column.
|
||||
layout_dir = config / 'desktop'
|
||||
layouts = list(layout_dir.glob('icons.screen*.rc'))
|
||||
if not layouts:
|
||||
layouts = [layout_dir / 'icons.screen.latest.rc']
|
||||
width, height, _, _ = screens[0]
|
||||
for layout in layouts:
|
||||
match = re.search(r'-(\d+)x(\d+)\.rc$', layout.name)
|
||||
w, h = map(int, match.groups()) if match else (width - 16, height - 43)
|
||||
cell = icon_size * 1.5 + 24
|
||||
columns = max(6, int(w // cell))
|
||||
start_col = max(0, (columns - 6) // 2)
|
||||
row = max(0, int(h * .23 // cell))
|
||||
updates = {'xfdesktop-version-4.10.3+-rcfile_format': {'4.10.3+': 'true'}}
|
||||
for i, (filename, *_) in enumerate(SHORTCUTS[:6]):
|
||||
updates[str(desktop / filename)] = {'row': row, 'col': start_col + i}
|
||||
for i, filename in enumerate(['iomatex-trash.desktop'] + ['iomatex-add-%d.desktop' % n for n in range(4)]):
|
||||
updates[str(desktop / filename)] = {'row': row + 1, 'col': start_col + i}
|
||||
ini(layout, updates)
|
||||
|
||||
|
||||
def configure_terminal(home):
|
||||
path = home / '.config/lxterminal/lxterminal.conf'
|
||||
marker = home / '.config/iomatex/field-terminal-v1'
|
||||
# Apply defaults once. Preferences edited by the engineer survive login/update.
|
||||
if not marker.exists() or not path.exists():
|
||||
ini(path, {'general': {
|
||||
'fontname': 'DejaVu Sans Mono 18', 'scrollback': 10000,
|
||||
'bgcolor': 'rgb(15,20,31)', 'fgcolor': 'rgb(228,234,244)',
|
||||
'hidemenubar': 'false', 'hidescrollbar': 'false',
|
||||
'audiblebell': 'false', 'visualbell': 'false',
|
||||
'disableconfirm': 'false', 'geometry_columns': 88, 'geometry_rows': 24,
|
||||
}, 'shortcut': {
|
||||
'zoom_in_accel': '<Primary>equal', 'zoom_out_accel': '<Primary>minus',
|
||||
'zoom_reset_accel': '<Primary>0',
|
||||
'copy_accel': '<Primary><Shift>c', 'paste_accel': '<Primary><Shift>v',
|
||||
'new_tab_accel': '<Primary><Shift>t',
|
||||
}})
|
||||
write(marker, 'Field terminal defaults applied; user preferences now own font and colors.\n')
|
||||
bashrc = home / '.bashrc'
|
||||
content = bashrc.read_text() if bashrc.exists() else ''
|
||||
if '# iOmatex field terminal help' not in content:
|
||||
write(bashrc, content + '''
|
||||
# iOmatex field terminal help (interactive local shells only)
|
||||
case $- in
|
||||
*i*)
|
||||
edge-help() { /usr/local/bin/iomatex-terminal-help; }
|
||||
if [ -n "${DISPLAY:-}" ] && [ -z "${SSH_CONNECTION:-}" ] && [ -x /usr/local/bin/iomatex-terminal-help ]; then
|
||||
/usr/local/bin/iomatex-terminal-help
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
''')
|
||||
|
||||
|
||||
def configure(home, assets=ASSETS, screens=None, system=Path('/etc/xdg'), environment=None):
|
||||
configure_terminal(home)
|
||||
config = home / '.config'
|
||||
desktop = home / 'Desktop'
|
||||
dirs = config / 'user-dirs.dirs'
|
||||
if dirs.exists():
|
||||
match = re.search(r'^XDG_DESKTOP_DIR="([^"]+)"', dirs.read_text(), re.M)
|
||||
if match:
|
||||
desktop = Path(match[1].replace('$HOME', str(home)))
|
||||
if not desktop.is_absolute():
|
||||
raise ValueError('XDG_DESKTOP_DIR must be absolute')
|
||||
write(desktop / APP, (assets / APP).read_text(), 0o755)
|
||||
screens = screens or monitors()
|
||||
if environment == 'xfce' or (environment is None and shutil.which('xfdesktop')):
|
||||
configure_xfce(home, desktop, assets, screens, system)
|
||||
return
|
||||
|
||||
profiles = {'LXDE'}
|
||||
for base in (config, system):
|
||||
for component in ('pcmanfm', 'lxpanel'):
|
||||
directory = base / component
|
||||
if directory.exists():
|
||||
profiles.update(p.name for p in directory.iterdir()
|
||||
if p.is_dir() and not p.name.startswith('.'))
|
||||
screens = screens or monitors()
|
||||
for profile in sorted(profiles):
|
||||
pc = config / 'pcmanfm' / profile
|
||||
for i, (width, height, x, y) in enumerate(screens):
|
||||
path = pc / ('desktop-items-%d.conf' % i)
|
||||
source = system / 'pcmanfm' / profile / path.name
|
||||
if not path.exists() and source.exists():
|
||||
write(path, source.read_text())
|
||||
ini(path, {'*': {
|
||||
'wallpaper_mode': 2, 'wallpaper': str(assets / 'wallpaper.svg'),
|
||||
'wallpaper_common': 1, 'desktop_bg': '#eef3fa',
|
||||
'desktop_fg': '#193b60', 'desktop_shadow': '#ffffff',
|
||||
'desktop_font': 'Sans 14',
|
||||
}, APP: {'x': x + max(0, width // 2 - 60),
|
||||
'y': y + max(0, height // 2 - 40)}})
|
||||
|
||||
panels = config / 'lxpanel' / profile / 'panels'
|
||||
defaults = system / 'lxpanel' / profile / 'panels'
|
||||
if not panels.exists() and defaults.exists():
|
||||
panels.mkdir(parents=True)
|
||||
for source in defaults.iterdir():
|
||||
if source.is_file():
|
||||
write(panels / source.name, source.read_text())
|
||||
bottom = next((p for p in sorted(panels.glob('*'))
|
||||
if p.is_file()
|
||||
and re.search(r'\bedge\s*=\s*bottom\b', p.read_text())), None)
|
||||
if bottom is None:
|
||||
bottom = panels / 'iomatex'
|
||||
content = ('Global {\nedge=bottom\nalign=center\nwidthtype=pixel\n'
|
||||
'width=160\nheight=56\niconsize=48\nsetdocktype=1\n'
|
||||
'setpartialstrut=1\nautohide=0\n}\n')
|
||||
else:
|
||||
content = bottom.read_text()
|
||||
if APP not in content:
|
||||
content += '\nPlugin {\n type=launchbar\n Config {\n Button {\n id=' + APP + '\n }\n }\n}\n'
|
||||
write(bottom, content)
|
||||
|
||||
|
||||
def wallpaper(assets):
|
||||
# Compose a vector background with the unchanged, canonical logo embedded.
|
||||
logo = base64.b64encode((assets / 'iomatex.png').read_bytes()).decode('ascii')
|
||||
return '''<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="1920" height="1080" viewBox="0 0 1920 1080">
|
||||
<defs><linearGradient id="bg" x2="1" y2="1"><stop stop-color="#ffffff"/><stop offset="1" stop-color="#dbe7f5"/></linearGradient></defs>
|
||||
<rect width="1920" height="1080" fill="url(#bg)"/>
|
||||
<image x="850" y="80" width="220" height="220" xlink:href="data:image/png;base64,''' + logo + '''"/>
|
||||
<text x="960" y="365" text-anchor="middle" font-family="sans-serif" font-size="32" fill="#193b60">iOmatex Edge</text>
|
||||
<text x="960" y="1000" text-anchor="middle" font-family="sans-serif" font-size="22" fill="#496484">EVAx10 · AI-native platform</text>
|
||||
</svg>
|
||||
'''
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import sys
|
||||
if sys.argv[1:] == ['--wallpaper']:
|
||||
write(ASSETS / 'wallpaper.svg', wallpaper(ASSETS))
|
||||
elif sys.argv[1:] == ['--terminal']:
|
||||
configure_terminal(Path.home())
|
||||
elif not sys.argv[1:]:
|
||||
configure(Path.home())
|
||||
else:
|
||||
raise SystemExit('Usage: iomatex-desktop [--wallpaper]')
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
#!/bin/sh
|
||||
set -eu
|
||||
fail() {
|
||||
logger -t iomatex-open-evax10 "$1"
|
||||
if command -v xmessage >/dev/null 2>&1; then
|
||||
xmessage -center -buttons OK:0 "$1"
|
||||
fi
|
||||
exit 1
|
||||
}
|
||||
state=$(systemctl show itscreen-x11.service -p LoadState --value)
|
||||
[ "$state" = loaded ] || fail 'EVAx10 is not installed. Install stage_itscreen in Edge Console.'
|
||||
# Reuse the client's authenticated maintenance desktop transition when installed.
|
||||
if [ -x /usr/local/sbin/iomatex-desktop ]; then
|
||||
sudo -n /usr/local/sbin/iomatex-desktop return || \
|
||||
fail 'Cannot return to EVAx10. Check the desktop access policy.'
|
||||
exit 0
|
||||
fi
|
||||
# The service owns X11 and conflicts with LightDM. Do not run a second player.
|
||||
sudo -n /usr/bin/systemctl --no-block start itscreen-x11.service || \
|
||||
fail 'Cannot start EVAx10. Check itscreen-x11.service in Edge Console.'
|
||||
|
|
@ -0,0 +1,3 @@
|
|||
#!/bin/sh
|
||||
# One owner for the desktop, dock and Debian terminal alternative.
|
||||
exec /usr/bin/lxterminal "$@"
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
#!/bin/sh
|
||||
cat <<'EOF'
|
||||
|
||||
iOmatex · Терминал инженера
|
||||
───────────────────────────────────────────────────────────────
|
||||
Шрифт: Ctrl+= увеличить · Ctrl+- уменьшить · Ctrl+0 сбросить.
|
||||
Постоянный размер: Правка → Параметры → Стиль → Шрифт
|
||||
(Edit → Preferences → Style → Font). По умолчанию: 18 pt.
|
||||
|
||||
Ctrl+Shift+C / V — копировать / вставить; Ctrl+Shift+T — вкладка.
|
||||
Ctrl+C — остановить команду; Ctrl+L — очистить экран; q — выйти
|
||||
из просмотра журнала. Tab — дополнение; Ctrl+R — поиск в истории.
|
||||
|
||||
Клиент: journalctl -u itscreen-x11 -n 80 --no-pager
|
||||
Лог вживую: journalctl -u itscreen-x11 -f
|
||||
Установщик: tail -n 80 /userdata/Iomatex_OS/local_installer.log
|
||||
Сеть / диск: ip -br addr ; df -h / /userdata
|
||||
Памятка снова: edge-help
|
||||
|
||||
Пароль sudo при вводе не отображается — это нормально.
|
||||
Работайте от iomatex; sudo используйте для отдельных команд.
|
||||
───────────────────────────────────────────────────────────────
|
||||
|
||||
EOF
|
||||
|
|
@ -0,0 +1,126 @@
|
|||
import importlib.machinery
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
import tempfile
|
||||
import unittest
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
ROOT = Path(__file__).parent
|
||||
loader = importlib.machinery.SourceFileLoader('branding', str(ROOT / 'iomatex-desktop-branding'))
|
||||
spec = importlib.util.spec_from_loader(loader.name, loader)
|
||||
branding = importlib.util.module_from_spec(spec)
|
||||
loader.exec_module(branding)
|
||||
|
||||
|
||||
class DesktopTest(unittest.TestCase):
|
||||
def test_terminal_defaults_keep_engineer_font_and_single_help_hook(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
(home / '.bashrc').write_text('alias ll="ls -l"\n')
|
||||
branding.configure_terminal(home)
|
||||
cfg = home / '.config/lxterminal/lxterminal.conf'
|
||||
self.assertIn('fontname=DejaVu Sans Mono 18', cfg.read_text())
|
||||
self.assertIn('zoom_in_accel=<Primary>equal', cfg.read_text())
|
||||
cfg.write_text(cfg.read_text().replace('Mono 18', 'Mono 22'))
|
||||
branding.configure_terminal(home)
|
||||
self.assertIn('fontname=DejaVu Sans Mono 22', cfg.read_text())
|
||||
self.assertEqual((home / '.bashrc').read_text().count('# iOmatex field terminal help'), 1)
|
||||
self.assertIn('alias ll=', (home / '.bashrc').read_text())
|
||||
self.assertEqual((home / '.local/state/iomatex-desktop/backups/bashrc').read_text(), 'alias ll="ls -l"\n')
|
||||
|
||||
def test_xfce_preserves_panel_and_reuses_launcher(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
channel = home / '.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-panel.xml'
|
||||
channel.parent.mkdir(parents=True)
|
||||
channel.write_text('''<channel name="xfce4-panel" version="1.0">
|
||||
<property name="panels" type="array"><value type="int" value="2"/>
|
||||
<property name="panel-2" type="empty"><property name="position" type="string" value="p=10;x=0;y=0"/>
|
||||
<property name="plugin-ids" type="array"><value type="int" value="3"/></property></property></property>
|
||||
<property name="plugins" type="empty"><property name="plugin-3" type="string" value="clock"/></property></channel>''')
|
||||
for _ in range(2):
|
||||
branding.configure(home, ROOT, [(1920, 1080, 0, 0)], home/'system', 'xfce')
|
||||
root = branding.ET.parse(channel).getroot()
|
||||
plugins = root.find("property[@name='plugins']")
|
||||
self.assertEqual(len(plugins), 7)
|
||||
self.assertEqual(plugins[0].get('value'), 'clock')
|
||||
self.assertEqual(len(root.findall(".//property[@name='plugin-ids']/value")), 6)
|
||||
self.assertIn(str(ROOT/'wallpaper-purple.png'), (channel.parent/'xfce4-desktop.xml').read_text())
|
||||
self.assertTrue((home/'Desktop'/branding.APP).exists())
|
||||
|
||||
def test_existing_desktop_panel_and_localized_directory_survive_repeat(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp) / 'home'
|
||||
config = home / '.config'
|
||||
config.mkdir(parents=True)
|
||||
(config / 'user-dirs.dirs').write_text('XDG_DESKTOP_DIR="$HOME/Рабочий стол"\n')
|
||||
pc = config / 'pcmanfm/LXDE/desktop-items-0.conf'
|
||||
pc.parent.mkdir(parents=True)
|
||||
original = '[*]\nshow_trash=1\n[notes.txt]\nx=10\ny=20\n'
|
||||
pc.write_text(original)
|
||||
panel = config / 'lxpanel/LXDE/panels/panel'
|
||||
panel.parent.mkdir(parents=True)
|
||||
panel.write_text('Global {\nedge=bottom\n}\nPlugin {\ntype=tray\n}\n')
|
||||
for _ in range(2):
|
||||
branding.configure(home, ROOT, [(1920, 1080, 0, 0)], Path(tmp) / 'system')
|
||||
self.assertTrue((home / 'Рабочий стол' / branding.APP).exists())
|
||||
self.assertIn('show_trash=1', pc.read_text())
|
||||
self.assertIn('[notes.txt]', pc.read_text())
|
||||
self.assertIn('x=900\ny=500', pc.read_text())
|
||||
self.assertIn('type=tray', panel.read_text())
|
||||
self.assertEqual(panel.read_text().count(branding.APP), 1)
|
||||
self.assertEqual(list(panel.parent.iterdir()), [panel])
|
||||
self.assertFalse((config / 'lxpanel/.iomatex-backups/panels').exists())
|
||||
self.assertEqual((pc.parent.parent / '.iomatex-backups/LXDE/desktop-items-0.conf').read_text(), original)
|
||||
|
||||
def test_system_panel_copied_and_small_display_centered(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home, system = Path(tmp) / 'home', Path(tmp) / 'system'
|
||||
panel = system / 'lxpanel/LXDE/panels/panel'
|
||||
panel.parent.mkdir(parents=True)
|
||||
panel.write_text('Global {\nedge=bottom\n}\nPlugin {\ntype=menu\n}\n')
|
||||
branding.configure(home, ROOT, [(800, 600, 0, 0)], system)
|
||||
target = home / '.config/lxpanel/LXDE/panels/panel'
|
||||
self.assertIn('type=menu', target.read_text())
|
||||
self.assertNotIn(branding.APP, panel.read_text())
|
||||
pc = home / '.config/pcmanfm/LXDE/desktop-items-0.conf'
|
||||
self.assertIn('x=340\ny=260', pc.read_text())
|
||||
branding.configure(home, ROOT, [(1280, 720, 0, 0)], system)
|
||||
self.assertIn('x=580\ny=320', pc.read_text())
|
||||
|
||||
def test_missing_bottom_panel_created_once(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
for _ in range(2):
|
||||
branding.configure(home, ROOT, [(1280, 720, 0, 0)], home / 'system')
|
||||
panels = home / '.config/lxpanel/LXDE/panels'
|
||||
self.assertEqual([p.name for p in panels.iterdir()], ['iomatex'])
|
||||
self.assertEqual((panels / 'iomatex').read_text().count(branding.APP), 1)
|
||||
|
||||
def test_launcher_reports_missing_service_and_uses_existing_service(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
root = Path(tmp)
|
||||
commands = {
|
||||
'systemctl': 'echo "$TEST_LOAD_STATE"',
|
||||
'sudo': 'printf "%s\\n" "$*" > "$TEST_CALL"',
|
||||
'logger': 'exit 0',
|
||||
'xmessage': 'exit 0',
|
||||
}
|
||||
for name, command in commands.items():
|
||||
path = root / name
|
||||
path.write_text('#!/bin/sh\n' + command + '\n')
|
||||
path.chmod(0o755)
|
||||
env = dict(os.environ, PATH=str(root), TEST_CALL=str(root / 'call'),
|
||||
TEST_LOAD_STATE='not-found')
|
||||
script = ['/bin/sh', str(ROOT / 'iomatex-open-evax10')]
|
||||
self.assertNotEqual(subprocess.run(script, env=env).returncode, 0)
|
||||
self.assertFalse((root / 'call').exists())
|
||||
env['TEST_LOAD_STATE'] = 'loaded'
|
||||
self.assertEqual(subprocess.run(script, env=env).returncode, 0)
|
||||
self.assertEqual((root / 'call').read_text().strip(),
|
||||
'-n /usr/bin/systemctl --no-block start itscreen-x11.service')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
After Width: | Height: | Size: 1.7 MiB |
|
After Width: | Height: | Size: 1.4 MiB |
|
|
@ -1104,6 +1104,71 @@ EOF
|
|||
|
||||
ensure_gui_home_state "$IOM_USER"
|
||||
ensure_lightdm_iomatex_login
|
||||
|
||||
install_desktop_branding() {
|
||||
local assets=/usr/local/share/iomatex/desktop
|
||||
local home_dir user_group
|
||||
home_dir="$(getent passwd "$IOM_USER" | cut -d: -f6)"
|
||||
user_group="$(id -gn "$IOM_USER")"
|
||||
apt_install_missing lxterminal fonts-dejavu-core
|
||||
install -d -m 0755 "$assets" /usr/local/bin /usr/share/applications
|
||||
install -m 0644 "$SCRIPT_DIR/../stage_ui/iomatex_logo_source.png" "$assets/iomatex.png"
|
||||
install -m 0644 "$SCRIPT_DIR/desktop/evax10_launcher.png" "$assets/evax10_launcher.png"
|
||||
install -m 0644 "$SCRIPT_DIR/desktop/app-icon-source.json" "$assets/app-icon-source.json"
|
||||
install -m 0644 "$SCRIPT_DIR/desktop/wallpaper-purple.png" "$assets/wallpaper-purple.png"
|
||||
install -m 0644 "$SCRIPT_DIR/desktop/transition.png" "$assets/transition.png"
|
||||
install -d -m 0755 "$assets/icons"
|
||||
install -m 0644 "$SCRIPT_DIR/desktop/icons/"*.svg "$assets/icons/"
|
||||
install -m 0755 "$SCRIPT_DIR/desktop/iomatex-desktop-branding" /usr/local/bin/iomatex-desktop-branding
|
||||
install -m 0755 "$SCRIPT_DIR/desktop/iomatex-open-evax10" /usr/local/bin/iomatex-open-evax10
|
||||
install -m 0755 "$SCRIPT_DIR/desktop/iomatex-terminal" /usr/local/bin/iomatex-terminal
|
||||
install -m 0755 "$SCRIPT_DIR/desktop/iomatex-terminal-help" /usr/local/bin/iomatex-terminal-help
|
||||
update-alternatives --install /usr/bin/x-terminal-emulator x-terminal-emulator /usr/local/bin/iomatex-terminal 60
|
||||
update-alternatives --set x-terminal-emulator /usr/local/bin/iomatex-terminal
|
||||
runuser -u "$IOM_USER" -- env HOME="$home_dir" /usr/local/bin/iomatex-desktop-branding --terminal
|
||||
install -m 0644 "$SCRIPT_DIR/desktop/evax10-return.desktop" "$assets/evax10-return.desktop"
|
||||
install -m 0644 "$assets/evax10-return.desktop" /usr/share/applications/evax10-return.desktop
|
||||
/usr/local/bin/iomatex-desktop-branding --wallpaper
|
||||
# Only this exact service start is passwordless; no arbitrary root commands.
|
||||
write_if_changed /etc/sudoers.d/91-iomatex-desktop 0440 <<EOF
|
||||
${IOM_USER} ALL=(root) NOPASSWD: /usr/bin/systemctl --no-block start itscreen-x11.service
|
||||
EOF
|
||||
visudo -cf /etc/sudoers.d/91-iomatex-desktop
|
||||
if { command -v pcmanfm >/dev/null 2>&1 && command -v lxpanel >/dev/null 2>&1; } || command -v xfdesktop >/dev/null 2>&1; then
|
||||
# Debian sources .xsessionrc before launching the desktop and its panels.
|
||||
# Prepare positions after X11 mode detection but before PCManFM reads them.
|
||||
local hook='[ ! -x /usr/local/bin/iomatex-desktop-branding ] || /usr/local/bin/iomatex-desktop-branding || logger -t iomatex-desktop "Desktop configuration failed"'
|
||||
if ! grep -qF '/usr/local/bin/iomatex-desktop-branding' "$home_dir/.xsessionrc" 2>/dev/null; then
|
||||
backup_if_exists "$home_dir/.xsessionrc"
|
||||
printf '\n# iOmatex desktop branding\n%s\n' "$hook" >> "$home_dir/.xsessionrc"
|
||||
chown "$IOM_USER:$user_group" "$home_dir/.xsessionrc"
|
||||
fi
|
||||
runuser -u "$IOM_USER" -- env HOME="$home_dir" /usr/local/bin/iomatex-desktop-branding
|
||||
log "iOmatex desktop branding installed; applied on next desktop login"
|
||||
else
|
||||
log "Desktop branding: LXDE/XFCE not detected; application menu entry installed only"
|
||||
fi
|
||||
if [ -x /usr/sbin/lightdm-gtk-greeter ]; then
|
||||
write_if_changed /etc/lightdm/lightdm-gtk-greeter.conf.d/80-iomatex.conf 0644 <<EOF
|
||||
[greeter]
|
||||
background=${assets}/transition.png
|
||||
default-user-image=${assets}/evax10_launcher.png
|
||||
EOF
|
||||
fi
|
||||
install -m 0755 "$SCRIPT_DIR/desktop/iomatex-boot-splash" /usr/local/bin/iomatex-boot-splash
|
||||
install -m 0644 "$SCRIPT_DIR/desktop/iomatex-boot-splash.service" /etc/systemd/system/iomatex-boot-splash.service
|
||||
local display_unit
|
||||
for display_unit in lightdm itscreen-x11; do
|
||||
write_if_changed "/etc/systemd/system/${display_unit}.service.d/15-iomatex-splash.conf" 0644 <<'EOF'
|
||||
[Service]
|
||||
ExecStartPre=-/bin/systemctl stop iomatex-boot-splash.service
|
||||
EOF
|
||||
done
|
||||
systemctl daemon-reload
|
||||
systemctl enable iomatex-boot-splash.service
|
||||
log "iOmatex userspace boot splash enabled; signed U-Boot FIT left intact"
|
||||
}
|
||||
install_desktop_branding
|
||||
if id youngfeel >/dev/null 2>&1; then
|
||||
log "Harden vendor user: youngfeel (lock password, disable shell, remove sudo)"
|
||||
soft_run "Lock password youngfeel" 10 /usr/bin/passwd -l youngfeel
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
{
|
||||
"version": "1.0.4"
|
||||
"version": "1.0.5"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,7 @@
|
|||
[Seat:*]
|
||||
pam-service=evax10-desktop
|
||||
autologin-user=
|
||||
autologin-guest=false
|
||||
allow-guest=false
|
||||
greeter-allow-guest=false
|
||||
greeter-show-manual-login=true
|
||||
|
|
@ -0,0 +1,6 @@
|
|||
# Local maintenance requires an actual Unix password; no blank-password login.
|
||||
auth requisite pam_nologin.so
|
||||
auth required pam_unix.so
|
||||
account include common-account
|
||||
session required pam_limits.so
|
||||
session include common-session
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
[Desktop Entry]
|
||||
Type=Application
|
||||
Name=Return to EVAx10
|
||||
Name[ru]=Вернуться в EVAx10
|
||||
Name[pl]=Powrót do EVAx10
|
||||
Comment=Close the maintenance desktop and resume the EVAx10 client
|
||||
Exec=/usr/bin/sudo -n /usr/local/sbin/iomatex-desktop return
|
||||
Icon=video-display
|
||||
Terminal=false
|
||||
|
|
@ -0,0 +1,27 @@
|
|||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
[[ $EUID == 0 ]] || exit 1
|
||||
cd "$(dirname "$0")"
|
||||
test -x /usr/sbin/lightdm
|
||||
install -o root -g root -m 644 evax10-desktop.pam /etc/pam.d/evax10-desktop
|
||||
install -d /etc/lightdm/lightdm.conf.d
|
||||
install -o root -g root -m 644 99-evax10-password-login.conf /etc/lightdm/lightdm.conf.d/
|
||||
install -o root -g root -m 755 iomatex-desktop /usr/local/sbin/iomatex-desktop
|
||||
/usr/local/sbin/iomatex-desktop check
|
||||
rule=$(mktemp)
|
||||
trap 'rm -f "$rule"' EXIT
|
||||
printf '%s\n' 'itscreen ALL=(root) NOPASSWD: /usr/local/sbin/iomatex-desktop open' 'iomatex ALL=(root) NOPASSWD: /usr/local/sbin/iomatex-desktop return' > "$rule"
|
||||
visudo -cf "$rule"
|
||||
install -o root -g root -m 440 "$rule" /etc/sudoers.d/itscreen-desktop
|
||||
install -o root -g root -m 644 evax10-return.desktop /usr/share/applications/
|
||||
# Desktop directory follows the system user's existing XDG configuration.
|
||||
home_dir=$(getent passwd iomatex | cut -d: -f6)
|
||||
if [[ -n $home_dir ]]; then
|
||||
desktop="$home_dir/Desktop"
|
||||
if command -v xdg-user-dir >/dev/null; then
|
||||
desktop=$(sudo -u iomatex env HOME="$home_dir" xdg-user-dir DESKTOP)
|
||||
fi
|
||||
[[ $desktop == "$home_dir/"* ]] || exit 1
|
||||
install -d -o iomatex -g iomatex "$desktop"
|
||||
install -o root -g root -m 755 evax10-return.desktop "$desktop/evax10-return.desktop"
|
||||
fi
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
#!/bin/bash
|
||||
set -euo pipefail
|
||||
export PATH=/usr/sbin:/usr/bin:/sbin:/bin
|
||||
[[ $EUID == 0 && $# == 1 ]] || exit 64
|
||||
case "$1" in
|
||||
check|open)
|
||||
test -x /usr/sbin/lightdm
|
||||
# Fail closed if another configuration reintroduces passwordless login.
|
||||
config=$(/usr/sbin/lightdm --show-config 2>&1)
|
||||
if printf '%s\n' "$config" | grep -Eq 'autologin-user=.+|autologin-guest=true|allow-guest=true'; then
|
||||
echo 'Passwordless desktop login is configured; refusing transition.' >&2
|
||||
exit 1
|
||||
fi
|
||||
printf '%s\n' "$config" | grep -q 'allow-guest=false'
|
||||
printf '%s\n' "$config" | grep -q 'pam-service=evax10-desktop'
|
||||
test -f /etc/pam.d/evax10-desktop
|
||||
if [[ $1 == open ]]; then
|
||||
# Survives termination of the client X11 service. Does not change boot mode.
|
||||
systemctl --no-block start lightdm.service
|
||||
fi
|
||||
;;
|
||||
return) systemctl --no-block start itscreen-x11.service ;;
|
||||
*) exit 64 ;;
|
||||
esac
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
#!/bin/sh
|
||||
# Root-owned narrow adapter for the existing YF MCU; input is epoch seconds or 0.
|
||||
set -eu
|
||||
[ "$#" -eq 1 ] || exit 64
|
||||
case "$1" in ''|*[!0-9]*) exit 64 ;; esac
|
||||
[ "${#1}" -le 10 ] || exit 64
|
||||
[ -c /dev/McuDemo2 ] || exit 69
|
||||
run_vendor() {
|
||||
status=0
|
||||
/usr/bin/yf_Interface "$@" || status=$?
|
||||
# This vendor binary returns 1 on successful Set_Rtc_OnOffTime, -1 on
|
||||
# invalid input/open failure. Verified by its symbols/disassembly and a
|
||||
# real off/on cycle. Do not reinterpret generic exit=1 for unknown builds.
|
||||
if [ "$status" = 1 ]; then
|
||||
vendor_hash=$(sha256sum /usr/bin/yf_Interface)
|
||||
case "$vendor_hash" in
|
||||
3f07ae57d3cd86485fdd48323d1292ab06dd8706d26fe0e81c52a58f107e0c86\ *) status=0 ;;
|
||||
esac
|
||||
fi
|
||||
return "$status"
|
||||
}
|
||||
if [ "$1" = 0 ]; then
|
||||
run_vendor set_onoff_time 0 0 0 0 0 0 0 0 0
|
||||
exit $?
|
||||
fi
|
||||
now=$(date +%s)
|
||||
[ "$1" -gt "$now" ] && [ "$1" -le "$((now + 691200))" ] || exit 65
|
||||
# Vendor accepts local civil time (month/day/hour/minute), not UTC.
|
||||
set -- $(date -d "@$1" '+%m %d %H %M')
|
||||
run_vendor set_onoff_time "$1" "$2" "$3" "$4" 0 0 0 0 1
|
||||
|
|
@ -1 +1 @@
|
|||
1ec74511b5df12e5e3d78ef728cfff651957c84d87875f5347f9dc02733ba334 itscreen
|
||||
5e14d2cabd2821620e03467bc5d8bc98d87895d3f6f22c3f82a9cf414c6d13d0 itscreen
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
5.1.28
|
||||
5.1.55
|
||||
|
|
|
|||
|
|
@ -1,14 +1,18 @@
|
|||
{
|
||||
"schema_version": 1,
|
||||
"client_version": "5.1.28",
|
||||
"stage_version": "1.0.28",
|
||||
"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_branch": "Debian_CLient",
|
||||
"source_commit": "dbac017bad046b46aaa3fe3ec3d8b878ec8e6f35",
|
||||
"source_repository": "https://git.iomatex.com/Development/It-screenClient.git",
|
||||
"source_branch": "iomatex_dev",
|
||||
"source_commit": "c4739d5dd87ba43c94578af0c6745b0086829175",
|
||||
"binary": "itscreen",
|
||||
"sha256": "1ec74511b5df12e5e3d78ef728cfff651957c84d87875f5347f9dc02733ba334",
|
||||
"assembly_method": "Native qmake/make release build on Debian 11 ARM64, Qt 5.15.2",
|
||||
"native_version_code": 5010128
|
||||
"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,17 +518,16 @@ 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() {
|
||||
step "Grant power actions (reboot/shutdown) to itscreen (sudoers)"
|
||||
write_file "$SUDOERS_FILE" 0440 root root <<'EOF'
|
||||
Defaults:itscreen !requiretty
|
||||
itscreen ALL=(root) NOPASSWD: /bin/systemctl enable itscreen-x11.service, /usr/bin/systemctl enable itscreen-x11.service, /bin/systemctl disable itscreen-x11.service, /usr/bin/systemctl disable itscreen-x11.service
|
||||
itscreen ALL=(root) NOPASSWD: /sbin/reboot, /usr/sbin/reboot, /bin/systemctl reboot, /usr/bin/systemctl reboot
|
||||
itscreen ALL=(root) NOPASSWD: /sbin/poweroff, /usr/sbin/poweroff, /bin/systemctl poweroff, /usr/bin/systemctl poweroff
|
||||
itscreen ALL=(root) NOPASSWD: /sbin/shutdown, /usr/sbin/shutdown, /bin/systemctl halt, /usr/bin/systemctl halt
|
||||
|
|
@ -1546,6 +1550,18 @@ main() {
|
|||
install_itscreen_binary
|
||||
install_itscreen_config
|
||||
install_sudoers
|
||||
if [ -c /dev/McuDemo2 ] && [ -x /usr/bin/yf_Interface ]; then
|
||||
install -o root -g root -m 755 "$SCRIPT_DIR/iomatex-power-wake" /usr/local/sbin/iomatex-power-wake
|
||||
write_file /etc/sudoers.d/itscreen-power-wake 0440 root root <<'POWER_WAKE'
|
||||
itscreen ALL=(root) NOPASSWD: /usr/local/sbin/iomatex-power-wake
|
||||
POWER_WAKE
|
||||
visudo -cf /etc/sudoers.d/itscreen-power-wake
|
||||
fi
|
||||
if [ -x /usr/sbin/lightdm ]; then
|
||||
bash "$SCRIPT_DIR/desktop/install.sh"
|
||||
else
|
||||
warn "LightDM is not installed; maintenance desktop remains unavailable"
|
||||
fi
|
||||
install_wrapper
|
||||
install_audio_route_state
|
||||
install_pulseaudio_assets
|
||||
|
|
@ -1553,6 +1569,7 @@ main() {
|
|||
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.28"
|
||||
"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.27"
|
||||
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,17 +2702,7 @@ 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"]
|
||||
|
||||
def build_health_services_payload(force=False):
|
||||
allowed_ids = {
|
||||
"itscreen",
|
||||
"mosquitto",
|
||||
|
|
@ -2718,16 +2716,13 @@ def build_health_services_payload():
|
|||
"environment",
|
||||
"console",
|
||||
}
|
||||
cards, _ = collect_provider_cards(build_provider_context())
|
||||
payload = {
|
||||
status = build_status_payload(force=force)
|
||||
return {
|
||||
"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],
|
||||
"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],
|
||||
}
|
||||
_HEALTH_SERVICES_CACHE["payload"] = payload
|
||||
_HEALTH_SERVICES_CACHE["expires_at"] = time.time() + max(1, int(cfg.get("cache_ttl_sec", 3)))
|
||||
return payload
|
||||
|
||||
|
||||
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", ""))
|
||||
|
|
|
|||