Preserve managed snapshot hotfixes before confirmed Edge updates

This commit is contained in:
Andrei Smaliak 2026-10-07 08:36:51 +02:00
parent 5c2d31cc22
commit 143fcebb2a
11 changed files with 174 additions and 15 deletions

View File

@ -0,0 +1,7 @@
# Edge Console 3.1.20
- Fixed confirmed service updates failing immediately with `Local change in snapshot` after manual Edge hotfixes. The managed installer snapshot now preserves modified tracked files in a verified, root-only sibling backup before replacing them with the selected Git release. Deleted files are recorded, original snapshot metadata is retained, and untracked operator configuration stays in place.
- Backup errors abort before replacing the existing snapshot. Dirty developer Git checkouts, unknown directories, unsafe paths and symlinks remain protected. Standalone bootstrap keeps its explicit local-change guard; automatic preservation is scoped to confirmed Console updates.
- Existing devices whose old updater already refuses its own Console update need a one-time updater helper repair, followed by a normal Console update. The permanent behavior belongs to the shared Git delivery and stage update owners, including Update all.
Validation: reproduced on dev Edge g-box-7e579e52 (14 locally modified installer files; failure at install_iomatex_edge.sh). Regression tests cover backup integrity, permissions, deleted files, preservation of operator configuration, abort on backup failure, subsequent clean checks and path/Git protections.

View File

@ -113,3 +113,19 @@ revisions are 1.0.0 (separate from upstream application versions). Includes the
12px service action spacing and explicit missing-catalog/credential errors. 12px service action spacing and explicit missing-catalog/credential errors.
Publication validation: 14 stage release tests, 8 Git delivery tests, 68 Console Publication validation: 14 stage release tests, 8 Git delivery tests, 68 Console
backend tests and the shared UI interaction test passed. backend tests and the shared UI interaction test passed.
## Locally patched managed snapshots
Confirmed Console updates preserve modified tracked installer files before replacing
an API snapshot (`.iomatex-source.json`). Backups live beside the checkout as
`.Iomatex_OS-local-changes-*`, mode 0700. `backup.json` retains the original source
manifest, deleted-file records and SHA-256 hashes of saved files under `files/`.
The installation log identifies the backup directory. Backup failure stops the
update before snapshot replacement. Operator configuration outside the tracked
snapshot remains unchanged. Dirty `.git` working trees are still refused.
An older updater that fails before downloading a new snapshot cannot repair itself
through the same button: preserve its installed helper files, replace the shared
`git_delivery.py` and `stage_versions.py` helpers with verified files from the
published release, then perform the normal Console update. Do not mark an old
snapshot clean by rewriting its hashes or discard manual changes with git reset.

View File

@ -91,19 +91,77 @@ def platform_check():
def is_payload(path): def is_payload(path):
return path.endswith(('.deb', '.tar.gz')) or path == 'stage_itscreen/itscreen' return path.endswith(('.deb', '.tar.gz')) or path == 'stage_itscreen/itscreen'
def check_existing(dest): def snapshot_changes(dest):
changes = []
source = json.loads((dest / '.iomatex-source.json').read_text())
for entry in source['files']:
relative = safe_path(entry['path'])
p = dest / relative
if p.is_symlink() or not p.resolve().is_relative_to(dest.resolve()):
raise ValueError('Preserve snapshot symlink before updating: ' + relative)
if p.exists() and not p.is_file():
raise ValueError('Snapshot file replaced by directory: ' + relative)
if not p.exists():
changes.append({'path': relative, 'deleted': True})
elif blob_hash(p.read_bytes()) != entry['sha']:
changes.append({'path': relative, 'deleted': False})
return changes
def check_existing(dest, preserve_local_changes=False):
if (dest / '.git').exists(): if (dest / '.git').exists():
changed = subprocess.check_output(['git', '-C', str(dest), 'status', '--porcelain', '--untracked-files=no'], text=True) changed = subprocess.check_output(['git', '-C', str(dest), 'status', '--porcelain', '--untracked-files=no'], text=True)
if changed.strip(): if changed.strip():
raise ValueError('Existing checkout has tracked local changes; preserve them before updating') raise ValueError('Existing checkout has tracked local changes; preserve them before updating')
elif (dest / '.iomatex-source.json').exists(): elif (dest / '.iomatex-source.json').exists():
for entry in json.loads((dest / '.iomatex-source.json').read_text())['files']: changes = snapshot_changes(dest)
p = dest / entry['path'] if changes and not preserve_local_changes:
if p.is_file() and blob_hash(p.read_bytes()) != entry['sha']: raise ValueError('Local change in snapshot: ' + changes[0]['path'])
raise ValueError('Local change in snapshot: ' + entry['path'])
elif dest.exists() and any(dest.iterdir()): elif dest.exists() and any(dest.iterdir()):
raise ValueError('Refusing to replace an unidentified nonempty directory') raise ValueError('Refusing to replace an unidentified nonempty directory')
def preserve_snapshot_changes(dest):
"""Retain local hotfixes outside the managed snapshot before a confirmed update."""
changes = snapshot_changes(dest)
if not changes:
return None
backup = Path(tempfile.mkdtemp(prefix='.' + dest.name + '-local-changes-', dir=dest.parent))
try:
records = []
for change in changes:
record = dict(change)
if not change['deleted']:
source = dest / change['path']
data = source.read_bytes()
target = backup / 'files' / change['path']
target.parent.mkdir(parents=True, exist_ok=True)
with target.open('wb') as stream:
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
shutil.copystat(source, target)
record['sha256'] = hashlib.sha256(data).hexdigest()
if hashlib.sha256(target.read_bytes()).hexdigest() != record['sha256']:
raise RuntimeError('Local change backup verification failed')
records.append(record)
write_json(backup / 'backup.json', {
'source': json.loads((dest / '.iomatex-source.json').read_text()),
'changes': records, 'created_at': int(time.time()), 'checkout': str(dest)}, 0o600)
with (backup / 'backup.json').open('rb') as manifest_file:
os.fsync(manifest_file.fileno())
for directory in [*sorted((p for p in backup.rglob('*') if p.is_dir()), key=lambda p: len(p.parts), reverse=True), backup, backup.parent]:
fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
try:
os.fsync(fd)
finally:
os.close(fd)
print(f'Preserved {len(records)} local installer changes in {backup}', flush=True)
return backup
except BaseException:
shutil.rmtree(backup)
raise
def transient_download_error(error): def transient_download_error(error):
if isinstance(error, urllib.error.HTTPError): if isinstance(error, urllib.error.HTTPError):
return error.code in (408, 429, 500, 502, 503, 504) return error.code in (408, 429, 500, 502, 503, 504)
@ -217,7 +275,7 @@ def recovery_gate(repo, branch, commit, auth, files, stages, job=None):
raise RecoveryPending('Offline userdata recovery queued; update is pending, not complete') raise RecoveryPending('Offline userdata recovery queued; update is pending, not complete')
def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery_job=None): def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery_job=None, preserve_local_changes=False):
platform_check() platform_check()
repo = repo_name(url) repo = repo_name(url)
requested = Path(checkout) requested = Path(checkout)
@ -244,11 +302,14 @@ def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery
files.append({k: item[k] for k in ('path', 'sha', 'mode')}) files.append({k: item[k] for k in ('path', 'sha', 'mode')})
stages = recovery_stages or os.environ.get('IOMATEX_RECOVERY_STAGES', '').split(',') stages = recovery_stages or os.environ.get('IOMATEX_RECOVERY_STAGES', '').split(',')
recovery_gate(repo, branch, commit, auth, files, [stage for stage in stages if stage], recovery_job) recovery_gate(repo, branch, commit, auth, files, [stage for stage in stages if stage], recovery_job)
check_existing(dest) check_existing(dest, preserve_local_changes=preserve_local_changes)
if (dest / '.git').exists(): if (dest / '.git').exists():
origin = subprocess.check_output(['git', '-C', str(dest), 'remote', 'get-url', 'origin'], text=True).strip() origin = subprocess.check_output(['git', '-C', str(dest), 'remote', 'get-url', 'origin'], text=True).strip()
if repo_name(origin) != repo: if repo_name(origin) != repo:
raise ValueError('Existing checkout origin mismatch') raise ValueError('Existing checkout origin mismatch')
elif (dest / '.iomatex-source.json').exists():
if json.loads((dest / '.iomatex-source.json').read_text()).get('repo') != repo:
raise ValueError('Existing snapshot origin mismatch')
dest.parent.mkdir(parents=True, exist_ok=True) dest.parent.mkdir(parents=True, exist_ok=True)
with tempfile.TemporaryDirectory(prefix='.iomatex-install-', dir=dest.parent) as tmp: with tempfile.TemporaryDirectory(prefix='.iomatex-install-', dir=dest.parent) as tmp:
staged = Path(tmp) / 'snapshot' staged = Path(tmp) / 'snapshot'
@ -261,6 +322,8 @@ def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery
write_json(staged / '.iomatex-source.json', source) write_json(staged / '.iomatex-source.json', source)
# Validate all metadata before replacing an existing installation snapshot. # Validate all metadata before replacing an existing installation snapshot.
catalog(staged) catalog(staged)
if preserve_local_changes and (dest / '.iomatex-source.json').exists() and not (dest / '.git').exists():
preserve_snapshot_changes(dest)
previous = Path(tmp) / 'previous' previous = Path(tmp) / 'previous'
if dest.exists(): if dest.exists():
# Keep untracked operator files/state/logs, never carry the old Git pack or payloads. # Keep untracked operator files/state/logs, never carry the old Git pack or payloads.

View File

@ -353,7 +353,7 @@ def install(stage, commit):
cfg = read_json(CONFIG) cfg = read_json(CONFIG)
delivery.write_json(STATE / 'job.json', {**job, 'state': 'running'}) delivery.write_json(STATE / 'job.json', {**job, 'state': 'running'})
delivery.bootstrap('https://' + delivery.HOST + '/' + cfg['repo'] + '.git', delivery.bootstrap('https://' + delivery.HOST + '/' + cfg['repo'] + '.git',
cfg['branch'], cfg['checkout'], commit=commit, recovery_stages=stages, recovery_job=job) cfg['branch'], cfg['checkout'], commit=commit, recovery_stages=stages, recovery_job=job, preserve_local_changes=True)
root = Path(cfg['checkout']) root = Path(cfg['checkout'])
completed = run_stages(root, stages, commit, job, lock.fileno()) completed = run_stages(root, stages, commit, job, lock.fileno())
if job.get('stages'): if job.get('stages'):

View File

@ -0,0 +1,72 @@
import hashlib
import io
import json
from pathlib import Path
import tempfile
import unittest
from unittest.mock import patch
import git_delivery as d
class SnapshotUpdateTest(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.parent = Path(self.tmp.name)
self.root = self.parent / 'installer'
self.root.mkdir()
self.entry = {'path': 'install.sh', 'sha': d.blob_hash(b'original'), 'mode': '100755'}
self.source = {'repo': 'An-J/Iomatex_OS', 'commit': 'a'*40, 'files':[self.entry]}
(self.root / '.iomatex-source.json').write_text(json.dumps(self.source))
(self.root / 'install.sh').write_bytes(b'local hotfix')
(self.root / 'operator.conf').write_bytes(b'operator configuration')
def bootstrap(self):
entry = {**self.entry, 'sha':d.blob_hash(b'new release'), 'type':'blob'}
with patch.object(d, 'platform_check'), patch.object(d, 'auth_from_env', return_value={}), \
patch.object(d, 'open_git', return_value=io.StringIO(json.dumps({'tree':[entry]}))), \
patch.object(d, 'recovery_gate'), patch.object(d, 'catalog'), \
patch.object(d, 'snapshot_bytes', return_value=b'new release'), \
patch.object(d, 'AUTH', self.parent / 'auth.json'), \
patch.object(d.subprocess, 'run'):
d.bootstrap('https://git.it-screen.com/An-J/Iomatex_OS.git', 'ci-cd', str(self.root),
commit='b'*40, preserve_local_changes=True)
def test_confirmed_update_preserves_hotfix_and_operator_files(self):
self.bootstrap()
self.assertEqual(b'new release', (self.root/'install.sh').read_bytes())
self.assertEqual(b'operator configuration', (self.root/'operator.conf').read_bytes())
backup, = self.parent.glob('.installer-local-changes-*')
self.assertEqual(0o700, backup.stat().st_mode & 0o777)
self.assertEqual(b'local hotfix', (backup/'files/install.sh').read_bytes())
manifest = json.loads((backup/'backup.json').read_text())
self.assertEqual(self.source, manifest['source'])
self.assertEqual(hashlib.sha256(b'local hotfix').hexdigest(),manifest['changes'][0]['sha256'])
d.check_existing(self.root) # Further updates now see a clean snapshot.
def test_backup_failure_never_replaces_existing_snapshot(self):
with patch.object(d.os, 'fsync', side_effect=OSError('disk full')):
with self.assertRaises(OSError): self.bootstrap()
self.assertEqual(b'local hotfix',(self.root/'install.sh').read_bytes())
self.assertEqual([],list(self.parent.glob('.installer-local-changes-*')))
def test_deleted_file_is_recorded_before_release_restores_it(self):
(self.root/'install.sh').unlink()
self.bootstrap()
backup, = self.parent.glob('.installer-local-changes-*')
self.assertTrue(json.loads((backup/'backup.json').read_text())['changes'][0]['deleted'])
self.assertEqual(b'new release',(self.root/'install.sh').read_bytes())
def test_paths_and_symlinks_cannot_escape_snapshot(self):
(self.root/'install.sh').unlink()
(self.root/'install.sh').symlink_to(self.parent/'outside')
with self.assertRaisesRegex(ValueError,'symlink'): d.check_existing(self.root, True)
self.source['files'][0]['path']='../outside'
(self.root/'.iomatex-source.json').write_text(json.dumps(self.source))
with self.assertRaisesRegex(ValueError,'Unsafe'): d.check_existing(self.root, True)
def test_developer_git_checkout_still_requires_preserving_edits(self):
(self.root/'.git').mkdir()
with patch.object(d.subprocess,'check_output',return_value=' M install.sh'):
with self.assertRaisesRegex(ValueError,'tracked local changes'):d.check_existing(self.root,True)
if __name__ == '__main__': unittest.main()

View File

@ -163,6 +163,7 @@ class StageVersionsTest(unittest.TestCase):
with mock.patch.object(versions.delivery, 'bootstrap') as boot, mock.patch.object(versions.subprocess, 'run', side_effect=subprocess.CalledProcessError(1, 'bash')) as run: 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) with self.assertRaises(subprocess.CalledProcessError): versions.install('stage_z2m', COMMIT)
self.assertEqual(COMMIT, boot.call_args.kwargs['commit']) self.assertEqual(COMMIT, boot.call_args.kwargs['commit'])
self.assertTrue(boot.call_args.kwargs['preserve_local_changes'])
self.assertEqual(['--only','stage_z2m'], run.call_args.args[0][-2:]) self.assertEqual(['--only','stage_z2m'], run.call_args.args[0][-2:])
self.assertEqual('failed', versions.read_json(versions.STATE / 'job.json')['state']) self.assertEqual('failed', versions.read_json(versions.STATE / 'job.json')['state'])
self.assertFalse((versions.STATE / 'stage_z2m.json').exists()) self.assertFalse((versions.STATE / 'stage_z2m.json').exists())

View File

@ -14,7 +14,7 @@
"version": "1.0.0" "version": "1.0.0"
}, },
"stage_ui": { "stage_ui": {
"version": "3.1.19" "version": "3.1.20"
}, },
"stage_avahi": { "stage_avahi": {
"version": "1.0.0" "version": "1.0.0"

View File

@ -55,7 +55,7 @@ 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 3.1.19" UI_VERSION = "V 3.1.20"
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"

View File

@ -49,7 +49,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 3.1.19"; const UI_VERSION = "V 3.1.20";
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;

View File

@ -23,7 +23,7 @@
} catch (error) {} } catch (error) {}
})(); })();
</script> </script>
<link rel="stylesheet" href="/console.css?v=3.1.19&amp;rev=camera-snapshot-1"> <link rel="stylesheet" href="/console.css?v=3.1.20&amp;rev=camera-snapshot-1">
</head> </head>
<body> <body>
<main class="shell"> <main class="shell">
@ -109,7 +109,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=3.1.19&amp;rev=camera-snapshot-1"></script> <script src="/console.i18n.js?v=3.1.20&amp;rev=camera-snapshot-1"></script>
<script src="/console.js?v=3.1.19&amp;rev=camera-snapshot-1"></script> <script src="/console.js?v=3.1.20&amp;rev=camera-snapshot-1"></script>
</body> </body>
</html> </html>

View File

@ -1,3 +1,3 @@
{ {
"version": "3.1.19" "version": "3.1.20"
} }