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
56 changes: 34 additions & 22 deletions controller/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -492,32 +492,39 @@ task refreshRootfsSizes {
def tiers = ['basic', 'standard', 'full']
def abis = ['arm64-v8a', 'armeabi-v7a']
def sizePat = ~/<size>(\d+)<\/size>/
// ADFA-5105: capture BOTH the compressed download size (.meta4 <size>) and the
// uncompressed installed size (.installed sidecar, ADFA-5110). The installed value is
// what the destructive free-space guard needs; keep both columns in sync per build.
def fetch = { String url ->
def conn = (HttpURLConnection) new URL(url).openConnection()
conn.setRequestProperty('User-Agent', 'iiab-android-build')
conn.connectTimeout = 6000
conn.readTimeout = 6000
if (conn.responseCode != 200) { conn.disconnect(); return null }
def body = conn.inputStream.getText('UTF-8')
conn.disconnect()
return body
}
def fetched = [:]
def fetchedInst = [:]
for (t in tiers) {
for (a in abis) {
def url = "${base}latest_${t}_${a}.meta4"
try {
def conn = (HttpURLConnection) new URL(url).openConnection()
conn.setRequestProperty('User-Agent', 'iiab-android-build')
conn.connectTimeout = 6000
conn.readTimeout = 6000
if (conn.responseCode != 200) {
logger.warn(">> [rootfs sizes] HTTP ${conn.responseCode} for ${url}")
conn.disconnect(); continue
}
def body = conn.inputStream.getText('UTF-8')
conn.disconnect()
def m = sizePat.matcher(body)
if (m.find()) { fetched["${t}|${a}".toString()] = m.group(1) }
else { logger.warn(">> [rootfs sizes] no <size> element in ${url}") }
def meta = fetch("${base}latest_${t}_${a}.meta4")
def m = meta != null ? sizePat.matcher(meta) : null
if (m != null && m.find()) { fetched["${t}|${a}".toString()] = m.group(1) }
else { logger.warn(">> [rootfs sizes] no compressed size for ${t}/${a}") }
def inst = fetch("${base}latest_${t}_${a}.installed")
if (inst != null && inst.trim() ==~ /\d+/) { fetchedInst["${t}|${a}".toString()] = inst.trim() }
else { logger.warn(">> [rootfs sizes] no installed size for ${t}/${a}") }
} catch (Exception e) {
logger.warn(">> [rootfs sizes] fetch failed for ${url}: ${e.message}")
logger.warn(">> [rootfs sizes] fetch failed for ${t}/${a}: ${e.message}")
}
}
}
def expected = tiers.size() * abis.size()
if (fetched.size() != expected) {
logger.warn(">> [rootfs sizes] incomplete fetch (${fetched.size()}/${expected}); keeping existing ${csv.name} (last known).")
if (fetched.size() != expected || fetchedInst.size() != expected) {
logger.warn(">> [rootfs sizes] incomplete fetch (compressed ${fetched.size()}/${expected}, installed ${fetchedInst.size()}/${expected}); keeping existing ${csv.name} (last known).")
return
}
def existing = [:]
Expand All @@ -526,18 +533,23 @@ task refreshRootfsSizes {
line = line.trim()
if (line.isEmpty() || line.startsWith('#')) return
def p = line.split(',')
if (p.length >= 3) existing["${p[0].trim()}|${p[1].trim()}".toString()] = p[2].trim()
if (p.length >= 5) existing["${p[0].trim()}|${p[1].trim()}".toString()] = "${p[2].trim()}|${p[4].trim()}".toString()
}
}
if (existing == fetched) {
println ">> [rootfs sizes] up to date (${fetched.size()} entries unchanged)."
def current = [:]
for (t in tiers) for (a in abis) current["${t}|${a}".toString()] = "${fetched[("${t}|${a}").toString()]}|${fetchedInst[("${t}|${a}").toString()]}".toString()
if (existing == current) {
println ">> [rootfs sizes] up to date (${current.size()} entries unchanged)."
return
}
def today = new Date().format('yyyy-MM-dd')
def rows = []
for (t in tiers) for (a in abis) rows << "${t},${a},${fetched[("${t}|${a}").toString()]},${today}".toString()
for (t in tiers) for (a in abis) {
def k = "${t}|${a}".toString()
rows << "${t},${a},${fetched[k]},${today},${fetchedInst[k]}".toString()
}
if (!csv.parentFile.exists()) csv.parentFile.mkdirs()
csv.text = '# tier,abi,bytes,fetched_date -- AUTO-GENERATED by the refreshRootfsSizes Gradle task; do not edit by hand\n' + rows.join('\n') + '\n'
csv.text = '# tier,abi,bytes,fetched_date,installed_bytes -- AUTO-GENERATED by the refreshRootfsSizes Gradle task; do not edit by hand\n' + rows.join('\n') + '\n'
println ">> [rootfs sizes] updated ${rows.size()} entries in ${csv.name} (${today})."
}
}
Expand Down
14 changes: 7 additions & 7 deletions controller/app/src/main/assets/rootfs_sizes.csv
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# tier,abi,bytes,fetched_date -- AUTO-GENERATED by the refreshRootfsSizes Gradle task; do not edit by hand
basic,arm64-v8a,1931026680,2026-08-03
basic,armeabi-v7a,1933300053,2026-08-03
standard,arm64-v8a,2140334409,2026-08-03
standard,armeabi-v7a,2142535092,2026-08-03
full,arm64-v8a,2834585013,2026-08-03
full,armeabi-v7a,2827035164,2026-08-03
# tier,abi,bytes,fetched_date,installed_bytes -- AUTO-GENERATED by the refreshRootfsSizes Gradle task; do not edit by hand
basic,arm64-v8a,1936814083,2026-08-12,3294993334
basic,armeabi-v7a,1937574673,2026-08-12,3162669853
standard,arm64-v8a,2146100011,2026-08-12,3675639489
standard,armeabi-v7a,2146813777,2026-08-12,3542808901
full,arm64-v8a,2841912764,2026-08-12,5103603118
full,armeabi-v7a,2833106837,2026-08-12,4856267277
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,20 @@ private void runBackup(final String uriStr) {
// ---- RESTORE (destructive) ----
private void runRestore(final String path) {
if (done) return;
// ADFA-5105: the restore overwrites the rootfs with the backup's contents. Refuse before
// anything is touched when the uncompressed backup plainly won't fit (fail-safe on UNKNOWN
// free space too). The "needed" is estimated from the backup archive already on disk.
long needed = org.iiab.controller.storage.SpaceEstimate.fromCompressed(new File(path).length());
org.iiab.controller.storage.FreeSpacePreflight.Result pf =
org.iiab.controller.storage.FreeSpacePreflight.check(this, needed);
if (!pf.ok) {
File tmp = new File(path);
if (tmp.exists()) tmp.delete();
finishJob(false, getString(R.string.k2go_br_restore_done),
getString(R.string.install_error_no_storage) + " ("
+ org.iiab.controller.util.ByteFormatter.toHuman(pf.amountToReport()) + ")");
return;
}
// ADFA-5070: stop the downloads before the tar starts overwriting the rootfs
// they were writing into. The pending orders are not touched yet — a tar that
// will not open leaves the system intact, and discarding them here would have
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -260,6 +260,10 @@ private void runPipeline() {
else finishSuccess();
return;
}
// ADFA-5105: from here on the pipeline extracts a rootfs (and, on reinstall, wipes the
// existing one first). Refuse before any destructive step when it plainly won't fit —
// UNKNOWN free space refuses too (a wipe that then runs out of disk leaves no bootable OS).
if (!ensureSpaceForRootfs()) return;
if (reinstall && debianRootfs.exists() && debianRootfs.isDirectory()) {
// ADFA-5023: a reinstall wipes the LIVE rootfs. Doing rm -rf while the server proot is up
// is the corruption the legacy reset/delete guarded against (they refused when alive). If a
Expand Down Expand Up @@ -402,6 +406,10 @@ public void onComplete(String destDir) {

@Override
public void onError(String error) {
// ADFA-5105: don't leave the compressed .tar.gz behind on a failed extract —
// on success it's deleted below, but a failure used to keep it, silently
// holding ~2–3 GB until the next attempt.
downloadedArchive.delete();
org.iiab.controller.analytics.AnalyticsClient.with(InstallService.this).logInstallFailed("extract", "extract_error");
fail(getString(R.string.install_error_extraction, error));
}
Expand Down Expand Up @@ -581,6 +589,9 @@ private void editLocalVarsForMaps(File debianRootfs, InstallationPlanner.Tier ti
*/
private void runResetPipeline() {
try {
// ADFA-5105: reset wipes the rootfs and re-extracts a base one. Refuse before the wipe
// when it won't fit (fail-safe on UNKNOWN free space too).
if (!ensureSpaceForRootfs()) return;
// ADFA-5070: stop and forget the downloads before the rootfs they were
// writing into goes away.
org.iiab.controller.system.data.ContentStateInvalidator.replacementStarting(this,
Expand Down Expand Up @@ -912,6 +923,30 @@ private void fail(String message) {
teardown();
}

/**
* ADFA-5105: destructive-run free-space preflight. This gate runs BEFORE the download, and the
* pipeline then writes the compressed .tar.gz and the uncompressed tree, which coexist during
* extraction — so the "needed" is the PEAK (compressed + uncompressed) for this tier+abi, from
* RootfsCatalog (measured via ADFA-5110 when published, estimate otherwise). Returns true to
* proceed; on a refusal it reports the shortfall through fail() and returns false so the caller
* stops before wiping.
*/
private boolean ensureSpaceForRootfs() {
if (cancelled) return false;
org.iiab.controller.rootfs.data.RootfsCatalog cat =
new org.iiab.controller.rootfs.data.RootfsCatalog(this);
org.iiab.controller.rootfs.domain.RootfsTier rTier =
(tier == null) ? org.iiab.controller.rootfs.domain.RootfsTier.BASIC
: org.iiab.controller.rootfs.domain.RootfsTier.valueOf(tier.name());
long needed = cat.peakInstallBytes(rTier, cat.detectAbi());
org.iiab.controller.storage.FreeSpacePreflight.Result pf =
org.iiab.controller.storage.FreeSpacePreflight.check(this, needed);
if (pf.ok) return true;
fail(getString(R.string.install_error_no_storage) + " ("
+ org.iiab.controller.util.ByteFormatter.toHuman(pf.amountToReport()) + ")");
return false;
}

private void doCancel() {
if (finished) return;
cancelled = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -294,6 +294,16 @@ private void recalculateProjection() {
}
}

/** ADFA-5105: the wizard tier -> the rootfs slice's tier enum (same names, null -> BASIC). */
private static org.iiab.controller.rootfs.domain.RootfsTier mapRootfsTier(org.iiab.controller.InstallationPlanner.Tier t) {
if (t == null) return org.iiab.controller.rootfs.domain.RootfsTier.BASIC;
switch (t) {
case FULL: return org.iiab.controller.rootfs.domain.RootfsTier.FULL;
case STANDARD: return org.iiab.controller.rootfs.domain.RootfsTier.STANDARD;
default: return org.iiab.controller.rootfs.domain.RootfsTier.BASIC;
}
}

private void onRootfsSizeResolved(RootfsUiState rootfsState) {
if (!fragment.isAdded() || rootfsState == null) return;
if (rootfsState.status == RootfsUiState.Status.LOADING) return;
Expand Down Expand Up @@ -322,17 +332,36 @@ public void onCalculated(InstallationPlanner.StorageProjection projection) {
double totalSpaceGb = path.getTotalSpace() / (1024.0 * 1024.0 * 1024.0);
double usedSpaceGb = totalSpaceGb - freeSpaceGb;

double pOs = (host.getSelectedTier() == null) ? 0.0 : projection.osSize;
double pMaps = (host.getSelectedTier() == null) ? 0.0 : projection.mapsSize;
final double GB = 1024.0 * 1024.0 * 1024.0;
boolean hasTier = host.getSelectedTier() != null;
// --- DETECT ARCHITECTURE ---
String arch = host.getTermuxArch();
boolean is64Bit = arch != null && arch.contains("64");

// ADFA-5105: size the OS by its UNCOMPRESSED footprint (what actually lands), the
// same figure the destructive gate uses — not the compressed download — so the
// legend and the "fits" decision agree with the hard preflight in InstallService.
org.iiab.controller.rootfs.data.RootfsCatalog rc =
new org.iiab.controller.rootfs.data.RootfsCatalog(fragment.requireContext());
org.iiab.controller.rootfs.domain.RootfsAbi rAbi = rc.detectAbi();
org.iiab.controller.rootfs.domain.RootfsTier rTier = mapRootfsTier(host.getSelectedTier());

double pOs = hasTier ? rc.installedBytes(rTier, rAbi) / GB : 0.0;
double pMaps = hasTier ? projection.mapsSize : 0.0;

// --- FORCE KIWIX TO ZERO IN 32-BITS (change if kiwix gets support for 32bits somehow) ---
double pKiwix = (host.getSelectedTier() == null || !is64Bit) ? 0.0 : projection.kiwixSize;
double pKiwix = (!hasTier || !is64Bit) ? 0.0 : projection.kiwixSize;
double pTotal = pOs + pMaps + pKiwix;

host.setStorageSafe(pTotal <= (freeSpaceGb - 5.0));
// Gate on the same PEAK the install needs — the compressed download and the
// uncompressed tree coexist during extraction (RootfsCatalog.peakInstallBytes) — plus
// the content, on the real write target. UNKNOWN free space stays "safe" (advisory);
// the hard preflight in InstallService refuses for real before any wipe.
long neededBytes = (hasTier ? rc.peakInstallBytes(rTier, rAbi) : 0L)
+ (long) Math.ceil((pMaps + pKiwix) * GB);
Long freeBytes = org.iiab.controller.storage.StorageProbe.freeBytes(fragment.requireContext());
host.setStorageSafe(org.iiab.controller.storage.StorageGuard.evaluate(freeBytes, neededBytes)
!= org.iiab.controller.storage.StorageGuard.Verdict.DOES_NOT_FIT);

if (txtLegendIiab != null)
txtLegendIiab.setText(String.format(java.util.Locale.US, "%.1fG", pOs));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.StatFs;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
Expand Down Expand Up @@ -198,9 +197,10 @@ private String langDisplay(String code) {

private void readFreeSpace() {
try {
StatFs st = new StatFs(requireContext().getFilesDir().getPath());
freeMb = st.getAvailableBytes() / (1024L * 1024L);
totalMb = st.getTotalBytes() / (1024L * 1024L);
Long fb = org.iiab.controller.storage.StorageProbe.freeBytes(requireContext()); // ADFA-5105: shared probe
Long tb = org.iiab.controller.storage.StorageProbe.totalBytes(requireContext());
freeMb = (fb == null ? 0L : fb) / (1024L * 1024L);
totalMb = (tb == null ? 0L : tb) / (1024L * 1024L);
} catch (Exception e) {
freeMb = 0L;
totalMb = 0L;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@

import android.content.Context;
import android.os.Bundle;
import android.os.StatFs;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
Expand Down Expand Up @@ -341,7 +340,7 @@ private long totalCost(List<Channel> chosen) {
/** Free bytes on the data partition, or null when it cannot be read. */
private Long readFreeBytes() {
try {
return new StatFs(requireContext().getFilesDir().getPath()).getAvailableBytes();
return org.iiab.controller.storage.StorageProbe.freeBytes(requireContext()); // ADFA-5105: shared probe
} catch (Exception e) {
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
import android.graphics.Typeface;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.os.StatFs;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
Expand Down Expand Up @@ -225,9 +224,10 @@ private Channel resolveChannel() {

private void readFreeSpace() {
try {
StatFs st = new StatFs(requireContext().getFilesDir().getPath());
freeMb = st.getAvailableBytes() / (1024L * 1024L);
totalMb = st.getTotalBytes() / (1024L * 1024L);
Long fb = org.iiab.controller.storage.StorageProbe.freeBytes(requireContext()); // ADFA-5105: shared probe
Long tb = org.iiab.controller.storage.StorageProbe.totalBytes(requireContext());
freeMb = (fb == null ? 0L : fb) / (1024L * 1024L);
totalMb = (tb == null ? 0L : tb) / (1024L * 1024L);
} catch (Exception e) {
freeMb = 0L;
totalMb = 0L;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@

import android.graphics.Typeface;
import android.os.Bundle;
import android.os.StatFs;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
Expand Down Expand Up @@ -109,11 +108,9 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c
fit = root.findViewById(R.id.k2go_fit);
download = root.findViewById(R.id.k2go_download_btn);

try {
freeMb = new StatFs(requireContext().getFilesDir().getPath()).getAvailableBytes() / (1024L * 1024L);
} catch (Exception e) {
freeMb = 0;
}
// ADFA-5105: read free space through the shared probe, not a per-screen StatFs copy.
Long fb = org.iiab.controller.storage.StorageProbe.freeBytes(requireContext());
freeMb = (fb == null ? 0L : fb) / (1024L * 1024L);

resolveSizes();
buildGroups(root.findViewById(R.id.k2go_maps_groups));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
package org.iiab.controller.redesign;

import android.os.Bundle;
import android.os.StatFs;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
Expand Down Expand Up @@ -121,11 +120,11 @@ public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup c
sortGroup.setOnClickListener(v -> { view = "group"; render(); });
sortGroup.setVisibility(isWiki() ? View.VISIBLE : View.GONE);

try {
StatFs st = new StatFs(requireContext().getFilesDir().getPath());
freeMb = st.getAvailableBytes() / (1024L * 1024L);
totalMb = st.getTotalBytes() / (1024L * 1024L);
} catch (Exception e) { freeMb = 0; totalMb = 0; }
// ADFA-5105: shared free-space probe instead of a per-screen StatFs copy.
Long fb = org.iiab.controller.storage.StorageProbe.freeBytes(requireContext());
Long tb = org.iiab.controller.storage.StorageProbe.totalBytes(requireContext());
freeMb = (fb == null ? 0L : fb) / (1024L * 1024L);
totalMb = (tb == null ? 0L : tb) / (1024L * 1024L);

KiwixCatalog.getOrFetch(requireContext(), new KiwixCatalog.Listener() {
@Override public void onReady(JSONObject c) { if (!isAdded()) return; catalog = c; rebuild(); }
Expand Down
Loading
Loading