Skip to content
Draft
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
7 changes: 7 additions & 0 deletions app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,13 @@
android:foregroundServiceType="dataSync"
android:stopWithTask="false" />

<service
android:name=".install.RootfsCheckpointService"
android:description="@string/checkpoint_service_description"
android:exported="false"
android:foregroundServiceType="dataSync"
android:stopWithTask="false" />

<service
android:name=".update.AppUpdateDownloadService"
android:description="@string/update_service_description"
Expand Down
154 changes: 154 additions & 0 deletions app/src/main/java/org/randomcoder/udroid/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,9 @@ import org.randomcoder.udroid.install.InstallerService
import org.randomcoder.udroid.install.InstallerWorkRequest
import org.randomcoder.udroid.install.OciInstallationSelection
import org.randomcoder.udroid.install.ResetInstallationSelection
import org.randomcoder.udroid.install.RootfsCheckpointOperation
import org.randomcoder.udroid.install.RootfsCheckpointService
import org.randomcoder.udroid.install.RootfsCheckpointStage
import org.randomcoder.udroid.linuxapps.DesktopApplicationScanner
import org.randomcoder.udroid.linuxapps.LinuxApplication
import org.randomcoder.udroid.linuxapps.LinuxApplicationShortcutContract
Expand Down Expand Up @@ -87,6 +90,9 @@ import org.randomcoder.udroid.update.AppUpdatePhase
import org.randomcoder.udroid.update.AppUpdateScheduler
import org.randomcoder.udroid.update.AppUpdateState
import org.randomcoder.udroid.update.UpdateInstallResult
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.UUID

class MainActivity : ComponentActivity() {
Expand Down Expand Up @@ -116,6 +122,8 @@ class MainActivity : ComponentActivity() {
private var rootfsOccupiedBytes by mutableStateOf<Long?>(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<List<DesktopEnvironment>>(emptyList())
private var desktopConfiguration by
mutableStateOf(DesktopConfiguration(null, compositingEnabled = false, touchScaleEnabled = true))
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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)
},
Expand Down Expand Up @@ -343,6 +383,7 @@ class MainActivity : ComponentActivity() {
handleStopIntent(intent)
handleUpdateIntent(intent)
handleInstallerIntent(intent)
handleCheckpointIntent(intent)
if (!handleShortcutIntent(intent)) loadLinuxApplications()
handleDebugCommand()
}
Expand All @@ -353,6 +394,7 @@ class MainActivity : ComponentActivity() {
handleStopIntent(intent)
handleUpdateIntent(intent)
handleInstallerIntent(intent)
handleCheckpointIntent(intent)
handleShortcutIntent(intent)
handleDebugCommand()
}
Expand All @@ -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,
Expand Down Expand Up @@ -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 =
Expand Down Expand Up @@ -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?,
Expand Down Expand Up @@ -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 -> {
Expand Down
46 changes: 46 additions & 0 deletions app/src/main/java/org/randomcoder/udroid/UdroidApplication.kt
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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

Expand All @@ -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 ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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.*")
Expand Down
Loading
Loading