Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -408,6 +408,55 @@ public void killProcess() {
final Process p = currentProcess;
if (p == null) return;
p.destroy();
reap(p);
}

/**
* K2GO-593: stop the command and every box process it started. {@link #killProcess} sends
* SIGTERM, and proot does not exit on it: it stays until its guests end, so a cancelled runrole
* kept downloading. SIGKILL ends proot, and PTRACE_O_EXITKILL (K2GO-544) then makes the kernel
* kill all its guests.
*/
public void forceKill() {
final Process p = currentProcess;
if (p == null || !isAlive(p)) return; // an ended command's pid can belong to another process now
// Not destroyForcibly(): on the device it left proot running, the same as destroy().
int pid = pidOf(p);
if (pid > 0) {
android.os.Process.sendSignal(pid, android.os.Process.SIGNAL_KILL);
Log.i(TAG, "K2GO-593: SIGKILL sent to proot pid " + pid);
} else {
Log.w(TAG, "K2GO-593: proot pid unknown; falling back to destroy()");
p.destroy();
}
reap(p);
}

/** Process.isAlive() is API 26+, minSdk is 24: exitValue() throws while the process runs. */
private static boolean isAlive(Process p) {
try {
p.exitValue();
return false;
} catch (IllegalThreadStateException running) {
return true;
}
}

/** The pid of a child process, or -1 if unknown. Process.pid() is API 33+, minSdk is 24. */
static int pidOf(Process p) {
java.util.regex.Matcher m =
java.util.regex.Pattern.compile("pid=(\\d+)").matcher(String.valueOf(p));
if (m.find()) return Integer.parseInt(m.group(1));
try {
java.lang.reflect.Field f = p.getClass().getDeclaredField("pid");
f.setAccessible(true);
return f.getInt(p);
} catch (Exception e) {
return -1;
}
}

private static void reap(final Process p) {
// Reap the child off the caller's thread so it does not linger as a
// zombie / hold proot mounts. Process.waitFor(timeout) is API 26+ and
// minSdk is 24, so we drain on the shared io() executor instead of
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -953,8 +953,10 @@ private void installNextModule() {
"cd /opt/iiab/iiab && ./runrole " + roleName;
// K2GO-464: refresh the stale rootfs apt index before the runrole, or a pinned dep 404s as the
// box ages. Best-effort (short timeout, || true) so an offline/local-only install still runs.
// K2GO-593: a Cancel SIGKILLs the runrole, also during dpkg; finish any interrupted dpkg first.
final String installCmd =
"apt-get -o Acquire::http::Timeout=10 -o Acquire::https::Timeout=10 update || true ; " + runroleCmd;
"DEBIAN_FRONTEND=noninteractive dpkg --force-confdef --force-confold --configure -a < /dev/null || true ; "
+ "apt-get -o Acquire::http::Timeout=10 -o Acquire::https::Timeout=10 update || true ; " + runroleCmd;

// K2GO-394: the runrole (post-processing) as a deferred step. For maps it runs only AFTER the
// base maps are downloaded through dash-node (the gate below); other modules run it at once.
Expand Down Expand Up @@ -1074,7 +1076,9 @@ private void revertModuleInLocalVars(String module, Runnable then) {
if (prootEngine == null) prootEngine = new PRootEngine();
String revertCmd = "sed -i -E '/^[[:space:]]*" + module + "_(install|enabled)[[:space:]]*:/d' /etc/iiab/local_vars.yml && " +
"echo '" + module + "_install: False' >> /etc/iiab/local_vars.yml && " +
"echo '" + module + "_enabled: False' >> /etc/iiab/local_vars.yml";
"echo '" + module + "_enabled: False' >> /etc/iiab/local_vars.yml ; " +
// K2GO-593: a killed runrole leaves its task dirs (a partial download) behind.
"rm -rf /root/.ansible/tmp/ansible-tmp-*";
prootEngine.executeInContainer(this, debianRootfs.getAbsolutePath(), revertCmd, new PRootEngine.OutputListener() {
@Override public void onOutputLine(String line) { }
@Override public void onProcessExit(int exitCode) { then.run(); }
Expand Down Expand Up @@ -1140,18 +1144,16 @@ private void stopModuleStallWatch() {
* unset so that callback runs (the cancel path suppresses it). {@code gen} drops a kill queued for
* a module that has since ended.
*
* <p>Known limit (shared with doCancel): killProcess SIGKILLs proot, orphaning its in-container
* child. Low impact by the role's own flags -- aria2c self-exits (max-tries=5, timeout=60) and the
* meta4 fetch just idles a socket; neither firehoses disk, so recovery works regardless. Reap the
* orphan (reuse EnvironmentProcess's /proc sweep) only if a retry-conflict is ever observed.
* <p>K2GO-593: forceKill SIGKILLs proot, and PTRACE_O_EXITKILL (K2GO-544) makes the kernel kill
* its box processes too, so no orphan keeps working after the kill.
*/
private void hardStallKill(final String moduleKey, final int gen) {
if (gen != moduleStallGen || finished || cancelled || moduleStallKilled) return;
moduleStallKilled = true;
log("[Stall] '" + moduleKey + "' made no progress for " + (MODULE_HARD_STALL_MS / 1000)
+ "s; killing the runrole so it fails through to Retry");
stopModuleStallWatch();
if (prootEngine != null) prootEngine.killProcess();
if (prootEngine != null) prootEngine.forceKill(); // K2GO-593: SIGTERM did not end proot
}

/**
Expand Down Expand Up @@ -1702,22 +1704,27 @@ private void doCancel() {
}
if (moduleMode) {
// ADFA-4898 P5: user-confirmed cancel of a running module install. Kill the in-flight runrole
// (proot runs with --kill-on-exit, so its container children go with it), roll back that
// and its box processes (forceKill below), roll back that
// module's speculative <mod>_install so a cancel is not left looking installed, and surface it
// as failed so the existing per-module Retry is offered immediately. Ordering mirrors
// finishModuleQueue: clear InstallGuard BEFORE postDone so the server-restart observer (the
// server was pdsm-stopped for the runroles) is not raced by teardown's later clear.
final String cur = ModuleQueueRepository.get().current().currentModule;
// K2GO-593: during pdsm stop no module is current yet; the cancel stops the first one.
final String running = ModuleQueueRepository.get().current().currentModule;
final String cur = running != null ? running : (moduleQueue != null ? moduleQueue.peek() : null);
stopModuleStallWatch(); // ADFA-4898 P4
if (prootEngine != null) prootEngine.killProcess();
// K2GO-593: SIGKILL, not SIGTERM. On SIGTERM proot stayed up and the runrole kept downloading.
if (prootEngine != null) prootEngine.forceKill();
if (failedModules == null) failedModules = new java.util.ArrayList<>();
// K2GO-593: the user stopped it, so it is not an error; only earlier real failures notify.
final java.util.List<String> realFailures = new java.util.ArrayList<>(failedModules);
if (cur != null && !failedModules.contains(cur)) failedModules.add(cur);
final java.util.List<String> failedSnapshot = new java.util.ArrayList<>(failedModules);
final Runnable finishCancel = () -> {
persistClearQueue();
org.appdevforall.k2go.InstallGuard.end(this);
ModuleQueueRepository.get().postDone(failedSnapshot);
if (!failedSnapshot.isEmpty()) InstallNotifications.postModuleFailure(this, failedSnapshot);
ModuleQueueRepository.get().postCanceled(failedSnapshot, cur);
if (!realFailures.isEmpty()) InstallNotifications.postModuleFailure(this, realFailures);
teardown();
};
if (cur != null) revertModuleInLocalVars(cur, finishCancel); // best-effort rollback, then finish
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ public boolean isInstalling(String moduleKey) {
/** ADFA-5228: running with a determinate percent and an estimated seconds-remaining. */
public void postRunning(String currentModule, int remaining, int percent, long etaSeconds) { post(ModuleQueueState.running(currentModule, remaining, percent, etaSeconds)); }
public void postDone(List<String> failedModules) { stalled.postValue(false); post(ModuleQueueState.done(failedModules)); }
/** K2GO-593: the batch ended on a user Cancel of {@code canceledModule}. */
public void postCanceled(List<String> failedModules, String canceledModule) { stalled.postValue(false); post(ModuleQueueState.done(failedModules, canceledModule)); }
public void postIdle() { stalled.postValue(false); post(ModuleQueueState.idle()); }

private synchronized void post(ModuleQueueState s) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,17 @@ public enum Phase { IDLE, RUNNING, DONE }
public final long etaSeconds;
/** Modules whose runrole failed in this batch. Only meaningful on DONE. */
public final List<String> failedModules;
/**
* K2GO-593: the module the user stopped with Cancel, or null. It is also in
* {@link #failedModules} (it did not install, so Retry is offered); this only says why, so the
* UI shows "Canceled" instead of an error. Only meaningful on DONE.
*/
public final String canceledModule;
/** Monotonic sequence for one-shot effects (finish/fail snackbars exactly once). */
public final long seq;

private ModuleQueueState(Phase phase, String currentModule, int remaining, int percent,
long etaSeconds, List<String> failedModules, long seq) {
long etaSeconds, List<String> failedModules, String canceledModule, long seq) {
this.phase = phase;
this.currentModule = currentModule;
this.remaining = Math.max(0, remaining);
Expand All @@ -56,6 +62,7 @@ private ModuleQueueState(Phase phase, String currentModule, int remaining, int p
this.failedModules = failedModules != null
? Collections.unmodifiableList(failedModules)
: Collections.emptyList();
this.canceledModule = canceledModule;
this.seq = seq;
}

Expand Down Expand Up @@ -83,8 +90,13 @@ public boolean didFail(String moduleKey) {
return phase == Phase.DONE && failedModules.contains(moduleKey);
}

/** K2GO-593: true when the user stopped {@code moduleKey} with Cancel in the batch that just ended. */
public boolean wasCanceled(String moduleKey) {
return phase == Phase.DONE && canceledModule != null && canceledModule.equals(moduleKey);
}

public static ModuleQueueState idle() {
return new ModuleQueueState(Phase.IDLE, null, 0, INDETERMINATE, ETA_UNKNOWN, null, 0L);
return new ModuleQueueState(Phase.IDLE, null, 0, INDETERMINATE, ETA_UNKNOWN, null, null, 0L);
}

/** Running with no determinate progress (indeterminate spinner). */
Expand All @@ -99,14 +111,20 @@ public static ModuleQueueState running(String currentModule, int remaining, int

/** ADFA-5228: running with a determinate percent and an estimated seconds-remaining. */
public static ModuleQueueState running(String currentModule, int remaining, int percent, long etaSeconds) {
return new ModuleQueueState(Phase.RUNNING, currentModule, remaining, percent, etaSeconds, null, 0L);
return new ModuleQueueState(Phase.RUNNING, currentModule, remaining, percent, etaSeconds, null, null, 0L);
}

public static ModuleQueueState done(List<String> failedModules) {
return new ModuleQueueState(Phase.DONE, null, 0, INDETERMINATE, ETA_UNKNOWN, failedModules, 0L);
return done(failedModules, null);
}

/** K2GO-593: the batch ended because the user canceled {@code canceledModule} (also in failedModules). */
public static ModuleQueueState done(List<String> failedModules, String canceledModule) {
return new ModuleQueueState(Phase.DONE, null, 0, INDETERMINATE, ETA_UNKNOWN, failedModules,
canceledModule, 0L);
}

ModuleQueueState withSeq(long seq) {
return new ModuleQueueState(phase, currentModule, remaining, percent, etaSeconds, failedModules, seq);
return new ModuleQueueState(phase, currentModule, remaining, percent, etaSeconds, failedModules, canceledModule, seq);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -227,11 +227,9 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c
// — where the batch we just re-fired shows its rows, progress and log. NOT onBackPressed:
// that dropped the user on the hub, which during an install only shows "Adding content"
// with no route to the progress (the bug seen retrying from Module management).
schedule.setOnClickListener(v -> {
if (ModuleRetry.fire(v, c.key())) {
startActivity(new android.content.Intent(requireContext(), SetupProgressActivity.class));
}
});
schedule.setOnClickListener(v -> ModuleRetry.fire(v, c.key(), () -> {
if (isAdded()) startActivity(new android.content.Intent(requireContext(), SetupProgressActivity.class));
}));
schedule.setVisibility(View.VISIBLE);
installNowBtn.setText(R.string.k2go_setup_back);
installNowBtn.setOnClickListener(v -> requireActivity().getOnBackPressedDispatcher().onBackPressed());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -496,15 +496,19 @@ private View cardRow(final ModuleCards.Card c, final boolean isInstalled,
// already there cannot meaningfully be waiting to be installed, and if a stale wishlist
// entry survived an install, saying "Scheduled" over it would be the older lie again.
boolean scheduled = !isInstalled && !unknown && ModuleWishlist.contains(requireContext(), c.key());
boolean canceled = failed && org.appdevforall.k2go.install.presentation.ModuleQueueRepository.get()
.current().wasCanceled(c.key());
// K2GO-385 (PR3): a lifecycle state is a read-only STATUS -- dot + text, semantic colour, no
// ripple (the shared K2GoStatusBadge) -- not an outlined pill that reads like a button.
LinearLayout pill = K2GoStatusBadge.create(requireContext(),
isInstalled ? getString(R.string.k2go_mod_phase_done)
: canceled ? getString(R.string.k2go_mod_phase_canceled) // K2GO-593
: failed ? getString(R.string.k2go_mod_phase_failed)
: unknown ? getString(R.string.k2go_state_no_answer)
: scheduled ? getString(R.string.k2go_mod_scheduled)
: getString(R.string.k2go_state_not_installed),
isInstalled ? R.color.k2go_leaf
: canceled ? R.color.k2go_muted
: failed ? R.color.k2go_clay
: unknown ? R.color.k2go_amber_text
: scheduled ? R.color.k2go_teal : R.color.k2go_muted);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,8 @@ private void updateStatus() {
// failedModules.contains(...); routed through the shared atom so the three can't drift apart.
if (mq.didFail(key)) {
terminalDone = true;
status.setText(getString(R.string.k2go_mod_phase_failed));
status.setText(getString(mq.wasCanceled(key) // K2GO-593: a user stop is not an error
? R.string.k2go_mod_phase_canceled : R.string.k2go_mod_phase_failed));
return;
}
if (mq.phase == ModuleQueueState.Phase.DONE) {
Expand Down
Loading
Loading