backup asset db

Signed-off-by: 尹耀德 <yinyaode1@huawei.com>
Change-Id: Id694a61ab979997d3f8ebc603d28443c8eebdde0
This commit is contained in:
尹耀德 2024-03-12 15:22:41 +08:00
parent 563d013c7e
commit 08354d0ac8
10 changed files with 84 additions and 25 deletions

View File

@ -15,7 +15,7 @@
//! This module defines asset-related data structures.
use std::collections::HashMap;
use std::{collections::HashMap, io};
mod extension;
#[macro_use]
@ -217,6 +217,15 @@ pub struct AssetError {
pub msg: String,
}
impl From<io::Error> for AssetError {
fn from(error: io::Error) -> Self {
AssetError {
code: (ErrCode::FileOperationError),
msg: (format!("[FATAL]Backup db failed! error is [{error}]"))
}
}
}
/// Alias of the Asset result type.
pub type Result<T> = std::result::Result<T, AssetError>;

View File

@ -67,3 +67,28 @@ pub fn delete_user_db_dir(user_id: i32) -> Result<()> {
},
}
}
fn fmt_db_path(dir_path: &str) -> String {
let mut bp = dir_path.to_string();
bp.push_str("/asset.db");
bp
}
fn fmt_backup_path(path: &str) -> String {
let mut bp = path.to_string();
bp.push_str(".backup");
bp
}
/// Backup all users db.
pub fn backup_all_db() -> Result<()> {
for entry in fs::read_dir(ROOT_PATH)? {
let entry = entry?;
if let Some(dir_path) = entry.path().to_str() {
let db_path = fmt_db_path(dir_path);
let backup_path = fmt_backup_path(db_path.as_str());
fs::copy(&db_path, backup_path)?;
}
}
Ok(())
}

View File

@ -24,7 +24,7 @@ use asset_db_operator::{
types::{column, DbMap},
};
use asset_definition::{Result, Value};
use asset_file_operator::delete_user_db_dir;
use asset_file_operator::{backup_all_db, delete_user_db_dir};
use asset_log::{loge, logi};
use crate::sys_event::upload_fault_system_event;
@ -80,17 +80,31 @@ extern "C" fn delete_crypto_need_unlock() {
crypto_manager.lock().unwrap().remove_need_device_unlocked();
}
extern "C" fn backup_db() {
let start_time = Instant::now();
match backup_all_db() {
Ok(_) => (),
Err(e) => {
// Report the file operator fault event.
let calling_info = CallingInfo::new_self();
upload_fault_system_event(&calling_info, start_time, "backup_db", &e);
},
}
}
extern "C" {
fn SubscribeSystemAbility(
onPackageRemoved: extern "C" fn(i32, *const u8, u32),
onUserRemoved: extern "C" fn(i32),
onScreenOff: extern "C" fn(),
onCharging: extern "C" fn(),
) -> bool;
fn UnSubscribeSystemAbility() -> bool;
fn SubscribeSystemEvent(
onPackageRemoved: extern "C" fn(i32, *const u8, u32),
onUserRemoved: extern "C" fn(i32),
onScreenOff: extern "C" fn(),
onCharging: extern "C" fn(),
) -> bool;
fn UnSubscribeSystemEvent() -> bool;
}
@ -98,13 +112,13 @@ extern "C" {
/// Subscribe to the add and remove events of system abilities.
pub(crate) fn subscribe() {
unsafe {
if SubscribeSystemEvent(delete_data_by_owner, delete_dir_by_user, delete_crypto_need_unlock) {
if SubscribeSystemEvent(delete_data_by_owner, delete_dir_by_user, delete_crypto_need_unlock, backup_db) {
logi!("Subscribe system event success.");
} else {
loge!("Subscribe system event failed.")
}
if SubscribeSystemAbility(delete_data_by_owner, delete_dir_by_user, delete_crypto_need_unlock) {
if SubscribeSystemAbility(delete_data_by_owner, delete_dir_by_user, delete_crypto_need_unlock, backup_db) {
logi!("Subscribe system ability success.");
} else {
loge!("Subscribe system ability failed.")

View File

@ -121,7 +121,6 @@ impl Database {
/// Open the database connection and recovery the database if the connection fails.
fn open_and_recovery(&mut self) -> Result<()> {
let result = self.open();
#[cfg(test)]
let result = match result {
Err(ret) if ret.code == ErrCode::DataCorrupted => self.recovery(),
ret => ret,
@ -138,7 +137,6 @@ impl Database {
}
// Recovery the corrupt database and reopen it.
#[cfg(test)]
pub(crate) fn recovery(&mut self) -> Result<()> {
loge!("[WARNING]Database is corrupt, start to recovery, path={}", self.path);
self.close();
@ -180,7 +178,6 @@ impl Database {
return log_throw_error!(ErrCode::FileOperationError, "[FATAL][DB]Delete database failed, err={}", e);
}
#[cfg(test)]
if let Err(e) = fs::remove_file(_backup_path) {
return log_throw_error!(
ErrCode::FileOperationError,
@ -232,7 +229,6 @@ impl Database {
pub(crate) fn execute_and_backup<T, F: Fn(&Table) -> Result<T>>(&mut self, _modified: bool, func: F) -> Result<T> {
let table = Table::new(TABLE_NAME, self);
let result = func(&table);
#[cfg(test)]
let result = match result {
Err(ret) if ret.code == ErrCode::DataCorrupted => {
self.recovery()?;
@ -241,11 +237,6 @@ impl Database {
},
ret => ret,
};
#[cfg(test)]
if result.is_ok() && _modified && fs::copy(&self.path, &self.backup_path).is_err() {
loge!("[WARNING]Backup database {} failed", self.backup_path);
}
result
}

View File

@ -22,7 +22,7 @@
extern "C" {
#endif
bool SubscribeSystemAbility(OnPackageRemoved onPackageRemoved, OnUserRemoved onUserRemoved, OnScreenOff onScreenOff);
bool SubscribeSystemAbility(OnPackageRemoved onPackageRemoved, OnUserRemoved onUserRemoved, OnScreenOff onScreenOff, OnCharging onCharging);
bool UnSubscribeSystemAbility(void);
#ifdef __cplusplus

View File

@ -21,12 +21,13 @@
typedef void (*OnPackageRemoved)(int32_t, const uint8_t *owner, uint32_t ownerSize);
typedef void (*OnUserRemoved)(int32_t);
typedef void (*OnScreenOff)(void);
typedef void (*OnCharging)(void);
#ifdef __cplusplus
extern "C" {
#endif
bool SubscribeSystemEvent(OnPackageRemoved onPackageRemoved, OnUserRemoved onUserRemoved, OnScreenOff onScreenOff);
bool SubscribeSystemEvent(OnPackageRemoved onPackageRemoved, OnUserRemoved onUserRemoved, OnScreenOff onScreenOff, OnCharging onCharging);
bool UnSubscribeSystemEvent(void);
#ifdef __cplusplus

View File

@ -31,8 +31,8 @@ const int32_t RETRY_DURATION_US = 200 * 1000;
class SystemAbilityHandler : public OHOS::SystemAbilityStatusChangeStub {
public:
SystemAbilityHandler(OnPackageRemoved onPackageRemoved, OnUserRemoved onUserRemoved, OnScreenOff onScreenOff)
: onPackageRemoved(onPackageRemoved), onUserRemoved(onUserRemoved), onScreenOff(onScreenOff) {};
SystemAbilityHandler(OnPackageRemoved onPackageRemoved, OnUserRemoved onUserRemoved, OnScreenOff onScreenOff, OnCharging onCharging)
: onPackageRemoved(onPackageRemoved), onUserRemoved(onUserRemoved), onScreenOff(onScreenOff), onCharging(onCharging) {};
~SystemAbilityHandler() = default;
void OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) override
{
@ -40,7 +40,7 @@ public:
return;
}
if (SubscribeSystemEvent(onPackageRemoved, onUserRemoved, onScreenOff)) {
if (SubscribeSystemEvent(onPackageRemoved, onUserRemoved, onScreenOff, onCharging)) {
LOGI("Subscribe system event success.");
} else {
LOGE("Subscribe system event failed.");
@ -61,6 +61,7 @@ private:
OnPackageRemoved onPackageRemoved;
OnUserRemoved onUserRemoved;
OnScreenOff onScreenOff;
OnCharging onCharging;
};
OHOS::sptr<OHOS::ISystemAbilityManager> GetSystemAbility(void)
@ -79,7 +80,7 @@ OHOS::sptr<OHOS::ISystemAbilityManager> GetSystemAbility(void)
OHOS::sptr<SystemAbilityHandler> abilityHandler;
} // namespace
bool SubscribeSystemAbility(OnPackageRemoved onPackageRemoved, OnUserRemoved onUserRemoved, OnScreenOff onScreenOff)
bool SubscribeSystemAbility(OnPackageRemoved onPackageRemoved, OnUserRemoved onUserRemoved, OnScreenOff onScreenOff, OnCharging onCharging)
{
OHOS::sptr<OHOS::ISystemAbilityManager> samgrProxy = GetSystemAbility();
if (samgrProxy == nullptr) {
@ -87,7 +88,7 @@ bool SubscribeSystemAbility(OnPackageRemoved onPackageRemoved, OnUserRemoved onU
return false;
}
abilityHandler = new (std::nothrow) SystemAbilityHandler(onPackageRemoved, onUserRemoved, onScreenOff);
abilityHandler = new (std::nothrow) SystemAbilityHandler(onPackageRemoved, onUserRemoved, onScreenOff, onCharging);
if (abilityHandler == nullptr) {
LOGE("Create system ability handler failed.");
return false;

View File

@ -52,11 +52,12 @@ void HandlePackageRemoved(const OHOS::AAFwk::Want &want, bool isSandBoxApp, OnPa
class SystemEventHandler : public CommonEventSubscriber {
public:
explicit SystemEventHandler(const CommonEventSubscribeInfo &subscribeInfo, OnPackageRemoved onPackageRemoved,
OnUserRemoved onUserRemoved, OnScreenOff onScreenOff): CommonEventSubscriber(subscribeInfo)
OnUserRemoved onUserRemoved, OnScreenOff onScreenOff, OnCharging onCharging): CommonEventSubscriber(subscribeInfo)
{
this->onPackageRemoved = onPackageRemoved;
this->onUserRemoved = onUserRemoved;
this->onScreenOff = onScreenOff;
this->onCharging = onCharging;
}
~SystemEventHandler() = default;
void OnReceiveEvent(const CommonEventData &data) override
@ -79,6 +80,11 @@ public:
this->onScreenOff();
}
LOGI("[INFO]Receive event: SCREEN_OFF, start_time: %{public}ld", startTime);
} else if (action == CommonEventSupport::COMMON_EVENT_CHARGING) {
if (this->onCharging != nullptr) {
this->onCharging();
}
LOGI("[INFO]Receive event: SCREEN_OFF, start_time: %{public}ld", startTime);
} else {
LOGW("[WARNING]Receive unknown event: %{public}s", action.c_str());
}
@ -87,22 +93,24 @@ private:
OnPackageRemoved onPackageRemoved;
OnUserRemoved onUserRemoved;
OnScreenOff onScreenOff;
OnCharging onCharging;
};
std::shared_ptr<SystemEventHandler> g_eventHandler = nullptr;
}
bool SubscribeSystemEvent(OnPackageRemoved onPackageRemoved, OnUserRemoved onUserRemoved, OnScreenOff onScreenOff)
bool SubscribeSystemEvent(OnPackageRemoved onPackageRemoved, OnUserRemoved onUserRemoved, OnScreenOff onScreenOff, OnCharging onCharging)
{
MatchingSkills matchingSkills;
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED);
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SANDBOX_PACKAGE_REMOVED);
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED);
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_OFF);
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_CHARGING);
CommonEventSubscribeInfo info(matchingSkills);
if (g_eventHandler == nullptr) {
g_eventHandler = std::shared_ptr<SystemEventHandler>(
new (std::nothrow) SystemEventHandler(info, onPackageRemoved, onUserRemoved, onScreenOff));
new (std::nothrow) SystemEventHandler(info, onPackageRemoved, onUserRemoved, onScreenOff, onCharging));
if (g_eventHandler == nullptr) {
LOGE("[FATAL]Asset system event handler is nullptr.");
return false;

View File

@ -62,6 +62,10 @@ void OnScreenOffCallback(void)
{
}
void OnChargingCallback(void)
{
}
/**
* @tc.name: AssetSystemAbilityWrapperTest.AssetSystemAbilityWrapperTest001
* @tc.desc: Test asset func SubscribeSystemEvent, expect ACCESS_TOKEN_ERROR
@ -73,7 +77,8 @@ HWTEST_F(AssetSystemAbilityWrapperTest, AssetSystemAbilityWrapperTest001, TestSi
OnPackageRemoved onPackageRemovedPtr = &PackageRemovedCallback;
OnUserRemoved onUserRemovedPtr = &OnUserRemovedCallback;
OnScreenOff onScreenOffPtr = &OnScreenOffCallback;
ASSERT_EQ(true, SubscribeSystemEvent(onPackageRemovedPtr, onUserRemovedPtr, onScreenOffPtr));
OnCharging onChargingPtr = &OnChargingCallback;
ASSERT_EQ(true, SubscribeSystemEvent(onPackageRemovedPtr, onUserRemovedPtr, onScreenOffPtr, onChargingPtr));
}
/**

View File

@ -61,6 +61,10 @@ void OnScreenOffCallback(void)
{
}
void OnChargingCallback(void)
{
}
/**
* @tc.name: AssetSystemEventWrapperTest.AssetSystemEventWrapperTest001
* @tc.desc: Test asset func SubscribeSystemEvent, expect ACCESS_TOKEN_ERROR
@ -72,7 +76,8 @@ HWTEST_F(AssetSystemEventWrapperTest, AssetSystemEventWrapperTest001, TestSize.L
OnPackageRemoved onPackageRemovedPtr = &PackageRemovedCallback;
OnUserRemoved onUserRemovedPtr = &OnUserRemovedCallback;
OnScreenOff onScreenOffPtr = &OnScreenOffCallback;
ASSERT_EQ(true, SubscribeSystemEvent(onPackageRemovedPtr, onUserRemovedPtr, onScreenOffPtr));
OnCharging onChargingPtr = &OnChargingCallback;
ASSERT_EQ(true, SubscribeSystemEvent(onPackageRemovedPtr, onUserRemovedPtr, onScreenOffPtr, onChargingPtr));
}
/**