diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 83b2244..2b3f59a 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -70,6 +70,13 @@ android:foregroundServiceType="dataSync" android:stopWithTask="false" /> + + (null) private var rootfsStorageLoading by mutableStateOf(false) private var rootfsStorageName: String? = null + private var pendingCheckpointRootfsName: String? = null + private var activeCheckpointOperationId: String? = null private var desktopEnvironments by mutableStateOf>(emptyList()) private var desktopConfiguration by mutableStateOf(DesktopConfiguration(null, compositingEnabled = false, touchScaleEnabled = true)) @@ -167,6 +175,36 @@ class MainActivity : ComponentActivity() { } } + private val backupDocumentLauncher = + registerForActivityResult(ActivityResultContracts.CreateDocument("application/x-xz")) { uri -> + val rootfsName = pendingCheckpointRootfsName + pendingCheckpointRootfsName = null + if (uri != null && rootfsName != null) { + runCatching { + contentResolver.takePersistableUriPermission( + uri, + Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION, + ) + } + startRootfsBackup(rootfsName, uri) + } + } + + private val restoreDocumentLauncher = + registerForActivityResult(ActivityResultContracts.OpenDocument()) { uri -> + val rootfsName = pendingCheckpointRootfsName + pendingCheckpointRootfsName = null + if (uri != null && rootfsName != null) { + runCatching { + contentResolver.takePersistableUriPermission( + uri, + Intent.FLAG_GRANT_READ_URI_PERMISSION, + ) + } + startRootfsRestore(rootfsName, uri) + } + } + private val runtimeServiceConnection = object : ServiceConnection { override fun onServiceConnected( @@ -274,6 +312,8 @@ class MainActivity : ComponentActivity() { onOpenInstallation = { openInstallationDetails(it) }, onOpenRootfsTerminal = { openRootfsTerminal(it) }, onOpenRootfsApps = { openRootfsApps(it) }, + onBackupRootfs = { chooseRootfsBackupDestination(it) }, + onRestoreRootfs = { chooseRootfsBackupToRestore(it) }, onResetRootfs = { rootfsName, fallback -> resetRootfs(rootfsName, fallback) }, @@ -343,6 +383,7 @@ class MainActivity : ComponentActivity() { handleStopIntent(intent) handleUpdateIntent(intent) handleInstallerIntent(intent) + handleCheckpointIntent(intent) if (!handleShortcutIntent(intent)) loadLinuxApplications() handleDebugCommand() } @@ -353,6 +394,7 @@ class MainActivity : ComponentActivity() { handleStopIntent(intent) handleUpdateIntent(intent) handleInstallerIntent(intent) + handleCheckpointIntent(intent) handleShortcutIntent(intent) handleDebugCommand() } @@ -366,6 +408,7 @@ class MainActivity : ComponentActivity() { addAction(RuntimeSupervisorService.ACTION_STATE_CHANGED) addAction(RuntimeSupervisorService.ACTION_TERMINAL_TABS_CHANGED) addAction(InstallerService.ACTION_STATE_CHANGED) + addAction(RootfsCheckpointService.ACTION_STATE_CHANGED) addAction(AppUpdateContract.ACTION_STATE_CHANGED) }, ContextCompat.RECEIVER_NOT_EXPORTED, @@ -470,6 +513,7 @@ class MainActivity : ComponentActivity() { snapshot = app.runtimeState.current() installProgress = app.installState.current() updateState = app.updateState.current() + refreshCheckpointState() installedRootfses = app.rootfsRegistry.all() installedRootfsName = app.rootfsRegistry.active()?.name resettableRootfsNames = @@ -708,6 +752,106 @@ class MainActivity : ComponentActivity() { maintainRootfs(rootfsName, resetWork = null) } + private fun chooseRootfsBackupDestination(rootfsName: String) { + rootfsMaintenanceBlockReason(rootfsName)?.let { + rootfsMaintenanceMessage = it + return + } + if (installedRootfses.none { it.name == rootfsName }) { + rootfsMaintenanceMessage = "Linux system $rootfsName is no longer installed" + return + } + pendingCheckpointRootfsName = rootfsName + val timestamp = SimpleDateFormat("yyyyMMdd-HHmm", Locale.US).format(Date()) + backupDocumentLauncher.launch("$rootfsName-$timestamp.tar.xz") + } + + private fun chooseRootfsBackupToRestore(rootfsName: String) { + rootfsMaintenanceBlockReason(rootfsName)?.let { + rootfsMaintenanceMessage = it + return + } + if (installedRootfses.none { it.name == rootfsName }) { + rootfsMaintenanceMessage = "Linux system $rootfsName is no longer installed" + return + } + pendingCheckpointRootfsName = rootfsName + restoreDocumentLauncher.launch(arrayOf("application/x-xz", "application/octet-stream")) + } + + private fun startRootfsBackup( + rootfsName: String, + destination: Uri, + ) { + rootfsMaintenanceBlockReason(rootfsName)?.let { + rootfsMaintenanceMessage = it + runCatching { contentResolver.delete(destination, null, null) } + return + } + rootfsMaintenanceName = rootfsName + rootfsMaintenanceMessage = "Preparing the rootfs backup" + ensureNotificationPermission() + runCatching { RootfsCheckpointService.backup(this, rootfsName, destination) } + .onSuccess { activeCheckpointOperationId = it } + .onFailure { + rootfsMaintenanceName = null + rootfsMaintenanceMessage = it.message ?: "Could not start the rootfs backup" + runCatching { contentResolver.delete(destination, null, null) } + } + } + + private fun startRootfsRestore( + rootfsName: String, + source: Uri, + ) { + rootfsMaintenanceBlockReason(rootfsName)?.let { + rootfsMaintenanceMessage = it + return + } + rootfsMaintenanceName = rootfsName + rootfsMaintenanceMessage = "Preparing to restore the rootfs" + ensureNotificationPermission() + runCatching { RootfsCheckpointService.restore(this, rootfsName, source) } + .onSuccess { activeCheckpointOperationId = it } + .onFailure { + rootfsMaintenanceName = null + rootfsMaintenanceMessage = it.message ?: "Could not start the rootfs restore" + } + } + + private fun refreshCheckpointState() { + val checkpoint = app.checkpointState.current() ?: return + if (checkpoint.stage.running) { + activeCheckpointOperationId = checkpoint.operationId + rootfsMaintenanceName = checkpoint.rootfsName + rootfsMaintenanceMessage = + checkpoint.progress?.let { "${checkpoint.detail} · $it%" } ?: checkpoint.detail + return + } + if (activeCheckpointOperationId == checkpoint.operationId) { + activeCheckpointOperationId = null + rootfsMaintenanceName = null + rootfsMaintenanceMessage = + checkpoint.detail.takeIf { checkpoint.stage == RootfsCheckpointStage.FAILED } + if ( + checkpoint.operation == RootfsCheckpointOperation.RESTORE && + checkpoint.stage == RootfsCheckpointStage.COMPLETE + ) { + rootfsStorageName = null + rootfsOccupiedBytes = null + linuxApplicationsLoadGeneration++ + desktopScanGeneration++ + loadDesktopEnvironments(checkpoint.rootfsName) + } + } else if ( + rootfsMaintenanceName == null && + checkpoint.stage == RootfsCheckpointStage.FAILED && + selectedSystemRootfsName == checkpoint.rootfsName + ) { + rootfsMaintenanceMessage = checkpoint.detail + } + } + private fun resetRootfs( rootfsName: String, fallbackDistro: DistroVariant?, @@ -1471,6 +1615,16 @@ class MainActivity : ComponentActivity() { selectDestination(UdroidDestination.SYSTEM) } + private fun handleCheckpointIntent(intent: Intent?) { + if (intent?.action != RootfsCheckpointService.ACTION_SHOW_CHECKPOINT) return + selectedSystemRootfsName = + intent.getStringExtra(RootfsCheckpointService.EXTRA_ROOTFS_NAME) + ?: app.checkpointState.current()?.rootfsName + intent.action = null + refreshFromDisk() + selectDestination(UdroidDestination.SYSTEM) + } + private fun installDownloadedUpdate() { when (val result = AppUpdateInstaller.install(this, updateState)) { UpdateInstallResult.Submitted -> { diff --git a/app/src/main/java/org/randomcoder/udroid/UdroidApplication.kt b/app/src/main/java/org/randomcoder/udroid/UdroidApplication.kt index 13c23a0..299298e 100644 --- a/app/src/main/java/org/randomcoder/udroid/UdroidApplication.kt +++ b/app/src/main/java/org/randomcoder/udroid/UdroidApplication.kt @@ -1,10 +1,15 @@ package org.randomcoder.udroid import android.app.Application +import android.net.Uri import android.os.Build import org.randomcoder.udroid.install.InstallStage import org.randomcoder.udroid.install.InstallStateStore import org.randomcoder.udroid.install.InstalledRootfsSourceStore +import org.randomcoder.udroid.install.RootfsCheckpointOperation +import org.randomcoder.udroid.install.RootfsCheckpointStage +import org.randomcoder.udroid.install.RootfsCheckpointStateStore +import org.randomcoder.udroid.install.RootfsCheckpointSwap import org.randomcoder.udroid.runtime.EventJournal import org.randomcoder.udroid.runtime.InstalledRootfsRegistry import org.randomcoder.udroid.runtime.ProotMountProfileStore @@ -27,6 +32,9 @@ class UdroidApplication : Application() { lateinit var rootfsInstallSources: InstalledRootfsSourceStore private set + lateinit var checkpointState: RootfsCheckpointStateStore + private set + lateinit var updateState: AppUpdateStateStore private set @@ -42,11 +50,49 @@ class UdroidApplication : Application() { journal = EventJournal(this) installState = InstallStateStore(this) rootfsInstallSources = InstalledRootfsSourceStore(this) + checkpointState = RootfsCheckpointStateStore(this) updateState = AppUpdateStateStore(this) rootfsRegistry = InstalledRootfsRegistry(this) mountProfiles = ProotMountProfileStore(this) if (!isMainProcess()) return + checkpointState.current()?.let { checkpoint -> + val recoveryFailure = + if (checkpoint.operation == RootfsCheckpointOperation.RESTORE) { + runCatching { + RootfsCheckpointSwap.recover( + RootfsCheckpointSwap.paths( + File(filesDir, "rootfs"), + checkpoint.rootfsName, + checkpoint.operationId, + ), + ) + val checkpointDirectory = File(filesDir, "checkpoints") + File(checkpointDirectory, "restore-${checkpoint.operationId}.tar.xz.part").delete() + File(checkpointDirectory, "restore-${checkpoint.operationId}.tar.xz").delete() + }.exceptionOrNull() + } else { + null + } + if (checkpoint.stage.running || recoveryFailure != null) { + if (checkpoint.operation == RootfsCheckpointOperation.BACKUP) { + checkpoint.documentUri?.let(Uri::parse)?.let { uri -> + runCatching { contentResolver.delete(uri, null, null) } + } + } + checkpointState.save( + checkpoint.copy( + stage = RootfsCheckpointStage.FAILED, + detail = + recoveryFailure?.message + ?: "Previous checkpoint operation was interrupted", + progress = null, + documentUri = null, + ), + ) + } + } + updateState.reconcileInstalledVersion(BuildConfig.VERSION_NAME) AppUpdateScheduler.ensureScheduled(this) installState.current()?.takeIf { it.cancellable }?.let { interrupted -> diff --git a/app/src/main/java/org/randomcoder/udroid/install/AndroidRootfsRuntime.kt b/app/src/main/java/org/randomcoder/udroid/install/AndroidRootfsRuntime.kt index ab141df..0987ee2 100644 --- a/app/src/main/java/org/randomcoder/udroid/install/AndroidRootfsRuntime.kt +++ b/app/src/main/java/org/randomcoder/udroid/install/AndroidRootfsRuntime.kt @@ -300,6 +300,8 @@ class ProotTarExtractor( add("--exclude=${path.removePrefix("/")}") } add("--exclude=$RUNTIME_MOUNT_DIRECTORY") + add("--exclude=${RootfsInstallationPipeline.READY_MARKER}") + add("--exclude=${RootfsInstallationPipeline.INSTALLING_MARKER}") if (excludeOciWhiteouts) { add("--wildcards") add("--exclude=.wh.*") diff --git a/app/src/main/java/org/randomcoder/udroid/install/RootfsCheckpoint.kt b/app/src/main/java/org/randomcoder/udroid/install/RootfsCheckpoint.kt new file mode 100644 index 0000000..59c43c1 --- /dev/null +++ b/app/src/main/java/org/randomcoder/udroid/install/RootfsCheckpoint.kt @@ -0,0 +1,315 @@ +package org.randomcoder.udroid.install + +import android.content.Context +import org.randomcoder.udroid.runtime.ANDROID_PROOT_BIND_MOUNTS +import org.randomcoder.udroid.runtime.AndroidExecutableCommand +import org.randomcoder.udroid.runtime.ProotPathContract +import org.randomcoder.udroid.runtime.RootfsTreeDeleter +import org.randomcoder.udroid.runtime.addAndroidProotBindMounts +import java.io.BufferedReader +import java.io.File +import java.io.FileOutputStream +import java.io.InputStreamReader +import java.io.InterruptedIOException +import java.io.OutputStream +import java.nio.charset.StandardCharsets +import java.nio.file.Files +import java.util.concurrent.TimeUnit + +class RootfsCheckpointArchiver( + private val context: Context, + private val runtime: ProotRuntime, +) { + fun archive( + rootfs: File, + output: OutputStream, + onProgress: (bytes: Long) -> Unit = {}, + ) { + require(File(rootfs, RootfsInstallationPipeline.READY_MARKER).isFile) { + "Linux system ${rootfs.name} is not ready" + } + val runtimeMount = File(rootfs, RUNTIME_MOUNT_DIRECTORY) + check(!Files.isSymbolicLink(runtimeMount.toPath())) { + "Unsafe checkpoint runtime path" + } + check(runtimeMount.mkdirs() || runtimeMount.isDirectory) { + "Could not prepare checkpoint runtime" + } + val tarMount = File(runtimeMount, "tar").apply { + if (exists()) check(delete()) { "Could not clear the previous GNU tar mount" } + check(createNewFile()) { "Could not prepare the GNU tar mount" } + } + val command = + AndroidExecutableCommand.create( + runtime.executable, + *buildArguments( + rootfsPath = ProotPathContract.rootfsPath(context, rootfs), + tarExecutablePath = runtime.tarExecutable.absolutePath, + tarMountPath = "/$RUNTIME_MOUNT_DIRECTORY/${tarMount.name}", + ).toTypedArray(), + ) + val temporaryDirectory = + File(context.cacheDir, "proot").apply { + check(mkdirs() || isDirectory) { "Could not create PRoot temporary storage" } + } + val process = + ProcessBuilder(command) + .directory(context.filesDir) + .redirectErrorStream(false) + .apply { + environment().remove("LD_PRELOAD") + environment()["HOME"] = context.filesDir.absolutePath + environment()["TMPDIR"] = temporaryDirectory.absolutePath + environment()["PROOT_TMP_DIR"] = temporaryDirectory.absolutePath + environment()["PROOT_LOADER"] = runtime.loader.absolutePath + }.start() + val stderr = mutableListOf() + val stderrThread = + Thread { + BufferedReader(InputStreamReader(process.errorStream)).useLines { lines -> + lines.forEach { line -> + synchronized(stderr) { + if (stderr.size == MAX_DIAGNOSTIC_LINES) stderr.removeAt(0) + stderr += line + } + } + } + }.apply { + name = "udroid-checkpoint-stderr" + isDaemon = true + start() + } + + try { + process.inputStream.buffered().use { input -> + val buffer = ByteArray(COPY_BUFFER_BYTES) + var written = 0L + while (true) { + if (Thread.currentThread().isInterrupted) { + throw InterruptedIOException("Checkpoint backup interrupted") + } + val count = input.read(buffer) + if (count < 0) break + output.write(buffer, 0, count) + written += count + onProgress(written) + } + } + val exitCode = process.waitFor() + stderrThread.join(DIAGNOSTIC_JOIN_MS) + check(exitCode == 0) { + synchronized(stderr) { + stderr.lastOrNull { it.isNotBlank() } + ?.let { "GNU tar failed ($exitCode): $it" } + ?: "GNU tar failed with exit code $exitCode" + } + } + } catch (error: Throwable) { + process.destroy() + if (!process.waitFor(PROCESS_STOP_GRACE_MS, TimeUnit.MILLISECONDS)) { + process.destroyForcibly() + } + stderrThread.join(DIAGNOSTIC_JOIN_MS) + throw error + } finally { + tarMount.delete() + runtimeMount.delete() + } + } + + companion object { + internal fun buildArguments( + rootfsPath: String, + tarExecutablePath: String, + tarMountPath: String, + ): List = + buildList { + add("--link2symlink") + add("--kill-on-exit") + add("--root-id") + add("--rootfs=$rootfsPath") + addAndroidProotBindMounts() + add("-b") + add("$tarExecutablePath:$tarMountPath") + add("--cwd=/") + add(tarMountPath) + add("--one-file-system") + add("--numeric-owner") + add("--exclude=${RootfsInstallationPipeline.READY_MARKER}") + add("--exclude=${RootfsInstallationPipeline.INSTALLING_MARKER}") + add("--exclude=$RUNTIME_MOUNT_DIRECTORY") + add("--exclude=.udroid-extract") + add("--exclude=*.l2s.*") + ANDROID_PROOT_BIND_MOUNTS.forEach { path -> + add("--exclude=${path.removePrefix("/")}") + add("--exclude=${path.removePrefix("/")}/*") + } + listOf("run", "tmp", "mnt", "media").forEach { path -> + add("--exclude=$path/*") + } + add("-cpf") + add("-") + add(".") + } + + private const val RUNTIME_MOUNT_DIRECTORY = ".udroid-backup" + private const val COPY_BUFFER_BYTES = 64 * 1024 + private const val MAX_DIAGNOSTIC_LINES = 40 + private const val DIAGNOSTIC_JOIN_MS = 1_000L + private const val PROCESS_STOP_GRACE_MS = 1_000L + } +} + +class RootfsCheckpointRestorer( + private val context: Context, + private val runtime: ProotRuntime, +) { + fun restore( + archive: File, + rootfsName: String, + operationId: String, + onExtractionProgress: (completedBytes: Long, totalBytes: Long) -> Unit = { _, _ -> }, + onStage: (RootfsCheckpointStage, String) -> Unit = { _, _ -> }, + ) { + require(archive.isFile) { "Selected rootfs backup is unavailable" } + require(SAFE_NAME.matches(rootfsName)) { "Unsafe rootfs name: $rootfsName" } + require(SAFE_OPERATION_ID.matches(operationId)) { "Unsafe checkpoint operation id" } + val rootfsDirectory = File(context.filesDir, "rootfs") + val paths = RootfsCheckpointSwap.paths(rootfsDirectory, rootfsName, operationId) + RootfsCheckpointSwap.recover(paths) + require(File(paths.current, RootfsInstallationPipeline.READY_MARKER).isFile) { + "Linux system $rootfsName is no longer installed" + } + check(paths.staging.mkdir()) { "Could not create restore staging filesystem" } + + try { + onStage(RootfsCheckpointStage.EXTRACTING, "Extracting the checkpoint") + ProotTarExtractor(context, runtime).extract( + archive = archive, + destination = paths.staging, + onProgress = onExtractionProgress, + ) + onStage(RootfsCheckpointStage.CONFIGURING, "Applying current uDroid integration") + AndroidRootfsConfigurator().configure(paths.staging) + ProotRootfsHealthCheck(context, runtime).check(paths.staging) + RootfsCheckpointReadyMarker.write(paths.staging, rootfsName, operationId) + onStage(RootfsCheckpointStage.SWAPPING, "Activating the restored filesystem") + RootfsCheckpointSwap.swapValidated(paths) + } catch (error: Throwable) { + runCatching { RootfsCheckpointSwap.recover(paths) } + .onFailure { recovery -> error.addSuppressed(recovery) } + throw error + } + } + + companion object { + private val SAFE_NAME = Regex("[A-Za-z0-9][A-Za-z0-9._-]{0,95}") + private val SAFE_OPERATION_ID = Regex("[A-Za-z0-9-]{1,64}") + } +} + +internal data class RootfsCheckpointPaths( + val current: File, + val staging: File, + val previous: File, +) + +internal object RootfsCheckpointSwap { + fun paths( + rootfsDirectory: File, + rootfsName: String, + operationId: String, + ): RootfsCheckpointPaths { + require(SAFE_NAME.matches(rootfsName)) { "Unsafe rootfs name: $rootfsName" } + require(SAFE_OPERATION_ID.matches(operationId)) { "Unsafe checkpoint operation id" } + return RootfsCheckpointPaths( + current = File(rootfsDirectory, rootfsName), + staging = File(rootfsDirectory, "restore-staging-$operationId"), + previous = File(rootfsDirectory, "restore-previous-$operationId"), + ) + } + + fun swapValidated(paths: RootfsCheckpointPaths) { + check(File(paths.current, RootfsInstallationPipeline.READY_MARKER).isFile) { + "Current filesystem is not ready" + } + check(File(paths.staging, RootfsInstallationPipeline.READY_MARKER).isFile) { + "Restored filesystem did not pass validation" + } + check(!paths.previous.exists()) { "Previous restore cleanup is incomplete" } + check(paths.current.renameTo(paths.previous)) { "Could not preserve the current filesystem" } + val previousMarker = File(paths.previous, RootfsInstallationPipeline.READY_MARKER) + val rollbackMarker = File(paths.previous, ROLLBACK_MARKER) + try { + check(previousMarker.renameTo(rollbackMarker)) { + "Could not prepare the current filesystem for rollback" + } + check(paths.staging.renameTo(paths.current)) { + "Could not activate the restored filesystem" + } + } catch (error: Throwable) { + rollbackMarker.renameTo(previousMarker) + if (!paths.current.exists()) paths.previous.renameTo(paths.current) + throw error + } + runCatching { deleteTree(paths.previous) } + } + + fun recover(paths: RootfsCheckpointPaths) { + if (paths.previous.exists()) { + if (!paths.current.exists()) { + if (File(paths.staging, RootfsInstallationPipeline.READY_MARKER).isFile) { + check(paths.staging.renameTo(paths.current)) { + "Could not finish activating the restored filesystem" + } + } else { + val rollbackMarker = File(paths.previous, ROLLBACK_MARKER) + val readyMarker = File(paths.previous, RootfsInstallationPipeline.READY_MARKER) + if (rollbackMarker.isFile) { + check(rollbackMarker.renameTo(readyMarker)) { + "Could not recover the previous filesystem marker" + } + } + check(paths.previous.renameTo(paths.current)) { + "Could not recover the previous filesystem" + } + } + } + if (paths.current.exists()) runCatching { deleteTree(paths.previous) } + } + if (paths.current.exists() && paths.staging.exists()) { + runCatching { deleteTree(paths.staging) } + } + } + + private fun deleteTree(directory: File) { + if (directory.exists()) { + RootfsTreeDeleter.delete(requireNotNull(directory.parentFile).toPath(), directory.name) + } + } + + private const val ROLLBACK_MARKER = ".udroid-rollback-ready" + private val SAFE_NAME = Regex("[A-Za-z0-9][A-Za-z0-9._-]{0,95}") + private val SAFE_OPERATION_ID = Regex("[A-Za-z0-9-]{1,64}") +} + +private object RootfsCheckpointReadyMarker { + fun write( + rootfs: File, + rootfsName: String, + operationId: String, + ) { + val marker = File(rootfs, RootfsInstallationPipeline.READY_MARKER) + FileOutputStream(marker).use { output -> + output.write( + buildString { + appendLine("format=1") + appendLine("name=$rootfsName") + appendLine("operation=$operationId") + appendLine("source=checkpoint") + }.toByteArray(StandardCharsets.UTF_8), + ) + output.fd.sync() + } + } +} diff --git a/app/src/main/java/org/randomcoder/udroid/install/RootfsCheckpointService.kt b/app/src/main/java/org/randomcoder/udroid/install/RootfsCheckpointService.kt new file mode 100644 index 0000000..c2d5f42 --- /dev/null +++ b/app/src/main/java/org/randomcoder/udroid/install/RootfsCheckpointService.kt @@ -0,0 +1,436 @@ +package org.randomcoder.udroid.install + +import android.Manifest +import android.app.Notification +import android.app.NotificationChannel +import android.app.NotificationManager +import android.app.PendingIntent +import android.app.Service +import android.content.Context +import android.content.Intent +import android.content.pm.PackageManager +import android.net.Uri +import android.os.IBinder +import androidx.core.app.NotificationCompat +import androidx.core.content.ContextCompat +import org.randomcoder.udroid.MainActivity +import org.randomcoder.udroid.UdroidApplication +import org.randomcoder.udroid.filesystem.notifyRootfsDocumentsChanged +import org.randomcoder.udroid.linuxapps.LinuxApplicationShortcutPublisher +import org.randomcoder.udroid.runtime.ProotMountResolver +import org.randomcoder.udroid.runtime.DesktopSessionPhase +import org.randomcoder.udroid.runtime.RuntimePhase +import org.randomcoder.udroid.runtime.RootfsStorageUsage +import org.tukaani.xz.LZMA2Options +import org.tukaani.xz.XZOutputStream +import java.io.File +import java.io.FileOutputStream +import java.io.InterruptedIOException +import java.util.UUID +import java.util.concurrent.Executors +import java.util.concurrent.Future + +class RootfsCheckpointService : Service() { + private val worker = Executors.newSingleThreadExecutor() + private var active: Future<*>? = null + + private val app: UdroidApplication + get() = application as UdroidApplication + + override fun onCreate() { + super.onCreate() + createNotificationChannel() + } + + override fun onStartCommand( + intent: Intent?, + flags: Int, + startId: Int, + ): Int { + val action = intent?.action + val operation = + when (action) { + ACTION_BACKUP -> RootfsCheckpointOperation.BACKUP + ACTION_RESTORE -> RootfsCheckpointOperation.RESTORE + else -> null + } + val rootfsName = intent?.getStringExtra(EXTRA_ROOTFS_NAME) + val operationId = intent?.getStringExtra(EXTRA_OPERATION_ID) + val uri = intent?.getStringExtra(EXTRA_URI)?.let(Uri::parse) + if (operation == null || rootfsName == null || operationId == null || uri == null) { + stopSelf(startId) + return START_NOT_STICKY + } + synchronized(this) { + if (active?.isDone == false) return START_NOT_STICKY + val state = + RootfsCheckpointState( + operationId = operationId, + rootfsName = rootfsName, + operation = operation, + stage = RootfsCheckpointStage.PREPARING, + detail = if (operation == RootfsCheckpointOperation.BACKUP) { + "Preparing the rootfs backup" + } else { + "Preparing to restore the rootfs" + }, + documentUri = uri.toString(), + ) + publish(state) + startForeground(NOTIFICATION_ID, notification(state)) + active = + worker.submit { + runOperation(state, uri, startId) + } + } + return START_NOT_STICKY + } + + override fun onBind(intent: Intent?): IBinder? = null + + override fun onDestroy() { + worker.shutdownNow() + super.onDestroy() + } + + private fun runOperation( + initial: RootfsCheckpointState, + uri: Uri, + startId: Int, + ) { + try { + requireRootfsStopped(initial.rootfsName) + when (initial.operation) { + RootfsCheckpointOperation.BACKUP -> backup(initial, uri) + RootfsCheckpointOperation.RESTORE -> restore(initial, uri) + } + val completed = + initial.copy( + stage = RootfsCheckpointStage.COMPLETE, + detail = + if (initial.operation == RootfsCheckpointOperation.BACKUP) { + "Rootfs backup created" + } else { + "Rootfs restored from the selected backup" + }, + progress = 100, + documentUri = null, + ) + publish(completed) + app.journal.append( + component = "rootfs", + severity = "info", + event = + if (initial.operation == RootfsCheckpointOperation.BACKUP) { + "checkpoint_created" + } else { + "checkpoint_restored" + }, + message = completed.detail, + bootId = initial.operationId, + fields = mapOf("installation" to initial.rootfsName), + ) + } catch (error: Throwable) { + if (initial.operation == RootfsCheckpointOperation.BACKUP) { + runCatching { contentResolver.delete(uri, null, null) } + } + val detail = + if (error is InterruptedException || error is InterruptedIOException) { + "Checkpoint operation interrupted" + } else { + error.message ?: "Checkpoint operation failed" + } + publish( + initial.copy( + stage = RootfsCheckpointStage.FAILED, + detail = detail, + progress = null, + documentUri = null, + ), + ) + app.journal.append( + component = "rootfs", + severity = "error", + event = "checkpoint_failed", + message = detail, + bootId = initial.operationId, + fields = + mapOf( + "installation" to initial.rootfsName, + "operation" to initial.operation.name.lowercase(), + "exception" to error.javaClass.name, + ), + ) + } finally { + stopForeground(STOP_FOREGROUND_REMOVE) + stopSelfResult(startId) + } + } + + private fun requireRootfsStopped(rootfsName: String) { + val runtime = app.runtimeState.current() + check( + runtime.rootfsName != rootfsName || + runtime.phase !in + setOf(RuntimePhase.STARTING, RuntimePhase.RUNNING, RuntimePhase.STOPPING), + ) { + "Stop this Linux terminal before creating or restoring a backup" + } + check( + runtime.desktop.rootfsName != rootfsName || + runtime.desktop.phase !in + setOf( + DesktopSessionPhase.STARTING, + DesktopSessionPhase.RUNNING, + DesktopSessionPhase.STOPPING, + ), + ) { + "Stop this desktop before creating or restoring a backup" + } + } + + private fun backup( + state: RootfsCheckpointState, + uri: Uri, + ) { + val rootfs = + app.rootfsRegistry.all().firstOrNull { it.name == state.rootfsName }?.directory + ?: error("Linux system ${state.rootfsName} is no longer installed") + val totalBytes = RootfsStorageUsage.calculate(rootfs).coerceAtLeast(1L) + val progress = ProgressPublisher(state, RootfsCheckpointStage.ARCHIVING, "Creating rootfs backup") + val output = + contentResolver.openOutputStream(uri, "wt") + ?: error("Could not open the selected backup destination") + output.buffered().use { buffered -> + XZOutputStream(buffered, LZMA2Options(3)).use { compressed -> + RootfsCheckpointArchiver(this, ProotRuntimeInstaller.install(this)).archive( + rootfs = rootfs, + output = compressed, + onProgress = { bytes -> progress.update(bytes, totalBytes) }, + ) + } + } + } + + private fun restore( + state: RootfsCheckpointState, + uri: Uri, + ) { + val checkpointDirectory = File(filesDir, "checkpoints").apply { + check(mkdirs() || isDirectory) { "Could not create checkpoint storage" } + } + val partial = File(checkpointDirectory, "restore-${state.operationId}.tar.xz.part") + val archive = File(checkpointDirectory, "restore-${state.operationId}.tar.xz") + partial.delete() + archive.delete() + try { + val totalBytes = + runCatching { + contentResolver.openAssetFileDescriptor(uri, "r")?.use { it.length } ?: -1L + } + .getOrDefault(-1L) + val progress = ProgressPublisher(state, RootfsCheckpointStage.COPYING, "Reading the backup") + val input = contentResolver.openInputStream(uri) ?: error("Could not open the selected backup") + input.buffered().use { source -> + FileOutputStream(partial).use { output -> + val buffer = ByteArray(COPY_BUFFER_BYTES) + var copied = 0L + while (true) { + if (Thread.currentThread().isInterrupted) { + throw InterruptedIOException("Checkpoint restore interrupted") + } + val count = source.read(buffer) + if (count < 0) break + output.write(buffer, 0, count) + copied += count + if (totalBytes > 0L) progress.update(copied, totalBytes) + } + output.fd.sync() + } + } + check(partial.renameTo(archive)) { "Could not finish copying the backup" } + RootfsStoragePreflight.requireSpace(archive, File(filesDir, "rootfs")) + val extractionProgress = + ProgressPublisher(state, RootfsCheckpointStage.EXTRACTING, "Extracting the checkpoint") + RootfsCheckpointRestorer(this, ProotRuntimeInstaller.install(this)).restore( + archive = archive, + rootfsName = state.rootfsName, + operationId = state.operationId, + onExtractionProgress = extractionProgress::update, + onStage = { stage, detail -> publish(state.copy(stage = stage, detail = detail)) }, + ) + ProotMountResolver.removeRuntime(this, state.rootfsName) + LinuxApplicationShortcutPublisher(this).disableForRootfs(state.rootfsName) + notifyRootfsDocumentsChanged(this) + } finally { + partial.delete() + archive.delete() + } + } + + private inner class ProgressPublisher( + private val state: RootfsCheckpointState, + private val stage: RootfsCheckpointStage, + private val detail: String, + ) { + private var lastProgress = -1 + + fun update( + completedBytes: Long, + totalBytes: Long, + ) { + if (totalBytes <= 0L) return + val progress = ((completedBytes * 100L) / totalBytes).toInt().coerceIn(0, 99) + if (progress == lastProgress) return + lastProgress = progress + publish(state.copy(stage = stage, detail = detail, progress = progress)) + } + } + + private fun publish(state: RootfsCheckpointState) { + app.checkpointState.save(state) + updateNotification(state) + sendBroadcast( + Intent(ACTION_STATE_CHANGED) + .setPackage(packageName) + .putExtra(EXTRA_OPERATION_ID, state.operationId), + ) + } + + private fun createNotificationChannel() { + getSystemService(NotificationManager::class.java) + .createNotificationChannel( + NotificationChannel( + NOTIFICATION_CHANNEL, + "Linux backups", + NotificationManager.IMPORTANCE_LOW, + ).apply { + description = "Linux rootfs backup and restore operations" + }, + ) + } + + private fun notification(state: RootfsCheckpointState): Notification { + val openIntent = + PendingIntent.getActivity( + this, + 0, + Intent(this, MainActivity::class.java) + .setAction(ACTION_SHOW_CHECKPOINT) + .putExtra(EXTRA_ROOTFS_NAME, state.rootfsName), + PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, + ) + return NotificationCompat.Builder(this, NOTIFICATION_CHANNEL) + .setSmallIcon( + if (state.operation == RootfsCheckpointOperation.BACKUP) { + android.R.drawable.stat_sys_upload + } else { + android.R.drawable.stat_sys_download + }, + ).setContentTitle( + if (state.operation == RootfsCheckpointOperation.BACKUP) { + "Backing up ${state.rootfsName}" + } else { + "Restoring ${state.rootfsName}" + }, + ).setContentText(state.detail) + .setContentIntent(openIntent) + .setOngoing(state.stage.running) + .setOnlyAlertOnce(true) + .setPriority(NotificationCompat.PRIORITY_LOW) + .apply { + state.progress?.let { setProgress(100, it, false) } ?: setProgress(0, 0, true) + }.build() + } + + private fun updateNotification(state: RootfsCheckpointState) { + if ( + android.os.Build.VERSION.SDK_INT < 33 || + ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS) == + PackageManager.PERMISSION_GRANTED + ) { + getSystemService(NotificationManager::class.java) + .notify(NOTIFICATION_ID, notification(state)) + } + } + + companion object { + const val ACTION_STATE_CHANGED = "org.randomcoder.udroid.action.CHECKPOINT_STATE_CHANGED" + const val ACTION_SHOW_CHECKPOINT = "org.randomcoder.udroid.action.SHOW_CHECKPOINT" + const val EXTRA_ROOTFS_NAME = "org.randomcoder.udroid.extra.CHECKPOINT_ROOTFS_NAME" + + private const val ACTION_BACKUP = "org.randomcoder.udroid.action.BACKUP_ROOTFS" + private const val ACTION_RESTORE = "org.randomcoder.udroid.action.RESTORE_ROOTFS" + private const val EXTRA_OPERATION_ID = "org.randomcoder.udroid.extra.CHECKPOINT_OPERATION_ID" + private const val EXTRA_URI = "org.randomcoder.udroid.extra.CHECKPOINT_URI" + private const val NOTIFICATION_CHANNEL = "rootfs-checkpoints" + private const val NOTIFICATION_ID = 4405 + private const val COPY_BUFFER_BYTES = 64 * 1024 + + fun backup( + context: Context, + rootfsName: String, + destination: Uri, + ): String = start(context, ACTION_BACKUP, rootfsName, destination) + + fun restore( + context: Context, + rootfsName: String, + source: Uri, + ): String = start(context, ACTION_RESTORE, rootfsName, source) + + private fun start( + context: Context, + action: String, + rootfsName: String, + uri: Uri, + ): String { + val operationId = UUID.randomUUID().toString() + val stateStore = RootfsCheckpointStateStore(context) + check(stateStore.current()?.stage?.running != true) { + "Another rootfs backup or restore is already running" + } + val operation = + if (action == ACTION_BACKUP) { + RootfsCheckpointOperation.BACKUP + } else { + RootfsCheckpointOperation.RESTORE + } + val initial = + RootfsCheckpointState( + operationId = operationId, + rootfsName = rootfsName, + operation = operation, + stage = RootfsCheckpointStage.PREPARING, + detail = + if (operation == RootfsCheckpointOperation.BACKUP) { + "Preparing the rootfs backup" + } else { + "Preparing to restore the rootfs" + }, + documentUri = uri.toString(), + ) + stateStore.save(initial) + try { + ContextCompat.startForegroundService( + context, + Intent(context, RootfsCheckpointService::class.java) + .setAction(action) + .putExtra(EXTRA_ROOTFS_NAME, rootfsName) + .putExtra(EXTRA_OPERATION_ID, operationId) + .putExtra(EXTRA_URI, uri.toString()), + ) + } catch (error: Throwable) { + stateStore.save( + initial.copy( + stage = RootfsCheckpointStage.FAILED, + detail = error.message ?: "Could not start the checkpoint operation", + documentUri = null, + ), + ) + throw error + } + return operationId + } + } +} diff --git a/app/src/main/java/org/randomcoder/udroid/install/RootfsCheckpointState.kt b/app/src/main/java/org/randomcoder/udroid/install/RootfsCheckpointState.kt new file mode 100644 index 0000000..ca78786 --- /dev/null +++ b/app/src/main/java/org/randomcoder/udroid/install/RootfsCheckpointState.kt @@ -0,0 +1,91 @@ +package org.randomcoder.udroid.install + +import android.content.Context + +enum class RootfsCheckpointOperation { + BACKUP, + RESTORE, +} + +enum class RootfsCheckpointStage { + PREPARING, + COPYING, + ARCHIVING, + EXTRACTING, + CONFIGURING, + SWAPPING, + COMPLETE, + FAILED, + ; + + val running: Boolean + get() = this != COMPLETE && this != FAILED +} + +data class RootfsCheckpointState( + val operationId: String, + val rootfsName: String, + val operation: RootfsCheckpointOperation, + val stage: RootfsCheckpointStage, + val detail: String, + val progress: Int? = null, + val documentUri: String? = null, +) + +class RootfsCheckpointStateStore(context: Context) { + private val preferences = + context.applicationContext.getSharedPreferences(PREFERENCES_NAME, Context.MODE_PRIVATE) + + @Synchronized + fun current(): RootfsCheckpointState? { + val operationId = preferences.getString(KEY_OPERATION_ID, null) ?: return null + return runCatching { + RootfsCheckpointState( + operationId = operationId, + rootfsName = requireNotNull(preferences.getString(KEY_ROOTFS_NAME, null)), + operation = + RootfsCheckpointOperation.valueOf( + requireNotNull(preferences.getString(KEY_OPERATION, null)), + ), + stage = + RootfsCheckpointStage.valueOf( + requireNotNull(preferences.getString(KEY_STAGE, null)), + ), + detail = requireNotNull(preferences.getString(KEY_DETAIL, null)), + progress = preferences.getInt(KEY_PROGRESS, NO_PROGRESS).takeUnless { it == NO_PROGRESS }, + documentUri = preferences.getString(KEY_DOCUMENT_URI, null), + ) + }.getOrNull() + } + + @Synchronized + fun save(state: RootfsCheckpointState): RootfsCheckpointState { + check( + preferences + .edit() + .putString(KEY_OPERATION_ID, state.operationId) + .putString(KEY_ROOTFS_NAME, state.rootfsName) + .putString(KEY_OPERATION, state.operation.name) + .putString(KEY_STAGE, state.stage.name) + .putString(KEY_DETAIL, state.detail) + .putInt(KEY_PROGRESS, state.progress ?: NO_PROGRESS) + .putString(KEY_DOCUMENT_URI, state.documentUri) + .commit(), + ) { + "Failed to persist checkpoint state" + } + return state + } + + private companion object { + const val PREFERENCES_NAME = "rootfs-checkpoint-state" + const val KEY_OPERATION_ID = "operation-id" + const val KEY_ROOTFS_NAME = "rootfs-name" + const val KEY_OPERATION = "operation" + const val KEY_STAGE = "stage" + const val KEY_DETAIL = "detail" + const val KEY_PROGRESS = "progress" + const val KEY_DOCUMENT_URI = "document-uri" + const val NO_PROGRESS = -1 + } +} diff --git a/app/src/main/java/org/randomcoder/udroid/runtime/RuntimeSupervisorService.kt b/app/src/main/java/org/randomcoder/udroid/runtime/RuntimeSupervisorService.kt index 5cc4068..a11126b 100644 --- a/app/src/main/java/org/randomcoder/udroid/runtime/RuntimeSupervisorService.kt +++ b/app/src/main/java/org/randomcoder/udroid/runtime/RuntimeSupervisorService.kt @@ -258,6 +258,22 @@ class RuntimeSupervisorService : Service() { return when { action == ACTION_START_RUNTIME -> { val rootfsName = intent.getStringExtra(EXTRA_ROOTFS_NAME) + val checkpoint = app.checkpointState.current() + if ( + checkpoint?.stage?.running == true && + (rootfsName == null || checkpoint.rootfsName == rootfsName) + ) { + app.journal.append( + component = "supervisor", + severity = "warning", + event = "runtime_start_blocked", + message = "Linux cannot start while its rootfs backup or restore is running", + bootId = persisted.bootId, + fields = mapOf("installation" to checkpoint.rootfsName), + ) + stopSelf(startId) + return START_NOT_STICKY + } val configuration = effectiveAudioConfiguration(rootfsName, allowMicrophone = true) startRuntimeForeground("Starting Linux terminal…", configuration) startRuntime(rootfsName, configuration) diff --git a/app/src/main/java/org/randomcoder/udroid/ui/AppShell.kt b/app/src/main/java/org/randomcoder/udroid/ui/AppShell.kt index ce16778..5757443 100644 --- a/app/src/main/java/org/randomcoder/udroid/ui/AppShell.kt +++ b/app/src/main/java/org/randomcoder/udroid/ui/AppShell.kt @@ -233,6 +233,8 @@ fun UdroidApp( onOpenInstallation: (String) -> Unit, onOpenRootfsTerminal: (String) -> Unit, onOpenRootfsApps: (String) -> Unit, + onBackupRootfs: (String) -> Unit, + onRestoreRootfs: (String) -> Unit, onResetRootfs: (String, DistroVariant?) -> Unit, onCreateRootfsVariation: (String, DistroVariant?, ProotMountProfile) -> Unit, onDeleteRootfs: (String) -> Unit, @@ -459,6 +461,8 @@ fun UdroidApp( onOpenInstallation = onOpenInstallation, onOpenRootfsTerminal = onOpenRootfsTerminal, onOpenRootfsApps = onOpenRootfsApps, + onBackupRootfs = onBackupRootfs, + onRestoreRootfs = onRestoreRootfs, onSelectMountProfile = { systemId -> mountConfigurationSourceSystemId = systemId selectedMountProfileSystemId = null @@ -549,6 +553,8 @@ fun UdroidApp( onOpenInstallation = onOpenInstallation, onOpenRootfsTerminal = onOpenRootfsTerminal, onOpenRootfsApps = onOpenRootfsApps, + onBackupRootfs = onBackupRootfs, + onRestoreRootfs = onRestoreRootfs, onSelectMountProfile = { systemId -> mountConfigurationSourceSystemId = systemId selectedMountProfileSystemId = null @@ -655,6 +661,8 @@ private fun ManagementPane( onOpenInstallation: (String) -> Unit, onOpenRootfsTerminal: (String) -> Unit, onOpenRootfsApps: (String) -> Unit, + onBackupRootfs: (String) -> Unit, + onRestoreRootfs: (String) -> Unit, onSelectMountProfile: (String) -> Unit, onCreateMountProfile: () -> Unit, onEditMountProfile: (String) -> Unit, @@ -1037,6 +1045,12 @@ private fun ManagementPane( onConfigureEnvironment = { onDestinationSelected(UdroidDestination.ENVIRONMENT) }, + onBackupFilesystem = { + onBackupRootfs(selectedRootfs.name) + }, + onRestoreFilesystem = { + onRestoreRootfs(selectedRootfs.name) + }, onResetFilesystem = { onResetRootfs(selectedRootfs.name, selectedDistro) }, diff --git a/app/src/main/java/org/randomcoder/udroid/ui/LinuxSystemPage.kt b/app/src/main/java/org/randomcoder/udroid/ui/LinuxSystemPage.kt index f2862aa..0fbc0c1 100644 --- a/app/src/main/java/org/randomcoder/udroid/ui/LinuxSystemPage.kt +++ b/app/src/main/java/org/randomcoder/udroid/ui/LinuxSystemPage.kt @@ -19,12 +19,14 @@ import androidx.compose.foundation.shape.CircleShape import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.rounded.ArrowBack import androidx.compose.material.icons.rounded.Apps +import androidx.compose.material.icons.rounded.Backup import androidx.compose.material.icons.rounded.ChevronRight import androidx.compose.material.icons.rounded.Code import androidx.compose.material.icons.rounded.DeleteOutline import androidx.compose.material.icons.rounded.DesktopWindows import androidx.compose.material.icons.rounded.Refresh import androidx.compose.material.icons.rounded.RestartAlt +import androidx.compose.material.icons.rounded.Restore import androidx.compose.material.icons.rounded.Settings import androidx.compose.material.icons.rounded.Stop import androidx.compose.material.icons.rounded.Terminal @@ -120,6 +122,8 @@ fun LinuxSystemPage( onRestartDesktop: () -> Unit, onConfigureMounts: () -> Unit, onConfigureEnvironment: () -> Unit, + onBackupFilesystem: () -> Unit, + onRestoreFilesystem: () -> Unit, onResetFilesystem: () -> Unit, onDeleteFilesystem: () -> Unit, ) { @@ -577,12 +581,13 @@ fun LinuxSystemPage( maintenanceMessage ?: "Changing the Linux system…" rootfsInUse == null -> "Connecting to the Linux service…" runtimeBlocksMaintenance || desktopBlocksMaintenance -> - "Close this system’s terminals, apps and desktop before resetting or deleting it" + "Close this system’s terminals, apps and desktop before backing up, " + + "restoring, resetting or deleting it" !resetAvailable -> "Reset isn’t available because the original image source is missing. " + - "You can still delete this system." + "Backup, restore, and delete are still available." else -> - "Reset installs a fresh copy. Delete removes this Linux system." + "Backup exports the rootfs. Restore replaces it after validation." }, modifier = Modifier.padding(top = 4.dp), color = UdroidMuted, @@ -638,11 +643,32 @@ fun LinuxSystemPage( } } } else { + Row( + modifier = Modifier.fillMaxWidth().padding(top = 12.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp), + ) { + OutlinedButton( + modifier = Modifier.weight(1f), + enabled = maintenanceEnabled, + onClick = onBackupFilesystem, + ) { + Icon(Icons.Rounded.Backup, contentDescription = null) + Text("Backup", modifier = Modifier.padding(start = 6.dp)) + } + OutlinedButton( + modifier = Modifier.weight(1f), + enabled = maintenanceEnabled, + onClick = { confirmation = FilesystemConfirmation.RESTORE }, + ) { + Icon(Icons.Rounded.Restore, contentDescription = null) + Text("Restore", modifier = Modifier.padding(start = 6.dp)) + } + } Row( modifier = Modifier .fillMaxWidth() - .padding(top = 12.dp), + .padding(top = 8.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), ) { OutlinedButton( @@ -693,21 +719,25 @@ fun LinuxSystemPage( onDismissRequest = { confirmation = null }, title = { Text( - if (action == FilesystemConfirmation.RESET) { - "Reset this Linux system?" - } else { - "Delete this Linux system?" + when (action) { + FilesystemConfirmation.RESTORE -> "Restore this Linux system?" + FilesystemConfirmation.RESET -> "Reset this Linux system?" + FilesystemConfirmation.DELETE -> "Delete this Linux system?" }, ) }, text = { Text( - if (action == FilesystemConfirmation.RESET) { - "Reset permanently removes the packages, settings, and files you added. " + - "uDroid then installs a fresh copy of the original image." - } else { - "Delete permanently removes ${rootfs.name}, including its packages, " + - "settings, and files. You can’t undo this." + when (action) { + FilesystemConfirmation.RESTORE -> + "Restore replaces this rootfs with the selected backup after it passes " + + "a health check. The current mount profile is preserved." + FilesystemConfirmation.RESET -> + "Reset permanently removes the packages, settings, and files you added. " + + "uDroid then installs a fresh copy of the original image." + FilesystemConfirmation.DELETE -> + "Delete permanently removes ${rootfs.name}, including its packages, " + + "settings, and files. You can’t undo this." }, ) }, @@ -724,18 +754,18 @@ fun LinuxSystemPage( ), onClick = { confirmation = null - if (action == FilesystemConfirmation.RESET) { - onResetFilesystem() - } else { - onDeleteFilesystem() + when (action) { + FilesystemConfirmation.RESTORE -> onRestoreFilesystem() + FilesystemConfirmation.RESET -> onResetFilesystem() + FilesystemConfirmation.DELETE -> onDeleteFilesystem() } }, ) { Text( - if (action == FilesystemConfirmation.RESET) { - "Erase and reinstall" - } else { - "Delete permanently" + when (action) { + FilesystemConfirmation.RESTORE -> "Choose backup" + FilesystemConfirmation.RESET -> "Erase and reinstall" + FilesystemConfirmation.DELETE -> "Delete permanently" }, ) } @@ -825,6 +855,7 @@ private fun EnvironmentProfilePanel( } private enum class FilesystemConfirmation { + RESTORE, RESET, DELETE, } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index b316ba9..4f0c446 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -2,6 +2,7 @@ uDroid Downloads and verifies Linux images. + Creates and restores Linux filesystem backups. Downloads and verifies uDroid app updates. Keeps the Linux runtime and desktop process graph alive. diff --git a/app/src/test/java/org/randomcoder/udroid/install/ProotTarExtractorTest.kt b/app/src/test/java/org/randomcoder/udroid/install/ProotTarExtractorTest.kt index 415b099..988aa17 100644 --- a/app/src/test/java/org/randomcoder/udroid/install/ProotTarExtractorTest.kt +++ b/app/src/test/java/org/randomcoder/udroid/install/ProotTarExtractorTest.kt @@ -28,6 +28,8 @@ class ProotTarExtractorTest { assertTrue("Extraction bind $path must precede the guest command", bindIndex < guestCommandIndex) assertTrue("--exclude=${path.removePrefix("/")}" in arguments) } + assertTrue("--exclude=.udroid-ready" in arguments) + assertTrue("--exclude=.udroid-installing" in arguments) assertTrue( arguments.windowed(2).contains( listOf( diff --git a/app/src/test/java/org/randomcoder/udroid/install/RootfsCheckpointTest.kt b/app/src/test/java/org/randomcoder/udroid/install/RootfsCheckpointTest.kt new file mode 100644 index 0000000..6cf15be --- /dev/null +++ b/app/src/test/java/org/randomcoder/udroid/install/RootfsCheckpointTest.kt @@ -0,0 +1,107 @@ +package org.randomcoder.udroid.install + +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Test +import org.randomcoder.udroid.runtime.ANDROID_PROOT_BIND_MOUNTS +import java.io.File +import java.nio.file.Files + +class RootfsCheckpointTest { + @Test + fun `backup command excludes app markers and Android bind mounts`() { + val arguments = + RootfsCheckpointArchiver.buildArguments( + rootfsPath = "/data/user/0/org.randomcoder.udroid/files/rootfs/ubuntu", + tarExecutablePath = "/data/user/0/org.randomcoder.udroid/files/runtime/tar", + tarMountPath = "/.udroid-backup/tar", + ) + + assertTrue("--root-id" in arguments) + assertTrue("--one-file-system" in arguments) + assertTrue("--exclude=.udroid-ready" in arguments) + assertTrue("--exclude=.udroid-installing" in arguments) + assertTrue("--exclude=.udroid-backup" in arguments) + ANDROID_PROOT_BIND_MOUNTS.forEach { path -> + assertTrue("--exclude=${path.removePrefix("/")}" in arguments) + } + assertTrue( + arguments.windowed(2).contains( + listOf( + "-b", + "/data/user/0/org.randomcoder.udroid/files/runtime/tar:/.udroid-backup/tar", + ), + ), + ) + } + + @Test + fun `validated restore replaces the rootfs and removes rollback data`() { + val directory = Files.createTempDirectory("udroid-checkpoint-swap").toFile() + try { + val paths = RootfsCheckpointSwap.paths(directory, "ubuntu", OPERATION_ID) + ready(paths.current, "old") + ready(paths.staging, "new") + + RootfsCheckpointSwap.swapValidated(paths) + + assertTrue(File(paths.current, "new").isFile) + assertFalse(File(paths.current, "old").exists()) + assertFalse(paths.staging.exists()) + assertFalse(paths.previous.exists()) + } finally { + directory.deleteRecursively() + } + } + + @Test + fun `recovery finishes a validated swap after the current rootfs was moved`() { + val directory = Files.createTempDirectory("udroid-checkpoint-recover").toFile() + try { + val paths = RootfsCheckpointSwap.paths(directory, "ubuntu", OPERATION_ID) + ready(paths.current, "old") + ready(paths.staging, "new") + assertTrue(paths.current.renameTo(paths.previous)) + + RootfsCheckpointSwap.recover(paths) + + assertTrue(File(paths.current, "new").isFile) + assertFalse(paths.staging.exists()) + assertFalse(paths.previous.exists()) + } finally { + directory.deleteRecursively() + } + } + + @Test + fun `recovery discards an incomplete staging rootfs without touching current`() { + val directory = Files.createTempDirectory("udroid-checkpoint-partial").toFile() + try { + val paths = RootfsCheckpointSwap.paths(directory, "ubuntu", OPERATION_ID) + ready(paths.current, "old") + paths.staging.mkdirs() + File(paths.staging, "partial").writeText("incomplete") + + RootfsCheckpointSwap.recover(paths) + + assertTrue(File(paths.current, "old").isFile) + assertFalse(paths.staging.exists()) + assertFalse(paths.previous.exists()) + } finally { + directory.deleteRecursively() + } + } + + private fun ready( + rootfs: File, + content: String, + ) { + rootfs.mkdirs() + File(rootfs, RootfsInstallationPipeline.READY_MARKER).writeText("format=1\n") + File(rootfs, content).writeText(content) + } + + private companion object { + const val OPERATION_ID = "12345678-1234-1234-1234-123456789012" + } +}