Add backed-up offline userdata recovery before updates (stage_env 1.0.3)
This commit is contained in:
parent
e7996f0884
commit
26f75a9314
|
|
@ -0,0 +1,19 @@
|
|||
# stage_env 1.0.3
|
||||
|
||||
- Updates detect damaged `/userdata` before reading or replacing the old installer
|
||||
snapshot. A verified snapshot and the selected stages are saved on the system
|
||||
filesystem for automatic recovery and continuation after reboot.
|
||||
- Offline preparation checks partition identity and mount state, saves and
|
||||
verifies a full compressed image, repairs ext4, enables journaling, and validates
|
||||
the filesystem before allowing the update to continue. Unresolved preen errors
|
||||
permit one full repair only with the verified image retained.
|
||||
- Failed or interrupted recovery does not automatically retry, format the device,
|
||||
or claim a successful installation. Root-only diagnostics and backups remain
|
||||
under `/var/lib/iomatex/storage`.
|
||||
- Requires the current installer entrypoint and space for the snapshot, compressed
|
||||
image and a 512 MiB reserve outside userdata. Physical failures and insufficient
|
||||
backup space still require intervention.
|
||||
- Validation: disposable ext4 image with a deleted inode reference, preserved
|
||||
control file, backup verification, safety/continuation regression tests,
|
||||
shell syntax and generated systemd unit validation. Hardware boot validation
|
||||
on the affected Edge remains outstanding.
|
||||
|
|
@ -60,6 +60,7 @@ with opener.open(urllib.request.Request(base + 'branches/' + urllib.parse.quote(
|
|||
with opener.open(urllib.request.Request(base + 'raw/offline/git_delivery.py?ref=' + commit, headers=headers), timeout=120) as r:
|
||||
pathlib.Path(destination).write_bytes(r.read())
|
||||
PYTHON
|
||||
export IOMATEX_RECOVERY_STAGES="$STAGES"
|
||||
python3 "$work/git_delivery.py" bootstrap "$GIT_URL" "$GIT_BRANCH" "$CHECKOUT_DIR"
|
||||
unset IOMATEX_GIT_USERNAME IOMATEX_GIT_PASSWORD
|
||||
rm -rf "$work"
|
||||
|
|
|
|||
|
|
@ -1483,6 +1483,9 @@ if [[ "$RESUME_POST_REBOOT" -eq 1 ]]; then
|
|||
FROM_STAGE="${FROM_STAGE:-$(resolve_resume_stage || true)}"
|
||||
if [[ -z "$FROM_STAGE" ]]; then
|
||||
log "No remaining selected stages after reboot; cleaning continuation state"
|
||||
if [[ -f "$PROJECT_DIR/stage_env/userdata_recovery.py" ]]; then
|
||||
python3 "$PROJECT_DIR/stage_env/userdata_recovery.py" finish --root "$PROJECT_DIR"
|
||||
fi
|
||||
cleanup_post_reboot_unit
|
||||
record_summary_from_state
|
||||
print_summary
|
||||
|
|
@ -1572,6 +1575,14 @@ done
|
|||
record_summary_from_state
|
||||
print_summary
|
||||
|
||||
if [[ -f "$PROJECT_DIR/stage_env/userdata_recovery.py" ]]; then
|
||||
recovery_result=()
|
||||
if [[ "$RUN_FAILED" -ne 0 || "${#FAILED_STAGES[@]}" -gt 0 ]]; then
|
||||
recovery_result=(--failed)
|
||||
fi
|
||||
python3 "$PROJECT_DIR/stage_env/userdata_recovery.py" finish --root "$PROJECT_DIR" "${recovery_result[@]}"
|
||||
fi
|
||||
|
||||
if [[ "$RUN_FAILED" -ne 0 || "${#FAILED_STAGES[@]}" -gt 0 ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
|
|
|||
|
|
@ -86,3 +86,27 @@ sudo bash /userdata/Iomatex_OS/stage_ui/ui_installer.sh
|
|||
Транспорт использует штатный
|
||||
[протокол APT methods](https://sources.debian.org/src/apt/2.2.4/doc/method.dbk/).
|
||||
История проверок — `offline/TEST_REPORT_20260914.md`.
|
||||
|
||||
## Обновление старого Edge с ошибками `/userdata`
|
||||
|
||||
Используйте актуальный `install_iomatex_edge.sh`. До замены файлов установщик
|
||||
проверит `/userdata`. Если обнаружено повреждение ext4, он скачает проверенный
|
||||
набор скриптов на системный раздел, сохранит выбранные стадии и перезагрузит
|
||||
Edge для автоматического восстановления до монтирования `/userdata`.
|
||||
|
||||
Перед исправлением создаётся и проверяется полная сжатая копия раздела на
|
||||
системном разделе. После исправления, включения журнала и повторной проверки
|
||||
установка продолжится автоматически. Во время восстановления питание отключать
|
||||
нельзя. Этот сценарий может потребовать дополнительную перезагрузку перед
|
||||
обычным этапом `stage_env`.
|
||||
|
||||
Для копии и установщика должно хватать места вне `/userdata`, с остатком не
|
||||
менее 512 МиБ. Если места нет, чтение повреждённого накопителя невозможно или
|
||||
исправление не прошло проверку, установка остановится с диагностикой, без
|
||||
форматирования и бесконечных повторов. Неудачная попытка требует разбора
|
||||
сохранённого состояния; простой повтор запуска не запускает ремонт заново.
|
||||
|
||||
Состояние: `/var/lib/iomatex/storage/recovery.json`. Логи и резервная копия
|
||||
находятся рядом, в каталоге попытки, указанном в этом файле. Старый snapshot
|
||||
в `/userdata/Iomatex_OS` не удаляется; после такого восстановления рабочий
|
||||
установщик может находиться в `/var/lib/iomatex/storage/installer-*`.
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import base64
|
|||
from concurrent.futures import ThreadPoolExecutor
|
||||
import fcntl
|
||||
import gzip
|
||||
import importlib.util
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
|
|
@ -111,18 +112,60 @@ def materialize_file(repo, commit, auth, entry, existing, staged):
|
|||
p.write_bytes(data)
|
||||
p.chmod(int(entry['mode'][-3:], 8))
|
||||
|
||||
def bootstrap(url, branch, checkout, commit=None):
|
||||
class RecoveryPending(Exception):
|
||||
"""Boot recovery owns continuation; callers must not install or report success."""
|
||||
|
||||
|
||||
def recovery_gate(repo, branch, commit, auth, files, stages, job=None):
|
||||
entry = next((e for e in files if e['path'] == 'stage_env/userdata_recovery.py'), None)
|
||||
if entry is None:
|
||||
return # Older pinned releases do not contain this recovery contract.
|
||||
with tempfile.TemporaryDirectory(prefix='iomatex-storage-probe-') as folder:
|
||||
folder = Path(folder)
|
||||
materialize_file(repo, commit, auth, entry, folder / 'absent', folder)
|
||||
spec = importlib.util.spec_from_file_location('iomatex_userdata_recovery', folder / entry['path'])
|
||||
recovery = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(recovery)
|
||||
report = recovery.inspect()
|
||||
if not report or not report['needed']:
|
||||
return
|
||||
if not stages:
|
||||
raise RuntimeError('Damaged userdata detected. Download the current install_iomatex_edge.sh and run it again.')
|
||||
recovery.storage_directory(report['device'])
|
||||
if recovery.REQUEST.exists():
|
||||
previous = json.loads(recovery.REQUEST.read_text())
|
||||
if previous.get('status') not in ('complete', 'installer_reboot_pending'):
|
||||
raise RuntimeError('Storage recovery already pending or failed; see ' + str(recovery.REQUEST))
|
||||
# Fresh, verified snapshot on root: never read/replace the corrupt checkout.
|
||||
root = Path(tempfile.mkdtemp(prefix='installer-', dir=recovery.BASE))
|
||||
try:
|
||||
print('Fetching verified recovery installer onto the system filesystem...', flush=True)
|
||||
def download(item):
|
||||
if shutil.disk_usage(root).free < recovery.RESERVE:
|
||||
raise RuntimeError('Not enough system disk space for recovery installer')
|
||||
materialize_file(repo, commit, auth, item, root / 'absent', root)
|
||||
with ThreadPoolExecutor(max_workers=6) as pool:
|
||||
list(pool.map(download, files))
|
||||
write_json(root / '.iomatex-source.json',
|
||||
{'repo': repo, 'branch': branch, 'commit': commit, 'files': files})
|
||||
catalog(root)
|
||||
write_json(AUTH, auth, 0o600)
|
||||
recovery.arm(root, stages, report, job)
|
||||
except Exception:
|
||||
# Keep evidence and snapshots once a boot recovery request exists.
|
||||
if not recovery.REQUEST.exists():
|
||||
shutil.rmtree(root)
|
||||
raise
|
||||
raise RecoveryPending('Offline userdata recovery queued; update is pending, not complete')
|
||||
|
||||
|
||||
def bootstrap(url, branch, checkout, commit=None, recovery_stages=None, recovery_job=None):
|
||||
platform_check()
|
||||
repo = repo_name(url)
|
||||
requested = Path(checkout)
|
||||
dest = requested.resolve()
|
||||
if not requested.is_absolute() or len(dest.parts) < 3 or requested.is_symlink():
|
||||
raise ValueError('Use a dedicated absolute installer subdirectory')
|
||||
check_existing(dest)
|
||||
if (dest / '.git').exists():
|
||||
origin = subprocess.check_output(['git', '-C', str(dest), 'remote', 'get-url', 'origin'], text=True).strip()
|
||||
if repo_name(origin) != repo:
|
||||
raise ValueError('Existing checkout origin mismatch')
|
||||
auth = auth_from_env()
|
||||
if commit is None:
|
||||
with open_git(repo, 'branches/' + urllib.parse.quote(branch, safe=''), auth) as r:
|
||||
|
|
@ -141,6 +184,13 @@ def bootstrap(url, branch, checkout, commit=None):
|
|||
if item['type'] != 'blob' or item['mode'] not in ('100644', '100755'):
|
||||
raise ValueError('Unsupported Git tree member: ' + path)
|
||||
files.append({k: item[k] for k in ('path', 'sha', 'mode')})
|
||||
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)
|
||||
check_existing(dest)
|
||||
if (dest / '.git').exists():
|
||||
origin = subprocess.check_output(['git', '-C', str(dest), 'remote', 'get-url', 'origin'], text=True).strip()
|
||||
if repo_name(origin) != repo:
|
||||
raise ValueError('Existing checkout origin mismatch')
|
||||
dest.parent.mkdir(parents=True, exist_ok=True)
|
||||
with tempfile.TemporaryDirectory(prefix='.iomatex-install-', dir=dest.parent) as tmp:
|
||||
staged = Path(tmp) / 'snapshot'
|
||||
|
|
@ -360,6 +410,9 @@ def main():
|
|||
|
||||
if __name__ == '__main__':
|
||||
try: main()
|
||||
except RecoveryPending as error:
|
||||
print(str(error), flush=True)
|
||||
sys.exit(75)
|
||||
except Exception as error:
|
||||
print('Iomatex Git delivery failed: ' + type(error).__name__ + ': ' + str(error), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
|
|
|||
|
|
@ -136,6 +136,20 @@ def installer_busy():
|
|||
|
||||
def job_status():
|
||||
job = read_json(STATE / 'job.json')
|
||||
if job.get('phase') == 'storage_recovery' and job.get('state') == 'running':
|
||||
recovery = read_json(Path('/var/lib/iomatex/storage/recovery.json'))
|
||||
if (recovery.get('job') or {}).get('unit') == job.get('unit'):
|
||||
if recovery.get('status') in ('pending', 'repairing', 'verified'):
|
||||
return job
|
||||
if recovery.get('status') == 'failed':
|
||||
job = {**job, 'state': 'failed', 'error': recovery.get('error', 'Storage recovery failed')}
|
||||
delivery.write_json(STATE / 'job.json', job)
|
||||
return job
|
||||
if recovery.get('status') == 'resuming':
|
||||
unit = 'iomatex-userdata-recovery-resume.service'
|
||||
status = subprocess.run(['systemctl', 'is-active', unit], capture_output=True, text=True, timeout=3)
|
||||
if status.stdout.strip() in ('active', 'activating'):
|
||||
return job
|
||||
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)
|
||||
|
|
@ -229,7 +243,7 @@ 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)
|
||||
cfg['branch'], cfg['checkout'], commit=commit, recovery_stages=[stage], recovery_job=job)
|
||||
root = Path(cfg['checkout'])
|
||||
release = validate_manifest(read_json(root / 'stage-releases.json'))['stages'][stage]
|
||||
if release['version'] != job['version']:
|
||||
|
|
@ -243,6 +257,9 @@ def install(stage, commit):
|
|||
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 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__,
|
||||
'finished_at': int(time.time())})
|
||||
|
|
|
|||
|
|
@ -69,4 +69,25 @@ class DeliveryTest(unittest.TestCase):
|
|||
with self.assertRaisesRegex(ValueError,'redirect refused'):
|
||||
d.NoRedirect().redirect_request(None,None,302,'',{},'https://git.it-screen.com/other')
|
||||
|
||||
class RecoveryDeliveryTest(unittest.TestCase):
|
||||
def test_gate_runs_before_any_access_to_existing_snapshot(self):
|
||||
with tempfile.TemporaryDirectory() as folder, \
|
||||
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': []}))), \
|
||||
patch.object(d, 'recovery_gate', side_effect=d.RecoveryPending('pending')) as gate, \
|
||||
patch.object(d, 'check_existing') as old:
|
||||
with self.assertRaises(d.RecoveryPending):
|
||||
d.bootstrap('https://git.it-screen.com/An-J/Iomatex_OS.git', 'ci-cd', folder,
|
||||
commit='a'*40, recovery_stages=['stage_ui'])
|
||||
old.assert_not_called()
|
||||
self.assertEqual(['stage_ui'], gate.call_args.args[5])
|
||||
|
||||
def test_corrupt_recovery_code_is_rejected_before_import(self):
|
||||
entry = {'path': 'stage_env/userdata_recovery.py', 'sha': d.blob_hash(b'expected'), 'mode': '100644'}
|
||||
with patch.object(d, 'open_git', return_value=io.BytesIO(b'corrupt')), \
|
||||
patch.object(d.importlib.util, 'spec_from_file_location') as load:
|
||||
with self.assertRaisesRegex(ValueError, 'checksum'):
|
||||
d.recovery_gate('An-J/Iomatex_OS', 'ci-cd', 'a'*40, {}, [entry], ['stage_ui'])
|
||||
load.assert_not_called()
|
||||
|
||||
if __name__=='__main__': unittest.main()
|
||||
|
|
|
|||
|
|
@ -91,6 +91,18 @@ class StageVersionsTest(unittest.TestCase):
|
|||
self.assertEqual('failed', versions.read_json(versions.STATE / 'job.json')['state'])
|
||||
self.assertFalse((versions.STATE / 'stage_z2m.json').exists())
|
||||
|
||||
def test_storage_recovery_is_pending_without_success_receipt(self):
|
||||
job = {'stage':'stage_ui', 'commit':COMMIT, 'version':'3.1.2', 'unit':'test-recovery'}
|
||||
versions.delivery.write_json(versions.STATE / 'job.json', job)
|
||||
with mock.patch.object(versions.delivery, 'bootstrap', side_effect=versions.delivery.RecoveryPending('pending')) as boot, \
|
||||
mock.patch.object(versions.subprocess, 'run') as install:
|
||||
versions.install('stage_ui', COMMIT)
|
||||
self.assertEqual(['stage_ui'], boot.call_args.kwargs['recovery_stages'])
|
||||
self.assertEqual(job, boot.call_args.kwargs['recovery_job'])
|
||||
install.assert_not_called()
|
||||
self.assertEqual('storage_recovery', versions.read_json(versions.STATE / 'job.json')['phase'])
|
||||
self.assertFalse((versions.STATE / 'stage_ui.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'])
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
"schema": 1,
|
||||
"stages": {
|
||||
"stage_env": {
|
||||
"version": "1.0.2"
|
||||
"version": "1.0.3"
|
||||
},
|
||||
"stage_wifi": {
|
||||
"version": "1.0.0"
|
||||
|
|
|
|||
|
|
@ -105,3 +105,60 @@ return 0 or 1 before creating a journal. Other exit codes preserve the marker,
|
|||
stop migration and prevent the dependent userdata mount from proceeding.
|
||||
Journal protection becomes active only after successful offline preparation;
|
||||
installation success alone does not verify physical storage health.
|
||||
|
||||
## Stage release 1.0.3: automatic recovery before an update
|
||||
|
||||
For updates using the current `install_iomatex_edge.sh` or the updated Console
|
||||
stage worker, the Git delivery owner now checks userdata before accessing or
|
||||
replacing the local snapshot. The new `userdata_recovery.py` coordinates this
|
||||
check and is also the single offline preparation implementation behind
|
||||
`iomatex-userdata-prepare`. The earlier stage guard remains a final check for
|
||||
direct stage calls and faults detected after the delivery preflight.
|
||||
|
||||
On known ext4 corruption, a read-only mount or an unclean unmounted partition:
|
||||
|
||||
1. Download and hash-check a fresh installer from the selected Git commit into
|
||||
`/var/lib/iomatex/storage/installer-*` on the system filesystem. Preserve the
|
||||
original snapshot and all user data. Persist the exact selected stages and,
|
||||
for Console updates, the confirmed job/version. Older launchers which do not
|
||||
provide the stage selection must be replaced with the current launcher.
|
||||
2. Record the device path and UUID, save fstab, install a boot preparation unit
|
||||
and a one-shot update continuation, and reboot. The userdata fstab fsck pass
|
||||
is temporarily zero so generated systemd fsck does not race the preparation.
|
||||
3. Before mounting userdata, verify the identity and absence of any mount or
|
||||
swap use. Save metadata and a complete compressed raw partition image to
|
||||
an `attempt-*` directory on the system filesystem. Decompress and hash-check
|
||||
the image against all bytes read from the source, including its block-device
|
||||
size. A failed read, insufficient space or failed verification stops the
|
||||
process before filesystem repair. Preserve at least 512 MiB of free space.
|
||||
4. Run `e2fsck -pf -E nodiscard` with an undo file. If it returns exactly 4,
|
||||
the verified full backup permits one `e2fsck -fy -E nodiscard` pass with a
|
||||
separate undo file. This can remove inconsistent directory entries; healthy
|
||||
file preservation is tested, but lost data cannot be promised. Any result
|
||||
other than 0 or 1 stops the process (including a requested additional reboot).
|
||||
5. Enable the ext4 journal if absent, set `errors=remount-ro`, run a read-only
|
||||
forced verification and check clean state, zero recorded errors and journal
|
||||
presence. Only then set fstab pass 2 and permit mounting and update continuation.
|
||||
6. Resume the selected stages from the system-filesystem snapshot. The existing
|
||||
orchestrator owns stage validation, receipts and any stage_env reboot.
|
||||
Pending recovery never produces an installation success receipt.
|
||||
|
||||
State and diagnostics are in `/var/lib/iomatex/storage/recovery.json`,
|
||||
`resume.log`, and the referenced `attempt-*` directory (`repair.log`,
|
||||
`superblock.before.txt`, `metadata.qcow2`, `userdata.img.gz`, and undo files).
|
||||
These artifacts are root-only. The raw backup is not a guarantee against a
|
||||
physical failure of the same eMMC; it is retained for recovery and is not
|
||||
restored or deleted automatically. A repair failure or interruption blocks
|
||||
automatic retries and the dependent userdata mount, while its `nofail` policy
|
||||
allows the OS to boot for diagnosis. No formatting or factory reset is used.
|
||||
|
||||
The automatic path requires the recovery snapshot plus the compressed image
|
||||
and the free-space reserve to fit outside userdata. It cannot guarantee an
|
||||
update on failing media or when no backup storage is available. Metadata and
|
||||
undo files alone are explicitly not treated as a full user-data backup.
|
||||
|
||||
Validation includes a disposable ext4 image with a deleted inode referenced
|
||||
by a directory and a large recorded error count, plus simulated mounted-device,
|
||||
identity, low-space, backup, fsck, verification and continuation failures.
|
||||
The automatic repair and return-code semantics follow
|
||||
[e2fsck(8)](https://www.man7.org/linux/man-pages/man8/e2fsck.8.html).
|
||||
|
|
|
|||
|
|
@ -1,53 +1,3 @@
|
|||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
export LC_ALL=C
|
||||
|
||||
MARKER="/var/lib/iomatex/storage/enable-userdata-journal"
|
||||
DEVICE_LINK="/dev/disk/by-partlabel/userdata"
|
||||
|
||||
log() { echo "[iomatex-userdata-prepare] $*"; }
|
||||
|
||||
[ -e "$MARKER" ] || exit 0
|
||||
|
||||
for _ in $(seq 1 30); do
|
||||
[ -b "$DEVICE_LINK" ] && break
|
||||
sleep 1
|
||||
done
|
||||
[ -b "$DEVICE_LINK" ] || { log "ERROR: userdata block device did not appear"; exit 1; }
|
||||
|
||||
device="$(readlink -f "$DEVICE_LINK")"
|
||||
[ -b "$device" ] || { log "ERROR: resolved userdata path is not a block device"; exit 1; }
|
||||
if findmnt -rn -S "$device" >/dev/null 2>&1 || mountpoint -q /userdata; then
|
||||
log "ERROR: refusing to change a mounted filesystem: $device"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
fs_type="$(blkid -s TYPE -o value "$device" 2>/dev/null || true)"
|
||||
[ "$fs_type" = "ext4" ] || { log "ERROR: expected ext4 on $device, found ${fs_type:-unknown}"; exit 1; }
|
||||
|
||||
if tune2fs -l "$device" 2>/dev/null | awk -F: '/^Filesystem features:/{print $2}' | grep -qw has_journal; then
|
||||
log "Journal already enabled"
|
||||
else
|
||||
set +e
|
||||
e2fsck -pf "$device"
|
||||
fsck_rc=$?
|
||||
set -e
|
||||
case "$fsck_rc" in
|
||||
0|1) ;;
|
||||
*) log "ERROR: preflight e2fsck failed with rc=$fsck_rc; journal migration stopped; offline inspection required"; exit "$fsck_rc" ;;
|
||||
esac
|
||||
tune2fs -j "$device"
|
||||
sync
|
||||
tune2fs -l "$device" 2>/dev/null | awk -F: '/^Filesystem features:/{print $2}' | grep -qw has_journal \
|
||||
|| { log "ERROR: journal verification failed"; exit 1; }
|
||||
log "Ext4 journal enabled successfully"
|
||||
fi
|
||||
|
||||
tmp="$(mktemp)"
|
||||
awk '
|
||||
$1 !~ /^#/ && $2 == "/userdata" { $6="2" }
|
||||
{ print }
|
||||
' /etc/fstab >"$tmp"
|
||||
install -m 0644 -o root -g root "$tmp" /etc/fstab
|
||||
rm -f "$tmp" "$MARKER"
|
||||
log "Migration complete; automatic filesystem checks enabled for future boots"
|
||||
exec /usr/bin/python3 /usr/local/lib/iomatex/userdata_recovery.py prepare
|
||||
|
|
|
|||
|
|
@ -460,11 +460,14 @@ configure_userdata_storage_contract() {
|
|||
install -D -m 0755 -o root -g root \
|
||||
"$SCRIPT_DIR/iomatex-userdata-prepare" /usr/local/sbin/iomatex-userdata-prepare
|
||||
|
||||
install -D -m 0755 -o root -g root \
|
||||
"$SCRIPT_DIR/userdata_recovery.py" /usr/local/lib/iomatex/userdata_recovery.py
|
||||
|
||||
write_if_changed /etc/systemd/system/iomatex-userdata-prepare.service 0644 <<'EOF'
|
||||
[Unit]
|
||||
Description=Prepare IOMATEX userdata filesystem before first journaled mount
|
||||
DefaultDependencies=no
|
||||
After=systemd-udev-settle.service
|
||||
After=systemd-udev-settle.service systemd-remount-fs.service
|
||||
Before=userdata.mount local-fs-pre.target
|
||||
ConditionPathExists=/var/lib/iomatex/storage/enable-userdata-journal
|
||||
|
||||
|
|
@ -509,7 +512,7 @@ EOF
|
|||
mount_options="$(findmnt -n -o OPTIONS --mountpoint /userdata 2>/dev/null || true)"
|
||||
if [[ ",$mount_options," == *,ro,* ]] || [[ "$state" == *error* ]] || [ "${error_count:-0}" != "0" ]; then
|
||||
rm -f "$marker"
|
||||
log "ERROR: /userdata requires offline backup and repair (state=${state:-unknown}, errors=${error_count:-unknown}, mount=${mount_options:-unmounted}); stage_env cannot complete"
|
||||
log "ERROR: /userdata needs the automatic recovery entrypoint install_iomatex_edge.sh (state=${state:-unknown}, errors=${error_count:-unknown}, mount=${mount_options:-unmounted}); stage_env cannot complete"
|
||||
return 1
|
||||
fi
|
||||
features="$(printf '%s\n' "$metadata" | awk -F: '/^Filesystem features:/{sub(/^[[:space:]]+/, "", $2); print $2}')"
|
||||
|
|
|
|||
|
|
@ -132,69 +132,5 @@ findmnt() { case "$3" in OPTIONS) echo "$OPTIONS";; SOURCE) echo "$MOUNT_SOURCE"
|
|||
self.assertFalse(armed)
|
||||
|
||||
|
||||
class OfflinePreparationTest(unittest.TestCase):
|
||||
def run_preparation(self, fsck_rc=0, mounted=False):
|
||||
import os
|
||||
body = MODULE_PATH.with_name("iomatex-userdata-prepare").read_text()
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = pathlib.Path(directory)
|
||||
marker = root / "marker"
|
||||
marker.touch()
|
||||
fstab = root / "fstab"
|
||||
fstab.write_text("/dev/test /userdata ext4 defaults 0 0\n")
|
||||
events = root / "events"
|
||||
body = body.replace('/var/lib/iomatex/storage/enable-userdata-journal', str(marker))
|
||||
body = body.replace('/etc/fstab', str(fstab))
|
||||
mocks = r'''
|
||||
[() { if [[ "$1" == '-b' ]]; then return 0; fi; builtin [ "$@"; }
|
||||
readlink() { echo /dev/test; }
|
||||
findmnt() { [[ "$MOUNTED" == 1 ]]; }
|
||||
mountpoint() { [[ "$MOUNTED" == 1 ]]; }
|
||||
blkid() { echo ext4; }
|
||||
e2fsck() { echo fsck >>"$EVENTS"; return "$FSCK_RC"; }
|
||||
tune2fs() {
|
||||
if [[ "$1" == '-j' ]]; then
|
||||
echo journal >>"$EVENTS"
|
||||
elif [[ -f "$EVENTS" ]] && grep -qx journal "$EVENTS"; then
|
||||
echo 'Filesystem features: has_journal extent'
|
||||
else
|
||||
echo 'Filesystem features: extent'
|
||||
fi
|
||||
}
|
||||
sync() { :; }
|
||||
install() { cp "${@: -2:1}" "${@: -1}"; }
|
||||
'''
|
||||
result = subprocess.run(["bash", "-c", mocks + body], text=True, capture_output=True,
|
||||
env={**os.environ, "FSCK_RC": str(fsck_rc),
|
||||
"MOUNTED": "1" if mounted else "0", "EVENTS": str(events)})
|
||||
return (result.returncode, marker.exists(),
|
||||
events.read_text().splitlines() if events.exists() else [],
|
||||
fstab.read_text(), result.stdout + result.stderr)
|
||||
|
||||
def test_mounted_filesystem_is_never_repaired(self):
|
||||
rc, marker, events, fstab, output = self.run_preparation(mounted=True)
|
||||
self.assertNotEqual(0, rc, output)
|
||||
self.assertTrue(marker)
|
||||
self.assertEqual([], events)
|
||||
self.assertTrue(fstab.rstrip().endswith("0 0"))
|
||||
|
||||
def test_failed_or_reboot_required_fsck_stops_before_journal_creation(self):
|
||||
for fsck_rc in (2, 4, 8, 16):
|
||||
with self.subTest(fsck_rc=fsck_rc):
|
||||
rc, marker, events, fstab, output = self.run_preparation(fsck_rc)
|
||||
self.assertNotEqual(0, rc, output)
|
||||
self.assertTrue(marker)
|
||||
self.assertEqual(["fsck"], events)
|
||||
self.assertTrue(fstab.rstrip().endswith("0 0"))
|
||||
|
||||
def test_successful_offline_check_creates_journal_and_enables_boot_checks(self):
|
||||
for fsck_rc in (0, 1):
|
||||
rc, marker, events, fstab, output = self.run_preparation(fsck_rc)
|
||||
self.assertEqual(0, rc, output)
|
||||
self.assertFalse(marker)
|
||||
self.assertEqual(["fsck", "journal"], events)
|
||||
self.assertTrue(fstab.rstrip().endswith("0 2"))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
|
|
|
|||
|
|
@ -0,0 +1,289 @@
|
|||
import importlib.util
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import shutil
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
SPEC = importlib.util.spec_from_file_location('recovery', Path(__file__).with_name('userdata_recovery.py'))
|
||||
r = importlib.util.module_from_spec(SPEC)
|
||||
SPEC.loader.exec_module(r)
|
||||
|
||||
|
||||
class RecoveryTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.temp = tempfile.TemporaryDirectory()
|
||||
self.addCleanup(self.temp.cleanup)
|
||||
self.root = Path(self.temp.name)
|
||||
for name, value in {'BASE': self.root, 'REQUEST': self.root / 'recovery.json',
|
||||
'MARKER': self.root / 'marker', 'DEVICE': self.root / 'device',
|
||||
'FSTAB': self.root / 'fstab', 'SYSTEMD': self.root / 'units',
|
||||
'INSTALL_LOCK': self.root / 'lock', 'HELPER': self.root / 'helper.py'}.items():
|
||||
context = patch.object(r, name, value)
|
||||
context.start()
|
||||
self.addCleanup(context.stop)
|
||||
r.DEVICE.touch()
|
||||
r.FSTAB.write_text(str(r.DEVICE) + ' /userdata ext4 defaults 0 0\n')
|
||||
self.report = dict(device=str(r.DEVICE), uuid='fixture', state='not clean with errors',
|
||||
errors=7278252, journal=False, options=[], needed=True, metadata='before')
|
||||
self.final = {**self.report, 'state': 'clean', 'errors': 0, 'journal': True, 'needed': False}
|
||||
r.save(dict(status='pending', device=str(r.DEVICE), uuid='fixture', root=str(self.root), stages=['stage_env']))
|
||||
|
||||
def prepare(self, codes, report=None, mounted=False):
|
||||
with patch.object(r, 'inspect', side_effect=[report or self.report, self.final]), \
|
||||
patch.object(r, 'mounts', return_value=['/userdata'] if mounted else []), \
|
||||
patch.object(r.os.path, 'ismount', return_value=False), \
|
||||
patch.object(r, 'storage_directory'), patch.object(r, 'full_backup', return_value={'verified': True}), patch.object(r, 'output') as write, \
|
||||
patch.object(r, 'limited_run', side_effect=codes) as run, patch.object(r.os, 'sync'):
|
||||
try:
|
||||
r.prepare()
|
||||
error = None
|
||||
except Exception as exc:
|
||||
error = exc
|
||||
return error, run.call_args_list, write.call_args_list
|
||||
|
||||
def test_no_marker_or_request_does_not_touch_storage(self):
|
||||
r.REQUEST.unlink()
|
||||
with patch.object(r, 'inspect') as inspect:
|
||||
r.prepare()
|
||||
inspect.assert_not_called()
|
||||
|
||||
def test_legacy_journal_migration_does_not_escalate_without_full_backup(self):
|
||||
r.REQUEST.unlink()
|
||||
r.MARKER.touch()
|
||||
error, calls, writes = self.prepare([4])
|
||||
self.assertIsNotNone(error)
|
||||
self.assertEqual(1, len(calls))
|
||||
self.assertIn('-pf', calls[0].args[0])
|
||||
self.assertNotIn('-fy', str(calls))
|
||||
self.assertEqual([], writes)
|
||||
self.assertTrue(r.MARKER.exists())
|
||||
|
||||
def test_legacy_journal_migration_verifies_and_removes_marker(self):
|
||||
r.REQUEST.unlink()
|
||||
r.MARKER.touch()
|
||||
error, calls, writes = self.prepare([0, 0])
|
||||
self.assertIsNone(error)
|
||||
self.assertFalse(r.MARKER.exists())
|
||||
self.assertIn('-j', str(writes))
|
||||
self.assertTrue(r.FSTAB.read_text().rstrip().endswith('0\t2'))
|
||||
|
||||
def test_mounted_partition_is_never_modified(self):
|
||||
error, calls, writes = self.prepare([], mounted=True)
|
||||
self.assertIn('mounted', str(error))
|
||||
self.assertEqual([], calls)
|
||||
self.assertEqual([], writes)
|
||||
|
||||
def test_identity_change_is_never_repaired(self):
|
||||
error, calls, writes = self.prepare([], report={**self.report, 'uuid': 'different'})
|
||||
self.assertIn('identity', str(error))
|
||||
self.assertEqual([], calls)
|
||||
self.assertEqual([], writes)
|
||||
|
||||
def test_metadata_backup_failure_prevents_fsck(self):
|
||||
error, calls, writes = self.prepare([1])
|
||||
self.assertIsNotNone(error)
|
||||
self.assertEqual(['e2image'], [c.args[0][0] for c in calls])
|
||||
self.assertEqual([], writes)
|
||||
self.assertEqual('failed', json.loads(r.REQUEST.read_text())['status'])
|
||||
|
||||
def test_fsck_non_success_prevents_journal_and_mount_policy_change(self):
|
||||
for code in (2, 3, 8, 16, 32, 128):
|
||||
with self.subTest(code=code):
|
||||
r.save(dict(status='pending', uuid='fixture', device=str(r.DEVICE)))
|
||||
error, calls, writes = self.prepare([0, code])
|
||||
self.assertIn('rc=' + str(code), str(error))
|
||||
self.assertEqual([], writes)
|
||||
self.assertTrue(r.FSTAB.read_text().rstrip().endswith('0 0'))
|
||||
self.assertEqual('failed', json.loads(r.REQUEST.read_text())['status'])
|
||||
|
||||
def test_unresolved_preening_escalates_only_with_verified_full_backup(self):
|
||||
error, calls, writes = self.prepare([0, 4, 1, 0])
|
||||
self.assertIsNone(error)
|
||||
self.assertIn('-fy', calls[2].args[0])
|
||||
self.assertEqual('verified', json.loads(r.REQUEST.read_text())['status'])
|
||||
|
||||
def test_failed_escalation_stops_without_retries(self):
|
||||
error, calls, writes = self.prepare([0, 4, 4])
|
||||
self.assertIsNotNone(error)
|
||||
self.assertEqual([], writes)
|
||||
self.assertEqual('failed', json.loads(r.REQUEST.read_text())['status'])
|
||||
|
||||
def test_already_journaled_corruption_still_runs_fsck(self):
|
||||
error, calls, writes = self.prepare([0, 1, 0], report={**self.report, 'journal': True})
|
||||
self.assertIsNone(error)
|
||||
self.assertEqual(['e2image', 'e2fsck', 'e2fsck'], [c.args[0][0] for c in calls])
|
||||
self.assertNotIn('-j', str(writes))
|
||||
self.assertEqual('verified', json.loads(r.REQUEST.read_text())['status'])
|
||||
|
||||
def test_recovery_does_not_retry_after_failure_or_interruption(self):
|
||||
for state in ('failed', 'repairing'):
|
||||
r.save(dict(status=state))
|
||||
error, calls, writes = self.prepare([])
|
||||
self.assertIn('retries', str(error))
|
||||
self.assertEqual([], calls)
|
||||
|
||||
def test_readonly_verification_failure_blocks_resume(self):
|
||||
error, calls, writes = self.prepare([0, 1, 4])
|
||||
self.assertIn('verification', str(error))
|
||||
self.assertEqual('failed', json.loads(r.REQUEST.read_text())['status'])
|
||||
|
||||
def test_success_has_backup_then_preening_then_readonly_verification(self):
|
||||
error, calls, writes = self.prepare([0, 1, 0])
|
||||
self.assertIsNone(error)
|
||||
self.assertEqual('e2image', calls[0].args[0][0])
|
||||
self.assertIn('-pf', calls[1].args[0])
|
||||
self.assertIn('-z', calls[1].args[0])
|
||||
self.assertIn('-fn', calls[2].args[0])
|
||||
self.assertTrue(r.FSTAB.read_text().rstrip().endswith('0\t2'))
|
||||
self.assertEqual('verified', json.loads(r.REQUEST.read_text())['status'])
|
||||
|
||||
def test_fstab_refuses_ambiguous_or_wrong_partition(self):
|
||||
for contents in ('/dev/wrong /userdata ext4 defaults 0 0\n', '',
|
||||
r.FSTAB.read_text() * 2):
|
||||
r.FSTAB.write_text(contents)
|
||||
with self.assertRaises(RuntimeError):
|
||||
r.fstab_policy(str(r.DEVICE), 'fixture', 0)
|
||||
self.assertEqual(contents, r.FSTAB.read_text())
|
||||
|
||||
def test_resume_requires_verified_state(self):
|
||||
with self.assertRaisesRegex(RuntimeError, 'not verified'):
|
||||
r.resume()
|
||||
|
||||
def test_service_orders_repair_before_mount_and_resume(self):
|
||||
units = r.units()
|
||||
self.assertIn('Before=userdata.mount local-fs-pre.target', units[r.PREPARE])
|
||||
self.assertIn('systemd-remount-fs.service', units[r.PREPARE])
|
||||
self.assertIn('Requires=userdata.mount iomatex-userdata-prepare.service', units[r.RESUME])
|
||||
self.assertNotIn('Restart=always', units[r.RESUME])
|
||||
|
||||
def test_full_backup_space_failure_never_starts_repair(self):
|
||||
with patch.object(r, 'inspect', return_value=self.report), \
|
||||
patch.object(r, 'mounts', return_value=[]), \
|
||||
patch.object(r.os.path, 'ismount', return_value=False), \
|
||||
patch.object(r, 'storage_directory'), patch.object(r, 'limited_run', return_value=0) as run, \
|
||||
patch.object(r, 'full_backup', side_effect=RuntimeError('no space')):
|
||||
with self.assertRaisesRegex(RuntimeError, 'no space'):
|
||||
r.prepare()
|
||||
self.assertEqual(['e2image'], [c.args[0][0] for c in run.call_args_list])
|
||||
self.assertEqual('failed', json.loads(r.REQUEST.read_text())['status'])
|
||||
|
||||
def test_backup_rejects_short_read(self):
|
||||
r.DEVICE.write_bytes(b'original bytes')
|
||||
with patch.object(r, 'output', return_value='999'):
|
||||
with self.assertRaisesRegex(RuntimeError, 'Incomplete'):
|
||||
r.full_backup(r.DEVICE, self.root)
|
||||
self.assertFalse((self.root / 'userdata.img.gz').exists())
|
||||
self.assertFalse((self.root / 'userdata.img.gz.partial').exists())
|
||||
|
||||
def test_backup_preserves_exact_image_bytes(self):
|
||||
import gzip
|
||||
raw = b'original image' * 200
|
||||
r.DEVICE.write_bytes(raw)
|
||||
with patch.object(r, 'output', return_value=str(len(raw))):
|
||||
result = r.full_backup(r.DEVICE, self.root)
|
||||
self.assertEqual(raw, gzip.decompress(Path(result['path']).read_bytes()))
|
||||
self.assertEqual(len(raw), result['bytes'])
|
||||
|
||||
def test_arm_preserves_selection_and_orders_one_reboot_after_persistence(self):
|
||||
r.REQUEST.unlink()
|
||||
installer = self.root / 'installer'
|
||||
(installer / 'stage_env').mkdir(parents=True)
|
||||
(installer / 'stage_env/userdata_recovery.py').write_text('# fixture')
|
||||
(installer / 'stage-releases.json').write_text(json.dumps({'stages': {'stage_ui': {'version': '1.0.0'}}}))
|
||||
def run(args):
|
||||
if args == ['systemctl', 'reboot']:
|
||||
request = json.loads(r.REQUEST.read_text())
|
||||
self.assertEqual(['stage_ui'], request['stages'])
|
||||
self.assertEqual('pending', request['status'])
|
||||
self.assertTrue((r.SYSTEMD / r.PREPARE).exists())
|
||||
self.assertTrue(r.FSTAB.read_text().rstrip().endswith('0\t0'))
|
||||
return ''
|
||||
with patch.object(r, 'storage_directory'), patch.object(r, 'output', side_effect=run) as calls, \
|
||||
patch.object(r.os, 'sync'):
|
||||
r.arm(installer, ['stage_ui'], self.report)
|
||||
self.assertEqual(['systemctl', 'reboot'], calls.call_args_list[-1].args[0])
|
||||
|
||||
def test_failed_request_cannot_be_rearmed(self):
|
||||
r.save({'status': 'failed'})
|
||||
with patch.object(r, 'storage_directory'), patch.object(r, 'output') as run:
|
||||
with self.assertRaisesRegex(RuntimeError, 'already attempted'):
|
||||
r.arm(self.root, ['stage_env'], self.report)
|
||||
run.assert_not_called()
|
||||
|
||||
def test_resume_runs_only_requested_stages_from_root_snapshot(self):
|
||||
(self.root / 'local_installer.state').write_text('POST_REBOOT_PENDING=0\n')
|
||||
request = json.loads(r.REQUEST.read_text())
|
||||
request.update(status='verified', stages=['stage_ui'])
|
||||
r.save(request)
|
||||
with patch.object(r, 'inspect', return_value={**self.final, 'options': ['rw']}), \
|
||||
patch.object(r, 'output') as system, \
|
||||
patch.object(r.subprocess, 'run', return_value=subprocess.CompletedProcess([], 0)) as install:
|
||||
r.resume()
|
||||
args = install.call_args.args[0]
|
||||
self.assertEqual(['--only', 'stage_ui'], args[-2:])
|
||||
self.assertEqual(str(self.root / 'local_installer.sh'), args[1])
|
||||
self.assertIn('pass_fds', install.call_args.kwargs)
|
||||
self.assertEqual('complete', json.loads(r.REQUEST.read_text())['status'])
|
||||
system.assert_called_once_with(['systemctl', 'disable', r.RESUME])
|
||||
|
||||
def test_resume_refuses_readonly_mount_after_verification(self):
|
||||
request = json.loads(r.REQUEST.read_text())
|
||||
request.update(status='verified')
|
||||
r.save(request)
|
||||
with patch.object(r, 'inspect', return_value={**self.final, 'options': ['ro']}), \
|
||||
patch.object(r.subprocess, 'run') as install:
|
||||
with self.assertRaisesRegex(RuntimeError, 'read-write'):
|
||||
r.resume()
|
||||
install.assert_not_called()
|
||||
|
||||
def test_final_continuation_marks_recovery_complete_only_for_same_snapshot(self):
|
||||
request = json.loads(r.REQUEST.read_text())
|
||||
request['status'] = 'resuming'
|
||||
r.save(request)
|
||||
r.finish(self.root / 'other', False)
|
||||
self.assertEqual('resuming', json.loads(r.REQUEST.read_text())['status'])
|
||||
r.finish(self.root, False)
|
||||
self.assertEqual('complete', json.loads(r.REQUEST.read_text())['status'])
|
||||
|
||||
@unittest.skipUnless(all(shutil.which(x) for x in ('mkfs.ext4', 'debugfs', 'e2image', 'e2fsck')), 'e2fsprogs required')
|
||||
def test_real_ext4_image_deleted_inode_is_repaired_and_good_file_preserved(self):
|
||||
# Only a disposable regular file; no mounts, loop devices or physical disks.
|
||||
image = r.DEVICE
|
||||
with image.open('wb') as stream:
|
||||
stream.truncate(32 * 1024 * 1024)
|
||||
subprocess.run(['mkfs.ext4', '-q', '-F', '-O', '^has_journal', str(image)], check=True)
|
||||
fixture = self.root / 'content'
|
||||
fixture.write_text('registration-data-must-survive\n')
|
||||
def debug(text):
|
||||
return subprocess.run(['debugfs', '-w', '-R', text, str(image)], check=True,
|
||||
capture_output=True, text=True)
|
||||
debug('write ' + str(fixture) + ' /keep')
|
||||
debug('write ' + str(fixture) + ' /broken')
|
||||
debug('set_inode_field /broken links_count 0')
|
||||
debug('set_inode_field /broken dtime 1')
|
||||
debug('set_super_value state 2')
|
||||
debug('set_super_value error_count 7278252')
|
||||
def inspect_image():
|
||||
raw = subprocess.check_output(['tune2fs', '-l', str(image)], text=True)
|
||||
fields = {k.strip(): v.strip() for k, v in (line.split(':', 1) for line in raw.splitlines() if ':' in line)}
|
||||
return {**self.report, 'uuid': fields['Filesystem UUID'], 'state': fields['Filesystem state'],
|
||||
'journal': 'has_journal' in fields['Filesystem features'],
|
||||
'errors': int(fields.get('FS Error count', 0)), 'metadata': raw}
|
||||
current = inspect_image()
|
||||
r.save(dict(status='pending', uuid=current['uuid'], device=str(image)))
|
||||
with patch.object(r, 'inspect', side_effect=inspect_image), patch.object(r, 'mounts', return_value=[]), \
|
||||
patch.object(r.os.path, 'ismount', return_value=False), patch.object(r, 'storage_directory'), \
|
||||
patch.object(r.os, 'sync'), patch.object(r, 'output', side_effect=lambda args: str(image.stat().st_size) if args[0] == 'blockdev' else subprocess.check_output(args, text=True).strip()):
|
||||
r.prepare()
|
||||
self.assertEqual('verified', json.loads(r.REQUEST.read_text())['status'])
|
||||
self.assertEqual(fixture.read_text(), debug('cat /keep').stdout)
|
||||
self.assertTrue((self.root / 'metadata.qcow2').stat().st_size > 0)
|
||||
self.assertTrue((self.root / 'repair.e2undo').stat().st_size > 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
|
|
@ -0,0 +1,417 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Single userdata update gate and offline preparation owner (no mounted repairs)."""
|
||||
import argparse
|
||||
import fcntl
|
||||
import gzip
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import resource
|
||||
import shutil
|
||||
import stat
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
BASE = Path('/var/lib/iomatex/storage')
|
||||
REQUEST = BASE / 'recovery.json'
|
||||
MARKER = BASE / 'enable-userdata-journal'
|
||||
DEVICE = Path('/dev/disk/by-partlabel/userdata')
|
||||
FSTAB = Path('/etc/fstab')
|
||||
SYSTEMD = Path('/etc/systemd/system')
|
||||
HELPER = Path('/usr/local/lib/iomatex/userdata_recovery.py')
|
||||
PREPARE = 'iomatex-userdata-prepare.service'
|
||||
RESUME = 'iomatex-userdata-recovery-resume.service'
|
||||
INSTALL_LOCK = Path('/run/lock/iomatex-installer.lock')
|
||||
RESERVE = 512 * 1024 * 1024
|
||||
FILE_LIMIT = 128 * 1024 * 1024
|
||||
|
||||
|
||||
def command(args, **kwargs):
|
||||
return subprocess.run(args, env={**os.environ, 'LC_ALL': 'C'},
|
||||
text=True, capture_output=True, timeout=30, **kwargs)
|
||||
|
||||
|
||||
def output(args):
|
||||
result = command(args)
|
||||
if result.returncode:
|
||||
raise RuntimeError('Cannot inspect storage: ' + args[0])
|
||||
return result.stdout.strip()
|
||||
|
||||
|
||||
def atomic(path, data, mode=0o600):
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
fd, name = tempfile.mkstemp(dir=path.parent)
|
||||
try:
|
||||
with os.fdopen(fd, 'w') as stream:
|
||||
stream.write(data)
|
||||
stream.flush()
|
||||
os.fsync(stream.fileno())
|
||||
os.chmod(name, mode)
|
||||
os.replace(name, path)
|
||||
directory_fd = os.open(path.parent, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(directory_fd)
|
||||
finally:
|
||||
os.close(directory_fd)
|
||||
finally:
|
||||
Path(name).unlink(missing_ok=True)
|
||||
|
||||
|
||||
def save(data):
|
||||
atomic(REQUEST, json.dumps(data, indent=2) + '\n')
|
||||
|
||||
|
||||
def mounts(device):
|
||||
result = command(['findmnt', '-rn', '-S', str(device), '-o', 'TARGET'])
|
||||
if result.returncode not in (0, 1):
|
||||
raise RuntimeError('Cannot inspect device mounts')
|
||||
return result.stdout.strip().splitlines()
|
||||
|
||||
|
||||
def inspect():
|
||||
if not DEVICE.exists():
|
||||
return None
|
||||
device = DEVICE.resolve()
|
||||
if not stat.S_ISBLK(device.stat().st_mode):
|
||||
raise RuntimeError('userdata is not a block device')
|
||||
if output(['blkid', '-s', 'TYPE', '-o', 'value', str(device)]) != 'ext4':
|
||||
raise RuntimeError('userdata is not ext4')
|
||||
metadata = output(['tune2fs', '-l', str(device)])
|
||||
fields = dict(line.split(':', 1) for line in metadata.splitlines() if ':' in line)
|
||||
fields = {k.strip(): v.strip() for k, v in fields.items()}
|
||||
state = fields.get('Filesystem state', '')
|
||||
features = fields.get('Filesystem features', '').split()
|
||||
uuid = fields.get('Filesystem UUID', '')
|
||||
if state not in ('clean', 'not clean', 'clean with errors', 'not clean with errors') or not features or not uuid:
|
||||
raise RuntimeError('Incomplete or unsupported userdata metadata')
|
||||
errors = int(fields.get('FS Error count', '0'))
|
||||
result = command(['findmnt', '-rn', '--mountpoint', '/userdata', '-o', 'SOURCE,FSTYPE,OPTIONS'])
|
||||
if result.returncode not in (0, 1):
|
||||
raise RuntimeError('Cannot inspect userdata mount')
|
||||
options = []
|
||||
if result.returncode == 0:
|
||||
parts = result.stdout.split()
|
||||
if len(parts) != 3 or Path(parts[0]).resolve() != device or parts[1] != 'ext4':
|
||||
raise RuntimeError('userdata mount does not match the expected ext4 device')
|
||||
options = parts[2].split(',')
|
||||
needed = 'errors' in state or errors > 0 or 'ro' in options or (state == 'not clean' and not options)
|
||||
return dict(device=str(device), uuid=uuid, state=state, errors=errors,
|
||||
journal='has_journal' in features, options=options, needed=needed,
|
||||
metadata=metadata)
|
||||
|
||||
|
||||
def storage_directory(device):
|
||||
BASE.mkdir(parents=True, exist_ok=True)
|
||||
if BASE.resolve() != BASE or BASE.stat().st_dev == os.stat(device).st_rdev:
|
||||
raise RuntimeError('Recovery files must reside outside userdata, without symlinks')
|
||||
options = output(['findmnt', '-rn', '-T', str(BASE), '-o', 'OPTIONS']).split(',')
|
||||
if 'rw' not in options or shutil.disk_usage(BASE).free < RESERVE:
|
||||
raise RuntimeError('Recovery needs a writable system filesystem with 512 MiB free')
|
||||
os.chmod(BASE, 0o700)
|
||||
|
||||
|
||||
def fstab_policy(device, uuid, check_pass):
|
||||
lines = FSTAB.read_text().splitlines()
|
||||
found = 0
|
||||
for index, line in enumerate(lines):
|
||||
cols = line.split()
|
||||
if not cols or cols[0].startswith('#') or len(cols) < 2 or cols[1] != '/userdata':
|
||||
continue
|
||||
if len(cols) < 6 or cols[2] != 'ext4' or (cols[0] not in ('UUID=' + uuid, 'PARTLABEL=userdata', 'LABEL=userdata')
|
||||
and Path(cols[0]).resolve() != Path(device)):
|
||||
raise RuntimeError('Unsupported userdata fstab entry')
|
||||
found += 1
|
||||
opts = [x for x in cols[3].split(',') if not x.startswith('errors=')]
|
||||
for option in ('nofail', 'x-systemd.device-timeout=5s', 'errors=remount-ro'):
|
||||
if option not in opts:
|
||||
opts.append(option)
|
||||
cols[3], cols[5] = ','.join(opts), str(check_pass)
|
||||
lines[index] = '\t'.join(cols)
|
||||
if found != 1:
|
||||
raise RuntimeError('Expected exactly one userdata mount in fstab')
|
||||
atomic(FSTAB, '\n'.join(lines) + '\n', 0o644)
|
||||
|
||||
|
||||
def units():
|
||||
return {
|
||||
PREPARE: '''[Unit]
|
||||
Description=IOMATEX offline userdata preparation
|
||||
DefaultDependencies=no
|
||||
Wants=systemd-udev-settle.service
|
||||
After=systemd-udev-settle.service systemd-remount-fs.service
|
||||
Before=userdata.mount local-fs-pre.target
|
||||
[Service]
|
||||
Type=oneshot
|
||||
RemainAfterExit=yes
|
||||
ExecStart=/usr/bin/python3 /usr/local/lib/iomatex/userdata_recovery.py prepare
|
||||
TimeoutStartSec=1h
|
||||
[Install]
|
||||
WantedBy=local-fs-pre.target
|
||||
''',
|
||||
'userdata.mount.d/10-iomatex-prepare.conf': '''[Unit]
|
||||
Requires=iomatex-userdata-prepare.service
|
||||
After=iomatex-userdata-prepare.service
|
||||
''',
|
||||
RESUME: '''[Unit]
|
||||
Description=Resume IOMATEX update after userdata recovery
|
||||
Wants=network-online.target
|
||||
After=network-online.target userdata.mount iomatex-userdata-prepare.service
|
||||
Requires=userdata.mount iomatex-userdata-prepare.service
|
||||
[Service]
|
||||
Type=oneshot
|
||||
ExecStart=/usr/bin/python3 /usr/local/lib/iomatex/userdata_recovery.py resume
|
||||
TimeoutStartSec=infinity
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
'''}
|
||||
|
||||
|
||||
def arm(root, stages, report, job=None):
|
||||
storage_directory(report['device'])
|
||||
if REQUEST.exists():
|
||||
previous = json.loads(REQUEST.read_text())
|
||||
if previous.get('status') not in ('complete', 'installer_reboot_pending'):
|
||||
raise RuntimeError('Recovery already attempted or pending; inspect ' + str(REQUEST))
|
||||
root = Path(root).resolve()
|
||||
if not root.is_relative_to(BASE) or root.stat().st_dev == os.stat(report['device']).st_rdev:
|
||||
raise RuntimeError('Recovery installer must be staged on the system filesystem')
|
||||
catalog = json.loads((root / 'stage-releases.json').read_text())['stages']
|
||||
if not stages or any(stage not in catalog for stage in stages):
|
||||
raise RuntimeError('Recovery requires explicit valid update stages; use the current install_iomatex_edge.sh')
|
||||
if job:
|
||||
source = json.loads((root / '.iomatex-source.json').read_text())
|
||||
if (stages != [job.get('stage')] or source.get('commit') != job.get('commit')
|
||||
or catalog[stages[0]]['version'] != job.get('version')):
|
||||
raise RuntimeError('Recovery does not match the confirmed update job')
|
||||
for name in ('e2fsck', 'e2image', 'tune2fs', 'blkid', 'blockdev'):
|
||||
if not shutil.which(name):
|
||||
raise RuntimeError('Recovery prerequisite is missing: ' + name)
|
||||
atomic(BASE / 'fstab.before', FSTAB.read_text())
|
||||
# Disable generated fsck for this one boot: the preparation owner runs it.
|
||||
fstab_policy(report['device'], report['uuid'], 0)
|
||||
atomic(HELPER, (root / 'stage_env/userdata_recovery.py').read_text(), 0o755)
|
||||
for name, body in units().items():
|
||||
atomic(SYSTEMD / name, body, 0o644)
|
||||
save(dict(status='pending', device=report['device'], uuid=report['uuid'],
|
||||
root=str(root), stages=stages, job=job, before=report,
|
||||
artifacts=tempfile.mkdtemp(prefix='attempt-', dir=BASE), created_at=int(time.time())))
|
||||
output(['systemctl', 'daemon-reload'])
|
||||
output(['systemctl', 'enable', PREPARE, RESUME])
|
||||
os.sync()
|
||||
print('Userdata recovery queued. Update will resume after offline verification.', flush=True)
|
||||
output(['systemctl', 'reboot'])
|
||||
|
||||
|
||||
def limited_run(args, log):
|
||||
def limit():
|
||||
resource.setrlimit(resource.RLIMIT_FSIZE, (FILE_LIMIT, FILE_LIMIT))
|
||||
with log.open('a') as stream:
|
||||
return subprocess.run(args, stdout=stream, stderr=subprocess.STDOUT,
|
||||
env={**os.environ, 'LC_ALL': 'C'}, timeout=900,
|
||||
preexec_fn=limit).returncode
|
||||
|
||||
|
||||
def full_backup(device, directory):
|
||||
"""Read every source byte, then verify the compressed image before any repair."""
|
||||
target = directory / 'userdata.img.gz'
|
||||
partial = directory / 'userdata.img.gz.partial'
|
||||
digest, length = hashlib.sha256(), 0
|
||||
try:
|
||||
with open(device, 'rb') as source, partial.open('wb') as raw:
|
||||
with gzip.GzipFile(filename='', mode='wb', fileobj=raw, compresslevel=1, mtime=0) as compressed:
|
||||
while True:
|
||||
chunk = source.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
if shutil.disk_usage(directory).free < RESERVE:
|
||||
raise RuntimeError('Not enough system disk space for full userdata backup; no repair started')
|
||||
digest.update(chunk)
|
||||
length += len(chunk)
|
||||
compressed.write(chunk)
|
||||
raw.flush()
|
||||
os.fsync(raw.fileno())
|
||||
expected = int(output(['blockdev', '--getsize64', str(device)]))
|
||||
if not length or length != expected:
|
||||
raise RuntimeError('Incomplete userdata image; no repair started')
|
||||
verified, verified_length = hashlib.sha256(), 0
|
||||
with gzip.open(partial, 'rb') as stored:
|
||||
while True:
|
||||
chunk = stored.read(1024 * 1024)
|
||||
if not chunk:
|
||||
break
|
||||
verified.update(chunk)
|
||||
verified_length += len(chunk)
|
||||
if verified_length != length or verified.digest() != digest.digest():
|
||||
raise RuntimeError('Userdata backup verification failed')
|
||||
partial.rename(target)
|
||||
directory_fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
|
||||
try:
|
||||
os.fsync(directory_fd)
|
||||
finally:
|
||||
os.close(directory_fd)
|
||||
return dict(path=str(target), bytes=length, sha256=digest.hexdigest())
|
||||
except BaseException:
|
||||
partial.unlink(missing_ok=True)
|
||||
raise
|
||||
|
||||
|
||||
def prepare():
|
||||
recovery = json.loads(REQUEST.read_text()) if REQUEST.exists() else None
|
||||
active = recovery and recovery['status'] in ('pending', 'repairing', 'failed', 'verified')
|
||||
if not active and not MARKER.exists():
|
||||
return
|
||||
if active and recovery['status'] == 'verified':
|
||||
return
|
||||
if active and recovery['status'] != 'pending':
|
||||
raise RuntimeError('Recovery was interrupted or failed; automatic retries are disabled')
|
||||
for _ in range(30):
|
||||
if DEVICE.exists():
|
||||
break
|
||||
time.sleep(1)
|
||||
report = inspect()
|
||||
if not report:
|
||||
raise RuntimeError('userdata device is missing')
|
||||
if active and (report['uuid'] != recovery['uuid'] or report['device'] != recovery['device']):
|
||||
raise RuntimeError('userdata identity changed; refusing repair')
|
||||
if mounts(report['device']) or os.path.ismount('/userdata'):
|
||||
raise RuntimeError('Refusing to repair a mounted filesystem')
|
||||
for line in Path('/proc/swaps').read_text().splitlines()[1:]:
|
||||
if Path(line.split()[0]).resolve() == Path(report['device']):
|
||||
raise RuntimeError('userdata is used as swap')
|
||||
storage_directory(report['device'])
|
||||
if active:
|
||||
recovery['status'] = 'repairing'
|
||||
save(recovery) # persisted before any disk mutation: no retry after power loss
|
||||
artifacts = Path(recovery.get('artifacts', str(BASE))) if active else BASE
|
||||
log = artifacts / 'repair.log'
|
||||
device = report['device']
|
||||
try:
|
||||
if active:
|
||||
atomic(artifacts / 'superblock.before.txt', report['metadata'])
|
||||
if limited_run(['e2image', '-Q', device, str(artifacts / 'metadata.qcow2')], log):
|
||||
raise RuntimeError('Cannot save filesystem metadata; repair was not started')
|
||||
recovery['backup'] = full_backup(device, artifacts)
|
||||
save(recovery)
|
||||
if active or not report['journal']:
|
||||
args = ['e2fsck', '-pf', '-E', 'nodiscard']
|
||||
if active:
|
||||
args += ['-z', str(artifacts / 'repair.e2undo')]
|
||||
rc = limited_run(args + [device], log)
|
||||
if rc == 4 and active:
|
||||
# The full byte-for-byte pre-repair image was verified above.
|
||||
# -p cannot resolve deleted-inode directory references.
|
||||
rc = limited_run(['e2fsck', '-fy', '-E', 'nodiscard', '-z',
|
||||
str(artifacts / 'repair-full.e2undo'), device], log)
|
||||
if rc not in (0, 1):
|
||||
raise RuntimeError('Automatic e2fsck stopped with rc=' + str(rc) + '; see repair.log')
|
||||
if not report['journal']:
|
||||
output(['tune2fs', '-j', device])
|
||||
output(['tune2fs', '-e', 'remount-ro', device])
|
||||
if limited_run(['e2fsck', '-fn', device], log) != 0:
|
||||
raise RuntimeError('Read-only verification failed')
|
||||
final = inspect()
|
||||
if final['state'] != 'clean' or final['errors'] or not final['journal']:
|
||||
raise RuntimeError('Storage protection verification failed')
|
||||
fstab_policy(device, report['uuid'], 2)
|
||||
MARKER.unlink(missing_ok=True)
|
||||
if active:
|
||||
recovery.update(status='verified', after=final)
|
||||
save(recovery)
|
||||
os.sync()
|
||||
print('Userdata verified; journal and boot checks enabled.', flush=True)
|
||||
except Exception as error:
|
||||
if active:
|
||||
recovery.update(status='failed', error=str(error))
|
||||
save(recovery)
|
||||
raise
|
||||
|
||||
|
||||
def resume():
|
||||
request = json.loads(REQUEST.read_text())
|
||||
if request['status'] != 'verified':
|
||||
raise RuntimeError('Recovery is not verified; update cannot resume')
|
||||
report = inspect()
|
||||
if not report or report['uuid'] != request['uuid'] or report['needed'] or 'rw' not in report['options']:
|
||||
raise RuntimeError('userdata is not mounted read-write and healthy')
|
||||
# One attempt only; the existing orchestrator owns any later stage_env reboot.
|
||||
output(['systemctl', 'disable', RESUME])
|
||||
request['status'] = 'resuming'
|
||||
save(request)
|
||||
root = Path(request['root'])
|
||||
env = dict(os.environ)
|
||||
job = request.get('job')
|
||||
if job:
|
||||
env['IOMATEX_INSTALL_JOB_ID'] = job['unit']
|
||||
try:
|
||||
lock_path = INSTALL_LOCK
|
||||
lock_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
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(),))
|
||||
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'])
|
||||
atomic(receipts / 'job.json', json.dumps({**job, 'state': 'success' if success else 'failed',
|
||||
'finished_at': int(time.time())}) + '\n')
|
||||
if result.returncode:
|
||||
raise RuntimeError('Installer failed after recovery; see resume.log')
|
||||
except Exception as error:
|
||||
request.update(status='failed', error=str(error))
|
||||
raise
|
||||
finally:
|
||||
save(request)
|
||||
|
||||
|
||||
def finish(root, failed):
|
||||
if not REQUEST.exists():
|
||||
return
|
||||
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
|
||||
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'
|
||||
save(request)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('action', choices=('prepare', 'resume', 'inspect', 'finish'))
|
||||
parser.add_argument('--root')
|
||||
parser.add_argument('--failed', action='store_true')
|
||||
args = parser.parse_args()
|
||||
if args.action == 'inspect':
|
||||
print(json.dumps(inspect()))
|
||||
elif args.action == 'finish':
|
||||
if not args.root:
|
||||
parser.error('--root is required for finish')
|
||||
finish(args.root, args.failed)
|
||||
elif args.action == 'prepare':
|
||||
prepare()
|
||||
else:
|
||||
resume()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
main()
|
||||
except Exception as error:
|
||||
if REQUEST.exists():
|
||||
request = json.loads(REQUEST.read_text())
|
||||
if request.get('status') in ('pending', 'repairing', 'resuming'):
|
||||
request.update(status='failed', error=str(error))
|
||||
save(request)
|
||||
print('Userdata recovery stopped: ' + str(error), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
|
@ -1,3 +1,3 @@
|
|||
{
|
||||
"version": "1.0.2"
|
||||
"version": "1.0.3"
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in New Issue