Cloud & Backend Engineer Guide: Atomic OTA Updates & Rollback Agents for Edge Linux Fleet
Updating software across hundreds of remote Linux edge gateways, retail kiosks, or medical telemetry appliances over unstable cellular connections is perilous: if power drops or a cellular link disconnects mid-update, a naive git pull && pip install leaves the edge device bricked and unreachable. As a cloud engineer and backend engineer, I architect cryptographically signed, atomic symlink-swapping Over-The-Air (OTA) update agents in Python with automatic systemd health-check rollbacks.
1. Immutable Release Directories and Atomic Symlink Swaps
Never mutate an active installation directory in place. Instead, the OTA agent downloads a Ed25519-signed release archive into /opt/app/releases/<version>, verifies its SHA-256 digest and signature, runs a pre-flight self-test, atomically swaps the /opt/app/current symlink via os.replace(), and restarts the daemon:
# edge_agent/ota_updater.py
import hashlib
import os
import shutil
import subprocess
import tempfile
from pathlib import Path
from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
RELEASES_DIR = Path("/opt/edge_daemon/releases")
CURRENT_SYMLINK = Path("/opt/edge_daemon/current")
PREVIOUS_SYMLINK = Path("/opt/edge_daemon/previous")
def verify_and_stage_bundle(bundle_path: Path, sig_bytes: bytes, pubkey: Ed25519PublicKey, version: str) -> Path:
digest = hashlib.sha256(bundle_path.read_bytes()).digest()
pubkey.verify(sig_bytes, digest) # Raises InvalidSignature if tampered
target_dir = RELEASES_DIR / version
if target_dir.exists():
shutil.rmtree(target_dir)
target_dir.mkdir(parents=True)
shutil.unpack_archive(str(bundle_path), str(target_dir), "gztar")
return target_dir
def atomic_switch_and_verify(target_dir: Path, service_name: str = "edge-telemetry.service") -> bool:
old_target = CURRENT_SYMLINK.resolve() if CURRENT_SYMLINK.exists() else None
# Create temporary symlink and atomically rename over CURRENT_SYMLINK
tmp_link = CURRENT_SYMLINK.with_suffix(".tmp")
if tmp_link.exists() or tmp_link.is_symlink():
tmp_link.unlink()
tmp_link.symlink_to(target_dir)
os.replace(tmp_link, CURRENT_SYMLINK)
subprocess.run(["systemctl", "restart", service_name], check=False)
# Verify health check within 15 seconds; rollback if unhealthy
health = subprocess.run(
[str(CURRENT_SYMLINK / "bin" / "healthcheck"), "--timeout", "10"],
capture_output=True,
)
if health.returncode == 0:
return True
if old_target:
rollback_tmp = CURRENT_SYMLINK.with_suffix(".rollback")
rollback_tmp.symlink_to(old_target)
os.replace(rollback_tmp, CURRENT_SYMLINK)
subprocess.run(["systemctl", "restart", service_name], check=False)
return False
2. Delta Downloads and Watchdog Dead-Man Switches
Combined with systemd's hardware/software WatchdogSec=30s notification (sd_notify("WATCHDOG=1")), even a runtime deadlock 5 minutes after deployment triggers an automatic revert to the known-good release slot.