Skip to content

A rootless Android app that boots Alpine Linux: run containers (Podman/Docker/LXC) and GUI desktop apps.

fix(stats): send the container count over the host bridge

ExTv368cae9f5a66
diff --git a/CLAUDE.md b/CLAUDE.md
index 3526d90..136cbd5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -111,7 +111,7 @@ On **AVF** there is no QMP and no PL011: the console is captured via `ConsoleFan
### Guest → Android host bridge
-Lets guest processes call back to Android. Guest side: `podroid-hostd` (multi-call C binary, `build-rootfs/host-bridge/podroid-hostd.c`) owns a guest-local `AF_UNIX` socket `/run/podroid-host.sock`; `argv[0]` dispatch also exposes it as `podroid-notify` and `podroid-forward` (symlinks). The daemon relays one request line / one response line to Android over a backend transport: `/dev/hvc2` on QEMU, `AF_VSOCK:9101` on AVF (chosen by the `podroid.backend=avf` cmdline marker). Android side: `engine/hostbridge/` - `HostRequestServer` reads requests over a `HostTransport` (`QemuHostTransport` via `LocalSocket` to `host.sock`, or `AvfHostTransport` via `connectVsock`), `HostRequestDispatcher` parses them, and routes to `NotificationPoster` (posts via `NotificationManagerCompat`) or `PortForwardRepository` (rules persist and `EngineHolder` applies them live). `PodroidService` starts/stops the server over the VM lifecycle. Stop or parent cancellation shuts down the active transport to unblock reads; a transport returned by a late native connect is closed without dispatching. Android accepts only complete UTF-8 request lines up to 8191 bytes (matching the guest buffer). Free-text fields are base64 (`HostProtocol.kt`) so UTF-8 survives.
+Lets guest processes call back to Android. Guest side: `podroid-hostd` (multi-call C binary, `build-rootfs/host-bridge/podroid-hostd.c`) owns a guest-local `AF_UNIX` socket `/run/podroid-host.sock`; `argv[0]` dispatch also exposes it as `podroid-notify` and `podroid-forward` (symlinks). The daemon relays one request line / one response line to Android over a backend transport: `/dev/hvc2` on QEMU, `AF_VSOCK:9101` on AVF (chosen by the `podroid.backend=avf` cmdline marker). Android side: `engine/hostbridge/` - `HostRequestServer` reads requests over a `HostTransport` (`QemuHostTransport` via `LocalSocket` to `host.sock`, or `AvfHostTransport` via `connectVsock`), `HostRequestDispatcher` parses them, and routes to `NotificationPoster` (posts via `NotificationManagerCompat`) or `PortForwardRepository` (rules persist and `EngineHolder` applies them live). `PodroidService` starts/stops the server over the VM lifecycle. Stop or parent cancellation shuts down the active transport to unblock reads; a transport returned by a late native connect is closed without dispatching. Android accepts only complete UTF-8 request lines up to 8191 bytes (matching the guest buffer). Free-text fields are base64 (`HostProtocol.kt`) so UTF-8 survives. The daemon also self-originates a `STATS containers=<n>` push (inotify-driven, debounced) whenever the podman container count changes, which `HostRequestDispatcher` persists to the `last_container_count` DataStore key for `HomeViewModel` to show live on Home - the same channel on both backends, no polling.
> **Gotcha:** `/dev/hvc2` is a virtio-console **TTY** that defaults to echo on. The daemon must `cfmakeraw()` it, or the TTY echoes Android's responses back and the protocol desyncs after the first request. AVF (a raw vsock socket) is unaffected.
@@ -163,7 +163,7 @@ Single-activity Compose app: `ui/navigation/NavGraph.kt` routes `setup → home
│ │ │ ├── control/ # ControlProvider: shell-only `adb shell content call` test interface
│ │ │ └── usb/ # UsbPassthroughManager
│ │ ├── service/PodroidService.kt # foreground service; owns VM lifecycle, wakelock, notification; also VmControlReceiver (boot autostart + START_VM/STOP_VM automation intents)
-│ │ ├── data/repository/ # Settings, PortForward, Update, Language, ContainerBackup, ContainerStats (all DataStore)
+│ │ ├── data/repository/ # Settings, PortForward, Update, Language, ContainerBackup (all DataStore)
│ │ ├── di/ # Hilt module
│ │ ├── util/ # NetworkUtils, ShellQuote, HostMetrics + VmLoadSampler (Status screen), DeviceResourcePolicy (load-balance sizing)
│ │ ├── x11/ # X11/VNC viewer engine
diff --git a/app/src/main/java/com/excp/podroid/data/repository/ContainerStatsRepository.kt b/app/src/main/java/com/excp/podroid/data/repository/ContainerStatsRepository.kt
deleted file mode 100644
index ded6297..0000000
--- a/app/src/main/java/com/excp/podroid/data/repository/ContainerStatsRepository.kt
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Podroid - Rootless Podman for Android
- * Copyright (C) 2024-2026 Podroid contributors
- *
- * Reads the container count written by the guest `podroid-update-stats` tool
- * into Downloads/Podroid/container-count when sharing is enabled.
- */
-package com.excp.podroid.data.repository
-
-import android.os.Environment
-import kotlinx.coroutines.Dispatchers
-import kotlinx.coroutines.withContext
-import java.io.File
-import javax.inject.Inject
-import javax.inject.Singleton
-
-@Singleton
-class ContainerStatsRepository @Inject constructor(
- private val settingsRepository: SettingsRepository,
-) {
- fun statsFile(): File {
- val downloads = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
- return File(File(downloads, "Podroid"), "container-count")
- }
-
- suspend fun readContainerCount(): Int? {
- val file = statsFile()
- val text = withContext(Dispatchers.IO) {
- if (!file.isFile) return@withContext null
- try {
- file.readText()
- } catch (e: java.io.IOException) {
- // isFile can succeed (stat) while the read still fails, e.g. no
- // all-files access to the shared Downloads dir (EACCES). Fall
- // back to the cached count instead of crashing the caller.
- android.util.Log.w("ContainerStatsRepository", "failed to read $file", e)
- null
- } catch (e: SecurityException) {
- android.util.Log.w("ContainerStatsRepository", "failed to read $file", e)
- null
- }
- } ?: return settingsRepository.getLastContainerCount()
- val parsed = text.trim().toIntOrNull() ?: return settingsRepository.getLastContainerCount()
- settingsRepository.setLastContainerCount(parsed)
- return parsed
- }
-}
diff --git a/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt b/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
index 4ab4af2..c2c6538 100644
--- a/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
+++ b/app/src/main/java/com/excp/podroid/data/repository/SettingsRepository.kt
@@ -195,10 +195,10 @@ class SettingsRepository @Inject constructor(
suspend fun setDynamicColorEnabled(value: Boolean) = set(KEY_DYNAMIC_COLOR_ENABLED, value)
suspend fun setLastBootDurationMs(value: Long) = set(KEY_LAST_BOOT_DURATION_MS, value)
suspend fun setLastContainerCount(value: Int) = set(KEY_LAST_CONTAINER_COUNT, value)
- suspend fun getLastContainerCount(): Int? {
- val v = context.dataStore.data.first()[KEY_LAST_CONTAINER_COUNT] ?: -1
- return if (v < 0) null else v
- }
+ // Guest push over the host bridge (STATS verb) keeps this live; -1/missing means null.
+ val lastContainerCount: Flow<Int?> = context.dataStore.data
+ .catch { e -> if (e is IOException) emit(emptyPreferences()) else throw e }
+ .map { (it[KEY_LAST_CONTAINER_COUNT] ?: -1).let { v -> if (v < 0) null else v } }
suspend fun setLanguage(value: String) = set(KEY_LANGUAGE, value)
suspend fun setEngineSelection(value: EngineSelection) = set(KEY_ENGINE_SELECTION, value.name)
suspend fun setAvfHintDismissed(value: Boolean) = set(KEY_AVF_HINT_DISMISSED, value)
diff --git a/app/src/main/java/com/excp/podroid/engine/hostbridge/HostRequestDispatcher.kt b/app/src/main/java/com/excp/podroid/engine/hostbridge/HostRequestDispatcher.kt
index 764a751..6974722 100644
--- a/app/src/main/java/com/excp/podroid/engine/hostbridge/HostRequestDispatcher.kt
+++ b/app/src/main/java/com/excp/podroid/engine/hostbridge/HostRequestDispatcher.kt
@@ -22,11 +22,13 @@ class HostRequestDispatcher(
private val openUrl: suspend (String) -> String,
private val power: suspend (String) -> String,
private val setHeadless: suspend (String) -> String,
+ private val setContainerCount: suspend (Int) -> Unit,
) {
private val validProtocols = setOf("tcp", "udp")
private companion object {
private val WHITESPACE = Regex("\\s+")
+ private val STATS_ARG = Regex("^containers=(\\d+)$")
}
suspend fun handle(line: String): String {
@@ -45,6 +47,7 @@ class HostRequestDispatcher(
"OPEN" -> handleOpen(parts)
"POWER" -> handlePower(parts)
"HEADLESS" -> handleHeadless(parts)
+ "STATS" -> handleStats(parts)
"PING" -> "PONG"
else -> HostProtocol.err("bad request")
}
@@ -139,4 +142,14 @@ class HostRequestDispatcher(
if (p[1] !in setOf("on", "off", "status")) return HostProtocol.err("usage: on|off|status")
return setHeadless(p[1])
}
+
+ // STATS containers=<n>, 0..100000
+ private suspend fun handleStats(p: List<String>): String {
+ if (p.size != 2) return HostProtocol.err("bad request")
+ val count = STATS_ARG.matchEntire(p[1])?.groupValues?.get(1)?.toIntOrNull()
+ ?: return HostProtocol.err("bad request")
+ if (count !in 0..100000) return HostProtocol.err("bad request")
+ setContainerCount(count)
+ return HostProtocol.ok()
+ }
}
diff --git a/app/src/main/java/com/excp/podroid/service/PodroidService.kt b/app/src/main/java/com/excp/podroid/service/PodroidService.kt
index bb6a68c..d6a2403 100644
--- a/app/src/main/java/com/excp/podroid/service/PodroidService.kt
+++ b/app/src/main/java/com/excp/podroid/service/PodroidService.kt
@@ -317,6 +317,7 @@ class PodroidService : Service() {
openUrl = { handleOpenUrl(it) },
power = { handlePowerRequest(it) },
setHeadless = { handleHeadlessRequest(it) },
+ setContainerCount = { settingsRepository.setLastContainerCount(it) },
)
return com.excp.podroid.engine.hostbridge.HostRequestServer(
openTransport = { engine.openHostTransport() },
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt
index 08f1bf0..65e2ec8 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeScreen.kt
@@ -127,7 +127,6 @@ fun HomeScreen(
val observer = LifecycleEventObserver { _, event ->
if (event == Lifecycle.Event.ON_RESUME) {
phoneIp = viewModel.phoneIp()
- viewModel.refreshContainerCount()
permissionsGrantVersion++
}
}
diff --git a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt
index 0b9606c..e7ac873 100644
--- a/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt
+++ b/app/src/main/java/com/excp/podroid/ui/screens/home/HomeViewModel.kt
@@ -5,7 +5,6 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.excp.podroid.BuildConfig
import com.excp.podroid.R
-import com.excp.podroid.data.repository.ContainerStatsRepository
import com.excp.podroid.data.repository.PortForwardRepository
import com.excp.podroid.data.repository.SettingsRepository
import com.excp.podroid.data.repository.UpdateInfo
@@ -59,7 +58,6 @@ class HomeViewModel @Inject constructor(
private val engine: EngineHolder,
private val settingsRepository: SettingsRepository,
private val portForwardRepository: PortForwardRepository,
- private val containerStatsRepository: ContainerStatsRepository,
private val updateRepository: UpdateRepository,
) : ViewModel() {
@@ -73,8 +71,11 @@ class HomeViewModel @Inject constructor(
val bootStage: StateFlow<String> = engine.bootStage
.stateIn(viewModelScope, SharingStarted.Eagerly, "")
- private val _containerCount = MutableStateFlow<Int?>(null)
- val containerCount: StateFlow<Int?> = _containerCount.asStateFlow()
+ // Pushed live by the guest over the host bridge (STATS verb), persisted via
+ // SettingsRepository.setLastContainerCount and read back here as a Flow -
+ // works identically on both backends, no polling needed.
+ val containerCount: StateFlow<Int?> = settingsRepository.lastContainerCount
+ .stateIn(viewModelScope, SharingStarted.Eagerly, null)
/** Aggregated metadata for the Home data sections. */
val meta: StateFlow<HomeMeta> = combine(
@@ -194,24 +195,6 @@ class HomeViewModel @Inject constructor(
init {
checkForUpdate()
- viewModelScope.launch {
- val cached = settingsRepository.getLastContainerCount()
- if (cached != null) _containerCount.value = cached
- }
- viewModelScope.launch {
- var lastRunning = false
- engine.state.collect { state ->
- val running = state is VmState.Running
- if (running && !lastRunning) refreshContainerCount()
- lastRunning = running
- }
- }
- viewModelScope.launch {
- while (true) {
- if (engine.state.value is VmState.Running) refreshContainerCount()
- delay(5_000)
- }
- }
}
/** Format "Up Xm Ys" / "Up Xh Ym" from the engine's →Running timestamp. */
@@ -246,12 +229,6 @@ class HomeViewModel @Inject constructor(
viewModelScope.launch { settingsRepository.setAvfHintDismissed(true) }
}
- fun refreshContainerCount() {
- viewModelScope.launch {
- _containerCount.value = containerStatsRepository.readContainerCount()
- }
- }
-
fun startPodroid() = PodroidService.start(context)
fun stopVm() = PodroidService.stop(context)
diff --git a/app/src/test/java/com/excp/podroid/engine/hostbridge/HostRequestDispatcherTest.kt b/app/src/test/java/com/excp/podroid/engine/hostbridge/HostRequestDispatcherTest.kt
index 5f066dc..515582c 100644
--- a/app/src/test/java/com/excp/podroid/engine/hostbridge/HostRequestDispatcherTest.kt
+++ b/app/src/test/java/com/excp/podroid/engine/hostbridge/HostRequestDispatcherTest.kt
@@ -36,6 +36,7 @@ private fun dispatcher(
openUrl: suspend (String) -> String = { HostProtocol.ok() },
power: suspend (String) -> String = { HostProtocol.ok() },
setHeadless: suspend (String) -> String = { HostProtocol.ok() },
+ setContainerCount: suspend (Int) -> Unit = {},
addResult: AddRuleResult = AddRuleResult.ADDED,
) = HostRequestDispatcher(
notifications = poster,
@@ -52,6 +53,7 @@ private fun dispatcher(
openUrl = openUrl,
power = power,
setHeadless = setHeadless,
+ setContainerCount = setContainerCount,
)
class HostRequestDispatcherTest {
@@ -198,4 +200,46 @@ class HostRequestDispatcherTest {
assertEquals("on", seen)
assertTrue(d.handle("HEADLESS sideways").startsWith("ERR "))
}
+
+ @Test fun statsPersistsAndReturnsOk() = runBlocking {
+ var seen: Int? = null
+ val d = dispatcher(setContainerCount = { seen = it })
+ assertEquals("OK", d.handle("STATS containers=3"))
+ assertEquals(3, seen)
+ }
+
+ @Test fun statsRejectsMissingArg() = runBlocking {
+ var seen: Int? = null
+ val d = dispatcher(setContainerCount = { seen = it })
+ assertTrue(d.handle("STATS").startsWith("ERR "))
+ assertEquals(null, seen)
+ }
+
+ @Test fun statsRejectsNonNumeric() = runBlocking {
+ var seen: Int? = null
+ val d = dispatcher(setContainerCount = { seen = it })
+ assertTrue(d.handle("STATS containers=abc").startsWith("ERR "))
+ assertEquals(null, seen)
+ }
+
+ @Test fun statsRejectsNegative() = runBlocking {
+ var seen: Int? = null
+ val d = dispatcher(setContainerCount = { seen = it })
+ assertTrue(d.handle("STATS containers=-1").startsWith("ERR "))
+ assertEquals(null, seen)
+ }
+
+ @Test fun statsRejectsOverRange() = runBlocking {
+ var seen: Int? = null
+ val d = dispatcher(setContainerCount = { seen = it })
+ assertTrue(d.handle("STATS containers=100001").startsWith("ERR "))
+ assertEquals(null, seen)
+ }
+
+ @Test fun statsRejectsWrongKeyName() = runBlocking {
+ var seen: Int? = null
+ val d = dispatcher(setContainerCount = { seen = it })
+ assertTrue(d.handle("STATS count=3").startsWith("ERR "))
+ assertEquals(null, seen)
+ }
}
diff --git a/app/src/test/java/com/excp/podroid/engine/hostbridge/HostRequestServerTest.kt b/app/src/test/java/com/excp/podroid/engine/hostbridge/HostRequestServerTest.kt
index d24016f..5f63bdf 100644
--- a/app/src/test/java/com/excp/podroid/engine/hostbridge/HostRequestServerTest.kt
+++ b/app/src/test/java/com/excp/podroid/engine/hostbridge/HostRequestServerTest.kt
@@ -245,6 +245,7 @@ class HostRequestServerTest {
openUrl = openUrl,
power = { HostProtocol.ok() },
setHeadless = { HostProtocol.ok() },
+ setContainerCount = {},
)
private class BlockingTransport(private val resultAfterClose: String? = null) : HostTransport {
@@ -278,7 +279,6 @@ class HostRequestServerTest {
if (closeCount.incrementAndGet() == 1) closed.countDown()
}
}
-}
/** Throws [failure] from its first read, then reports EOF so the loop does not spin. */
private class ThrowingTransport(private val failure: Exception) : HostTransport {
@@ -296,3 +296,4 @@ class HostRequestServerTest {
if (closeCount.incrementAndGet() == 1) closed.countDown()
}
}
+}
diff --git a/build-rootfs/build-rootfs.sh b/build-rootfs/build-rootfs.sh
index 206ba9b..6105097 100755
--- a/build-rootfs/build-rootfs.sh
+++ b/build-rootfs/build-rootfs.sh
@@ -115,7 +115,6 @@ cp /work/files/usr/local/bin/podroid-resize "$ROOTFS/usr/local/bin/"
cp /work/files/usr/local/bin/podroid-login "$ROOTFS/usr/local/bin/"
cp /work/files/usr/local/bin/podroid-getty "$ROOTFS/usr/local/bin/"
cp /work/files/usr/local/bin/podroid-backup "$ROOTFS/usr/local/bin/"
-cp /work/files/usr/local/bin/podroid-update-stats "$ROOTFS/usr/local/bin/"
# podroid-vsock-agent is COPY'd in from the vsock-builder Docker stage. Make
# sure it's executable (cross-arch COPY can lose the mode bit on some buildkit
# versions).
diff --git a/build-rootfs/files/etc/init.d/podroid-downloads b/build-rootfs/files/etc/init.d/podroid-downloads
index 6a1b41b..011a8d4 100644
--- a/build-rootfs/files/etc/init.d/podroid-downloads
+++ b/build-rootfs/files/etc/init.d/podroid-downloads
@@ -25,6 +25,19 @@ start() {
--stderr /var/log/podroid-downloads.log \
--exec /usr/local/bin/podroid-vsock-agent -- downloads-9p
eend $?
+
+ # One-time cleanup of the stray container-count file an older Podroid
+ # version wrote into the user's real Downloads dir (the guest host bridge's
+ # STATS push replaced it). Detached because the 9p mount above completes
+ # asynchronously once Android accepts the vsock rendezvous; rm -f is
+ # idempotent so giving up after the wait just leaves it for next boot.
+ ( _i=0
+ while [ "$_i" -lt 30 ] && ! mountpoint -q /mnt/downloads 2>/dev/null; do
+ sleep 1
+ _i=$((_i + 1))
+ done
+ rm -f /mnt/downloads/Podroid/container-count 2>/dev/null
+ ) &
}
stop() {
diff --git a/build-rootfs/files/etc/init.d/podroid-ready b/build-rootfs/files/etc/init.d/podroid-ready
index b618c4e..8f5d3c6 100644
--- a/build-rootfs/files/etc/init.d/podroid-ready
+++ b/build-rootfs/files/etc/init.d/podroid-ready
@@ -21,9 +21,6 @@ start() {
done
# Emit the boot stages BootStageDetector expects.
- if [ -x /usr/local/bin/podroid-update-stats ]; then
- /usr/local/bin/podroid-update-stats || true
- fi
echo "Starting SSH..." > /dev/console
echo "Almost ready..." > /dev/console
echo "Ready!" > /dev/console
diff --git a/build-rootfs/files/usr/local/bin/podroid-backup b/build-rootfs/files/usr/local/bin/podroid-backup
index c951380..3045bd2 100644
--- a/build-rootfs/files/usr/local/bin/podroid-backup
+++ b/build-rootfs/files/usr/local/bin/podroid-backup
@@ -26,12 +26,6 @@ notify_err() {
fi
}
-refresh_stats() {
- if [ -x /usr/local/bin/podroid-update-stats ]; then
- /usr/local/bin/podroid-update-stats || true
- fi
-}
-
usage() {
cat <<'EOF'
usage:
@@ -75,7 +69,6 @@ cmd_export() {
fi
echo "exported $name -> $out"
notify_ok "Exported container $name"
- refresh_stats
}
cmd_save() {
@@ -93,7 +86,6 @@ cmd_save() {
fi
echo "saved $ref -> $out"
notify_ok "Saved image $ref"
- refresh_stats
}
cmd_all() {
@@ -116,7 +108,6 @@ cmd_all() {
done
notify_ok "Backed up $ok container(s)${fail:+, $fail failed}"
echo "done: $ok ok, $fail failed"
- refresh_stats
}
main() {
diff --git a/build-rootfs/files/usr/local/bin/podroid-update-stats b/build-rootfs/files/usr/local/bin/podroid-update-stats
deleted file mode 100644
index 1dd71f5..0000000
--- a/build-rootfs/files/usr/local/bin/podroid-update-stats
+++ /dev/null
@@ -1,16 +0,0 @@
-#!/bin/sh
-# Write Podman container count for the Android app (Downloads/Podroid/container-count).
-set -eu
-
-count=0
-if command -v podman >/dev/null 2>&1; then
- count="$(podman ps -aq 2>/dev/null | wc -l | tr -d ' ')"
-fi
-
-mkdir -p /var/lib/podroid
-printf '%s\n' "$count" > /var/lib/podroid/container-count
-
-if mountpoint -q /mnt/downloads 2>/dev/null; then
- mkdir -p /mnt/downloads/Podroid
- printf '%s\n' "$count" > /mnt/downloads/Podroid/container-count
-fi
diff --git a/build-rootfs/host-bridge/podroid-hostd.c b/build-rootfs/host-bridge/podroid-hostd.c
index b25009d..9fa3844 100644
--- a/build-rootfs/host-bridge/podroid-hostd.c
+++ b/build-rootfs/host-bridge/podroid-hostd.c
@@ -18,6 +18,7 @@
* QEMU (otherwise): open /dev/hvc2.
*/
#define _GNU_SOURCE
+#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <libgen.h>
@@ -27,11 +28,13 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
+#include <sys/inotify.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/un.h>
#include <termios.h>
+#include <time.h>
#include <unistd.h>
#define SOCK_PATH "/run/podroid-host.sock"
@@ -39,6 +42,15 @@
#define VSOCK_PORT 9101
#define HOST_TIMEOUT_S 5
+/* Podman container count, pushed to Android over the host channel instead of
+ * being polled: graphroot is pinned in
+ * build-rootfs/files/etc/containers/storage.conf, and podman creates one
+ * subdirectory per container here, named by its 64-char hex id. */
+#define STATS_DIR "/var/lib/containers/storage/overlay-containers"
+#define STATS_DEBOUNCE_MS 500
+#define STATS_SLOW_TICK_MS 15000
+#define STATS_WATCH_MASK (IN_CREATE | IN_DELETE | IN_MOVED_FROM | IN_MOVED_TO | IN_DELETE_SELF | IN_MOVE_SELF)
+
/* base64 (standard alphabet, no wrap) */
static const char B64[] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
@@ -385,6 +397,174 @@ static int make_vsock_listener(void) {
return fd;
}
+/* Opens the host channel if not already open: accepts Android's vsock
+ * connection on AVF (bounded by HOST_TIMEOUT_S so a slow or absent Android
+ * side can't wedge the caller), or opens /dev/hvc2 on QEMU. No-op if already
+ * connected. Returns 1 if this call established a fresh connection, 0 if
+ * already connected, -1 on failure. */
+static int ensure_host_fd(int *host_fd, int avf, int vsock_listener) {
+ if (*host_fd >= 0) return 0;
+ if (avf) {
+ struct pollfd pfd = { .fd = vsock_listener, .events = POLLIN };
+ int pr;
+ do { pr = poll(&pfd, 1, HOST_TIMEOUT_S * 1000); } while (pr < 0 && errno == EINTR);
+ if (pr > 0) *host_fd = accept(vsock_listener, NULL, NULL);
+ } else {
+ *host_fd = open(HVC_PATH, O_RDWR | O_NOCTTY);
+ }
+ if (*host_fd < 0) return -1;
+ set_raw_if_tty(*host_fd);
+ return 1;
+}
+
+/* Writes `req` to the already-open host channel and reads one response line
+ * into resp, draining any stale bytes first so resp always corresponds to
+ * req. Same return convention as read_line_timeout. The one path to the host
+ * channel - both CLI relaying and the daemon's own STATS push go through it. */
+static int host_roundtrip(int host_fd, const char *req, char *resp, size_t cap) {
+ drain_pending(host_fd); /* clear any stale/orphaned bytes so resp matches this req */
+ if (write_line(host_fd, req) < 0) return -1;
+ return read_line_timeout(host_fd, resp, cap, HOST_TIMEOUT_S);
+}
+
+static long long mono_ms(void) {
+ struct timespec ts;
+ clock_gettime(CLOCK_MONOTONIC, &ts);
+ return (long long)ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
+}
+
+/* podman names one overlay-containers subdirectory per container after its
+ * 64-character lowercase hex id. */
+static int is_container_id(const char *name) {
+ size_t len = strlen(name);
+ if (len != 64) return 0;
+ for (size_t i = 0; i < len; i++) {
+ char c = name[i];
+ if (!((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'))) return 0;
+ }
+ return 1;
+}
+
+/* Counts podman containers by counting STATS_DIR subdirectories whose name is
+ * a container id. Never execs podman or parses JSON. A missing directory (no
+ * containers created yet) counts as 0. */
+static int count_containers(void) {
+ DIR *dir = opendir(STATS_DIR);
+ if (!dir) {
+ if (errno != ENOENT)
+ fprintf(stderr, "podroid-hostd: opendir %s: %s\n", STATS_DIR, strerror(errno));
+ return 0;
+ }
+ int count = 0;
+ struct dirent *ent;
+ while ((ent = readdir(dir)) != NULL) {
+ if (!is_container_id(ent->d_name)) continue;
+ if (ent->d_type == DT_DIR) {
+ count++;
+ } else if (ent->d_type == DT_UNKNOWN) {
+ /* Some filesystems never fill d_type in; fall back to stat(). */
+ char path[sizeof(STATS_DIR) + 66];
+ snprintf(path, sizeof(path), "%s/%s", STATS_DIR, ent->d_name);
+ struct stat st;
+ if (stat(path, &st) == 0 && S_ISDIR(st.st_mode)) count++;
+ }
+ }
+ closedir(dir);
+ return count;
+}
+
+/* Guest-side state for the STATS push: change detection (inotify), debounce
+ * and the last count Android acknowledged. No threads - this lives entirely
+ * in the daemon's single event loop. */
+struct stats_state {
+ int inotify_fd; /* -1 if inotify_init1 failed: feature disabled */
+ int wd; /* -1 if STATS_DIR isn't currently watched */
+ int last_acked; /* -1 = nothing acknowledged yet (forces a first push) */
+ int dirty; /* 1 = current count may differ from last_acked */
+ long long debounce_until_ms; /* 0 = no debounce pending */
+ long long next_slow_tick_ms;
+};
+
+/* Establishes the inotify watch on STATS_DIR if it isn't already watched.
+ * Safe to call when the directory doesn't exist yet (podman hasn't created a
+ * container) - just retried on the next slow tick. */
+static void stats_try_watch(struct stats_state *st) {
+ if (st->inotify_fd < 0 || st->wd >= 0) return;
+ int wd = inotify_add_watch(st->inotify_fd, STATS_DIR, STATS_WATCH_MASK);
+ if (wd >= 0) {
+ st->wd = wd;
+ st->dirty = 1; /* may have missed changes while unwatched */
+ } else if (errno != ENOENT) {
+ fprintf(stderr, "podroid-hostd: inotify_add_watch %s: %s\n", STATS_DIR, strerror(errno));
+ }
+}
+
+static void stats_init(struct stats_state *st) {
+ st->inotify_fd = inotify_init1(IN_NONBLOCK);
+ if (st->inotify_fd < 0)
+ fprintf(stderr, "podroid-hostd: inotify_init1: %s\n", strerror(errno));
+ st->wd = -1;
+ st->last_acked = -1;
+ st->dirty = 1; /* push the current count once the host channel is up */
+ st->debounce_until_ms = 0;
+ st->next_slow_tick_ms = mono_ms() + STATS_SLOW_TICK_MS;
+ stats_try_watch(st);
+}
+
+/* Drains pending inotify events (the fd is O_NONBLOCK, so this never blocks)
+ * and marks the count dirty with a fresh debounce deadline, so a burst of
+ * events (e.g. `podman run --rm`) coalesces into one push. */
+static void stats_drain_inotify(struct stats_state *st) {
+ char buf[4096] __attribute__((aligned(__alignof__(struct inotify_event))));
+ for (;;) {
+ ssize_t n = read(st->inotify_fd, buf, sizeof(buf));
+ if (n < 0) {
+ if (errno == EINTR) continue;
+ break; /* EAGAIN: drained */
+ }
+ if (n == 0) break;
+ ssize_t off = 0;
+ while (off < n) {
+ struct inotify_event *ev = (struct inotify_event *)(buf + off);
+ if (ev->mask & (IN_DELETE_SELF | IN_MOVE_SELF | IN_IGNORED)) {
+ /* The watched directory itself is gone; the slow tick
+ * re-establishes the watch once it reappears. */
+ st->wd = -1;
+ }
+ off += (ssize_t)(sizeof(struct inotify_event) + ev->len);
+ }
+ st->dirty = 1;
+ st->debounce_until_ms = mono_ms() + STATS_DEBOUNCE_MS;
+ }
+}
+
+/* Sends the current count over the host channel, reusing ensure_host_fd() /
+ * host_roundtrip() - no second code path to the host channel. Unless `force`,
+ * skips the roundtrip entirely when the count already matches the last value
+ * Android acknowledged. Leaves `dirty` set on any failure (no channel, no
+ * reply, unexpected reply) so the caller retries on the next slow tick;
+ * never busy-loops and never blocks longer than ensure_host_fd's own
+ * HOST_TIMEOUT_S bound. */
+static void stats_push(struct stats_state *st, int *host_fd, int avf, int vsock_listener, int force) {
+ int count = count_containers();
+ if (!force && count == st->last_acked) { st->dirty = 0; return; }
+ if (ensure_host_fd(host_fd, avf, vsock_listener) < 0) { st->dirty = 1; return; }
+ char req[64], resp[32];
+ snprintf(req, sizeof(req), "STATS containers=%d", count);
+ int hn = host_roundtrip(*host_fd, req, resp, sizeof(resp));
+ if (hn <= 0) {
+ if (hn != LINE_TOO_LONG) { close(*host_fd); *host_fd = -1; }
+ st->dirty = 1;
+ return;
+ }
+ if (strcmp(resp, "OK") == 0) {
+ st->last_acked = count;
+ st->dirty = 0;
+ } else {
+ st->dirty = 1; /* unexpected reply: don't assume it was acknowledged */
+ }
+}
+
static int daemon_main(void) {
signal(SIGPIPE, SIG_IGN);
int avf = is_avf();
@@ -397,8 +577,50 @@ static int daemon_main(void) {
if (vsock_listener < 0) { perror("podroid-hostd: vsock listener"); return 1; }
}
+ struct stats_state stats;
+ stats_init(&stats);
+
int host_fd = -1;
for (;;) {
+ struct pollfd pfds[2];
+ pfds[0].fd = cli_listener; pfds[0].events = POLLIN; pfds[0].revents = 0;
+ int nfds = 1;
+ int inotify_idx = -1;
+ if (stats.inotify_fd >= 0) {
+ inotify_idx = nfds;
+ pfds[nfds].fd = stats.inotify_fd; pfds[nfds].events = POLLIN; pfds[nfds].revents = 0;
+ nfds++;
+ }
+
+ long long now = mono_ms();
+ long long deadline = stats.next_slow_tick_ms;
+ if (stats.debounce_until_ms != 0 && stats.debounce_until_ms < deadline)
+ deadline = stats.debounce_until_ms;
+ int timeout_ms = (int)(deadline > now ? deadline - now : 0);
+
+ int pr = poll(pfds, (nfds_t)nfds, timeout_ms);
+ if (pr < 0) { if (errno == EINTR) continue; break; }
+
+ if (inotify_idx >= 0 && (pfds[inotify_idx].revents & POLLIN))
+ stats_drain_inotify(&stats);
+
+ /* Act on whichever timer fired: re-establish the watch if it's down,
+ * and push a dirty count once the debounce (or the slow-tick catch-all
+ * for a failed/missed push) elapses. */
+ now = mono_ms();
+ int slow_tick_due = now >= stats.next_slow_tick_ms;
+ int debounce_due = stats.debounce_until_ms != 0 && now >= stats.debounce_until_ms;
+ if (slow_tick_due) {
+ stats.next_slow_tick_ms = now + STATS_SLOW_TICK_MS;
+ if (stats.wd < 0) stats_try_watch(&stats);
+ }
+ if (slow_tick_due || debounce_due) {
+ stats.debounce_until_ms = 0;
+ if (stats.dirty) stats_push(&stats, &host_fd, avf, vsock_listener, 0);
+ }
+
+ if (!(pfds[0].revents & POLLIN)) continue;
+
int cli = accept(cli_listener, NULL, NULL);
if (cli < 0) { if (errno == EINTR) continue; break; }
@@ -413,28 +635,11 @@ static int daemon_main(void) {
if (rn == LINE_TOO_LONG) { write_line(cli, "ERR cmVxdWVzdCB0b28gbG9uZw=="); close(cli); continue; }
if (rn <= 0) { close(cli); continue; }
- if (host_fd < 0) {
- if (avf) {
- /* Bound the wait for Android's vsock connection: without this,
- * a slow or absent Android side would block accept() forever,
- * wedging the single-threaded loop and every other podroid-*
- * call behind this one CLI connection. */
- struct pollfd pfd = { .fd = vsock_listener, .events = POLLIN };
- int pr;
- do { pr = poll(&pfd, 1, HOST_TIMEOUT_S * 1000); } while (pr < 0 && errno == EINTR);
- if (pr > 0) host_fd = accept(vsock_listener, NULL, NULL);
- } else {
- host_fd = open(HVC_PATH, O_RDWR | O_NOCTTY);
- }
- if (host_fd >= 0) set_raw_if_tty(host_fd);
- }
- if (host_fd < 0) { write_line(cli, "ERR aG9zdCBjaGFubmVsIG5vdCBjb25uZWN0ZWQ="); close(cli); continue; }
+ int conn = ensure_host_fd(&host_fd, avf, vsock_listener);
+ if (conn < 0) { write_line(cli, "ERR aG9zdCBjaGFubmVsIG5vdCBjb25uZWN0ZWQ="); close(cli); continue; }
char resp[8192];
- drain_pending(host_fd); /* clear any stale/orphaned bytes so resp matches this req */
- int hn = write_line(host_fd, req) < 0
- ? -1
- : read_line_timeout(host_fd, resp, sizeof(resp), HOST_TIMEOUT_S);
+ int hn = host_roundtrip(host_fd, req, resp, sizeof(resp));
/* "response too long": the channel is still aligned, since the reader
* consumed the rest of the line, so keep the connection and just refuse
* to pass on a half a reply. */
@@ -447,6 +652,11 @@ static int daemon_main(void) {
}
write_line(cli, resp);
close(cli);
+
+ /* A fresh host connection means Android's server just (re)started (or
+ * this is the first connection since boot); push the current count
+ * once instead of waiting on the next change or slow tick. */
+ if (conn == 1) stats_push(&stats, &host_fd, avf, vsock_listener, 1);
}
return 0;
}