Compare commits
No commits in common. "ci-cd" and "Command_Notification" have entirely different histories.
ci-cd
...
Command_No
|
|
@ -22,6 +22,7 @@ ssh iomatex@ip.add.re.ss
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /home/iomatex
|
cd /home/iomatex
|
||||||
|
|
||||||
curl --fail --show-error \
|
curl --fail --show-error \
|
||||||
--connect-timeout 15 --max-time 120 \
|
--connect-timeout 15 --max-time 120 \
|
||||||
--user clone \
|
--user clone \
|
||||||
|
|
@ -30,7 +31,6 @@ curl --fail --show-error \
|
||||||
```
|
```
|
||||||
|
|
||||||
`curl` запросит пароль Git пользователя `clone`. Ввод не отображается.
|
`curl` запросит пароль Git пользователя `clone`. Ввод не отображается.
|
||||||
|
|
||||||
Это пароль доступа к репозиторию, а не пароль пользователя Edge.
|
Это пароль доступа к репозиторию, а не пароль пользователя Edge.
|
||||||
Пароль не нужно добавлять в команду.
|
Пароль не нужно добавлять в команду.
|
||||||
|
|
||||||
|
|
@ -43,55 +43,6 @@ sudo bash /home/iomatex/install_iomatex_edge.new.sh
|
||||||
Установщик снова запросит `Git username` (`clone`) и `Git password or token`.
|
Установщик снова запросит `Git username` (`clone`) и `Git password or token`.
|
||||||
При ошибке скачивания повторите команду `curl`; не запускайте оставшийся файл.
|
При ошибке скачивания повторите команду `curl`; не запускайте оставшийся файл.
|
||||||
|
|
||||||
#### Для Белорусов
|
|
||||||
|
|
||||||
Если вы работаете из Windows PowerShell, сначала подключитесь к Edge:
|
|
||||||
|
|
||||||
```powershell
|
|
||||||
ssh iomatex@192.168.0.187
|
|
||||||
```
|
|
||||||
|
|
||||||
Замените `192.168.0.187` на актуальный IP вашего Edge. Введите пароль
|
|
||||||
пользователя **Linux `iomatex`**. Дождитесь приглашения вида
|
|
||||||
`iomatex@g-box-XXXXXXXX:~$` — следующие команды выполняются **на Debian через SSH**,
|
|
||||||
а не непосредственно в PowerShell Windows.
|
|
||||||
|
|
||||||
Для доступа из Беларуси используйте `git.iomatex.com`. Вместо команд скачивания
|
|
||||||
и запуска выше вставьте целиком этот блок:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
cd /home/iomatex &&
|
|
||||||
curl --fail --show-error \
|
|
||||||
--connect-timeout 15 --max-time 120 \
|
|
||||||
--user clone \
|
|
||||||
'https://git.iomatex.com/api/v1/repos/An-J/Iomatex_OS/raw/install_iomatex_edge.sh?ref=ci-cd' \
|
|
||||||
-o install_iomatex_edge.new.sh &&
|
|
||||||
bash -n install_iomatex_edge.new.sh &&
|
|
||||||
sudo bash install_iomatex_edge.new.sh \
|
|
||||||
--git-url https://git.iomatex.com/An-J/Iomatex_OS.git
|
|
||||||
```
|
|
||||||
|
|
||||||
Блок **скачивает и сразу запускает установку**. Благодаря `&&` при ошибке
|
|
||||||
скачивания или проверки синтаксиса установка не начнётся. Повторно запускать
|
|
||||||
команду из общего примера не нужно.
|
|
||||||
|
|
||||||
`curl` запросит пароль **Git пользователя `clone`**. Установщик затем снова
|
|
||||||
запросит `Git username` (`clone`) и `Git password or token`. Это не пароль
|
|
||||||
пользователя Linux. Пароли при вводе не отображаются; не добавляйте их в команды.
|
|
||||||
После `stage_env` произойдёт автоматическая перезагрузка с продолжением установки;
|
|
||||||
SSH-соединение прервётся, после загрузки подключитесь заново.
|
|
||||||
|
|
||||||
Используйте актуальный установщик: старые версии принимают только основной домен.
|
|
||||||
Выбранный адрес сохраняется для обновлений Console, загрузки пакетов и продолжения
|
|
||||||
установки после перезагрузки. Если выбранный домен недоступен по DNS, соединению
|
|
||||||
или таймауту, актуальный установщик автоматически пробует второй доверенный домен
|
|
||||||
при первоначальном скачивании загрузчика; последующие обновления используют
|
|
||||||
сохранённый адрес. При ошибках HTTP (включая пароль) и TLS переключения нет.
|
|
||||||
Оба имени ведут на один сервер; при блокировке его IP потребуется отдельная
|
|
||||||
точка доступа.
|
|
||||||
|
|
||||||
#### Первая установка и восстановление доступа
|
|
||||||
|
|
||||||
На заводском образе выполняйте скачивание под `youngfeel`: в командах выше
|
На заводском образе выполняйте скачивание под `youngfeel`: в командах выше
|
||||||
замените `/home/iomatex` на `/home/youngfeel`. После `stage_env` используйте
|
замените `/home/iomatex` на `/home/youngfeel`. После `stage_env` используйте
|
||||||
`iomatex`. Если `curl` отсутствует или Edge не имеет доступа к Git, передайте
|
`iomatex`. Если `curl` отсутствует или Edge не имеет доступа к Git, передайте
|
||||||
|
|
@ -357,43 +308,18 @@ ssh iomatex@ip.add.re.ss
|
||||||
|
|
||||||
## 7. Как смотреть ход установки
|
## 7. Как смотреть ход установки
|
||||||
|
|
||||||
Актуальный `install_iomatex_edge.sh` по умолчанию размещает проект в
|
|
||||||
`/userdata/Iomatex_OS`. Лог и файл состояния находятся рядом с
|
|
||||||
`local_installer.sh`, а не рядом со скачанным launcher в `/home/iomatex`.
|
|
||||||
Если вы указали `--checkout-dir` или `IOMATEX_GIT_DIR`, используйте выбранную
|
|
||||||
папку; фактические пути выводятся в начале установки и в итоговом отчёте.
|
|
||||||
|
|
||||||
|
|
||||||
Если хочешь видеть установку в реальном времени, выполни:
|
Если хочешь видеть установку в реальном времени, выполни:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo tail -f /userdata/Iomatex_OS/local_installer.log
|
sudo tail -f /opt/iomatex/Iomatex_OS/local_installer.log
|
||||||
```
|
```
|
||||||
|
|
||||||
Если хочешь проверить post-reboot сервис:
|
Если хочешь проверить post-reboot сервис:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo systemctl status iomatex-local-installer-post-reboot.service --no-pager -l
|
sudo systemctl status iomatex-local-installer-post-reboot.service --no-pager
|
||||||
```
|
```
|
||||||
|
|
||||||
После завершения установки проверьте последние строки лога и состояние:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo tail -n 100 /userdata/Iomatex_OS/local_installer.log
|
|
||||||
sudo cat /userdata/Iomatex_OS/local_installer.state
|
|
||||||
```
|
|
||||||
|
|
||||||
Если файл не найден, журнал службы продолжения не зависит от папки проекта:
|
|
||||||
|
|
||||||
```bash
|
|
||||||
sudo journalctl -u iomatex-local-installer-post-reboot.service -b -n 150 --no-pager -l
|
|
||||||
```
|
|
||||||
|
|
||||||
После завершения службы `inactive (dead)` и `disabled` сами по себе не являются
|
|
||||||
ошибкой. Проверяйте `Failed stages`, `LAST_RESULT` и `POST_REBOOT_PENDING`:
|
|
||||||
для полностью успешного завершения ожидаются отсутствие проваленных стадий,
|
|
||||||
`LAST_RESULT=success` и `POST_REBOOT_PENDING=0`.
|
|
||||||
|
|
||||||
Что это значит простыми словами:
|
Что это значит простыми словами:
|
||||||
- установщик пишет все в лог;
|
- установщик пишет все в лог;
|
||||||
- команда `tail -f` просто показывает новые строки по мере появления;
|
- команда `tail -f` просто показывает новые строки по мере появления;
|
||||||
|
|
@ -411,11 +337,11 @@ LOCAL INSTALLER SUMMARY
|
||||||
============================================================
|
============================================================
|
||||||
Source type :
|
Source type :
|
||||||
Source :
|
Source :
|
||||||
Project root : /userdata/Iomatex_OS
|
Project root : /opt/iomatex/Iomatex_OS
|
||||||
Selected stages : stage_env stage_wifi stage_mqtt stage_ui stage_itscreen stage_reverse_tunnels
|
Selected stages : stage_env stage_wifi stage_mqtt stage_ui stage_itscreen stage_reverse_tunnels
|
||||||
Reboot continuation : yes
|
Reboot continuation : yes
|
||||||
Log file : /userdata/Iomatex_OS/local_installer.log
|
Log file : /opt/iomatex/Iomatex_OS/local_installer.log
|
||||||
State file : /userdata/Iomatex_OS/local_installer.state
|
State file : /opt/iomatex/Iomatex_OS/local_installer.state
|
||||||
|
|
||||||
Successful stages:
|
Successful stages:
|
||||||
- stage_env
|
- stage_env
|
||||||
|
|
@ -439,7 +365,7 @@ Failed stages:
|
||||||
Если в этот момент у тебя открыт просмотр лога через:
|
Если в этот момент у тебя открыт просмотр лога через:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo tail -f /userdata/Iomatex_OS/local_installer.log
|
sudo tail -f /opt/iomatex/Iomatex_OS/local_installer.log
|
||||||
```
|
```
|
||||||
|
|
||||||
то после окончания установки нажми:
|
то после окончания установки нажми:
|
||||||
|
|
@ -635,26 +561,3 @@ journalctl -u iomatex-rt-webui.service -n 80 --no-pager
|
||||||
- надо переустановить только одну часть Edge;
|
- надо переустановить только одну часть Edge;
|
||||||
- надо решить, можно ли ставить стадию поверх уже рабочего устройства;
|
- надо решить, можно ли ставить стадию поверх уже рабочего устройства;
|
||||||
- надо подробно разобраться с `stage_reverse_tunnels`.
|
- надо подробно разобраться с `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. Визуальная проверка физического экрана и управление аппаратными выходами в эту диагностику не входили.
|
|
||||||
|
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
# Edge Console 3.1.24
|
|
||||||
|
|
||||||
- Replaced the unbounded Modbus marker with an expiring, renewable scanner lease owned by Edge Console.
|
|
||||||
- Edge Console now owns the complete `/dev/ttyS3` handoff: stop IT-Screen Client, scan, release the lease, and restore the Client even after a failed scan or an abandoned browser session.
|
|
||||||
- Added exact session ownership checks, heartbeat/watchdog recovery, legacy-lock recovery, and regression coverage for scanner lifecycle and frontend API calls.
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
# Edge Console 3.1.25
|
|
||||||
|
|
||||||
- Identify IOMX-SNG-500 applications installed on an ExBd Nano base with a
|
|
||||||
compound read-only fingerprint: the shared Nano identity plus SNG state,
|
|
||||||
error and power registers.
|
|
||||||
- Keep the ordinary ExBd Nano profile as a fallback when the application
|
|
||||||
fingerprint does not match.
|
|
||||||
- Retain the renewable scanner lease and abandoned-session recovery delivered
|
|
||||||
in Console 3.1.24.
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
# Edge Console 3.1.26
|
|
||||||
|
|
||||||
- Apply all three receiver-assigned reverse tunnel ports during registration,
|
|
||||||
server migration and the existing Configure action. Previously only the SSH
|
|
||||||
gateway/user changed, leaving old ports that the new receiver rejected.
|
|
||||||
- Validate complete, distinct TCP port assignments before changing local files.
|
|
||||||
- Migrate installed legacy wrappers to read assigned ports from the shared
|
|
||||||
environment file, preserving their SSH keys and local service endpoints.
|
|
||||||
- After a Console update, retry enrollment once using the existing client
|
|
||||||
registration. Offline/unregistered devices retain the manual Configure retry;
|
|
||||||
no client registration reset or client restart is required.
|
|
||||||
- Validation: 126 Console tests, 7 tunnel tests and 24 stage catalog tests pass.
|
|
||||||
Shell syntax checks pass for both installers.
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
# Edge Console 3.1.27
|
|
||||||
|
|
||||||
- Fix the 3.1.26 enrollment validator to consume the actual receiver response:
|
|
||||||
each named port is an object containing local, remote and available fields.
|
|
||||||
Persist remote; do not require availability before starting the tunnel.
|
|
||||||
- Retain support for scalar port assignments and reject missing, invalid and
|
|
||||||
duplicate remote ports before changing configuration.
|
|
||||||
- Add regression coverage using the observed EVA response, including offline
|
|
||||||
endpoints and invalid nested port values. All 127 Console tests pass.
|
|
||||||
- On g-box-8e6af561, enrollment successfully applied ports 34589/34590/34591.
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,10 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,12 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,14 +0,0 @@
|
||||||
# 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%).
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,11 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,34 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,51 +0,0 @@
|
||||||
# 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).
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
# stage_itscreen 1.0.27 — Debian ARM64 client 5.1.23
|
|
||||||
|
|
||||||
Release date: 2026-10-18.
|
|
||||||
|
|
||||||
- Publish the common Modbus input recovery verified during the UAE audit.
|
|
||||||
- Return interrupted FC02 and FC04 ranges to the polling scheduler after a
|
|
||||||
serial reconnect or configuration refresh.
|
|
||||||
- Apply the shared 1000 ms minimum response timeout to discrete-input and
|
|
||||||
input-register reads for SNG-500, ExBd, PT-100 and all other modules.
|
|
||||||
- Detect an SNG-500 application running on ExBd Nano hardware without hiding
|
|
||||||
the physical board identity from diagnostics.
|
|
||||||
- Preserve polling of healthy ranges when another range is unavailable and
|
|
||||||
recover suspended modules automatically after communication is restored.
|
|
||||||
- Raise the Console update stage from 1.0.26 to 1.0.27. Client 5.1.23 and
|
|
||||||
stage 1.0.27 remain separate version contracts.
|
|
||||||
|
|
||||||
The ARM64 binary is built natively from the exact `iomatex_dev` merge commit
|
|
||||||
recorded in `release-provenance.json`. No resource injection or binary patching
|
|
||||||
is used.
|
|
||||||
|
|
||||||
Validation: 58 Python contract tests passed, 2 skipped; the native Qt/Modbus
|
|
||||||
PTY integration test passed. On UAE Ogorod, slave 3 exposed 12/12 available
|
|
||||||
inputs. On UAE BeMD_Showroom, SNG-500 slave 1 exposed 16/16 available inputs.
|
|
||||||
The unsupported SNG register 1441 remains a separate template/firmware-map
|
|
||||||
issue and is not treated as a transport failure.
|
|
||||||
|
|
||||||
Binary SHA256: `5195c097727f34cc0552e4a0d0d2001c6e8a7b27490c1868266ea3198e0e76c0`.
|
|
||||||
|
|
@ -1,21 +0,0 @@
|
||||||
# stage_itscreen 1.0.28 — Debian ARM64 client 5.1.28
|
|
||||||
|
|
||||||
- Publish the shared EVAx10 menu, Settings and diagnostics UI on Debian.
|
|
||||||
- Show registration server and Device ID in shared headers; enlarge Settings
|
|
||||||
version and Device ID text. Include the English startup identity card.
|
|
||||||
- Add the HTTP/HTTPS selector before the registration address and keep the
|
|
||||||
confirmed address synchronized while Connection remains open.
|
|
||||||
- Prevent background busy notifications from covering Settings Close / Apply.
|
|
||||||
- Preserve Debian SerialPort/SerialBus, Modbus, ONVIF and local Console features.
|
|
||||||
- Source branch is now Debian_CLient (renamed from iomatex_dev).
|
|
||||||
|
|
||||||
Build provenance and checksum are recorded in stage_itscreen/release-provenance.json.
|
|
||||||
The client and Console installation-stage versions remain separate contracts.
|
|
||||||
|
|
||||||
Validation: native Debian 11 ARM64 / Qt 5.15.2 release build succeeded;
|
|
||||||
`itscreen --version` reports 5.1.28. No missing shared libraries; SerialPort,
|
|
||||||
SerialBus and WebView are linked. Client Python/Node suites and Modbus PTY
|
|
||||||
integration checks passed. Console stage-update API/UI and display tests passed.
|
|
||||||
The installed client on the build device was not replaced.
|
|
||||||
|
|
||||||
Binary SHA256: `1ec74511b5df12e5e3d78ef728cfff651957c84d87875f5347f9dc02733ba334`.
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,17 +0,0 @@
|
||||||
# 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`.
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,5 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
# 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`.
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,13 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,16 +0,0 @@
|
||||||
# stage_mqtt 1.0.6 — authoritative registration routing
|
|
||||||
|
|
||||||
Release date: 2026-10-23.
|
|
||||||
|
|
||||||
- Treat the registered IT-Screen client's MQTT prefix as authoritative when it
|
|
||||||
identifies the same broker as the system bridge.
|
|
||||||
- Replace a stale platform `BRIDGE_BASE_TOPIC` left by an earlier server
|
|
||||||
transfer instead of continuing to publish health into both environments.
|
|
||||||
- Preserve the intentional system-owned `v1/edge` namespace alongside the
|
|
||||||
active platform namespace.
|
|
||||||
- Clear the retired retained health topic before replacing its bridge route, so
|
|
||||||
the previous platform stops presenting the migrated Edge as current.
|
|
||||||
|
|
||||||
Validation: routing tests execute the generated `iomatex-mqtt-apply` functions
|
|
||||||
against matching and mismatched brokers, stale EVA-to-DEV platform prefixes,
|
|
||||||
the preserved system namespace, invalid prefixes and retained-topic cleanup.
|
|
||||||
|
|
@ -1,8 +0,0 @@
|
||||||
# Reverse Tunnels 1.0.2
|
|
||||||
|
|
||||||
- Read remote cockpit, webui and z2m ports from the environment assigned by
|
|
||||||
Console enrollment, with legacy derived ports as the pre-enrollment fallback.
|
|
||||||
- Preserve enrolled port assignments when reinstalling/updating this stage.
|
|
||||||
- Works with Console 3.1.26 to restore remote access after environment migration.
|
|
||||||
- Validation: installer lifecycle and generated-wrapper tests pass, including
|
|
||||||
saved gateway/port preservation and shell syntax checks.
|
|
||||||
|
|
@ -4,7 +4,7 @@ set -Eeuo pipefail
|
||||||
[[ ${EUID:-$(id -u)} -eq 0 ]] || exec sudo -E bash "$0" "$@"
|
[[ ${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 PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||||
export DEBIAN_FRONTEND=noninteractive
|
export DEBIAN_FRONTEND=noninteractive
|
||||||
GIT_URL=${IOMATEX_GIT_URL:-https://git.iomatex.com/An-J/Iomatex_OS.git}
|
GIT_URL=${IOMATEX_GIT_URL:-https://git.it-screen.com/An-J/Iomatex_OS.git}
|
||||||
GIT_BRANCH=${IOMATEX_GIT_BRANCH:-ci-cd}
|
GIT_BRANCH=${IOMATEX_GIT_BRANCH:-ci-cd}
|
||||||
CHECKOUT_DIR=${IOMATEX_GIT_DIR:-/userdata/Iomatex_OS}
|
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
|
STAGES=stage_env,stage_wifi,stage_mqtt,stage_ui,stage_avahi,stage_cockpit,stage_itscreen,stage_reverse_tunnels
|
||||||
|
|
@ -21,7 +21,7 @@ while [[ $# -gt 0 ]]; do
|
||||||
*) echo "Unknown argument: $1" >&2; exit 1 ;;
|
*) echo "Unknown argument: $1" >&2; exit 1 ;;
|
||||||
esac
|
esac
|
||||||
done
|
done
|
||||||
[[ ( "$GIT_URL" == https://git.it-screen.com/* || "$GIT_URL" == https://git.iomatex.com/* ) && "$GIT_URL" != *'@'* && "$GIT_URL" != *'?'* && "$GIT_URL" != *'#'* ]] || { echo 'Only HTTPS repositories on git.it-screen.com or git.iomatex.com are supported' >&2; exit 1; }
|
[[ "$GIT_URL" == https://git.it-screen.com/* && "$GIT_URL" != *'@'* && "$GIT_URL" != *'?'* && "$GIT_URL" != *'#'* ]] || { echo 'Only HTTPS repositories on git.it-screen.com are supported' >&2; exit 1; }
|
||||||
[[ "$GIT_BRANCH" =~ ^[A-Za-z0-9._/-]+$ ]] || { echo 'Invalid branch' >&2; exit 1; }
|
[[ "$GIT_BRANCH" =~ ^[A-Za-z0-9._/-]+$ ]] || { echo 'Invalid branch' >&2; exit 1; }
|
||||||
[[ "$CHECKOUT_DIR" == /* && "$CHECKOUT_DIR" != / && "$CHECKOUT_DIR" != /userdata && "$CHECKOUT_DIR" != /opt ]] || { echo 'Use an absolute checkout subdirectory' >&2; exit 1; }
|
[[ "$CHECKOUT_DIR" == /* && "$CHECKOUT_DIR" != / && "$CHECKOUT_DIR" != /userdata && "$CHECKOUT_DIR" != /opt ]] || { echo 'Use an absolute checkout subdirectory' >&2; exit 1; }
|
||||||
# Standalone bootstrap embeds the same lock contract as offline/install-lock.sh.
|
# Standalone bootstrap embeds the same lock contract as offline/install-lock.sh.
|
||||||
|
|
@ -47,47 +47,20 @@ fi
|
||||||
work=$(mktemp -d)
|
work=$(mktemp -d)
|
||||||
trap 'rm -rf "$work"' EXIT
|
trap 'rm -rf "$work"' EXIT
|
||||||
python3 - "$GIT_URL" "$GIT_BRANCH" "$work/git_delivery.py" <<'PYTHON'
|
python3 - "$GIT_URL" "$GIT_BRANCH" "$work/git_delivery.py" <<'PYTHON'
|
||||||
import base64, json, os, pathlib, socket, ssl, urllib.error, urllib.parse, urllib.request, sys
|
import base64, json, os, pathlib, urllib.parse, urllib.request, sys
|
||||||
url, branch, destination = sys.argv[1:]
|
url, branch, destination = sys.argv[1:]
|
||||||
parsed = urllib.parse.urlparse(url)
|
repo = urllib.parse.urlparse(url).path.strip('/').removesuffix('.git')
|
||||||
if parsed.scheme != 'https' or parsed.netloc not in ('git.it-screen.com', 'git.iomatex.com') or parsed.query or parsed.fragment:
|
base = 'https://git.it-screen.com/api/v1/repos/' + repo + '/'
|
||||||
raise ValueError('Unsupported Git URL')
|
|
||||||
repo = parsed.path.strip('/').removesuffix('.git')
|
|
||||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||||
def redirect_request(self, *args, **kwargs):
|
def redirect_request(self, *args, **kwargs):
|
||||||
raise RuntimeError('Git download redirect refused')
|
raise RuntimeError('Git download redirect refused')
|
||||||
headers = {'User-Agent': 'IomatexOS-Updater/1.0', 'Authorization': 'Basic ' + base64.b64encode((os.environ['IOMATEX_GIT_USERNAME'] + ':' + os.environ['IOMATEX_GIT_PASSWORD']).encode()).decode()}
|
headers = {'Authorization': 'Basic ' + base64.b64encode((os.environ['IOMATEX_GIT_USERNAME'] + ':' + os.environ['IOMATEX_GIT_PASSWORD']).encode()).decode()}
|
||||||
opener = urllib.request.build_opener(NoRedirect)
|
opener = urllib.request.build_opener(NoRedirect)
|
||||||
# Accept old saved URLs as input only; never make a request to the blocked host.
|
with opener.open(urllib.request.Request(base + 'branches/' + urllib.parse.quote(branch, safe=''), headers=headers), timeout=120) as r:
|
||||||
host = 'git.iomatex.com'
|
|
||||||
attempts = 2
|
|
||||||
commit = None
|
|
||||||
for index in range(attempts):
|
|
||||||
base = 'https://' + host + '/api/v1/repos/' + repo + '/'
|
|
||||||
try:
|
|
||||||
if commit is None:
|
|
||||||
with opener.open(urllib.request.Request(base + 'branches/' + urllib.parse.quote(branch, safe=''), headers=headers), timeout=15) as r:
|
|
||||||
commit = json.load(r)['commit']['id']
|
commit = json.load(r)['commit']['id']
|
||||||
with opener.open(urllib.request.Request(base + 'raw/offline/git_delivery.py?ref=' + commit, headers=headers), timeout=15) as r:
|
with opener.open(urllib.request.Request(base + 'raw/offline/git_delivery.py?ref=' + commit, headers=headers), timeout=120) as r:
|
||||||
content = r.read()
|
pathlib.Path(destination).write_bytes(r.read())
|
||||||
pathlib.Path(destination).write_bytes(content)
|
|
||||||
pathlib.Path(destination + '.source').write_text('https://' + host + '/' + repo + '.git')
|
|
||||||
print('Git source: ' + host, flush=True)
|
|
||||||
break
|
|
||||||
except urllib.error.HTTPError as exc:
|
|
||||||
raise SystemExit('Git returned HTTP ' + str(exc.code) + '; check credentials, repository and branch. No domain switch.') from None
|
|
||||||
except (urllib.error.URLError, OSError) as exc:
|
|
||||||
reason = exc.reason if isinstance(exc, urllib.error.URLError) else exc
|
|
||||||
if isinstance(reason, ssl.SSLError):
|
|
||||||
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 == 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
|
PYTHON
|
||||||
GIT_URL=$(cat "$work/git_delivery.py.source")
|
|
||||||
export IOMATEX_RECOVERY_STAGES="$STAGES"
|
export IOMATEX_RECOVERY_STAGES="$STAGES"
|
||||||
python3 "$work/git_delivery.py" bootstrap "$GIT_URL" "$GIT_BRANCH" "$CHECKOUT_DIR"
|
python3 "$work/git_delivery.py" bootstrap "$GIT_URL" "$GIT_BRANCH" "$CHECKOUT_DIR"
|
||||||
unset IOMATEX_GIT_USERNAME IOMATEX_GIT_PASSWORD
|
unset IOMATEX_GIT_USERNAME IOMATEX_GIT_PASSWORD
|
||||||
|
|
|
||||||
|
|
@ -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="iomatex-local-installer-post-reboot.desktop"
|
||||||
POST_REBOOT_AUTOSTART_PATH="/etc/xdg/autostart/${POST_REBOOT_AUTOSTART}"
|
POST_REBOOT_AUTOSTART_PATH="/etc/xdg/autostart/${POST_REBOOT_AUTOSTART}"
|
||||||
|
|
||||||
IOMATEX_GIT_URL="${IOMATEX_GIT_URL:-https://git.iomatex.com/An-J/Iomatex_OS.git}"
|
IOMATEX_GIT_URL="${IOMATEX_GIT_URL:-https://git.it-screen.com/An-J/Iomatex_OS.git}"
|
||||||
IOMATEX_GIT_BRANCH="${IOMATEX_GIT_BRANCH:-ci-cd}"
|
IOMATEX_GIT_BRANCH="${IOMATEX_GIT_BRANCH:-ci-cd}"
|
||||||
IOMATEX_GIT_DIR="${IOMATEX_GIT_DIR:-/opt/iomatex/Iomatex_OS}"
|
IOMATEX_GIT_DIR="${IOMATEX_GIT_DIR:-/opt/iomatex/Iomatex_OS}"
|
||||||
IOMATEX_GIT_TOKEN="${IOMATEX_GIT_TOKEN:-}"
|
IOMATEX_GIT_TOKEN="${IOMATEX_GIT_TOKEN:-}"
|
||||||
|
|
@ -206,7 +206,7 @@ Behavior:
|
||||||
- stops on first stage failure
|
- stops on first stage failure
|
||||||
|
|
||||||
Git defaults:
|
Git defaults:
|
||||||
- IOMATEX_GIT_URL=https://git.iomatex.com/An-J/Iomatex_OS.git
|
- IOMATEX_GIT_URL=https://git.it-screen.com/An-J/Iomatex_OS.git
|
||||||
- IOMATEX_GIT_BRANCH=ci-cd
|
- IOMATEX_GIT_BRANCH=ci-cd
|
||||||
- IOMATEX_GIT_DIR=/opt/iomatex/Iomatex_OS
|
- IOMATEX_GIT_DIR=/opt/iomatex/Iomatex_OS
|
||||||
EOF
|
EOF
|
||||||
|
|
@ -1427,7 +1427,7 @@ else
|
||||||
SOURCE_COMMIT=""
|
SOURCE_COMMIT=""
|
||||||
else
|
else
|
||||||
if [[ "$USE_GIT_SOURCE" -eq 1 ]]; then
|
if [[ "$USE_GIT_SOURCE" -eq 1 ]]; then
|
||||||
[[ ( "$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"
|
[[ "$GIT_URL" == https://git.it-screen.com/* ]] || die "Only our Git is allowed"
|
||||||
die "Use install_iomatex_edge.sh to update the lightweight snapshot; full Git clones on Edge are disabled"
|
die "Use install_iomatex_edge.sh to update the lightweight snapshot; full Git clones on Edge are disabled"
|
||||||
else
|
else
|
||||||
PROJECT_DIR="$SCRIPT_DIR"
|
PROJECT_DIR="$SCRIPT_DIR"
|
||||||
|
|
|
||||||
|
|
@ -26,15 +26,7 @@ import urllib.error
|
||||||
import urllib.parse
|
import urllib.parse
|
||||||
import urllib.request
|
import urllib.request
|
||||||
|
|
||||||
HOST = 'git.iomatex.com'
|
HOST = 'git.it-screen.com'
|
||||||
ALLOWED_HOSTS = (HOST, 'git.it-screen.com')
|
|
||||||
|
|
||||||
def git_host(value=HOST):
|
|
||||||
if value not in ALLOWED_HOSTS:
|
|
||||||
raise ValueError('Unsupported Git host')
|
|
||||||
# Normalize legacy saved credentials/snapshots before any network request.
|
|
||||||
return HOST
|
|
||||||
|
|
||||||
STATE = Path('/var/lib/iomatex/packages')
|
STATE = Path('/var/lib/iomatex/packages')
|
||||||
AUTH = Path('/etc/iomatex/git-credentials.json')
|
AUTH = Path('/etc/iomatex/git-credentials.json')
|
||||||
CACHE = Path('/userdata/iomatex-apt-cache')
|
CACHE = Path('/userdata/iomatex-apt-cache')
|
||||||
|
|
@ -52,7 +44,7 @@ def safe_path(value):
|
||||||
|
|
||||||
def repo_name(url):
|
def repo_name(url):
|
||||||
u = urllib.parse.urlparse(url)
|
u = urllib.parse.urlparse(url)
|
||||||
if u.scheme != 'https' or u.netloc not in ALLOWED_HOSTS or u.query or u.fragment:
|
if u.scheme != 'https' or u.netloc != HOST or u.query or u.fragment:
|
||||||
raise ValueError('Only HTTPS repositories on our Git are allowed')
|
raise ValueError('Only HTTPS repositories on our Git are allowed')
|
||||||
name = u.path.strip('/').removesuffix('.git')
|
name = u.path.strip('/').removesuffix('.git')
|
||||||
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', name):
|
if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', name):
|
||||||
|
|
@ -66,9 +58,9 @@ def auth_from_env():
|
||||||
return json.loads(AUTH.read_text())
|
return json.loads(AUTH.read_text())
|
||||||
|
|
||||||
def open_git(repo, endpoint, auth, timeout=120):
|
def open_git(repo, endpoint, auth, timeout=120):
|
||||||
url = 'https://' + git_host(auth.get('host', HOST)) + '/api/v1/repos/' + repo + '/' + endpoint
|
url = 'https://' + HOST + '/api/v1/repos/' + repo + '/' + endpoint
|
||||||
token = base64.b64encode((auth['username'] + ':' + auth['password']).encode()).decode()
|
token = base64.b64encode((auth['username'] + ':' + auth['password']).encode()).decode()
|
||||||
req = urllib.request.Request(url, headers={'Authorization': 'Basic ' + token, 'User-Agent': 'IomatexOS-Updater/1.0'})
|
req = urllib.request.Request(url, headers={'Authorization': 'Basic ' + token})
|
||||||
return urllib.request.build_opener(NoRedirect).open(req, timeout=timeout)
|
return urllib.request.build_opener(NoRedirect).open(req, timeout=timeout)
|
||||||
|
|
||||||
def raw_endpoint(path, commit):
|
def raw_endpoint(path, commit):
|
||||||
|
|
@ -269,7 +261,7 @@ def recovery_gate(repo, branch, commit, auth, files, stages, job=None):
|
||||||
materialize_file(repo, commit, auth, item, root / 'absent', root)
|
materialize_file(repo, commit, auth, item, root / 'absent', root)
|
||||||
download_snapshot(files, download)
|
download_snapshot(files, download)
|
||||||
write_json(root / '.iomatex-source.json',
|
write_json(root / '.iomatex-source.json',
|
||||||
{'repo': repo, 'host': git_host(auth.get('host', HOST)), 'branch': branch, 'commit': commit, 'files': files})
|
{'repo': repo, 'branch': branch, 'commit': commit, 'files': files})
|
||||||
print('Verifying recovery package catalog...', flush=True)
|
print('Verifying recovery package catalog...', flush=True)
|
||||||
catalog(root)
|
catalog(root)
|
||||||
write_json(AUTH, auth, 0o600)
|
write_json(AUTH, auth, 0o600)
|
||||||
|
|
@ -283,44 +275,6 @@ def recovery_gate(repo, branch, commit, auth, files, stages, job=None):
|
||||||
raise RecoveryPending('Offline userdata recovery queued; update is pending, not complete')
|
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):
|
def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery_job=None, preserve_local_changes=False):
|
||||||
platform_check()
|
platform_check()
|
||||||
repo = repo_name(url)
|
repo = repo_name(url)
|
||||||
|
|
@ -328,15 +282,18 @@ def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery
|
||||||
dest = requested.resolve()
|
dest = requested.resolve()
|
||||||
if not requested.is_absolute() or len(dest.parts) < 3 or requested.is_symlink():
|
if not requested.is_absolute() or len(dest.parts) < 3 or requested.is_symlink():
|
||||||
raise ValueError('Use a dedicated absolute installer subdirectory')
|
raise ValueError('Use a dedicated absolute installer subdirectory')
|
||||||
auth = {**auth_from_env(), 'host': git_host(urllib.parse.urlparse(url).netloc)}
|
auth = auth_from_env()
|
||||||
if commit is None:
|
if commit is None:
|
||||||
with open_git(repo, 'branches/' + urllib.parse.quote(branch, safe=''), auth) as r:
|
with open_git(repo, 'branches/' + urllib.parse.quote(branch, safe=''), auth) as r:
|
||||||
commit = json.load(r)['commit']['id']
|
commit = json.load(r)['commit']['id']
|
||||||
if not re.fullmatch('[a-f0-9]{40}', commit):
|
if not re.fullmatch('[a-f0-9]{40}', commit):
|
||||||
raise ValueError('Invalid pinned commit')
|
raise ValueError('Invalid pinned commit')
|
||||||
tree = repository_tree(repo, commit, auth)
|
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')
|
||||||
files = []
|
files = []
|
||||||
for item in tree:
|
for item in tree['tree']:
|
||||||
path = safe_path(item['path'])
|
path = safe_path(item['path'])
|
||||||
if item['type'] == 'tree' or is_payload(path):
|
if item['type'] == 'tree' or is_payload(path):
|
||||||
continue
|
continue
|
||||||
|
|
@ -361,7 +318,7 @@ def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery
|
||||||
materialize_file(repo, commit, auth, entry, dest, staged)
|
materialize_file(repo, commit, auth, entry, dest, staged)
|
||||||
print('Fetching', len(files), 'installer/metadata files; package payloads excluded', flush=True)
|
print('Fetching', len(files), 'installer/metadata files; package payloads excluded', flush=True)
|
||||||
download_snapshot(files, download)
|
download_snapshot(files, download)
|
||||||
source = {'repo': repo, 'host': git_host(auth.get('host', HOST)), 'commit': commit, 'branch': branch, 'files': files}
|
source = {'repo': repo, 'commit': commit, 'branch': branch, 'files': files}
|
||||||
write_json(staged / '.iomatex-source.json', source)
|
write_json(staged / '.iomatex-source.json', source)
|
||||||
# Validate all metadata before replacing an existing installation snapshot.
|
# Validate all metadata before replacing an existing installation snapshot.
|
||||||
catalog(staged)
|
catalog(staged)
|
||||||
|
|
@ -440,20 +397,14 @@ def activate(root):
|
||||||
platform_check()
|
platform_check()
|
||||||
root = Path(root).resolve()
|
root = Path(root).resolve()
|
||||||
source = json.loads((root / '.iomatex-source.json').read_text())
|
source = json.loads((root / '.iomatex-source.json').read_text())
|
||||||
repo_name('https://' + git_host(source.get('host', HOST)) + '/' + source['repo'])
|
repo_name('https://' + HOST + '/' + source['repo'])
|
||||||
raw_endpoint('probe', source['commit'])
|
raw_endpoint('probe', source['commit'])
|
||||||
auth = auth_from_env() # fail before modifying APT if reboot credentials are missing
|
auth_from_env() # fail before modifying APT if reboot credentials are missing
|
||||||
auth['host'] = git_host(auth.get('host', HOST))
|
|
||||||
text, objects = catalog(root)
|
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.mkdir(parents=True, exist_ok=True)
|
||||||
(STATE / 'Packages').write_text(text)
|
(STATE / 'Packages').write_text(text)
|
||||||
(STATE / 'Packages.gz').write_bytes(gzip.compress(text.encode(), mtime=0))
|
(STATE / 'Packages.gz').write_bytes(gzip.compress(text.encode(), mtime=0))
|
||||||
write_json(STATE / 'source.json', {'repo':source['repo'], 'host':git_host(source.get('host', HOST)), 'commit':source['commit'], 'objects':objects})
|
write_json(STATE / 'source.json', {'repo':source['repo'], 'commit':source['commit'], 'objects':objects})
|
||||||
owner = Path('/usr/local/lib/iomatex')
|
owner = Path('/usr/local/lib/iomatex')
|
||||||
owner.mkdir(parents=True, exist_ok=True)
|
owner.mkdir(parents=True, exist_ok=True)
|
||||||
shutil.copy2(root / 'offline/git_delivery.py', owner / 'git_delivery.py')
|
shutil.copy2(root / 'offline/git_delivery.py', owner / 'git_delivery.py')
|
||||||
|
|
@ -466,7 +417,7 @@ def activate(root):
|
||||||
CACHE.mkdir(parents=True, exist_ok=True)
|
CACHE.mkdir(parents=True, exist_ok=True)
|
||||||
(CACHE / 'partial').mkdir(exist_ok=True)
|
(CACHE / 'partial').mkdir(exist_ok=True)
|
||||||
apt = Path('/etc/apt')
|
apt = Path('/etc/apt')
|
||||||
(apt / 'iomatex-offline.list').write_text('deb [trusted=yes] iomatex://git.iomatex.com/ ./\n')
|
(apt / 'iomatex-offline.list').write_text('deb [trusted=yes] iomatex://git.it-screen.com/ ./\n')
|
||||||
(apt / 'apt.conf.d/99iomatex-offline').write_text(
|
(apt / 'apt.conf.d/99iomatex-offline').write_text(
|
||||||
'Dir::Etc::sourcelist "/etc/apt/iomatex-offline.list";\n'
|
'Dir::Etc::sourcelist "/etc/apt/iomatex-offline.list";\n'
|
||||||
'Dir::Etc::sourceparts "-";\n'
|
'Dir::Etc::sourceparts "-";\n'
|
||||||
|
|
@ -495,7 +446,7 @@ def download_object(config, key, dest, auth):
|
||||||
digest = hashlib.sha256()
|
digest = hashlib.sha256()
|
||||||
size = 0
|
size = 0
|
||||||
try:
|
try:
|
||||||
with open_git(config['repo'], raw_endpoint(entry['path'], config['commit']), {**auth, 'host': git_host(config.get('host', HOST))}) as response, path.open('wb') as output:
|
with open_git(config['repo'], raw_endpoint(entry['path'], config['commit']), auth) as response, path.open('wb') as output:
|
||||||
while True:
|
while True:
|
||||||
chunk = response.read(1024 * 1024)
|
chunk = response.read(1024 * 1024)
|
||||||
if not chunk: break
|
if not chunk: break
|
||||||
|
|
@ -517,7 +468,7 @@ def message(code, fields):
|
||||||
|
|
||||||
def apt_key(uri, objects):
|
def apt_key(uri, objects):
|
||||||
u = urllib.parse.urlparse(uri)
|
u = urllib.parse.urlparse(uri)
|
||||||
if u.scheme != 'iomatex' or u.netloc not in ALLOWED_HOSTS or u.query or u.fragment:
|
if u.scheme != 'iomatex' or u.netloc != HOST or u.query or u.fragment:
|
||||||
raise ValueError('Unsupported APT source')
|
raise ValueError('Unsupported APT source')
|
||||||
# APT's method protocol may already decode the URI displayed by apt-get.
|
# 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.
|
# Preserve literal %3a in Git filenames; never decode it twice into an epoch colon.
|
||||||
|
|
|
||||||
|
|
@ -16,7 +16,6 @@ lxterminal openbox wmctrl xdotool libqt5serialbus5-bin qml-module-qtmultimedia
|
||||||
qml-module-qtpositioning qml-module-qtquick-virtualkeyboard qtvirtualkeyboard-plugin
|
qml-module-qtpositioning qml-module-qtquick-virtualkeyboard qtvirtualkeyboard-plugin
|
||||||
qml-module-qtwebview qml-module-qt-labs-settings qml-module-qtquick-xmllistmodel
|
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-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).
|
# Camera streaming and snapshots (CLI, in addition to multimedia libraries).
|
||||||
ffmpeg
|
ffmpeg
|
||||||
# Keep installed OpenCV/GStreamer development chains compatible during FFmpeg upgrades.
|
# Keep installed OpenCV/GStreamer development chains compatible during FFmpeg upgrades.
|
||||||
|
|
|
||||||
|
|
@ -84,9 +84,8 @@ def record(root, stage):
|
||||||
def configure(root):
|
def configure(root):
|
||||||
root = Path(root).resolve()
|
root = Path(root).resolve()
|
||||||
source = read_json(root / '.iomatex-source.json')
|
source = read_json(root / '.iomatex-source.json')
|
||||||
delivery.repo_name('https://' + delivery.git_host(source.get('host', delivery.HOST)) + '/' + source['repo'] + '.git')
|
delivery.repo_name('https://' + delivery.HOST + '/' + source['repo'] + '.git')
|
||||||
next_config = {'checkout': str(root), 'repo': source['repo'], 'branch': source['branch'],
|
next_config = {'checkout': str(root), 'repo': source['repo'], 'branch': source['branch']}
|
||||||
'host': delivery.git_host(source.get('host', delivery.HOST))}
|
|
||||||
if read_json(CONFIG) != next_config:
|
if read_json(CONFIG) != next_config:
|
||||||
delivery.write_json(STATE / 'available.json', {})
|
delivery.write_json(STATE / 'available.json', {})
|
||||||
delivery.write_json(CONFIG, next_config)
|
delivery.write_json(CONFIG, next_config)
|
||||||
|
|
@ -98,8 +97,8 @@ def refresh():
|
||||||
phase = 'branch'
|
phase = 'branch'
|
||||||
try:
|
try:
|
||||||
cfg = read_json(CONFIG)
|
cfg = read_json(CONFIG)
|
||||||
repo = delivery.repo_name('https://' + delivery.git_host(cfg.get('host', delivery.HOST)) + '/' + cfg['repo'] + '.git')
|
repo = delivery.repo_name('https://' + delivery.HOST + '/' + cfg['repo'] + '.git')
|
||||||
auth = {**delivery.auth_from_env(), 'host': delivery.git_host(cfg.get('host', delivery.HOST))}
|
auth = delivery.auth_from_env()
|
||||||
with delivery.open_git(repo, 'branches/' + urllib.parse.quote(cfg['branch'], safe=''), auth, timeout=15) as response:
|
with delivery.open_git(repo, 'branches/' + urllib.parse.quote(cfg['branch'], safe=''), auth, timeout=15) as response:
|
||||||
commit = json.load(response)['commit']['id']
|
commit = json.load(response)['commit']['id']
|
||||||
phase = 'catalog'
|
phase = 'catalog'
|
||||||
|
|
@ -116,14 +115,6 @@ def refresh():
|
||||||
error = 'The stage release catalog has not been published to Git yet.'
|
error = 'The stage release catalog has not been published to Git yet.'
|
||||||
elif exc.code in (401, 403):
|
elif exc.code in (401, 403):
|
||||||
error = 'Git access was denied. Check the Edge Git credentials.'
|
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.
|
# Do not expose credentials, HTTP bodies or private paths in the API.
|
||||||
delivery.write_json(STATE / 'available.json', {
|
delivery.write_json(STATE / 'available.json', {
|
||||||
**previous, 'attempt_at': int(time.time()), 'error': error,
|
**previous, 'attempt_at': int(time.time()), 'error': error,
|
||||||
|
|
@ -361,7 +352,7 @@ def install(stage, commit):
|
||||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||||
cfg = read_json(CONFIG)
|
cfg = read_json(CONFIG)
|
||||||
delivery.write_json(STATE / 'job.json', {**job, 'state': 'running'})
|
delivery.write_json(STATE / 'job.json', {**job, 'state': 'running'})
|
||||||
delivery.bootstrap('https://' + delivery.git_host(cfg.get('host', delivery.HOST)) + '/' + cfg['repo'] + '.git',
|
delivery.bootstrap('https://' + delivery.HOST + '/' + cfg['repo'] + '.git',
|
||||||
cfg['branch'], cfg['checkout'], commit=commit, recovery_stages=stages, recovery_job=job, preserve_local_changes=True)
|
cfg['branch'], cfg['checkout'], commit=commit, recovery_stages=stages, recovery_job=job, preserve_local_changes=True)
|
||||||
root = Path(cfg['checkout'])
|
root = Path(cfg['checkout'])
|
||||||
completed = run_stages(root, stages, commit, job, lock.fileno())
|
completed = run_stages(root, stages, commit, job, lock.fileno())
|
||||||
|
|
|
||||||
|
|
@ -1,60 +0,0 @@
|
||||||
import io
|
|
||||||
import os
|
|
||||||
from pathlib import Path
|
|
||||||
import socket
|
|
||||||
import ssl
|
|
||||||
import sys
|
|
||||||
import tempfile
|
|
||||||
import unittest
|
|
||||||
from unittest.mock import patch, Mock
|
|
||||||
from urllib.error import URLError, HTTPError
|
|
||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[1]
|
|
||||||
SOURCE = (ROOT/'install_iomatex_edge.sh').read_text().split("<<'PYTHON'\n", 1)[1].split('\nPYTHON', 1)[0]
|
|
||||||
BRANCH = b'{"commit":{"id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}}'
|
|
||||||
|
|
||||||
class BootstrapFallbackTest(unittest.TestCase):
|
|
||||||
def run_bootstrap(self, responses, host='git.it-screen.com'):
|
|
||||||
temp = tempfile.TemporaryDirectory()
|
|
||||||
self.addCleanup(temp.cleanup)
|
|
||||||
destination = Path(temp.name)/'git_delivery.py'
|
|
||||||
opener = Mock()
|
|
||||||
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_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_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_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'))]:
|
|
||||||
with self.subTest(error=type(error).__name__):
|
|
||||||
with self.assertRaises(SystemExit):
|
|
||||||
self.run_bootstrap([error, AssertionError('Must not switch')])
|
|
||||||
|
|
||||||
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,66 +11,6 @@ sys.path.insert(0, str(Path(__file__).parent))
|
||||||
import git_delivery as d
|
import git_delivery as d
|
||||||
|
|
||||||
class DeliveryTest(unittest.TestCase):
|
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('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.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):
|
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']:
|
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))
|
self.assertTrue(d.is_payload(name))
|
||||||
|
|
@ -171,8 +111,7 @@ class DeliveryTest(unittest.TestCase):
|
||||||
key='debian/xserver-common_2%3a1.0+deb11_all.deb'
|
key='debian/xserver-common_2%3a1.0+deb11_all.deb'
|
||||||
objects={key:{}}
|
objects={key:{}}
|
||||||
for path in [key, 'debian/xserver-common_2%253a1.0%2bdeb11_all.deb']:
|
for path in [key, 'debian/xserver-common_2%253a1.0%2bdeb11_all.deb']:
|
||||||
for host in d.ALLOWED_HOSTS:
|
self.assertEqual(key,d.apt_key('iomatex://git.it-screen.com/'+path,objects))
|
||||||
self.assertEqual(key,d.apt_key('iomatex://'+host+'/'+path,objects))
|
|
||||||
|
|
||||||
def test_unchanged_snapshot_file_is_reused_without_network(self):
|
def test_unchanged_snapshot_file_is_reused_without_network(self):
|
||||||
with tempfile.TemporaryDirectory() as folder:
|
with tempfile.TemporaryDirectory() as folder:
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,6 @@ dpkg-query() {
|
||||||
if [[ "$EXISTING" == 1 ]]; then printf 'install ok installed'; else return 1; fi
|
if [[ "$EXISTING" == 1 ]]; then printf 'install ok installed'; else return 1; fi
|
||||||
}
|
}
|
||||||
install_packages_best_effort() { printf '%s\\n' "$*"; }
|
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'],
|
return subprocess.check_output(['bash', '-ec', stubs + functions + '\nprepare_qt_gles_stack\ninstall_qt_packages'],
|
||||||
env={**os.environ, 'EXISTING': str(existing)}, text=True)
|
env={**os.environ, 'EXISTING': str(existing)}, text=True)
|
||||||
|
|
@ -33,12 +32,4 @@ run_long() { printf '%s\\n' "$*"; }
|
||||||
def test_fresh_image_gets_gles(self):
|
def test_fresh_image_gets_gles(self):
|
||||||
self.assertIn('libqt5gui5-gles libqt5quick5-gles', self.run_selection(0))
|
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()
|
if __name__ == '__main__': unittest.main()
|
||||||
|
|
|
||||||
|
|
@ -34,7 +34,6 @@ class SnapshotUpdateTest(unittest.TestCase):
|
||||||
def test_confirmed_update_preserves_hotfix_and_operator_files(self):
|
def test_confirmed_update_preserves_hotfix_and_operator_files(self):
|
||||||
self.bootstrap()
|
self.bootstrap()
|
||||||
self.assertEqual(b'new release', (self.root/'install.sh').read_bytes())
|
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())
|
self.assertEqual(b'operator configuration', (self.root/'operator.conf').read_bytes())
|
||||||
backup, = self.parent.glob('.installer-local-changes-*')
|
backup, = self.parent.glob('.installer-local-changes-*')
|
||||||
self.assertEqual(0o700, backup.stat().st_mode & 0o777)
|
self.assertEqual(0o700, backup.stat().st_mode & 0o777)
|
||||||
|
|
|
||||||
|
|
@ -29,33 +29,6 @@ class StageVersionsTest(unittest.TestCase):
|
||||||
versions.delivery.write_json(versions.STATE / 'available.json', self.available)
|
versions.delivery.write_json(versions.STATE / 'available.json', self.available)
|
||||||
versions.delivery.write_json(versions.CONFIG, {'repo':'An-J/Iomatex_OS', 'branch':'ci-cd', 'checkout':str(root / 'checkout')})
|
versions.delivery.write_json(versions.CONFIG, {'repo':'An-J/Iomatex_OS', 'branch':'ci-cd', 'checkout':str(root / 'checkout')})
|
||||||
|
|
||||||
def test_selected_host_survives_update_configuration(self):
|
|
||||||
root = Path(self.tmp.name)/'source'
|
|
||||||
root.mkdir()
|
|
||||||
versions.delivery.write_json(root/'.iomatex-source.json', {
|
|
||||||
'repo': 'An-J/Iomatex_OS', 'branch': 'ci-cd', 'host': 'git.iomatex.com'})
|
|
||||||
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):
|
def test_published_catalog_is_accepted_by_legacy_console(self):
|
||||||
raw = json.loads((ROOT / 'stage-releases.json').read_text())
|
raw = json.loads((ROOT / 'stage-releases.json').read_text())
|
||||||
# This is the exact set checked by Console 3.1.2's validator.
|
# This is the exact set checked by Console 3.1.2's validator.
|
||||||
|
|
@ -275,18 +248,6 @@ class StageVersionsTest(unittest.TestCase):
|
||||||
self.assertEqual(expected, versions.read_json(versions.STATE / 'available.json')['error'])
|
self.assertEqual(expected, versions.read_json(versions.STATE / 'available.json')['error'])
|
||||||
self.assertFalse(self.snapshot()['can_install'])
|
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):
|
def test_release_check_refreshes_after_one_minute(self):
|
||||||
for age, expected in [(59, False), (61, True)]:
|
for age, expected in [(59, False), (61, True)]:
|
||||||
with self.subTest(age=age), mock.patch.object(versions, '_checking', False), \
|
with self.subTest(age=age), mock.patch.object(versions, '_checking', False), \
|
||||||
|
|
|
||||||
|
|
@ -2,19 +2,19 @@
|
||||||
"schema": 1,
|
"schema": 1,
|
||||||
"stages": {
|
"stages": {
|
||||||
"stage_env": {
|
"stage_env": {
|
||||||
"version": "1.0.5"
|
"version": "1.0.4"
|
||||||
},
|
},
|
||||||
"stage_wifi": {
|
"stage_wifi": {
|
||||||
"version": "1.0.0"
|
"version": "1.0.0"
|
||||||
},
|
},
|
||||||
"stage_mqtt": {
|
"stage_mqtt": {
|
||||||
"version": "1.0.6"
|
"version": "1.0.5"
|
||||||
},
|
},
|
||||||
"stage_z2m": {
|
"stage_z2m": {
|
||||||
"version": "1.0.1"
|
"version": "1.0.1"
|
||||||
},
|
},
|
||||||
"stage_ui": {
|
"stage_ui": {
|
||||||
"version": "3.1.42"
|
"version": "3.1.23"
|
||||||
},
|
},
|
||||||
"stage_avahi": {
|
"stage_avahi": {
|
||||||
"version": "1.0.0"
|
"version": "1.0.0"
|
||||||
|
|
@ -23,15 +23,15 @@
|
||||||
"version": "1.0.0"
|
"version": "1.0.0"
|
||||||
},
|
},
|
||||||
"stage_itscreen": {
|
"stage_itscreen": {
|
||||||
"version": "1.0.42"
|
"version": "1.0.26"
|
||||||
},
|
},
|
||||||
"stage_reverse_tunnels": {
|
"stage_reverse_tunnels": {
|
||||||
"version": "1.0.2"
|
"version": "1.0.1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"optional_stages": {
|
"optional_stages": {
|
||||||
"stage_ip_stream": {
|
"stage_ip_stream": {
|
||||||
"version": "1.0.10"
|
"version": "1.0.8"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -39,7 +39,7 @@ The main Edge install can continue without Cockpit.
|
||||||
After reboot, retry separately:
|
After reboot, retry separately:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
cd /userdata/Iomatex_OS
|
cd /opt/iomatex/Iomatex_OS
|
||||||
sudo dpkg --configure -a
|
sudo dpkg --configure -a
|
||||||
sudo apt-get -y -f install
|
sudo apt-get -y -f install
|
||||||
sudo apt-get check
|
sudo apt-get check
|
||||||
|
|
|
||||||
|
|
@ -6,8 +6,6 @@ import re
|
||||||
import sys
|
import sys
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
import uuid
|
|
||||||
import math
|
|
||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||||
from urllib.parse import parse_qs, urlparse
|
from urllib.parse import parse_qs, urlparse
|
||||||
|
|
@ -65,11 +63,6 @@ class BridgeState:
|
||||||
self.last_message_at = ""
|
self.last_message_at = ""
|
||||||
self.mqtt_connected = False
|
self.mqtt_connected = False
|
||||||
self.mqtt_last_error = ""
|
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):
|
def set_mqtt_connected(self, value):
|
||||||
with self.lock:
|
with self.lock:
|
||||||
|
|
@ -96,36 +89,6 @@ class BridgeState:
|
||||||
self.raw_payload = payload
|
self.raw_payload = payload
|
||||||
self.last_message_at = utc_timestamp()
|
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):
|
def get_component(self, component_id):
|
||||||
with self.lock:
|
with self.lock:
|
||||||
component = self.components.get(str(component_id))
|
component = self.components.get(str(component_id))
|
||||||
|
|
@ -141,14 +104,12 @@ class BridgeState:
|
||||||
|
|
||||||
|
|
||||||
class MqttBridge:
|
class MqttBridge:
|
||||||
def __init__(self, mqtt_url, device_id, state, prefix="it-screen/dev"):
|
def __init__(self, mqtt_url, device_id, state):
|
||||||
self.mqtt_url = mqtt_url
|
self.mqtt_url = mqtt_url
|
||||||
self.device_id = device_id
|
self.device_id = device_id
|
||||||
self.state = state
|
self.state = state
|
||||||
self.host, self.port = parse_mqtt_url(mqtt_url)
|
self.host, self.port = parse_mqtt_url(mqtt_url)
|
||||||
self.topic_prefix = prefix
|
self.state_topic = f"it-screen/dev/client/pub/component/plays/{device_id}"
|
||||||
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._publish_lock = threading.Lock()
|
||||||
self._ready = threading.Event()
|
self._ready = threading.Event()
|
||||||
self._client = None
|
self._client = None
|
||||||
|
|
@ -191,10 +152,10 @@ class MqttBridge:
|
||||||
def is_connected(self):
|
def is_connected(self):
|
||||||
return self._ready.is_set()
|
return self._ready.is_set()
|
||||||
|
|
||||||
def publish_event(self, component_id, value, title, expires_in_ms=None):
|
def publish_event(self, component_id, value, title):
|
||||||
if self._client is None:
|
if self._client is None:
|
||||||
raise RuntimeError("MQTT client is unavailable")
|
raise RuntimeError("MQTT client is unavailable")
|
||||||
topic = f"{self.topic_prefix}/client/sub/event/push/{component_id}"
|
topic = f"it-screen/dev/client/sub/event/push/{component_id}"
|
||||||
payload = {
|
payload = {
|
||||||
"action": "push",
|
"action": "push",
|
||||||
"value": str(value),
|
"value": str(value),
|
||||||
|
|
@ -202,11 +163,7 @@ class MqttBridge:
|
||||||
"time": utc_timestamp(),
|
"time": utc_timestamp(),
|
||||||
"user": "root",
|
"user": "root",
|
||||||
"title": str(title),
|
"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=(",", ":"))
|
serialized = json.dumps(payload, ensure_ascii=True, separators=(",", ":"))
|
||||||
with self._publish_lock:
|
with self._publish_lock:
|
||||||
if not self.is_connected():
|
if not self.is_connected():
|
||||||
|
|
@ -226,7 +183,7 @@ class MqttBridge:
|
||||||
self.state.set_mqtt_error(f"connect failed ({rc})")
|
self.state.set_mqtt_error(f"connect failed ({rc})")
|
||||||
log(f"mqtt connect failed rc={rc}")
|
log(f"mqtt connect failed rc={rc}")
|
||||||
return
|
return
|
||||||
result, _ = client.subscribe([(self.state_topic, 0), (self.register_topic, 0)])
|
result, _ = client.subscribe(self.state_topic, qos=0)
|
||||||
if result != mqtt_err_success():
|
if result != mqtt_err_success():
|
||||||
self._ready.clear()
|
self._ready.clear()
|
||||||
self.state.set_mqtt_error("subscribe failed")
|
self.state.set_mqtt_error("subscribe failed")
|
||||||
|
|
@ -258,10 +215,6 @@ class MqttBridge:
|
||||||
log(f"ignored invalid mqtt json topic={msg.topic} error={exc}")
|
log(f"ignored invalid mqtt json topic={msg.topic} error={exc}")
|
||||||
return
|
return
|
||||||
try:
|
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)
|
self.state.update_components(payload)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
log(f"ignored invalid mqtt payload topic={msg.topic} error={exc}")
|
log(f"ignored invalid mqtt payload topic={msg.topic} error={exc}")
|
||||||
|
|
@ -281,6 +234,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||||
|
|
||||||
def end_headers(self):
|
def end_headers(self):
|
||||||
self.send_header("Cache-Control", "no-store")
|
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-Origin", "*")
|
||||||
self.send_header("Access-Control-Allow-Headers", "Content-Type")
|
self.send_header("Access-Control-Allow-Headers", "Content-Type")
|
||||||
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
self.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
|
||||||
|
|
@ -289,7 +243,6 @@ class Handler(BaseHTTPRequestHandler):
|
||||||
def send_json(self, payload, code=200):
|
def send_json(self, payload, code=200):
|
||||||
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
|
||||||
self.send_response(code)
|
self.send_response(code)
|
||||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
|
||||||
self.send_header("Content-Length", str(len(body)))
|
self.send_header("Content-Length", str(len(body)))
|
||||||
self.end_headers()
|
self.end_headers()
|
||||||
self.wfile.write(body)
|
self.wfile.write(body)
|
||||||
|
|
@ -320,7 +273,6 @@ class Handler(BaseHTTPRequestHandler):
|
||||||
self.end_headers()
|
self.end_headers()
|
||||||
|
|
||||||
def do_GET(self):
|
def do_GET(self):
|
||||||
if self.app.offline_edit and self.app.offline_edit.handle(self): return
|
|
||||||
parsed = urlparse(self.path)
|
parsed = urlparse(self.path)
|
||||||
if parsed.path == "/api/health":
|
if parsed.path == "/api/health":
|
||||||
snapshot = self.app.state.health_snapshot()
|
snapshot = self.app.state.health_snapshot()
|
||||||
|
|
@ -351,11 +303,7 @@ class Handler(BaseHTTPRequestHandler):
|
||||||
self.send_json({"ok": False, "error": "Not found"}, code=404)
|
self.send_json({"ok": False, "error": "Not found"}, code=404)
|
||||||
|
|
||||||
def do_POST(self):
|
def do_POST(self):
|
||||||
if self.app.offline_edit and self.app.offline_edit.handle(self): return
|
|
||||||
parsed = urlparse(self.path)
|
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":
|
if parsed.path != "/api/event":
|
||||||
self.send_json({"ok": False, "error": "Not found"}, code=404)
|
self.send_json({"ok": False, "error": "Not found"}, code=404)
|
||||||
return
|
return
|
||||||
|
|
@ -409,31 +357,7 @@ class App:
|
||||||
self.mqtt_url = os.environ.get("DASHBOARD_BRIDGE_MQTT_URL", DEFAULT_MQTT_URL).strip() or DEFAULT_MQTT_URL
|
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.device_id = os.environ.get("DASHBOARD_BRIDGE_DEVICE_ID", "").strip() or device_id_from_hostname()
|
||||||
self.state = BridgeState()
|
self.state = BridgeState()
|
||||||
offline_config = os.environ.get('OFFLINE_HMI_CONFIG', '').strip()
|
self.mqtt_bridge = MqttBridge(self.mqtt_url, self.device_id, self.state)
|
||||||
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 = ThreadingHTTPServer((self.bind, self.port), Handler)
|
||||||
self.httpd.app = self
|
self.httpd.app = self
|
||||||
|
|
||||||
|
|
@ -442,11 +366,9 @@ class App:
|
||||||
f"starting http bind={self.bind} port={self.port} device_id={self.device_id} mqtt_url={self.mqtt_url}"
|
f"starting http bind={self.bind} port={self.port} device_id={self.device_id} mqtt_url={self.mqtt_url}"
|
||||||
)
|
)
|
||||||
self.mqtt_bridge.start()
|
self.mqtt_bridge.start()
|
||||||
if self.offline_edit: self.offline_edit.start()
|
|
||||||
try:
|
try:
|
||||||
self.httpd.serve_forever()
|
self.httpd.serve_forever()
|
||||||
finally:
|
finally:
|
||||||
if self.offline_edit: self.offline_edit.stop()
|
|
||||||
self.mqtt_bridge.stop()
|
self.mqtt_bridge.stop()
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1 +0,0 @@
|
||||||
"""Optional offline settings module; importing the legacy bridge does not enable it."""
|
|
||||||
|
|
@ -1,51 +0,0 @@
|
||||||
"""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']}
|
|
||||||
|
|
@ -1,201 +0,0 @@
|
||||||
"""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
|
|
||||||
|
|
@ -1,256 +0,0 @@
|
||||||
"""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
|
|
||||||
|
|
@ -1,25 +0,0 @@
|
||||||
"""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()
|
|
||||||
|
|
@ -1,72 +0,0 @@
|
||||||
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)
|
|
||||||
|
|
@ -1,131 +0,0 @@
|
||||||
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()
|
|
||||||
|
|
@ -1,120 +0,0 @@
|
||||||
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()
|
|
||||||
|
|
@ -1,36 +0,0 @@
|
||||||
# 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.
|
|
||||||
|
|
@ -1,87 +0,0 @@
|
||||||
# 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`.
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
{
|
|
||||||
"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"
|
|
||||||
}
|
|
||||||
|
Before Width: | Height: | Size: 845 KiB |
|
|
@ -1,10 +0,0 @@
|
||||||
[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
|
|
||||||
|
Before Width: | Height: | Size: 1.8 MiB |
|
|
@ -1 +0,0 @@
|
||||||
<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>
|
|
||||||
|
Before Width: | Height: | Size: 440 B |
|
|
@ -1 +0,0 @@
|
||||||
<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>
|
|
||||||
|
Before Width: | Height: | Size: 652 B |
|
|
@ -1 +0,0 @@
|
||||||
<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>
|
|
||||||
|
Before Width: | Height: | Size: 599 B |
|
|
@ -1 +0,0 @@
|
||||||
<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>
|
|
||||||
|
Before Width: | Height: | Size: 630 B |
|
|
@ -1 +0,0 @@
|
||||||
<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>
|
|
||||||
|
Before Width: | Height: | Size: 876 B |
|
|
@ -1 +0,0 @@
|
||||||
<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>
|
|
||||||
|
Before Width: | Height: | Size: 538 B |
|
|
@ -1 +0,0 @@
|
||||||
<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>
|
|
||||||
|
Before Width: | Height: | Size: 622 B |
|
|
@ -1,81 +0,0 @@
|
||||||
#!/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()
|
|
||||||
|
|
@ -1,17 +0,0 @@
|
||||||
[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
|
|
||||||
|
|
@ -1,356 +0,0 @@
|
||||||
#!/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]')
|
|
||||||
|
|
@ -1,20 +0,0 @@
|
||||||
#!/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.'
|
|
||||||
|
|
@ -1,3 +0,0 @@
|
||||||
#!/bin/sh
|
|
||||||
# One owner for the desktop, dock and Debian terminal alternative.
|
|
||||||
exec /usr/bin/lxterminal "$@"
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
#!/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
|
|
||||||
|
|
@ -1,126 +0,0 @@
|
||||||
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()
|
|
||||||
|
Before Width: | Height: | Size: 1.7 MiB |
|
Before Width: | Height: | Size: 1.4 MiB |
|
|
@ -1104,71 +1104,6 @@ EOF
|
||||||
|
|
||||||
ensure_gui_home_state "$IOM_USER"
|
ensure_gui_home_state "$IOM_USER"
|
||||||
ensure_lightdm_iomatex_login
|
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
|
if id youngfeel >/dev/null 2>&1; then
|
||||||
log "Harden vendor user: youngfeel (lock password, disable shell, remove sudo)"
|
log "Harden vendor user: youngfeel (lock password, disable shell, remove sudo)"
|
||||||
soft_run "Lock password youngfeel" 10 /usr/bin/passwd -l youngfeel
|
soft_run "Lock password youngfeel" 10 /usr/bin/passwd -l youngfeel
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,3 @@
|
||||||
{
|
{
|
||||||
"version": "1.0.5"
|
"version": "1.0.4"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -7,7 +7,6 @@ import signal
|
||||||
import socket
|
import socket
|
||||||
import subprocess
|
import subprocess
|
||||||
import shutil
|
import shutil
|
||||||
import tempfile
|
|
||||||
import threading
|
import threading
|
||||||
import time
|
import time
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
@ -23,8 +22,6 @@ SUPPORTED_INPUT_SCHEMES = {"rtsp"}
|
||||||
SUPPORTED_OUTPUT_SCHEMES = {"rtsp", "rtmp", "srt", "udp"}
|
SUPPORTED_OUTPUT_SCHEMES = {"rtsp", "rtmp", "srt", "udp"}
|
||||||
MAX_STREAMS = 8
|
MAX_STREAMS = 8
|
||||||
PREVIEW_TTL_SEC = 10 * 60
|
PREVIEW_TTL_SEC = 10 * 60
|
||||||
STARTUP_GUARD_SEC = 0.75
|
|
||||||
MAX_FORWARD_RESTARTS = 2
|
|
||||||
FFMPEG_BINARY = "/usr/bin/ffmpeg"
|
FFMPEG_BINARY = "/usr/bin/ffmpeg"
|
||||||
FFPROBE_BINARY = "/usr/bin/ffprobe"
|
FFPROBE_BINARY = "/usr/bin/ffprobe"
|
||||||
|
|
||||||
|
|
@ -91,12 +88,6 @@ def video_arguments(payload):
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
def sanitize_process_error(value):
|
|
||||||
value = re.sub(r"([a-z][a-z0-9+.-]*://)[^/@\s]+@", r"\1[redacted]@", str(value or ""), flags=re.I)
|
|
||||||
value = re.sub(r"(srt://[^?\s]+)\?[^\s]+", r"\1?[redacted]", value, flags=re.I)
|
|
||||||
return value.strip()[-2048:]
|
|
||||||
|
|
||||||
|
|
||||||
class StreamManager:
|
class StreamManager:
|
||||||
def __init__(self, device=None, prefix=None):
|
def __init__(self, device=None, prefix=None):
|
||||||
self.device = device or edge_id()
|
self.device = device or edge_id()
|
||||||
|
|
@ -109,7 +100,6 @@ class StreamManager:
|
||||||
self.operation_lock = threading.RLock()
|
self.operation_lock = threading.RLock()
|
||||||
self.control_socket = None
|
self.control_socket = None
|
||||||
self.supervisor_stop = threading.Event()
|
self.supervisor_stop = threading.Event()
|
||||||
self.last_failure = None
|
|
||||||
|
|
||||||
def publish(self, payload):
|
def publish(self, payload):
|
||||||
subprocess.run([
|
subprocess.run([
|
||||||
|
|
@ -130,19 +120,8 @@ class StreamManager:
|
||||||
code = process.poll()
|
code = process.poll()
|
||||||
if code is None:
|
if code is None:
|
||||||
continue
|
continue
|
||||||
error = self.read_error_log(record)
|
stopped.append({"stream_id": stream_id, "exit_code": code})
|
||||||
stopped.append({"stream_id": stream_id, "exit_code": code, "error": error})
|
|
||||||
self.remember_failure(stream_id, code, error)
|
|
||||||
if (record.get("kind") == "forward" and record.get("expires_at", 0) > now
|
|
||||||
and record.get("restart_count", 0) < MAX_FORWARD_RESTARTS):
|
|
||||||
self.close_error_log(record)
|
|
||||||
record["restart_count"] = record.get("restart_count", 0) + 1
|
|
||||||
record["error_log"] = tempfile.TemporaryFile(mode="w+b")
|
|
||||||
record["process"] = self.spawn(record["command"], stderr=record["error_log"])
|
|
||||||
stopped[-1]["restarted"] = True
|
|
||||||
continue
|
|
||||||
self.processes.pop(stream_id, None)
|
self.processes.pop(stream_id, None)
|
||||||
self.close_error_log(record)
|
|
||||||
self.write_status()
|
self.write_status()
|
||||||
return stopped
|
return stopped
|
||||||
|
|
||||||
|
|
@ -163,13 +142,11 @@ class StreamManager:
|
||||||
stream_id: {
|
stream_id: {
|
||||||
"kind": record.get("kind", "forward"),
|
"kind": record.get("kind", "forward"),
|
||||||
"expires_at": int(record.get("expires_at", 0)),
|
"expires_at": int(record.get("expires_at", 0)),
|
||||||
"restart_count": int(record.get("restart_count", 0)),
|
|
||||||
}
|
}
|
||||||
for stream_id, record in self.processes.items()
|
for stream_id, record in self.processes.items()
|
||||||
},
|
},
|
||||||
"active_count": len(self.processes),
|
"active_count": len(self.processes),
|
||||||
"max_streams": MAX_STREAMS,
|
"max_streams": MAX_STREAMS,
|
||||||
"last_failure": self.last_failure,
|
|
||||||
}), encoding="utf-8")
|
}), encoding="utf-8")
|
||||||
os.replace(temporary, STATUS_PATH)
|
os.replace(temporary, STATUS_PATH)
|
||||||
|
|
||||||
|
|
@ -200,76 +177,27 @@ class StreamManager:
|
||||||
"-application", "lowdelay", "-frame_duration", "20",
|
"-application", "lowdelay", "-frame_duration", "20",
|
||||||
*output_arguments(output_url),
|
*output_arguments(output_url),
|
||||||
]
|
]
|
||||||
error_log = tempfile.TemporaryFile(mode="w+b")
|
self.processes[stream_id] = {
|
||||||
process = self.spawn(command, stderr=error_log)
|
"process": self.spawn(command),
|
||||||
record = {
|
|
||||||
"process": process,
|
|
||||||
"error_log": error_log,
|
|
||||||
"kind": "forward",
|
"kind": "forward",
|
||||||
"expires_at": expires_at,
|
"expires_at": expires_at,
|
||||||
"input_url": input_url,
|
"input_url": input_url,
|
||||||
"output_url": output_url,
|
"output_url": output_url,
|
||||||
"low_latency": low_latency,
|
"low_latency": low_latency,
|
||||||
"profile": profile,
|
"profile": profile,
|
||||||
"command": command,
|
|
||||||
"restart_count": 0,
|
|
||||||
}
|
}
|
||||||
self.processes[stream_id] = record
|
|
||||||
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()
|
self.write_status()
|
||||||
return {"action": "start", "status": "ok", "stream_id": stream_id, "already_running": False}
|
return {"action": "start", "status": "ok", "stream_id": stream_id, "already_running": False}
|
||||||
|
|
||||||
def spawn(self, command, stderr=subprocess.DEVNULL):
|
def spawn(self, command):
|
||||||
return subprocess.Popen(
|
return subprocess.Popen(
|
||||||
command,
|
command,
|
||||||
stdin=subprocess.DEVNULL,
|
stdin=subprocess.DEVNULL,
|
||||||
stdout=subprocess.DEVNULL,
|
stdout=subprocess.DEVNULL,
|
||||||
stderr=stderr,
|
stderr=subprocess.DEVNULL,
|
||||||
start_new_session=True,
|
start_new_session=True,
|
||||||
)
|
)
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def read_error_log(record):
|
|
||||||
error_log = record.get("error_log")
|
|
||||||
if error_log is None:
|
|
||||||
return ""
|
|
||||||
try:
|
|
||||||
error_log.flush()
|
|
||||||
error_log.seek(0)
|
|
||||||
return sanitize_process_error(error_log.read().decode("utf-8", errors="replace"))
|
|
||||||
except (OSError, ValueError):
|
|
||||||
return ""
|
|
||||||
|
|
||||||
@staticmethod
|
|
||||||
def close_error_log(record):
|
|
||||||
error_log = record.pop("error_log", None)
|
|
||||||
if error_log is not None:
|
|
||||||
try:
|
|
||||||
error_log.close()
|
|
||||||
except OSError:
|
|
||||||
pass
|
|
||||||
|
|
||||||
def remember_failure(self, stream_id, exit_code, error):
|
|
||||||
self.last_failure = {
|
|
||||||
"stream_id": stream_id,
|
|
||||||
"exit_code": exit_code,
|
|
||||||
"error": error,
|
|
||||||
"at": int(time.time()),
|
|
||||||
}
|
|
||||||
print(json.dumps({"event": "camera_stream_process_failed", **self.last_failure}, separators=(",", ":")), flush=True)
|
|
||||||
|
|
||||||
def preview_start(self, payload):
|
def preview_start(self, payload):
|
||||||
stream_id = validate_stream_id(payload.get("stream_id"))
|
stream_id = validate_stream_id(payload.get("stream_id"))
|
||||||
expires_at = time.time() + PREVIEW_TTL_SEC
|
expires_at = time.time() + PREVIEW_TTL_SEC
|
||||||
|
|
@ -405,8 +333,6 @@ class StreamManager:
|
||||||
except subprocess.TimeoutExpired:
|
except subprocess.TimeoutExpired:
|
||||||
os.killpg(process.pid, signal.SIGKILL)
|
os.killpg(process.pid, signal.SIGKILL)
|
||||||
process.wait(timeout=2)
|
process.wait(timeout=2)
|
||||||
if record is not None:
|
|
||||||
self.close_error_log(record)
|
|
||||||
self.write_status()
|
self.write_status()
|
||||||
return {"action": "stop", "status": "ok", "stream_id": stream_id}
|
return {"action": "stop", "status": "ok", "stream_id": stream_id}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -92,7 +92,6 @@ class IpStreamTest(unittest.TestCase):
|
||||||
self.assertEqual(command[command.index("-c:a") + 1], "libopus")
|
self.assertEqual(command[command.index("-c:a") + 1], "libopus")
|
||||||
self.assertEqual(command[command.index("-application") + 1], "lowdelay")
|
self.assertEqual(command[command.index("-application") + 1], "lowdelay")
|
||||||
self.assertNotIn(payload["output_url"], json.dumps(manager.status()))
|
self.assertNotIn(payload["output_url"], json.dumps(manager.status()))
|
||||||
manager.close_error_log(manager.processes["cdn-camera-a1b2"])
|
|
||||||
|
|
||||||
def test_forward_low_latency_profile_transcodes_without_b_frames(self):
|
def test_forward_low_latency_profile_transcodes_without_b_frames(self):
|
||||||
manager = stream.StreamManager("g-box-test", "it-screen/dev")
|
manager = stream.StreamManager("g-box-test", "it-screen/dev")
|
||||||
|
|
@ -116,40 +115,6 @@ class IpStreamTest(unittest.TestCase):
|
||||||
self.assertEqual(command[command.index("-profile:v") + 1], "baseline")
|
self.assertEqual(command[command.index("-profile:v") + 1], "baseline")
|
||||||
self.assertEqual(command[command.index("-g") + 1], "25")
|
self.assertEqual(command[command.index("-g") + 1], "25")
|
||||||
self.assertEqual(command[command.index("-b:v") + 1], "600k")
|
self.assertEqual(command[command.index("-b:v") + 1], "600k")
|
||||||
manager.close_error_log(manager.processes["cdn-camera-a1b2"])
|
|
||||||
|
|
||||||
def test_forward_rejects_an_ffmpeg_process_that_exits_during_startup(self):
|
|
||||||
manager = stream.StreamManager("g-box-test", "it-screen/dev")
|
|
||||||
process = MagicMock(returncode=1)
|
|
||||||
process.poll.return_value = 1
|
|
||||||
manager.spawn = MagicMock(return_value=process)
|
|
||||||
manager.write_status = MagicMock()
|
|
||||||
|
|
||||||
def write_error(command, stderr=stream.subprocess.DEVNULL):
|
|
||||||
stderr.write(b"Failed to open rtsp://camera-user:camera-password@camera.local/stream2\n")
|
|
||||||
stderr.flush()
|
|
||||||
return process
|
|
||||||
|
|
||||||
manager.spawn.side_effect = write_error
|
|
||||||
with self.assertRaisesRegex(RuntimeError, "Camera stream process exited during startup") as error:
|
|
||||||
manager.start({
|
|
||||||
"stream_id": "cdn-camera-a1b2",
|
|
||||||
"input_url": "rtsp://camera-user:camera-password@camera.local/stream2",
|
|
||||||
"output_url": "srt://cdn.dev.iomatex.com:8890?streamid=publish:edge/device/camera:user:secret",
|
|
||||||
"ttl_sec": 600,
|
|
||||||
})
|
|
||||||
|
|
||||||
self.assertNotIn("camera-password", str(error.exception))
|
|
||||||
self.assertNotIn("user:secret", str(error.exception))
|
|
||||||
self.assertEqual(manager.processes, {})
|
|
||||||
|
|
||||||
def test_console_returns_the_sanitized_stream_service_error(self):
|
|
||||||
console = MODULE_PATH.parents[1] / "stage_ui" / "console_core" / "backend" / "app.py"
|
|
||||||
source = console.read_text(encoding="utf-8")
|
|
||||||
self.assertIn('error = str(result.get("error") or "").strip()', source)
|
|
||||||
self.assertIn('raise RuntimeError(error or "Unable to start camera media operation")', source)
|
|
||||||
self.assertIn('if parsed.path == "/api/camera-stream/stop":', source)
|
|
||||||
self.assertIn('publish_camera_preview({"action": "stop", "stream_id": stream_id})', source)
|
|
||||||
|
|
||||||
def test_supervisor_reaps_expired_and_dead_processes_without_status_request(self):
|
def test_supervisor_reaps_expired_and_dead_processes_without_status_request(self):
|
||||||
manager = stream.StreamManager("g-box-test", "it-screen/dev")
|
manager = stream.StreamManager("g-box-test", "it-screen/dev")
|
||||||
|
|
@ -160,7 +125,7 @@ class IpStreamTest(unittest.TestCase):
|
||||||
dead.poll.return_value = 7
|
dead.poll.return_value = 7
|
||||||
manager.processes = {
|
manager.processes = {
|
||||||
"expired": {"process": expired, "kind": "forward", "expires_at": 1},
|
"expired": {"process": expired, "kind": "forward", "expires_at": 1},
|
||||||
"dead": {"process": dead, "kind": "preview", "expires_at": 0},
|
"dead": {"process": dead, "kind": "forward", "expires_at": 0},
|
||||||
}
|
}
|
||||||
manager.write_status = MagicMock()
|
manager.write_status = MagicMock()
|
||||||
|
|
||||||
|
|
@ -169,39 +134,8 @@ class IpStreamTest(unittest.TestCase):
|
||||||
|
|
||||||
self.assertEqual(manager.processes, {})
|
self.assertEqual(manager.processes, {})
|
||||||
self.assertEqual({item["stream_id"] for item in stopped}, {"expired", "dead"})
|
self.assertEqual({item["stream_id"] for item in stopped}, {"expired", "dead"})
|
||||||
self.assertEqual(manager.last_failure["stream_id"], "dead")
|
|
||||||
self.assertEqual(manager.last_failure["exit_code"], 7)
|
|
||||||
killpg.assert_called_once_with(1001, stream.signal.SIGTERM)
|
killpg.assert_called_once_with(1001, stream.signal.SIGTERM)
|
||||||
|
|
||||||
def test_supervisor_restarts_a_failed_forward_within_its_ttl(self):
|
|
||||||
manager = stream.StreamManager("g-box-test", "it-screen/dev")
|
|
||||||
dead = MagicMock(pid=1002)
|
|
||||||
dead.poll.return_value = 1
|
|
||||||
replacement = MagicMock(pid=1003)
|
|
||||||
replacement.poll.return_value = None
|
|
||||||
error_log = tempfile.TemporaryFile(mode="w+b")
|
|
||||||
error_log.write(b"srt://cdn.example:8891?streamid=secret Input/output error")
|
|
||||||
manager.processes = {
|
|
||||||
"camera": {
|
|
||||||
"process": dead,
|
|
||||||
"error_log": error_log,
|
|
||||||
"kind": "forward",
|
|
||||||
"expires_at": stream.time.time() + 60,
|
|
||||||
"restart_count": 0,
|
|
||||||
"command": [stream.FFMPEG_BINARY, "-i", "rtsp://camera/stream2"],
|
|
||||||
},
|
|
||||||
}
|
|
||||||
manager.spawn = MagicMock(return_value=replacement)
|
|
||||||
manager.write_status = MagicMock()
|
|
||||||
|
|
||||||
stopped = manager.reap()
|
|
||||||
|
|
||||||
self.assertTrue(stopped[0]["restarted"])
|
|
||||||
self.assertEqual(manager.processes["camera"]["restart_count"], 1)
|
|
||||||
self.assertIs(manager.processes["camera"]["process"], replacement)
|
|
||||||
self.assertNotIn("streamid=secret", manager.last_failure["error"])
|
|
||||||
manager.close_error_log(manager.processes["camera"])
|
|
||||||
|
|
||||||
def test_run_starts_periodic_supervisor(self):
|
def test_run_starts_periodic_supervisor(self):
|
||||||
source = MODULE_PATH.read_text(encoding="utf-8")
|
source = MODULE_PATH.read_text(encoding="utf-8")
|
||||||
self.assertIn('target=self.supervise, name="ip-stream-supervisor"', source)
|
self.assertIn('target=self.supervise, name="ip-stream-supervisor"', source)
|
||||||
|
|
|
||||||
|
|
@ -1,3 +1,3 @@
|
||||||
{
|
{
|
||||||
"version": "1.0.10"
|
"version": "1.0.8"
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -1,7 +0,0 @@
|
||||||
[Seat:*]
|
|
||||||
pam-service=evax10-desktop
|
|
||||||
autologin-user=
|
|
||||||
autologin-guest=false
|
|
||||||
allow-guest=false
|
|
||||||
greeter-allow-guest=false
|
|
||||||
greeter-show-manual-login=true
|
|
||||||
|
|
@ -1,6 +0,0 @@
|
||||||
# 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
|
|
||||||
|
|
@ -1,9 +0,0 @@
|
||||||
[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
|
|
||||||
|
|
@ -1,27 +0,0 @@
|
||||||
#!/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
|
|
||||||
|
|
@ -1,24 +0,0 @@
|
||||||
#!/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
|
|
||||||
|
|
@ -1,30 +0,0 @@
|
||||||
#!/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 @@
|
||||||
5e14d2cabd2821620e03467bc5d8bc98d87895d3f6f22c3f82a9cf414c6d13d0 itscreen
|
7111ffff8d81764c6e4385f550faea26f012c9bd178754edba3f6211ad63c765 itscreen
|
||||||
|
|
|
||||||
|
|
@ -1 +1 @@
|
||||||
5.1.55
|
5.1.20
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,14 @@
|
||||||
{
|
{
|
||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
"client_version": "5.1.55",
|
"client_version": "5.1.20",
|
||||||
"stage_version": "1.0.40",
|
"stage_version": "1.0.26",
|
||||||
"platform": "linux",
|
"platform": "linux",
|
||||||
"architecture": "arm64",
|
"architecture": "arm64",
|
||||||
"source_repository": "https://git.iomatex.com/Development/It-screenClient.git",
|
"source_repository": "https://git.it-screen.com/Development/It-screenClient.git",
|
||||||
"source_branch": "iomatex_dev",
|
"source_branch": "iomatex_dev",
|
||||||
"source_commit": "c4739d5dd87ba43c94578af0c6745b0086829175",
|
"source_commit": "1f97f4b6d2260449d78762ccc35d2f44f7878a68",
|
||||||
"binary": "itscreen",
|
"binary": "itscreen",
|
||||||
"sha256": "5e14d2cabd2821620e03467bc5d8bc98d87895d3f6f22c3f82a9cf414c6d13d0",
|
"sha256": "7111ffff8d81764c6e4385f550faea26f012c9bd178754edba3f6211ad63c765",
|
||||||
"assembly_method": "Clean isolated release build from git archive using iomatex-debian-dev:local; --version and linked libraries verified on Debian 11 ARM64",
|
"assembly_method": "Native qmake/make release build on Debian 11 ARM64, Qt 5.15.2",
|
||||||
"native_version_code": 5010055,
|
"native_version_code": 5010020
|
||||||
"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,11 +442,6 @@ install_qt_packages() {
|
||||||
libqt5texttospeech5 \
|
libqt5texttospeech5 \
|
||||||
libqt5serialbus5
|
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 \
|
install_packages_best_effort "Install Qt extras" 1800 \
|
||||||
lxterminal openbox wmctrl xdotool \
|
lxterminal openbox wmctrl xdotool \
|
||||||
libqt5serialbus5-bin \
|
libqt5serialbus5-bin \
|
||||||
|
|
@ -518,16 +513,17 @@ cleanup_legacy_x11_hacks() {
|
||||||
install_itscreen_binary() (
|
install_itscreen_binary() (
|
||||||
set -e
|
set -e
|
||||||
step "Install itscreen binary"
|
step "Install itscreen binary"
|
||||||
# One Download owner for initial provisioning and subsequent automatic updates.
|
local src
|
||||||
# A failed download aborts the stage; never silently install the bundled legacy ELF.
|
src=$(mktemp /userdata/.iomatex-client.XXXXXX)
|
||||||
python3 "$SCRIPT_DIR/updater/client_updater.py" --bootstrap
|
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"
|
||||||
)
|
)
|
||||||
|
|
||||||
install_sudoers() {
|
install_sudoers() {
|
||||||
step "Grant power actions (reboot/shutdown) to itscreen (sudoers)"
|
step "Grant power actions (reboot/shutdown) to itscreen (sudoers)"
|
||||||
write_file "$SUDOERS_FILE" 0440 root root <<'EOF'
|
write_file "$SUDOERS_FILE" 0440 root root <<'EOF'
|
||||||
Defaults:itscreen !requiretty
|
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/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/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
|
itscreen ALL=(root) NOPASSWD: /sbin/shutdown, /usr/sbin/shutdown, /bin/systemctl halt, /usr/bin/systemctl halt
|
||||||
|
|
@ -1550,18 +1546,6 @@ main() {
|
||||||
install_itscreen_binary
|
install_itscreen_binary
|
||||||
install_itscreen_config
|
install_itscreen_config
|
||||||
install_sudoers
|
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_wrapper
|
||||||
install_audio_route_state
|
install_audio_route_state
|
||||||
install_pulseaudio_assets
|
install_pulseaudio_assets
|
||||||
|
|
@ -1569,7 +1553,6 @@ POWER_WAKE
|
||||||
install_x11_session_scripts
|
install_x11_session_scripts
|
||||||
install_recovery_assets
|
install_recovery_assets
|
||||||
install_systemd_unit
|
install_systemd_unit
|
||||||
bash "$SCRIPT_DIR/updater/install.sh"
|
|
||||||
enable_managed_services
|
enable_managed_services
|
||||||
post_install_self_test
|
post_install_self_test
|
||||||
flush_filesystems
|
flush_filesystems
|
||||||
|
|
|
||||||
|
|
@ -1,23 +0,0 @@
|
||||||
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)
|
|
||||||