A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.
fix(avf): detect dead control channel, capture full boot log, bound forwarder, volatile handle
ExTv17004d28273d
diff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.ktindex bc1bb1f..bd15397 100644--- a/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfEngine.kt@@ -72,6 +72,13 @@ class AvfEngine @Inject constructor(override var terminalSession: TerminalSession? = nullprivate set+ // Wall-clock millis of the most recent →Running transition (both the+ // detector onReady path and the boot-timeout fallback set it), null until+ // running and after cleanup(). Drives the Home uptime readout. @Volatile:+ // set on the detector/timeout thread, read by the UI ticker on another.+ @Volatile private var _runningSinceMs: Long? = null+ override val runningSinceMs: Long? get() = _runningSinceMs+override val backendId: String = "avf"/** AVF has no QMP socket; port forwarding is deferred to a future milestone. */@@ -102,7 +109,11 @@ class AvfEngine @Inject constructor(}private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)- private var vmHandle: Any? = null+ // @Volatile: written on the start()/cleanup() thread, read from stop() and+ // addPortForward() on other threads. Every other shared lifecycle field here+ // (control, stopRequested, vmGeneration) is already @Volatile for the same+ // cross-thread visibility reason; vmHandle was the lone unsynchronized gap.+ @Volatile private var vmHandle: Any? = null/*** Monotonic per-start token. Captured in each VM's callback closures so a* late callback from a PREVIOUS VM (callbacks run on ForkJoinPool, so a fast@@ -156,6 +167,8 @@ class AvfEngine @Inject constructor(val ctrlSockPath: String get() = "${context.filesDir.absolutePath}/avf-ctrl.sock"private val detector = BootStageDetector(_bootStage, _state) {+ // Detector already flipped _state to Running; stamp the uptime origin.+ _runningSinceMs = System.currentTimeMillis()Log.i(TAG, "boot Ready! detected — bridge connects via ConsoleFanout")// Wipe the boot log from the emulator so the user sees a clean login// prompt. AVF only exposes one captured console stream, so unlike@@ -364,6 +377,7 @@ class AvfEngine @Inject constructor(_state.value is VmState.Starting) {Log.w(TAG, "AVF boot timeout — forcing Running state")_bootStage.value = "Ready"+ _runningSinceMs = System.currentTimeMillis()_state.value = VmState.RunningbringUpControlChannel()}@@ -577,6 +591,7 @@ class AvfEngine @Inject constructor(private fun cleanup() {if (cleanedUp.getAndSet(true)) return+ _runningSinceMs = nullbootTimeoutJob?.cancel()bootTimeoutJob = null// Tear down forwarders + control before draining the fanout so thediff --git a/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.kt b/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.ktindex f8e0bb6..3efe0e3 100644--- a/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.kt+++ b/app/src/main/java/com/excp/podroid/engine/avf/AvfReflect.kt@@ -47,7 +47,15 @@ object AvfReflect {* delete + recreate on that path.*/fun setConfig(vm: Any, cfg: Any) {- val m = vm.javaClass.getDeclaredMethod("setConfig", CFG).apply { isAccessible = true }+ // getDeclaredMethod only finds a method declared on the exact runtime+ // class; on OS builds where setConfig is inherited from a supertype it+ // throws NoSuchMethodException, which the caller misreads as "config+ // rejected" and forces a needless delete+recreate every start. Fall back+ // to getMethod (searches supertypes) before concluding it's absent. A+ // genuine absence still throws — the caller's delete+recreate handles it.+ val m = (runCatching { vm.javaClass.getDeclaredMethod("setConfig", CFG) }+ .getOrNull() ?: vm.javaClass.getMethod("setConfig", CFG))+ .apply { isAccessible = true }m.invoke(vm, cfg)}diff --git a/app/src/main/java/com/excp/podroid/engine/avf/ConsoleFanout.kt b/app/src/main/java/com/excp/podroid/engine/avf/ConsoleFanout.ktindex 29d6215..1770c21 100644--- a/app/src/main/java/com/excp/podroid/engine/avf/ConsoleFanout.kt+++ b/app/src/main/java/com/excp/podroid/engine/avf/ConsoleFanout.kt@@ -97,8 +97,14 @@ class ConsoleFanout(while (true) {val n = consoleOutput.read(buf)if (n <= 0) break- detector.feed(buf, n)+ // Tee to capture BEFORE feeding the detector. detector.feed+ // flips _state Starting→Running on "Ready!", and onVmBytes+ // only persists while Starting; feeding first would drop the+ // very chunk carrying "Ready!" (and any late-boot error+ // batched with it) from console.log. Order guarantees capture+ // is never LESS than before — it now includes the Ready chunk.onVmBytes?.invoke(buf, n)+ detector.feed(buf, n)val client = clientFd ?: continue // no bridge attached → keep capturingvar off = 0while (off < n) {diff --git a/app/src/main/java/com/excp/podroid/engine/avf/VsockControlChannel.kt b/app/src/main/java/com/excp/podroid/engine/avf/VsockControlChannel.ktindex bfad607..db090d0 100644--- a/app/src/main/java/com/excp/podroid/engine/avf/VsockControlChannel.kt+++ b/app/src/main/java/com/excp/podroid/engine/avf/VsockControlChannel.kt@@ -76,12 +76,16 @@ class VsockControlChannel(if (closed) { runCatching { p.close() }; return@launch }pfd = pwriter = w- // Drain anything queued before we got connected.- for (line in pending) {- runCatching { w.println(line) }- .onFailure { Log.w(TAG, "drain send failed: $line", it) }- }+ // Drain anything queued before we got connected. writeLine+ // checks checkError() after each println; a mid-drain dead+ // connection tears down + re-arms (and stops the drain) so we+ // don't spin writing into a broken pipe. Snapshot first so the+ // re-arm path can't mutate `pending` while we iterate it.+ val toDrain = pending.toList()pending.clear()+ for (line in toDrain) {+ if (!writeLine(w, line)) break+ }}Log.d(TAG, "control channel connected after ${attempt + 1} attempts")true@@ -100,11 +104,50 @@ class VsockControlChannel(}}+ /**+ * Write one line and check for a silently-swallowed I/O error. PrintWriter+ * never throws on a dead socket — it only flips an internal flag exposed via+ * checkError(). Without this poll a dropped guest agent meant every+ * RESIZE/ADD/REMOVE was lost forever with no signal and no reconnect. On+ * error we tear down the writer/pfd and re-arm the connect loop so a later+ * command reconnects. Returns true if the write looks healthy.+ *+ * Caller must hold the instance monitor (both call sites are @Synchronized+ * or run inside `synchronized(this)`).+ */+ private fun writeLine(w: PrintWriter, line: String): Boolean {+ w.println(line)+ if (!w.checkError()) return true+ Log.w(TAG, "control channel write error on '$line'; tearing down + reconnecting")+ reconnect()+ return false+ }++ /**+ * Tear down a dead connection and re-arm the retry loop so the next command+ * reconnects. Idempotent against close(): a closed channel never reconnects.+ * The in-flight line that triggered this is dropped (RESIZE self-heals on the+ * next geometry change; ADD/REMOVE are re-dispatched by the engine layer).+ * Caller must hold the instance monitor.+ */+ private fun reconnect() {+ if (closed) return+ runCatching { writer?.close() }+ runCatching { pfd?.close() }+ writer = null+ pfd = null+ // Clear gaveUp so the fresh open() actually retries instead of immediately+ // dropping; cancel any prior connect coroutine before launching a new one.+ gaveUp = false+ warnedUnavailable = false+ runCatching { connectJob?.cancel() }+ open()+ }+@Synchronized private fun sendOrQueue(line: String) {val w = writerwhen {- w != null -> runCatching { w.println(line) }- .onFailure { Log.w(TAG, "send failed: $line", it) }+ w != null -> writeLine(w, line)closed || gaveUp -> {// Channel will never connect (gave up) or is shutting down:// drop with a single warning instead of growing `pending`.diff --git a/app/src/main/java/com/excp/podroid/engine/avf/VsockPortForwarder.kt b/app/src/main/java/com/excp/podroid/engine/avf/VsockPortForwarder.ktindex 577b864..32f2e2b 100644--- a/app/src/main/java/com/excp/podroid/engine/avf/VsockPortForwarder.kt+++ b/app/src/main/java/com/excp/podroid/engine/avf/VsockPortForwarder.kt@@ -26,6 +26,7 @@ import kotlinx.coroutines.coroutineScopeimport kotlinx.coroutines.delayimport kotlinx.coroutines.launchimport kotlinx.coroutines.selects.select+import kotlinx.coroutines.sync.Semaphoreimport java.io.InputStreamimport java.io.OutputStreamimport java.net.InetAddress@@ -48,6 +49,11 @@ class VsockPortForwarder(// Mirror the control channel's retry, but briefly (per-connection).private const val CONNECT_ATTEMPTS = 6private const val CONNECT_RETRY_MS = 250L+ // Hard ceiling on simultaneous in-flight proxy connections. A burst+ // against 0.0.0.0:hostPort while the guest agent isn't up would otherwise+ // launch one coroutine per inbound TCP connection, each holding a socket+ // for up to ~1.5s of connect retries — an unbounded fd/coroutine spike.+ private const val MAX_INFLIGHT = 64}private var server: ServerSocket? = null@@ -59,6 +65,11 @@ class VsockPortForwarder(// Live client sockets — force-closed in close() so a pump blocked in a// native read() unblocks (cancel() alone can't interrupt a blocking read).private val openSockets = java.util.Collections.synchronizedSet(mutableSetOf<Socket>())+ // Caps concurrent in-flight proxy() coroutines so an accept burst can't+ // exhaust fds/coroutines. tryAcquire (non-suspending) keeps the accept loop+ // hot: when the cap is hit we drop the new connection immediately rather than+ // parking coroutines that would each pin a socket while waiting for a permit.+ private val inflight = Semaphore(MAX_INFLIGHT)@Volatile private var closed = falsefun start() {@@ -68,8 +79,15 @@ class VsockPortForwarder(acceptJob = scope.launch(Dispatchers.IO) {while (!closed) {val client = try { s.accept() } catch (_: SocketException) { break }+ if (!inflight.tryAcquire()) {+ Log.w(TAG, "inflight cap ($MAX_INFLIGHT) reached on :$hostPort; dropping connection")+ runCatching { client.close() }+ continue+ }openSockets.add(client)- scope.launch(Dispatchers.IO + connections) { proxy(client) }+ scope.launch(Dispatchers.IO + connections) {+ try { proxy(client) } finally { inflight.release() }+ }}}}