Release Console 3.1.1 with Git-backed per-stage updates in Health

This commit is contained in:
Andrei Smaliak 2026-09-15 11:43:47 +02:00
parent e01751ed27
commit 9238e8b442
40 changed files with 1088 additions and 17 deletions

View File

@ -23,6 +23,17 @@ done
[[ "$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_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.
if [[ ${EUID:-$(id -u)} -eq 0 ]]; then
if [[ ! ${IOMATEX_INSTALL_LOCK_FD:-} =~ ^[0-9]+$ ]] ||
[[ $(readlink "/proc/$$/fd/${IOMATEX_INSTALL_LOCK_FD:-999}" 2>/dev/null) != /run/lock/iomatex-installer.lock ]]; then
mkdir -p /run/lock
exec 9>/run/lock/iomatex-installer.lock
flock -n 9 || { echo 'ERROR: another Iomatex installation is running.' >&2; exit 1; }
export IOMATEX_INSTALL_LOCK_FD=9
fi
fi
command -v python3 >/dev/null || { echo 'Supported vendor image requires Python 3. No bootstrap packages will be downloaded externally.' >&2; exit 1; } command -v python3 >/dev/null || { echo 'Supported vendor image requires Python 3. No bootstrap packages will be downloaded externally.' >&2; exit 1; }
export IOMATEX_GIT_USERNAME=${IOMATEX_GIT_USERNAME:-} export IOMATEX_GIT_USERNAME=${IOMATEX_GIT_USERNAME:-}
export IOMATEX_GIT_PASSWORD=${IOMATEX_GIT_PASSWORD:-} export IOMATEX_GIT_PASSWORD=${IOMATEX_GIT_PASSWORD:-}

View File

@ -1154,6 +1154,7 @@ run_stage() {
return 1 return 1
fi fi
python3 "$PROJECT_DIR/offline/stage_versions.py" record "$PROJECT_DIR" "$stage" || return 1
set_stage_status "$stage" "success" set_stage_status "$stage" "success"
set_state_value "LAST_RESULT" "success" set_state_value "LAST_RESULT" "success"
SUCCESS_STAGES+=("$stage") SUCCESS_STAGES+=("$stage")

115
offline/STAGE_UPDATES.md Normal file
View File

@ -0,0 +1,115 @@
# Stage releases and Health updates
Health uses the existing service card renderer, action buttons and warning dialog.
Every managed service maps to one of nine stages. Mosquitto and MQTT Bridge share
`stage_mqtt`; Display and IT-Screen share `stage_itscreen`. Environment, Console,
Wi-Fi/AP and Avahi also have cards. Updates install the selected stage only.
Stage revisions are distinct from upstream package/client versions (client 122
and Zigbee2MQTT 2.9.2 do not become different software because a stage script changes).
## Publishing
Each stage owns `version.json`; `stage-releases.json` is their small API catalog.
Initial stage release numbers are `1.0.0`. Whenever a stage's scripts, assets or
pinned dependencies change, bump that stage before publishing. A shared installer
change that changes installed behavior requires bumping all affected stages.
```bash
python3 offline/bump_stage_version.py stage_z2m 1.0.1
python3 -m unittest discover -s offline -p test_stage_versions.py
```
Commit the stage manifest and root catalog together with the implementation.
Keep the existing Console `bump_ui_version.sh` version in sync with actual Console
code changes; that version is separate from the stage release number. Publish to
the Edge's configured branch only when ready. An unpublished local change is not
available through Health.
Existing devices need the new `stage_ui` once through the standalone bootstrap:
```bash
sudo bash ~/install_iomatex_edge.sh --only stage_ui
```
The bootstrap must be current. It fetches a small snapshot from our Git, as before.
An older local bootstrap can be downloaded via the existing documented API command.
No full package mirror or `.git` is kept on Edge.
## API and runtime
- Authenticated `GET /api/health/services` adds `release` to each managed card and
`updates` with check time, busy state and the last job. It only reads local
state; a coalesced background thread checks our Git API at most every 15 minutes
while Health is used. Failed/explicit checks have a 30-second cooldown.
- Authenticated JSON `POST /api/stages/check` requests a background check.
- Authenticated JSON `POST /api/stages/install` accepts only an allowlisted
`stage`, the `commit` displayed in Health, and boolean `confirmed: true`.
Confirmation older than the release-check TTL is rejected. No arbitrary
URLs, commands or installer paths are accepted from the browser.
- Git downloads use the existing HTTPS-only, no-redirect delivery owner and the
stored root-only Git credential file. The worker pins the exact commit the
user confirmed, even if the publishing branch advances in the meantime.
- A transient `iomatex-stage-update-*` system unit runs independently of Console.
Closing the page or restarting/updating Console does not kill the installer.
A global inherited flock excludes bootstrap, orchestrator, stage and UI jobs.
A competing update returns a conflict. There is no automatic installation retry.
- The selected stage runs through `local_installer.sh --only <stage>`, including
its post-install validation. Successful CLI/direct stage installs write
`/var/lib/iomatex/stages/<stage>.json`. During orchestrated installs only the
orchestrator writes this receipt after validation. A unique job ID prevents
an old successful receipt from hiding a failed repeat installation.
- The last job is in `/var/lib/iomatex/stages/job.json`; its output is in
`/var/lib/iomatex/stages/install.log`. A new job replaces the previous log.
Interrupted jobs are reconciled against systemd and their receipt after reboot.
`stage_env` retains its mandatory reboot; the confirmation explicitly says so.
- Previously installed stages without receipts show an unknown installed version.
The current snapshot is never treated as proof that its contents were installed.
Applying the published stage establishes its first receipt. An unavailable Git
check never claims that an installed version is latest. Known newer installed
versions cannot be downgraded through this API.
## Validation
`offline/test_stage_versions.py`, `backend/test_stage_updates_api.py` and
`backend/test_stage_updates_ui.js` cover release validation, legacy/missing/current
states, offline checks, background request coalescing, exact-commit installation,
failed jobs, locking, authentication, JSON/confirmation and cancel behavior.
Existing Health, provider and Git delivery tests remain part of regression checks.
Browser regression: `stage_ui/console_core/backend/test_stage_updates_browser.cjs`
uses Playwright supplied by the development environment, with mocked Edge API
responses (no real device actions). Verified Russian Health at widths 360, 768,
1024 and 1440, no horizontal overflow, a body-mounted warning dialog, Escape
cancellation and one confirmed stage-only request. The existing mobile brand
layout now stacks its image above the title to keep the page within the viewport.
Validated locally: 68 Console backend tests, 12 stage release/job tests,
8 Git delivery tests, UI interaction tests and syntax of 33 shell scripts.
The Git-only source suite passes; its root-only missing-snapshot test is skipped
when run as a normal development user. No installation on a physical Edge has
been performed for this change, and the release is not published yet.
## Local Edge deployment: Console 3.1.1, 2026-09-15
Console and its stage manifest were raised to `3.1.1`. Installed only `stage_ui`
on `192.168.0.100` (`g-box-8e6af561`) using the existing pinned Git package
catalog and a temporary local source snapshot. The receipt explicitly records
`local_build=console-3.1.1-20260915`, with no claimed published commit. Temporary
snapshot/archive files were removed; future Git updates target the original
`/userdata/Iomatex_OS`. The release catalog is still unpublished.
The installer exited successfully; Console, IT-Screen and Zigbee2MQTT remained
active. Authenticated Health returned 11 service cards and Console 3.1.1.
A live browser verified the version dialog, Escape, 360/1440 layouts and absence
of JavaScript errors. A previous Console backup is available on Edge and in the
private workstation backup directory. Publishing is still required before the
Git catalog can offer updates from Health.
## Publication: Console 3.1.1 and stage catalog, 2026-09-15
The first catalog release publishes all nine stage manifests and the complete
shared update worker in `ci-cd`. Console stage is 3.1.1; the other initial stage
revisions are 1.0.0 (separate from upstream application versions). Includes the
12px service action spacing and explicit missing-catalog/credential errors.
Publication validation: 14 stage release tests, 8 Git delivery tests, 68 Console
backend tests and the shared UI interaction test passed.

View File

@ -0,0 +1,30 @@
#!/usr/bin/env python3
"""Maintainer command: bump one stage and regenerate the API catalog from stage manifests."""
import argparse
import json
from pathlib import Path
import re
from stage_versions import STAGES, validate_manifest
def bump(root, stage, version):
if stage not in STAGES or not re.fullmatch(r'\d+\.\d+\.\d+', version):
raise ValueError('Expected an existing stage and MAJOR.MINOR.PATCH')
path = root / stage / 'version.json'
old = json.loads(path.read_text())
if tuple(map(int, version.split('.'))) <= tuple(map(int, old['version'].split('.'))):
raise ValueError('Version must increase')
releases = {key: json.loads((root / key / 'version.json').read_text()) for key in STAGES}
releases[stage] = {**old, 'version':version}
catalog = validate_manifest({'schema':1, 'stages':releases})
path.write_text(json.dumps(releases[stage], indent=2) + '\n')
(root / 'stage-releases.json').write_text(json.dumps(catalog, indent=2) + '\n')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('stage', choices=STAGES)
parser.add_argument('version')
args = parser.parse_args()
bump(Path(__file__).resolve().parents[1], args.stage, args.version)

View File

@ -51,11 +51,11 @@ def auth_from_env():
return {'username': user, 'password': password} return {'username': user, 'password': password}
return json.loads(AUTH.read_text()) return json.loads(AUTH.read_text())
def open_git(repo, endpoint, auth): def open_git(repo, endpoint, auth, timeout=120):
url = 'https://' + 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}) req = urllib.request.Request(url, headers={'Authorization': 'Basic ' + token})
return urllib.request.build_opener(NoRedirect).open(req, timeout=120) return urllib.request.build_opener(NoRedirect).open(req, timeout=timeout)
def raw_endpoint(path, commit): def raw_endpoint(path, commit):
if not re.fullmatch('[a-f0-9]{40}', commit): if not re.fullmatch('[a-f0-9]{40}', commit):
@ -111,7 +111,7 @@ def materialize_file(repo, commit, auth, entry, existing, staged):
p.write_bytes(data) p.write_bytes(data)
p.chmod(int(entry['mode'][-3:], 8)) p.chmod(int(entry['mode'][-3:], 8))
def bootstrap(url, branch, checkout): def bootstrap(url, branch, checkout, commit=None):
platform_check() platform_check()
repo = repo_name(url) repo = repo_name(url)
requested = Path(checkout) requested = Path(checkout)
@ -124,8 +124,11 @@ def bootstrap(url, branch, checkout):
if repo_name(origin) != repo: if repo_name(origin) != repo:
raise ValueError('Existing checkout origin mismatch') raise ValueError('Existing checkout origin mismatch')
auth = auth_from_env() auth = auth_from_env()
with open_git(repo, 'branches/' + urllib.parse.quote(branch, safe=''), auth) as r: if commit is None:
commit = json.load(r)['commit']['id'] with open_git(repo, 'branches/' + urllib.parse.quote(branch, safe=''), auth) as r:
commit = json.load(r)['commit']['id']
if not re.fullmatch('[a-f0-9]{40}', commit):
raise ValueError('Invalid pinned commit')
with open_git(repo, 'git/trees/' + commit + '?recursive=true', auth) as r: with open_git(repo, 'git/trees/' + commit + '?recursive=true', auth) as r:
tree = json.load(r) tree = json.load(r)
if tree.get('truncated'): if tree.get('truncated'):
@ -235,6 +238,9 @@ def activate(root):
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')
if (root / 'offline/stage_versions.py').exists():
shutil.copy2(root / 'offline/stage_versions.py', owner / 'stage_versions.py')
subprocess.run([sys.executable, str(owner / 'stage_versions.py'), 'configure', str(root)], check=True)
method = Path('/usr/lib/apt/methods/iomatex') method = Path('/usr/lib/apt/methods/iomatex')
method.write_text('#!/bin/sh\nexec /usr/bin/python3 /usr/local/lib/iomatex/git_delivery.py apt-method\n') method.write_text('#!/bin/sh\nexec /usr/bin/python3 /usr/local/lib/iomatex/git_delivery.py apt-method\n')
method.chmod(0o755) method.chmod(0o755)

11
offline/install-lock.sh Normal file
View File

@ -0,0 +1,11 @@
#!/usr/bin/env bash
# Inherit the same open lock across bootstrap, orchestrator and nested stages.
if [[ ${EUID:-$(id -u)} -eq 0 ]]; then
if [[ ! ${IOMATEX_INSTALL_LOCK_FD:-} =~ ^[0-9]+$ ]] ||
[[ $(readlink "/proc/$$/fd/${IOMATEX_INSTALL_LOCK_FD:-999}" 2>/dev/null) != /run/lock/iomatex-installer.lock ]]; then
mkdir -p /run/lock
exec 9>/run/lock/iomatex-installer.lock
flock -n 9 || { echo 'ERROR: another Iomatex installation is running.' >&2; exit 1; }
export IOMATEX_INSTALL_LOCK_FD=9
fi
fi

View File

@ -1,6 +1,7 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# One owner for package sources across all stages. Payloads are never cached in the snapshot. # One owner for package sources across all stages. Payloads are never cached in the snapshot.
IOMATEX_PROJECT_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd) IOMATEX_PROJECT_ROOT=$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)
source "$IOMATEX_PROJECT_ROOT/offline/install-lock.sh"
if [[ ${EUID:-$(id -u)} -eq 0 ]]; then if [[ ${EUID:-$(id -u)} -eq 0 ]]; then
[[ -f "$IOMATEX_PROJECT_ROOT/.iomatex-source.json" ]] || { [[ -f "$IOMATEX_PROJECT_ROOT/.iomatex-source.json" ]] || {
echo 'ERROR: initialize the lightweight Edge snapshot with install_iomatex_edge.sh first.' >&2 echo 'ERROR: initialize the lightweight Edge snapshot with install_iomatex_edge.sh first.' >&2
@ -8,3 +9,10 @@ if [[ ${EUID:-$(id -u)} -eq 0 ]]; then
} }
python3 "$IOMATEX_PROJECT_ROOT/offline/git_delivery.py" activate "$IOMATEX_PROJECT_ROOT" || exit 1 python3 "$IOMATEX_PROJECT_ROOT/offline/git_delivery.py" activate "$IOMATEX_PROJECT_ROOT" || exit 1
fi fi
# Direct stage invocation also records success; the orchestrator records only after validation.
iomatex_record_stage() {
if [[ -z ${IOMATEX_INSTALLER_SELECTED_STAGES:-} ]]; then
python3 "$IOMATEX_PROJECT_ROOT/offline/stage_versions.py" record "$IOMATEX_PROJECT_ROOT" "$1"
fi
}

253
offline/stage_versions.py Normal file
View File

@ -0,0 +1,253 @@
#!/usr/bin/env python3
"""Shared stage releases, installation receipts and detached Console update jobs.
Health reads local state only; Git checks run in a background thread.
"""
import fcntl
import json
import os
from pathlib import Path
import re
import subprocess
import sys
import threading
import time
import urllib.parse
import urllib.error
import uuid
import git_delivery as delivery
STATE = Path('/var/lib/iomatex/stages')
CONFIG = Path('/etc/iomatex/stage-updates.json')
LOCK = Path('/run/lock/iomatex-installer.lock')
OWNER = Path('/usr/local/lib/iomatex/stage_versions.py')
STAGES = {
'stage_env': ('Edge environment', ['environment']),
'stage_wifi': ('Wi-Fi / Access Point', ['access_point']),
'stage_mqtt': ('MQTT', ['mosquitto', 'mqtt_bridge']),
'stage_z2m': ('Zigbee2MQTT', ['zigbee2mqtt']),
'stage_ui': ('Edge Console', ['console']),
'stage_avahi': ('Avahi / mDNS', ['avahi']),
'stage_cockpit': ('Cockpit', ['cockpit']),
'stage_itscreen': ('IT-Screen / Display', ['itscreen', 'display']),
'stage_reverse_tunnels': ('Reverse Tunnels', ['reverse_tunnel']),
}
CHECK_TTL = 900
_guard = threading.Lock()
_job_guard = threading.Lock()
_checking = False
def read_json(path, default=None):
try:
return json.loads(path.read_text())
except (OSError, ValueError):
return {} if default is None else default
def validate_manifest(value):
if not isinstance(value, dict) or value.get('schema') != 1 or set(value.get('stages', {})) != set(STAGES):
raise ValueError('Invalid stage release catalog')
for stage, release in value['stages'].items():
if not isinstance(release, dict) or not re.fullmatch(r'\d+\.\d+\.\d+', str(release.get('version', ''))):
raise ValueError('Invalid stage version: ' + stage)
return value
def record(root, stage):
if stage not in STAGES:
raise ValueError('Unknown stage')
root = Path(root)
manifest = validate_manifest(read_json(root / 'stage-releases.json'))
release = read_json(root / stage / 'version.json')
if release != manifest['stages'][stage]:
raise ValueError('Stage version differs from release catalog')
source = read_json(root / '.iomatex-source.json')
delivery.write_json(STATE / (stage + '.json'), {
**release, 'commit': '' if source.get('local_build') else source.get('commit', ''),
'local_build': source.get('local_build', ''), 'installed_at': int(time.time()),
'job_id': os.environ.get('IOMATEX_INSTALL_JOB_ID', ''),
})
def configure(root):
root = Path(root).resolve()
source = read_json(root / '.iomatex-source.json')
delivery.repo_name('https://' + delivery.HOST + '/' + source['repo'] + '.git')
next_config = {'checkout': str(root), 'repo': source['repo'], 'branch': source['branch']}
if read_json(CONFIG) != next_config:
delivery.write_json(STATE / 'available.json', {})
delivery.write_json(CONFIG, next_config)
def refresh():
global _checking
previous = read_json(STATE / 'available.json')
phase = 'branch'
try:
cfg = read_json(CONFIG)
repo = delivery.repo_name('https://' + delivery.HOST + '/' + cfg['repo'] + '.git')
auth = delivery.auth_from_env()
with delivery.open_git(repo, 'branches/' + urllib.parse.quote(cfg['branch'], safe=''), auth, timeout=15) as response:
commit = json.load(response)['commit']['id']
phase = 'catalog'
with delivery.open_git(repo, delivery.raw_endpoint('stage-releases.json', commit), auth, timeout=15) as response:
catalog = validate_manifest(json.load(response))
delivery.write_json(STATE / 'available.json', {
**catalog, 'commit': commit, 'checked_at': int(time.time()),
'attempt_at': int(time.time()), 'error': '',
})
except Exception as exc:
error = 'Cannot check releases on our Git'
if isinstance(exc, urllib.error.HTTPError):
if exc.code == 404 and phase == 'catalog':
error = 'The stage release catalog has not been published to Git yet.'
elif exc.code in (401, 403):
error = 'Git access was denied. Check the Edge Git credentials.'
# Do not expose credentials, HTTP bodies or private paths in the API.
delivery.write_json(STATE / 'available.json', {
**previous, 'attempt_at': int(time.time()), 'error': error,
})
finally:
with _guard:
_checking = False
def request_check(force=False):
global _checking
with _guard:
cached = read_json(STATE / 'available.json')
age = time.time() - cached.get('attempt_at', 0)
if _checking or age < (30 if force or cached.get('error') else CHECK_TTL):
return
_checking = True
threading.Thread(target=refresh, daemon=True, name='stage-release-check').start()
def installer_busy():
try:
LOCK.parent.mkdir(parents=True, exist_ok=True)
with LOCK.open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
return False
except BlockingIOError:
return True
def job_status():
job = read_json(STATE / 'job.json')
if job.get('state') in ('queued', 'running') and time.time() - job.get('started_at', 0) > 15:
# Reconcile interrupted workers (reboot, OOM, power loss) without retrying.
result = subprocess.run(['systemctl', 'is-active', job['unit']], capture_output=True, text=True, timeout=3)
if result.stdout.strip() not in ('active', 'activating', 'reloading'):
receipt = read_json(STATE / (job['stage'] + '.json'))
ok = receipt.get('commit') == job.get('commit') and receipt.get('job_id') == job['unit']
job = {**job, 'state': 'success' if ok else 'interrupted', 'finished_at': int(time.time())}
delivery.write_json(STATE / 'job.json', job)
return job
def snapshot(cards):
request_check()
available = read_json(STATE / 'available.json')
job = job_status()
busy = job.get('state') in ('queued', 'running') or installer_busy()
fresh = bool(available.get('commit') and not available.get('error') and
time.time() - available.get('checked_at', 0) <= CHECK_TTL)
versions = {}
for stage, (title, ids) in STAGES.items():
receipt = read_json(STATE / (stage + '.json'))
installed = any(c.get('installed') for c in cards if c.get('id') in ids)
# Non-provider stages have a receipt as their installation evidence.
if not any(c.get('id') in ids for c in cards):
installed = bool(receipt)
latest = available.get('stages', {}).get(stage, {}).get('version')
current = receipt.get('version') if installed else None
status = 'not_installed' if not installed else ('not_checked' if not fresh else 'unknown')
if fresh and installed and current:
current_tuple = tuple(map(int, current.split('.')))
latest_tuple = tuple(map(int, latest.split('.')))
status = 'latest' if current_tuple == latest_tuple else ('update_available' if current_tuple < latest_tuple else 'ahead')
if receipt.get('local_build') and current_tuple <= latest_tuple:
status = 'local_build'
versions[stage] = {
'stage': stage, 'title': title, 'installed': installed,
'current': current, 'latest': latest, 'status': status,
'commit': available.get('commit'),
'can_install': bool(fresh and not busy and status in ('not_installed', 'unknown', 'update_available', 'local_build')),
'reboot': stage == 'stage_env', 'services': ids,
}
return {'stages': versions, 'checking': _checking, 'checked_at': available.get('checked_at'),
'error': available.get('error', ''), 'busy': busy, 'job': job}
def start_install(stage, commit):
if stage not in STAGES or not isinstance(commit, str) or not re.fullmatch('[a-f0-9]{40}', commit):
raise ValueError('Invalid stage or release')
with _job_guard:
available = read_json(STATE / 'available.json')
if available.get('error') or commit != available.get('commit') or time.time() - available.get('checked_at', 0) > CHECK_TTL:
raise ValueError('Release check expired; refresh before confirming')
if installer_busy() or job_status().get('state') in ('queued', 'running'):
raise ValueError('An installation is already running')
cfg = read_json(CONFIG)
if not cfg.get('checkout') or not delivery.AUTH.exists():
raise ValueError('Initialize this Edge with install_iomatex_edge.sh first')
receipt = read_json(STATE / (stage + '.json'))
version = available['stages'][stage]['version']
if receipt.get('version') and tuple(map(int, receipt['version'].split('.'))) > tuple(map(int, version.split('.'))):
raise ValueError('Downgrades are not allowed')
unit = 'iomatex-stage-update-' + uuid.uuid4().hex
job = {'stage': stage, 'commit': commit, 'version': version, 'unit': unit,
'state': 'queued', 'started_at': int(time.time())}
delivery.write_json(STATE / 'job.json', job)
try:
(STATE / 'install.log').write_text('')
# Independent system unit survives Console replacement and browser disconnect.
subprocess.run(['systemd-run', '--unit=' + unit, '--collect',
'--property=Type=exec', '--property=TimeoutStartSec=0',
'--property=StandardOutput=append:' + str(STATE / 'install.log'),
'--property=StandardError=inherit',
sys.executable, str(OWNER), 'install', stage, commit],
check=True, capture_output=True, timeout=10)
except Exception:
delivery.write_json(STATE / 'job.json', {**job, 'state': 'failed', 'error': 'Cannot start installer'})
raise RuntimeError('Cannot start installer') from None
return job
def install(stage, commit):
job = read_json(STATE / 'job.json')
if stage not in STAGES or job.get('stage') != stage or job.get('commit') != commit:
raise ValueError('Update job mismatch')
STATE.mkdir(parents=True, exist_ok=True)
try:
LOCK.parent.mkdir(parents=True, exist_ok=True)
with LOCK.open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
cfg = read_json(CONFIG)
delivery.write_json(STATE / 'job.json', {**job, 'state': 'running'})
delivery.bootstrap('https://' + delivery.HOST + '/' + cfg['repo'] + '.git',
cfg['branch'], cfg['checkout'], commit=commit)
root = Path(cfg['checkout'])
release = validate_manifest(read_json(root / 'stage-releases.json'))['stages'][stage]
if release['version'] != job['version']:
raise ValueError('Downloaded release does not match confirmation')
# The orchestrator validates the result and writes the receipt only on success.
env = dict(os.environ, IOMATEX_INSTALL_LOCK_FD=str(lock.fileno()), IOMATEX_INSTALL_JOB_ID=job['unit'])
subprocess.run(['bash', str(root / 'local_installer.sh'), str(root),
'--non-interactive', '--reset-state', '--only', stage],
check=True, env=env, pass_fds=(lock.fileno(),))
receipt = read_json(STATE / (stage + '.json'))
if receipt.get('commit') != commit or receipt.get('version') != job['version'] or receipt.get('job_id') != job['unit']:
raise RuntimeError('Stage did not finish successfully; see installation log')
delivery.write_json(STATE / 'job.json', {**job, 'state': 'success', 'finished_at': int(time.time())})
except Exception as exc:
delivery.write_json(STATE / 'job.json', {**job, 'state': 'failed', 'error': type(exc).__name__,
'finished_at': int(time.time())})
raise
if __name__ == '__main__':
action, *args = sys.argv[1:]
{'record': record, 'configure': configure, 'install': install}[action](*args)

View File

@ -0,0 +1,192 @@
import io
import json
import os
from pathlib import Path
import subprocess
import tempfile
import threading
import time
import unittest
from unittest import mock
import stage_versions as versions
ROOT = Path(__file__).resolve().parents[1]
COMMIT = 'a' * 40
class StageVersionsTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
root = Path(self.tmp.name)
for key, value in [('STATE', root / 'state'), ('CONFIG', root / 'config.json'), ('LOCK', root / 'lock')]:
patch = mock.patch.object(versions, key, value)
patch.start()
self.addCleanup(patch.stop)
versions._checking = False
self.catalog = versions.validate_manifest(json.loads((ROOT / 'stage-releases.json').read_text()))
self.available = {**self.catalog, 'commit': COMMIT, 'checked_at': int(time.time()), 'attempt_at': int(time.time()), 'error': ''}
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')})
def test_every_stage_has_matching_manifest(self):
for stage, release in self.catalog['stages'].items():
self.assertEqual(release, json.loads((ROOT / stage / 'version.json').read_text()))
def snapshot(self, installed=True):
with mock.patch.object(versions, 'request_check'):
return versions.snapshot([{'id':'zigbee2mqtt', 'installed':installed}])['stages']['stage_z2m']
def test_legacy_is_unknown_and_missing_can_install(self):
self.assertEqual('unknown', self.snapshot()['status'])
self.assertTrue(self.snapshot()['can_install'])
self.assertEqual('not_installed', self.snapshot(False)['status'])
self.assertTrue(self.snapshot(False)['can_install'])
def test_record_and_compare_versions_numerically(self):
versions.record(ROOT, 'stage_z2m')
self.assertEqual('latest', self.snapshot()['status'])
self.assertFalse(self.snapshot()['can_install'])
self.available['stages']['stage_z2m']['version'] = '1.10.0'
versions.delivery.write_json(versions.STATE / 'available.json', self.available)
self.assertEqual('update_available', self.snapshot()['status'])
versions.delivery.write_json(versions.STATE / 'stage_z2m.json', {'version':'2.0.0'})
self.assertEqual('ahead', self.snapshot()['status'])
self.assertFalse(self.snapshot()['can_install'])
def test_failure_or_stale_check_never_claims_latest(self):
versions.record(ROOT, 'stage_z2m')
for changes in [{'error':'Cannot check releases on our Git'}, {'checked_at':0}]:
versions.delivery.write_json(versions.STATE / 'available.json', {**self.available, **changes})
result = self.snapshot()
self.assertEqual('not_checked', result['status'])
self.assertFalse(result['can_install'])
def test_install_rejects_path_injection_stale_and_duplicate(self):
with self.assertRaises(ValueError): versions.start_install('../../bin/sh', COMMIT)
with self.assertRaises(ValueError): versions.start_install('stage_z2m', 'b'*40)
versions.delivery.write_json(versions.STATE / 'job.json', {'state':'queued', 'started_at':int(time.time())})
with self.assertRaises(ValueError): versions.start_install('stage_z2m', COMMIT)
def test_detached_job_has_no_shell_or_credentials(self):
with mock.patch.object(versions.delivery.Path, 'exists', return_value=True), mock.patch.object(versions.subprocess, 'run') as run:
job = versions.start_install('stage_z2m', COMMIT)
args = run.call_args.args[0]
self.assertEqual('systemd-run', args[0])
self.assertEqual(['install', 'stage_z2m', COMMIT], args[-3:])
self.assertNotIn('shell', run.call_args.kwargs)
self.assertEqual('queued', job['state'])
def test_worker_installs_only_confirmed_stage_and_records_failure(self):
versions.delivery.write_json(versions.STATE / 'job.json', {'stage':'stage_z2m', 'commit':COMMIT, 'version':'1.0.0', 'unit':'test-job'})
checkout = Path(versions.read_json(versions.CONFIG)['checkout'])
checkout.mkdir()
(checkout / 'stage-releases.json').write_text(json.dumps(self.catalog))
with mock.patch.object(versions.delivery, 'bootstrap') as boot, mock.patch.object(versions.subprocess, 'run', side_effect=subprocess.CalledProcessError(1, 'bash')) as run:
with self.assertRaises(subprocess.CalledProcessError): versions.install('stage_z2m', COMMIT)
self.assertEqual(COMMIT, boot.call_args.kwargs['commit'])
self.assertEqual(['--only','stage_z2m'], run.call_args.args[0][-2:])
self.assertEqual('failed', versions.read_json(versions.STATE / 'job.json')['state'])
self.assertFalse((versions.STATE / 'stage_z2m.json').exists())
def test_success_requires_receipt_from_this_job(self):
job = {'stage':'stage_z2m', 'commit':COMMIT, 'version':'1.0.0', 'unit':'unique-job'}
checkout = Path(versions.read_json(versions.CONFIG)['checkout'])
checkout.mkdir()
(checkout / 'stage-releases.json').write_text(json.dumps(self.catalog))
for job_id, expected in [('old-job', 'failed'), ('unique-job', 'success')]:
versions.delivery.write_json(versions.STATE / 'job.json', job)
def finish(*args, **kwargs):
self.assertEqual('unique-job', kwargs['env']['IOMATEX_INSTALL_JOB_ID'])
versions.delivery.write_json(versions.STATE / 'stage_z2m.json', {
'commit':COMMIT, 'version':'1.0.0', 'job_id':job_id,
})
with mock.patch.object(versions.delivery, 'bootstrap'), mock.patch.object(versions.subprocess, 'run', side_effect=finish):
if expected == 'failed':
with self.assertRaises(RuntimeError): versions.install('stage_z2m', COMMIT)
else:
versions.install('stage_z2m', COMMIT)
self.assertEqual(expected, versions.read_json(versions.STATE / 'job.json')['state'])
def test_reboot_reconciles_receipt_without_retry(self):
job = {'stage':'stage_env', 'commit':COMMIT, 'state':'running', 'unit':'reboot-job', 'started_at':0}
for receipt_id, expected in [('old-job','interrupted'), ('reboot-job','success')]:
versions.delivery.write_json(versions.STATE / 'job.json', job)
versions.delivery.write_json(versions.STATE / 'stage_env.json', {'commit':COMMIT,'job_id':receipt_id})
with mock.patch.object(versions.subprocess, 'run', return_value=mock.Mock(stdout='inactive')) as run:
self.assertEqual(expected, versions.job_status()['state'])
self.assertEqual(['systemctl','is-active','reboot-job'], run.call_args.args[0])
def test_local_build_is_not_reported_as_published_latest(self):
versions.delivery.write_json(versions.STATE / 'stage_z2m.json', {
'version':'1.0.0', 'commit':'', 'local_build':'unpublished-test',
})
result = self.snapshot()
self.assertEqual('local_build', result['status'])
self.assertTrue(result['can_install'])
def test_bump_owner_updates_both_manifests_and_rejects_downgrade(self):
import bump_stage_version
root = Path(self.tmp.name) / 'releases'
for stage, release in self.catalog['stages'].items():
(root / stage).mkdir(parents=True)
(root / stage / 'version.json').write_text(json.dumps(release))
bump_stage_version.bump(root, 'stage_z2m', '1.0.1')
catalog = versions.validate_manifest(json.loads((root / 'stage-releases.json').read_text()))
self.assertEqual({'version':'1.0.1'},catalog['stages']['stage_z2m'])
self.assertEqual(catalog['stages']['stage_z2m'],json.loads((root / 'stage_z2m/version.json').read_text()))
with self.assertRaises(ValueError): bump_stage_version.bump(root, 'stage_z2m', '1.0.0')
def test_missing_catalog_and_denied_credentials_have_specific_messages(self):
from urllib.error import HTTPError
for code, expected in [(404, 'The stage release catalog has not been published to Git yet.'),
(403, 'Git access was denied. Check the Edge Git credentials.')]:
def network(repo, endpoint, auth, **kwargs):
if endpoint.startswith('branches/'):
return io.StringIO(json.dumps({'commit':{'id':COMMIT}}))
self.assertEqual(15, kwargs['timeout'])
raise HTTPError('https://git.it-screen.com/', code, 'test', {}, None)
with mock.patch.object(versions.delivery, 'open_git', side_effect=network), mock.patch.object(versions.delivery, 'auth_from_env', return_value={}):
versions.refresh()
self.assertEqual(expected, versions.read_json(versions.STATE / 'available.json')['error'])
self.assertFalse(self.snapshot()['can_install'])
def test_release_fetch_is_async_coalesced_and_pinned(self):
(versions.STATE / 'available.json').unlink()
started, release = threading.Event(), threading.Event()
paths = []
def network(repo, endpoint, auth, **kwargs):
paths.append(endpoint)
if endpoint.startswith('branches/'):
started.set()
release.wait(3)
return io.StringIO(json.dumps({'commit':{'id':COMMIT}}))
return io.StringIO(json.dumps(self.catalog))
with mock.patch.object(versions.delivery, 'open_git', side_effect=network), mock.patch.object(versions.delivery, 'auth_from_env', return_value={}):
start = time.monotonic()
versions.request_check()
self.assertLess(time.monotonic()-start, .2)
self.assertTrue(started.wait(1))
versions.request_check(force=True)
self.assertEqual(1,len(paths))
release.set()
for thread in threading.enumerate():
if thread.name == 'stage-release-check': thread.join(3)
self.assertEqual('raw/stage-releases.json?ref='+COMMIT, paths[1])
self.assertEqual(COMMIT, versions.read_json(versions.STATE / 'available.json')['commit'])
def test_shell_lock_blocks_competing_installer_but_allows_child(self):
# Run the actual lock owner against a private replacement path, never the host lock.
script = (ROOT / 'offline/install-lock.sh').read_text().replace('/run/lock/iomatex-installer.lock', str(versions.LOCK)).replace('mkdir -p /run/lock', ':').replace('${EUID:-$(id -u)}', '0')
helper = Path(self.tmp.name) / 'lock.sh'
helper.write_text(script)
with versions.LOCK.open('a') as fd:
import fcntl
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
proc = subprocess.run(['bash','-c','source "$1"', 'test',str(helper)],capture_output=True)
self.assertNotEqual(0, proc.returncode)
env = dict(os.environ, IOMATEX_INSTALL_LOCK_FD=str(fd.fileno()))
proc = subprocess.run(['bash','-c','source "$1"', 'test',str(helper)],env=env,pass_fds=(fd.fileno(),),capture_output=True)
self.assertEqual(0,proc.returncode,proc.stderr)
if __name__ == '__main__': unittest.main()

32
stage-releases.json Normal file
View File

@ -0,0 +1,32 @@
{
"schema": 1,
"stages": {
"stage_env": {
"version": "1.0.0"
},
"stage_wifi": {
"version": "1.0.0"
},
"stage_mqtt": {
"version": "1.0.0"
},
"stage_z2m": {
"version": "1.0.0"
},
"stage_ui": {
"version": "3.1.1"
},
"stage_avahi": {
"version": "1.0.0"
},
"stage_cockpit": {
"version": "1.0.0"
},
"stage_itscreen": {
"version": "1.0.0"
},
"stage_reverse_tunnels": {
"version": "1.0.0"
}
}
}

View File

@ -554,3 +554,5 @@ main() {
} }
main "$@" main "$@"
iomatex_record_stage stage_avahi

3
stage_avahi/version.json Normal file
View File

@ -0,0 +1,3 @@
{
"version": "1.0.0"
}

View File

@ -235,3 +235,5 @@ main() {
} }
main "$@" main "$@"
iomatex_record_stage stage_cockpit

View File

@ -0,0 +1,3 @@
{
"version": "1.0.0"
}

View File

@ -1593,3 +1593,5 @@ timedatectl status 2>/dev/null | sed -n '1,12p' || true
echo echo
echo " DONE. Recommended next step: reboot" echo " DONE. Recommended next step: reboot"
echo echo
iomatex_record_stage stage_env

3
stage_env/version.json Normal file
View File

@ -0,0 +1,3 @@
{
"version": "1.0.0"
}

View File

@ -1512,3 +1512,5 @@ main() {
} }
main "$@" main "$@"
iomatex_record_stage stage_itscreen

View File

@ -0,0 +1,3 @@
{
"version": "1.0.0"
}

View File

@ -811,3 +811,5 @@ echo "Timer check:"
echo " systemctl list-timers --all | grep -F iomatex-mqtt-health" echo " systemctl list-timers --all | grep -F iomatex-mqtt-health"
echo echo
log "Stage1 MQTT finished successfully." log "Stage1 MQTT finished successfully."
iomatex_record_stage stage_mqtt

3
stage_mqtt/version.json Normal file
View File

@ -0,0 +1,3 @@
{
"version": "1.0.0"
}

View File

@ -401,3 +401,5 @@ main() {
} }
main "$@" main "$@"
iomatex_record_stage stage_reverse_tunnels

View File

@ -0,0 +1,3 @@
{
"version": "1.0.0"
}

View File

@ -4,6 +4,7 @@ set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKEND_FILE="$SCRIPT_DIR/console_core/backend/app.py" BACKEND_FILE="$SCRIPT_DIR/console_core/backend/app.py"
FRONTEND_FILE="$SCRIPT_DIR/console_core/frontend/console.js" FRONTEND_FILE="$SCRIPT_DIR/console_core/frontend/console.js"
INDEX_FILE="$SCRIPT_DIR/console_core/frontend/index.html"
extract_version() { extract_version() {
sed -n 's/.*V \([0-9][0-9.]*\).*/\1/p' "$1" | head -n 1 sed -n 's/.*V \([0-9][0-9.]*\).*/\1/p' "$1" | head -n 1
@ -41,6 +42,8 @@ new_label="V $next_version"
sed -i "s/${old_label}/${new_label}/g" "$BACKEND_FILE" "$FRONTEND_FILE" sed -i "s/${old_label}/${new_label}/g" "$BACKEND_FILE" "$FRONTEND_FILE"
sed -i -E "s/(console\.(css|js|i18n\.js)\?v=)[0-9.]+/\1${next_version}/g" "$INDEX_FILE"
echo "UI version bumped: $old_label -> $new_label" echo "UI version bumped: $old_label -> $new_label"
echo "Updated files:" echo "Updated files:"
echo " $BACKEND_FILE" echo " $BACKEND_FILE"

View File

@ -30,3 +30,13 @@
- Future `ui_backend` can own richer workflows: actions, forms, provisioning, and service-specific control paths. - Future `ui_backend` can own richer workflows: actions, forms, provisioning, and service-specific control paths.
- The normalized card contract can remain stable while richer backend features evolve separately. - The normalized card contract can remain stable while richer backend features evolve separately.
- When a workflow already exists as a proven edge shell helper, backend should call that helper rather than rewrite the behavior in frontend. - When a workflow already exists as a proven edge shell helper, backend should call that helper rather than rewrite the behavior in frontend.
## Stage releases
Health extends the shared service renderer with one version/action owner.
`offline/stage_versions.py` owns release checks, installation receipts and jobs
for every stage; Console does not implement its own package installation path.
Checks run in the background against our Git API. Mutations use authenticated
JSON, explicit confirmation, an allowlisted stage and a pinned commit. The worker
runs outside the Console service, with the same installer lock as CLI entrypoints.
See [stage update contract](../../offline/STAGE_UPDATES.md) for publishing and API details.

View File

@ -42,11 +42,18 @@ from modbus_backend import (
write_register as modbus_write_register, write_register as modbus_write_register,
) )
# One owner shared with all CLI stage installations.
_STAGE_OWNER_DIR = "/usr/local/lib/iomatex"
if not os.path.isfile(os.path.join(_STAGE_OWNER_DIR, "stage_versions.py")):
_STAGE_OWNER_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__), "../../../offline"))
sys.path.insert(0, _STAGE_OWNER_DIR)
import stage_versions
APP_DIR = "/opt/iomatex-console" APP_DIR = "/opt/iomatex-console"
PUBLIC_DIR = os.path.join(APP_DIR, "public") PUBLIC_DIR = os.path.join(APP_DIR, "public")
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d") PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
CONFIG_PATH = "/etc/iomatex/console.json" CONFIG_PATH = "/etc/iomatex/console.json"
UI_VERSION = "V 2.2.80" UI_VERSION = "V 3.1.1"
STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health" STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health"
ZONEINFO_ROOT = "/usr/share/zoneinfo" ZONEINFO_ROOT = "/usr/share/zoneinfo"
@ -2368,6 +2375,10 @@ def build_health_services_payload():
"reverse_tunnel", "reverse_tunnel",
"display", "display",
"edge_api", "edge_api",
"access_point",
"environment",
"console",
"avahi",
} }
cards, _ = collect_provider_cards(build_provider_context()) cards, _ = collect_provider_cards(build_provider_context())
payload = { payload = {
@ -3251,7 +3262,13 @@ class Handler(BaseHTTPRequestHandler):
return return
if parsed.path == "/api/health/services": if parsed.path == "/api/health/services":
try: try:
self.send_json(build_health_services_payload()) payload = build_health_services_payload()
cards = [dict(card) for card in payload["services"]]
updates = stage_versions.snapshot(cards)
for card in cards:
card["release"] = next((v for v in updates["stages"].values()
if card["id"] in v["services"]), None)
self.send_json({**payload, "services": cards, "updates": updates})
except Exception as exc: except Exception as exc:
self.send_json({"ok": False, "error": str(exc), "services": []}, code=500) self.send_json({"ok": False, "error": str(exc), "services": []}, code=500)
return return
@ -3429,6 +3446,28 @@ class Handler(BaseHTTPRequestHandler):
return return
if not self.require_auth(parsed): if not self.require_auth(parsed):
return return
if parsed.path in ("/api/stages/check", "/api/stages/install"):
if self.headers.get("Content-Type", "").split(";", 1)[0].strip().lower() != "application/json":
self.send_json({"ok": False, "error": "JSON content type required"}, code=415)
return
payload = self.read_json_body()
if not isinstance(payload, dict):
self.send_json({"ok": False, "error": "Invalid JSON body"}, code=400)
return
try:
if parsed.path == "/api/stages/check":
stage_versions.request_check(force=True)
self.send_json({"ok": True}, code=202)
else:
if payload.get("confirmed") is not True:
raise ValueError("Explicit confirmation is required")
job = stage_versions.start_install(payload.get("stage"), payload.get("commit"))
self.send_json({"ok": True, "job": job}, code=202)
except ValueError as exc:
self.send_json({"ok": False, "error": str(exc)}, code=409)
except Exception:
self.send_json({"ok": False, "error": "Cannot start stage operation"}, code=500)
return
if parsed.path == "/api/auth/password/change": if parsed.path == "/api/auth/password/change":
payload = self.read_json_body() payload = self.read_json_body()
if payload is None: if payload is None:

View File

@ -19,8 +19,8 @@ class ReverseTunnelActionsContractTest(unittest.TestCase):
self.assertIn('onclick="window.__configureReverseTunnel()"', card) self.assertIn('onclick="window.__configureReverseTunnel()"', card)
self.assertIn('restartBusy || configuring ? "disabled"', card) self.assertIn('restartBusy || configuring ? "disabled"', card)
index = (ROOT / "frontend" / "index.html").read_text() index = (ROOT / "frontend" / "index.html").read_text()
self.assertIn('console.js?v=2.2.81', index) self.assertIn(f'console.js?v={app.UI_VERSION.removeprefix("V ")}', index)
self.assertIn('console.i18n.js?v=2.2.81', index) self.assertIn(f'console.i18n.js?v={app.UI_VERSION.removeprefix("V ")}', index)
def test_card_restarts_all_units_and_exposes_local_service_links(self): def test_card_restarts_all_units_and_exposes_local_service_links(self):
backend = (ROOT / "backend" / "app.py").read_text(encoding="utf-8") backend = (ROOT / "backend" / "app.py").read_text(encoding="utf-8")
@ -39,7 +39,7 @@ class ReverseTunnelActionsContractTest(unittest.TestCase):
self.assertIn('restartable=installed', provider) self.assertIn('restartable=installed', provider)
self.assertIn('.reverseTunnelCommand{\n margin-top:14px;', stylesheet) self.assertIn('.reverseTunnelCommand{\n margin-top:14px;', stylesheet)
self.assertIn('grid-template-columns:minmax(110px,42%) minmax(0,1fr)', stylesheet) self.assertIn('grid-template-columns:minmax(110px,42%) minmax(0,1fr)', stylesheet)
self.assertIn('console.css?v=2.2.80', index) self.assertIn(f'console.css?v={app.UI_VERSION.removeprefix("V ")}', index)
class ReverseTunnelConfigurationTest(unittest.TestCase): class ReverseTunnelConfigurationTest(unittest.TestCase):

View File

@ -0,0 +1,51 @@
import http.client
import importlib.util
import json
from pathlib import Path
import sys
import threading
import unittest
from unittest import mock
BACKEND = Path(__file__).resolve().parent
sys.path.insert(0, str(BACKEND))
spec = importlib.util.spec_from_file_location('stage_updates_api_app', BACKEND / 'app.py')
app = importlib.util.module_from_spec(spec)
spec.loader.exec_module(app)
class StageUpdateApiTest(unittest.TestCase):
def setUp(self):
self.server = app.ThreadingHTTPServer(('127.0.0.1', 0), app.Handler)
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
self.addCleanup(self.server.server_close)
self.addCleanup(self.server.shutdown)
patch = mock.patch.object(app.Handler, 'log_message')
patch.start(); self.addCleanup(patch.stop)
def post(self, payload, content_type='application/json'):
connection = http.client.HTTPConnection(*self.server.server_address)
connection.request('POST', '/api/stages/install', json.dumps(payload), {'Content-Type':content_type})
response = connection.getresponse()
body = json.loads(response.read())
connection.close()
return response.status, body
def test_anonymous_cannot_start_job(self):
with mock.patch.object(app.Handler, 'auth_session', return_value=None), mock.patch.object(app.stage_versions, 'start_install') as start:
self.assertEqual(401, self.post({'confirmed':True})[0])
start.assert_not_called()
def test_requires_json_and_explicit_confirmation(self):
with mock.patch.object(app.Handler, 'auth_session', return_value={'username':'iomatex'}), mock.patch.object(app.stage_versions, 'start_install') as start:
self.assertEqual(415, self.post({'confirmed':True}, 'text/plain')[0])
self.assertEqual(409, self.post({'stage':'stage_z2m'})[0])
self.assertEqual(400, self.post([])[0])
start.assert_not_called()
def test_confirmed_request_uses_allowlisted_owner(self):
with mock.patch.object(app.Handler, 'auth_session', return_value={'username':'iomatex'}), mock.patch.object(app.stage_versions, 'start_install', return_value={'state':'queued'}) as start:
self.assertEqual(202, self.post({'stage':'stage_z2m','commit':'a'*40,'confirmed':True})[0])
start.assert_called_once_with('stage_z2m','a'*40)
if __name__ == '__main__': unittest.main()

View File

@ -0,0 +1,69 @@
const {chromium}=require('playwright');
const fs=require('node:fs');
const assert=require('node:assert/strict');
const root=require('node:path').resolve(__dirname,'../frontend');
(async()=>{
const browser=await chromium.launch({headless:true});
const page=await browser.newPage();
const errors=[]; const installs=[];
page.on('pageerror',e=>errors.push(e.message));
const services=[
{id:'zigbee2mqtt',title:'Zigbee2MQTT',installed:false,state:'not installed',status_text:'Not installed',release:{stage:'stage_z2m',installed:false,current:null,latest:'1.0.0',status:'not_installed',can_install:true,commit:'a'.repeat(40)}},
{id:'mosquitto',title:'Local Mosquitto MQTT',installed:true,state:'active',status_text:'Running',release:{stage:'stage_mqtt',installed:true,current:'1.0.0',latest:'1.1.0',status:'update_available',can_install:true,commit:'a'.repeat(40)}},
{id:'console',title:'Edge Console',installed:true,status_text:'Installed',release:{stage:'stage_ui',installed:true,current:'1.0.0',latest:'1.0.0',status:'latest',can_install:false,commit:'a'.repeat(40)}}
];
await page.route('http://edge.test/**', async route=>{
const p=new URL(route.request().url()).pathname;
if(p.startsWith('/api/')){
let data={ok:true};
if(p==='/api/auth/session') data={ok:true,authenticated:true,username:'iomatex',expires_at:Math.floor(Date.now()/1000)+3600};
if(p==='/api/health/services') data={ok:true,services,updates:{checked_at:Math.floor(Date.now()/1000)}};
if(p==='/api/stages/install') {installs.push(route.request().postDataJSON()); data={ok:true,job:{state:'queued'}};}
return route.fulfill({contentType:'application/json',body:JSON.stringify(data)});
}
const file=p==='/'?'index.html':p.slice(1);
if(!['index.html','console.js','console.i18n.js','console.css'].includes(file)) return route.fulfill({status:404,body:''});
return route.fulfill({contentType:file.endsWith('js')?'text/javascript':file.endsWith('css')?'text/css':'text/html',body:fs.readFileSync(root+'/'+file)});
});
await page.addInitScript(()=>localStorage.setItem('consoleLanguage','ru'));
await page.goto('http://edge.test/');
await page.getByRole('button',{name:'Установить 1.0.0',exact:true}).waitFor();
for(const width of [360,768,1024,1440]){
await page.setViewportSize({width,height:900});
await page.waitForTimeout(250);
assert.equal(await page.evaluate(()=>document.documentElement.scrollWidth>innerWidth+1),false,'horizontal overflow '+width);
const gaps=await page.locator('.list').filter({has:page.getByText('Версия стадии',{exact:true})}).evaluateAll(nodes=>nodes.map(node=>{
return node.querySelector('.serviceActionRow').getBoundingClientRect().top-node.querySelector('.meta').getBoundingClientRect().bottom;
}));
assert.ok(gaps.length===3 && gaps.every(gap=>gap>=12),'status-to-button spacing '+width);
}
await page.getByRole('button',{name:'Установить 1.0.0',exact:true}).click();
await page.getByRole('dialog').waitFor();
assert.equal(await page.locator('.modalBackdrop').evaluate(el=>el.parentNode===document.body),true);
await page.keyboard.press('Escape');
assert.equal(await page.getByRole('dialog').count(),0);
assert.equal(installs.length,0);
await page.setViewportSize({width:360,height:640});
await page.getByRole('button',{name:'Установить 1.0.0',exact:true}).click();
const rect=await page.getByRole('dialog').boundingBox();
assert.ok(rect.y>=0 && rect.y+rect.height<=640,'dialog stays in viewport');
await page.getByRole('dialog').getByRole('button',{name:'Установить',exact:true}).click();
assert.equal(installs.length,1);
assert.equal(installs[0].stage,'stage_z2m');
assert.equal(installs[0].confirmed,true);
assert.equal(installs[0].commit,'a'.repeat(40));
await page.setViewportSize({width:1440,height:1000});
services[0].release.latest=null;
services[0].release.status='not_checked';
services[0].release.can_install=false;
await page.reload({waitUntil:'networkidle'});
const unavailable=page.locator('article').filter({has:page.getByRole('heading',{name:'Zigbee2MQTT',exact:true})});
await unavailable.getByRole('button',{name:'Проверить версии',exact:true}).waitFor();
assert.equal(await unavailable.getByRole('button',{name:'Проверить версии',exact:true}).isEnabled(),true);
assert.equal(await unavailable.getByRole('button',{name:/^Установить/}).count(),0);
assert.deepEqual(errors,[]);
console.log('Browser: 360/768/1024/1440, Russian labels, warning, Escape, pinned install passed');
await browser.close();
})().catch(e=>{console.error(e);process.exit(1)});

View File

@ -0,0 +1,39 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const vm = require('node:vm');
const source = fs.readFileSync(path.join(__dirname, '../frontend/console.js'), 'utf8');
const owner = source.slice(source.indexOf(' function stageReleaseStatus'), source.indexOf(' function renderServiceCardContent'));
const handlers = source.slice(source.indexOf(' window.__checkStageVersions'), source.indexOf(' window.__restartService'));
const release = {stage:'stage_z2m',current:null,latest:'1.0.0',status:'not_installed',installed:false,can_install:true,commit:'a'.repeat(40)};
const card = {id:'zigbee2mqtt', title:'Zigbee2MQTT', release};
const requests=[];
let confirmed=false;
const context = {window:{}, state:{activeTab:'health',healthServices:{services:[card],updates:{}}},
t:x=>x, esc:x=>String(x), renderKeyValueRows:rows=>rows.map(row=>row.value).join(' '), renderServiceCardContent:()=>'<article>original</article>',
confirmAction:async()=>confirmed, platformDialog:async()=>{},
fetchJson:async(url,options)=>{ requests.push({url,...JSON.parse(options.body)}); return {}; },
showToast:()=>{}, loadHealth:async()=>{}, renderActiveTab:()=>{}};
vm.createContext(context);
vm.runInContext(owner+handlers,context);
(async()=>{
assert.match(context.renderServiceCard(card),/original/);
assert.match(context.renderServiceCard(card),/Install 1.0.0/);
await context.window.__stageVersion('zigbee2mqtt');
assert.equal(requests.length,0,'cancel never installs');
confirmed=true;
await context.window.__stageVersion('zigbee2mqtt');
assert.deepEqual(requests[0],{url:'/api/stages/install',stage:'stage_z2m',commit:release.commit,confirmed:true});
release.status='latest'; release.can_install=false; release.current='1.0.0';
assert.match(context.renderServiceCard(card),/Latest version installed/);
assert.doesNotMatch(context.renderServiceCard(card),/>Install/);
await context.window.__stageVersion('zigbee2mqtt');
assert.equal(requests.length,1,'latest only opens version details');
release.status='not_checked'; release.latest=null;
context.state.healthServices.updates.error='The stage release catalog has not been published to Git yet.';
const unavailable=context.renderServiceCard(card);
assert.match(unavailable,/Check versions/);
assert.match(unavailable,/catalog has not been published/);
assert.doesNotMatch(unavailable,/>Update</);
console.log('Stage update UI: shared renderer, cancel, pinned confirmation and latest state passed');
})().catch(error=>{console.error(error);process.exitCode=1;});

View File

@ -1025,7 +1025,7 @@ html[dir="rtl"] .itscreenLogsActions{
color:var(--ink); color:var(--ink);
line-height:1.55; line-height:1.55;
} }
.serviceActionRow{align-items:center} .serviceActionRow{align-items:center;margin-top:12px}
.actionBadge{ .actionBadge{
display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px; display:inline-flex;align-items:center;border-radius:999px;padding:6px 10px;
background:var(--surface-strong);color:var(--muted);font-size:12px;font-weight:700; background:var(--surface-strong);color:var(--muted);font-size:12px;font-weight:700;
@ -1617,6 +1617,7 @@ html[dir="rtl"] .timezoneOption{text-align:right}
.itscreenCards{grid-template-columns:repeat(2,minmax(0,1fr))} .itscreenCards{grid-template-columns:repeat(2,minmax(0,1fr))}
} }
@media (max-width:720px){ @media (max-width:720px){
.brand{flex-direction:column;align-items:flex-start}
.meta{grid-template-columns:1fr 1fr} .meta{grid-template-columns:1fr 1fr}
.splitMeta{grid-template-columns:1fr} .splitMeta{grid-template-columns:1fr}
.networkOverviewGrid{grid-template-columns:1fr} .networkOverviewGrid{grid-template-columns:1fr}

View File

@ -12,6 +12,38 @@
], ],
translations: { translations: {
ru: { ru: {
"Another installation is running": "Уже выполняется другая установка",
"Check available versions before installing.": "Перед установкой проверьте доступные версии.",
"The stage release catalog has not been published to Git yet.": "Каталог версий стадий ещё не опубликован в Git.",
"Git access was denied. Check the Edge Git credentials.": "Git отклонил доступ. Проверьте учётные данные Git на Edge.",
"Local build installed": "Установлена локальная сборка",
"Version check required": "Нужно проверить доступную версию",
"Stage version": "Версия стадии",
"Version": "Версия",
"Not checked": "Не проверено",
"Latest version installed": "Установлена последняя версия",
"Update available": "Доступно обновление",
"Installed version is unknown": "Версия установленной стадии неизвестна",
"Installed version is newer than the published release": "Установленная версия новее опубликованной",
"Update": "Обновить",
"Install": "Установить",
"Installing...": "Установка…",
"Queued": "В очереди",
"Installation completed": "Установка завершена",
"Installation failed": "Ошибка установки",
"Installation interrupted": "Установка прервана",
"Checking versions...": "Проверка версий…",
"Check versions": "Проверить версии",
"Last version check": "Последняя проверка версий",
"Cannot check releases on our Git": "Не удалось проверить версии в нашем Git",
"See installation log": "Смотрите журнал установки",
"Only the selected stage will be installed. Related services may restart and the connection may be interrupted.": "Будет установлена только выбранная стадия. Связанные сервисы могут перезапуститься, соединение может прерваться.",
"This stage reboots the Edge.": "Эта стадия перезагрузит Edge.",
"Are you sure you want to install this version?": "Точно хотите установить эту версию?",
"Confirm service update": "Подтверждение установки / обновления",
"Installation started. You may close this page.": "Установка запущена. Эту страницу можно закрыть.",
"Edge environment": "Окружение Edge",
"Edge Console": "Консоль Edge",
"IOMATEX Console": "IOMATEX Console", "IOMATEX Console": "IOMATEX Console",
"Open menu": "Открыть меню", "Open menu": "Открыть меню",
"Close menu": "Закрыть меню", "Close menu": "Закрыть меню",

View File

@ -48,7 +48,7 @@
{ mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" }, { mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" },
{ mode: "custom", label: "Custom", host: "" } { mode: "custom", label: "Custom", host: "" }
]; ];
const UI_VERSION = "V 2.2.80"; const UI_VERSION = "V 3.1.1";
const ITSCREEN_LOG_INITIAL_LINES = 50; const ITSCREEN_LOG_INITIAL_LINES = 50;
const ITSCREEN_LOG_BUFFER_LIMIT = 300; const ITSCREEN_LOG_BUFFER_LIMIT = 300;
const ITSCREEN_LOG_BATCH_MS = 250; const ITSCREEN_LOG_BATCH_MS = 250;
@ -156,6 +156,7 @@
health: null, health: null,
healthServices: null, healthServices: null,
healthRequest: null, healthRequest: null,
stageUpdateDialogOpen: false,
mqttSelfTest: { mqttSelfTest: {
loading: false, loading: false,
result: null, result: null,
@ -1041,13 +1042,24 @@
</div> </div>
</div> </div>
`; `;
let finished = false;
const isTopmost = () => {
const layers = document.querySelectorAll(".modalBackdrop");
return layers[layers.length - 1] === backdrop;
};
const finish = (result) => { const finish = (result) => {
if (finished || !isTopmost()) return;
finished = true;
document.removeEventListener("keydown", onKeydown); document.removeEventListener("keydown", onKeydown);
backdrop.remove(); backdrop.remove();
resolve(result); resolve(result);
}; };
const onKeydown = (event) => { const onKeydown = (event) => {
if (event.key === "Escape") finish(false); if (event.key === "Escape" && isTopmost()) {
event.preventDefault();
event.stopImmediatePropagation();
finish(false);
}
}; };
backdrop.addEventListener("click", (event) => { backdrop.addEventListener("click", (event) => {
if (event.target === backdrop) finish(false); if (event.target === backdrop) finish(false);
@ -2235,7 +2247,51 @@
`; `;
} }
function stageReleaseStatus(release) {
const labels = {
latest: "Latest version installed", update_available: "Update available", local_build: "Local build installed",
not_installed: "Not installed", unknown: "Installed version is unknown", not_checked: "Version check required",
ahead: "Installed version is newer than the published release"
};
return t(labels[release.status] || "Unknown");
}
function renderStageVersion(card) {
const release = card.release;
if (!release) return "";
const updates = (state.healthServices && state.healthServices.updates) || {};
const job = updates.job || {};
const running = ["queued", "running"].includes(job.state) && job.stage === release.stage;
const action = release.installed ? t("Update") : t("Install");
const needsCheck = release.status === "not_checked" || !release.latest;
const reason = updates.busy ? t("Another installation is running")
: updates.checking ? t("Checking versions...")
: updates.error ? t(updates.error)
: needsCheck ? t("Check available versions before installing.") : "";
return `<div class="list">
<div class="listTitle">${esc(t("Stage version"))}</div>
<div class="meta compactMeta">${renderKeyValueRows([
{ label: t("Installed"), value: release.current || t("Unknown") },
{ label: t("Available"), value: release.latest || t("Not checked") },
{ label: t("Status"), value: stageReleaseStatus(release) }
])}</div>
<div class="actionRow serviceActionRow">
<button class="actionBtn secondary" type="button" onclick="window.__stageVersion('${esc(card.id)}')">${esc(t("Version"))}: ${esc(release.current || t("Unknown"))}</button>
${needsCheck && !running ? `<button class="actionBtn secondary" type="button" ${updates.checking || updates.busy ? "disabled" : ""} onclick="window.__checkStageVersions()">${esc(t(updates.checking ? "Checking versions..." : "Check versions"))}</button>`
: release.status !== "latest" && release.status !== "ahead" ? `<button class="actionBtn" type="button" ${release.can_install ? "" : "disabled"} onclick="window.__stageVersion('${esc(card.id)}')">${esc(running ? t("Installing...") : `${action}${release.latest ? ` ${release.latest}` : ""}`)}</button>` : ""}
</div>
${!release.can_install && reason ? `<div class="formHint" role="status">${esc(reason)}</div>` : ""}
</div>`;
}
function renderServiceCard(card) { function renderServiceCard(card) {
const content = renderServiceCardContent(card);
// All specialized cards retain their existing renderer and share one release control.
const end = content.lastIndexOf("</article>");
return end < 0 ? content : content.slice(0, end) + renderStageVersion(card) + content.slice(end);
}
function renderServiceCardContent(card) {
if (card.id === "itscreen") return renderItscreenServiceCard(card); if (card.id === "itscreen") return renderItscreenServiceCard(card);
if (card.id === "display") return renderDisplayCard(card); if (card.id === "display") return renderDisplayCard(card);
if (card.id === "access_point") return renderAccessPointCard(card); if (card.id === "access_point") return renderAccessPointCard(card);
@ -2477,6 +2533,9 @@
function renderHealthTab() { function renderHealthTab() {
const payload = state.healthServices || { services: [] }; const payload = state.healthServices || { services: [] };
const health = state.health || {}; const health = state.health || {};
const updates = payload.updates || {};
const updateJob = updates.job || {};
const jobLabels = { queued: "Queued", running: "Installing...", success: "Installation completed", failed: "Installation failed", interrupted: "Installation interrupted" };
const metrics = [ const metrics = [
{ label: t("CPU usage"), value: health.cpu_usage_percent === null || health.cpu_usage_percent === undefined ? t("Collecting...") : `${health.cpu_usage_percent}%` }, { label: t("CPU usage"), value: health.cpu_usage_percent === null || health.cpu_usage_percent === undefined ? t("Collecting...") : `${health.cpu_usage_percent}%` },
renderLoadAverageMetric(health), renderLoadAverageMetric(health),
@ -2488,7 +2547,6 @@
]; ];
const temps = Array.isArray(health.temperatures) ? health.temperatures : []; const temps = Array.isArray(health.temperatures) ? health.temperatures : [];
const serviceCards = (payload.services || []) const serviceCards = (payload.services || [])
.filter((card) => card.id !== "access_point")
.sort((left, right) => { .sort((left, right) => {
const order = { const order = {
itscreen: 10, itscreen: 10,
@ -2515,6 +2573,12 @@
<div class="sectionHead"> <div class="sectionHead">
<div class="panelTitleRow"><h2>${esc(t("Installed Services"))}</h2>${renderHelpButton("service_generic")}</div> <div class="panelTitleRow"><h2>${esc(t("Installed Services"))}</h2>${renderHelpButton("service_generic")}</div>
<p>${esc(t("Core diagnostics and service state from providers."))}</p> <p>${esc(t("Core diagnostics and service state from providers."))}</p>
<div class="actionRow">
<button class="actionBtn secondary" type="button" ${updates.checking || updates.busy ? "disabled" : ""} onclick="window.__checkStageVersions()">${esc(t(updates.checking ? "Checking versions..." : "Check versions"))}</button>
<span>${esc(t("Last version check"))}: ${esc(updates.checked_at ? new Date(updates.checked_at * 1000).toLocaleString() : t("Not checked"))}</span>
</div>
${updates.error ? `<div class="banner warn">${esc(t(updates.error))}</div>` : ""}
${updateJob.state ? `<div class="banner ${["failed", "interrupted"].includes(updateJob.state) ? "warn" : ""}" role="status">${esc(t(jobLabels[updateJob.state] || updateJob.state))} · ${esc(updateJob.stage)} ${esc(updateJob.version || "")}${["failed", "interrupted"].includes(updateJob.state) ? ` · ${esc(t("See installation log"))}: /var/lib/iomatex/stages/install.log` : ""}</div>` : ""}
</div> </div>
<div class="cards">${serviceCards.map(renderServiceCard).join("") || `<div class="empty">${esc(t("No service cards available."))}</div>`}</div> <div class="cards">${serviceCards.map(renderServiceCard).join("") || `<div class="empty">${esc(t("No service cards available."))}</div>`}</div>
</section> </section>
@ -5128,6 +5192,40 @@
} }
}; };
window.__checkStageVersions = async function () {
try {
await fetchJson("/api/stages/check", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" });
await loadHealth();
if (state.activeTab === "health") renderActiveTab();
} catch (error) { showToast("error", error.message); }
};
window.__stageVersion = async function (serviceId) {
if (state.stageUpdateDialogOpen) return;
const card = ((state.healthServices && state.healthServices.services) || []).find(item => item.id === serviceId);
if (!card || !card.release) return;
state.stageUpdateDialogOpen = true;
try {
const release = card.release;
const details = `${t("Stage version")}: ${release.current || t("Unknown")} → ${release.latest || t("Not checked")}. ${stageReleaseStatus(release)}.`;
if (!release.can_install) {
await platformDialog({ title: t(card.title), message: details, primaryLabel: t("Close") });
return;
}
const message = `${details} ${t("Only the selected stage will be installed. Related services may restart and the connection may be interrupted.")} ${release.reboot ? t("This stage reboots the Edge.") : ""} ${t("Are you sure you want to install this version?")}`;
if (!await confirmAction(t("Confirm service update"), message, t(release.installed ? "Update" : "Install"))) return;
try {
await fetchJson("/api/stages/install", {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ stage: release.stage, commit: release.commit, confirmed: true })
});
showToast("success", t("Installation started. You may close this page."));
await loadHealth();
if (state.activeTab === "health") renderActiveTab();
} catch (error) { showToast("error", error.message); }
} finally { state.stageUpdateDialogOpen = false; }
};
window.__restartService = async function (serviceId) { window.__restartService = async function (serviceId) {
if (!serviceId || state.serviceActions.busyById[serviceId]) return; if (!serviceId || state.serviceActions.busyById[serviceId]) return;
if (serviceId === "reverse_tunnel" && state.reverseTunnelUi.configuring) return; if (serviceId === "reverse_tunnel" && state.reverseTunnelUi.configuring) return;

View File

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

View File

@ -962,6 +962,26 @@ def placeholder_card(service_id, title):
) )
def managed_system_cards(ctx):
installed = ctx["any_exists"]([
"/usr/local/sbin/iomatex-storage-health",
"/etc/systemd/system/iomatex-userdata-bootstrap.service",
])
cards = [_service_card("environment", "Edge environment", "", installed, installed,
installed, "active" if installed else "not installed",
"Installed" if installed else "Not installed")]
for service_id, title, name in [
("console", "Edge Console", "iomatex-console.service"),
("avahi", "Avahi / mDNS", "avahi-daemon.service"),
]:
unit = ctx["systemd_unit"](name)
state, label = _lifecycle(unit["installed"], unit["installed"], unit["active"],
failed=unit["active_state"] == "failed")
cards.append(_service_card(service_id, title, name, unit["installed"], unit["installed"],
unit["active"], state, label, _short_unit_errors(unit)))
return cards
def get_cards(ctx): def get_cards(ctx):
return [ return [
itscreen_card(ctx), itscreen_card(ctx),
@ -971,4 +991,5 @@ def get_cards(ctx):
reverse_tunnel_card(ctx), reverse_tunnel_card(ctx),
access_point_card(ctx), access_point_card(ctx),
display_card(ctx), display_card(ctx),
*managed_system_cards(ctx),
] ]

View File

@ -342,6 +342,11 @@ remove_if_exists /etc/avahi/services/iomatex-console.service
remove_if_exists /usr/local/sbin/iomatex-mdns-alias remove_if_exists /usr/local/sbin/iomatex-mdns-alias
remove_if_exists /etc/systemd/system/iomatex-mdns-alias.service remove_if_exists /etc/systemd/system/iomatex-mdns-alias.service
# Install the shared version owner outside Console, so a UI update cannot kill its worker.
install -d /usr/local/lib/iomatex
install -m 0644 "$IOMATEX_PROJECT_ROOT/offline/stage_versions.py" /usr/local/lib/iomatex/stage_versions.py
python3 /usr/local/lib/iomatex/stage_versions.py configure "$IOMATEX_PROJECT_ROOT"
step "Validate and restart" step "Validate and restart"
python3 -m py_compile "$STAGE_BACKEND_DIR/app.py" "$STAGE_BACKEND_DIR/itscreen_registration.py" "$STAGE_BACKEND_DIR/modbus_backend.py" "$STAGE_PROVIDERS_DIR/00_core_services.py" python3 -m py_compile "$STAGE_BACKEND_DIR/app.py" "$STAGE_BACKEND_DIR/itscreen_registration.py" "$STAGE_BACKEND_DIR/modbus_backend.py" "$STAGE_PROVIDERS_DIR/00_core_services.py"
require_file "$STAGE_PUBLIC_DIR/index.html" require_file "$STAGE_PUBLIC_DIR/index.html"
@ -400,3 +405,5 @@ echo "Modbus profiles dir: ${MODBUS_PROFILES_DIR}"
echo "Config: ${CFG_PATH}" echo "Config: ${CFG_PATH}"
echo "Previous install backup: ${PREV_DIR}" echo "Previous install backup: ${PREV_DIR}"
echo "Legacy backup: ${LEGACY_PREV_DIR}" echo "Legacy backup: ${LEGACY_PREV_DIR}"
iomatex_record_stage stage_ui

3
stage_ui/version.json Normal file
View File

@ -0,0 +1,3 @@
{
"version": "3.1.1"
}

View File

@ -1513,3 +1513,5 @@ echo " /usr/local/sbin/iomatex-wifi-status"
echo " /usr/local/sbin/iomatex-ap-reset-password" echo " /usr/local/sbin/iomatex-ap-reset-password"
echo " systemctl status iomatex-wifi-ui.service iomatex-ap-watch.timer iomatex-ap-resetd.service iomatex-wifi-dstate-watchdog.timer --no-pager" echo " systemctl status iomatex-wifi-ui.service iomatex-ap-watch.timer iomatex-ap-resetd.service iomatex-wifi-dstate-watchdog.timer --no-pager"
echo " journalctl -u iomatex-wifi-ui.service -u iomatex-ap-watch.service -u iomatex-ap-resetd.service -u iomatex-wifi-dstate-watchdog.service --no-pager -n 200" echo " journalctl -u iomatex-wifi-ui.service -u iomatex-ap-watch.service -u iomatex-ap-resetd.service -u iomatex-wifi-dstate-watchdog.service --no-pager -n 200"
iomatex_record_stage stage_wifi

3
stage_wifi/version.json Normal file
View File

@ -0,0 +1,3 @@
{
"version": "1.0.0"
}

View File

@ -117,6 +117,7 @@ main() {
require_root require_root
orchestrator_init orchestrator_init
run_all run_all
iomatex_record_stage stage_z2m
;; ;;
from) from)
[ "$#" -eq 2 ] || die "Usage: stage_z2m.sh from <stage>" [ "$#" -eq 2 ] || die "Usage: stage_z2m.sh from <stage>"

3
stage_z2m/version.json Normal file
View File

@ -0,0 +1,3 @@
{
"version": "1.0.0"
}