From b4fa9b6ff5ef76ec69686448d03c7167d2f7d2ad Mon Sep 17 00:00:00 2001 From: libo429 Date: Sat, 7 Sep 2024 17:25:24 +0800 Subject: [PATCH] fix:backup files cannot be cleaned in abnormal scenarios Signed-off-by: libo429 --- .../native/backup_ext/include/ext_backup.h | 7 +- .../native/backup_ext/include/ext_extension.h | 3 + .../native/backup_ext/src/ext_backup.cpp | 17 +- .../native/backup_ext/src/ext_extension.cpp | 15 + .../backup_ext/src/sub_ext_extension.cpp | 1 - .../src/b_incremental_backup_session.cpp | 2 +- .../src/b_incremental_restore_session.cpp | 2 +- .../b_incremental_session_restore_async.cpp | 2 +- .../backup_kit_inner/src/b_session_backup.cpp | 2 +- .../src/b_session_restore.cpp | 2 +- .../src/b_session_restore_async.cpp | 2 +- .../backup_kit_inner/src/service_proxy.cpp | 6 + .../backup_kit_inner/impl/i_service_reverse.h | 1 + .../backup_kit_inner/impl/service_proxy.h | 1 + services/5203.json | 1 + .../backup_sa/include/module_ipc/service.h | 44 ++- .../include/module_ipc/svc_session_manager.h | 9 +- .../app_gallery_dispose_proxy.cpp | 8 + services/backup_sa/src/module_ipc/service.cpp | 362 ++++++++++++------ .../src/module_ipc/service_incremental.cpp | 59 ++- .../src/module_ipc/svc_session_manager.cpp | 50 ++- .../src/module_sched/sched_scheduler.cpp | 9 +- services/backupservice.para | 2 +- .../backup_kit_inner/service_proxy_mock.cpp | 5 + tests/mock/module_ipc/service_mock.cpp | 4 + .../module_ipc/svc_session_manager_mock.cpp | 11 +- .../svc_session_manager_throw_mock.cpp | 14 +- .../svc_session_manager_throw_mock.h | 12 +- .../module_ipc/service_throw_test.cpp | 98 ++--- .../backup_sa/session/service_proxy_mock.cpp | 5 + utils/BUILD.gn | 1 + .../include/b_json/b_json_clear_data_config.h | 86 +++++ utils/include/b_resources/b_constants.h | 1 + utils/src/b_json/b_json_clear_data_config.cpp | 356 +++++++++++++++++ 34 files changed, 919 insertions(+), 281 deletions(-) create mode 100644 utils/include/b_json/b_json_clear_data_config.h create mode 100644 utils/src/b_json/b_json_clear_data_config.cpp diff --git a/frameworks/native/backup_ext/include/ext_backup.h b/frameworks/native/backup_ext/include/ext_backup.h index aa41134c2..570bdac44 100644 --- a/frameworks/native/backup_ext/include/ext_backup.h +++ b/frameworks/native/backup_ext/include/ext_backup.h @@ -26,6 +26,7 @@ namespace OHOS::FileManagement::Backup { class ExtBackup; using CreatorFunc = std::function &runtime)>; +class BackupExtExtension; class ExtBackup : public AbilityRuntime::ExtensionBase { public: @@ -175,8 +176,6 @@ public: */ bool RestoreDataReady(); - void SetClearDataFlag(bool isClearData); - /** * @brief Invoke the extended function of the APP */ @@ -188,6 +187,8 @@ public: static void SetCreator(const CreatorFunc &creator); + void SetBackupExtExtension(const wptr &extExtension); + protected: std::string appVersionStr_; std::string restoreRetInfo_; @@ -202,7 +203,7 @@ private: BConstants::ExtensionAction extAction_ {BConstants::ExtensionAction::INVALID}; ErrCode GetParament(const AAFwk::Want &want); static CreatorFunc creator_; - bool isClearData_ {true}; + wptr bakExtExtension_; }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index 2c6808436..63da52beb 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -61,6 +61,9 @@ public: explicit BackupExtExtension(const std::shared_ptr &extension, const std::string &bundleName) : extension_(extension) { + if (extension_ != nullptr) { + extension_->SetBackupExtExtension(this); + } bundleName_ = bundleName; threadPool_.Start(BConstants::EXTENSION_THREAD_POOL_COUNT); } diff --git a/frameworks/native/backup_ext/src/ext_backup.cpp b/frameworks/native/backup_ext/src/ext_backup.cpp index af2cd18d8..2bef6b2d3 100644 --- a/frameworks/native/backup_ext/src/ext_backup.cpp +++ b/frameworks/native/backup_ext/src/ext_backup.cpp @@ -45,6 +45,11 @@ void ExtBackup::SetCreator(const CreatorFunc &creator) creator_ = creator; } +void ExtBackup::SetBackupExtExtension(const wptr &extExtension) +{ + bakExtExtension_ = extExtension; +} + void ExtBackup::Init(const shared_ptr &record, const shared_ptr &application, shared_ptr &handler, @@ -206,10 +211,9 @@ void ExtBackup::OnDisconnect(const AAFwk::Want &want) { try { HILOGI("begin disconnect"); - if (isClearData_) { - auto remoteObject = sptr( - new BackupExtExtension(std::static_pointer_cast(shared_from_this()), want.GetBundle())); - remoteObject->ExtClear(); + sptr extExtension = bakExtExtension_.promote(); + if (extExtension != nullptr) { + extExtension->ExtClear(); } Extension::OnDisconnect(want); extAction_ = BConstants::ExtensionAction::INVALID; @@ -253,11 +257,6 @@ bool ExtBackup::RestoreDataReady() return restoreType_ == RestoreTypeEnum::RESTORE_DATA_READDY; } -void ExtBackup::SetClearDataFlag(bool isClearData) -{ - isClearData_ = isClearData; -} - ErrCode ExtBackup::OnBackup(function callback) { HILOGI("BackupExtensionAbility(base) OnBackup."); diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index 3a058df56..4f5f7498a 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -66,6 +66,8 @@ const string INDEX_FILE_RESTORE = string(BConstants::PATH_BUNDLE_BACKUP_HOME). append(BConstants::EXT_BACKUP_MANAGE); const string INDEX_FILE_INCREMENTAL_BACKUP = string(BConstants::PATH_BUNDLE_BACKUP_HOME). append(BConstants::SA_BUNDLE_BACKUP_BACKUP); +const string MEDIA_LIBRARY_BUNDLE_NAME = "com.ohos.medialibrary.medialibrarydata"; +const string FILE_MANAGER_BUNDLE_NAME = "com.ohos.filepicker"; using namespace std; static string GetIndexFileRestorePath(const string &bundleName) @@ -1378,6 +1380,19 @@ void BackupExtExtension::DoClear() string(BConstants::PATH_BUNDLE_BACKUP_HOME_EL1).append(BConstants::SA_BUNDLE_BACKUP_BACKUP)); ForceRemoveDirectory( string(BConstants::PATH_BUNDLE_BACKUP_HOME_EL1).append(BConstants::SA_BUNDLE_BACKUP_RESTORE)); + // delete special directory + if (bundleName_.compare(MEDIA_LIBRARY_BUNDLE_NAME) == 0) { + ForceRemoveDirectory( + string(BConstants::PATH_MEDIALDATA_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP)); + ForceRemoveDirectory( + string(BConstants::PATH_MEDIALDATA_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE)); + } + if (bundleName_.compare(FILE_MANAGER_BUNDLE_NAME) == 0) { + ForceRemoveDirectory( + string(BConstants::PATH_FILEMANAGE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP)); + ForceRemoveDirectory( + string(BConstants::PATH_FILEMANAGE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE)); + } unique_lock lock(lock_); } catch (...) { HILOGE("Failed to clear"); diff --git a/frameworks/native/backup_ext/src/sub_ext_extension.cpp b/frameworks/native/backup_ext/src/sub_ext_extension.cpp index 1cabf6ce7..3f17e07bd 100644 --- a/frameworks/native/backup_ext/src/sub_ext_extension.cpp +++ b/frameworks/native/backup_ext/src/sub_ext_extension.cpp @@ -102,7 +102,6 @@ void BackupExtExtension::SetClearDataFlag(bool isClearData) HILOGE("Extension handle have been released"); return; } - extension_->SetClearDataFlag(isClearData); if (!extension_->WasFromSpecialVersion() && !extension_->RestoreDataReady()) { DoClear(); } diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp index 404dd88e8..cfaaf5ef5 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp @@ -30,7 +30,7 @@ BIncrementalBackupSession::~BIncrementalBackupSession() HILOGI("Death Recipient is nullptr"); return; } - auto proxy = ServiceProxy::GetInstance(); + auto proxy = ServiceProxy::GetServiceProxyPointer(); if (proxy == nullptr) { return; } diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp index 6ac805b80..ed51e8cb9 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp @@ -30,7 +30,7 @@ BIncrementalRestoreSession::~BIncrementalRestoreSession() HILOGI("Death Recipient is nullptr"); return; } - auto proxy = ServiceProxy::GetInstance(); + auto proxy = ServiceProxy::GetServiceProxyPointer(); if (proxy == nullptr) { return; } diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp index 4b064edce..75c7e3cbc 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp @@ -31,7 +31,7 @@ BIncrementalSessionRestoreAsync::~BIncrementalSessionRestoreAsync() HILOGE("Death Recipient is nullptr"); return; } - auto proxy = ServiceProxy::GetInstance(); + auto proxy = ServiceProxy::GetServiceProxyPointer(); if (proxy == nullptr) { return; } diff --git a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp index 1fadd8de2..f20285515 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp @@ -30,7 +30,7 @@ BSessionBackup::~BSessionBackup() HILOGI("Death Recipient is nullptr"); return; } - auto proxy = ServiceProxy::GetInstance(); + auto proxy = ServiceProxy::GetServiceProxyPointer(); if (proxy == nullptr) { return; } diff --git a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp index 7789277a7..0c37d2603 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp @@ -30,7 +30,7 @@ BSessionRestore::~BSessionRestore() HILOGI("Death Recipient is nullptr"); return; } - auto proxy = ServiceProxy::GetInstance(); + auto proxy = ServiceProxy::GetServiceProxyPointer(); if (proxy == nullptr) { return; } diff --git a/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp b/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp index 0510800d0..b3cea05e1 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp @@ -32,7 +32,7 @@ BSessionRestoreAsync::~BSessionRestoreAsync() HILOGI("Death Recipient is nullptr"); return; } - auto proxy = ServiceProxy::GetInstance(); + auto proxy = ServiceProxy::GetServiceProxyPointer(); if (proxy == nullptr) { return; } diff --git a/frameworks/native/backup_kit_inner/src/service_proxy.cpp b/frameworks/native/backup_kit_inner/src/service_proxy.cpp index 42e3a1d85..8d7be32ab 100644 --- a/frameworks/native/backup_kit_inner/src/service_proxy.cpp +++ b/frameworks/native/backup_kit_inner/src/service_proxy.cpp @@ -433,6 +433,12 @@ ErrCode ServiceProxy::Finish() return reply.ReadInt32(); } +sptr ServiceProxy::GetServiceProxyPointer() +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + return serviceProxy_; +} + sptr ServiceProxy::GetInstance() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h index 868361486..52311dde5 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h @@ -28,6 +28,7 @@ public: UNDEFINED, BACKUP, RESTORE, + CLEAN, }; public: diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h b/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h index 124033056..3afae9539 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h @@ -79,6 +79,7 @@ public: public: template bool WriteParcelableVector(const std::vector &parcelableVector, Parcel &data); + static sptr GetServiceProxyPointer(); static sptr GetInstance(); static void InvaildInstance(); diff --git a/services/5203.json b/services/5203.json index a38a55395..758a56c82 100644 --- a/services/5203.json +++ b/services/5203.json @@ -5,6 +5,7 @@ "name": 5203, "libpath": "libbackup_sa.z.so", "run-on-create": false, + "auto-restart": true, "distributed": false, "dump_level": 1, "start-on-demand": { diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index 7988b0fbe..bfbae637e 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -20,6 +20,7 @@ #include #include "b_jsonutil/b_jsonutil.h" +#include "b_json/b_json_clear_data_config.h" #include "b_json/b_json_entity_caps.h" #include "b_json/b_json_service_disposal_config.h" #include "i_service_reverse.h" @@ -177,12 +178,6 @@ public: */ void SessionDeactive(); - /** - * @brief 卸载服务 - * - */ - void UnloadService(); - /** * @brief 构造拉起应用所需的want * @@ -238,12 +233,37 @@ public: */ std::function TimeOutCallback(wptr ptr, std::string bundleName); + /** + * @brief 清理残留数据 + * + * @param bundleName 应用名称 + * + */ + void ClearResidualBundleData(const std::string &bundleName); + + /** + * @brief 添加清理记录 + * + * @param bundleName 应用名称 + * + */ + void AddClearBundleRecord(const std::string &bundleName); + + /** + * @brief 删除清理记录 + * + * @param bundleName 应用名称 + * + */ + void DelClearBundleRecord(const std::string &bundleName); + public: explicit Service(int32_t saID, bool runOnCreate = false) : SystemAbility(saID, runOnCreate) { threadPool_.Start(BConstants::EXTENSION_THREAD_POOL_COUNT); session_ = sptr(new SvcSessionManager(wptr(this))); disposal_ = make_shared(); + clearRecorder_ = make_shared(); }; ~Service() override { @@ -347,6 +367,8 @@ private: void SetCurrentSessProperties(std::vector &restoreBundleInfos, std::vector &restoreBundleNames, RestoreTypeEnum restoreType); + void SetCurrentSessProperties(BJsonEntityCaps::BundleInfo &info, std::map &isClearDataFlags); + /** * @brief 通知权限模块 * @@ -401,6 +423,13 @@ private: */ ErrCode GetBackupInfoCmdHandle(BundleName &bundleName, std::string &result); + /** + * @brief 添加需要清理的Session + * + * @param bundleNames 需要清理的应用包信息 + * + */ + ErrCode AppendBundlesClearSession(const std::vector &bundleNames); private: static sptr instance_; static std::mutex instanceLock_; @@ -408,11 +437,12 @@ private: std::condition_variable getBackupInfoCondition_; static inline std::atomic seed {1}; std::atomic isConnectDied_ {false}; - std::atomic isUnloadService_ {false}; + std::atomic isCleanService_ {false}; sptr session_; sptr sched_; std::shared_ptr disposal_; + std::shared_ptr clearRecorder_; friend class ServiceTest; diff --git a/services/backup_sa/include/module_ipc/svc_session_manager.h b/services/backup_sa/include/module_ipc/svc_session_manager.h index 676d2d205..8f6190a8a 100644 --- a/services/backup_sa/include/module_ipc/svc_session_manager.h +++ b/services/backup_sa/include/module_ipc/svc_session_manager.h @@ -107,7 +107,7 @@ public: * * @param impl 客户端信息 */ - ErrCode Active(Impl newImpl); + ErrCode Active(Impl newImpl, bool force = false); /** * @brief 关闭会话 @@ -437,20 +437,20 @@ public: * * @param sessionCnt */ - void IncreaseSessionCnt(); + void IncreaseSessionCnt(const std::string funcName); /** * @brief sessionCnt加计数 * * @param sessionCnt */ - void DecreaseSessionCnt(); + void DecreaseSessionCnt(const std::string funcName); /** * @brief clear session data * */ - void ClearSessionData(); + ErrCode ClearSessionData(); /** * @brief Get the Is Incremental Backup object @@ -569,7 +569,6 @@ private: uint32_t extConnectNum_ {0}; Utils::Timer timer_ {"backupTimer"}; std::atomic sessionCnt_ {0}; - bool unloadSAFlag_ {false}; int32_t memoryParaCurSize_ {BConstants::DEFAULT_VFS_CACHE_PRESSURE}; }; } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp b/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp index 877584be9..3dd80d2ac 100644 --- a/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp +++ b/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp @@ -75,12 +75,20 @@ DisposeErr AppGalleryDisposeProxy::EndBackup(const std::string &bundleName) DisposeErr AppGalleryDisposeProxy::StartRestore(const std::string &bundleName) { + if (SAUtils::IsSABundleName(bundleName)) { + HILOGI("SA does not need to StartRestore"); + return DisposeErr::OK; + } HILOGI("StartRestore, app %{public}s", bundleName.c_str()); return DoDispose(bundleName, DisposeOperation::START_RESTORE); } DisposeErr AppGalleryDisposeProxy::EndRestore(const std::string &bundleName) { + if (SAUtils::IsSABundleName(bundleName)) { + HILOGI("SA does not need to EndRestore"); + return DisposeErr::OK; + } HILOGI("EndRestore, app %{public}s", bundleName.c_str()); return DoDispose(bundleName, DisposeOperation::END_RESTORE); } diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 76ea9057b..1c9f06a63 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -76,6 +76,7 @@ namespace { constexpr int32_t DEBUG_ID = 100; constexpr int32_t INDEX = 3; constexpr int32_t MS_1000 = 1000; +constexpr int DEFAULT_FD_SEND_RATE = 60; const static string BROADCAST_TYPE = "broadcast"; const std::string FILE_BACKUP_EVENTS = "FILE_BACKUP_EVENTS"; const static string UNICAST_TYPE = "unicast"; @@ -105,17 +106,34 @@ void Service::OnStart() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("SA OnStart Begin."); - ClearDisposalOnSaStart(); + std::vector bundleNameList; + if (disposal_ != nullptr) { + bundleNameList = disposal_->GetBundleNameFromConfigFile(); + } + std::vector residualBundleNameList; + if (clearRecorder_ != nullptr) { + residualBundleNameList = clearRecorder_->GetAllClearBundleRecords(); + } + if (!bundleNameList.empty() || !residualBundleNameList.empty()) { + session_->Active( + { + .clientToken = IPCSkeleton::GetCallingTokenID(), + .scenario = IServiceReverse::Scenario::CLEAN, + .clientProxy = nullptr, + .userId = GetUserIdDefault(), + }, + true); + isCleanService_.store(true); + HILOGI("SA OnStart, cleaning up backup data"); + } bool res = SystemAbility::Publish(sptr(this)); sched_ = sptr(new SchedScheduler(wptr(this), wptr(session_))); sched_->StartTimer(); - string work_status = system::GetParameter(BACKUPSERVICE_WORK_STATUS_KEY, ""); - HILOGI("Param %{public}s value is %{public}s", BACKUPSERVICE_WORK_STATUS_KEY.c_str(), work_status.c_str()); - if (work_status.compare(BACKUPSERVICE_WORK_STATUS_ON) == 0) { - bool isSetSucc = system::SetParameter(BACKUPSERVICE_WORK_STATUS_KEY, BACKUPSERVICE_WORK_STATUS_OFF); - HILOGI("SetParameter %{public}s false end, result %{public}d.", BACKUPSERVICE_WORK_STATUS_KEY.c_str(), - isSetSucc); - sched_->TryUnloadService(); + ClearDisposalOnSaStart(); + auto ret = AppendBundlesClearSession(residualBundleNameList); + if (isCleanService_.load() && ret) { + isCleanService_.store(false); + StopAll(nullptr, true); } HILOGI("SA OnStart End, res = %{public}d", res); } @@ -129,13 +147,6 @@ void Service::OnStop() oldMemoryParaSize = session_->GetMemParaCurSize(); } StorageMgrAdapter::UpdateMemPara(oldMemoryParaSize); - string work_status = system::GetParameter(BACKUPSERVICE_WORK_STATUS_KEY, ""); - HILOGI("Param %{public}s value is %{public}s", BACKUPSERVICE_WORK_STATUS_KEY.c_str(), work_status.c_str()); - if (work_status.compare(BACKUPSERVICE_WORK_STATUS_ON) == 0) { - bool isSetSucc = system::SetParameter(BACKUPSERVICE_WORK_STATUS_KEY, BACKUPSERVICE_WORK_STATUS_OFF); - HILOGI("SetParameter %{public}s false end, result %{public}d.", BACKUPSERVICE_WORK_STATUS_KEY.c_str(), - isSetSucc); - } HILOGI("SA OnStop End."); } @@ -148,11 +159,11 @@ UniqueFd Service::GetLocalCapabilities() so there must be set init userId. */ HILOGI("Begin"); - if (session_ == nullptr) { + if (session_ == nullptr || isCleanService_.load()) { HILOGE("GetLocalCapabilities error, session is empty."); return UniqueFd(-EPERM); } - session_->IncreaseSessionCnt(); + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); session_->SetSessionUserId(GetUserIdDefault()); VerifyCaller(); string path = BConstants::GetSaBundleBackupRootDir(session_->GetSessionUserId()); @@ -160,7 +171,7 @@ UniqueFd Service::GetLocalCapabilities() UniqueFd fd(open(path.data(), O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR)); if (fd < 0) { HILOGE("Failed to open config file = %{private}s, err = %{public}d", path.c_str(), errno); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return UniqueFd(-EPERM); } BJsonCachedEntity cachedEntity(std::move(fd)); @@ -172,19 +183,19 @@ UniqueFd Service::GetLocalCapabilities() auto bundleInfos = BundleMgrAdapter::GetFullBundleInfos(session_->GetSessionUserId()); cache.SetBundleInfos(bundleInfos); cachedEntity.Persist(); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("End"); return move(cachedEntity.GetFd()); } catch (const BError &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("GetLocalCapabilities failed, errCode = %{public}d", e.GetCode()); return UniqueFd(-e.GetCode()); } catch (const exception &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); return UniqueFd(-EPERM); } catch (...) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return UniqueFd(-EPERM); } @@ -443,7 +454,11 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vectorIncreaseSessionCnt(); + if (session_ == nullptr || isCleanService_.load()) { + HILOGE("Init Incremental backup session error, session is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); if (userId != DEFAULT_INVAL_VALUE) { /* multi user scenario */ session_->SetSessionUserId(userId); } @@ -457,25 +472,25 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vectorDecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } session_->AppendBundles(restoreBundleNames); SetCurrentSessProperties(restoreInfos, restoreBundleNames, bundleNameDetailMap, isClearDataFlags, restoreType); OnStartSched(); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("End"); return BError(BError::Codes::OK); } catch (const BError &e) { HILOGE("Catch exception"); HandleExceptionOnAppendBundles(session_, bundleNames, {}); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return e.GetCode(); } catch (...) { HILOGE("Unexpected exception"); HandleExceptionOnAppendBundles(session_, bundleNames, {}); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return EPERM; } } @@ -514,7 +529,11 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { - session_->IncreaseSessionCnt(); + if (session_ == nullptr || isCleanService_.load()) { + HILOGE("Init Incremental backup session error, session is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); if (userId != DEFAULT_INVAL_VALUE) { /* multi user scenario */ session_->SetSessionUserId(userId); } @@ -523,24 +542,24 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, auto restoreBundleNames = SvcRestoreDepsManager::GetInstance().GetRestoreBundleNames(restoreInfos, restoreType); HandleExceptionOnAppendBundles(session_, bundleNames, restoreBundleNames); if (restoreBundleNames.empty()) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGW("RestoreBundleNames is empty."); return BError(BError::Codes::OK); } session_->AppendBundles(restoreBundleNames); SetCurrentSessProperties(restoreInfos, restoreBundleNames, restoreType); OnStartSched(); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (const BError &e) { HILOGE("Catch exception"); HandleExceptionOnAppendBundles(session_, bundleNames, {}); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return e.GetCode(); } catch (...) { HILOGE("Unexpected exception"); HandleExceptionOnAppendBundles(session_, bundleNames, {}); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return EPERM; } } @@ -598,11 +617,29 @@ void Service::SetCurrentSessProperties(std::vector HILOGI("End"); } +void Service::SetCurrentSessProperties(BJsonEntityCaps::BundleInfo &info, + std::map &isClearDataFlags) +{ + if (session_ == nullptr) { + return; + } + session_->SetBundleDataSize(info.name, info.spaceOccupied); + session_->SetBackupExtName(info.name, info.extensionName); + auto iter = isClearDataFlags.find(info.name); + if (iter != isClearDataFlags.end()) { + session_->SetClearDataFlag(info.name, iter->second); + } +} + ErrCode Service::AppendBundlesBackupSession(const vector &bundleNames) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { - session_->IncreaseSessionCnt(); // BundleMgrAdapter::GetBundleInfos可能耗时 + if (session_ == nullptr || isCleanService_.load()) { + HILOGE("Init Incremental backup session error, session is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 VerifyCaller(IServiceReverse::Scenario::BACKUP); auto backupInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session_->GetSessionUserId()); session_->AppendBundles(bundleNames); @@ -616,21 +653,21 @@ ErrCode Service::AppendBundlesBackupSession(const vector &bundleName } } OnStartSched(); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (const BError &e) { HandleExceptionOnAppendBundles(session_, bundleNames, {}); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("Failed, errCode = %{public}d", e.GetCode()); return e.GetCode(); } catch (const exception &e) { HandleExceptionOnAppendBundles(session_, bundleNames, {}); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); return EPERM; } catch (...) { HandleExceptionOnAppendBundles(session_, bundleNames, {}); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("Unexpected exception"); return EPERM; } @@ -641,7 +678,11 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { - session_->IncreaseSessionCnt(); // BundleMgrAdapter::GetBundleInfos可能耗时 + if (session_ == nullptr || isCleanService_.load()) { + HILOGE("Init Incremental backup session error, session is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 VerifyCaller(IServiceReverse::Scenario::BACKUP); std::vector bundleNamesOnly; std::map isClearDataFlags; @@ -651,12 +692,7 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun auto backupInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session_->GetSessionUserId()); session_->AppendBundles(bundleNames); for (auto info : backupInfos) { - session_->SetBundleDataSize(info.name, info.spaceOccupied); - session_->SetBackupExtName(info.name, info.extensionName); - auto iter = isClearDataFlags.find(info.name); - if (iter != isClearDataFlags.end()) { - session_->SetClearDataFlag(info.name, iter->second); - } + SetCurrentSessProperties(info, isClearDataFlags); if (info.allToBackup == false) { session_->GetServiceReverseProxy()->BackupOnBundleStarted( BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), info.name); @@ -669,22 +705,22 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun } } OnStartSched(); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (const BError &e) { HILOGE("Failed, errCode = %{public}d", e.GetCode()); HandleExceptionOnAppendBundles(session_, bundleNames, {}); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return e.GetCode(); } catch (const exception &e) { HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); HandleExceptionOnAppendBundles(session_, bundleNames, {}); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return EPERM; } catch(...) { HILOGE("Unexpected exception"); HandleExceptionOnAppendBundles(session_, bundleNames, {}); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return EPERM; } } @@ -812,9 +848,9 @@ ErrCode Service::AppDone(ErrCode errCode) proxy->HandleClear(); session_->StopFwkTimer(callerName); session_->StopExtTimer(callerName); - NotifyCallerCurAppDone(errCode, callerName); backUpConnection->DisconnectBackupExtAbility(); ClearSessionAndSchedInfo(callerName); + NotifyCallerCurAppDone(errCode, callerName); } OnAllBundlesFinished(BError(BError::Codes::OK)); return BError(BError::Codes::OK); @@ -925,7 +961,7 @@ ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) HILOGI("begin %{public}s", bundleName.data()); IServiceReverse::Scenario scenario = session_->GetScenario(); BConstants::ExtensionAction action; - if (scenario == IServiceReverse::Scenario::BACKUP) { + if (scenario == IServiceReverse::Scenario::BACKUP || scenario == IServiceReverse::Scenario::CLEAN) { action = BConstants::ExtensionAction::BACKUP; } else if (scenario == IServiceReverse::Scenario::RESTORE) { action = BConstants::ExtensionAction::RESTORE; @@ -1046,37 +1082,9 @@ void Service::OnBackupExtensionDied(const string &&bundleName) string callName = move(bundleName); HILOGE("Backup <%{public}s> Extension Process Died", callName.c_str()); session_->VerifyBundleName(callName); - string versionName = session_->GetBundleVersionName(bundleName); /* old device app version name */ - string versionNameFlag = - versionName.substr(0, versionName.find_first_of(BConstants::VERSION_NAME_SEPARATOR_CHAR)); - if (versionNameFlag == BConstants::DEFAULT_VERSION_NAME && - session_->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_READDY)) { - ExtConnectDied(bundleName); - return; - } // 重新连接清理缓存 - HILOGE("Clear backup extension data, bundleName: %{public}s", bundleName.data()); - auto backUpConnection = session_->GetExtConnection(bundleName); - auto callConnected = [ptr {wptr(this)}](const string &&bundleName) { - HILOGE("OnBackupExtensionDied callConnected <%{public}s>", bundleName.c_str()); - auto thisPtr = ptr.promote(); - if (!thisPtr) { - HILOGW("this pointer is null."); - return; - } - thisPtr->ExtConnectDied(bundleName); - }; - if (backUpConnection == nullptr) { - HILOGE("OnBackupExtensionDied error. backUpConnection is empty"); - ExtConnectDied(bundleName); - return; - } - backUpConnection->SetCallback(callConnected); - auto ret = LaunchBackupExtension(bundleName); - if (ret) { - ExtConnectDied(bundleName); - return; - } + HILOGI("Clear backup extension data, bundleName: %{public}s", callName.c_str()); + ExtConnectDied(callName); } catch (...) { HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str()); ExtConnectDied(bundleName); @@ -1096,8 +1104,12 @@ void Service::ExtConnectDied(const string &callName) if (backUpConnection != nullptr && backUpConnection->IsExtAbilityConnected()) { backUpConnection->DisconnectBackupExtAbility(); } - /* Clear Session before notice client finish event */ - ClearSessionAndSchedInfo(callName); + session_->SetServiceSchedAction(callName, BConstants::ServiceSchedAction::CLEAN); + auto ret = LaunchBackupExtension(callName); + if (ret) { + /* Clear Session before notice client finish event */ + ClearSessionAndSchedInfo(callName); + } /* Notice Client Ext Ability Process Died */ NoticeClientFinish(callName, BError(BError::Codes::EXT_ABILITY_DIED)); } catch (...) { @@ -1129,6 +1141,8 @@ void Service::ExtStart(const string &bundleName) if (!proxy) { throw BError(BError::Codes::SA_INVAL_ARG, "ExtStart bundle task error, Extension backup Proxy is empty"); } + std::string name = bundleName; + proxy->UpdateFdSendRate(name, DEFAULT_FD_SEND_RATE); if (scenario == IServiceReverse::Scenario::BACKUP) { auto ret = proxy->HandleBackup(session_->GetClearDataFlag(bundleName)); session_->GetServiceReverseProxy()->BackupOnBundleStarted(ret, bundleName); @@ -1253,7 +1267,19 @@ void Service::ExtConnectDone(string bundleName) } else if (scenario == IServiceReverse::Scenario::RESTORE) { session_->StartFwkTimer(bundleName, timeoutCallback); } - session_->SetServiceSchedAction(bundleName, BConstants::ServiceSchedAction::RUNNING); + + BConstants::ServiceSchedAction curSchedAction = session_->GetServiceSchedAction(bundleName); + if (curSchedAction == BConstants::ServiceSchedAction::CLEAN) { + sched_->Sched(bundleName); + return; + } + if (curSchedAction == BConstants::ServiceSchedAction::START && + clearRecorder_->FindClearBundleRecord(bundleName)) { + session_->SetServiceSchedAction(bundleName, BConstants::ServiceSchedAction::CLEAN); + } else { + session_->SetServiceSchedAction(bundleName, BConstants::ServiceSchedAction::RUNNING); + AddClearBundleRecord(bundleName); + } sched_->Sched(bundleName); } catch (...) { HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str()); @@ -1271,6 +1297,7 @@ void Service::ClearSessionAndSchedInfo(const string &bundleName) session_->RemoveExtInfo(bundleName); sched_->RemoveExtConn(bundleName); HandleRestoreDepsBundle(bundleName); + DelClearBundleRecord(bundleName); sched_->Sched(); } catch (const BError &e) { return; @@ -1360,17 +1387,14 @@ void Service::OnStartSched() void Service::SendStartAppGalleryNotify(const BundleName &bundleName) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + if (SAUtils::IsSABundleName(bundleName)) { + HILOGI("SA does not need to StartRestore"); + return ; + } IServiceReverse::Scenario scenario = session_->GetScenario(); if (scenario != IServiceReverse::Scenario::RESTORE) { return ; } - string work_status = system::GetParameter(BACKUPSERVICE_WORK_STATUS_KEY, ""); - HILOGI("Param %{public}s value is %{public}s", BACKUPSERVICE_WORK_STATUS_KEY.c_str(), work_status.c_str()); - if (work_status.compare(BACKUPSERVICE_WORK_STATUS_OFF) == 0) { - bool isSetSucc = system::SetParameter(BACKUPSERVICE_WORK_STATUS_KEY, BACKUPSERVICE_WORK_STATUS_ON); - HILOGI("SetParameter %{public}s true end, result %{public}d.", BACKUPSERVICE_WORK_STATUS_KEY.c_str(), - isSetSucc); - } if (!disposal_->IfBundleNameInDisposalConfigFile(bundleName)) { HILOGE("WriteDisposalConfigFile Failed"); return ; @@ -1384,6 +1408,10 @@ void Service::SendStartAppGalleryNotify(const BundleName &bundleName) void Service::SendEndAppGalleryNotify(const BundleName &bundleName) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + if (SAUtils::IsSABundleName(bundleName)) { + HILOGI("SA does not need to EndRestore"); + return ; + } IServiceReverse::Scenario scenario = session_->GetScenario(); if (scenario != IServiceReverse::Scenario::RESTORE) { return ; @@ -1423,6 +1451,10 @@ void Service::SendErrAppGalleryNotify() HILOGE("Error,disposal will be clear in the end"); return ; } + if (!disposal_->DeleteFromDisposalConfigFile(bundleName)) { + HILOGE("DeleteFromDisposalConfigFile Failed, bundleName=%{public}s", bundleName.c_str()); + return ; + } } } @@ -1436,6 +1468,14 @@ void Service::ClearDisposalOnSaStart() DisposeErr disposeErr = AppGalleryDisposeProxy::GetInstance()->EndRestore(bundleName); HILOGI("EndRestore, code=%{public}d, bundleName=%{public}s", disposeErr, bundleName.c_str()); + if (disposeErr != DisposeErr::OK) { + HILOGE("Error, disposal will be clear in the end"); + return ; + } + if (!disposal_->DeleteFromDisposalConfigFile(bundleName)) { + HILOGE("DeleteFromDisposalConfigFile Failed, bundleName=%{public}s", bundleName.c_str()); + return ; + } } } HILOGI("SA start, All Errdisposal pasitions have been cleared"); @@ -1458,18 +1498,6 @@ void Service::DeleteDisConfigFile() } } -void Service::UnloadService() -{ - if (sched_ == nullptr) { - HILOGE("Unload Service error, sched is empty"); - return; - } - if (!isUnloadService_.load()) { - isUnloadService_.store(true); - sched_->TryUnloadService(); - } -} - void Service::SessionDeactive() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); @@ -1489,7 +1517,10 @@ void Service::SessionDeactive() HILOGE("Session deactive error, session is empty"); return; } - session_->ClearSessionData(); + auto ret = session_->ClearSessionData(); + if (clearRecorder_ != nullptr && !ret) { + clearRecorder_->DeleteConfigFile(); + } // close session StopAll(nullptr, true); if (session_->GetSessionCnt() <= 0) { @@ -1529,6 +1560,36 @@ std::function Service::GetBackupInfoConnectDied(wptr }; } +void Service::ClearResidualBundleData(const std::string &bundleName) +{ + if (session_ == nullptr) { + return ; + } + auto backUpConnection = session_->GetExtConnection(bundleName); + if (backUpConnection == nullptr) { + throw BError(BError::Codes::SA_INVAL_ARG, "backUpConnection is empty"); + } + auto proxy = backUpConnection->GetBackupExtProxy(); + if (!proxy) { + throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + } + // 通知ext清理 + proxy->HandleClear(); + if (backUpConnection->IsExtAbilityConnected()) { + backUpConnection->DisconnectBackupExtAbility(); + } + ClearSessionAndSchedInfo(bundleName); + if (isCleanService_.load() && session_->IsOnAllBundlesFinished()) { + isCleanService_.store(false); + StopAll(nullptr, true); + return ; + } + // 非清理任务,需要上报 + if (session_->GetScenario() != IServiceReverse::Scenario::CLEAN) { + OnAllBundlesFinished(BError(BError::Codes::OK)); + } +} + ErrCode Service::GetBackupInfoCmdHandle(BundleName &bundleName, std::string &result) { if (session_ == nullptr) { @@ -1580,20 +1641,20 @@ ErrCode Service::GetBackupInfo(BundleName &bundleName, std::string &result) { try { HILOGI("Service::GetBackupInfo begin."); - if (session_ == nullptr) { + if (session_ == nullptr || isCleanService_.load()) { HILOGE("Get BackupInfo error, session is empty."); return BError(BError::Codes::SA_INVAL_ARG); } if (session_->GetImpl().clientToken) { return BError(BError::Codes::SA_REFUSED_ACT, "Already have an active session"); } - session_->IncreaseSessionCnt(); + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); auto ret = GetBackupInfoCmdHandle(bundleName, result); HILOGI("Service::GetBackupInfo end. result: %s", result.c_str()); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return ret; } catch (...) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return EPERM; } @@ -1609,15 +1670,15 @@ ErrCode Service::StartExtTimer(bool &isExtStart) isExtStart = false; return BError(BError::Codes::SA_INVAL_ARG); } - session_->IncreaseSessionCnt(); + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); auto timeoutCallback = TimeOutCallback(wptr(this), bundleName); session_->StopFwkTimer(bundleName); isExtStart = session_->StartExtTimer(bundleName, timeoutCallback); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (...) { isExtStart = false; - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return EPERM; } @@ -1633,20 +1694,55 @@ ErrCode Service::StartFwkTimer(bool &isFwkStart) isFwkStart = false; return BError(BError::Codes::SA_INVAL_ARG); } - session_->IncreaseSessionCnt(); + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); auto timeoutCallback = TimeOutCallback(wptr(this), bundleName); session_->StopExtTimer(bundleName); isFwkStart = session_->StartFwkTimer(bundleName, timeoutCallback); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (...) { isFwkStart = false; - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return EPERM; } } +ErrCode Service::AppendBundlesClearSession(const std::vector &bundleNames) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + try { + if (bundleNames.empty() || session_ == nullptr) { + HILOGE("Init Incremental backup session error, session is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 + auto backupInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session_->GetSessionUserId()); + session_->AppendBundles(bundleNames); + for (auto info : backupInfos) { + session_->SetBackupExtName(info.name, info.extensionName); + } + OnStartSched(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return BError(BError::Codes::OK); + } catch (const BError &e) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + HILOGE("Failed, errCode = %{public}d", e.GetCode()); + return e.GetCode(); + } catch (const exception &e) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); + return EPERM; + } catch (...) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + HILOGE("Unexpected exception"); + return EPERM; + } +} + ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) { auto timeoutCallback = [ptr {wptr(this)}, bundleName]() { @@ -1676,19 +1772,19 @@ ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &res }; try { HILOGI("Service::UpdateTimer begin."); - if (session_ == nullptr) { + if (session_ == nullptr || isCleanService_.load()) { HILOGE("Update Timer error, session is empty."); result = false; return BError(BError::Codes::SA_INVAL_ARG); } - session_->IncreaseSessionCnt(); + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); VerifyCaller(); result = session_->UpdateTimer(bundleName, timeOut, timeoutCallback); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (...) { result = false; - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return EPERM; } @@ -1698,18 +1794,18 @@ ErrCode Service::UpdateSendRate(std::string &bundleName, int32_t sendRate, bool { try { HILOGI("Begin, bundle name:%{public}s, sendRate is:%{public}d", bundleName.c_str(), sendRate); - if (session_ == nullptr) { + if (session_ == nullptr || isCleanService_.load()) { HILOGE("Update Send Rate error, session is empty."); result = false; return BError(BError::Codes::SA_INVAL_ARG); } - session_->IncreaseSessionCnt(); + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); VerifyCaller(); IServiceReverse::Scenario scenario = session_ -> GetScenario(); if (scenario != IServiceReverse::Scenario::BACKUP) { HILOGE("This method is applicable to the backup scenario"); result = false; - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::SA_INVAL_ARG); } auto backupConnection = session_->GetExtConnection(bundleName); @@ -1720,15 +1816,15 @@ ErrCode Service::UpdateSendRate(std::string &bundleName, int32_t sendRate, bool auto ret = proxy->UpdateFdSendRate(bundleName, sendRate); if (ret != NO_ERROR) { result = false; - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::EXT_BROKEN_IPC); } result = true; - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (...) { result = false; - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return EPERM; } @@ -1902,4 +1998,24 @@ std::function Service::TimeOutCallback(wptr ptr, std::string bu } }; } + +void Service::AddClearBundleRecord(const std::string &bundleName) +{ + // 添加清理记录 + if (!clearRecorder_->InsertClearBundleRecord(bundleName)) { + HILOGE("Failed to add clear bundle record, bundleName=%{public}s", bundleName.c_str()); + return; + } + HILOGI("Add clear bundle record OK, bundleName=%{public}s", bundleName.c_str()); +} + +void Service::DelClearBundleRecord(const std::string &bundleName) +{ + // 删除清理记录 + if (!clearRecorder_->DeleteClearBundleRecord(bundleName)) { + HILOGE("Failed to delete clear bundle record, bundleName=%{public}s", bundleName.c_str()); + return; + } + HILOGI("Delete clear bundle record OK, bundleName=%{public}s", bundleName.c_str()); +} } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/service_incremental.cpp b/services/backup_sa/src/module_ipc/service_incremental.cpp index deb63ff3c..7dcc1bd7b 100644 --- a/services/backup_sa/src/module_ipc/service_incremental.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental.cpp @@ -93,11 +93,11 @@ UniqueFd Service::GetLocalCapabilitiesIncremental(const std::vectorIncreaseSessionCnt(); + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); session_->SetSessionUserId(GetUserIdDefault()); VerifyCaller(); string path = BConstants::GetSaBundleBackupRootDir(session_->GetSessionUserId()); @@ -105,7 +105,7 @@ UniqueFd Service::GetLocalCapabilitiesIncremental(const std::vectorDecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return UniqueFd(-ENOENT); } BJsonCachedEntity cachedEntity(move(fd)); @@ -117,19 +117,19 @@ UniqueFd Service::GetLocalCapabilitiesIncremental(const std::vectorDecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("End, bundleInfos size:%{public}zu", bundleInfos.size()); return move(cachedEntity.GetFd()); } catch (const BError &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("GetLocalCapabilitiesIncremental failed, errCode = %{public}d", e.GetCode()); return UniqueFd(-e.GetCode()); } catch (const exception &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); return UniqueFd(-EPERM); } catch (...) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return UniqueFd(-EPERM); } @@ -181,11 +181,11 @@ ErrCode Service::GetAppLocalListAndDoIncrementalBackup() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { - if (session_ == nullptr) { + if (session_ == nullptr || isCleanService_.load()) { HILOGE("session is nullptr"); return BError(BError::Codes::SA_INVAL_ARG); } - session_->IncreaseSessionCnt(); + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); session_->SetSessionUserId(GetUserIdDefault()); std::string bundleName = VerifyCallerAndGetCallerName(); auto task = [this, bundleName]() { @@ -202,18 +202,18 @@ ErrCode Service::GetAppLocalListAndDoIncrementalBackup() HILOGI("Unexpected exception"); } }); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (const BError &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("GetAppLocalListAndDoIncrementalBackup failed, errCode = %{public}d", e.GetCode()); return e.GetCode(); } catch (const exception &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); return EPERM; } catch (...) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return EPERM; } @@ -243,11 +243,11 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vectorIncreaseSessionCnt(); // BundleMgrAdapter::GetBundleInfos可能耗时 + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 VerifyCaller(IServiceReverse::Scenario::BACKUP); vector bundleNames {}; for (auto &bundle : bundlesToBackup) { @@ -268,14 +268,14 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vectorSetIncrementalData(bundleInfo); } OnStartSched(); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (const BError &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("Failed, errCode = %{public}d", e.GetCode()); return e.GetCode(); } catch (...) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return EPERM; } @@ -286,7 +286,11 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vectorIncreaseSessionCnt(); // BundleMgrAdapter::GetBundleInfos可能耗时 + if (session_ == nullptr || isCleanService_.load()) { + HILOGE("Init Incremental backup session error, session is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 VerifyCaller(IServiceReverse::Scenario::BACKUP); vector bundleNames {}; for (auto &bundle : bundlesToBackup) { @@ -300,12 +304,7 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vectorGetSessionUserId()); session_->AppendBundles(bundleNames); for (auto info : backupInfos) { - session_->SetBundleDataSize(info.name, info.spaceOccupied); - session_->SetBackupExtName(info.name, info.extensionName); - auto iter = isClearDataFlags.find(info.name); - if (iter != isClearDataFlags.end()) { - session_->SetClearDataFlag(info.name, iter->second); - } + SetCurrentSessProperties(info, isClearDataFlags); if (info.allToBackup == false) { session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted( BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), info.name); @@ -321,14 +320,14 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vectorSetIncrementalData(bundleInfo); } OnStartSched(); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (const BError &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("Failed, errCode = %{public}d", e.GetCode()); return e.GetCode(); } catch (...) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return EPERM; } @@ -460,9 +459,9 @@ ErrCode Service::AppIncrementalDone(ErrCode errCode) proxy->HandleClear(); session_->StopFwkTimer(callerName); session_->StopExtTimer(callerName); - NotifyCallerCurAppIncrementDone(errCode, callerName); backUpConnection->DisconnectBackupExtAbility(); ClearSessionAndSchedInfo(callerName); + NotifyCallerCurAppIncrementDone(errCode, callerName); } OnAllBundlesFinished(BError(BError::Codes::OK)); return BError(BError::Codes::OK); diff --git a/services/backup_sa/src/module_ipc/svc_session_manager.cpp b/services/backup_sa/src/module_ipc/svc_session_manager.cpp index e8caf7d7c..8f1503319 100644 --- a/services/backup_sa/src/module_ipc/svc_session_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_session_manager.cpp @@ -69,7 +69,7 @@ int SvcSessionManager::GetSessionCnt() return sessionCnt_.load(); } -ErrCode SvcSessionManager::Active(Impl newImpl) +ErrCode SvcSessionManager::Active(Impl newImpl, bool force) { unique_lock lock(lock_); const Impl &oldImpl = impl_; @@ -78,39 +78,40 @@ ErrCode SvcSessionManager::Active(Impl newImpl) return BError(BError::Codes::SA_REFUSED_ACT); } - if (!newImpl.clientToken) { + if (!force && !newImpl.clientToken) { throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); } - if (newImpl.scenario == IServiceReverse::Scenario::UNDEFINED) { + if (!force && newImpl.scenario == IServiceReverse::Scenario::UNDEFINED) { throw BError(BError::Codes::SA_INVAL_ARG, "No scenario was specified"); } - InitClient(newImpl); + if (!force) { + InitClient(newImpl); + } impl_ = newImpl; - unloadSAFlag_ = false; + IncreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } void SvcSessionManager::Deactive(const wptr &remoteInAction, bool force) { unique_lock lock(lock_); - if (!impl_.clientToken || !impl_.clientProxy) { + if (!impl_.clientToken) { HILOGI("Empty session"); return; } if (!force && (!impl_.clientToken || !impl_.clientProxy)) { - throw BError(BError::Codes::SA_REFUSED_ACT, "Try to deactive an empty session"); + return; } - auto remoteHeldByProxy = impl_.clientProxy->AsObject(); - if (!force && (remoteInAction != remoteHeldByProxy)) { + if (!force && (remoteInAction != impl_.clientProxy->AsObject())) { throw BError(BError::Codes::SA_INVAL_ARG, "Only the client actived the session can deactive it"); } deathRecipient_ = nullptr; HILOGI("Succeed to deactive a session"); impl_ = {}; - unloadSAFlag_ = true; extConnectNum_ = 0; + DecreaseSessionCnt(__PRETTY_FUNCTION__); } void SvcSessionManager::VerifyBundleName(string &bundleName) @@ -826,33 +827,26 @@ bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t time return true; } -void SvcSessionManager::IncreaseSessionCnt() +void SvcSessionManager::IncreaseSessionCnt(const std::string funcName) { sessionCnt_++; + HILOGI("func name:%{public}s, %{public}d.", funcName.c_str(), sessionCnt_.load()); } -void SvcSessionManager::DecreaseSessionCnt() +void SvcSessionManager::DecreaseSessionCnt(const std::string funcName) { - unique_lock lock(lock_); if (sessionCnt_.load() > 0) { sessionCnt_--; } else { HILOGE("Invalid sessionCount."); - return; - } - if (reversePtr_ == nullptr) { - HILOGE("Service reverse pointer is empty."); - return; - } - if (sessionCnt_.load() <= 0 && unloadSAFlag_ == true) { - HILOGI("do unload Service."); - reversePtr_->UnloadService(); } + HILOGI("func name:%{public}s, %{public}d.", funcName.c_str(), sessionCnt_.load()); } -void SvcSessionManager::ClearSessionData() +ErrCode SvcSessionManager::ClearSessionData() { unique_lock lock(lock_); + ErrCode ret = BError(BError::Codes::OK); for (auto &&it : impl_.backupExtNameMap) { // clear timer if (it.second.fwkTimerStatus == true || it.second.extTimerStatus == true) { @@ -865,22 +859,26 @@ void SvcSessionManager::ClearSessionData() auto backUpConnection = it.second.backUpConnection; if (backUpConnection == nullptr) { HILOGE("Clear session error, backUpConnection is empty"); - return; + return BError(BError::Codes::SA_INVAL_ARG); } auto proxy = backUpConnection->GetBackupExtProxy(); if (proxy == nullptr) { HILOGE("Clear session error, proxy is empty"); - return; + return BError(BError::Codes::EXT_INVAL_ARG); } if (impl_.restoreDataType != RestoreTypeEnum::RESTORE_DATA_READDY) { - proxy->HandleClear(); + ret = proxy->HandleClear(); } backUpConnection->DisconnectBackupExtAbility(); } + if (ret != BError(BError::Codes::OK)) { + return ret; + } // clear data it.second.schedAction = BConstants::ServiceSchedAction::FINISH; } impl_.backupExtNameMap.clear(); + return BError(BError::Codes::OK); } bool SvcSessionManager::GetIsIncrementalBackup() diff --git a/services/backup_sa/src/module_sched/sched_scheduler.cpp b/services/backup_sa/src/module_sched/sched_scheduler.cpp index 20f7e530c..8d85731b3 100644 --- a/services/backup_sa/src/module_sched/sched_scheduler.cpp +++ b/services/backup_sa/src/module_sched/sched_scheduler.cpp @@ -116,6 +116,9 @@ void SchedScheduler::ExecutingQueueTasks(const string &bundleName) reversePtr_->SendStartAppGalleryNotify(bundleName); reversePtr_->ExtStart(bundleName); } + } else if (action == BConstants::ServiceSchedAction::CLEAN) { + HILOGI("Current bundle %{public}s process is cleaning", bundleName.data()); + reversePtr_->ClearResidualBundleData(bundleName); } } @@ -137,16 +140,14 @@ void SchedScheduler::RemoveExtConn(const string &bundleName) void SchedScheduler::StartTimer() { extTime_.Setup(); - if (!BackupPara().GetBackupOverrideBackupSARelease()) { - TryUnloadServiceTimer(); - } + TryUnloadServiceTimer(); } void SchedScheduler::TryUnloadServiceTimer(bool force) { auto tryUnload = [sessionPtr {sessionPtr_}]() { auto ptr = sessionPtr.promote(); - if (ptr && !ptr->NeedToUnloadService()) { + if (ptr && ptr->GetSessionCnt() > 0) { return; } HILOGI("Unload system ability"); diff --git a/services/backupservice.para b/services/backupservice.para index b2d857b67..f87a8b1a6 100644 --- a/services/backupservice.para +++ b/services/backupservice.para @@ -11,4 +11,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -persist.backupservice.workstatus=false \ No newline at end of file +persist.backupservice.workstatus=true \ No newline at end of file diff --git a/tests/mock/backup_kit_inner/service_proxy_mock.cpp b/tests/mock/backup_kit_inner/service_proxy_mock.cpp index e3f5d6560..b32e4d3c7 100644 --- a/tests/mock/backup_kit_inner/service_proxy_mock.cpp +++ b/tests/mock/backup_kit_inner/service_proxy_mock.cpp @@ -201,6 +201,11 @@ ErrCode ServiceProxy::ReportAppProcessInfo(const std::string processInfo, const return BError(BError::Codes::OK); } +sptr ServiceProxy::GetServiceProxyPointer() +{ + return serviceProxy_; +} + sptr ServiceProxy::GetInstance() { if (!GetMockGetInstance()) { diff --git a/tests/mock/module_ipc/service_mock.cpp b/tests/mock/module_ipc/service_mock.cpp index 7da582128..2dbfa662a 100644 --- a/tests/mock/module_ipc/service_mock.cpp +++ b/tests/mock/module_ipc/service_mock.cpp @@ -249,4 +249,8 @@ void Service::OnSABackup(const std::string &bundleName, } void Service::OnSARestore(const std::string &bundleName, const std::string &result, const ErrCode &errCode) {} + +void Service::ClearResidualBundleData(const std::string &bundleName) +{ +} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/svc_session_manager_mock.cpp b/tests/mock/module_ipc/svc_session_manager_mock.cpp index dcaf5e5ec..0d13c7cf9 100644 --- a/tests/mock/module_ipc/svc_session_manager_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_mock.cpp @@ -41,7 +41,7 @@ void SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceRe GTEST_LOG_(INFO) << "VerifyCallerAndScenario"; } -ErrCode SvcSessionManager::Active(Impl newImpl) +ErrCode SvcSessionManager::Active(Impl newImpl, bool force) { GTEST_LOG_(INFO) << "Active"; extConnectNum_ = 0; @@ -380,9 +380,9 @@ bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t time return true; } -void SvcSessionManager::IncreaseSessionCnt() {} +void SvcSessionManager::IncreaseSessionCnt(const std::string funcName) {} -void SvcSessionManager::DecreaseSessionCnt() {} +void SvcSessionManager::DecreaseSessionCnt(const std::string funcName) {} int32_t SvcSessionManager::GetMemParaCurSize() { @@ -391,7 +391,10 @@ int32_t SvcSessionManager::GetMemParaCurSize() void SvcSessionManager::SetMemParaCurSize(int32_t size) {} -void SvcSessionManager::ClearSessionData() {} +ErrCode SvcSessionManager::ClearSessionData() +{ + return 0; +} bool SvcSessionManager::GetIsIncrementalBackup() { diff --git a/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp b/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp index 6176f43dd..803c8aaef 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp @@ -24,7 +24,7 @@ void SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceRe BackupSvcSessionManager::session->VerifyCallerAndScenario(clientToken, scenario); } -ErrCode SvcSessionManager::Active(Impl newImpl) +ErrCode SvcSessionManager::Active(Impl newImpl, bool force) { return BackupSvcSessionManager::session->Active(newImpl); } @@ -245,14 +245,14 @@ bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t time return BackupSvcSessionManager::session->UpdateTimer(bundleName, timeOut, callback); } -void SvcSessionManager::IncreaseSessionCnt() +void SvcSessionManager::IncreaseSessionCnt(const std::string funcName) { - BackupSvcSessionManager::session->IncreaseSessionCnt(); + BackupSvcSessionManager::session->IncreaseSessionCnt(funcName); } -void SvcSessionManager::DecreaseSessionCnt() +void SvcSessionManager::DecreaseSessionCnt(const std::string funcName) { - BackupSvcSessionManager::session->DecreaseSessionCnt(); + BackupSvcSessionManager::session->DecreaseSessionCnt(funcName); } int32_t SvcSessionManager::GetMemParaCurSize() @@ -265,9 +265,9 @@ void SvcSessionManager::SetMemParaCurSize(int32_t size) BackupSvcSessionManager::session->SetMemParaCurSize(size); } -void SvcSessionManager::ClearSessionData() +ErrCode SvcSessionManager::ClearSessionData() { - BackupSvcSessionManager::session->ClearSessionData(); + return BackupSvcSessionManager::session->ClearSessionData(); } bool SvcSessionManager::GetIsIncrementalBackup() diff --git a/tests/mock/module_ipc/svc_session_manager_throw_mock.h b/tests/mock/module_ipc/svc_session_manager_throw_mock.h index a916d7c6a..2185cec60 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.h +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.h @@ -72,11 +72,11 @@ public: virtual bool StartExtTimer(const std::string &, const Utils::Timer::TimerCallback &) = 0; virtual bool StopExtTimer(const std::string &) = 0; virtual bool UpdateTimer(const std::string &, uint32_t, const Utils::Timer::TimerCallback &) = 0; - virtual void IncreaseSessionCnt() = 0; - virtual void DecreaseSessionCnt() = 0; + virtual void IncreaseSessionCnt(const std::string) = 0; + virtual void DecreaseSessionCnt(const std::string) = 0; virtual int32_t GetMemParaCurSize() = 0; virtual void SetMemParaCurSize(int32_t) = 0; - virtual void ClearSessionData() = 0; + virtual ErrCode ClearSessionData() = 0; virtual bool GetIsIncrementalBackup() = 0; virtual bool ValidRestoreDataType(RestoreTypeEnum) = 0; virtual SvcSessionManager::Impl GetImpl() = 0; @@ -137,11 +137,11 @@ public: MOCK_METHOD(bool, StartExtTimer, (const std::string &, const Utils::Timer::TimerCallback &)); MOCK_METHOD(bool, StopExtTimer, (const std::string &)); MOCK_METHOD(bool, UpdateTimer, (const std::string &, uint32_t, const Utils::Timer::TimerCallback &)); - MOCK_METHOD(void, IncreaseSessionCnt, ()); - MOCK_METHOD(void, DecreaseSessionCnt, ()); + MOCK_METHOD(void, IncreaseSessionCnt, (const std::string)); + MOCK_METHOD(void, DecreaseSessionCnt, (const std::string)); MOCK_METHOD(int32_t, GetMemParaCurSize, ()); MOCK_METHOD(void, SetMemParaCurSize, (int32_t)); - MOCK_METHOD(void, ClearSessionData, ()); + MOCK_METHOD(ErrCode, ClearSessionData, ()); MOCK_METHOD(bool, GetIsIncrementalBackup, ()); MOCK_METHOD(bool, ValidRestoreDataType, (RestoreTypeEnum)); MOCK_METHOD(SvcSessionManager::Impl, GetImpl, ()); diff --git a/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp b/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp index e6f98a924..daac79e01 100644 --- a/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp @@ -67,24 +67,24 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_GetLocalCapabilities_0100, testing: GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_GetLocalCapabilities_0100"; try { EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->GetLocalCapabilities(); EXPECT_EQ(-ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw runtime_error("运行时错误"); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->GetLocalCapabilities(); EXPECT_EQ(-ret, EPERM); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->GetLocalCapabilities(); EXPECT_EQ(-ret, EPERM); } catch (...) { @@ -177,17 +177,17 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppendBundlesRestoreSession_0100, t GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_AppendBundlesRestoreSession_0100"; try { EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->AppendBundlesRestoreSession(UniqueFd(-1), {}, {}, RESTORE_DATA_WAIT_SEND, 0); EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesRestoreSession(UniqueFd(-1), {}, {}, RESTORE_DATA_WAIT_SEND, 0); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -211,17 +211,17 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppendBundlesRestoreSession_0200, t GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_AppendBundlesRestoreSession_0200"; try { EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->AppendBundlesRestoreSession(UniqueFd(-1), {}, RESTORE_DATA_WAIT_SEND, 0); EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesRestoreSession(UniqueFd(-1), {}, RESTORE_DATA_WAIT_SEND, 0); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -245,24 +245,24 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppendBundlesBackupSession_0100, te GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_AppendBundlesBackupSession_0100"; try { EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->AppendBundlesBackupSession({}); EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw runtime_error("运行时错误"); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesBackupSession({}); EXPECT_EQ(ret, EPERM); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesBackupSession({}); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -286,24 +286,24 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppendBundlesDetailsBackupSession_0 GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_AppendBundlesDetailsBackupSession_0100"; try { EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->AppendBundlesDetailsBackupSession({}, {}); EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw runtime_error("运行时错误"); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesDetailsBackupSession({}, {}); EXPECT_EQ(ret, EPERM); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesDetailsBackupSession({}, {}); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -715,7 +715,7 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_GetBackupInfo_0100, testing::ext::T throw "未知错误"; return SvcSessionManager::Impl(); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->GetBackupInfo(bundleName, result); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -741,10 +741,10 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_UpdateTimer_0100, testing::ext::Tes EXPECT_NE(service, nullptr); BundleName bundleName; bool result = false; - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->UpdateTimer(bundleName, 0, result); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -812,24 +812,24 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_GetLocalCapabilitiesIncremental_010 try { EXPECT_NE(service, nullptr); vector bundleNames; - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->GetLocalCapabilitiesIncremental(bundleNames); EXPECT_EQ(-ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw runtime_error("运行时错误"); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->GetLocalCapabilitiesIncremental(bundleNames); EXPECT_EQ(-ret, EPERM); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->GetLocalCapabilitiesIncremental(bundleNames); EXPECT_EQ(-ret, EPERM); } catch (...) { @@ -853,24 +853,24 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_GetAppLocalListAndDoIncrementalBack GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_GetAppLocalListAndDoIncrementalBackup_0100"; try { EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->GetAppLocalListAndDoIncrementalBackup(); EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw runtime_error("运行时错误"); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->GetAppLocalListAndDoIncrementalBackup(); EXPECT_EQ(ret, EPERM); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->GetAppLocalListAndDoIncrementalBackup(); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -923,17 +923,17 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppendBundlesIncrementalBackupSessi try { EXPECT_NE(service, nullptr); vector bundlesToBackup; - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->AppendBundlesIncrementalBackupSession(bundlesToBackup); EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesIncrementalBackupSession(bundlesToBackup); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -959,17 +959,17 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppendBundlesIncrementalBackupSessi EXPECT_NE(service, nullptr); vector bundlesToBackup; vector infos; - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->AppendBundlesIncrementalBackupSession(bundlesToBackup, infos); EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesIncrementalBackupSession(bundlesToBackup, infos); EXPECT_EQ(ret, EPERM); } catch (...) { diff --git a/tests/unittests/backup_sa/session/service_proxy_mock.cpp b/tests/unittests/backup_sa/session/service_proxy_mock.cpp index 22c1556bf..d7bb5f63e 100644 --- a/tests/unittests/backup_sa/session/service_proxy_mock.cpp +++ b/tests/unittests/backup_sa/session/service_proxy_mock.cpp @@ -182,6 +182,11 @@ ErrCode ServiceProxy::ReportAppProcessInfo(const std::string processInfo, const return BError(BError::Codes::OK); } +sptr ServiceProxy::GetServiceProxyPointer() +{ + return serviceProxy_; +} + sptr ServiceProxy::GetInstance() { return serviceProxy_; diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 90126bd99..bb735177f 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -65,6 +65,7 @@ ohos_shared_library("backup_utils") { "src/b_filesystem/b_dir.cpp", "src/b_filesystem/b_file.cpp", "src/b_filesystem/b_file_hash.cpp", + "src/b_json/b_json_clear_data_config.cpp", "src/b_json/b_json_entity_ext_manage.cpp", "src/b_json/b_json_entity_extension_config.cpp", "src/b_json/b_json_service_disposal_config.cpp", diff --git a/utils/include/b_json/b_json_clear_data_config.h b/utils/include/b_json/b_json_clear_data_config.h new file mode 100644 index 000000000..1f60863fc --- /dev/null +++ b/utils/include/b_json/b_json_clear_data_config.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_BACKUP_B_JSON_CLEAR_DATA_CONFIG_H +#define OHOS_FILEMGMT_BACKUP_B_JSON_CLEAR_DATA_CONFIG_H + +#include +#include +#include + +namespace OHOS::FileManagement::Backup { +class BJsonClearDataConfig { +public: + /** + * @brief 判断配置文件中是否有记录 + * + */ + bool HasClearBundleRecord(); + + /** + * @brief 判断配置文件中是否存在bundleName记录 + * + * @param bundlename + */ + bool FindClearBundleRecord(const std::string& bundleName); + + /** + * @brief 配置文件中插入bundleName记录 + * + * @param bundlename + */ + bool InsertClearBundleRecord(const std::string& bundleName); + + /** + * @brief 配置文件中删除bundleName记录 + * + * @param bundlename + */ + bool DeleteClearBundleRecord(const std::string& bundleName); + + /** + * @brief 配置文件中获取bundlename + * + */ + std::vector GetAllClearBundleRecords(); + + /** + * @brief 删除配置文件 + * + * + */ + bool DeleteConfigFile(); + +public: + /** + * @brief 构造方法 + * + * + */ + BJsonClearDataConfig(); +private: + /** + * @brief 配置文件中删除bundleName记录 + * + * @param bundlename + */ + bool WriteClearBundleRecord(const std::string& bundleName); + +private: + std::mutex fileMutex_; +}; + +} // namespace OHOS::FileManagement::Backup +#endif // OHOS_FILEMGMT_BACKUP_B_JSON_CLEAR_DATA_CONFIG_H \ No newline at end of file diff --git a/utils/include/b_resources/b_constants.h b/utils/include/b_resources/b_constants.h index f50e544dd..abb3dde22 100644 --- a/utils/include/b_resources/b_constants.h +++ b/utils/include/b_resources/b_constants.h @@ -43,6 +43,7 @@ enum ServiceSchedAction { START = 1, RUNNING = 2, FINISH = 3, + CLEAN = 4, }; constexpr int SPAN_USERID_UID = 200000; diff --git a/utils/src/b_json/b_json_clear_data_config.cpp b/utils/src/b_json/b_json_clear_data_config.cpp new file mode 100644 index 000000000..8210c1397 --- /dev/null +++ b/utils/src/b_json/b_json_clear_data_config.cpp @@ -0,0 +1,356 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "b_json/b_json_clear_data_config.h" + +#include +#include +#include +#include +#include "unique_fd.h" +#include "filemgmt_libhilog.h" + +#include "cJSON.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +namespace { + const string PATH_BUNDLE_BACKUP_HOME = "/data/service/el2/100/backup/"; + const string CONFIG_NAME = "ClearDataConfig.json"; +} + +BJsonClearDataConfig::BJsonClearDataConfig() +{ + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + if (access(filePath.c_str(), F_OK) == 0) { + HILOGI("file exist filePath:%{public}s", filePath.c_str()); + return ; + } + HILOGI("Failed to access filePath :%{public}s", filePath.c_str()); + UniqueFd fd(open(filePath.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR)); + if (fd < 0) { + HILOGE("Failed to creat filePath :%{public}s", filePath.c_str()); + return ; + } + cJSON *jsonObjectDis = cJSON_CreateObject(); + if (jsonObjectDis == nullptr) { + HILOGE("Creat json failed"); + return ; + } + cJSON *jsonArray = cJSON_CreateArray(); + if (jsonArray == nullptr) { + HILOGE("Creat json failed"); + cJSON_Delete(jsonObjectDis); + return ; + } + cJSON_AddItemToObject(jsonObjectDis, "ClearDataConfigFile", jsonArray); + + char *newStr = cJSON_Print(jsonObjectDis); + if (newStr == nullptr) { + HILOGE("cJSON_Print json failed"); + cJSON_Delete(jsonObjectDis); + return ; + } + ofstream outFile(filePath); + if (!outFile.is_open()) { + HILOGE("open json failed"); + cJSON_free(newStr); + cJSON_Delete(jsonObjectDis); + return ; + } + outFile << newStr; + outFile.close(); + cJSON_free(newStr); + cJSON_Delete(jsonObjectDis); + HILOGI("Creat filePath ok :%{public}s", filePath.c_str()); +} + +bool BJsonClearDataConfig::HasClearBundleRecord() +{ + lock_guard autoLock(fileMutex_); + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + ifstream inFile(filePath); + if (!inFile.is_open()) { + HILOGE("open json failed"); + return false; + } + + string jsonString((istreambuf_iterator(inFile)), istreambuf_iterator()); + inFile.close(); + + cJSON *jsonObjectDis = cJSON_Parse(jsonString.c_str()); + if (jsonObjectDis == nullptr) { + HILOGE("parse json failed"); + return false; + } + + cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "ClearDataConfigFile"); + if (configArray == nullptr) { + HILOGE("parse json failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + + int recordSize = cJSON_GetArraySize(configArray); + cJSON_Delete(jsonObjectDis); + return recordSize > 0; +} + +bool BJsonClearDataConfig::FindClearBundleRecord(const string& bundleName) +{ + lock_guard autoLock(fileMutex_); + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + ifstream inFile(filePath); + if (!inFile.is_open()) { + HILOGE("open json failed"); + return false; + } + + string jsonString((istreambuf_iterator(inFile)), istreambuf_iterator()); + inFile.close(); + + cJSON *jsonObjectDis = cJSON_Parse(jsonString.c_str()); + if (jsonObjectDis == nullptr) { + HILOGE("parse json failed"); + return false; + } + + cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "ClearDataConfigFile"); + if (configArray == nullptr) { + HILOGE("parse json failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + bool ifBundlename = false; + for (int i = 0; i < cJSON_GetArraySize(configArray); ++i) { + cJSON *item = cJSON_GetArrayItem(configArray, i); + if (item != nullptr && cJSON_GetObjectItem(item, "bundleName") != nullptr && + cJSON_GetObjectItem(item, "bundleName")->type == cJSON_String && + cJSON_GetObjectItem(item, "bundleName")->valuestring == bundleName) { + ifBundlename = true; + } + } + + cJSON_Delete(jsonObjectDis); + return ifBundlename; +} + +bool BJsonClearDataConfig::InsertClearBundleRecord(const string& bundleName) +{ + lock_guard autoLock(fileMutex_); + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + ifstream inFile(filePath); + if (!inFile.is_open()) { + HILOGE("open json failed"); + return false; + } + + string jsonString((istreambuf_iterator(inFile)), istreambuf_iterator()); + inFile.close(); + + cJSON *jsonObjectDis = cJSON_Parse(jsonString.c_str()); + if (jsonObjectDis == nullptr) { + HILOGE("parse json failed"); + return false; + } + + cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "ClearDataConfigFile"); + if (configArray == nullptr) { + HILOGE("parse json failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + + for (int i = 0; i < cJSON_GetArraySize(configArray); ++i) { + cJSON *item = cJSON_GetArrayItem(configArray, i); + if (item != nullptr && cJSON_GetObjectItem(item, "bundleName") != nullptr && + cJSON_GetObjectItem(item, "bundleName")->type == cJSON_String && + cJSON_GetObjectItem(item, "bundleName")->valuestring == bundleName) { + HILOGI("record already exist, bundleName=%{public}s", bundleName.c_str()); + cJSON_Delete(jsonObjectDis); + return true; + } + } + + if (!WriteClearBundleRecord(bundleName)) { + HILOGE("InsertClearBundleRecord Failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + + HILOGI("InsertClearBundleRecord Ok"); + cJSON_Delete(jsonObjectDis); + return true; +} + +bool BJsonClearDataConfig::DeleteClearBundleRecord(const string& bundleName) +{ + lock_guard autoLock(fileMutex_); + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + ifstream input(filePath); + if (!input.is_open()) { + HILOGE("open json failed"); + return false; + } + + string jsonString((istreambuf_iterator(input)), istreambuf_iterator()); + input.close(); + + cJSON *jsonObjectDis = cJSON_Parse(jsonString.c_str()); + if (jsonObjectDis == nullptr) { + HILOGE("parse json failed"); + return false; + } + + cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "ClearDataConfigFile"); + if (configArray == nullptr) { + cJSON_Delete(jsonObjectDis); + return false; + } + for (int i = 0; i < cJSON_GetArraySize(configArray); ++i) { + cJSON *item = cJSON_GetArrayItem(configArray, i); + if (item != nullptr && cJSON_GetObjectItem(item, "bundleName") != nullptr && + cJSON_GetObjectItem(item, "bundleName")->type == cJSON_String && + cJSON_GetObjectItem(item, "bundleName")->valuestring == bundleName) { + cJSON_DeleteItemFromArray(configArray, i); + break; + } + } + char *newStr = cJSON_Print(jsonObjectDis); + if (newStr == nullptr) { + HILOGE("cJSON_Print json failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + ofstream output(filePath); + if (!output.is_open()) { + HILOGE("open json failed"); + cJSON_free(newStr); + cJSON_Delete(jsonObjectDis); + return false; + } + output << newStr; + output.close(); + + cJSON_free(newStr); + cJSON_Delete(jsonObjectDis); + return true; +} + +vector BJsonClearDataConfig::GetAllClearBundleRecords() +{ + lock_guard autoLock(fileMutex_); + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + vector bundleNameList; + ifstream inFile(filePath); + if (!inFile.is_open()) { + HILOGE("open json failed"); + return {}; + } + string jsonString((istreambuf_iterator(inFile)), istreambuf_iterator()); + inFile.close(); + + cJSON *jsonObjectDis = cJSON_Parse(jsonString.c_str()); + if (jsonObjectDis == nullptr) { + HILOGE("parse json failed"); + return {}; + } + + cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "ClearDataConfigFile"); + if (configArray == nullptr) { + HILOGE("parse json failed"); + cJSON_Delete(jsonObjectDis); + return {}; + } + for (int i = 0; i < cJSON_GetArraySize(configArray); ++i) { + cJSON *item = cJSON_GetArrayItem(configArray, i); + if (item != nullptr && cJSON_GetObjectItem(item, "bundleName") != nullptr && + cJSON_GetObjectItem(item, "bundleName")->type == cJSON_String) { + bundleNameList.push_back(cJSON_GetObjectItem(item, "bundleName")->valuestring); + } + } + cJSON_Delete(jsonObjectDis); + return bundleNameList; +} + +bool BJsonClearDataConfig::DeleteConfigFile() +{ + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + if (access(filePath.c_str(), F_OK) != 0) { + HILOGE("File is not exist"); + return false; + } + if (remove(filePath.c_str()) != 0) { + HILOGE("Delete ClearDataConfigFile failed"); + return false; + } + HILOGI("All Restore Finished, Delete ClearDataConfigFile OK"); + return true; +} + +bool BJsonClearDataConfig::WriteClearBundleRecord(const string& bundleName) +{ + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + ifstream inFile(filePath); + if (!inFile.is_open()) { + HILOGE("open json failed"); + return false; + } + string jsonString((istreambuf_iterator(inFile)), istreambuf_iterator()); + inFile.close(); + + cJSON *jsonObjectDis = cJSON_Parse(jsonString.c_str()); + if (jsonObjectDis == nullptr) { + HILOGE("parse json failed"); + return false; + } + + cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "ClearDataConfigFile"); + if (configArray == nullptr) { + HILOGE("parse json failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + cJSON *newItem = cJSON_CreateObject(); + if (configArray == nullptr || newItem == nullptr) { + HILOGE("parse json failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + + cJSON_AddStringToObject(newItem, "bundleName", bundleName.c_str()); + cJSON_AddItemToArray(configArray, newItem); + char *newStr = cJSON_Print(jsonObjectDis); + if (newStr == nullptr) { + HILOGE("cJSON_Print json failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + ofstream outFile(filePath); + if (!outFile.is_open()) { + HILOGE("open json failed"); + cJSON_free(newStr); + cJSON_Delete(jsonObjectDis); + return false; + } + outFile << newStr; + outFile.close(); + + cJSON_free(newStr); + cJSON_Delete(jsonObjectDis); + return true; +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee