diff --git a/frameworks/native/backup_ext/include/ext_backup.h b/frameworks/native/backup_ext/include/ext_backup.h index b5fcd46650b3dd5e02d1f0cd39c8a36ec8c5cedc..ff9b95ccbac8e0c4bd4b99072bea562c6ddbb0a5 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 0d9164788e849429a31ee8785645bf789e0bab75..8df461ec1b0818601df793812ef2c3f5815a5531 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 304936753ad19eec1f1eb14374dd82b2bdd1c6de..b11b3e4201c940532e00a9839c5140532b3fdde4 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."); @@ -175,7 +185,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 f931cbb4415f7627f1ee201b572ebf52883baf3c..b601055620cc1d8b7004aba9ef3b9336bee80176 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); @@ -2074,6 +2073,8 @@ ErrCode BackupExtExtension::IncrementalTarFileReady(const TarMap &bigFileInfo, } else { HILOGE("IncrementalTarFileReady interface fails to be invoked: %{public}d", ret); } + close(fd); + close(manifestFd); return ret; } @@ -2173,25 +2174,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 59203d07e43ed5d295f6f075e57352750c8cc625..6a48cf91bf81141a5b4d49f33fca5d59efad0fdf 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(); @@ -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"); @@ -1727,6 +1728,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"); @@ -1919,4 +1941,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 d84c328a7693a92cf84b38299892be665e1b3a96..c065dfa655378d057bd99c4aef2747be309a56f3 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/service.h b/services/backup_sa/include/module_ipc/service.h index 359b508808cd25c05c7d6740fd40326abba2f37c..b1b933a28d06e7b6476e3138550eca790c83846c 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; @@ -401,11 +406,6 @@ private: */ void ClearSessionAndSchedInfo(const std::string &bundleName); - /** - * @brief 上报总体统计打点 - */ - void TotalStatReport(ErrCode errCode); - /** * @brief 整个备份恢复流程结束 * @@ -724,37 +724,19 @@ 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 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 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,10 +772,13 @@ 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_; std::map> backupExtOnReleaseMap_; + std::map bundleBroadCastInfoMap_; + std::shared_mutex extOnReleaseLock_; public: std::map> backupExtMutexMap_; std::map failedBundles_; 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 d9a40dd69bbd9c54930c8086363b8e1e2b5920ab..1afb97b2cf19635e088370996659b2fac225d8c7 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/include/module_notify/notify_work_service.h b/services/backup_sa/include/module_notify/notify_work_service.h index c4bb9b749a14a798aaaeee3362c9bcd9b008b5d5..c27b1450342544eb3fdd4dc8ab39f228828c93df 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 777caa094f5165704a11c914f631a9a0ebcb5c97..d946a8facd2e0b8186c4e07b21ed2ed143027ac2 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 */ @@ -469,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({ @@ -486,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; @@ -505,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); @@ -525,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; @@ -585,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(); @@ -668,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()) { @@ -769,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"); @@ -840,27 +837,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"); } @@ -868,7 +866,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"); @@ -883,10 +880,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); @@ -910,7 +905,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"); @@ -930,10 +924,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); @@ -972,6 +964,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); + } } } @@ -1147,6 +1143,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); @@ -1496,6 +1495,7 @@ void Service::SessionDeactive() HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGI("Begin"); + TotalStatReport(); isInRelease_.store(true); //清理处置状态 if (session_ == nullptr) { @@ -1503,6 +1503,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)) { @@ -1518,8 +1519,7 @@ void Service::SessionDeactive() if (!bundleNameList.empty()) { DelClearBundleRecord(bundleNameList); } - SendErrAppGalleryNotify(); - DeleteDisConfigFile(); + ClearRecord(); // 结束定时器 if (sched_ == nullptr) { HILOGE("Session deactive error, sched is empty"); @@ -1543,7 +1543,6 @@ void Service::SessionDeactive() } } catch (...) { HILOGE("Unexpected exception"); - return; } } @@ -2087,4 +2086,22 @@ 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_->SetBundleUserId(bundleNameIndexInfo, session_->GetSessionUserId()); + 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 1b478b1030ed8bdf91951a0255e324994def8597..21c2dbc208f0ab623586916d68de21c640815e1e 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" @@ -321,11 +322,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 +342,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 +371,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 +390,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 +421,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 +436,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 +468,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 +488,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); @@ -733,12 +728,6 @@ ErrCode Service::AppIncrementalDone(ErrCode errCode) callerName.c_str(), errCode); ClearIncrementalStatFile(GetUserIdDefault(), callerName); 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); } @@ -1107,6 +1096,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 a71006c6ede85910f370dbc162a76b5eb493a45d..351db9aae05a3d0b71c0ffc42a2ca9f04e451dc4 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); } @@ -466,6 +460,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 +470,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, @@ -762,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(); @@ -946,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({ @@ -962,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(), @@ -994,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); @@ -1013,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(), @@ -1397,7 +1383,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); @@ -1493,6 +1484,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) { @@ -1513,6 +1505,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()) { @@ -1524,6 +1517,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()); @@ -1605,4 +1599,103 @@ 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 (const 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.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()); + } +} + +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/services/backup_sa/src/module_ipc/svc_session_manager.cpp b/services/backup_sa/src/module_ipc/svc_session_manager.cpp index 18af5a9fd639643cc24e62c9f8f24d664fb3ea00..4d45a0605f6e84d10d7c26ff57e50a464d132c33 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/services/backup_sa/src/module_notify/notify_work_service.cpp b/services/backup_sa/src/module_notify/notify_work_service.cpp index f9e403a22aaab708a59611f62b04bd40ca429da3..b43838da072ee576fceb6f04d73fac5f12546e1c 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/backup_ext/src/ext_extension_mock.cpp b/tests/mock/backup_ext/src/ext_extension_mock.cpp index 712ce158d2a5f54f931af0ed3d4434ae331b8564..6f72efde9a1c022a5a2df2433ddc11ca45c002fa 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/mock/module_ipc/include/notify_work_service_mock.h b/tests/mock/module_ipc/include/notify_work_service_mock.h index 522a08e7cc36ff248c59cdf300f78014a87d9f87..de46c859e978a19d7c640d1a2e583e835ea1011d 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/include/svc_session_manager_mock.h b/tests/mock/module_ipc/include/svc_session_manager_mock.h index 9588ac367bada2fb7b3e6ad10179757945880082..7827190f2220f84e8c366cdd7a04e04f1bea2e1b 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/service_mock.cpp b/tests/mock/module_ipc/service_mock.cpp index 735762b1801a06d38beb540225e0ea7946de1b8d..ce6398b50a1297196f712b429f1bf3fa08cb122c 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 e802517a617dc3639f46164f111ab840117c7d08..84588312e1b8e6525da29e09ca947f336be315ec 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/mock/module_ipc/src/svc_session_manager_mock.cpp b/tests/mock/module_ipc/src/svc_session_manager_mock.cpp index ab02cc68d06b40fcfce0f269621d7961ac159e77..f71b61aa426346a57d3f84a9574af1f009adeaae 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 2cc861333c3c18bdc4a8ea9a53903849e12d3eb6..7096895e69b69da70777a0572aa9d6b55f1ccb30 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 1fa56ea3be626518d805ad8fb252a0382e0ee76f..28c285d255d4ccc85f4cdb5d0ace62c55045a7f8 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 8cd651ca786c2024a7a8836528efdcf4a3fcdf6f..ecd8d8f23666822c45510150c720524a6f591868 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/tests/unittests/backup_ext/ext_extension_sub_test.cpp b/tests/unittests/backup_ext/ext_extension_sub_test.cpp index 284cf4744ce99ef7eff615020e2400e253363820..93c61b6d483df34312168492f85923a143657ef2 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."; 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 9111b9b552c389d8890f6eeb0121f41f4621048a..642013783056ab40a7d89ea3cb4dc99d3a46c541 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,51 @@ 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); +} + +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_other_test.cpp b/tests/unittests/backup_sa/module_ipc/service_other_test.cpp index a1253d5ea7e912a6cc45e3b7a628dab9b7033812..023da0a568c935a1fc9b8287941ed63042e28e7a 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)); @@ -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/tests/unittests/backup_sa/module_ipc/service_test.cpp b/tests/unittests/backup_sa/module_ipc/service_test.cpp index f51d1fc6fb944ee434c18c6308f46d8a249f8af2..1057e00700f84e30e294c77fb109565383783de3 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); @@ -2574,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 17947b793d91efe3914232bf21f19d19fe587c2f..4156cdc8d9ae2479573c12ee07bd439496947c10 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_json/b_json_entity_extension_config.h b/utils/include/b_json/b_json_entity_extension_config.h index 8523f2e93a4c27cad138956084fc6954b5d770a4..3e7f98eb6f6aa15b0bd116f7feb9ff626187f94f 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 686f146fb1e42d904c925fabc87b70e83dafd4aa..e15583e894f766217770ce0a48cc7826d8ffc125 100644 --- a/utils/include/b_jsonutil/b_jsonutil.h +++ b/utils/include/b_jsonutil/b_jsonutil.h @@ -23,6 +23,8 @@ namespace OHOS::FileManagement::Backup { class BJsonUtil { public: typedef struct BundleDetailInfo { + std::string backupScene; + std::string broadCastType; std::string bundleName; std::string type; std::string detail; @@ -200,6 +202,31 @@ 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); + + /** + * @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_radar/radar_total_statistic.h b/utils/include/b_radar/radar_total_statistic.h index 22d4824d7f8e241b1a3d361cfe6de6065cdfcdfb..9f0ce31383438931032bc479cd2d9b5c430d041e 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/include/b_resources/b_constants.h b/utils/include/b_resources/b_constants.h index bf66f58f90488193fe906e5275434533db1349c4..68d6bff29558ece864e846328a578c12b44c941c 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,16 @@ 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 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; + // 特殊版本信息 constexpr int DEFAULT_VERSION_CODE = 0; constexpr char VERSION_NAME_SEPARATOR_CHAR = '-'; @@ -222,7 +233,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 = { @@ -246,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_filesystem/b_dir.cpp b/utils/src/b_filesystem/b_dir.cpp index e5630d7322fb6c635ced01ca5b70c4bc544bf8df..14a1caec61601c3edb3efdcf9be9ba78b5cb3899 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; diff --git a/utils/src/b_hiaudit/hi_audit.cpp b/utils/src/b_hiaudit/hi_audit.cpp index 8367eab470480c3685124c3954a8fa2c775af263..99346855519d7bf04f40c6136c4efc9f9b589d62 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); } 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 6f17cf0dae69f01a5eb6bf13898626a949caa462..a7b47d67a7a5b8d1b6df70d574a1357c81df72be 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 cdd7a085d35e30863d0d897a45318ae78f15c90f..a4dd4583d389ec1b31f0356a20ab0d290dd11665 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); } @@ -243,12 +250,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 +545,40 @@ 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; +} + +bool BJsonUtil::FindBroadCastInfoByName(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 diff --git a/utils/src/b_radar/radar_total_statistic.cpp b/utils/src/b_radar/radar_total_statistic.cpp index 87035f4a55b59a8d7c5d027e843f4e9da815ed7f..d89db4c1c0dbd206f8633da9054985bb0a706ec2 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)