From 7cba610964fe873760abbb87ae4374df90d73afa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=9F=B3=E4=BD=B3=E7=82=9C?= Date: Thu, 21 Aug 2025 20:24:42 +0800 Subject: [PATCH 01/17] clean code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 石佳炜 --- tests/mock/backup_ext/src/ext_extension_mock.cpp | 5 ----- tests/unittests/backup_sa/module_ipc/service_other_test.cpp | 2 +- tests/unittests/backup_sa/module_ipc/service_test.cpp | 3 +-- 3 files changed, 2 insertions(+), 8 deletions(-) diff --git a/tests/mock/backup_ext/src/ext_extension_mock.cpp b/tests/mock/backup_ext/src/ext_extension_mock.cpp index 712ce158d..6f72efde9 100644 --- a/tests/mock/backup_ext/src/ext_extension_mock.cpp +++ b/tests/mock/backup_ext/src/ext_extension_mock.cpp @@ -187,11 +187,6 @@ void BackupExtExtension::DoClearInner() BExtExtension::extExtension->DoClearInner(); } -ErrCode BackupExtExtension::CleanBundleTempDir() -{ - return BExtExtension::extExtension->CleanBundleTempDir(); -} - void BackupExtExtension::GetTarIncludes(const string &tarName, unordered_map &infos) { BExtExtension::extExtension->GetTarIncludes(tarName, infos); diff --git a/tests/unittests/backup_sa/module_ipc/service_other_test.cpp b/tests/unittests/backup_sa/module_ipc/service_other_test.cpp index a1253d5ea..5cace8b41 100644 --- a/tests/unittests/backup_sa/module_ipc/service_other_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_other_test.cpp @@ -875,7 +875,7 @@ HWTEST_F(ServiceTest, SUB_Service_AppendBundlesRestoreSession_0200, TestSize.Lev service->isOccupyingSession_.store(false); service->session_ = sptr(new SvcSessionManager(wptr(service))); EXPECT_CALL(*param, GetBackupDebugOverrideAccount()) - .WillOnce(Return(make_pair(true, DEBUG_ID + 1))); + .WillRepeatedly(Return(make_pair(true, DEBUG_ID + 1))); EXPECT_CALL(*skeleton, GetCallingTokenID()).WillOnce(Return(0)).WillOnce(Return(0)); EXPECT_CALL(*token, GetTokenType(_)).WillOnce(Return(Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL)); EXPECT_CALL(*skeleton, GetCallingUid()).WillOnce(Return(BConstants::SYSTEM_UID)); diff --git a/tests/unittests/backup_sa/module_ipc/service_test.cpp b/tests/unittests/backup_sa/module_ipc/service_test.cpp index f51d1fc6f..faeb4852c 100644 --- a/tests/unittests/backup_sa/module_ipc/service_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_test.cpp @@ -729,8 +729,7 @@ HWTEST_F(ServiceTest, SUB_Service_GetFileHandle_0101, testing::ext::TestSize.Lev BackupExtInfo extInfo {}; auto callDied = [](const string &&bundleName, bool isCleanCalled) {}; auto callConnected = [](const string &&bundleName) {}; - string bundleNameIndexInfo = "123456"; - extInfo.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnected, bundleNameIndexInfo)); + extInfo.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnected, BUNDLE_NAME)); extInfo.schedAction = BConstants::ServiceSchedAction::RUNNING; impl_.backupExtNameMap[BUNDLE_NAME] = extInfo; EXPECT_TRUE(servicePtr_ != nullptr); -- Gitee From 3c241fa62d028e87190861e769e4703497d8b7d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=9F=B3=E4=BD=B3=E7=82=9C?= Date: Fri, 22 Aug 2025 12:25:07 +0800 Subject: [PATCH 02/17] clean code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 石佳炜 --- .../native/backup_ext/src/ext_extension.cpp | 21 ------------------- .../backup_ext/src/sub_ext_extension.cpp | 21 +++++++++++++++++++ 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index f931cbb44..7cf79a69f 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -2173,25 +2173,4 @@ ErrCode BackupExtExtension::IncrementalAllFileReady(const TarMap &pkgInfo, close(manifestFdval); return ret; } - -ErrCode BackupExtExtension::CleanBundleTempDir() -{ - HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - HILOGI("BackupExtExtension::CleanBundleTempDir begin"); - if (extension_ == nullptr) { - HILOGE("Failed to CleanBundleTempDir, extension is nullptr"); - return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); - } - if (extension_->GetExtensionAction() == BConstants::ExtensionAction::INVALID) { - return BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid").GetCode(); - } - try { - VerifyCaller(); - DoClearInner(); - return ERR_OK; - } catch (...) { - HILOGE("Failed to CleanBundleTempDir"); - return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); - } -} } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/sub_ext_extension.cpp b/frameworks/native/backup_ext/src/sub_ext_extension.cpp index 59203d07e..5b21fabdf 100644 --- a/frameworks/native/backup_ext/src/sub_ext_extension.cpp +++ b/frameworks/native/backup_ext/src/sub_ext_extension.cpp @@ -1727,6 +1727,27 @@ tuple BackupExtExtension::GetIncrementalBackupFileHandle() return {UniqueFd(BConstants::INVALID_FD_NUM), UniqueFd(BConstants::INVALID_FD_NUM)}; } +ErrCode BackupExtExtension::CleanBundleTempDir() +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + HILOGI("BackupExtExtension::CleanBundleTempDir begin"); + if (extension_ == nullptr) { + HILOGE("Failed to CleanBundleTempDir, extension is nullptr"); + return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); + } + if (extension_->GetExtensionAction() == BConstants::ExtensionAction::INVALID) { + return BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid").GetCode(); + } + try { + VerifyCaller(); + DoClearInner(); + return ERR_OK; + } catch (...) { + HILOGE("Failed to CleanBundleTempDir"); + return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); + } +} + std::function BackupExtExtension::OnReleaseCallback(wptr obj) { HILOGI("Begin get HandleOnReleaseCallback"); -- Gitee From 1f92d12ba2f7f5550c1df0ff6a2a33f310bc7322 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=9F=B3=E4=BD=B3=E7=82=9C?= Date: Fri, 22 Aug 2025 15:50:01 +0800 Subject: [PATCH 03/17] add try catch MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 石佳炜 --- frameworks/native/backup_ext/src/ext_backup.cpp | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/frameworks/native/backup_ext/src/ext_backup.cpp b/frameworks/native/backup_ext/src/ext_backup.cpp index 304936753..1c2181418 100644 --- a/frameworks/native/backup_ext/src/ext_backup.cpp +++ b/frameworks/native/backup_ext/src/ext_backup.cpp @@ -104,7 +104,17 @@ string ExtBackup::GetUsrConfig() const { vector config; AppExecFwk::BundleMgrClient client; - BExcepUltils::BAssert(abilityInfo_, BError::Codes::EXT_BROKEN_FRAMEWORK, "Invalid abilityInfo_"); + try { + BExcepUltils::BAssert(abilityInfo_, BError::Codes::EXT_BROKEN_FRAMEWORK, "Invalid abilityInfo_"); + } catch (const BError &e) { + return ""; + } catch (const exception &e) { + HILOGE("%{public}s", e.what()); + return ""; + } catch (...) { + HILOGE("Unknown exception"); + return ""; + } const AppExecFwk::AbilityInfo &info = *abilityInfo_; if (!client.GetProfileFromAbility(info, "ohos.extension.backup", config)) { throw BError(BError::Codes::EXT_INVAL_ARG, "Failed to invoke the GetProfileFromAbility method."); -- Gitee From 7b0188a4453dac709e7462d8a6c51ce97e9aa9da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=9F=B3=E4=BD=B3=E7=82=9C?= Date: Mon, 25 Aug 2025 20:25:28 +0800 Subject: [PATCH 04/17] safe code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 石佳炜 --- utils/src/b_filesystem/b_dir.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/utils/src/b_filesystem/b_dir.cpp b/utils/src/b_filesystem/b_dir.cpp index e5630d732..55f147ee4 100644 --- a/utils/src/b_filesystem/b_dir.cpp +++ b/utils/src/b_filesystem/b_dir.cpp @@ -256,7 +256,10 @@ static void RmForceExcludePath(set &expandPath) static set ExpandPathWildcard(const vector &vec, bool onlyPath) { - unique_ptr> gl {new glob_t, [](glob_t *ptr) { globfree(ptr); }}; + unique_ptr> gl {new glob_t, [](glob_t *ptr) { + globfree(ptr); + delete ptr; + }}; *gl = {}; unsigned int flags = GLOB_DOOFFS | GLOB_MARK; -- Gitee From a96892855fa69c8af466f0155db3008ae5554e95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=9F=B3=E4=BD=B3=E7=82=9C?= Date: Tue, 26 Aug 2025 19:50:58 +0800 Subject: [PATCH 05/17] safe code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 石佳炜 --- utils/src/b_filesystem/b_dir.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/utils/src/b_filesystem/b_dir.cpp b/utils/src/b_filesystem/b_dir.cpp index 55f147ee4..14a1caec6 100644 --- a/utils/src/b_filesystem/b_dir.cpp +++ b/utils/src/b_filesystem/b_dir.cpp @@ -256,7 +256,7 @@ static void RmForceExcludePath(set &expandPath) static set ExpandPathWildcard(const vector &vec, bool onlyPath) { - unique_ptr> gl {new glob_t, [](glob_t *ptr) { + unique_ptr> gl {new glob_t, [](glob_t *ptr) { globfree(ptr); delete ptr; }}; -- Gitee From 99e8fe73b5d417563672c1e6230abed9c8de3d08 Mon Sep 17 00:00:00 2001 From: lizhengxing Date: Fri, 22 Aug 2025 15:01:18 +0800 Subject: [PATCH 06/17] dh compatibility Signed-off-by: lizhengxing --- .../native/backup_ext/include/ext_backup.h | 3 + .../native/backup_ext/include/ext_extension.h | 3 + .../native/backup_ext/src/ext_backup.cpp | 4 +- .../native/backup_ext/src/ext_extension.cpp | 7 +-- .../backup_ext/src/sub_ext_extension.cpp | 25 ++++++++- .../native/backup_ext/src/untar_file.cpp | 2 +- .../include/module_ipc/svc_session_manager.h | 18 ++++++ services/backup_sa/src/module_ipc/service.cpp | 4 ++ .../backup_sa/src/module_ipc/sub_service.cpp | 2 + .../src/module_ipc/svc_session_manager.cpp | 31 ++++++++++ .../include/svc_session_manager_mock.h | 4 ++ .../src/svc_session_manager_mock.cpp | 7 +++ .../module_ipc/svc_session_manager_mock.cpp | 7 +++ .../svc_session_manager_throw_mock.cpp | 7 +++ .../svc_session_manager_throw_mock.h | 4 ++ .../b_json/b_json_entity_extension_config.h | 27 +++++++++ utils/include/b_jsonutil/b_jsonutil.h | 12 ++++ utils/include/b_resources/b_constants.h | 10 +++- .../b_json/b_json_entity_extension_config.cpp | 56 +++++++++++++++++++ utils/src/b_jsonutil/b_jsonutil.cpp | 24 +++++++- 20 files changed, 247 insertions(+), 10 deletions(-) diff --git a/frameworks/native/backup_ext/include/ext_backup.h b/frameworks/native/backup_ext/include/ext_backup.h index b5fcd4665..ff9b95ccb 100644 --- a/frameworks/native/backup_ext/include/ext_backup.h +++ b/frameworks/native/backup_ext/include/ext_backup.h @@ -206,6 +206,9 @@ public: void SetBackupExtExtension(const wptr &extExtension); +public: + std::string backupScene_; + protected: std::string appVersionStr_; std::string restoreRetInfo_; diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index 0d9164788..8df461ec1 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -397,6 +397,9 @@ private: void HandleExtOnRelease(bool isAppResultReport, ErrCode errCode); std::function OnReleaseCallback(wptr obj); std::function GetComInfoCallback(wptr obj); + void GetScanDirList(vector& includes, + vector& excludes, + const BJsonEntityExtensionConfig &usrConfig); private: pair> GetFileInfos(const vector &includes, const vector &excludes); TarMap GetIncrmentBigInfos(const vector &files); diff --git a/frameworks/native/backup_ext/src/ext_backup.cpp b/frameworks/native/backup_ext/src/ext_backup.cpp index 304936753..9bc516afa 100644 --- a/frameworks/native/backup_ext/src/ext_backup.cpp +++ b/frameworks/native/backup_ext/src/ext_backup.cpp @@ -175,7 +175,9 @@ ErrCode ExtBackup::GetParament(const AAFwk::Want &want) HILOGI("oldBackupVersion_ is %{public}s", oldBackupVersion_.c_str()); } else if (extAction_ == BConstants::ExtensionAction::BACKUP) { backupExtInfo_ = want.GetStringParam(BConstants::EXTENSION_BACKUP_EXT_INFO_PARA); - HILOGI("backupExtInfo_ is %{public}s", backupExtInfo_.c_str()); + backupScene_ = want.GetStringParam(BConstants::EXTENSION_BACKUP_SCENE_PARA); + HILOGI("backupExtInfo_ is %{public}s, backupScene_ is %{public}s", + backupExtInfo_.c_str(), backupScene_.c_str()); } /* backup don't need parament. */ return ERR_OK; diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index f931cbb44..8dae6bbd1 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -848,10 +848,9 @@ tuple BackupExtExtension::CalculateDataSize(const B HILOGE("mkdir failed path :%{public}s, err = %{public}d", path.c_str(), errno); return {errno, 0, 0}; } - - vector includes = usrConfig.GetIncludes(); - vector excludes = usrConfig.GetExcludes(); - + vector includes = {}; + vector excludes = {}; + GetScanDirList(includes, excludes, usrConfig); // 扫描文件计算数据量 tie(bigFileInfo, smallFiles) = GetFileInfos(includes, excludes); ScanFileSingleton::GetInstance().SetCompletedFlag(true); diff --git a/frameworks/native/backup_ext/src/sub_ext_extension.cpp b/frameworks/native/backup_ext/src/sub_ext_extension.cpp index 59203d07e..11148a7a2 100644 --- a/frameworks/native/backup_ext/src/sub_ext_extension.cpp +++ b/frameworks/native/backup_ext/src/sub_ext_extension.cpp @@ -1003,8 +1003,9 @@ void BackupExtExtension::DoUser0Backup(const BJsonEntityExtensionConfig &usrConf if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { throw BError(errno); } - vector includes = usrConfig.GetIncludes(); - vector excludes = usrConfig.GetExcludes(); + vector includes = {}; + vector excludes = {}; + GetScanDirList(includes, excludes, usrConfig); auto task = [obj {wptr(this)}, includes, excludes]() { auto ptr = obj.promote(); BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); @@ -1919,4 +1920,24 @@ ErrCode BackupExtExtension::HandleGetCompatibilityInfo(const string &extInfo, in return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); } } + +void BackupExtExtension::GetScanDirList(vector& includes, + vector& excludes, + const BJsonEntityExtensionConfig &usrConfig) +{ + if (extension_ == nullptr) { + HILOGI("extension is nullptr."); + return; + } + HILOGI("extension_->backupScene_:%{public}s, optionDir:%{public}d", + extension_->backupScene_.c_str(), usrConfig.HasOptionDir()); + if (extension_->backupScene_ != "" && usrConfig.HasOptionDir()) { + includes = usrConfig.GetOptionDir(extension_->backupScene_, BConstants::INCLUDES); + excludes = usrConfig.GetOptionDir(extension_->backupScene_, BConstants::EXCLUDES); + } else { + includes = usrConfig.GetIncludes(); + excludes = usrConfig.GetExcludes(); + } +} + } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/untar_file.cpp b/frameworks/native/backup_ext/src/untar_file.cpp index d84c328a7..c065dfa65 100644 --- a/frameworks/native/backup_ext/src/untar_file.cpp +++ b/frameworks/native/backup_ext/src/untar_file.cpp @@ -608,7 +608,7 @@ ErrFileInfo UntarFile::CreateDir(string &path, mode_t mode) path[len - 1] = '\0'; } if (access(path.c_str(), F_OK) != 0) { - HILOGE("directory does not exist, path:%{public}s, err = %{public}d", path.c_str(), errno); + HILOGD("directory does not exist, path:%{public}s, err = %{public}d", path.c_str(), errno); if (!ForceCreateDirectoryWithMode(path, mode)) { HILOGE("Failed to force create directory %{public}s, err = %{public}d", path.c_str(), errno); errFileInfo[path].emplace_back(errno); 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 d9a40dd69..1afb97b2c 100644 --- a/services/backup_sa/include/module_ipc/svc_session_manager.h +++ b/services/backup_sa/include/module_ipc/svc_session_manager.h @@ -75,6 +75,7 @@ struct BackupExtInfo { bool isInPublishFile {false}; bool isReadyLaunch {false}; bool isRestoreEnd {false}; + std::string backupScene; }; class Service; @@ -584,6 +585,23 @@ public: bool GetIsRestoreEnd(const std::string &bundleName); + /** + * @brief Get the backupScene + * + * @param bundleName + * @return std::string + */ + std::string GetBackupScene(const std::string &bundleName); + + /** + * @brief Set the backupScene + * + * @param bundleName + * @param backupScene + * @return void + */ + void SetBackupScene(const std::string &bundleName, const std::string &backupScene); + private: /** * @brief 获取backup extension ability diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 777caa094..44ce7919c 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -972,6 +972,10 @@ void Service::HandleCurGroupBackupInfos( session_->SetBundleUserId(bundleNameIndexInfo, session_->GetSessionUserId()); session_->SetBackupExtName(bundleNameIndexInfo, info.extensionName); session_->SetIsReadyLaunch(bundleNameIndexInfo); + std::string backupScene = ""; + if (BJsonUtil::FindBackupSceneByName(bundleNameDetailMap, bundleNameIndexInfo, backupScene)) { + session_->SetBackupScene(bundleNameIndexInfo, backupScene); + } } } diff --git a/services/backup_sa/src/module_ipc/sub_service.cpp b/services/backup_sa/src/module_ipc/sub_service.cpp index a71006c6e..51a6b972b 100644 --- a/services/backup_sa/src/module_ipc/sub_service.cpp +++ b/services/backup_sa/src/module_ipc/sub_service.cpp @@ -466,6 +466,7 @@ void Service::SetWant(AAFwk::Want &want, const BundleName &bundleName, const BCo if (oldBackupVersion.empty()) { HILOGE("Failed to get backupVersion of old device"); } + bundleDetail.backupScene = session_->GetBackupScene(bundleName); want.SetElementName(bundleDetail.bundleName, backupExtName); want.SetParam(BConstants::EXTENSION_ACTION_PARA, static_cast(action)); want.SetParam(BConstants::EXTENSION_VERSION_CODE_PARA, static_cast(versionCode)); @@ -475,6 +476,7 @@ void Service::SetWant(AAFwk::Want &want, const BundleName &bundleName, const BCo want.SetParam(BConstants::EXTENSION_BACKUP_EXT_INFO_PARA, bundleExtInfo); want.SetParam(BConstants::EXTENSION_APP_CLONE_INDEX_PARA, bundleDetail.bundleIndex); want.SetParam(BConstants::EXTENSION_OLD_BACKUP_VERSION_PARA, oldBackupVersion); + want.SetParam(BConstants::EXTENSION_BACKUP_SCENE_PARA, bundleDetail.backupScene); } std::vector Service::GetSupportBackupBundleNames(vector &backupInfos, 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 18af5a9fd..4d45a0605 100644 --- a/services/backup_sa/src/module_ipc/svc_session_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_session_manager.cpp @@ -1361,4 +1361,35 @@ bool SvcSessionManager::GetIsRestoreEnd(const std::string &bundleName) } return it->second.isRestoreEnd; } + +void SvcSessionManager::SetBackupScene(const std::string &bundleName, const std::string &backupScene) +{ + unique_lock lock(lock_); + if (!impl_.clientToken) { + HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str()); + return; + } + auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName); + if (!findBundleSuc) { + HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str()); + return; + } + it->second.backupScene = backupScene; + HILOGI("SetBackupScene success, bundleName = %{public}s", bundleName.c_str()); +} + +std::string SvcSessionManager::GetBackupScene(const std::string &bundleName) +{ + shared_lock lock(lock_); + if (!impl_.clientToken) { + HILOGE("No caller token was specified, bundleName:%{public}s", bundleName.c_str()); + return ""; + } + auto [findBundleSuc, it] = GetBackupExtNameMap(bundleName); + if (!findBundleSuc) { + HILOGE("BackupExtNameMap can not find bundle %{public}s", bundleName.c_str()); + return ""; + } + return it->second.backupScene; +} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/include/svc_session_manager_mock.h b/tests/mock/module_ipc/include/svc_session_manager_mock.h index 9588ac367..7827190f2 100644 --- a/tests/mock/module_ipc/include/svc_session_manager_mock.h +++ b/tests/mock/module_ipc/include/svc_session_manager_mock.h @@ -66,6 +66,8 @@ public: virtual void HandleOnRelease(sptr proxy) = 0; virtual void SetIsRestoreEnd(const std::string &bundleName) = 0; virtual bool GetIsRestoreEnd(const std::string &bundleName) = 0; + virtual std::string GetBackupScene(const std::string &bundleName) = 0; + virtual void SetBackupScene(const std::string &bundleName, const std::string &backupScene) = 0; public: BSvcSessionManager() = default; virtual ~BSvcSessionManager() = default; @@ -118,6 +120,8 @@ public: MOCK_METHOD(void, HandleOnRelease, (sptr)); MOCK_METHOD(void, SetIsRestoreEnd, (const std::string &)); MOCK_METHOD(bool, GetIsRestoreEnd, (const std::string &)); + MOCK_METHOD(void, SetBackupScene, (const std::string &, const std::string &)); + MOCK_METHOD(std::string, GetBackupScene, (const std::string &)); }; } // namespace OHOS::FileManagement::Backup #endif // OHOS_FILEMGMT_BACKUP_SVC_SESSION_MANAGER_MOCK_H diff --git a/tests/mock/module_ipc/src/svc_session_manager_mock.cpp b/tests/mock/module_ipc/src/svc_session_manager_mock.cpp index ab02cc68d..f71b61aa4 100644 --- a/tests/mock/module_ipc/src/svc_session_manager_mock.cpp +++ b/tests/mock/module_ipc/src/svc_session_manager_mock.cpp @@ -319,4 +319,11 @@ bool SvcSessionManager::GetIsRestoreEnd(const std::string &bundleName) { return false; } + +std::string SvcSessionManager::GetBackupScene(const std::string &bundleName) +{ + return BSvcSessionManager::sessionManager->GetBackupScene(bundleName); +} + +void SvcSessionManager::SetBackupScene(const std::string &bundleName, const std::string &backupScene) {} } // 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 2cc861333..7096895e6 100644 --- a/tests/mock/module_ipc/svc_session_manager_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_mock.cpp @@ -543,4 +543,11 @@ bool SvcSessionManager::GetIsRestoreEnd(const std::string &bundleName) { return false; } + +std::string SvcSessionManager::GetBackupScene(const std::string &bundleName) +{ + return ""; +} + +void SvcSessionManager::SetBackupScene(const std::string &bundleName, const std::string &backupScene) {} } // namespace OHOS::FileManagement::Backup 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 1fa56ea3b..28c285d25 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp @@ -373,4 +373,11 @@ bool SvcSessionManager::GetIsRestoreEnd(const std::string &bundleName) { return false; } + +std::string SvcSessionManager::GetBackupScene(const std::string &bundleName) +{ + return BackupSvcSessionManager::session->GetBackupScene(bundleName); +} + +void SvcSessionManager::SetBackupScene(const std::string &bundleName, const std::string &backupScene) {} } // namespace OHOS::FileManagement::Backup 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 8cd651ca7..ecd8d8f23 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.h +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.h @@ -102,6 +102,8 @@ public: virtual void HandleOnRelease(sptr proxy) = 0; virtual void SetIsRestoreEnd(const std::string &bundleName) = 0; virtual bool GetIsRestoreEnd(const std::string &bundleName) = 0; + virtual std::string GetBackupScene(const std::string &bundleName) = 0; + virtual void SetBackupScene(const std::string &bundleName, const std::string &backupScene) = 0; public: static inline std::shared_ptr session = nullptr; }; @@ -183,6 +185,8 @@ public: MOCK_METHOD(void, HandleOnRelease, (sptr)); MOCK_METHOD(void, SetIsRestoreEnd, (const std::string &)); MOCK_METHOD(bool, GetIsRestoreEnd, (const std::string &)); + MOCK_METHOD(void, SetBackupScene, (const std::string &, const std::string &)); + MOCK_METHOD(std::string, GetBackupScene, (const std::string &)); }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/include/b_json/b_json_entity_extension_config.h b/utils/include/b_json/b_json_entity_extension_config.h index 8523f2e93..3e7f98eb6 100644 --- a/utils/include/b_json/b_json_entity_extension_config.h +++ b/utils/include/b_json/b_json_entity_extension_config.h @@ -83,6 +83,33 @@ public: */ bool GetRequireCompatibility() const; + /** + * @brief Get the backupScene object + * + * @return std::string + */ + std::string GetBackupScene() const; + + /** + * @brief Judge the optionDir key exist + * + * @return bool + */ + bool HasOptionDir() const; + + /** + * @brief Get the optionDir object + * + * @return vector + */ + vector GetOptionDir(const std::string& sceneId, const std::string& fileType) const; + + /** + * @brief Get the GetDirList + * + * @return vector + */ + vector GetDirList(Json::Value& jsonItem) const; public: std::string GetJSonSource(std::string_view jsonFromRealWorld, std::any option); diff --git a/utils/include/b_jsonutil/b_jsonutil.h b/utils/include/b_jsonutil/b_jsonutil.h index 686f146fb..2e19abdca 100644 --- a/utils/include/b_jsonutil/b_jsonutil.h +++ b/utils/include/b_jsonutil/b_jsonutil.h @@ -23,6 +23,7 @@ namespace OHOS::FileManagement::Backup { class BJsonUtil { public: typedef struct BundleDetailInfo { + std::string backupScene; std::string bundleName; std::string type; std::string detail; @@ -200,6 +201,17 @@ public: size_t listSize, std::string scanning, std::string &jsonStr); + /** + * @brief 通过bundlename找sceneId + * + * @param bundleNameDetailsMap 包名和当前包扩展信息解析结果的集合 + * @param bundleName 包名 + * @param backupScene 存储backupScene的变量 + * + * @return 是否成功 + */ + static bool FindBackupSceneByName(std::map> &bundleNameDetailsMap, + std::string &bundleName, std::string &backupScene); }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/include/b_resources/b_constants.h b/utils/include/b_resources/b_constants.h index bf66f58f9..f78eaf4cc 100644 --- a/utils/include/b_resources/b_constants.h +++ b/utils/include/b_resources/b_constants.h @@ -32,6 +32,7 @@ static inline const char *EXTENSION_RESTORE_EXT_INFO_PARA = "restoreExtInfo"; static inline const char *EXTENSION_BACKUP_EXT_INFO_PARA = "backupExtInfo"; static inline const char *EXTENSION_APP_CLONE_INDEX_PARA = "ohos.extra.param.key.appCloneIndex"; static inline const char *EXTENSION_OLD_BACKUP_VERSION_PARA = "oldBackupVersion"; +static inline const char *EXTENSION_BACKUP_SCENE_PARA = "backupScene"; enum class ExtensionAction { INVALID = 0, @@ -209,6 +210,13 @@ static inline std::string_view REPORT_FILE_EXT = "rp"; // 空简报 static inline std::string BLANK_REPORT_NAME = "blankReport.rp"; +// 兼容性字段 +static inline std::string BACKUP_SCENE = "backupScene"; +static inline std::string OPTION_DIR = "optionDir"; +static inline std::string INCLUDES = "includes"; +static inline std::string EXCLUDES = "excludes"; +static inline int DEFAULT_APPINDEX = 0; + // 特殊版本信息 constexpr int DEFAULT_VERSION_CODE = 0; constexpr char VERSION_NAME_SEPARATOR_CHAR = '-'; @@ -222,7 +230,7 @@ static inline std::vector DEFAULT_VERSION_NAMES_VEC = { DEFAULT_VERSION_NAME, DEFAULT_VERSION_NAME_CLONE, DEFAULT_VERSION_NAME_CLONE_2, DEFAULT_VERSION_NAME_CLONE_3, DEFAULT_VERSION_NAME_PC, DEFAULT_VERSION_NAME_CLOUD, }; -static inline std::string BACKUP_VERSION = R"({"backupVersion" : "20.0"})"; +static inline std::string BACKUP_VERSION = R"({"backupVersion" : "20.1"})"; // 应用默认备份的目录,其均为相对根路径的路径。为避免模糊匹配,务必以斜线为结尾。 static inline std::array PATHES_TO_BACKUP = { diff --git a/utils/src/b_json/b_json_entity_extension_config.cpp b/utils/src/b_json/b_json_entity_extension_config.cpp index 6f17cf0da..a7b47d67a 100644 --- a/utils/src/b_json/b_json_entity_extension_config.cpp +++ b/utils/src/b_json/b_json_entity_extension_config.cpp @@ -189,5 +189,61 @@ bool BJsonEntityExtensionConfig::GetRequireCompatibility() const return obj_["requireCompatibility"].asBool(); } +string BJsonEntityExtensionConfig::GetBackupScene() const +{ + if (!obj_ || !obj_.isMember("backupScene") || !obj_["backupScene"].isString()) { + HILOGD("Failed to get field backupScene"); + return ""; + } + + return obj_["backupScene"].asString(); +} + +bool BJsonEntityExtensionConfig::HasOptionDir() const +{ + if (!obj_ || !obj_.isMember("optionDir") || !obj_["optionDir"].isArray()) { + HILOGE("OptionDir is not exist"); + return false; + } + return true; +} + +vector BJsonEntityExtensionConfig::GetOptionDir(const string& sceneId, const string& fileType) const +{ + if (!HasOptionDir()) { + return {}; + } + for (auto &&item : obj_["optionDir"]) { + if (item.empty()) { + HILOGE("Each item of array 'optionDir' must be not empty"); + continue; + } + if (item.isMember("sceneId") && item["sceneId"] == sceneId && item.isMember(fileType)) { + return GetDirList(item[fileType]); + } + } + return {}; +} + +vector BJsonEntityExtensionConfig::GetDirList(Json::Value& jsonItem) const +{ + vector dirs; + if (!jsonItem.isArray()) { + HILOGE("item must be not array"); + return dirs; + } + for (auto &&item : jsonItem) { + if (!item.isString() || item.empty()) { + HILOGE("Each item of array must be of the type string"); + continue; + } + dirs.emplace_back(item.asString()); + } + + if (dirs.empty()) { + dirs.emplace_back(""); + } + return dirs; +} } // namespace OHOS::FileManagement::Backup diff --git a/utils/src/b_jsonutil/b_jsonutil.cpp b/utils/src/b_jsonutil/b_jsonutil.cpp index cdd7a085d..ce3c1a889 100644 --- a/utils/src/b_jsonutil/b_jsonutil.cpp +++ b/utils/src/b_jsonutil/b_jsonutil.cpp @@ -243,12 +243,17 @@ void BJsonUtil::ParseBundleInfoJson(const std::string &bundleInfo, std::vectorvaluestring == nullptr)) { - HILOGE("Parse json error."); + HILOGE("Parse clearBackupData error."); } else { std::string value = clearBackupData->valuestring; isClearData = value.compare("false") != 0; HILOGI("bundleName:%{public}s clear data falg:%{public}d", bundleDetailInfo.bundleName.c_str(), isClearData); } + cJSON *backupScene = cJSON_GetObjectItem(root, "backupScene"); + if (backupScene != nullptr && cJSON_IsString(backupScene) && (backupScene->valuestring != nullptr)) { + HILOGI("Parse backupScene success"); + bundleDetailInfo.backupScene = backupScene->valuestring; + } cJSON *infos = cJSON_GetObjectItem(root, "infos"); if (infos == nullptr || !cJSON_IsArray(infos) || cJSON_GetArraySize(infos) == 0) { HILOGE("Parse json error, infos is not array"); @@ -533,4 +538,21 @@ bool BJsonUtil::WriteToStr(std::vector &bundleDataList, HILOGI("write json str ok, scanned size is %{public}zu", listSize); return true; } + +bool BJsonUtil::FindBackupSceneByName(std::map> &bundleNameDetailsMap, + std::string &bundleName, std::string &backupScene) +{ + auto iter = bundleNameDetailsMap.find(bundleName); + if (iter == bundleNameDetailsMap.end()) { + return false; + } + std::vector bundleDetailInfos = iter->second; + for (const auto &bundleDetailInfo : bundleDetailInfos) { + if (bundleDetailInfo.backupScene != "") { + backupScene = bundleDetailInfo.backupScene; + return true; + } + } + return false; +} } \ No newline at end of file -- Gitee From a114338390269c1b617c8ec1857e46e927a26bdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=9F=B3=E4=BD=B3=E7=82=9C?= Date: Thu, 28 Aug 2025 12:09:40 +0800 Subject: [PATCH 07/17] ipc error MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 石佳炜 --- services/backup_sa/src/module_ipc/service.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 44ce7919c..53a258108 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -86,6 +86,7 @@ const std::string BACKUPSERVICE_WORK_STATUS_ON = "true"; const std::string BACKUPSERVICE_WORK_STATUS_OFF = "false"; const std::string BACKUP_PERMISSION = "ohos.permission.BACKUP"; const int32_t MAX_TRY_CLEAR_DISPOSE_NUM = 3; +const int IPC_ERROR = 29189; } // namespace /* Shell/Xts user id equal to 0/1, we need set default 100 */ @@ -1151,6 +1152,9 @@ void Service::StartCurBundleBackupOrRestore(const std::string &bundleName) } } else if (scenario == IServiceReverseType::Scenario::RESTORE) { auto ret = proxy->HandleRestore(session_->GetClearDataFlag(bundleName)); + if (ret == IPC_ERROR) { + ret = BError::BackupErrorCode::E_BTO; + } session_->GetServiceReverseProxy()->RestoreOnBundleStarted(ret, bundleName); GetOldDeviceBackupVersion(); BundleBeginRadarReport(bundleName, ret, scenario); -- Gitee From 6a97a852bbf8b8718b1e8a0fb29f003cad55ca09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=9F=B3=E4=BD=B3=E7=82=9C?= Date: Thu, 28 Aug 2025 17:45:10 +0800 Subject: [PATCH 08/17] safe code MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 石佳炜 --- utils/src/b_hiaudit/hi_audit.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/utils/src/b_hiaudit/hi_audit.cpp b/utils/src/b_hiaudit/hi_audit.cpp index 8367eab47..993468555 100644 --- a/utils/src/b_hiaudit/hi_audit.cpp +++ b/utils/src/b_hiaudit/hi_audit.cpp @@ -74,7 +74,7 @@ void HiAudit::Init() } std::string logFilePath = hiAuditConfig_.logPath + hiAuditConfig_.logName + "_audit.csv"; writeFd_ = - open(logFilePath.c_str(), O_CREAT | O_APPEND | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); + open(logFilePath.c_str(), O_CREAT | O_APPEND | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (writeFd_ < 0) { HILOGE("Init, open error, logFilePath is:%{public}s, errno:%{public}d", logFilePath.c_str(), errno); } @@ -143,7 +143,7 @@ void HiAudit::GetWriteFilePath() } std::string logFilePath = hiAuditConfig_.logPath + hiAuditConfig_.logName + "_audit.csv"; writeFd_ = - open(logFilePath.c_str(), O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH); + open(logFilePath.c_str(), O_CREAT | O_TRUNC | O_RDWR, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (writeFd_ < 0) { HILOGE("GetWriteFilePath, Open fd error, errno:%{public}d", errno); } -- Gitee From 915b05247ccfffde01ce438eb5b4f757b0672693 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=95=E6=8C=AF=E6=9D=B0?= Date: Thu, 28 Aug 2025 21:01:59 +0800 Subject: [PATCH 09/17] FinishOnProcessTask normally MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 吕振杰 --- .../backup_ext/src/sub_ext_extension.cpp | 44 +++++++++---------- .../backup_ext/ext_extension_sub_test.cpp | 12 ++++- 2 files changed, 33 insertions(+), 23 deletions(-) diff --git a/frameworks/native/backup_ext/src/sub_ext_extension.cpp b/frameworks/native/backup_ext/src/sub_ext_extension.cpp index b05dc211d..0fe4ad092 100644 --- a/frameworks/native/backup_ext/src/sub_ext_extension.cpp +++ b/frameworks/native/backup_ext/src/sub_ext_extension.cpp @@ -296,26 +296,26 @@ std::function BackupExtExtension::OnRestoreExCallbac HILOGE("Appdone has been executed for the current application"); return; } - if (errCode == ERR_OK && !restoreRetInfo.empty()) { - auto spendTime = extensionPtr->GetOnStartTimeCost(); - if (spendTime >= BConstants::MAX_TIME_COST) { - std::stringstream ss; - ss << R"("spendTime": )"<< spendTime << "ms"; - AppRadar::Info info (extensionPtr->bundleName_, "", ss.str()); - AppRadar::GetInstance().RecordRestoreFuncRes(info, "BackupExtExtension::OnRestoreExCallback", - AppRadar::GetInstance().GetUserId(), BizStageRestore::BIZ_STAGE_ON_RESTORE, ERR_OK); - } - } - extensionPtr->FinishOnProcessTask(); extensionPtr->extension_->InvokeAppExtMethod(errCode, restoreRetInfo); if (errCode == ERR_OK) { if (restoreRetInfo.size()) { + auto spendTime = extensionPtr->GetOnStartTimeCost(); + if (spendTime >= BConstants::MAX_TIME_COST) { + std::stringstream ss; + ss << R"("spendTime": )"<< spendTime << "ms"; + AppRadar::Info info (extensionPtr->bundleName_, "", ss.str()); + AppRadar::GetInstance().RecordRestoreFuncRes(info, "BackupExtExtension::OnRestoreExCallback", + AppRadar::GetInstance().GetUserId(), BizStageRestore::BIZ_STAGE_ON_RESTORE, ERR_OK); + } HILOGI("Will notify restore result report"); + extensionPtr->FinishOnProcessTask(); extensionPtr->ReportAppStatistic("OnRestoreExCallback1", errCode); extensionPtr->AppResultReport(restoreRetInfo, BackupRestoreScenario::FULL_RESTORE); } return; } + HILOGE("Call extension onRestoreEx failed, errInfo = %{public}s", restoreRetInfo.c_str()); + extensionPtr->FinishOnProcessTask(); if (restoreRetInfo.empty()) { extensionPtr->AppDone(errCode); extensionPtr->DoClear(); @@ -363,25 +363,25 @@ std::function BackupExtExtension::IncreOnRestoreExCa HILOGE("Appdone has been executed for the current application"); return; } - if (errCode == ERR_OK && !restoreRetInfo.empty()) { - auto spendTime = extensionPtr->GetOnStartTimeCost(); - if (spendTime >= BConstants::MAX_TIME_COST) { - std::stringstream ss; - ss << R"("spendTime": )"<< spendTime << "ms"; - AppRadar::Info info (extensionPtr->bundleName_, "", ss.str()); - AppRadar::GetInstance().RecordRestoreFuncRes(info, "BackupExtExtension::IncreOnRestoreExCallback", - AppRadar::GetInstance().GetUserId(), BizStageRestore::BIZ_STAGE_ON_RESTORE, ERR_OK); - } - } - extensionPtr->FinishOnProcessTask(); extensionPtr->extension_->InvokeAppExtMethod(errCode, restoreRetInfo); if (errCode == ERR_OK) { if (restoreRetInfo.size()) { + auto spendTime = extensionPtr->GetOnStartTimeCost(); + if (spendTime >= BConstants::MAX_TIME_COST) { + std::stringstream ss; + ss << R"("spendTime": )"<< spendTime << "ms"; + AppRadar::Info info (extensionPtr->bundleName_, "", ss.str()); + AppRadar::GetInstance().RecordRestoreFuncRes(info, "BackupExtExtension::IncreOnRestoreExCallback", + AppRadar::GetInstance().GetUserId(), BizStageRestore::BIZ_STAGE_ON_RESTORE, ERR_OK); + } + extensionPtr->FinishOnProcessTask(); extensionPtr->ReportAppStatistic("IncreOnRestoreExCallback1", errCode); extensionPtr->AppResultReport(restoreRetInfo, BackupRestoreScenario::INCREMENTAL_RESTORE); } return; } + HILOGE("Call increment onRestoreEx failed, errInfo = %{public}s", restoreRetInfo.c_str()); + extensionPtr->FinishOnProcessTask(); if (restoreRetInfo.empty()) { extensionPtr->AppIncrementalDone(errCode); extensionPtr->DoClear(); diff --git a/tests/unittests/backup_ext/ext_extension_sub_test.cpp b/tests/unittests/backup_ext/ext_extension_sub_test.cpp index 284cf4744..93c61b6d4 100644 --- a/tests/unittests/backup_ext/ext_extension_sub_test.cpp +++ b/tests/unittests/backup_ext/ext_extension_sub_test.cpp @@ -394,7 +394,17 @@ HWTEST_F(ExtExtensionSubTest, Ext_Extension_Sub_OnRestoreExCallback_Test_0100, t restoreCallBack(errCode, restoreRetInfo); extExtension->isExecAppDone_.store(false); EXPECT_EQ(restoreRetInfo, "err"); - + + extExtension->isExecAppDone_.store(false); + restoreRetInfo = ""; + restoreCallBack = extExtension->OnRestoreExCallback(extExtension); + restoreCallBack(errCode, restoreRetInfo); + EXPECT_EQ(restoreRetInfo, ""); + + restoreRetInfo = "err"; + restoreCallBack = extExtension->OnRestoreExCallback(extExtension); + restoreCallBack(errCode, restoreRetInfo); + EXPECT_EQ(restoreRetInfo, "err"); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ExtExtensionSubTest-an exception occurred by construction."; -- Gitee From 9f550db47a6fdd0e27e35fe1c15a3cb5bd07b00d Mon Sep 17 00:00:00 2001 From: linan24 Date: Thu, 4 Sep 2025 16:30:55 +0800 Subject: [PATCH 10/17] add exception catch Signed-off-by: linan24 --- services/backup_sa/src/module_ipc/sub_service.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/services/backup_sa/src/module_ipc/sub_service.cpp b/services/backup_sa/src/module_ipc/sub_service.cpp index 51a6b972b..da71f1b81 100644 --- a/services/backup_sa/src/module_ipc/sub_service.cpp +++ b/services/backup_sa/src/module_ipc/sub_service.cpp @@ -1399,7 +1399,12 @@ ErrCode Service::TryToConnectExt(const std::string& bundleName, sptrSetCallback(callConnected); extConnection->SetCallDied(callDied); - AAFwk::Want want = CreateConnectWant(bundleName); + AAFwk::Want want; + try { + want = CreateConnectWant(bundleName); + } catch (const BError &e) { + return e.GetCode(); + } ErrCode err = extConnection->ConnectBackupExtAbility(want, GetUserIdDefault(), false); if (err != BError(BError::Codes::OK)) { HILOGE("ConnectBackupExtAbility failed, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), err); -- Gitee From c1f875d99fc835337fcf027cb60e5feccf5e7c07 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=95=E6=8C=AF=E6=9D=B0?= Date: Tue, 9 Sep 2025 10:41:06 +0800 Subject: [PATCH 11/17] add lock and close fd MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 吕振杰 --- frameworks/native/backup_ext/src/ext_extension.cpp | 2 ++ services/backup_sa/include/module_ipc/service.h | 1 + .../backup_sa/src/module_ipc/service_incremental.cpp | 6 ------ services/backup_sa/src/module_ipc/sub_service.cpp | 9 +++------ 4 files changed, 6 insertions(+), 12 deletions(-) diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index 8a2801f32..55b868e52 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -2106,6 +2106,8 @@ ErrCode BackupExtExtension::IncrementalTarFileReady(const TarMap &bigFileInfo, } else { HILOGE("IncrementalTarFileReady interface fails to be invoked: %{public}d", ret); } + close(fd); + close(manifestFd); return ret; } diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index 5735f3f55..3e36aed0e 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -790,6 +790,7 @@ private: std::shared_mutex statMapMutex_; std::map> saStatisticMap_; std::map> backupExtOnReleaseMap_; + std::shared_mutex extOnReleaseLock_; public: std::map> backupExtMutexMap_; std::map failedBundles_; diff --git a/services/backup_sa/src/module_ipc/service_incremental.cpp b/services/backup_sa/src/module_ipc/service_incremental.cpp index f223767e3..8c5bfa838 100644 --- a/services/backup_sa/src/module_ipc/service_incremental.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental.cpp @@ -713,12 +713,6 @@ ErrCode Service::AppIncrementalDone(ErrCode errCode) HILOGI("Service AppIncrementalDone start, callerName is %{public}s, errCode is: %{public}d", callerName.c_str(), errCode); if (session_->OnBundleFileReady(callerName) || errCode != BError(BError::Codes::OK)) { - std::shared_ptr mutexPtr = GetExtensionMutex(callerName); - if (mutexPtr == nullptr) { - HILOGE("extension mutex ptr is nullptr, bundleName:%{public}s", callerName.c_str()); - return BError(BError::Codes::SA_INVAL_ARG); - } - std::lock_guard lock(mutexPtr->callbackMutex); SetExtOnRelease(callerName, true); return BError(BError::Codes::OK); } diff --git a/services/backup_sa/src/module_ipc/sub_service.cpp b/services/backup_sa/src/module_ipc/sub_service.cpp index 37300712a..00e2ecc6f 100644 --- a/services/backup_sa/src/module_ipc/sub_service.cpp +++ b/services/backup_sa/src/module_ipc/sub_service.cpp @@ -384,12 +384,6 @@ ErrCode Service::AppDone(ErrCode errCode) } HILOGI("Begin, callerName is: %{public}s, errCode: %{public}d", callerName.c_str(), errCode); if (session_->OnBundleFileReady(callerName) || errCode != BError(BError::Codes::OK)) { - std::shared_ptr mutexPtr = GetExtensionMutex(callerName); - if (mutexPtr == nullptr) { - HILOGE("extension mutex ptr is nullptr, bundleName:%{public}s", callerName.c_str()); - return BError(BError::Codes::SA_INVAL_ARG); - } - std::lock_guard lock(mutexPtr->callbackMutex); SetExtOnRelease(callerName, true); return BError(BError::Codes::OK); } @@ -1494,6 +1488,7 @@ ErrCode Service::HandleExtDisconnect(BackupRestoreScenario scenario, bool isAppR ErrCode Service::GetExtOnRelease(bool &isExtOnRelease) { + std::shared_lock lock(extOnReleaseLock_); std::string bundleName; auto ret = VerifyCallerAndGetCallerName(bundleName); if (ret != ERR_OK) { @@ -1514,6 +1509,7 @@ ErrCode Service::GetExtOnRelease(bool &isExtOnRelease) void Service::SetExtOnRelease(const BundleName &bundleName, bool isOnRelease) { + std::unique_lock lock(extOnReleaseLock_); HILOGI("Set bundleName:%{public}s isOnRelease:%{public}d", bundleName.c_str(), isOnRelease); auto it = backupExtOnReleaseMap_.find(bundleName); if (it == backupExtOnReleaseMap_.end()) { @@ -1525,6 +1521,7 @@ void Service::SetExtOnRelease(const BundleName &bundleName, bool isOnRelease) void Service::RemoveExtOnRelease(const BundleName &bundleName) { + std::unique_lock lock(extOnReleaseLock_); auto it = backupExtOnReleaseMap_.find(bundleName); if (it == backupExtOnReleaseMap_.end()) { HILOGI("BackupExtOnReleaseMap not contain %{public}s", bundleName.c_str()); -- Gitee From bfd14ca2b06f4c33d97d8e7608b79ea949734bbf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E6=B8=8A?= Date: Fri, 12 Sep 2025 10:05:30 +0800 Subject: [PATCH 12/17] optimize total stat MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 刘渊 --- .../backup_sa/include/module_ipc/service.h | 41 ++-------- services/backup_sa/src/module_ipc/service.cpp | 23 ++---- .../src/module_ipc/service_incremental.cpp | 18 ++--- .../backup_sa/src/module_ipc/sub_service.cpp | 66 ++++++++++++---- .../module_ipc/service_incremental_test.cpp | 30 +++++++ .../backup_sa/module_ipc/service_test.cpp | 78 ++++++++++++++++--- .../backup_utils/b_radar/b_radar_test.cpp | 3 +- utils/include/b_radar/radar_total_statistic.h | 9 +-- utils/src/b_radar/radar_total_statistic.cpp | 10 +-- 9 files changed, 169 insertions(+), 109 deletions(-) diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index a161014eb..001b83d91 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -401,11 +401,6 @@ private: */ void ClearSessionAndSchedInfo(const std::string &bundleName); - /** - * @brief 上报总体统计打点 - */ - void TotalStatReport(ErrCode errCode); - /** * @brief 整个备份恢复流程结束 * @@ -724,37 +719,10 @@ private: void ClearIncrementalStatFile(int32_t userId, const string &bundleName); BJsonCachedEntity CreateJsonEntity(UniqueFd &fd, vector &bundleInfos, const std::vector &bundleNames); - void TotalStart() - { - if (totalStatistic_ != nullptr) { - totalStatistic_->totalSpendTime_.Start(); - } - } - - void GetBundleInfoStart() - { - if (totalStatistic_ != nullptr) { - totalStatistic_->getBundleInfoSpend_.Start(); - } - } - - void GetBundleInfoEnd() - { - if (totalStatistic_ != nullptr) { - totalStatistic_->getBundleInfoSpend_.End(); - } - } - - void UpdateHandleCnt(ErrCode errCode) - { - if (totalStatistic_ != nullptr) { - if (errCode == ERR_OK) { - totalStatistic_->succBundleCount_.fetch_add(1); - } else { - totalStatistic_->failBundleCount_.fetch_add(1); - } - } - } + void TotalStatStart(BizScene bizScene, std::string caller, uint64_t startTime, Mode mode = Mode::FULL); + void TotalStatEnd(ErrCode errCode); + void UpdateHandleCnt(ErrCode errCode); + void TotalStatReport(); private: static sptr instance_; static std::mutex instanceLock_; @@ -790,6 +758,7 @@ private: std::condition_variable getDataSizeCon_; std::atomic isScannedEnd_ {false}; std::atomic onScanning_ {false}; + std::shared_mutex totalStatMutex_; std::shared_ptr totalStatistic_ = nullptr; std::shared_mutex statMapMutex_; std::map> saStatisticMap_; diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 53a258108..d7405aef4 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -470,11 +470,11 @@ ErrCode Service::VerifyCaller(IServiceReverseType::Scenario scenario) ErrCode Service::InitRestoreSession(const sptr &remote) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - totalStatistic_ = std::make_shared(BizScene::RESTORE, GetCallerName()); + Duration totalSpend; + totalSpend.Start(); ErrCode ret = VerifyCaller(); if (ret != ERR_OK) { HILOGE("Init restore session failed, verify caller failed"); - totalStatistic_->Report("InitRestoreSession", MODULE_INIT, ret); return ret; } ret = session_->Active({ @@ -487,13 +487,13 @@ ErrCode Service::InitRestoreSession(const sptr &remote) }); if (ret == ERR_OK) { HILOGE("Success to init a new restore session"); + TotalStatStart(BizScene::RESTORE, GetCallerName(), totalSpend.startMilli_); ClearFailedBundles(); successBundlesNum_ = 0; ClearBundleRadarReport(); ClearFileReadyRadarReport(); return ret; } - totalStatistic_->Report("InitRestoreSession", MODULE_INIT, ret); if (ret == BError(BError::Codes::SA_SESSION_CONFLICT)) { HILOGE("Active restore session error, Already have a session"); return ret; @@ -506,11 +506,11 @@ ErrCode Service::InitRestoreSession(const sptr &remote) ErrCode Service::InitBackupSession(const sptr &remote) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - totalStatistic_ = std::make_shared(BizScene::BACKUP, GetCallerName()); + Duration totalSpend; + totalSpend.Start(); ErrCode ret = VerifyCaller(); if (ret != ERR_OK) { HILOGE("Init full backup session fail, verify caller failed"); - totalStatistic_->Report("InitBackupSession", MODULE_INIT, ret); return ret; } int32_t oldSize = StorageMgrAdapter::UpdateMemPara(BConstants::BACKUP_VFS_CACHE_PRESSURE); @@ -526,13 +526,13 @@ ErrCode Service::InitBackupSession(const sptr &remote) }); if (ret == ERR_OK) { HILOGE("Success to init a new backup session"); + TotalStatStart(BizScene::BACKUP, GetCallerName(), totalSpend.startMilli_); ClearFailedBundles(); successBundlesNum_ = 0; ClearBundleRadarReport(); ClearFileReadyRadarReport(); return ret; } - totalStatistic_->Report("InitBackupSession", MODULE_INIT, ret); if (ret == BError(BError::Codes::SA_SESSION_CONFLICT)) { HILOGE("Active backup session error, Already have a session"); return ret; @@ -586,9 +586,7 @@ vector Service::GetRestoreBundleNames(UniqueFd fd, const vector &bundleNames, std::string &oldBackupVersion) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - GetBundleInfoStart(); auto restoreInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session->GetSessionUserId()); - GetBundleInfoEnd(); BJsonCachedEntity cachedEntity(move(fd)); auto cache = cachedEntity.Structuralize(); oldBackupVersion = cache.GetBackupVersion(); @@ -669,7 +667,6 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, int32_t userId) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - TotalStart(); HILOGI("Begin"); try { if (session_ == nullptr || isOccupyingSession_.load()) { @@ -770,7 +767,6 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, int32_t userId) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - TotalStart(); try { if (session_ == nullptr || isOccupyingSession_.load()) { HILOGE("AppendBundles restore session error, session is empty"); @@ -869,7 +865,6 @@ void Service::SetCurrentSessProperties( ErrCode Service::AppendBundlesBackupSession(const vector &bundleNames) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - TotalStart(); try { if (session_ == nullptr || isOccupyingSession_.load()) { HILOGE("AppendBundles backup session error, session is empty"); @@ -884,10 +879,8 @@ ErrCode Service::AppendBundlesBackupSession(const vector &bundleName return ret; } auto bundleDetails = MakeDetailList(bundleNames); - GetBundleInfoStart(); auto backupInfos = BundleMgrAdapter::GetBundleInfosForAppendBundles(bundleDetails, session_->GetSessionUserId()); - GetBundleInfoEnd(); std::vector supportBackupNames = GetSupportBackupBundleNames(backupInfos, false, bundleNames); AppendBundles(supportBackupNames); SetCurrentBackupSessProperties(supportBackupNames, session_->GetSessionUserId(), backupInfos, false); @@ -911,7 +904,6 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun const vector &bundleInfos) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - TotalStart(); try { if (session_ == nullptr || isOccupyingSession_.load()) { HILOGE("AppendBundles backup session with infos error, session is empty"); @@ -931,10 +923,8 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, session_->GetSessionUserId(), isClearDataFlags); auto bundleDetails = MakeDetailList(bundleNames); - GetBundleInfoStart(); auto backupInfos = BundleMgrAdapter::GetBundleInfosForAppendBundles(bundleDetails, session_->GetSessionUserId()); - GetBundleInfoEnd(); std::vector supportBackupNames = GetSupportBackupBundleNames(backupInfos, false, bundleNames); AppendBundles(supportBackupNames); HandleCurGroupBackupInfos(backupInfos, bundleNameDetailMap, isClearDataFlags); @@ -1504,6 +1494,7 @@ void Service::SessionDeactive() HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGI("Begin"); + TotalStatReport(); isInRelease_.store(true); //清理处置状态 if (session_ == nullptr) { diff --git a/services/backup_sa/src/module_ipc/service_incremental.cpp b/services/backup_sa/src/module_ipc/service_incremental.cpp index b3b33ebc0..172187090 100644 --- a/services/backup_sa/src/module_ipc/service_incremental.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental.cpp @@ -321,11 +321,11 @@ ErrCode Service::GetAppLocalListAndDoIncrementalBackup() ErrCode Service::InitIncrementalBackupSession(const sptr& remote) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - totalStatistic_ = std::make_shared(BizScene::BACKUP, GetCallerName(), Mode::INCREMENTAL); + Duration totalSpend; + totalSpend.Start(); ErrCode errCode = VerifyCaller(); if (errCode != ERR_OK) { HILOGE("Init incremental backup session fail, Verify caller failed, errCode:%{public}d", errCode); - totalStatistic_->Report("InitIncrementalBackupSession", MODULE_INIT, errCode); return errCode; } if (session_ == nullptr) { @@ -341,13 +341,13 @@ ErrCode Service::InitIncrementalBackupSession(const sptr& remot .activeTime = TimeUtils::GetCurrentTime()}); if (errCode == ERR_OK) { HILOGE("Success to init a new incremental backup session"); + TotalStatStart(BizScene::BACKUP, GetCallerName(), totalSpend.startMilli_, Mode::INCREMENTAL); ClearFailedBundles(); successBundlesNum_ = 0; ClearBundleRadarReport(); ClearFileReadyRadarReport(); return errCode; } - totalStatistic_->Report("InitIncrementalBackupSession", MODULE_INIT, errCode); if (errCode == BError(BError::Codes::SA_SESSION_CONFLICT)) { HILOGE("Active incremental backup error, Already have a session"); return errCode; @@ -370,11 +370,11 @@ ErrCode Service::InitIncrementalBackupSessionWithErrMsg(const sptr& remote, std::string &errMsg) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - totalStatistic_ = std::make_shared(BizScene::BACKUP, GetCallerName(), Mode::INCREMENTAL); + Duration totalSpend; + totalSpend.Start(); ErrCode errCode = VerifyCaller(); if (errCode != ERR_OK) { HILOGE("Init incremental backup session fail, Verify caller failed, errCode:%{public}d", errCode); - totalStatistic_->Report("InitIncrementalBackupSessionWithErrMsg", MODULE_INIT, errCode); return errCode; } if (session_ == nullptr) { @@ -389,13 +389,13 @@ ErrCode Service::InitIncrementalBackupSession(const sptr& remot .callerName = GetCallerName(), .activeTime = TimeUtils::GetCurrentTime()}); if (errCode == ERR_OK) { + TotalStatStart(BizScene::BACKUP, GetCallerName(), totalSpend.startMilli_, Mode::INCREMENTAL); ClearFailedBundles(); successBundlesNum_ = 0; ClearBundleRadarReport(); ClearFileReadyRadarReport(); return errCode; } - totalStatistic_->Report("InitIncrementalBackupSessionWithErrMsg", MODULE_INIT, errCode); if (errCode == BError(BError::Codes::SA_SESSION_CONFLICT)) { errMsg = BJsonUtil::BuildInitSessionErrInfo(session_->GetSessionUserId(), session_->GetSessionCallerName(), @@ -420,7 +420,6 @@ vector Service::GetBundleNameByDetails(const std::vector &bundlesToBackup) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - TotalStart(); vector bundleNames; try { if (session_ == nullptr || isOccupyingSession_.load()) { @@ -436,10 +435,8 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vectorDecreaseSessionCnt(__PRETTY_FUNCTION__); return ret; } - GetBundleInfoStart(); auto backupInfos = BundleMgrAdapter::GetBundleInfosForAppendBundles(bundlesToBackup, session_->GetSessionUserId()); - GetBundleInfoEnd(); std::vector supportBackupNames = GetSupportBackupBundleNames(backupInfos, true, bundleNames); AppendBundles(supportBackupNames); SetBundleIncDataInfo(bundlesToBackup, supportBackupNames); @@ -470,7 +467,6 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vector &infos) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - TotalStart(); vector bundleNames; try { if (session_ == nullptr || isOccupyingSession_.load()) { @@ -491,10 +487,8 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vector> bundleNameDetailMap = BJsonUtil::BuildBundleInfos(bundleNames, infos, bundleNamesOnly, session_->GetSessionUserId(), isClearDataFlags); - GetBundleInfoStart(); auto backupInfos = BundleMgrAdapter::GetBundleInfosForAppendBundles(bundlesToBackup, session_->GetSessionUserId()); - GetBundleInfoEnd(); std::vector supportBackupNames = GetSupportBackupBundleNames(backupInfos, true, bundleNames); AppendBundles(supportBackupNames); SetBundleIncDataInfo(bundlesToBackup, supportBackupNames); diff --git a/services/backup_sa/src/module_ipc/sub_service.cpp b/services/backup_sa/src/module_ipc/sub_service.cpp index de1d44c84..18a8c5978 100644 --- a/services/backup_sa/src/module_ipc/sub_service.cpp +++ b/services/backup_sa/src/module_ipc/sub_service.cpp @@ -758,23 +758,13 @@ void Service::NoticeClientFinish(const string &bundleName, ErrCode errCode) } } -void Service::TotalStatReport(ErrCode errCode) -{ - if (totalStatistic_ == nullptr) { - HILOGE("totalStat is null"); - return; - } - totalStatistic_->totalSpendTime_.End(); - totalStatistic_->Report("OnAllBundlesFinished", errCode); -} - void Service::OnAllBundlesFinished(ErrCode errCode) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("called begin."); if (session_->IsOnAllBundlesFinished()) { IServiceReverseType::Scenario scenario = session_->GetScenario(); - TotalStatReport(errCode); + TotalStatEnd(errCode); if (isInRelease_.load() && (scenario == IServiceReverseType::Scenario::RESTORE)) { HILOGI("Will destory session info"); SessionDeactive(); @@ -942,11 +932,11 @@ ErrCode Service::InitRestoreSessionWithErrMsg(const sptr &remot ErrCode Service::InitRestoreSession(const sptr& remote, std::string &errMsg) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - totalStatistic_ = std::make_shared(BizScene::RESTORE, GetCallerName()); + Duration totalSpend; + totalSpend.Start(); ErrCode ret = VerifyCaller(); if (ret != ERR_OK) { HILOGE("Init restore session failed, verify caller failed"); - totalStatistic_->Report("InitRestoreSession", MODULE_INIT, ret); return ret; } ret = session_->Active({ @@ -958,13 +948,13 @@ ErrCode Service::InitRestoreSession(const sptr& remote, std::st .activeTime = TimeUtils::GetCurrentTime(), }); if (ret == ERR_OK) { + TotalStatStart(BizScene::RESTORE, GetCallerName(), totalSpend.startMilli_); ClearFailedBundles(); successBundlesNum_ = 0; ClearBundleRadarReport(); ClearFileReadyRadarReport(); return ret; } - totalStatistic_->Report("InitRestoreSession", MODULE_INIT, ret); if (ret == BError(BError::Codes::SA_SESSION_CONFLICT)) { errMsg = BJsonUtil::BuildInitSessionErrInfo(session_->GetSessionUserId(), session_->GetSessionCallerName(), @@ -990,11 +980,11 @@ ErrCode Service::InitBackupSessionWithErrMsg(const sptr& remote ErrCode Service::InitBackupSession(const sptr& remote, std::string &errMsg) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - totalStatistic_ = std::make_shared(BizScene::BACKUP, GetCallerName()); + Duration totalSpend; + totalSpend.Start(); ErrCode ret = VerifyCaller(); if (ret != ERR_OK) { HILOGE("Init full backup session fail, verify caller failed"); - totalStatistic_->Report("InitBackupSessionWithErrMsg", MODULE_INIT, ret); return ret; } int32_t oldSize = StorageMgrAdapter::UpdateMemPara(BConstants::BACKUP_VFS_CACHE_PRESSURE); @@ -1009,13 +999,13 @@ ErrCode Service::InitBackupSession(const sptr& remote, std::str .activeTime = TimeUtils::GetCurrentTime(), }); if (ret == ERR_OK) { + TotalStatStart(BizScene::BACKUP, GetCallerName(), totalSpend.startMilli_, Mode::INCREMENTAL); ClearFailedBundles(); successBundlesNum_ = 0; ClearBundleRadarReport(); ClearFileReadyRadarReport(); return ret; } - totalStatistic_->Report("InitBackupSessionWithErrMsg", MODULE_INIT, ret); if (ret == BError(BError::Codes::SA_SESSION_CONFLICT)) { errMsg = BJsonUtil::BuildInitSessionErrInfo(session_->GetSessionUserId(), session_->GetSessionCallerName(), @@ -1609,4 +1599,46 @@ void Service::DoNoticeClientFinish(const std::string &bundleName, ErrCode errCod NoticeClientFinish(bundleName, errCode); } } + +void Service::TotalStatStart(BizScene bizScene, std::string caller, uint64_t startTime, Mode mode) +{ + std::unique_lock lock(totalStatMutex_); + totalStatistic_ = std::make_shared(bizScene, caller, mode); + totalStatistic_->totalSpendTime_.startMilli_ = startTime; +} + +void Service::TotalStatEnd(ErrCode errCode) +{ + std::unique_lock lock(totalStatMutex_); + if (totalStatistic_ != nullptr) { + totalStatistic_->totalSpendTime_.End(); + if (errCode != ERROR_OK) { + totalStatistic_->innerErr_ = errCode; + } + } +} + +void Service::UpdateHandleCnt(ErrCode errCode) +{ + std::unique_lock lock(totalStatMutex_); + if (totalStatistic_ != nullptr) { + if (errCode == ERROR_OK) { + totalStatistic_->succBundleCount_++; + } else { + totalStatistic_->failBundleCount_++; + } + } +} + +void Service::TotalStatReport() +{ + std::shared_lock lock(totalStatMutex_); + if (totalStatistic_ == nullptr) { + HILOGE("totalStat is null"); + return; + } + if (totalStatistic_->succBundleCount_ > 0 || totalStatistic_->failBundleCount_ > 0) { + totalStatistic_->Report("OnAllBundlesFinished", totalStatistic_->innerErr_); + } +} } \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp b/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp index 9111b9b55..f1e9c3a0e 100644 --- a/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp @@ -488,6 +488,36 @@ ErrCode Service::GetCompatibilityInfo(const std::string &bundleName, const std:: { return BService::serviceMock->GetCompatibilityInfo(bundleName, extInfo, compatInfo); } + +void Service::TotalStatStart(BizScene bizScene, std::string caller, uint64_t startTime, Mode mode) +{ + std::unique_lock lock(totalStatMutex_); + totalStatistic_ = std::make_shared(bizScene, caller, mode); + totalStatistic_->totalSpendTime_.startMilli_ = startTime; +} + +void Service::TotalStatEnd(ErrCode errCode) +{ + std::unique_lock lock(totalStatMutex_); + if (totalStatistic_ != nullptr) { + totalStatistic_->totalSpendTime_.End(); + if (errCode != ERROR_OK) { + totalStatistic_->innerErr_ = errCode; + } + } +} + +void Service::UpdateHandleCnt(ErrCode errCode) +{ + std::unique_lock lock(totalStatMutex_); + if (totalStatistic_ != nullptr) { + if (errCode == ERROR_OK) { + totalStatistic_->succBundleCount_++; + } else { + totalStatistic_->failBundleCount_++; + } + } +} } // namespace OHOS::FileManagement::Backup namespace OHOS::FileManagement::Backup { diff --git a/tests/unittests/backup_sa/module_ipc/service_test.cpp b/tests/unittests/backup_sa/module_ipc/service_test.cpp index faeb4852c..1057e0070 100644 --- a/tests/unittests/backup_sa/module_ipc/service_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_test.cpp @@ -2573,26 +2573,80 @@ HWTEST_F(ServiceTest, SUB_Service_AppFileReady_0104, testing::ext::TestSize.Leve GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_AppFileReady_0104"; } -HWTEST_F(ServiceTest, Service_Total_Start, testing::ext::TestSize.Level1) +/** + * @tc.number: Service_Total_Start_Test + * @tc.name: Service_Total_Start_Test + * @tc.desc: 测试 TotalStatStart 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(ServiceTest, Service_Total_Start_Test, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin Service_Total_Start_Test"; + servicePtr_->TotalStatStart(BizScene::BACKUP, BUNDLE_NAME, 1); + EXPECT_GT(servicePtr_->totalStatistic_->totalSpendTime_.startMilli_, 0); + GTEST_LOG_(INFO) << "ServiceTest-end Service_Total_Start_Test"; +} + +/** + * @tc.number: Service_Total_Stat_Report_Test + * @tc.name: Service_Total_Stat_Report_Test + * @tc.desc: 测试 TotalStatReport 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(ServiceTest, Service_Total_Stat_Report_Test, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "ServiceTest-begin Service_Total_Start"; + GTEST_LOG_(INFO) << "ServiceTest-begin Service_Total_Stat_Report_Test"; servicePtr_->totalStatistic_ = nullptr; - servicePtr_->TotalStart(); + servicePtr_->TotalStatReport(); servicePtr_->totalStatistic_ = totalStat_; - servicePtr_->TotalStart(); - EXPECT_GT(totalStat_->totalSpendTime_.startMilli_, 0); - GTEST_LOG_(INFO) << "ServiceTest-end Service_Total_Start"; + servicePtr_->TotalStatReport(); + EXPECT_GT(totalStat_->uniqId_, 0); + GTEST_LOG_(INFO) << "ServiceTest-end Service_Total_Stat_Report_Test"; } -HWTEST_F(ServiceTest, Service_Total_Stat_Report, testing::ext::TestSize.Level1) +/** + * @tc.number: Service_Total_Stat_End_Test + * @tc.name: Service_Total_Stat_End_Test + * @tc.desc: 测试 TotalStatEnd 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(ServiceTest, Service_Total_Stat_End_Test, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "ServiceTest-begin Service_Total_Stat_Report"; + GTEST_LOG_(INFO) << "ServiceTest-begin Service_Total_Stat_End_Test"; servicePtr_->totalStatistic_ = nullptr; - servicePtr_->TotalStatReport(ERR_OK); + servicePtr_->TotalStatEnd(0); servicePtr_->totalStatistic_ = totalStat_; - servicePtr_->TotalStatReport(ERR_OK); - EXPECT_GT(totalStat_->totalSpendTime_.endMilli_, 0); - GTEST_LOG_(INFO) << "ServiceTest-end Service_Total_Stat_Report"; + servicePtr_->TotalStatEnd(0); + EXPECT_EQ(totalStat_->innerErr_, 0); + servicePtr_->TotalStatEnd(1); + EXPECT_EQ(totalStat_->innerErr_, 1); + GTEST_LOG_(INFO) << "ServiceTest-end Service_Total_Stat_End_Test"; } +/** + * @tc.number: Service_Update_Handle_Count_Test + * @tc.name: Service_Update_Handle_Count_Test + * @tc.desc: 测试 UpdateHandleCnt 接口 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + */ +HWTEST_F(ServiceTest, Service_Update_Handle_Count_Test, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceTest-begin Service_Update_Handle_Count_Test"; + servicePtr_->totalStatistic_ = nullptr; + servicePtr_->UpdateHandleCnt(0); + servicePtr_->totalStatistic_ = totalStat_; + servicePtr_->UpdateHandleCnt(0); + EXPECT_EQ(totalStat_->succBundleCount_, 1); + servicePtr_->UpdateHandleCnt(1); + EXPECT_EQ(totalStat_->failBundleCount_, 1); + GTEST_LOG_(INFO) << "ServiceTest-end Service_Update_Handle_Count_Test"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_radar/b_radar_test.cpp b/tests/unittests/backup_utils/b_radar/b_radar_test.cpp index 17947b793..4156cdc8d 100644 --- a/tests/unittests/backup_utils/b_radar/b_radar_test.cpp +++ b/tests/unittests/backup_utils/b_radar/b_radar_test.cpp @@ -104,11 +104,10 @@ HWTEST_F(BRadarTest, TOTAL_CONSTRUCTOR_0100, testing::ext::TestSize.Level1) EXPECT_EQ(totalStatistic1.hostPkg_, caller); EXPECT_GT(totalStatistic1.uniqId_, 0); EXPECT_EQ(totalStatistic1.uniqId_, totalStatistic1.GetUniqId()); - int64_t uniqId1 = totalStatistic1.uniqId_; RadarTotalStatistic totalStatistic2(BizScene::RESTORE, caller); EXPECT_EQ(totalStatistic2.bizScene_, BizScene::RESTORE); EXPECT_EQ(totalStatistic2.mode_, Mode::FULL); - EXPECT_NE(uniqId1, totalStatistic2.uniqId_); + EXPECT_GT(totalStatistic2.uniqId_, 0); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "BRadarTest-an exception occurred."; diff --git a/utils/include/b_radar/radar_total_statistic.h b/utils/include/b_radar/radar_total_statistic.h index 22d4824d7..9f0ce3138 100644 --- a/utils/include/b_radar/radar_total_statistic.h +++ b/utils/include/b_radar/radar_total_statistic.h @@ -25,10 +25,10 @@ namespace OHOS::FileManagement::Backup { class RadarTotalStatistic { public: - std::atomic succBundleCount_ = 0; - std::atomic failBundleCount_ = 0; - Duration getBundleInfoSpend_ = {0, 0}; + uint32_t succBundleCount_ = 0; + uint32_t failBundleCount_ = 0; Duration totalSpendTime_ = {0, 0}; + int innerErr_ = 0; RadarTotalStatistic(BizScene bizScene, std::string caller, Mode mode = Mode::FULL); RadarTotalStatistic(const RadarTotalStatistic &) = delete; @@ -48,9 +48,6 @@ private: std::string hostPkg_ = ""; Mode mode_ = Mode::FULL; int64_t uniqId_ = 0; - std::mutex lastCntMutex_; - uint32_t lastSuccCnt_ = 0; - uint32_t lastFailCnt_ = 0; }; } // namespace OHOS::FileManagement::Backup #endif // OHOS_FILEMGMT_BACKUP_RADAR_TOTAL_STATISTIC_H diff --git a/utils/src/b_radar/radar_total_statistic.cpp b/utils/src/b_radar/radar_total_statistic.cpp index 87035f4a5..d89db4c1c 100644 --- a/utils/src/b_radar/radar_total_statistic.cpp +++ b/utils/src/b_radar/radar_total_statistic.cpp @@ -29,17 +29,13 @@ RadarTotalStatistic::RadarTotalStatistic(BizScene bizScene, std::string callerNa void RadarTotalStatistic::Report(const std::string &func, int32_t error, std::string errMsg) { - std::lock_guard lastCntLock(lastCntMutex_); - uint32_t succCount = succBundleCount_.load(); - uint32_t failCount = failBundleCount_.load(); HiSysEventWrite( DOMAIN, BACKUP_RESTORE_STATISTIC, OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR, - GET_BUNDLE_INFO_SPEND, getBundleInfoSpend_.GetSpan(), TOTAL_SPEND, totalSpendTime_.GetSpan(), - SUCC_BUNDLE_CNT, succCount - lastSuccCnt_, - FAIL_BUNDLE_CNT, failCount - lastFailCnt_, + SUCC_BUNDLE_CNT, succBundleCount_, + FAIL_BUNDLE_CNT, failBundleCount_, ORG_PKG, DOMAIN_NAME, FUNC, func, CONCURRENT_ID, uniqId_, @@ -50,8 +46,6 @@ void RadarTotalStatistic::Report(const std::string &func, int32_t error, std::st ERROR_CODE, error, BIZ_STAGE, DEFAULT_STAGE, STAGE_RES, error == 0 ? STAGE_RES_SUCCESS : STAGE_RES_FAIL); - lastSuccCnt_ = succCount; - lastFailCnt_ = failCount; } void RadarTotalStatistic::Report(const std::string &func, uint32_t moduleId, uint32_t moduleErr) -- Gitee From d52ae3a8ec37f68a021887ffa020f5b60de7240c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E6=B8=8A?= Date: Fri, 12 Sep 2025 10:39:06 +0800 Subject: [PATCH 13/17] fix code sytle problem MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: 刘渊 --- services/backup_sa/src/module_ipc/service.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index d7405aef4..dec015f50 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -1542,7 +1542,6 @@ void Service::SessionDeactive() } } catch (...) { HILOGE("Unexpected exception"); - return; } } -- Gitee From f5ed61234b0109bd2e3e50cac3d314e3bea885b6 Mon Sep 17 00:00:00 2001 From: lizhengxing Date: Thu, 28 Aug 2025 09:43:53 +0800 Subject: [PATCH 14/17] dh broadcast Signed-off-by: lizhengxing --- .../backup_sa/include/module_ipc/service.h | 14 +++++ .../module_notify/notify_work_service.h | 8 ++- services/backup_sa/src/module_ipc/service.cpp | 40 +++++++++---- .../src/module_ipc/service_incremental.cpp | 2 + .../backup_sa/src/module_ipc/sub_service.cpp | 58 +++++++++++++++++++ .../src/module_notify/notify_work_service.cpp | 8 ++- .../include/notify_work_service_mock.h | 6 +- tests/mock/module_ipc/service_mock.cpp | 8 +++ .../src/notify_work_service_mock.cpp | 4 +- .../module_ipc/service_incremental_test.cpp | 23 ++++++++ .../module_ipc/service_other_test.cpp | 2 +- utils/include/b_jsonutil/b_jsonutil.h | 15 +++++ utils/include/b_resources/b_constants.h | 4 ++ utils/src/b_jsonutil/b_jsonutil.cpp | 26 +++++++++ 14 files changed, 198 insertions(+), 20 deletions(-) diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index 359b50880..1138aa437 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -45,6 +45,11 @@ struct BundleTaskInfo { std::string reportTime; ErrCode errCode; }; + +struct BundleBroadCastInfo { + std::map broadCastInfoMap = {}; + int userId = 0; +}; const int INVALID_FD = -1; constexpr const int32_t CONNECT_WAIT_TIME_S = 15; @@ -724,6 +729,14 @@ private: void ClearIncrementalStatFile(int32_t userId, const string &bundleName); BJsonCachedEntity CreateJsonEntity(UniqueFd &fd, vector &bundleInfos, const std::vector &bundleNames); + void SetBundleParam(const BJsonEntityCaps::BundleInfo &restoreInfo, std::string &bundleNameIndexInfo, + RestoreTypeEnum &restoreType); + void ClearRecord(); + void SetBroadCastInfoMap(const std::string &bundleName, + const std::map &broadCastInfoMap, + int userId); + void BroadCastRestore(const std::string &bundleName, const std::string &broadCastType); + void BroadCastSingle(const std::string &bundleName, const std::string &broadCastType); void TotalStart() { if (totalStatistic_ != nullptr) { @@ -794,6 +807,7 @@ private: std::shared_mutex statMapMutex_; std::map> saStatisticMap_; std::map> backupExtOnReleaseMap_; + std::map bundleBroadCastInfoMap_; public: std::map> backupExtMutexMap_; std::map failedBundles_; diff --git a/services/backup_sa/include/module_notify/notify_work_service.h b/services/backup_sa/include/module_notify/notify_work_service.h index c4bb9b749..c27b14503 100644 --- a/services/backup_sa/include/module_notify/notify_work_service.h +++ b/services/backup_sa/include/module_notify/notify_work_service.h @@ -22,10 +22,16 @@ #include "b_jsonutil/b_jsonutil.h" namespace OHOS::FileManagement::Backup { + +enum BroadCastType { + START_TYPE = 0, + END_TYPE = 1, +}; + class NotifyWorkService final : public NoCopyable { DECLARE_DELAYED_SINGLETON(NotifyWorkService); public: - bool NotifyBundleDetail(BJsonUtil::BundleDetailInfo bundleDetailInfo); + bool NotifyBundleDetail(BJsonUtil::BundleDetailInfo bundleDetailInfo, BroadCastType type); }; } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 44ce7919c..00abef2ad 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -840,27 +840,28 @@ void Service::SetCurrentSessProperties( session_->RemoveExtInfo(bundleNameIndexInfo); continue; } - session_->SetBundleRestoreType(bundleNameIndexInfo, restoreType); - session_->SetBundleVersionCode(bundleNameIndexInfo, restoreInfo.versionCode); - session_->SetBundleVersionName(bundleNameIndexInfo, restoreInfo.versionName); - session_->SetBundleDataSize(bundleNameIndexInfo, restoreInfo.spaceOccupied); - session_->SetBundleUserId(bundleNameIndexInfo, session_->GetSessionUserId()); + SetBundleParam(restoreInfo, bundleNameIndexInfo, restoreType); auto iter = isClearDataFlags.find(bundleNameIndexInfo); if (iter != isClearDataFlags.end()) { session_->SetClearDataFlag(bundleNameIndexInfo, iter->second); } BJsonUtil::BundleDetailInfo broadCastInfo; BJsonUtil::BundleDetailInfo uniCastInfo; - if (BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, BROADCAST_TYPE, broadCastInfo)) { - bool notifyRet = DelayedSingleton::GetInstance()->NotifyBundleDetail(broadCastInfo); + std::map broadCastInfoMap; + if (BJsonUtil::FindBroadCastInfoByName(bundleNameDetailMap, bundleNameIndexInfo, + BROADCAST_TYPE, broadCastInfoMap)) { + SetBroadCastInfoMap(bundleNameIndexInfo, broadCastInfoMap, session_->GetSessionUserId()); + BroadCastRestore(bundleNameIndexInfo, BConstants::BROADCAST_RESTORE_START); + } else if (BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, + BROADCAST_TYPE, broadCastInfo)) { + bool notifyRet = DelayedSingleton::GetInstance()->NotifyBundleDetail( + broadCastInfo, START_TYPE); HILOGI("Publish event end, notify result is:%{public}d", notifyRet); } if (BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, UNICAST_TYPE, uniCastInfo)) { HILOGI("current bundle, unicast info:%{public}s", GetAnonyString(uniCastInfo.detail).c_str()); session_->SetBackupExtInfo(bundleNameIndexInfo, uniCastInfo.detail); } - session_->SetBackupExtName(bundleNameIndexInfo, restoreInfo.extensionName); - session_->SetIsReadyLaunch(bundleNameIndexInfo); } HILOGI("End"); } @@ -1507,6 +1508,7 @@ void Service::SessionDeactive() return; } ErrCode ret = BError(BError::Codes::OK); + BroadCastRestore(BConstants::BROADCAST_RELEASE_BUNDLES, BConstants::BROADCAST_RESTORE_END); std::vector bundleNameList; if (session_->GetScenario() == IServiceReverseType::Scenario::RESTORE && session_->CleanAndCheckIfNeedWait(ret, bundleNameList)) { @@ -1522,8 +1524,7 @@ void Service::SessionDeactive() if (!bundleNameList.empty()) { DelClearBundleRecord(bundleNameList); } - SendErrAppGalleryNotify(); - DeleteDisConfigFile(); + ClearRecord(); // 结束定时器 if (sched_ == nullptr) { HILOGE("Session deactive error, sched is empty"); @@ -2091,4 +2092,21 @@ void Service::SetUserIdAndRestoreType(RestoreTypeEnum restoreType, int32_t userI session_->SetSessionUserId(GetUserIdDefault()); } } + +void Service::SetBundleParam(const BJsonEntityCaps::BundleInfo &restoreInfo, std::string &bundleNameIndexInfo, + RestoreTypeEnum &restoreType) +{ + session_->SetBundleRestoreType(bundleNameIndexInfo, restoreType); + session_->SetBundleVersionCode(bundleNameIndexInfo, restoreInfo.versionCode); + session_->SetBundleVersionName(bundleNameIndexInfo, restoreInfo.versionName); + session_->SetBundleDataSize(bundleNameIndexInfo, restoreInfo.spaceOccupied); + session_->SetBackupExtName(bundleNameIndexInfo, restoreInfo.extensionName); + session_->SetIsReadyLaunch(bundleNameIndexInfo); +} + +void Service::ClearRecord() +{ + SendErrAppGalleryNotify(); + DeleteDisConfigFile(); +} } // 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 1b478b103..22c1e0886 100644 --- a/services/backup_sa/src/module_ipc/service_incremental.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental.cpp @@ -51,6 +51,7 @@ #include "module_external/bms_adapter.h" #include "module_ipc/svc_backup_connection.h" #include "module_ipc/svc_restore_deps_manager.h" +#include "module_notify/notify_work_service.h" #include "parameter.h" #include "system_ability_definition.h" #include "hitrace_meter.h" @@ -1107,6 +1108,7 @@ ErrCode Service::Cancel(const std::string& bundleName, int32_t &result) HILOGE("Verify caller failed, bundleName:%{public}s, scenario:%{public}d", bundleName.c_str(), scenario); return BError(BError::BackupErrorCode::E_CANCEL_UNSTARTED_TASK); } + BroadCastRestore(bundleName, BConstants::BROADCAST_RESTORE_END); auto impl = session_->GetImpl(); auto it = impl.backupExtNameMap.find(bundleName); if (it == impl.backupExtNameMap.end()) { diff --git a/services/backup_sa/src/module_ipc/sub_service.cpp b/services/backup_sa/src/module_ipc/sub_service.cpp index 51a6b972b..a3025deca 100644 --- a/services/backup_sa/src/module_ipc/sub_service.cpp +++ b/services/backup_sa/src/module_ipc/sub_service.cpp @@ -1607,4 +1607,62 @@ void Service::DoNoticeClientFinish(const std::string &bundleName, ErrCode errCod NoticeClientFinish(bundleName, errCode); } } + +void Service::SetBroadCastInfoMap(const std::string &bundleName, + const std::map &broadCastInfoMap, + int userId) +{ + if (bundleName == "") { + HILOGE("bundleName empty!"); + return; + } + bundleBroadCastInfoMap_[bundleName].broadCastInfoMap = broadCastInfoMap; + bundleBroadCastInfoMap_[bundleName].userId = userId; + return; +} + +void Service::BroadCastRestore(const std::string &bundleName, const std::string &broadCastType) +{ + if (bundleBroadCastInfoMap_.empty()) { + HILOGD("bundleBroadCastInfoMap_ empty, BroadCastRestore fail"); + return; + } + if (bundleName == BConstants::BROADCAST_RELEASE_BUNDLES && + session_->GetScenario() == IServiceReverseType::Scenario::RESTORE) { + for (auto item : bundleBroadCastInfoMap_) { + BroadCastSingle(item.first, broadCastType); + } + return; + } + if (bundleBroadCastInfoMap_.count(bundleName) == 0) { + HILOGE("%{public}s not found in bundleBroadCastInfoMap_", bundleName.c_str()); + return; + } + BroadCastSingle(bundleName, broadCastType); + return; +} + +void Service::BroadCastSingle(const std::string &bundleName, const std::string &broadCastType) +{ + std::map broadCastInfoMap; + broadCastInfoMap = bundleBroadCastInfoMap_[bundleName].broadCastInfoMap; + if (broadCastInfoMap.count(broadCastType) && session_->GetScenario() == IServiceReverseType::Scenario::RESTORE) { + // 分身应用 + BJsonUtil::BundleDetailInfo broadCastInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName); + broadCastInfo.bundleName = broadCastInfo.bundleName; + broadCastInfo.userId = bundleBroadCastInfoMap_[bundleName].userId; + broadCastInfo.bundleIndex = broadCastInfo.bundleIndex; + broadCastInfo.detail = broadCastInfoMap[broadCastType]; + bool notifyRet; + if (broadCastType == BConstants::BROADCAST_RESTORE_START) { + notifyRet = DelayedSingleton::GetInstance()->NotifyBundleDetail( + broadCastInfo, START_TYPE); + } else { + notifyRet = DelayedSingleton::GetInstance()->NotifyBundleDetail( + broadCastInfo, END_TYPE); + } + HILOGI("Publish event end, notify result is:%{public}d, broadCastType:%{public}s", + notifyRet, broadCastType.c_str()); + } +} } \ No newline at end of file diff --git a/services/backup_sa/src/module_notify/notify_work_service.cpp b/services/backup_sa/src/module_notify/notify_work_service.cpp index f9e403a22..b43838da0 100644 --- a/services/backup_sa/src/module_notify/notify_work_service.cpp +++ b/services/backup_sa/src/module_notify/notify_work_service.cpp @@ -28,7 +28,7 @@ namespace OHOS::FileManagement::Backup { NotifyWorkService::NotifyWorkService() {} NotifyWorkService::~NotifyWorkService() {} -bool NotifyWorkService::NotifyBundleDetail(BJsonUtil::BundleDetailInfo bundleDetailInfo) +bool NotifyWorkService::NotifyBundleDetail(BJsonUtil::BundleDetailInfo bundleDetailInfo, BroadCastType type) { AAFwk::Want want; std::string bundleName = bundleDetailInfo.bundleName; @@ -40,7 +40,11 @@ bool NotifyWorkService::NotifyBundleDetail(BJsonUtil::BundleDetailInfo bundleDet want.SetParam("userId", bundleDetailInfo.userId); want.SetParam("index", bundleDetailInfo.bundleIndex); want.SetParam("detail", bundleDetail); - want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_RESTORE_START); + if (type == END_TYPE) { + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_RESTORE_END); + } else { + want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_RESTORE_START); + } EventFwk::CommonEventData commonData {want}; HILOGI("End publish event, bundleName is: %{public}s", bundleName.c_str()); return EventFwk::CommonEventManager::PublishCommonEvent(commonData); diff --git a/tests/mock/module_ipc/include/notify_work_service_mock.h b/tests/mock/module_ipc/include/notify_work_service_mock.h index 522a08e7c..de46c859e 100644 --- a/tests/mock/module_ipc/include/notify_work_service_mock.h +++ b/tests/mock/module_ipc/include/notify_work_service_mock.h @@ -18,12 +18,12 @@ #include -#include "notify_work_service.h" +#include "module_notify/notify_work_service.h" namespace OHOS::FileManagement::Backup { class BNotifyWorkService { public: - virtual bool NotifyBundleDetail(BJsonUtil::BundleDetailInfo) = 0; + virtual bool NotifyBundleDetail(BJsonUtil::BundleDetailInfo, BroadCastType type) = 0; public: BNotifyWorkService() = default; virtual ~BNotifyWorkService() = default; @@ -33,7 +33,7 @@ public: class NotifyWorkServiceMock : public BNotifyWorkService { public: - MOCK_METHOD(bool, NotifyBundleDetail, (BJsonUtil::BundleDetailInfo)); + MOCK_METHOD(bool, NotifyBundleDetail, (BJsonUtil::BundleDetailInfo, BroadCastType)); }; } // namespace OHOS::FileManagement::Backup #endif // OHOS_FILEMGMT_BACKUP_NOTIFY_WORK_SERVICE_MOCK_H \ No newline at end of file diff --git a/tests/mock/module_ipc/service_mock.cpp b/tests/mock/module_ipc/service_mock.cpp index 735762b18..ce6398b50 100644 --- a/tests/mock/module_ipc/service_mock.cpp +++ b/tests/mock/module_ipc/service_mock.cpp @@ -458,4 +458,12 @@ ErrCode Service::GetCompatibilityInfo(const std::string &bundleName, const std:: } void Service::DoNoticeClientFinish(const std::string &bundleName, ErrCode errCode, bool isRestoreEnd) {} + +void Service::SetBroadCastInfoMap(const std::string &bundleName, + const std::map &broadCastInfoMap, + int userId) {} + +void Service::BroadCastRestore(const std::string &bundleName, const std::string &broadCastType) {} + +void Service::BroadCastSingle(const std::string &bundleName, const std::string &broadCastType) {} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/src/notify_work_service_mock.cpp b/tests/mock/module_ipc/src/notify_work_service_mock.cpp index e802517a6..84588312e 100644 --- a/tests/mock/module_ipc/src/notify_work_service_mock.cpp +++ b/tests/mock/module_ipc/src/notify_work_service_mock.cpp @@ -22,8 +22,8 @@ NotifyWorkService::NotifyWorkService() {} NotifyWorkService::~NotifyWorkService() {} -bool NotifyWorkService::NotifyBundleDetail(BJsonUtil::BundleDetailInfo bundleDetailInfo) +bool NotifyWorkService::NotifyBundleDetail(BJsonUtil::BundleDetailInfo bundleDetailInfo, BroadCastType type) { - return BNotifyWorkService::notify->NotifyBundleDetail(bundleDetailInfo); + return BNotifyWorkService::notify->NotifyBundleDetail(bundleDetailInfo, type); } } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp b/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp index 9111b9b55..26e4effca 100644 --- a/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp @@ -84,6 +84,11 @@ public: virtual void SetExtOnRelease(const BundleName&, bool) = 0; virtual void RemoveExtOnRelease(const BundleName&) = 0; virtual ErrCode GetCompatibilityInfo(const std::string&, const std::string&, std::string&) = 0; + virtual void SetBroadCastInfoMap(const std::string &bundleName, + const std::map &broadCastInfoMap, + int userId) = 0; + virtual void BroadCastRestore(const std::string &bundleName, const std::string &broadCastType) = 0; + virtual void BroadCastSingle(const std::string &bundleName, const std::string &broadCastType) = 0; public: virtual bool UpdateToRestoreBundleMap(const string&, const string&) = 0; public: @@ -145,6 +150,9 @@ public: MOCK_METHOD(void, SetExtOnRelease, (const BundleName&, bool)); MOCK_METHOD(void, RemoveExtOnRelease, (const BundleName&)); MOCK_METHOD(ErrCode, GetCompatibilityInfo, (const std::string&, const std::string&, std::string&)); + MOCK_METHOD(void, SetBroadCastInfoMap, (const std::string &, (const std::map &), int)); + MOCK_METHOD(void, BroadCastRestore, (const std::string &, const std::string &)); + MOCK_METHOD(void, BroadCastSingle, (const std::string &, const std::string &)); public: MOCK_METHOD(bool, UpdateToRestoreBundleMap, (const string&, const string&)); }; @@ -488,6 +496,21 @@ ErrCode Service::GetCompatibilityInfo(const std::string &bundleName, const std:: { return BService::serviceMock->GetCompatibilityInfo(bundleName, extInfo, compatInfo); } + +void Service::SetBroadCastInfoMap(const std::string &bundleName, + const std::map &broadCastInfoMap, + int userId) +{ + BService::serviceMock->SetBroadCastInfoMap(bundleName, broadCastInfoMap, userId); +} +void Service::BroadCastRestore(const std::string &bundleName, const std::string &broadCastType) +{ + BService::serviceMock->BroadCastRestore(bundleName, broadCastType); +} +void Service::BroadCastSingle(const std::string &bundleName, const std::string &broadCastType) +{ + BService::serviceMock->BroadCastSingle(bundleName, broadCastType); +} } // namespace OHOS::FileManagement::Backup namespace OHOS::FileManagement::Backup { diff --git a/tests/unittests/backup_sa/module_ipc/service_other_test.cpp b/tests/unittests/backup_sa/module_ipc/service_other_test.cpp index 5cace8b41..023da0a56 100644 --- a/tests/unittests/backup_sa/module_ipc/service_other_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_other_test.cpp @@ -1063,7 +1063,7 @@ HWTEST_F(ServiceTest, SUB_Service_SetCurrentSessProperties_0300, TestSize.Level1 EXPECT_CALL(*jsonUtil, BuildBundleNameIndexInfo(_, _)).WillOnce(Return("bundleName")) .WillOnce(Return("bundleName")); EXPECT_CALL(*jsonUtil, FindBundleInfoByName(_, _, _, _)).WillOnce(Return(true)).WillOnce(Return(false)); - EXPECT_CALL(*notify, NotifyBundleDetail(_)).WillOnce(Return(true)); + EXPECT_CALL(*notify, NotifyBundleDetail(_, _)).WillOnce(Return(true)); service->SetCurrentSessProperties(restoreBundleInfos, restoreBundleNames, bundleNameDetailMap, isClearDataFlags, restoreType, backupVersion); diff --git a/utils/include/b_jsonutil/b_jsonutil.h b/utils/include/b_jsonutil/b_jsonutil.h index 2e19abdca..e15583e89 100644 --- a/utils/include/b_jsonutil/b_jsonutil.h +++ b/utils/include/b_jsonutil/b_jsonutil.h @@ -24,6 +24,7 @@ class BJsonUtil { public: typedef struct BundleDetailInfo { std::string backupScene; + std::string broadCastType; std::string bundleName; std::string type; std::string detail; @@ -201,6 +202,7 @@ public: size_t listSize, std::string scanning, std::string &jsonStr); + /** * @brief 通过bundlename找sceneId * @@ -212,6 +214,19 @@ public: */ static bool FindBackupSceneByName(std::map> &bundleNameDetailsMap, std::string &bundleName, std::string &backupScene); + + /** + * @brief 通过bundlename找BroadCastInfo + * + * @param bundleNameDetailsMap 包名和当前包扩展信息解析结果的集合 + * @param bundleName 包名 + * @param jobType 业务类型broadcast或者unicast + * @param broadCastInfoMap 存储broadCastInfoMap的变量 + * + * @return 是否成功 + */ + static bool FindBroadCastInfoByName(std::map> &bundleNameDetailsMap, + std::string &bundleName, const std::string &jobType, std::map &broadCastInfoMap); }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/include/b_resources/b_constants.h b/utils/include/b_resources/b_constants.h index f78eaf4cc..68d6bff29 100644 --- a/utils/include/b_resources/b_constants.h +++ b/utils/include/b_resources/b_constants.h @@ -215,6 +215,9 @@ static inline std::string BACKUP_SCENE = "backupScene"; static inline std::string OPTION_DIR = "optionDir"; static inline std::string INCLUDES = "includes"; static inline std::string EXCLUDES = "excludes"; +static inline std::string BROADCAST_RESTORE_START = "restore_start"; +static inline std::string BROADCAST_RESTORE_END = "restore_end"; +static inline std::string BROADCAST_RELEASE_BUNDLES = "release_bundles"; static inline int DEFAULT_APPINDEX = 0; // 特殊版本信息 @@ -254,6 +257,7 @@ static inline std::string PRIORITY = "priority"; // unicast const std::string UNICAST_TYPE = "unicast"; +const std::string BROADCAST_TYPE = "broadcast"; // 雷达打点引用到的常量 constexpr int32_t MS_1000 = 1000; diff --git a/utils/src/b_jsonutil/b_jsonutil.cpp b/utils/src/b_jsonutil/b_jsonutil.cpp index ce3c1a889..a4dd4583d 100644 --- a/utils/src/b_jsonutil/b_jsonutil.cpp +++ b/utils/src/b_jsonutil/b_jsonutil.cpp @@ -221,6 +221,13 @@ static void InsertBundleDetailInfo(cJSON *infos, int infosCount, } char *detailInfos = cJSON_Print(details); bundleDetailInfo.detail = std::string(detailInfos); + if (bundleDetailInfo.type.compare(BConstants::BROADCAST_TYPE) == 0) { + cJSON *broadCastType = cJSON_GetObjectItem(infoItem, "broadcastType"); + if (broadCastType != nullptr && cJSON_IsString(broadCastType) && (broadCastType->valuestring != nullptr)) { + HILOGI("Parse broadCastType success"); + bundleDetailInfo.broadCastType = broadCastType->valuestring; + } + } bundleDetails.emplace_back(bundleDetailInfo); cJSON_free(detailInfos); } @@ -555,4 +562,23 @@ bool BJsonUtil::FindBackupSceneByName(std::map> &bundleNameDetailsMap, + std::string &bundleName, const std::string &jobType, std::map &broadCastInfoMap) +{ + auto iter = bundleNameDetailsMap.find(bundleName); + if (iter == bundleNameDetailsMap.end()) { + return false; + } + std::vector bundleDetailInfos = iter->second; + for (const auto &bundleDetailInfo : bundleDetailInfos) { + if (bundleDetailInfo.type == jobType && bundleDetailInfo.broadCastType != "") { + broadCastInfoMap[bundleDetailInfo.broadCastType] = bundleDetailInfo.detail; + } + } + if (broadCastInfoMap.empty()) { + return false; + } + return true; +} } \ No newline at end of file -- Gitee From 9987b3f13c0fff260fec97d028124b71e50a0b7a Mon Sep 17 00:00:00 2001 From: lizhengxing Date: Sat, 13 Sep 2025 03:43:52 +0000 Subject: [PATCH 15/17] static-check Signed-off-by: lizhengxing --- .../backup_sa/module_ipc/service_incremental_test.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp b/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp index a0ac96a85..642013783 100644 --- a/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_incremental_test.cpp @@ -498,8 +498,8 @@ ErrCode Service::GetCompatibilityInfo(const std::string &bundleName, const std:: } void Service::SetBroadCastInfoMap(const std::string &bundleName, - const std::map &broadCastInfoMap, - int userId) + const std::map &broadCastInfoMap, + int userId) { BService::serviceMock->SetBroadCastInfoMap(bundleName, broadCastInfoMap, userId); } -- Gitee From f38c061930db8a2c6f12a53b5a4c831360310b85 Mon Sep 17 00:00:00 2001 From: lizhengxing Date: Sat, 13 Sep 2025 06:36:31 +0000 Subject: [PATCH 16/17] modity Signed-off-by: lizhengxing --- services/backup_sa/src/module_ipc/sub_service.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/backup_sa/src/module_ipc/sub_service.cpp b/services/backup_sa/src/module_ipc/sub_service.cpp index ea4c179ca..351db9aae 100644 --- a/services/backup_sa/src/module_ipc/sub_service.cpp +++ b/services/backup_sa/src/module_ipc/sub_service.cpp @@ -1621,7 +1621,7 @@ void Service::BroadCastRestore(const std::string &bundleName, const std::string } if (bundleName == BConstants::BROADCAST_RELEASE_BUNDLES && session_->GetScenario() == IServiceReverseType::Scenario::RESTORE) { - for (auto item : bundleBroadCastInfoMap_) { + for (const auto &item : bundleBroadCastInfoMap_) { BroadCastSingle(item.first, broadCastType); } return; @@ -1641,7 +1641,6 @@ void Service::BroadCastSingle(const std::string &bundleName, const std::string & if (broadCastInfoMap.count(broadCastType) && session_->GetScenario() == IServiceReverseType::Scenario::RESTORE) { // 分身应用 BJsonUtil::BundleDetailInfo broadCastInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName); - broadCastInfo.bundleName = broadCastInfo.bundleName; broadCastInfo.userId = bundleBroadCastInfoMap_[bundleName].userId; broadCastInfo.bundleIndex = broadCastInfo.bundleIndex; broadCastInfo.detail = broadCastInfoMap[broadCastType]; -- Gitee From b065fdcbe2c13ce3bf5fbe73d274ff6a4aa02498 Mon Sep 17 00:00:00 2001 From: lizhengxing Date: Sat, 13 Sep 2025 06:43:26 +0000 Subject: [PATCH 17/17] ADD Signed-off-by: lizhengxing --- services/backup_sa/src/module_ipc/service.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 8c2dfd2a9..d946a8fac 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -2094,6 +2094,7 @@ void Service::SetBundleParam(const BJsonEntityCaps::BundleInfo &restoreInfo, std session_->SetBundleVersionCode(bundleNameIndexInfo, restoreInfo.versionCode); session_->SetBundleVersionName(bundleNameIndexInfo, restoreInfo.versionName); session_->SetBundleDataSize(bundleNameIndexInfo, restoreInfo.spaceOccupied); + session_->SetBundleUserId(bundleNameIndexInfo, session_->GetSessionUserId()); session_->SetBackupExtName(bundleNameIndexInfo, restoreInfo.extensionName); session_->SetIsReadyLaunch(bundleNameIndexInfo); } -- Gitee