diff --git a/controller/app/src/main/java/org/iiab/controller/IIABApplication.java b/controller/app/src/main/java/org/iiab/controller/IIABApplication.java index fe3349335..62cd2d9b3 100644 --- a/controller/app/src/main/java/org/iiab/controller/IIABApplication.java +++ b/controller/app/src/main/java/org/iiab/controller/IIABApplication.java @@ -29,9 +29,11 @@ public void onCreate() { super.onCreate(); // ADFA-4640: wire up persistence for the server log (survives app restarts). org.iiab.controller.LogRepository.get().init(this); - // ADFA-5343 (Phase 1): establish the app-scoped server-lifecycle reconciler. Log-only for now, - // fed by the status poll; it gains its own tick + WatchdogService promotion in a later phase. - org.iiab.controller.env.ServerLifecycleReconciler.get(); + // ADFA-5343 (Phase 1): establish the app-scoped server-lifecycle reconciler. + // ADFA-5343 (Phase 4a): start its own background tick so it can bring the box up / re-drive a flap + // with NO foreground Activity. The tick stands down while an Activity is foregrounded (the Activity + // poll + bridge drive then); it only actuates OFF-UI when backgrounded. + org.iiab.controller.env.ServerLifecycleReconciler.get().startBackgroundTick(this); // We inject Conscrypt as the app's primary security provider try { Security.insertProviderAt(Conscrypt.newProvider(), 1); diff --git a/controller/app/src/main/java/org/iiab/controller/ServerController.java b/controller/app/src/main/java/org/iiab/controller/ServerController.java index 9a821e36d..5efa6f45f 100644 --- a/controller/app/src/main/java/org/iiab/controller/ServerController.java +++ b/controller/app/src/main/java/org/iiab/controller/ServerController.java @@ -16,7 +16,6 @@ */ package org.iiab.controller; -import org.iiab.controller.config.BoxEndpoints; import android.content.Context; import android.os.Handler; @@ -28,7 +27,7 @@ import java.io.File; -public class ServerController implements org.iiab.controller.env.ServerLifecycleReconciler.Actuator { +public class ServerController { private static final String TAG = "IIAB-ServerController"; private static final int CHECK_INTERVAL_MS = 3000; @@ -46,20 +45,11 @@ public class ServerController implements org.iiab.controller.env.ServerLifecycle public interface Host { void addToLog(String message); void startFusionPulse(); - void startExitPulse(); void stopBtnProgress(); void updateConnectivityLeds(boolean wifiOn, boolean hotspotOn); void refreshServerUi(); Boolean getTargetServerState(); void setTargetServerState(Boolean target); - boolean isNegotiating(); - void enableSystemProtection(); - void disableSystemProtection(); - /** ADFA-4834: the pdsm service currently stopping, for the shutdown screen. */ - default void onShutdownProgress(String service) {} - /** ADFA-4834: the graceful teardown finished (pdsm stop exited, proot killed, watchdog off). - * This is the real "everything is down" signal the close should hang off of. */ - default void onShutdownComplete() {} /** ADFA-4837: a start has begun. Fires immediately (before any pdsm output) so the boot * screen can show an animated "starting" message during the long silent warm-up, instead of * a blank line until the first pdsm service reports ~15s later. */ @@ -74,12 +64,8 @@ default void onStartupProgress(String service) {} private final Preferences prefs; public PRootEngine serverEngine; - private long serverUpSinceMs = 0L; private boolean isWifiActive = false; private boolean isHotspotActive = false; - private String currentTargetUrl = null; - // ADFA-4834: hard guard so a repeat "Turn off" tap never spawns a second concurrent pdsm stop. - private volatile boolean stopping = false; // ADFA-5103: an ensure-up decision or launch is in flight. Because the decision now runs off the // main thread, two concurrent startEnvironment() calls could each read /proc, both see nothing, // and both LAUNCH — the synchronous main-thread serialisation that used to prevent that is gone. @@ -103,10 +89,11 @@ default void onStartupProgress(String service) {} private final Handler timeoutHandler = new Handler(android.os.Looper.getMainLooper()); private Runnable timeoutRunnable; private final Handler serverCheckHandler = new Handler(android.os.Looper.getMainLooper()); + // ADFA-5343 (Phase 4d-2): connectivity-only poll now — server liveness moved to the reconciler tick, + // the single driver + publisher. This runnable just keeps the Wi-Fi/hotspot LEDs fresh. private final Runnable serverCheckRunnable = new Runnable() { @Override public void run() { - checkServerStatus(); updateConnectivityStatus(); serverCheckHandler.postDelayed(this, CHECK_INTERVAL_MS); } @@ -129,100 +116,18 @@ public void onResume() { updateConnectivityStatus(); // instant refresh when returning to the app serverCheckHandler.removeCallbacks(serverCheckRunnable); serverCheckHandler.post(serverCheckRunnable); - // ADFA-5343 (Phase 2): register as the foreground actuator the reconciler drives. Whichever - // Activity is resumed owns this slot; the reconciler boots through it (the one existing boot). - org.iiab.controller.env.ServerLifecycleReconciler.get().setActuator(this); } public void onPause() { serverCheckHandler.removeCallbacks(serverCheckRunnable); - // ADFA-5343 (Phase 2): release the actuator slot — but clearActuator only clears if we still - // hold it, so a resume/pause overlap does not wipe the next Activity's registration. - org.iiab.controller.env.ServerLifecycleReconciler.get().clearActuator(this); } - /** ADFA-5343 (Phase 2): the reconciler's boot entry point. Delegates to the one existing, idempotent - * boot path so no second actuator is introduced. */ - @Override - public void ensureServerUp() { - startEnvironment(); - } - - public String getCurrentTargetUrl() { return currentTargetUrl; } public boolean isWifiActive() { return isWifiActive; } public boolean isHotspotActive() { return isHotspotActive; } - // --- server-alive transition analytics ------------------------------------- - - private void updateServerAlive(boolean nowAlive) { - boolean wasAlive = ServerStateRepository.get().current().alive; - if (nowAlive && !wasAlive) { - serverUpSinceMs = System.currentTimeMillis(); - org.iiab.controller.analytics.AnalyticsClient.with(activity).logServerStarted(); - } else if (!nowAlive && wasAlive) { - long uptime = serverUpSinceMs > 0L ? System.currentTimeMillis() - serverUpSinceMs : -1L; - serverUpSinceMs = 0L; - org.iiab.controller.analytics.AnalyticsClient.with(activity).logServerStopped(uptime); - } - // The repository is updated by the poll (checkServerStatus) right after this. - } - - // --- status poll ------------------------------------------------------------ - - private void checkServerStatus() { - if (host.isNegotiating()) return; - - AppExecutors.get().io().execute(() -> { - // ADFA-5343 (Phase 0): one honest liveness snapshot instead of a single /home ping. - // nginx answers /home before its dash-node upstream is ready, so a restarting engine read - // as "up" (the flap). servicesAnswering probes /k2go-api (the usable signal); processPresent - // (/proc) is recorded for the richer phase the reconciler will consume in a later phase. - // alive stays a 1-bit fact (phase == UP) so ServerStateRepository and every reader are - // unchanged here — the only shift is that "up" now means the services answer, not nginx. - long now = android.os.SystemClock.elapsedRealtime(); - // Probe OUTSIDE the lock — RestReadiness.apiReady() can block ~2.5s and must never hold - // livenessLock (that would stall a concurrent boot reset). - boolean processPresent = org.iiab.controller.env.EnvironmentProcess.isRunning(activity); - boolean servicesAnswering = org.iiab.controller.redesign.RestReadiness.apiReady(); - // ADFA-5343a (D1) / ADFA-5343 (Phase 2): read prev and write the next snapshot atomically - // under livenessLock, so a boot-time reset (doLaunchEnvironment) is never clobbered by this - // poll writing a prev it had read before the reset. next() still measures CONTINUOUS downtime - // and resets it on an observation gap (a stale prev — e.g. the app was backgrounded). - org.iiab.controller.env.domain.ServerLiveness liveness; - synchronized (livenessLock) { - liveness = org.iiab.controller.env.domain.ServerLiveness.next( - lastLiveness, processPresent, servicesAnswering, now, - org.iiab.controller.env.domain.ServerLiveness.DEFAULT_FRESH_MS); - lastLiveness = liveness; - } - boolean localAlive = - liveness.phase(now) == org.iiab.controller.env.domain.ServerLiveness.Phase.UP; - - updateServerAlive(localAlive); - - // ADFA-4578: evaluate + publish the SystemState at app level (every poll), - // so every tab reflects the server live instead of only after visiting the Dashboard. - final SystemState sysState = SystemStateEvaluator.evaluate(activity, localAlive); - ServerStateRepository.get().post(ServerState.of(localAlive, sysState)); - - // ADFA-5343 (Phase 1): feed the same snapshot to the log-only reconciler — no second liveness - // source, no actuation. It logs desired-vs-actual each poll. Removing this line + the class is - // the full rollback. - org.iiab.controller.env.ServerLifecycleReconciler.get().observe(activity, liveness); - - // STATE MACHINE: Has the target state been reached? - Boolean target = host.getTargetServerState(); - if (target != null && ServerStateRepository.get().current().alive == target) { - host.setTargetServerState(null); // Transition complete! - timeoutHandler.removeCallbacks(timeoutRunnable); // Cancel safety net - activity.runOnUiThread(host::stopBtnProgress); - } - - currentTargetUrl = localAlive ? BoxEndpoints.BASE + "/home" : null; - - activity.runOnUiThread(host::refreshServerUi); - }); - } + // ADFA-5343 (Phase 4d-2): the server-liveness poll (checkServerStatus), the log-only reconciler seam, + // the targetServerState transition, and the server-uptime analytics all moved to the reconciler's tick + // — the single liveness capture + publisher + actuator. The bridge (Actuator/setActuator) is gone too. private void updateConnectivityStatus() { boolean isWifiOn = false; @@ -275,9 +180,6 @@ public void createFakeSysData(File rootfsDir) { // --- server start / stop (the control button) ------------------------------- - /** ADFA-4837: true while a graceful stop is in flight; a start must not stack over it. */ - public boolean isStopping() { return stopping; } - /** * ADFA-4842: UNCONDITIONAL, deterministic boot of the Debian/proot environment (pdsm start). * @@ -299,7 +201,6 @@ public void createFakeSysData(File rootfsDir) { * none of this applies there. This method is only for the post-module boot driven by the index. */ public void startEnvironment() { - if (stopping) return; // a graceful stop is still tearing its proot down — don't stack a second if (ensuring) return; // ADFA-5103: a decision/launch is already in flight; never double-launch ensuring = true; // ADFA-5103: "ensure it is up", decided OFF the main thread — this has six callers, all on it, @@ -394,8 +295,7 @@ public void onError(String error) { activity.runOnUiThread(() -> host.addToLog(activity.getString(R.string.log_server_error, error))); } }); - prefs.setWatchdogEnable(true); - host.enableSystemProtection(); + prefs.setWatchdogEnable(true); // sets desired=UP; the reconciler promotes WatchdogService (Phase 4b) host.addToLog(activity.getString(R.string.watchdog_started)); host.startFusionPulse(); ensuring = false; // ADFA-5103: launch issued — release the ensure-up guard @@ -443,20 +343,9 @@ public void handleServerLaunchClick(View v) { }; timeoutHandler.postDelayed(timeoutRunnable, activity.getResources().getInteger(R.integer.server_cool_off_duration_ms)); - File rootfsDir = new File(activity.getFilesDir(), "rootfs/installed-rootfs/iiab"); - if (!ServerStateRepository.get().current().alive) { - // ADFA-4837: a graceful stop can already have flipped the server to !alive while its - // proot is still tearing down. Never start on top of that — it would stack a second - // proot over the same rootfs (the collision class we keep fighting). - if (stopping) { - host.setTargetServerState(null); - activity.runOnUiThread(host::stopBtnProgress); - return; - } - // ADFA-4842: the actual boot is the shared, unconditional startEnvironment() (also used by the - // install index after the last module). Here it runs only in the !alive branch, so the UI button - // keeps its start/stop TOGGLE semantics. + // ADFA-4842: the actual boot is the shared, unconditional startEnvironment(). Reached now only + // by the recovery caller (LibraryActivity:394, Phase 5). startEnvironment(); // ADFA-5061: a 20 s timer used to fire a snackbar here — "Termux not opening? Enable @@ -472,67 +361,11 @@ public void handleServerLaunchClick(View v) { // nothing was happening while the start was happening. The honest report of a start // that did not take is the timeout above, which is still here and still runs. - } else { - if (stopping) return; // ADFA-4834: a stop is already in flight; ignore repeat taps - stopping = true; - host.addToLog(activity.getString(R.string.log_server_stopping_gracefully)); - - PRootEngine stopEngine = new PRootEngine(); - - stopEngine.executeInContainer(activity, rootfsDir.getAbsolutePath(), "/usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin bash -lc '/usr/local/bin/pdsm stop'", new PRootEngine.OutputListener() { - @Override - public void onOutputLine(String line) { - activity.runOnUiThread(() -> host.addToLog("[PDSM Stop] " + line)); - // ADFA-4834: surface which service is stopping to the shutdown screen. - java.util.regex.Matcher m = PDSM_SVC.matcher(line); - if (m.find()) { - final String svc = m.group(1); - activity.runOnUiThread(() -> host.onShutdownProgress(svc)); - } - } - - @Override - public void onProcessExit(int exitCode) { - activity.runOnUiThread(() -> { - stopping = false; // ADFA-4834: stop finished; allow a future stop - if (serverEngine != null) { - serverEngine.killProcess(); - serverEngine = null; - } - - AppExecutors.get().io().execute(() -> { - // ADFA-4811: never global-kill proot while an install is running — it - // would kill the in-flight installer's proot over the shared rootfs. - if (InstallGuard.inProgress(activity)) { - return; - } - try { - Runtime.getRuntime().exec(new String[]{"sh", "-c", "killall -9 proot 2>/dev/null"}); - } catch (Exception ignored) { - } - }); - - if (prefs.getWatchdogEnable()) { - prefs.setWatchdogEnable(false); - host.disableSystemProtection(); - host.addToLog(activity.getString(R.string.watchdog_stopped)); - host.startExitPulse(); - } - - // ADFA-4834: the graceful stop has exited and proot is being killed — this is - // the real "everything is down" moment. Tell the host so a pending "Turn off" - // can finish closing (and terminate the process) instead of hanging on the - // /home poll heuristic. - host.onShutdownComplete(); - }); - } - - @Override - public void onError(String error) { - stopping = false; // ADFA-4834: allow a retry if the stop failed to launch - activity.runOnUiThread(() -> host.addToLog(activity.getString(R.string.log_server_stop_error, error))); - } - }); } + // ADFA-5343 (Phase 4c): the toggle no longer stops the box. A user turn-off is now an intent + // (LibraryActivity.turnOffK2Go -> setUserWantsOn(false)) that the reconciler honors with a graceful + // pdsm stop + proot teardown. This branch's callers (LibraryActivity install-success / recovering / + // autostart) are all boot-gated on !alive, so the old stop branch was dead once the button + // converted. handleServerLaunchClick is boot-only now and 4d deletes it with the autostart cluster. } } diff --git a/controller/app/src/main/java/org/iiab/controller/WatchdogService.java b/controller/app/src/main/java/org/iiab/controller/WatchdogService.java index dfa292040..47b62ec37 100644 --- a/controller/app/src/main/java/org/iiab/controller/WatchdogService.java +++ b/controller/app/src/main/java/org/iiab/controller/WatchdogService.java @@ -36,6 +36,12 @@ public class WatchdogService extends Service { public static final String ACTION_STATE_STARTED = "org.iiab.controller.WATCHDOG_STARTED"; public static final String ACTION_STATE_STOPPED = "org.iiab.controller.WATCHDOG_STOPPED"; + // ADFA-5343 (Phase 4b): process-scoped "is the watchdog protecting right now", so the reconciler — + // the one promoter — can edge-detect (start only when not running, stop only when running) without a + // reconciler-side flag. Resets to false if the process is recreated (START_STICKY re-delivers a start). + private static volatile boolean RUNNING = false; + public static boolean isRunning() { return RUNNING; } + // Hardware Locks private PowerManager.WakeLock wakeLock; private WifiManager.WifiLock wifiLock; @@ -61,10 +67,16 @@ public int onStartCommand(Intent intent, int flags, int startId) { } private void startWatchdog() { - // 1. Start Foreground to prevent OOM (Out of Memory) kills + // 1. Start Foreground to prevent OOM (Out of Memory) kills. Called on EVERY start (idempotent) so a + // re-delivered / repeat ACTION_START still satisfies the startForeground() contract. Notification notification = createNotification(); startForeground(NOTIFICATION_ID, notification); + // ADFA-5343 (Phase 4b): the reconciler may re-send ACTION_START; guard so a repeat does NOT + // re-acquire the hardware locks (that would leak the held ones). Acquire once per running session. + if (RUNNING) return; + RUNNING = true; + // 2. Acquire CPU WakeLock to prevent sleep during heavy operations (e.g., Tar extraction, Rsync) acquireHardwareLocks(); @@ -106,6 +118,7 @@ private void releaseHardwareLocks() { @Override public void onDestroy() { + RUNNING = false; // ADFA-5343 (Phase 4b): protection is ending — clear the promoter's state signal // 1. Notify the UI that protection is gone Intent stopIntent = new Intent(ACTION_STATE_STOPPED); stopIntent.setPackage(getPackageName()); diff --git a/controller/app/src/main/java/org/iiab/controller/dashboard/data/HttpServerReachability.java b/controller/app/src/main/java/org/iiab/controller/dashboard/data/HttpServerReachability.java deleted file mode 100644 index 46059296f..000000000 --- a/controller/app/src/main/java/org/iiab/controller/dashboard/data/HttpServerReachability.java +++ /dev/null @@ -1,40 +0,0 @@ -/* - * ============================================================================ - * Name : HttpServerReachability.java - * Author : AppDevForAll - * Copyright : Copyright (c) 2026 AppDevForAll - * Description : Data impl of ServerReachability: a short-timeout HTTP GET probe - * (consolidates the old DashboardFragment.pingUrl). Treats 2xx/3xx - * as reachable; any failure is "not reachable". - * ============================================================================ - */ -package org.iiab.controller.dashboard.data; - -import org.iiab.controller.dashboard.domain.ServerReachability; - -import java.net.HttpURLConnection; -import java.net.URL; - -public class HttpServerReachability implements ServerReachability { - - private static final int TIMEOUT_MS = 1500; - - @Override - public boolean isReachable(String urlStr) { - HttpURLConnection conn = null; - try { - URL url = new URL(urlStr); - conn = (HttpURLConnection) url.openConnection(); - conn.setUseCaches(false); - conn.setConnectTimeout(TIMEOUT_MS); - conn.setReadTimeout(TIMEOUT_MS); - conn.setRequestMethod("GET"); - int code = conn.getResponseCode(); - return code >= 200 && code < 400; - } catch (Exception e) { - return false; - } finally { - if (conn != null) conn.disconnect(); - } - } -} diff --git a/controller/app/src/main/java/org/iiab/controller/dashboard/presentation/DashboardStatusViewModel.java b/controller/app/src/main/java/org/iiab/controller/dashboard/presentation/DashboardStatusViewModel.java deleted file mode 100644 index 3202cc26b..000000000 --- a/controller/app/src/main/java/org/iiab/controller/dashboard/presentation/DashboardStatusViewModel.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * ============================================================================ - * Name : DashboardStatusViewModel.java - * Author : AppDevForAll - * Copyright : Copyright (c) 2026 AppDevForAll - * Description : Polls the local server + module endpoints off the main thread on - * the shared scheduler (ADFA-4457), replacing DashboardFragment's - * per-tick `new Thread()` ping. Exposes a DashboardStatus stream; - * polling is lifecycle-scoped (start in onResume, stop in onPause, - * cancelled in onCleared). - * ============================================================================ - */ -package org.iiab.controller.dashboard.presentation; - -import org.iiab.controller.config.BoxEndpoints; - -import androidx.lifecycle.LiveData; -import androidx.lifecycle.MutableLiveData; -import androidx.lifecycle.ViewModel; - -import org.iiab.controller.dashboard.domain.ServerReachability; -import org.iiab.controller.util.AppExecutors; - -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.concurrent.ScheduledFuture; -import java.util.concurrent.TimeUnit; - -public class DashboardStatusViewModel extends ViewModel { - - private static final String BASE_URL = BoxEndpoints.BASE + "/"; - private static final String HOME_URL = BASE_URL + "home"; - private static final long PERIOD_SECONDS = 5; - - private final ServerReachability reachability; - private final MutableLiveData state = new MutableLiveData<>(); - private volatile List endpoints = Collections.emptyList(); - private ScheduledFuture pollTask; - - public DashboardStatusViewModel(ServerReachability reachability) { - this.reachability = reachability; - } - - public LiveData state() { - return state; - } - - /** Start (or refresh endpoints for) periodic polling. Safe to call on each onResume. */ - public synchronized void start(List endpoints) { - this.endpoints = endpoints != null ? endpoints : Collections.emptyList(); - if (pollTask != null && !pollTask.isCancelled()) return; - pollTask = AppExecutors.get().scheduler() - .scheduleWithFixedDelay(this::poll, 0, PERIOD_SECONDS, TimeUnit.SECONDS); - } - - /** Stop polling (onPause); can be restarted via start(). */ - public synchronized void stop() { - if (pollTask != null) { - pollTask.cancel(false); - pollTask = null; - } - } - - @Override - protected void onCleared() { - stop(); - } - - private void poll() { - // scheduleWithFixedDelay silently cancels the task if it throws, so the - // whole probe must be guarded. - try { - boolean serverAlive = reachability.isReachable(HOME_URL); - Map modules = new HashMap<>(); - for (String endpoint : endpoints) { - if (endpoint == null) continue; - boolean alive = serverAlive && reachability.isReachable(BASE_URL + endpoint); - modules.put(endpoint, alive); - } - state.postValue(new DashboardStatus(serverAlive, modules)); - } catch (Exception ignored) { - // Transient probe failure: keep the poller alive for the next tick. - } - } -} diff --git a/controller/app/src/main/java/org/iiab/controller/dashboard/presentation/DashboardStatusViewModelFactory.java b/controller/app/src/main/java/org/iiab/controller/dashboard/presentation/DashboardStatusViewModelFactory.java deleted file mode 100644 index 46f8d0322..000000000 --- a/controller/app/src/main/java/org/iiab/controller/dashboard/presentation/DashboardStatusViewModelFactory.java +++ /dev/null @@ -1,29 +0,0 @@ -/* - * ============================================================================ - * Name : DashboardStatusViewModelFactory.java - * Author : AppDevForAll - * Copyright : Copyright (c) 2026 AppDevForAll - * Description : Hand-wired DI for DashboardStatusViewModel (Data -> Domain -> - * Presentation), same approach as RootfsViewModelFactory. - * ============================================================================ - */ -package org.iiab.controller.dashboard.presentation; - -import androidx.annotation.NonNull; -import androidx.lifecycle.ViewModel; -import androidx.lifecycle.ViewModelProvider; - -import org.iiab.controller.dashboard.data.HttpServerReachability; - -public class DashboardStatusViewModelFactory implements ViewModelProvider.Factory { - - @NonNull - @Override - @SuppressWarnings("unchecked") - public T create(@NonNull Class modelClass) { - if (modelClass.isAssignableFrom(DashboardStatusViewModel.class)) { - return (T) new DashboardStatusViewModel(new HttpServerReachability()); - } - throw new IllegalArgumentException("Unknown ViewModel class: " + modelClass.getName()); - } -} diff --git a/controller/app/src/main/java/org/iiab/controller/env/EnvironmentControl.java b/controller/app/src/main/java/org/iiab/controller/env/EnvironmentControl.java index 3565d2d5f..4629aa917 100644 --- a/controller/app/src/main/java/org/iiab/controller/env/EnvironmentControl.java +++ b/controller/app/src/main/java/org/iiab/controller/env/EnvironmentControl.java @@ -6,9 +6,12 @@ * Description : ADFA-4957. Context-based quiescing of the Debian environment SERVICES (pdsm stop), * extracted from ServerController so a foreground service (DeepOpService) can stop the * environment off ANY Activity — the same deterministic pdsm command the UI path uses. - * stop() runs `pdsm stop`; callbacks fire on the PRootEngine worker thread. Booting is - * deliberately NOT here: the hosting Activity boots via ServerController.startEnvironment() - * (which shares createFakeSysData below, so the fake /proc data has a single copy). + * stop() runs `pdsm stop`; callbacks fire on the PRootEngine worker thread. + * ADFA-5343 (Phase 4): start() is now here too — the OFF-UI boot the app-scoped reconciler + * owner uses to bring the box up with no foreground Activity (the process-scoped owner the + * ADR §1.1 root cause needs). Both share createFakeSysData below, one copy of the fake /proc + * data. ServerController.doLaunchEnvironment keeps its own Activity-UI boot until the + * app-scoped actuator is device-verified (then it delegates here / is deleted). * ============================================================================ */ package org.iiab.controller.env; @@ -29,6 +32,9 @@ public final class EnvironmentControl { private static final String PATH_ENV = "/usr/bin/env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin bash -lc "; private static final String CMD_STOP = PATH_ENV + "'/usr/local/bin/pdsm stop'"; + // ADFA-5343 (Phase 4): the persistent boot — the same command ServerController.doLaunchEnvironment + // uses (pdsm start, then `tail -f /dev/null` so the proot outlives the command and stays up). + private static final String CMD_START = PATH_ENV + "'/usr/local/bin/pdsm start && tail -f /dev/null'"; private EnvironmentControl() {} @@ -54,6 +60,32 @@ public static void stop(Context ctx, final LineSink log, final Runnable onDone) }); } + /** + * ADFA-5343 (Phase 4): the OFF-UI boot — bring the environment up in a fresh, app-scoped + * {@link PRootEngine} with no Activity, so the app-scoped reconciler owner can boot the box when no + * screen is foregrounded. Mirrors {@code ServerController.doLaunchEnvironment}'s launch + * (createFakeSysData + {@code pdsm start && tail -f /dev/null}) minus the Activity-UI callbacks + * (onStartupBegan / per-service progress / fusion pulse) — those belong to a foreground screen, and + * the UI observes the published phase instead. + * + *

The caller (the reconciler) HOLDS the returned engine — it is the process-scoped owner of the + * launch, which is the ADR §1.1 root-cause fix (the proot outlives any Activity). Runs the command on + * the PRootEngine worker thread; call after an idempotency decision (EnvironmentEnsure) so a live + * proot is never stacked. + */ + public static PRootEngine start(Context ctx, final LineSink log) { + File rootfsDir = rootfs(ctx); + createFakeSysData(rootfsDir); + PRootEngine engine = new PRootEngine(); + engine.executeInContainer(ctx.getApplicationContext(), rootfsDir.getAbsolutePath(), CMD_START, + new PRootEngine.OutputListener() { + @Override public void onOutputLine(String line) { if (log != null) log.onLine("[Server] " + line); } + @Override public void onProcessExit(int exitCode) { if (log != null) log.onLine("[Server] engine exit " + exitCode); } + @Override public void onError(String error) { if (log != null) log.onLine("[Server] error " + error); } + }); + return engine; + } + /** * Writes the fake /proc files (uptime/version/stat/loadavg) the container expects. Extracted * verbatim from ServerController.createFakeSysData; that method now delegates here so there is a diff --git a/controller/app/src/main/java/org/iiab/controller/env/ServerLifecycleReconciler.java b/controller/app/src/main/java/org/iiab/controller/env/ServerLifecycleReconciler.java index 35aae014d..b1a12f78f 100644 --- a/controller/app/src/main/java/org/iiab/controller/env/ServerLifecycleReconciler.java +++ b/controller/app/src/main/java/org/iiab/controller/env/ServerLifecycleReconciler.java @@ -15,15 +15,26 @@ package org.iiab.controller.env; import android.content.Context; +import android.content.Intent; +import android.os.Handler; +import android.os.Looper; import android.os.SystemClock; import android.util.Log; +import androidx.core.content.ContextCompat; + +import org.iiab.controller.PRootEngine; import org.iiab.controller.Preferences; +import org.iiab.controller.ServerState; +import org.iiab.controller.ServerStateRepository; +import org.iiab.controller.SystemStateEvaluator; +import org.iiab.controller.WatchdogService; +import org.iiab.controller.env.domain.EnvironmentEnsure; import org.iiab.controller.env.domain.ServerLiveness; import org.iiab.controller.env.domain.ServerReconcile; import org.iiab.controller.system.data.SystemFactsReader; -import org.iiab.controller.system.domain.Operation; import org.iiab.controller.system.domain.SystemFacts; +import org.iiab.controller.util.AppExecutors; /** * One process-scoped owner of "the server should be up," observing only (Phase 1). @@ -52,103 +63,201 @@ public static ServerLifecycleReconciler get() { */ public static final boolean ACTUATES = true; + private volatile boolean lastDesiredUp; + private long serverUpSinceMs; // ADFA-5343 (Phase 4d-2): wall-clock, for the server-uptime analytics + // migrated off the deleted ServerController poll. + + // ADFA-5343 (Phase 4a/4d-2): the app-scoped tick — the reconciler's SINGLE driver, foreground AND + // background (4d-2 removed the ServerController poll + the foreground bridge, so there is no + // stand-down: this is the one liveness capture + publisher + actuator). It captures liveness, publishes + // ServerStateRepository, and actuates OFF-UI via EnvironmentControl. Runs while the process is alive; + // WatchdogService (START_STICKY, up while the box is up) keeps the process alive in the background so a + // flap is re-driven with no Activity. (ServerController's own boot survives only for the recovery path + // :394 — Phase 5.) + private static final long TICK_MS = 3000L; + private final Handler tickHandler = new Handler(Looper.getMainLooper()); + private volatile boolean tickStarted; + private volatile Context appContext; + private volatile ServerLiveness lastTickLiveness; // threaded across ticks for the service-downtime clock + private PRootEngine appScopedEngine; // the off-UI boot handle this owner holds (Phase 4a) + // ADFA-5343 (Phase 4c): serialises the reconciler's async STOP so it fires once per turn-off, not + // every tick during the ~40s graceful pdsm stop. Subsumes ServerController.stopping (deleted in 4d). + private volatile boolean reconcilerStopping; + + private ServerLifecycleReconciler() { + } + /** - * ADFA-5343 (Phase 2): the single actuator the reconciler drives — the foregrounded - * {@code ServerController}, which registers on resume. The reconciler owns the DECISION (desired); - * the boot MECHANISM stays in the one existing, tested path - * ({@code ServerController.startEnvironment} via {@code EnvironmentEnsure}) until Phase 4 relocates - * it off-UI and deletes the toggle. No second boot path is introduced. + * ADFA-5343 (Phase 4a): start the app-scoped background tick. Idempotent; call once from + * {@link org.iiab.controller.IIABApplication}. The tick fires every {@link #TICK_MS} while the process + * is alive; each fire hops to an IO thread (the liveness probe can block ~2.5s) and stands down unless + * the app is backgrounded (no foreground actuator). */ - public interface Actuator { - /** Ensure the server is up. Idempotent and self-gating: a no-op if already up or still inside - * its boot grace, a relaunch only for a stuck past-grace proot. */ - void ensureServerUp(); + public void startBackgroundTick(Context appCtx) { + if (appCtx == null || tickStarted) { + return; + } + this.appContext = appCtx.getApplicationContext(); + tickStarted = true; + tickHandler.post(tickRunnable); } - private volatile ServerLiveness lastLiveness; - private volatile boolean lastDesiredUp; - private volatile Actuator actuator; + private final Runnable tickRunnable = new Runnable() { + @Override + public void run() { + AppExecutors.get().io().execute(ServerLifecycleReconciler.this::backgroundTick); + tickHandler.postDelayed(this, TICK_MS); + } + }; - private ServerLifecycleReconciler() { + /** + * One tick (IO thread) — the single driver, foreground and background (Phase 4d-2). Captures one + * liveness snapshot, publishes {@link ServerStateRepository} (the one publisher now the poll is gone), + * and reconciles: promote/teardown the watchdog, and actuate OFF-UI (up or stop) per desired. + */ + private void backgroundTick() { + Context ctx = appContext; + if (ctx == null) { + return; + } + long now = SystemClock.elapsedRealtime(); + ServerLiveness live = ServerLiveness.next( + lastTickLiveness, + EnvironmentProcess.isRunning(ctx), + org.iiab.controller.redesign.RestReadiness.apiReady(), + now, ServerLiveness.DEFAULT_FRESH_MS); + lastTickLiveness = live; + ServerLiveness.Phase actual = live.phase(now); + + // Publish liveness for the UI (the sole publisher now the ServerController poll is deleted) and + // fire the server-uptime analytics on an alive transition (migrated off that poll). + boolean alive = actual == ServerLiveness.Phase.UP; + boolean wasAlive = ServerStateRepository.get().current().alive; + if (alive && !wasAlive) { + serverUpSinceMs = System.currentTimeMillis(); + org.iiab.controller.analytics.AnalyticsClient.with(ctx).logServerStarted(); + } else if (!alive && wasAlive) { + long uptime = serverUpSinceMs > 0L ? System.currentTimeMillis() - serverUpSinceMs : -1L; + serverUpSinceMs = 0L; + org.iiab.controller.analytics.AnalyticsClient.with(ctx).logServerStopped(uptime); + } + ServerStateRepository.get().post(ServerState.of(alive, SystemStateEvaluator.evaluate(ctx, alive))); + + synchronized (this) { + SystemFacts facts = SystemFactsReader.read(ctx); + boolean userWantsOn = new Preferences(ctx).getWatchdogEnable(); + EnvironmentLock.Holder holder = EnvironmentLock.currentHolder(ctx); + boolean desiredUp = ServerReconcile.desired( + facts.isInstalled(), facts.isHealthy(), userWantsOn, holder.executionClass); + this.lastDesiredUp = desiredUp; // the header's "Starting" reads this (isServerStarting) + ServerReconcile.Intent intent = ServerReconcile.intent(desiredUp, actual); + + // ADFA-5343 (Phase 4b): the one WatchdogService promoter, driven by desired — in the + // background too, so the process stays alive to keep the box up / re-drive a flap under Doze. + promoteOrTeardownWatchdog(ctx, desiredUp); + + boolean ensureUp = ACTUATES && ServerReconcile.shouldEnsureUp(intent, holder.selfRestartsServer); + boolean doStop = ACTUATES && ServerReconcile.shouldStop(intent, holder == EnvironmentLock.Holder.NONE); + + Log.i(TAG, "ADFA-5343 tick: desired=" + (desiredUp ? "UP" : "DOWN") + + " actual=" + actual + " intent=" + intent + + (ensureUp ? " -> off-UI ensureServerUp" : doStop ? " -> off-UI STOP" : "") + + " [holder=" + holder + " userWantsOn=" + userWantsOn + "]"); + + if (ensureUp) { + offUiEnsureUp(ctx, live, now); + } else if (doStop) { + actuateStop(ctx); + } + } } - /** The foregrounded {@code ServerController} registers here in {@code onResume}. */ - public synchronized void setActuator(Actuator a) { - this.actuator = a; + /** + * The OFF-UI actuation (Phase 4a): the same {@link EnvironmentEnsure} decision the foreground boot + * uses, launching the app-scoped {@link EnvironmentControl#start} engine this owner holds — no + * Activity. EnvironmentEnsure keeps it idempotent (LAUNCH only when nothing runs; relaunch only a + * stuck past-grace proot), so it never stacks a second proot. Resets the tick's downtime clock after a + * launch so the fresh proot gets its full grace. Caller holds {@code this} monitor. + */ + /** + * ADFA-5343 (Phase 4c): the user button's set-desired API. Turn-on/off write the one persisted intent + * ({@code WatchdogEnable}); the reconciler does the rest (boot on desired=UP, stop on desired=DOWN). + * Replaces the toggle's start-XOR-stop-on-a-cache. + */ + public void setUserWantsOn(Context ctx, boolean on) { + new Preferences(ctx).setWatchdogEnable(on); } /** - * Cleared in {@code onPause} — but only if {@code a} is still the current one, so a resume/pause - * overlap (the next Activity registered before the previous paused) does not clear the live - * registration. Idempotent. + * ADFA-5343 (Phase 4d): act NOW instead of on the next tick — for the user's last-defense Retry, after + * {@link #setUserWantsOn}(true). Runs an immediate reconcile (the single tick is the one actuator now). */ - public synchronized void clearActuator(Actuator a) { - if (this.actuator == a) { - this.actuator = null; - } + public void requestReconcileNow() { + tickHandler.post(tickRunnable); } /** - * A tick: compute desired, compare to the observed liveness, and log the action that would follow. - * No actuation in Phase 1. Called on the poll's worker thread; {@code synchronized} keeps the - * "single-threaded tick" invariant if two polls ever overlap. - * - * @param ctx any context (the poll's Activity today). - * @param liveness the snapshot the poll just read — reused, not re-probed. + * ADFA-5343 (Phase 4c): the reconciler's STOP — a graceful {@code pdsm stop} then kill the proot so + * the box reaches phase DOWN (a user turn-off, honored by the owner instead of a bespoke inline stop). + * Serialised by {@link #reconcilerStopping} so it fires once, not every tick through the ~40s stop. + * Only reached when {@link ServerReconcile#shouldStop} is true (desired down, box up, holder NONE) — + * a deep op holds a STOPPED-class lock and quiesces itself, so this never double-stops it. */ - public synchronized void observe(Context ctx, ServerLiveness liveness) { - if (ctx == null || liveness == null) { + private void actuateStop(Context ctx) { + if (reconcilerStopping) { return; } - ServerLiveness.Phase actual = liveness.phase(SystemClock.elapsedRealtime()); - - SystemFacts facts = SystemFactsReader.read(ctx); - boolean userWantsOn = new Preferences(ctx).getWatchdogEnable(); - EnvironmentLock.Holder holder = EnvironmentLock.currentHolder(ctx); - Operation.ExecutionClass holderClass = holder.executionClass; - - boolean desiredUp = ServerReconcile.desired( - facts.isInstalled(), facts.isHealthy(), userWantsOn, holderClass); - ServerReconcile.Intent wouldDo = ServerReconcile.intent(desiredUp, actual); - - this.lastLiveness = liveness; - this.lastDesiredUp = desiredUp; - - // ADFA-5343 (Phase 2): actuate only the "bring it up" direction. START (down) and WAIT (still - // coming up, or a stuck flap) both route to ensureServerUp(); its EnvironmentEnsure decides - // launch / leave-in-grace / relaunch-stuck, so a healthy boot is never disturbed and a - // past-grace flap is re-driven wherever the app is foregrounded (the 5336 fix). STOP stays with - // the toggle / deep-ops until Phase 4; and desired=DOWN yields neither START nor WAIT, so the - // reconciler can never fight a legitimate stop. - // ADFA-5343a (Phase 3B): but DEFER entirely while a self-restarting holder (DASHBOARD's live - // rebuild) holds — it owns the restart, so any relaunch mid-swap would fight it. The defer is - // bounded (Holder.selfRestartsServer): the lock releases on every terminal + a stall backstop. - boolean wouldEnsure = ServerReconcile.ensuresUp(wouldDo); - boolean ensureUp = ACTUATES - && ServerReconcile.shouldEnsureUp(wouldDo, holder.selfRestartsServer); - Actuator a = ensureUp ? this.actuator : null; - - String actNote = !ACTUATES ? "" - : (wouldEnsure && holder.selfRestartsServer) - ? " -> (deferred: " + holder + " self-restarts the server)" - : ensureUp ? (a != null ? " -> ensureServerUp()" : " -> (no foreground actuator)") - : ""; - Log.i(TAG, "ADFA-5343 reconcile: desired=" + (desiredUp ? "UP" : "DOWN") - + " actual=" + actual + " wouldDo=" + wouldDo + actNote - + " [installed=" + facts.isInstalled() + " healthy=" + facts.isHealthy() - + " userWantsOn=" + userWantsOn + " holder=" + holder + "/" + holderClass + "]"); - - if (a != null) { - a.ensureServerUp(); + reconcilerStopping = true; + Log.i(TAG, "ADFA-5343 reconcile: STOP (desired=DOWN, no holder) — graceful pdsm stop + teardown"); + EnvironmentControl.stop(ctx, line -> Log.i(TAG, line), () -> { + PRootEngine e = appScopedEngine; + appScopedEngine = null; + if (e != null) { + e.killProcess(); + } + EnvironmentProcess.killOrphan(ctx); // ensure the proot is gone (whoever launched it) -> phase DOWN + lastTickLiveness = null; // fresh liveness clock after the teardown + reconcilerStopping = false; + }); + } + + /** + * ADFA-5343 (Phase 4b): the reconciler is the ONE promoter of {@link WatchdogService} — up while the + * server should be up (the foreground service + wakelock keep the process alive so the tick survives + * Doze and re-drives a flap), down otherwise (deep ops run their own foreground services; a user-off / + * uninstalled box needs no keeper). Edge-detected via the service's own {@link WatchdogService#isRunning} + * state — no reconciler-side flag — so it is safe to call on every reconcile and self-corrects a + * START_STICKY-revived service. At targetSdk 28 the app may start a foreground service from the + * background (the API-31 restriction does not apply); revisit if the targetSdk is raised. + */ + private void promoteOrTeardownWatchdog(Context ctx, boolean desiredUp) { + Context app = ctx.getApplicationContext(); + if (desiredUp && !WatchdogService.isRunning()) { + ContextCompat.startForegroundService(app, + new Intent(app, WatchdogService.class).setAction(WatchdogService.ACTION_START)); + } else if (!desiredUp && WatchdogService.isRunning()) { + app.startService(new Intent(app, WatchdogService.class).setAction(WatchdogService.ACTION_STOP)); } } - /** The last snapshot observed, or null before the first tick. For later phases / diagnostics. */ - public ServerLiveness lastLiveness() { - return lastLiveness; + private void offUiEnsureUp(Context ctx, ServerLiveness live, long now) { + long downMs = live.servicesDownMs(now, ServerLiveness.DEFAULT_FRESH_MS); + EnvironmentEnsure.Action action = EnvironmentEnsure.decide( + live.processPresent(), live.servicesAnswering(), downMs, + EnvironmentEnsure.DEFAULT_SERVICE_DOWN_GRACE_MS); + if (action == EnvironmentEnsure.Action.KILL_AND_RELAUNCH) { + EnvironmentProcess.killOrphan(ctx); + } else if (action != EnvironmentEnsure.Action.LAUNCH) { + return; // NOOP_HEALTHY / WAIT_BOOT_GRACE — leave it + } + if (appScopedEngine != null) { + appScopedEngine.killProcess(); + } + appScopedEngine = EnvironmentControl.start(ctx, line -> Log.i(TAG, line)); + lastTickLiveness = null; // restart the downtime clock so the fresh proot gets its full grace } - /** The last desired verdict. For later phases / diagnostics. */ + /** The last desired verdict — the header's "Starting" reads this (LibraryActivity.isServerStarting). */ public boolean lastDesiredUp() { return lastDesiredUp; } diff --git a/controller/app/src/main/java/org/iiab/controller/env/domain/EnvironmentEnsure.java b/controller/app/src/main/java/org/iiab/controller/env/domain/EnvironmentEnsure.java index a2ba1371a..00361f3b1 100644 --- a/controller/app/src/main/java/org/iiab/controller/env/domain/EnvironmentEnsure.java +++ b/controller/app/src/main/java/org/iiab/controller/env/domain/EnvironmentEnsure.java @@ -33,6 +33,14 @@ public final class EnvironmentEnsure { private EnvironmentEnsure() { } + /** + * ADFA-5343a (D1): the default service-downtime grace — how long "proot alive but services not + * answering" is read as "still coming up / pdsm will respawn it" before {@link Action#KILL_AND_RELAUNCH}. + * The one canonical value both actuators use (ServerController's foreground boot and the app-scoped + * reconciler tick), so the threshold has a single source. + */ + public static final long DEFAULT_SERVICE_DOWN_GRACE_MS = 20_000L; + public enum Action { /** Nothing of ours is running — start it. */ LAUNCH, diff --git a/controller/app/src/main/java/org/iiab/controller/env/domain/ServerReconcile.java b/controller/app/src/main/java/org/iiab/controller/env/domain/ServerReconcile.java index 99b90e5c0..10bf3d655 100644 --- a/controller/app/src/main/java/org/iiab/controller/env/domain/ServerReconcile.java +++ b/controller/app/src/main/java/org/iiab/controller/env/domain/ServerReconcile.java @@ -113,4 +113,16 @@ public static boolean ensuresUp(Intent intent) { public static boolean shouldEnsureUp(Intent intent, boolean holderSelfRestartsServer) { return ensuresUp(intent) && !holderSelfRestartsServer; } + + /** + * Whether the reconciler should STOP the server now: the intent is {@link Intent#STOP} (desired down, + * box still up) AND no holder is in force. The {@code holderIsNone} gate is what keeps the + * reconciler from double-stopping a deep op: clone/backup/restore/install already quiesced the box + * synchronously and hold a STOPPED-class lock, so the reconciler must NOT also stop — it stops only a + * plain user turn-off (holder NONE, userWantsOn false). LIVE holders (DOWNLOAD/DASHBOARD) keep + * desired UP, so they never produce a STOP intent in the first place. + */ + public static boolean shouldStop(Intent intent, boolean holderIsNone) { + return intent == Intent.STOP && holderIsNone; + } } diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/BackupRestoreFragment.java b/controller/app/src/main/java/org/iiab/controller/redesign/BackupRestoreFragment.java index 10acd9549..cd86579b7 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/BackupRestoreFragment.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/BackupRestoreFragment.java @@ -151,10 +151,9 @@ private View buildReturnBar() { private void startReturnToHome() { returnCancelled = false; returnStartMs = android.os.SystemClock.elapsedRealtime(); - if (getActivity() instanceof SetupLibraryActivity) { - org.iiab.controller.ServerController sc = ((SetupLibraryActivity) getActivity()).server(); - if (sc != null) sc.startEnvironment(); - } + // ADFA-5343 (Phase 4d-1): no bespoke boot here. DeepOpService.finishJob already set desired=UP and + // released the lock (Phase 3A), so the reconciler brings the box back; this only waits for it to + // answer before going Home (below). readyPoll = new Runnable() { @Override public void run() { if (returnCancelled || !isAdded()) return; diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java b/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java index 196e38460..a17031a1d 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/LibraryActivity.java @@ -17,7 +17,6 @@ import org.iiab.controller.R; import org.iiab.controller.ServerController; import org.iiab.controller.ServerStateRepository; -import org.iiab.controller.WatchdogService; import org.iiab.controller.install.presentation.InstallProgressRepository; import org.iiab.controller.install.presentation.InstallState; import org.iiab.controller.system.data.PendingContent; @@ -31,7 +30,6 @@ public class LibraryActivity extends AppCompatActivity implements ServerController.Host { private static final String TAG = "K2Go-Library"; - private static final long AUTOSTART_DELAY_MS = 3500L; private static final long GATE_SAFETY_MS = 25000L; /** Nothing installed → nothing to boot: dismiss the gate promptly instead of waiting. */ private static final long NO_SYSTEM_GATE_MS = 900L; @@ -67,7 +65,6 @@ public class LibraryActivity extends AppCompatActivity implements ServerControll private boolean navSyncing = false; private ServerController serverController; - private boolean isNegotiating = false; private Boolean targetServerState = null; private LottieAnimationView bootGate; @@ -342,9 +339,10 @@ public android.graphics.Typeface fetchFont(String fontFamily) { // the FIRST run (no relaunch). The install just cleared the guard, so this is // allowed. The gate stays until the server responds (alive observer), with a // safety timeout so the user is never trapped if it doesn't come up. - if (!ServerStateRepository.get().current().alive && targetServerState == null) { - serverController.handleServerLaunchClick(findViewById(android.R.id.content)); - } + // ADFA-5343 (Phase 4d-1): install SUCCESS sets desired=UP (route install through + // desired — the piece Phase 3 deferred here); the reconciler boots the box. Idempotent, + // so no bespoke start and no need to gate on !alive. + org.iiab.controller.env.ServerLifecycleReconciler.get().setUserWantsOn(this, true); // ADFA-4853: if the wizard banked content, go straight to Finishing setup // (over the library) — no brief stop on the home. That screen shows // "Starting services…" and drains the wishlists when the engine is up. @@ -403,16 +401,15 @@ public android.graphics.Typeface fetchFont(String fontFamily) { // (CloneFragment.releaseCloneEnv / the DeepOp terminal observer), never the boot gate. onServerReady(); } else { - // If the stack isn't up after one poll cycle, start it. - if (systemInstalled) { - main.postDelayed(() -> { - // ADFA-4986: never autostart the server if an install went live after onCreate. - if (!isFinishing() && !installing - && !ServerStateRepository.get().current().alive - && targetServerState == null) { - serverController.handleServerLaunchClick(findViewById(android.R.id.content)); - } - }, AUTOSTART_DELAY_MS); + // ADFA-5343 (Phase 4d-1, corrected): opening the app is a POWER-ON gesture. On a FRESH launch + // (savedInstanceState == null) of an installed system, set desired=UP so the reconciler boots + // the box — "open = boot". This is set-desired, not the old raw autostart: it is idempotent, + // and gated to a fresh launch so a config-change recreate (rotation) does not re-power-on. + // The desired-gate ("stay off") then applies ONLY to a background PROCESS-RESTART after a + // turn-off — no Activity, so no power-on gesture, so userWantsOn stays false and the box stays + // down (the real D3 case). Settings turn-off = setUserWantsOn(false) = stop + no background. + if (systemInstalled && savedInstanceState == null) { + org.iiab.controller.env.ServerLifecycleReconciler.get().setUserWantsOn(this, true); } // Safety: never trap the user behind the gate — but ADFA-4986: don't lift it mid-install. // Deliberate trade-off: while an install is live there is intentionally NO safety-timeout @@ -991,9 +988,12 @@ private boolean reduceMotion() { return org.iiab.controller.util.Motion.reduced(this); } - /** ADFA-4837: true while a server start is actually in progress (header shows "Starting…"). */ + /** ADFA-4837 / ADFA-5343 (Phase 4d-2): true while a server start is actually in progress (header shows + * "Starting…"). Now reads the reconciler's published state instead of the retired poll's + * targetServerState: the reconciler wants it up (desired) and it is not up yet. */ public boolean isServerStarting() { - return Boolean.TRUE.equals(targetServerState); + return org.iiab.controller.env.ServerLifecycleReconciler.get().lastDesiredUp() + && !ServerStateRepository.get().current().alive; } /** ADFA-4956: expose the ServerController so Clone can quiesce/boot the environment via the @@ -1006,7 +1006,6 @@ public boolean canStartServer() { return !closing && targetServerState == null && !ServerStateRepository.get().current().alive - && (serverController == null || !serverController.isStopping()) && !InstallProgressRepository.get().isRunning() && !org.iiab.controller.InstallGuard.inProgress(this) // ADFA-5143: the last two align this with ServerController.handleServerLaunchClick, @@ -1048,8 +1047,13 @@ public void openLibraryTab() { /** ADFA-4837: header "Couldn't start — tap to retry" action. Safe no-op unless truly idle. */ public void startServer() { if (!canStartServer()) return; - targetServerState = Boolean.TRUE; // make "starting" explicit for the home header - serverController.handleServerLaunchClick(findViewById(android.R.id.content)); + // ADFA-5343 (Phase 4c/4d): the last-defense Retry — set desired=UP and kick an immediate reconcile + // so it acts now, not on the next tick. A set-desired + nudge, never a raw start/stop. The + // "Starting" header now derives from the reconciler (isServerStarting), so no targetServerState. + org.iiab.controller.env.ServerLifecycleReconciler r = + org.iiab.controller.env.ServerLifecycleReconciler.get(); + r.setUserWantsOn(this, true); + r.requestReconcileNow(); } /** Settings "Turn off K2Go": full-screen closing scene + graceful teardown, then leave. */ @@ -1073,10 +1077,12 @@ public void turnOffK2Go() { bootGate.setMinAndMaxFrame("C_EXIT_LOOP"); bootGate.playAnimation(); } - if (ServerStateRepository.get().current().alive && targetServerState == null) { - serverController.handleServerLaunchClick(findViewById(android.R.id.content)); - } else if (!ServerStateRepository.get().current().alive) { - onClosedReady(); + // ADFA-5343 (Phase 4c): the user's off is an intent — set desired=DOWN and let the reconciler stop + // the box (graceful pdsm stop + proot teardown). The close scene stays observer-driven + // (closing && !alive -> onClosedReady), fed by the reconciler's stop making alive=false. + org.iiab.controller.env.ServerLifecycleReconciler.get().setUserWantsOn(this, false); + if (!ServerStateRepository.get().current().alive) { + onClosedReady(); // already down — nothing to stop } // The real close is driven by the server-alive observer (closing && !alive -> onClosedReady). // A graceful stop can take ~40s (kolibri), so keep only a long last-resort safety; the old 15s @@ -1114,25 +1120,11 @@ private void finishAndExit() { // --- ServerController.Host (shell: pulses / LEDs are no-ops for now) -------- @Override public void addToLog(String message) { Log.d(TAG, message); } @Override public void startFusionPulse() { } - @Override public void startExitPulse() { } @Override public void stopBtnProgress() { } @Override public void updateConnectivityLeds(boolean wifiOn, boolean hotspotOn) { } @Override public void refreshServerUi() { } @Override public Boolean getTargetServerState() { return targetServerState; } @Override public void setTargetServerState(Boolean target) { targetServerState = target; } - @Override public boolean isNegotiating() { return isNegotiating; } - - // ADFA-4834: minimal shutdown feedback — show the service currently stopping while closing. - @Override public void onShutdownProgress(String service) { - if (!closing || installDetail == null) return; - installDetail.setText(service); - } - - // ADFA-4834: teardown really finished (pdsm stop exited, proot killed, watchdog off). This is - // the primary close trigger; the /home-poll observer and the 120s timeout are only fallbacks. - @Override public void onShutdownComplete() { - if (closing) onClosedReady(); - } // ADFA-4837: a start began — show an animated "Starting your library…" immediately so the ~15s // before the first pdsm line isn't a blank, frozen-looking screen. @@ -1172,21 +1164,4 @@ private void startReadingEllipsis(final String base) { if (readingEllipsis != null) readingEllipsis.start(base); } - @Override - public void enableSystemProtection() { - Intent i = new Intent(this, WatchdogService.class); - i.setAction(WatchdogService.ACTION_START); - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) { - startForegroundService(i); - } else { - startService(i); - } - } - - @Override - public void disableSystemProtection() { - Intent i = new Intent(this, WatchdogService.class); - i.setAction(WatchdogService.ACTION_STOP); - startService(i); - } } diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/SetupLibraryActivity.java b/controller/app/src/main/java/org/iiab/controller/redesign/SetupLibraryActivity.java index 245c1c310..180912f14 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/SetupLibraryActivity.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/SetupLibraryActivity.java @@ -24,7 +24,6 @@ public class SetupLibraryActivity extends AppCompatActivity implements org.iiab. // job (a static rootfs) and boot it after (startEnvironment). The server proot is process-scoped, so // it survives back to LibraryActivity, which only monitors it. private org.iiab.controller.ServerController serverController; - private Boolean targetServerState = null; // ServerController.Host state /** Launch extra: skip Step 1 (system) and open Step 2 (content) directly, for when a * system is already installed so adding content never overwrites it. */ @@ -660,26 +659,12 @@ public void openMapsPreparing(String[] levels) { // own status). The two protection methods drive the WatchdogService so the job isn't killed. @Override public void addToLog(String message) { Log.d("K2Go-SetupLibrary", message); } @Override public void startFusionPulse() { } - @Override public void startExitPulse() { } @Override public void stopBtnProgress() { } @Override public void updateConnectivityLeds(boolean wifiOn, boolean hotspotOn) { } @Override public void refreshServerUi() { } - @Override public Boolean getTargetServerState() { return targetServerState; } - @Override public void setTargetServerState(Boolean target) { targetServerState = target; } - @Override public boolean isNegotiating() { return false; } - - @Override public void enableSystemProtection() { - Intent i = new Intent(this, org.iiab.controller.WatchdogService.class); - i.setAction(org.iiab.controller.WatchdogService.ACTION_START); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) startForegroundService(i); - else startService(i); - } - - @Override public void disableSystemProtection() { - Intent i = new Intent(this, org.iiab.controller.WatchdogService.class); - i.setAction(org.iiab.controller.WatchdogService.ACTION_STOP); - startService(i); - } + // ADFA-5343 (Phase 4d-3): this host never toggled the server; the transition state was always null. + @Override public Boolean getTargetServerState() { return null; } + @Override public void setTargetServerState(Boolean target) { } /** ADFA-4900: Maps Confirm terminal in wizard mode — bank the per-layer selection to MapsWishlist * (MapsProvisioner applies it post-install) and return to the Get More hub. No live runrole. */ diff --git a/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java b/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java index ac9c815f1..3f39052b2 100644 --- a/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java +++ b/controller/app/src/main/java/org/iiab/controller/redesign/SetupProgressActivity.java @@ -121,7 +121,6 @@ public class SetupProgressActivity extends AppCompatActivity implements org.iiab // core answers, then completes/redirects to an already-live Library. Owns a ServerController (Host) // just to issue that start; the server proot is process-scoped so it survives into LibraryActivity. private org.iiab.controller.ServerController serverController; - private Boolean targetServerState = null; // ServerController.Host state // ADFA-5343 (Phase 2): the post-batch server restart is owned by the reconciler now, not this screen. // The three boot latches (moduleRestartKicked/moduleServerUp/moduleServerFailed) are gone: "up" is // read from the one observed server phase (serverObservedUp()), and "didn't come back in time" is a @@ -1384,24 +1383,11 @@ private void backToIndex() { // a module batch. UI-affordance callbacks are no-ops here (the index has its own status line). ---- @Override public void addToLog(String message) { android.util.Log.d("K2Go-SetupProgress", message); } @Override public void startFusionPulse() { } - @Override public void startExitPulse() { } @Override public void stopBtnProgress() { } @Override public void updateConnectivityLeds(boolean wifiOn, boolean hotspotOn) { } @Override public void refreshServerUi() { } - @Override public Boolean getTargetServerState() { return targetServerState; } - @Override public void setTargetServerState(Boolean target) { targetServerState = target; } - @Override public boolean isNegotiating() { return false; } - - @Override public void enableSystemProtection() { - android.content.Intent i = new android.content.Intent(this, org.iiab.controller.WatchdogService.class); - i.setAction(org.iiab.controller.WatchdogService.ACTION_START); - if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) startForegroundService(i); - else startService(i); - } + // ADFA-5343 (Phase 4d-3): this host never toggled the server; the transition state was always null. + @Override public Boolean getTargetServerState() { return null; } + @Override public void setTargetServerState(Boolean target) { } - @Override public void disableSystemProtection() { - android.content.Intent i = new android.content.Intent(this, org.iiab.controller.WatchdogService.class); - i.setAction(org.iiab.controller.WatchdogService.ACTION_STOP); - startService(i); - } } diff --git a/controller/app/src/test/java/org/iiab/controller/env/domain/ServerReconcileTest.java b/controller/app/src/test/java/org/iiab/controller/env/domain/ServerReconcileTest.java index 1d524f1a1..66aacdf5c 100644 --- a/controller/app/src/test/java/org/iiab/controller/env/domain/ServerReconcileTest.java +++ b/controller/app/src/test/java/org/iiab/controller/env/domain/ServerReconcileTest.java @@ -145,4 +145,27 @@ public void shouldEnsureUpNeverActsOnNonUpIntents() { assertFalse(ServerReconcile.shouldEnsureUp(ServerReconcile.Intent.HOLD, false)); assertFalse(ServerReconcile.shouldEnsureUp(ServerReconcile.Intent.HOLD, true)); } + + // --- shouldStop (reconciler STOP, gated by holder==NONE, ADFA-5343 Phase 4c) ------------------- + + @Test + public void stopsOnlyWhenStopIntentAndNoHolder() { + // A plain user turn-off: desired down, box up, no holder -> the reconciler stops. + assertTrue(ServerReconcile.shouldStop(ServerReconcile.Intent.STOP, true)); + } + + @Test + public void doesNotStopWhileAHolderIsInForce() { + // A deep op holds a STOPPED-class lock and quiesced the box itself: the reconciler must NOT + // double-stop, even though desired is DOWN (STOP intent). + assertFalse(ServerReconcile.shouldStop(ServerReconcile.Intent.STOP, false)); + } + + @Test + public void neverStopsOnNonStopIntents() { + assertFalse(ServerReconcile.shouldStop(ServerReconcile.Intent.NOOP, true)); + assertFalse(ServerReconcile.shouldStop(ServerReconcile.Intent.START, true)); + assertFalse(ServerReconcile.shouldStop(ServerReconcile.Intent.WAIT, true)); + assertFalse(ServerReconcile.shouldStop(ServerReconcile.Intent.HOLD, true)); + } } diff --git a/controller/docs/ADR-5343a-flap-recovery-delta.md b/controller/docs/ADR-5343a-flap-recovery-delta.md index ea0856fd0..a4b7508d8 100644 --- a/controller/docs/ADR-5343a-flap-recovery-delta.md +++ b/controller/docs/ADR-5343a-flap-recovery-delta.md @@ -234,3 +234,45 @@ reconciler): replace the fixed `sleep 3` with an **adaptive poll-until-ready loo logging real elapsed)** — adaptive across devices, self-instrumenting, failing only when genuinely broken. Its own rebuild-robustness item; best batched with the php-fpm dashboard follow-up (§10 residual) + the CPU-based backstop above. + +--- + +## 13. Phase 4 tick / service cycle (short note — implements ADR-5343 §2 item 5, no new ADR) + +The app-scoped owner gets its own tick, so it acts with no foreground Activity (removes the Phase-2/3 +"box returns needs a foreground Activity" limit). Cycle: + +- **Tick (4a, landed):** `ServerLifecycleReconciler` runs a `Handler` tick every 3 s while the process is + alive. It **stands down** while an Activity is foregrounded (`actuator != null` — the Activity poll + + bridge drive, as in Phases 2–3) and only takes over when backgrounded (`actuator == null`): it captures + one `ServerLiveness`, publishes `ServerStateRepository`, and actuates **off-UI** via + `EnvironmentControl.start` (a fresh app-scoped `PRootEngine` the owner holds — the §1.1 root-cause fix). + Mutually exclusive with the foreground path, so no double-boot; `EnvironmentEnsure` keeps it idempotent. +- **Service promotion (4b, next):** the reconciler will start/stop `WatchdogService` (START_STICKY) from a + **single place** on the `desired` UP↔DOWN transition — up keeps the process alive in the background so + the tick survives to keep the box up; down tears it down (nothing to keep up). START_STICKY resumes the + tick after an OEM kill; `desired` is recomputed from persisted facts, so it self-heals. The persistent + foreground notification is the existing watchdog notification (UX unchanged). +- **Battery:** the tick probes only when foregrounded (== today's poll cost) or when the box is up + (WatchdogService alive); when `desired=DOWN` + backgrounded there is no service, the process can die, + and no tick runs. No new always-on cost. +- **Transition (unwinds in 4d):** 4a keeps the foreground boot (`ServerController.doLaunchEnvironment`) and + the Activity poll intact; 4d deletes the poll + the autostart cluster and makes the tick the single + liveness publisher + `doLaunchEnvironment` delegate/delete, at which point the transitional dual + liveness-capture and dual boot mechanism collapse to one. + +--- + +## 14. Phase 4 battery follow-ups (tracked — need device measurement, not guessed) + +Phase 4b lands WatchdogService promotion at the **current 3 s tick + held wakelock** (== today's cost, +no regression). Two battery items are deferred as measured follow-ups, not designed blind in 4b: + +- **Unplugged idle back-off.** While `desired=UP` the box stays up with a PARTIAL_WAKE_LOCK + 3 s tick, + which drains when unplugged and idle. Candidate: when unplugged **and** idle (no clients / no recent + activity) slow the tick and/or drop the wakelock between Doze maintenance windows (ADR-5343 §6 "slow + idle tick"). Requires device battery measurement and must not slow the flap recovery Phase 4 just + fixed. Explicitly NOT power-tied (box up only while charging) — that is an availability-semantics + product decision, not a battery tweak. +- **Doze survival characterization.** The 4b gate proves recovery under real unplugged-stationary Doze on + OnePlus + HMD; capture the measured battery cost there so the back-off above is tuned against real data.