SlideShare a Scribd company logo
Aayush Gupta
Writing OS Updater App for
Android
Agenda
OS updates & updater app
• Legacy system updates
• Seamless updates
• Writing an OS updater app
Legacy System Updates
Non-A/B devices
• Devices launched before Android
8.0 are known as non-A/B
devices
• Recovery handles the installation
of updates, while cache and
misc partitions store commands
and logs
Legacy system updates
boot
system
vendor
recovery
userdata
cache
misc
Legacy system updates (contd.)
• Device checks and downloads update (either in cache or userdata)
• Update’s signature is verified with system
• Device reboots into recovery mode while loading commands stored in cache
• Recovery (binary) verifies signature of update and installs it
• Device reboots, system updates recovery partition with new image if required
Issues with legacy system updates
• Updater app needs to handle storage space issues
• User is unable to use the device while updating
• After update, rebooting takes longer compared to normal boot
• On update failure, device is affected and user needs to visit service centre in
most cases
Seamless Updates
Seamless updates
A/B devices
• New way to update OS on device since Android 8.0+
• Ensures device has a working bootable system in case of update failure
• Updates are installed in background without affecting device usability
• Storage space issues can be avoided with streaming updates
• A/B system updates contains
two set of partitions for running
system
• Partitions are also known as
slots (slot_a, slot_b)
• System runs on current slot
while other slot remains unused
• Updates are installed by Updater
app in unused slot
Seamless updates (contd.)
userdata
boot_a
system_a
vendor_a
system_b
vendor_b
boot_b
• A/B updates uses a background
daemon called update_engine
• update_engine is responsible for
streaming/installing the update
• update_engine can either install
update from a local file or stream
it directly from remote server
• Once update is installed in unused
slot, update_engine marks it as
active
• System switches to active slot on
reboot
Seamless updates (contd.)
Writing an OS Updater App
• Exists in AOSP’s
bootable/recovery repository
• Showcases basic APIs usage
• Provides python script to
generate update config
• Not compatible with Gradle build
system
• Written in Java and last updated
4+ years ago
AOSP sample app
• Updater needs to connect with
remote server for downloading
and installing updates
• Periodic automatic updates
check and install is required
• Need to handle different kind of
errors
Real world use-case
• Written in Kotlin and Material3
• UI shows different elements
based on status code emitted in
a StateFlow
• Codes emitted in flow contains
both custom and update_engine
codes to accommodate
operations in different stages
CalyxOS’s SystemUpdater
Update stages
IDLE Checking for updates Update Available Preparing to update
Downloading
Verification & Finalising
Updated, needs reboot
Error
Suspended
Update status (API & App)
/**
* Possible status of the Update
*
* This enum holds a combination of both status supplied by update_engine and
* custom ones required for this app. Status from update_engine are followed by custom.
*/
// Keep in sync with: system/update_engine/client_library/include/update_engine/update_status.h
enum class UpdateStatus {
IDLE, // 0
CHECKING_FOR_UPDATE, // 1
UPDATE_AVAILABLE, // 2
DOWNLOADING, // 3
VERIFYING, // 4
FINALIZING, // 5
UPDATED_NEED_REBOOT, // 6
REPORTING_ERROR_EVENT, // 7
ATTEMPTING_ROLLBACK, // 8
DISABLED, // 9
NEED_PERMISSION_TO_UPDATE, // 10
CLEANUP_PREVIOUS_UPDATE, // 11
SUSPENDED, // custom: event when update is suspended
PREPARING_TO_UPDATE, // custom: event sent during payload verification, fetching props
FAILED_PREPARING_UPDATE // custom: event when payload verification or fetching props
fails
}
Listening callbacks (API)
/**
* Callback function for UpdateEngine. Used to keep the caller up to date
* with progress, so the UI (if any) can be updated.
*/
@SystemApi
public abstract class UpdateEngineCallback {
/**
* Invoked when anything changes. The value of {@code status} will
* be one of the values from {@link UpdateEngine.UpdateStatusConstants},
* and {@code percent} will be valid [TODO: in which cases?].
*/
public abstract void onStatusUpdate(int status, float percent);
/**
* Invoked when the payload has been applied, whether successfully or
* unsuccessfully. The value of {@code errorCode} will be one of the
* values from {@link UpdateEngine.ErrorCodeConstants}.
*/
public abstract void onPayloadApplicationComplete(
@UpdateEngine.ErrorCode int errorCode);
}
Listening callbacks (contd.)
init {
// restore last update status to properly reflect the status
restoreLastUpdate()
// handle status updates from update_engine
updateEngine.bind(this)
GlobalScope.launch {
updateStatus.onEach {
when (it) {
UpdateStatus.CHECKING_FOR_UPDATE -> {}
else -> {
sharedPreferences.edit(true) { putString(UPDATE_STATUS, it.name) }
}
}
}.collect()
updateProgress.collect()
}
}
Checking for updates
class UpdateWorker @AssistedInject constructor(
@Assisted val appContext: Context,
@Assisted workerParams: WorkerParameters,
) : CoroutineWorker(appContext, workerParams) {
companion object {
const val WORK_NAME = "UpdateWork"
}
override suspend fun doWork(): Result {
Intent(appContext, SystemUpdaterService::class.java).also {
it.action = SystemUpdaterService.CHECK_AND_APPLY_UPDATES
appContext.startService(it)
}
return Result.success()
}
}
Preparing to update (Verifying metadata)
metadataFile.createNewFile()
val connection = URL(url).openConnection() as HttpsURLConnection
// Request a specific range to avoid skipping through load of data
// Also do a [-1] to the range end to adjust the file size
connection.setRequestProperty(
"Range",
"bytes=${packageFile.offset}-${packageFile.offset + packageFile.size - 1}"
)
connection.inputStream.use { input ->
metadataFile.outputStream().use { input.copyTo(it) }
}
if (!updateEngine.verifyPayloadMetadata(metadataFile.absolutePath)) {
_updateStatus.value = UpdateStatus.FAILED_PREPARING_UPDATE
return@withContext Result.failure(Exception("Failed verifying metadata!"))
}
return@withContext Result.success(true)
Downloading
val propertiesFile = updateConfig.find { it.filename == payloadProperties }
val payloadFile = updateConfig.find { it.filename == payloadBinary }
if (propertiesFile != null && payloadFile != null) {
val properties = fetchPayloadProperties(updateConfig.url, propertiesFile)
if (properties.isSuccess) {
_updateStatus.value = UpdateStatus.DOWNLOADING
updateEngine.applyPayload(
updateConfig.url,
payloadFile.offset,
payloadFile.size,
properties.getOrDefault(emptyArray())
)
}
}
Suspending & resuming
fun suspendUpdate() {
updateEngine.suspend()
_updateStatus.value = UpdateStatus.SUSPENDED
}
fun resumeUpdate() {
restoreLastUpdate()
updateEngine.resume()
}
Errors
• Common errors that can occur are usually related to permissions
• Ensure the OS uses proper CA certificates
• Write SELinux rules for update_engine and app
• Verify metadata and other files have proper rw permissions
• Allow updater app to run in background for proper operations
Thank You!

More Related Content

Similar to Writing OS Updater App for Android

Steps for Upgrade OutSystems platform.pdf
Steps for Upgrade OutSystems platform.pdfSteps for Upgrade OutSystems platform.pdf
Steps for Upgrade OutSystems platform.pdf
RicardoPereira244364
 
Bring and distribute your dekstop applications on the Universal Windows Platf...
Bring and distribute your dekstop applications on the Universal Windows Platf...Bring and distribute your dekstop applications on the Universal Windows Platf...
Bring and distribute your dekstop applications on the Universal Windows Platf...
Matteo Pagani
 
Apache Cordova phonegap plugins for mobile app development
Apache Cordova phonegap plugins for mobile app developmentApache Cordova phonegap plugins for mobile app development
Apache Cordova phonegap plugins for mobile app development
webprogr.com
 
Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014
Lou Sacco
 
Browser_Stack_Intro
Browser_Stack_IntroBrowser_Stack_Intro
Browser_Stack_Intro
Mithilesh Singh
 
R12 d49656 gc10-apps dba 26
R12 d49656 gc10-apps dba 26R12 d49656 gc10-apps dba 26
R12 d49656 gc10-apps dba 26
zeesniper
 
Application engine
Application engineApplication engine
Application engine
JAYAARC
 
Xen mobile 8.5_migration_whitepaper
Xen mobile 8.5_migration_whitepaperXen mobile 8.5_migration_whitepaper
Xen mobile 8.5_migration_whitepaper
Nuno Alves
 
Wally Mead - Upgrading to system center 2012 r2 configuration manager
Wally Mead - Upgrading to system center 2012 r2 configuration managerWally Mead - Upgrading to system center 2012 r2 configuration manager
Wally Mead - Upgrading to system center 2012 r2 configuration manager
Nordic Infrastructure Conference
 
Odoo shipworks Integration
Odoo shipworks IntegrationOdoo shipworks Integration
Odoo shipworks Integration
Er. Jay Vora
 
Application slides
Application slidesApplication slides
Application slides
IBM Rational software
 
R12 d49656 gc10-apps dba 03
R12 d49656 gc10-apps dba 03R12 d49656 gc10-apps dba 03
R12 d49656 gc10-apps dba 03
zeesniper
 
UiPath_Orchestrtor_Upgrade_IAAS_PAAS.pptx
UiPath_Orchestrtor_Upgrade_IAAS_PAAS.pptxUiPath_Orchestrtor_Upgrade_IAAS_PAAS.pptx
UiPath_Orchestrtor_Upgrade_IAAS_PAAS.pptx
Rohit Radhakrishnan
 
Unit 4- State Machine in mobile programming
Unit 4- State Machine in mobile programmingUnit 4- State Machine in mobile programming
Unit 4- State Machine in mobile programming
LeahRachael
 
Parallelminds.asp.net with sp
Parallelminds.asp.net with spParallelminds.asp.net with sp
Parallelminds.asp.net with sp
parallelminder
 
R12 d49656 gc10-apps dba 16
R12 d49656 gc10-apps dba 16R12 d49656 gc10-apps dba 16
R12 d49656 gc10-apps dba 16
zeesniper
 
R12 d49656 gc10-apps dba 02
R12 d49656 gc10-apps dba 02R12 d49656 gc10-apps dba 02
R12 d49656 gc10-apps dba 02
zeesniper
 
Microsoft DevOps AZ-400 Real Dumps 2023
Microsoft DevOps AZ-400 Real Dumps 2023Microsoft DevOps AZ-400 Real Dumps 2023
Microsoft DevOps AZ-400 Real Dumps 2023
VictoriaMeisel
 
Remote Config REST API and Versioning
Remote Config REST API and VersioningRemote Config REST API and Versioning
Remote Config REST API and Versioning
Jumpei Matsuda
 
class based component.pptx
class based component.pptxclass based component.pptx
class based component.pptx
saikatsamanta49
 

Similar to Writing OS Updater App for Android (20)

Steps for Upgrade OutSystems platform.pdf
Steps for Upgrade OutSystems platform.pdfSteps for Upgrade OutSystems platform.pdf
Steps for Upgrade OutSystems platform.pdf
 
Bring and distribute your dekstop applications on the Universal Windows Platf...
Bring and distribute your dekstop applications on the Universal Windows Platf...Bring and distribute your dekstop applications on the Universal Windows Platf...
Bring and distribute your dekstop applications on the Universal Windows Platf...
 
Apache Cordova phonegap plugins for mobile app development
Apache Cordova phonegap plugins for mobile app developmentApache Cordova phonegap plugins for mobile app development
Apache Cordova phonegap plugins for mobile app development
 
Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014Meteor Meet-up San Diego December 2014
Meteor Meet-up San Diego December 2014
 
Browser_Stack_Intro
Browser_Stack_IntroBrowser_Stack_Intro
Browser_Stack_Intro
 
R12 d49656 gc10-apps dba 26
R12 d49656 gc10-apps dba 26R12 d49656 gc10-apps dba 26
R12 d49656 gc10-apps dba 26
 
Application engine
Application engineApplication engine
Application engine
 
Xen mobile 8.5_migration_whitepaper
Xen mobile 8.5_migration_whitepaperXen mobile 8.5_migration_whitepaper
Xen mobile 8.5_migration_whitepaper
 
Wally Mead - Upgrading to system center 2012 r2 configuration manager
Wally Mead - Upgrading to system center 2012 r2 configuration managerWally Mead - Upgrading to system center 2012 r2 configuration manager
Wally Mead - Upgrading to system center 2012 r2 configuration manager
 
Odoo shipworks Integration
Odoo shipworks IntegrationOdoo shipworks Integration
Odoo shipworks Integration
 
Application slides
Application slidesApplication slides
Application slides
 
R12 d49656 gc10-apps dba 03
R12 d49656 gc10-apps dba 03R12 d49656 gc10-apps dba 03
R12 d49656 gc10-apps dba 03
 
UiPath_Orchestrtor_Upgrade_IAAS_PAAS.pptx
UiPath_Orchestrtor_Upgrade_IAAS_PAAS.pptxUiPath_Orchestrtor_Upgrade_IAAS_PAAS.pptx
UiPath_Orchestrtor_Upgrade_IAAS_PAAS.pptx
 
Unit 4- State Machine in mobile programming
Unit 4- State Machine in mobile programmingUnit 4- State Machine in mobile programming
Unit 4- State Machine in mobile programming
 
Parallelminds.asp.net with sp
Parallelminds.asp.net with spParallelminds.asp.net with sp
Parallelminds.asp.net with sp
 
R12 d49656 gc10-apps dba 16
R12 d49656 gc10-apps dba 16R12 d49656 gc10-apps dba 16
R12 d49656 gc10-apps dba 16
 
R12 d49656 gc10-apps dba 02
R12 d49656 gc10-apps dba 02R12 d49656 gc10-apps dba 02
R12 d49656 gc10-apps dba 02
 
Microsoft DevOps AZ-400 Real Dumps 2023
Microsoft DevOps AZ-400 Real Dumps 2023Microsoft DevOps AZ-400 Real Dumps 2023
Microsoft DevOps AZ-400 Real Dumps 2023
 
Remote Config REST API and Versioning
Remote Config REST API and VersioningRemote Config REST API and Versioning
Remote Config REST API and Versioning
 
class based component.pptx
class based component.pptxclass based component.pptx
class based component.pptx
 

Recently uploaded

22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
KrishnaveniKrishnara1
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
bijceesjournal
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
LAXMAREDDY22
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
Roger Rozario
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
Prakhyath Rai
 
cnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classicationcnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classication
SakkaravarthiShanmug
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
IJECEIAES
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
171ticu
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
Divyanshu
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
Las Vegas Warehouse
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
PKavitha10
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
insn4465
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
gowrishankartb2005
 

Recently uploaded (20)

22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt22CYT12-Unit-V-E Waste and its Management.ppt
22CYT12-Unit-V-E Waste and its Management.ppt
 
Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...Comparative analysis between traditional aquaponics and reconstructed aquapon...
Comparative analysis between traditional aquaponics and reconstructed aquapon...
 
BRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdfBRAIN TUMOR DETECTION for seminar ppt.pdf
BRAIN TUMOR DETECTION for seminar ppt.pdf
 
Transformers design and coooling methods
Transformers design and coooling methodsTransformers design and coooling methods
Transformers design and coooling methods
 
Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...Software Engineering and Project Management - Introduction, Modeling Concepts...
Software Engineering and Project Management - Introduction, Modeling Concepts...
 
cnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classicationcnn.pptx Convolutional neural network used for image classication
cnn.pptx Convolutional neural network used for image classication
 
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
Redefining brain tumor segmentation: a cutting-edge convolutional neural netw...
 
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样学校原版美国波士顿大学毕业证学历学位证书原版一模一样
学校原版美国波士顿大学毕业证学历学位证书原版一模一样
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Null Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAMNull Bangalore | Pentesters Approach to AWS IAM
Null Bangalore | Pentesters Approach to AWS IAM
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1CEC 352 - SATELLITE COMMUNICATION UNIT 1
CEC 352 - SATELLITE COMMUNICATION UNIT 1
 
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
哪里办理(csu毕业证书)查尔斯特大学毕业证硕士学历原版一模一样
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
Material for memory and display system h
Material for memory and display system hMaterial for memory and display system h
Material for memory and display system h
 

Writing OS Updater App for Android

  • 1. Aayush Gupta Writing OS Updater App for Android
  • 2. Agenda OS updates & updater app • Legacy system updates • Seamless updates • Writing an OS updater app
  • 4. Non-A/B devices • Devices launched before Android 8.0 are known as non-A/B devices • Recovery handles the installation of updates, while cache and misc partitions store commands and logs Legacy system updates boot system vendor recovery userdata cache misc
  • 5. Legacy system updates (contd.) • Device checks and downloads update (either in cache or userdata) • Update’s signature is verified with system • Device reboots into recovery mode while loading commands stored in cache • Recovery (binary) verifies signature of update and installs it • Device reboots, system updates recovery partition with new image if required
  • 6. Issues with legacy system updates • Updater app needs to handle storage space issues • User is unable to use the device while updating • After update, rebooting takes longer compared to normal boot • On update failure, device is affected and user needs to visit service centre in most cases
  • 8. Seamless updates A/B devices • New way to update OS on device since Android 8.0+ • Ensures device has a working bootable system in case of update failure • Updates are installed in background without affecting device usability • Storage space issues can be avoided with streaming updates
  • 9. • A/B system updates contains two set of partitions for running system • Partitions are also known as slots (slot_a, slot_b) • System runs on current slot while other slot remains unused • Updates are installed by Updater app in unused slot Seamless updates (contd.) userdata boot_a system_a vendor_a system_b vendor_b boot_b
  • 10. • A/B updates uses a background daemon called update_engine • update_engine is responsible for streaming/installing the update • update_engine can either install update from a local file or stream it directly from remote server • Once update is installed in unused slot, update_engine marks it as active • System switches to active slot on reboot Seamless updates (contd.)
  • 11. Writing an OS Updater App
  • 12. • Exists in AOSP’s bootable/recovery repository • Showcases basic APIs usage • Provides python script to generate update config • Not compatible with Gradle build system • Written in Java and last updated 4+ years ago AOSP sample app
  • 13. • Updater needs to connect with remote server for downloading and installing updates • Periodic automatic updates check and install is required • Need to handle different kind of errors Real world use-case
  • 14. • Written in Kotlin and Material3 • UI shows different elements based on status code emitted in a StateFlow • Codes emitted in flow contains both custom and update_engine codes to accommodate operations in different stages CalyxOS’s SystemUpdater
  • 15. Update stages IDLE Checking for updates Update Available Preparing to update Downloading Verification & Finalising Updated, needs reboot Error Suspended
  • 16. Update status (API & App) /** * Possible status of the Update * * This enum holds a combination of both status supplied by update_engine and * custom ones required for this app. Status from update_engine are followed by custom. */ // Keep in sync with: system/update_engine/client_library/include/update_engine/update_status.h enum class UpdateStatus { IDLE, // 0 CHECKING_FOR_UPDATE, // 1 UPDATE_AVAILABLE, // 2 DOWNLOADING, // 3 VERIFYING, // 4 FINALIZING, // 5 UPDATED_NEED_REBOOT, // 6 REPORTING_ERROR_EVENT, // 7 ATTEMPTING_ROLLBACK, // 8 DISABLED, // 9 NEED_PERMISSION_TO_UPDATE, // 10 CLEANUP_PREVIOUS_UPDATE, // 11 SUSPENDED, // custom: event when update is suspended PREPARING_TO_UPDATE, // custom: event sent during payload verification, fetching props FAILED_PREPARING_UPDATE // custom: event when payload verification or fetching props fails }
  • 17. Listening callbacks (API) /** * Callback function for UpdateEngine. Used to keep the caller up to date * with progress, so the UI (if any) can be updated. */ @SystemApi public abstract class UpdateEngineCallback { /** * Invoked when anything changes. The value of {@code status} will * be one of the values from {@link UpdateEngine.UpdateStatusConstants}, * and {@code percent} will be valid [TODO: in which cases?]. */ public abstract void onStatusUpdate(int status, float percent); /** * Invoked when the payload has been applied, whether successfully or * unsuccessfully. The value of {@code errorCode} will be one of the * values from {@link UpdateEngine.ErrorCodeConstants}. */ public abstract void onPayloadApplicationComplete( @UpdateEngine.ErrorCode int errorCode); }
  • 18. Listening callbacks (contd.) init { // restore last update status to properly reflect the status restoreLastUpdate() // handle status updates from update_engine updateEngine.bind(this) GlobalScope.launch { updateStatus.onEach { when (it) { UpdateStatus.CHECKING_FOR_UPDATE -> {} else -> { sharedPreferences.edit(true) { putString(UPDATE_STATUS, it.name) } } } }.collect() updateProgress.collect() } }
  • 19. Checking for updates class UpdateWorker @AssistedInject constructor( @Assisted val appContext: Context, @Assisted workerParams: WorkerParameters, ) : CoroutineWorker(appContext, workerParams) { companion object { const val WORK_NAME = "UpdateWork" } override suspend fun doWork(): Result { Intent(appContext, SystemUpdaterService::class.java).also { it.action = SystemUpdaterService.CHECK_AND_APPLY_UPDATES appContext.startService(it) } return Result.success() } }
  • 20. Preparing to update (Verifying metadata) metadataFile.createNewFile() val connection = URL(url).openConnection() as HttpsURLConnection // Request a specific range to avoid skipping through load of data // Also do a [-1] to the range end to adjust the file size connection.setRequestProperty( "Range", "bytes=${packageFile.offset}-${packageFile.offset + packageFile.size - 1}" ) connection.inputStream.use { input -> metadataFile.outputStream().use { input.copyTo(it) } } if (!updateEngine.verifyPayloadMetadata(metadataFile.absolutePath)) { _updateStatus.value = UpdateStatus.FAILED_PREPARING_UPDATE return@withContext Result.failure(Exception("Failed verifying metadata!")) } return@withContext Result.success(true)
  • 21. Downloading val propertiesFile = updateConfig.find { it.filename == payloadProperties } val payloadFile = updateConfig.find { it.filename == payloadBinary } if (propertiesFile != null && payloadFile != null) { val properties = fetchPayloadProperties(updateConfig.url, propertiesFile) if (properties.isSuccess) { _updateStatus.value = UpdateStatus.DOWNLOADING updateEngine.applyPayload( updateConfig.url, payloadFile.offset, payloadFile.size, properties.getOrDefault(emptyArray()) ) } }
  • 22. Suspending & resuming fun suspendUpdate() { updateEngine.suspend() _updateStatus.value = UpdateStatus.SUSPENDED } fun resumeUpdate() { restoreLastUpdate() updateEngine.resume() }
  • 23. Errors • Common errors that can occur are usually related to permissions • Ensure the OS uses proper CA certificates • Write SELinux rules for update_engine and app • Verify metadata and other files have proper rw permissions • Allow updater app to run in background for proper operations