Add confirmed sequential update-all job to Edge Console 3.1.18
This commit is contained in:
parent
ee93633d13
commit
48d7e75d2f
|
|
@ -0,0 +1,8 @@
|
|||
# Edge Console 3.1.18
|
||||
|
||||
- Added **Update all** beside **Check versions** in Installed Services, with a count of installed modules that have newer published releases. Shared stages such as MQTT are included once; missing optional modules are excluded.
|
||||
- Confirmation lists module versions and warns when Edge Environment requires a reboot. The authenticated API revalidates the complete selection against the pinned release catalog.
|
||||
- Updates run sequentially in one detached installer job with the existing global lock. Failure stops remaining updates. Console runs near the end and Edge Environment last. Progress and the shared installation log remain available after leaving the page.
|
||||
- Storage recovery resumes the same ordered batch; successful completion requires receipts for every selected stage from that job.
|
||||
|
||||
Validation: stage version/batch tests, authenticated API tests, shared UI handler tests, storage recovery tests; Playwright checked cancellation, a single mocked batch request, exclusion of missing modules and button placement at 1440/768/360 px. No bulk update was executed on the live Edge during validation.
|
||||
|
|
@ -166,9 +166,10 @@ def job_status():
|
|||
# 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']
|
||||
ok = receipts_match(job)
|
||||
job = {**job, 'state': 'success' if ok else 'interrupted', 'finished_at': int(time.time())}
|
||||
if ok and job.get('stages'):
|
||||
job['completed'] = job['stages']
|
||||
delivery.write_json(STATE / 'job.json', job)
|
||||
return job
|
||||
|
||||
|
|
@ -177,7 +178,7 @@ def job_status():
|
|||
def installation_log(stage, unit="", full=False):
|
||||
"""Only the latest job owns install.log; never accept a filesystem path."""
|
||||
job = read_json(STATE / 'job.json')
|
||||
if stage not in STAGES or job.get('stage') != stage or (unit and job.get('unit') != unit):
|
||||
if stage not in STAGES or stage not in job_stages(job) or (unit and job.get('unit') != unit):
|
||||
raise ValueError('Installation log belongs to a different job; refresh the card')
|
||||
try:
|
||||
with (STATE / 'install.log').open('rb') as stream:
|
||||
|
|
@ -247,7 +248,33 @@ def snapshot(cards):
|
|||
'error': available.get('error', ''), 'busy': busy, 'job': job}
|
||||
|
||||
|
||||
def start_install(stage, commit):
|
||||
def job_stages(job):
|
||||
return job.get('stages') or [job.get('stage')]
|
||||
|
||||
|
||||
def receipts_match(job):
|
||||
for stage in job_stages(job):
|
||||
receipt = read_json(STATE / (stage + '.json'))
|
||||
expected = job.get('versions', {}).get(stage, job.get('version'))
|
||||
if receipt.get('commit') != job.get('commit') or receipt.get('job_id') != job.get('unit'):
|
||||
return False
|
||||
if expected and receipt.get('version') != expected:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def start_install_all(stages, commit, cards):
|
||||
releases = snapshot(cards)['stages']
|
||||
expected = {key for key, value in releases.items()
|
||||
if value['installed'] and value['status'] == 'update_available' and value['can_install']}
|
||||
if not isinstance(stages, list) or not stages or not all(isinstance(key, str) for key in stages) or len(set(stages)) != len(stages) or set(stages) != expected:
|
||||
raise ValueError('Available updates changed; check versions and confirm again')
|
||||
ordered = [key for key in STAGES if key in expected and key not in ('stage_ui', 'stage_env')]
|
||||
ordered += [key for key in ('stage_ui', 'stage_env') if key in expected]
|
||||
return start_install(ordered[0], commit, batch=ordered)
|
||||
|
||||
|
||||
def start_install(stage, commit, batch=None):
|
||||
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:
|
||||
|
|
@ -263,9 +290,17 @@ def start_install(stage, commit):
|
|||
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')
|
||||
stages = batch or [stage]
|
||||
versions = {key: available['stages'][key]['version'] for key in stages}
|
||||
for key in stages:
|
||||
current = read_json(STATE / (key + '.json')).get('version')
|
||||
if current and tuple(map(int, current.split('.'))) > tuple(map(int, versions[key].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())}
|
||||
if batch:
|
||||
job.update(stages=stages, versions=versions, completed=[])
|
||||
delivery.write_json(STATE / 'job.json', job)
|
||||
try:
|
||||
(STATE / 'install.log').write_text('')
|
||||
|
|
@ -283,10 +318,33 @@ def start_install(stage, commit):
|
|||
return job
|
||||
|
||||
|
||||
def run_stages(root, stages, commit, job, lock_fd, output=None):
|
||||
releases = validate_manifest(read_json(root / 'stage-releases.json'))['stages']
|
||||
for stage in stages:
|
||||
expected = job.get('versions', {}).get(stage, job['version'])
|
||||
if releases[stage]['version'] != expected:
|
||||
raise ValueError('Downloaded release does not match confirmation')
|
||||
completed = []
|
||||
for stage in stages:
|
||||
if job.get('stages'):
|
||||
delivery.write_json(STATE / 'job.json', {**job, 'state': 'running', 'current_stage': stage, 'completed': completed})
|
||||
env = dict(os.environ, IOMATEX_INSTALL_LOCK_FD=str(lock_fd), 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_fd,), stdout=output, stderr=subprocess.STDOUT)
|
||||
receipt = read_json(STATE / (stage + '.json'))
|
||||
expected = job.get('versions', {}).get(stage, job['version'])
|
||||
if receipt.get('commit') != commit or receipt.get('version') != expected or receipt.get('job_id') != job['unit']:
|
||||
raise RuntimeError('Stage did not finish successfully; see installation log')
|
||||
completed.append(stage)
|
||||
return completed
|
||||
|
||||
|
||||
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')
|
||||
stages = job_stages(job)
|
||||
STATE.mkdir(parents=True, exist_ok=True)
|
||||
try:
|
||||
LOCK.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
|
@ -295,25 +353,17 @@ def install(stage, commit):
|
|||
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, recovery_stages=[stage], recovery_job=job)
|
||||
cfg['branch'], cfg['checkout'], commit=commit, recovery_stages=stages, recovery_job=job)
|
||||
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')
|
||||
completed = run_stages(root, stages, commit, job, lock.fileno())
|
||||
if job.get('stages'):
|
||||
job = {**job, 'completed': completed}
|
||||
delivery.write_json(STATE / 'job.json', {**job, 'state': 'success', 'finished_at': int(time.time())})
|
||||
except delivery.RecoveryPending:
|
||||
delivery.write_json(STATE / 'job.json', {**job, 'state': 'running', 'phase': 'storage_recovery'})
|
||||
return
|
||||
except Exception as exc:
|
||||
delivery.write_json(STATE / 'job.json', {**job, 'state': 'failed', 'error': type(exc).__name__,
|
||||
delivery.write_json(STATE / 'job.json', {**read_json(STATE / 'job.json'), 'state': 'failed', 'error': type(exc).__name__,
|
||||
'finished_at': int(time.time())})
|
||||
raise
|
||||
|
||||
|
|
|
|||
|
|
@ -0,0 +1,66 @@
|
|||
import json
|
||||
import subprocess
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
import test_stage_versions as fixtures
|
||||
COMMIT = fixtures.COMMIT
|
||||
import stage_versions as versions
|
||||
|
||||
class StageBatchTest(unittest.TestCase):
|
||||
setUp = fixtures.StageVersionsTest.setUp
|
||||
def batch(self):
|
||||
stages = ['stage_mqtt', 'stage_ui', 'stage_env']
|
||||
return dict(stage=stages[0], stages=stages, commit=COMMIT, unit='batch-job',
|
||||
version=self.catalog['stages'][stages[0]]['version'],
|
||||
versions={s: self.catalog['stages'][s]['version'] for s in stages},
|
||||
state='running', started_at=0, completed=[])
|
||||
|
||||
def test_selection_is_exact_deduplicated_and_orders_reboot_last(self):
|
||||
job = self.batch()
|
||||
releases = {s: dict(installed=True, status='update_available', can_install=True) for s in job['stages']}
|
||||
releases['stage_z2m'] = dict(installed=False, status='not_installed', can_install=True)
|
||||
releases['stage_wifi'] = dict(installed=True, status='latest', can_install=False)
|
||||
with mock.patch.object(versions, 'snapshot', return_value={'stages': releases}), mock.patch.object(versions, 'start_install') as start:
|
||||
versions.start_install_all(list(reversed(job['stages'])), COMMIT, [])
|
||||
start.assert_called_once_with('stage_mqtt', COMMIT, batch=job['stages'])
|
||||
for invalid in [[], ['stage_mqtt'], job['stages'] + ['stage_z2m'], job['stages'] * 2, [None], 'stage_ui']:
|
||||
with self.assertRaises(ValueError): versions.start_install_all(invalid, COMMIT, [])
|
||||
|
||||
def test_worker_runs_in_order_and_stops_at_first_failure(self):
|
||||
job = self.batch()
|
||||
root = Path(versions.read_json(versions.CONFIG)['checkout'])
|
||||
root.mkdir()
|
||||
(root / 'stage-releases.json').write_text(json.dumps(self.catalog))
|
||||
for failing in [None, 'stage_ui']:
|
||||
versions.delivery.write_json(versions.STATE / 'job.json', job)
|
||||
called = []
|
||||
def run(args, **kwargs):
|
||||
stage = args[-1]; called.append(stage)
|
||||
if stage == failing: raise subprocess.CalledProcessError(1, args)
|
||||
versions.delivery.write_json(versions.STATE / (stage + '.json'), dict(
|
||||
commit=COMMIT, version=job['versions'][stage], job_id=job['unit']))
|
||||
with mock.patch.object(versions.delivery, 'bootstrap'), mock.patch.object(versions.subprocess, 'run', side_effect=run):
|
||||
if failing:
|
||||
with self.assertRaises(subprocess.CalledProcessError): versions.install(job['stage'], COMMIT)
|
||||
else: versions.install(job['stage'], COMMIT)
|
||||
status = versions.read_json(versions.STATE / 'job.json')
|
||||
self.assertEqual(job['stages'][:2] if failing else job['stages'], called)
|
||||
self.assertEqual(['stage_mqtt'] if failing else job['stages'], status['completed'])
|
||||
self.assertEqual('failed' if failing else 'success', status['state'])
|
||||
|
||||
def test_reconciliation_requires_every_receipt_and_log_is_shared(self):
|
||||
job = self.batch()
|
||||
for stage in job['stages']:
|
||||
versions.delivery.write_json(versions.STATE / (stage + '.json'), dict(
|
||||
commit=COMMIT, version=job['versions'][stage], job_id=job['unit']))
|
||||
with mock.patch.object(versions.subprocess, 'run', return_value=mock.Mock(stdout='inactive')):
|
||||
versions.delivery.write_json(versions.STATE / 'job.json', job)
|
||||
self.assertEqual(job['stages'], versions.job_status()['completed'])
|
||||
(versions.STATE / 'stage_ui.json').unlink()
|
||||
versions.delivery.write_json(versions.STATE / 'job.json', job)
|
||||
self.assertEqual('interrupted', versions.job_status()['state'])
|
||||
(versions.STATE / 'install.log').write_text('batch output')
|
||||
for stage in job['stages']:
|
||||
self.assertEqual(['batch output'], versions.installation_log(stage, job['unit'])['lines'])
|
||||
with self.assertRaises(ValueError): versions.installation_log('stage_z2m', job['unit'])
|
||||
|
|
@ -14,7 +14,7 @@
|
|||
"version": "1.0.0"
|
||||
},
|
||||
"stage_ui": {
|
||||
"version": "3.1.17"
|
||||
"version": "3.1.18"
|
||||
},
|
||||
"stage_avahi": {
|
||||
"version": "1.0.0"
|
||||
|
|
|
|||
|
|
@ -230,6 +230,26 @@ class RecoveryTest(unittest.TestCase):
|
|||
self.assertEqual('complete', json.loads(r.REQUEST.read_text())['status'])
|
||||
system.assert_called_once_with(['systemctl', 'disable', r.RESUME])
|
||||
|
||||
def test_batch_recovery_waits_for_all_stage_receipts(self):
|
||||
receipts = self.root / 'receipts'
|
||||
receipts.mkdir()
|
||||
job = dict(stages=['stage_mqtt', 'stage_env'], unit='batch', commit='a'*40,
|
||||
versions={'stage_mqtt':'1.0.1', 'stage_env':'1.0.3'})
|
||||
request = json.loads(r.REQUEST.read_text())
|
||||
request.update(status='resuming', job=job)
|
||||
r.save(request)
|
||||
real_path = Path
|
||||
def path(value):
|
||||
return receipts if value == '/var/lib/iomatex/stages' else real_path(value)
|
||||
with patch.object(r, 'Path', side_effect=path):
|
||||
for stage in job['stages']:
|
||||
r.finish(self.root, False)
|
||||
self.assertEqual('resuming', json.loads(r.REQUEST.read_text())['status'])
|
||||
(receipts / (stage + '.json')).write_text(json.dumps(dict(
|
||||
job_id=job['unit'], commit=job['commit'], version=job['versions'][stage])))
|
||||
r.finish(self.root, False)
|
||||
self.assertEqual('complete', json.loads(r.REQUEST.read_text())['status'])
|
||||
|
||||
def test_resume_refuses_readonly_mount_after_verification(self):
|
||||
request = json.loads(r.REQUEST.read_text())
|
||||
request.update(status='verified')
|
||||
|
|
|
|||
|
|
@ -352,18 +352,31 @@ def resume():
|
|||
with lock_path.open('a') as lock, (BASE / 'resume.log').open('a') as log:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
env['IOMATEX_INSTALL_LOCK_FD'] = str(lock.fileno())
|
||||
result = subprocess.run(['bash', str(root / 'local_installer.sh'), str(root),
|
||||
'--non-interactive', '--reset-state', '--only', ','.join(request['stages'])],
|
||||
stdout=log, stderr=subprocess.STDOUT, env=env, pass_fds=(lock.fileno(),))
|
||||
if job and job.get('stages'):
|
||||
# Reuse the same ordered batch worker after storage recovery.
|
||||
sys.path.insert(0, str(root / 'offline'))
|
||||
import stage_versions
|
||||
job = {**job, 'phase': 'storage_recovery'}
|
||||
with (stage_versions.STATE / 'install.log').open('a') as batch_log:
|
||||
completed = stage_versions.run_stages(root, job['stages'], job['commit'], job, lock.fileno(), output=batch_log)
|
||||
job = {**job, 'completed': completed}
|
||||
result = subprocess.CompletedProcess([], 0)
|
||||
else:
|
||||
result = subprocess.run(['bash', str(root / 'local_installer.sh'), str(root),
|
||||
'--non-interactive', '--reset-state', '--only', ','.join(request['stages'])],
|
||||
stdout=log, stderr=subprocess.STDOUT, env=env, pass_fds=(lock.fileno(),))
|
||||
request['status'] = 'complete' if result.returncode == 0 else 'failed'
|
||||
if result.returncode == 0 and 'POST_REBOOT_PENDING=1' in (root / 'local_installer.state').read_text():
|
||||
request['status'] = 'installer_reboot_pending'
|
||||
if job:
|
||||
# Receipt is written only after the selected stage has passed validation.
|
||||
receipts = Path('/var/lib/iomatex/stages')
|
||||
receipt = json.loads((receipts / (job['stage'] + '.json')).read_text())
|
||||
success = (result.returncode == 0 and receipt.get('commit') == job['commit']
|
||||
and receipt.get('version') == job['version'] and receipt.get('job_id') == job['unit'])
|
||||
success = result.returncode == 0
|
||||
for stage in job.get('stages') or [job['stage']]:
|
||||
receipt = json.loads((receipts / (stage + '.json')).read_text())
|
||||
expected = job.get('versions', {}).get(stage, job['version'])
|
||||
success = success and (receipt.get('commit') == job['commit']
|
||||
and receipt.get('version') == expected and receipt.get('job_id') == job['unit'])
|
||||
atomic(receipts / 'job.json', json.dumps({**job, 'state': 'success' if success else 'failed',
|
||||
'finished_at': int(time.time())}) + '\n')
|
||||
if result.returncode:
|
||||
|
|
@ -381,6 +394,15 @@ def finish(root, failed):
|
|||
request = json.loads(REQUEST.read_text())
|
||||
if request.get('root') != str(Path(root).resolve()) or request.get('status') not in ('resuming', 'installer_reboot_pending'):
|
||||
return
|
||||
if not failed and (request.get('job') or {}).get('stages'):
|
||||
# Each selected installer invokes finish; recovery ends only after the batch.
|
||||
job = request['job']
|
||||
for stage in job['stages']:
|
||||
receipt_path = Path('/var/lib/iomatex/stages') / (stage + '.json')
|
||||
receipt = json.loads(receipt_path.read_text()) if receipt_path.exists() else {}
|
||||
if (receipt.get('job_id') != job['unit'] or receipt.get('commit') != job['commit']
|
||||
or receipt.get('version') != job['versions'][stage]):
|
||||
return
|
||||
request.update(status='failed' if failed else 'complete', finished_at=int(time.time()))
|
||||
if failed:
|
||||
request['error'] = 'Installer failed after storage recovery; see resume.log and local_installer.log'
|
||||
|
|
|
|||
|
|
@ -54,7 +54,7 @@ APP_DIR = "/opt/iomatex-console"
|
|||
PUBLIC_DIR = os.path.join(APP_DIR, "public")
|
||||
PROVIDERS_DIR = os.path.join(APP_DIR, "providers.d")
|
||||
CONFIG_PATH = "/etc/iomatex/console.json"
|
||||
UI_VERSION = "V 3.1.17"
|
||||
UI_VERSION = "V 3.1.18"
|
||||
STORAGE_HEALTH_COMMAND = "/usr/local/sbin/iomatex-storage-health"
|
||||
ZONEINFO_ROOT = "/usr/share/zoneinfo"
|
||||
|
||||
|
|
@ -3581,7 +3581,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||
except Exception as exc:
|
||||
self.send_json({"ok": False, "error": str(exc)}, code=503)
|
||||
return
|
||||
if parsed.path in ("/api/stages/check", "/api/stages/install"):
|
||||
if parsed.path in ("/api/stages/check", "/api/stages/install", "/api/stages/install-all"):
|
||||
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
|
||||
|
|
@ -3596,7 +3596,10 @@ class Handler(BaseHTTPRequestHandler):
|
|||
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"))
|
||||
if parsed.path == "/api/stages/install-all":
|
||||
job = stage_versions.start_install_all(payload.get("stages"), payload.get("commit"), build_status_payload().get("services", []))
|
||||
else:
|
||||
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)
|
||||
|
|
|
|||
|
|
@ -23,9 +23,9 @@ class StageUpdateApiTest(unittest.TestCase):
|
|||
patch = mock.patch.object(app.Handler, 'log_message')
|
||||
patch.start(); self.addCleanup(patch.stop)
|
||||
|
||||
def post(self, payload, content_type='application/json'):
|
||||
def post(self, payload, content_type='application/json', path='/api/stages/install'):
|
||||
connection = http.client.HTTPConnection(*self.server.server_address)
|
||||
connection.request('POST', '/api/stages/install', json.dumps(payload), {'Content-Type':content_type})
|
||||
connection.request('POST', path, json.dumps(payload), {'Content-Type':content_type})
|
||||
response = connection.getresponse()
|
||||
body = json.loads(response.read())
|
||||
connection.close()
|
||||
|
|
@ -48,4 +48,16 @@ class StageUpdateApiTest(unittest.TestCase):
|
|||
self.assertEqual(202, self.post({'stage':'stage_z2m','commit':'a'*40,'confirmed':True})[0])
|
||||
start.assert_called_once_with('stage_z2m','a'*40)
|
||||
|
||||
def test_bulk_requires_auth_confirmation_and_shared_selection_owner(self):
|
||||
path = '/api/stages/install-all'
|
||||
payload = {'stages': ['stage_mqtt', 'stage_ui'], 'commit': 'a'*40, 'confirmed': True}
|
||||
with mock.patch.object(app.stage_versions, 'start_install_all', return_value={'state':'queued'}) as start, mock.patch.object(app, 'build_status_payload', return_value={'services': []}):
|
||||
with mock.patch.object(app.Handler, 'auth_session', return_value=None):
|
||||
self.assertEqual(401, self.post(payload, path=path)[0])
|
||||
with mock.patch.object(app.Handler, 'auth_session', return_value={'username':'iomatex'}):
|
||||
self.assertEqual(409, self.post({**payload, 'confirmed':False}, path=path)[0])
|
||||
start.assert_not_called()
|
||||
self.assertEqual(202, self.post(payload, path=path)[0])
|
||||
start.assert_called_once_with(payload['stages'], payload['commit'], [])
|
||||
|
||||
if __name__ == '__main__': unittest.main()
|
||||
|
|
|
|||
|
|
@ -39,5 +39,17 @@ vm.runInContext(owner+handlers,context);
|
|||
assert.match(unavailable,/Check versions/);
|
||||
assert.match(unavailable,/catalog has not been published/);
|
||||
assert.doesNotMatch(unavailable,/>Update</);
|
||||
requests.length=0;
|
||||
const updates=context.state.healthServices.updates;
|
||||
updates.stages={stage_mqtt:{stage:'stage_mqtt',installed:true,status:'update_available',can_install:true,current:'1.0.0',latest:'1.0.1',commit:release.commit}, stage_z2m:release};
|
||||
confirmed=false;
|
||||
await context.window.__updateAllStages();
|
||||
assert.equal(requests.length,0,'bulk cancel never installs');
|
||||
confirmed=true;
|
||||
await context.window.__updateAllStages();
|
||||
assert.deepEqual(requests[0],{url:'/api/stages/install-all',stages:['stage_mqtt'],commit:release.commit,confirmed:true});
|
||||
updates.busy=true;
|
||||
await context.window.__updateAllStages();
|
||||
assert.equal(requests.length,1,'busy prevents duplicate bulk jobs');
|
||||
console.log('Stage update UI: shared renderer, cancel, pinned confirmation and latest state passed');
|
||||
})().catch(error=>{console.error(error);process.exitCode=1;});
|
||||
|
|
|
|||
|
|
@ -2126,5 +2126,5 @@
|
|||
"Critical": "गंभीर",
|
||||
"Wear is a coarse JEDEC estimate. This eMMC does not expose exact power-on hours or write cycles.": "घिसाव एक मोटा JEDEC अनुमान है। यह eMMC सटीक चालू घंटे या लेखन चक्र नहीं बताती।"
|
||||
});
|
||||
Object.assign(window.ConsoleI18n.translations.ru, {"Copy entire log": "Копировать весь лог", "Copied": "Скопировано", "Installation log": "Лог установки", "FFmpeg is required for camera video and snapshots.": "Для видео и снимков камер необходим FFmpeg.", "FFmpeg is missing. The streaming installer stopped before creating the service.": "FFmpeg отсутствует. Установка видеосервиса остановилась до создания службы.", "Installation did not complete. Open the installation log for details.": "Установка не завершена. Откройте лог установки для выяснения причины.", "Installed but unavailable": "Установлен, но не работает", "Showing the last 300 lines (maximum 64 KB).": "Показаны последние 300 строк (не более 64 КБ).", "Installation log is empty": "Лог установки пока пуст"});
|
||||
Object.assign(window.ConsoleI18n.translations.ru, {"Update all": "Обновить всё", "Updates run sequentially and stop on failure. The task continues if this page closes.": "Обновления выполняются последовательно и останавливаются при ошибке. Задача продолжится после закрытия страницы.", "This update will reboot the Edge.": "Это обновление перезагрузит Edge.", "Copy entire log": "Копировать весь лог", "Copied": "Скопировано", "Installation log": "Лог установки", "FFmpeg is required for camera video and snapshots.": "Для видео и снимков камер необходим FFmpeg.", "FFmpeg is missing. The streaming installer stopped before creating the service.": "FFmpeg отсутствует. Установка видеосервиса остановилась до создания службы.", "Installation did not complete. Open the installation log for details.": "Установка не завершена. Откройте лог установки для выяснения причины.", "Installed but unavailable": "Установлен, но не работает", "Showing the last 300 lines (maximum 64 KB).": "Показаны последние 300 строк (не более 64 КБ).", "Installation log is empty": "Лог установки пока пуст"});
|
||||
})();
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@
|
|||
{ mode: "test_by", label: "test.it-screen.by", host: "rest.test.it-screen.by" },
|
||||
{ mode: "custom", label: "Custom", host: "" }
|
||||
];
|
||||
const UI_VERSION = "V 3.1.17";
|
||||
const UI_VERSION = "V 3.1.18";
|
||||
const ITSCREEN_LOG_INITIAL_LINES = 50;
|
||||
const ITSCREEN_LOG_BUFFER_LIMIT = 300;
|
||||
const ITSCREEN_LOG_BATCH_MS = 250;
|
||||
|
|
@ -2440,12 +2440,21 @@
|
|||
return t(labels[release.status] || "Unknown");
|
||||
}
|
||||
|
||||
function availableStageUpdates() {
|
||||
return Object.values(state.healthServices?.updates?.stages || {}).filter(release =>
|
||||
release.installed && release.status === "update_available");
|
||||
}
|
||||
|
||||
function stageInJob(job, stage) {
|
||||
return (job.stages || [job.stage]).includes(stage);
|
||||
}
|
||||
|
||||
function renderStageVersion(card, compact = false) {
|
||||
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 running = ["queued", "running"].includes(job.state) && stageInJob(job, 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")
|
||||
|
|
@ -2465,9 +2474,9 @@
|
|||
${(needsCheck || compact) && !running ? `<button class="actionBtn secondary" type="button" ${updates.checking || updates.busy ? "disabled" : ""} onclick="window.__checkStageVersions()">${esc(t(updates.checking ? "Checking versions..." : "Check versions"))}</button>`
|
||||
: ""}
|
||||
${!needsCheck && release.status !== "latest" && release.status !== "ahead" ? `<button class="actionBtn" type="button" ${release.can_install ? "" : "disabled"} onclick="window.__stageVersion('${esc(card.id)}')">${esc(running ? t("Installing...") : `${action}${release.latest ? ` ${release.latest}` : ""}`)}</button>` : ""}
|
||||
${job.stage === release.stage && job.state ? `<button class="actionBtn secondary" type="button" onclick="window.__stageInstallLog('${esc(release.stage)}', '${esc(job.unit || "")}')">${esc(t("Installation log"))}</button>` : ""}
|
||||
${stageInJob(job, release.stage) && job.state ? `<button class="actionBtn secondary" type="button" onclick="window.__stageInstallLog('${esc(release.stage)}', '${esc(job.unit || "")}')">${esc(t("Installation log"))}</button>` : ""}
|
||||
</div>
|
||||
${job.stage === release.stage && ["failed", "interrupted"].includes(job.state) ? `<div class="banner warn" role="status">${esc(t(job.reason || "Installation did not complete. Open the installation log for details."))}</div>` : ""}
|
||||
${stageInJob(job, release.stage) && ["failed", "interrupted"].includes(job.state) ? `<div class="banner warn" role="status">${esc(t(job.reason || "Installation did not complete. Open the installation log for details."))}</div>` : ""}
|
||||
${!release.can_install && reason ? `<div class="formHint" role="status">${esc(reason)}</div>` : ""}
|
||||
</div>`;
|
||||
}
|
||||
|
|
@ -2773,10 +2782,11 @@
|
|||
<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>
|
||||
<button class="actionBtn" type="button" ${updates.checking || updates.busy || !availableStageUpdates().length || availableStageUpdates().some(release => !release.can_install) ? "disabled" : ""} onclick="window.__updateAllStages()">${esc(t("Update all"))}${availableStageUpdates().length ? ` (${availableStageUpdates().length})` : ""}</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(updateJob.reason || "Installation did not complete. Open the installation log for details."))}` : ""}</div>` : ""}
|
||||
${updateJob.state ? `<div class="banner ${["failed", "interrupted"].includes(updateJob.state) ? "warn" : ""}" role="status">${esc(t(jobLabels[updateJob.state] || updateJob.state))} · ${esc(updateJob.current_stage || updateJob.stage)} ${esc(updateJob.stages ? `${(updateJob.completed || []).length}/${updateJob.stages.length}` : (updateJob.version || ""))}${["failed", "interrupted"].includes(updateJob.state) ? ` · ${esc(t(updateJob.reason || "Installation did not complete. Open the installation log for details."))}` : ""}</div>` : ""}
|
||||
</div>
|
||||
<div class="cards">${serviceCards.map(renderServiceCard).join("") || `<div class="empty">${esc(t("No service cards available."))}</div>`}</div>
|
||||
</section>
|
||||
|
|
@ -5488,6 +5498,29 @@
|
|||
} catch (error) { showToast("error", error.message); }
|
||||
};
|
||||
|
||||
window.__updateAllStages = async function () {
|
||||
if (state.stageUpdateDialogOpen) return;
|
||||
const updates = state.healthServices?.updates || {};
|
||||
const releases = availableStageUpdates();
|
||||
if (updates.busy || updates.checking || !releases.length || releases.some(item => !item.can_install)) return;
|
||||
const commit = releases[0].commit;
|
||||
if (releases.some(item => item.commit !== commit)) return;
|
||||
state.stageUpdateDialogOpen = true;
|
||||
try {
|
||||
const list = releases.map(item => `${t(item.title)}: ${item.current} → ${item.latest}`).join("; ");
|
||||
const message = `${list}. ${t("Updates run sequentially and stop on failure. The task continues if this page closes.")} ${releases.some(item => item.reboot) ? t("This update will reboot the Edge.") : ""}`;
|
||||
if (!await confirmAction(t("Update all"), message, t("Update all"))) return;
|
||||
await fetchJson("/api/stages/install-all", {
|
||||
method: "POST", headers: {"Content-Type": "application/json"},
|
||||
body: JSON.stringify({stages: releases.map(item => item.stage), 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.__stageInstallLog = async function (stage, unit) {
|
||||
try {
|
||||
const log = await fetchJson(`/api/stages/log?stage=${encodeURIComponent(stage)}&unit=${encodeURIComponent(unit)}&full=1`, {cache: "no-store"});
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@
|
|||
} catch (error) {}
|
||||
})();
|
||||
</script>
|
||||
<link rel="stylesheet" href="/console.css?v=3.1.17&rev=camera-snapshot-1">
|
||||
<link rel="stylesheet" href="/console.css?v=3.1.18&rev=camera-snapshot-1">
|
||||
</head>
|
||||
<body>
|
||||
<main class="shell">
|
||||
|
|
@ -109,7 +109,7 @@
|
|||
</main>
|
||||
<div id="menuBackdrop" class="menuBackdrop" hidden></div>
|
||||
<div id="toastStack" class="toastStack" aria-live="polite" aria-atomic="true"></div>
|
||||
<script src="/console.i18n.js?v=3.1.17&rev=camera-snapshot-1"></script>
|
||||
<script src="/console.js?v=3.1.17&rev=camera-snapshot-1"></script>
|
||||
<script src="/console.i18n.js?v=3.1.18&rev=camera-snapshot-1"></script>
|
||||
<script src="/console.js?v=3.1.18&rev=camera-snapshot-1"></script>
|
||||
</body>
|
||||
</html>
|
||||
|
|
|
|||
|
|
@ -1,3 +1,3 @@
|
|||
{
|
||||
"version": "3.1.17"
|
||||
"version": "3.1.18"
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue