diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index ff6aabe7a3778a5cc18169082f71d37cc4e2ca47..f6dad6ace98b4691d6b70755e34c7ea9dce8eba8 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -380,9 +380,12 @@ private: void PreDealExcludes(std::vector &excludes); template map MatchFiles(map files, vector endExcludes); + void UpdateTarStat(uint64_t tarFileSize); private: pair> GetFileInfos(const vector &includes, const vector &excludes); - void ReportAppStatistic(ErrCode errCode); + TarMap GetIncrmentBigInfos(const vector &files); + void UpdateFileStat(std::string filePath, uint64_t fileSize); + void ReportAppStatistic(const std::string &func, ErrCode errCode); ErrCode IndexFileReady(const TarMap &pkgInfo, sptr proxy); std::shared_mutex lock_; diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index c1cdc4ed998b09a2bfb3da49fd4d7a4271c45a5c..cf7df101cb91f520dea0a4900ab9391a18d21383 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -469,7 +469,11 @@ ErrCode BackupExtExtension::IndexFileReady(const TarMap &pkgInfo, sptr cache.SetExtManage(pkgInfo); cachedEntity.Persist(); close(cachedEntity.GetFd().Release()); - appStatistic_->manageJsonSize_ = BFile::GetFileSize(INDEX_FILE_BACKUP); + int32_t err = 0; + appStatistic_->manageJsonSize_ = BFile::GetFileSize(INDEX_FILE_BACKUP, err); + if (err != 0) { + HILOGE("get index size fail err:%{public}d", err); + } int fdval = open(INDEX_FILE_BACKUP.data(), O_RDONLY); ErrCode ret = proxy->AppFileReady(string(BConstants::EXT_BACKUP_MANAGE), fdval, @@ -647,7 +651,7 @@ pair> BackupExtExtension::GetFileInfos(const vector< { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); appStatistic_->scanFileSpend_.Start(); - auto [errCode, files, smallFiles] = BDir::GetBigFiles(includes, excludes, appStatistic_); + auto [errCode, files, smallFiles] = BDir::GetBigFiles(includes, excludes); appStatistic_->scanFileSpend_.End(); if (errCode != 0) { return {}; @@ -674,6 +678,7 @@ pair> BackupExtExtension::GetFileInfos(const vector< for (const auto &item : files) { int64_t hashStart = TimeUtils::GetTimeUS(); string md5Name = getStringHash(bigFiles, item.first); + UpdateFileStat(item.first, item.second.st_size); appStatistic_->hashSpendUS_ += TimeUtils::GetSpendUS(hashStart); if (!md5Name.empty()) { bigFiles.emplace(md5Name, make_tuple(item.first, item.second, true)); @@ -851,6 +856,7 @@ tuple BackupExtExtension::CalculateDataSize(const B appStatistic_->bigFileSize_ = totalSize; HILOGI("bigfile size = %{public}" PRId64 "", totalSize); for (const auto &item : smallFiles) { + UpdateFileStat(item.first, item.second); totalSize += static_cast(item.second); } appStatistic_->smallFileSize_ = totalSize - appStatistic_->bigFileSize_; @@ -1810,11 +1816,11 @@ void BackupExtExtension::DoClear() } } -void BackupExtExtension::ReportAppStatistic(ErrCode errCode) +void BackupExtExtension::ReportAppStatistic(const std::string &func, ErrCode errCode) { if (curScenario_ == BackupRestoreScenario::FULL_BACKUP || curScenario_ == BackupRestoreScenario::INCREMENTAL_BACKUP) { - appStatistic_->ReportBackup("AppDone", errCode); + appStatistic_->ReportBackup(func, errCode); } else { appStatistic_->untarSpend_ = static_cast(radarRestoreInfo_.tarFileSpendTime); appStatistic_->bigFileSpend_ = static_cast(radarRestoreInfo_.bigFileSpendTime); @@ -1823,7 +1829,7 @@ void BackupExtExtension::ReportAppStatistic(ErrCode errCode) appStatistic_->tarFileCount_ = radarRestoreInfo_.tarFileNum; appStatistic_->bigFileSize_ = radarRestoreInfo_.bigFileSize; appStatistic_->tarFileSize_ = radarRestoreInfo_.tarFileSize; - appStatistic_->ReportRestore("AppDone", errCode); + appStatistic_->ReportRestore(func, errCode); } } @@ -1831,7 +1837,7 @@ void BackupExtExtension::AppDone(ErrCode errCode) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("AppDone Begin."); - ReportAppStatistic(errCode); + ReportAppStatistic("AppDone", errCode); auto proxy = ServiceClient::GetInstance(); if (proxy == nullptr) { HILOGE("Failed to obtain the ServiceClient handle"); @@ -1990,13 +1996,13 @@ static bool IfEquality(const ReportFileInfo &info, const ReportFileInfo &infoAd) return info.filePath < infoAd.filePath; } -static void AdDeduplication(vector &FilesList) +static void AdDeduplication(vector &filesList) { - sort(FilesList.begin(), FilesList.end(), IfEquality); - auto it = unique(FilesList.begin(), FilesList.end(), [](const ReportFileInfo &info, const ReportFileInfo &infoAd) { + sort(filesList.begin(), filesList.end(), IfEquality); + auto it = unique(filesList.begin(), filesList.end(), [](const ReportFileInfo &info, const ReportFileInfo &infoAd) { return info.filePath == infoAd.filePath; }); - FilesList.erase(it, FilesList.end()); + filesList.erase(it, filesList.end()); } void BackupExtExtension::FillFileInfos(UniqueFd incrementalFd, @@ -2009,14 +2015,19 @@ void BackupExtExtension::FillFileInfos(UniqueFd incrementalFd, BReportEntity cloudRp(move(manifestFd)); unordered_map cloudFiles; cloudRp.GetReportInfos(cloudFiles); + appStatistic_->scanFileSpend_.Start(); if (cloudFiles.empty()) { FillFileInfosWithoutCmp(allFiles, smallFiles, bigFiles, move(incrementalFd)); } else { FillFileInfosWithCmp(allFiles, smallFiles, bigFiles, cloudFiles, move(incrementalFd)); } + AdDeduplication(allFiles); AdDeduplication(smallFiles); AdDeduplication(bigFiles); + appStatistic_->smallFileCount_ = smallFiles.size(); + appStatistic_->bigFileCount_ = bigFiles.size(); + appStatistic_->scanFileSpend_.End(); HILOGI("End Compare, allfile is %{public}zu, smallfile is %{public}zu, bigfile is %{public}zu", allFiles.size(), smallFiles.size(), bigFiles.size()); } diff --git a/frameworks/native/backup_ext/src/sub_ext_extension.cpp b/frameworks/native/backup_ext/src/sub_ext_extension.cpp index 83d4f8a535479982d3aa2a6337e729d2e5a62765..f54990c69de6005d5f608f8e323ba6c443bc1e90 100644 --- a/frameworks/native/backup_ext/src/sub_ext_extension.cpp +++ b/frameworks/native/backup_ext/src/sub_ext_extension.cpp @@ -326,14 +326,14 @@ std::function BackupExtExtension::IncreOnRestoreExCa 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); + AppRadar::GetInstance().GetUserId(), BizStageRestore::BIZ_STAGE_ON_RESTORE, ERR_OK); } } extensionPtr->FinishOnProcessTask(); extensionPtr->extension_->InvokeAppExtMethod(errCode, restoreRetInfo); if (errCode == ERR_OK) { if (restoreRetInfo.size()) { + extensionPtr->ReportAppStatistic("IncreOnRestoreExCallback", errCode); extensionPtr->AppResultReport(restoreRetInfo, BackupRestoreScenario::INCREMENTAL_RESTORE); } return; @@ -344,6 +344,7 @@ std::function BackupExtExtension::IncreOnRestoreExCa } else { std::string errInfo; BJsonUtil::BuildExtensionErrInfo(errInfo, errCode, restoreRetInfo); + extensionPtr->ReportAppStatistic("IncreOnRestoreExCallback", errCode); extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::INCREMENTAL_RESTORE, errCode); extensionPtr->DoClear(); } @@ -380,6 +381,7 @@ std::function BackupExtExtension::IncreOnRestoreCall } else { std::string errInfo; BJsonUtil::BuildExtensionErrInfo(errInfo, errCode, errMsg); + extensionPtr->ReportAppStatistic("IncreOnRestoreCallback", errCode); extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::INCREMENTAL_RESTORE, errCode); } extensionPtr->DoClear(); @@ -779,7 +781,7 @@ void BackupExtExtension::CloseOnProcessTimeOutTimer() void BackupExtExtension::AppIncrementalDone(ErrCode errCode) { HILOGI("Begin"); - ReportAppStatistic(errCode); + ReportAppStatistic("AppIncrementalDone", errCode); auto proxy = ServiceClient::GetInstance(); if (proxy == nullptr) { HILOGE("Failed to obtain the ServiceClient handle"); @@ -1002,10 +1004,28 @@ int BackupExtExtension::User0DoBackup(const BJsonEntityExtensionConfig &usrConfi return ERR_OK; } +void BackupExtExtension::UpdateFileStat(std::string filePath, uint64_t fileSize) +{ + appStatistic_->UpdateFileDist(ExtractFileExt(filePath), fileSize); + uint32_t dirDepth = 0; + const char* pstr = filePath.c_str(); + char pre = '-'; + uint32_t pathLen = filePath.size(); + for (uint32_t i = 0; i < pathLen; i++) { + if (pstr[i] == '/' && pre != '/') { + dirDepth++; + } + pre = pstr[i]; + } + if (dirDepth > appStatistic_->dirDepth_) { + appStatistic_->dirDepth_ = dirDepth; + } +} + /** * 获取增量的大文件的信息 */ -static TarMap GetIncrmentBigInfos(const vector &files) +TarMap BackupExtExtension::GetIncrmentBigInfos(const vector &files) { auto getStringHash = [](const TarMap &tarMap, const string &str) -> string { ostringstream strHex; @@ -1031,7 +1051,11 @@ static TarMap GetIncrmentBigInfos(const vector &files) HILOGE("Failed to stat file %{public}s, err = %{public}d", item.filePath.c_str(), errno); throw errno; } + appStatistic_->bigFileSize_ += sta.st_size; + UpdateFileStat(item.filePath, sta.st_size); + uint64_t hashStart = TimeUtils::GetTimeUS(); string md5Name = getStringHash(bigFiles, item.filePath); + appStatistic_->hashSpendUS_ += TimeUtils::GetSpendUS(hashStart); if (!md5Name.empty()) { bigFiles.emplace(md5Name, make_tuple(item.filePath, sta, true)); } @@ -1046,8 +1070,10 @@ int BackupExtExtension::DoIncrementalBackupTask(UniqueFd incrementalFd, UniqueFd vector allFiles; vector smallFiles; vector bigFiles; + appStatistic_->doBackupSpend_.Start(); FillFileInfos(move(incrementalFd), move(manifestFd), allFiles, smallFiles, bigFiles); auto ret = DoIncrementalBackup(allFiles, smallFiles, bigFiles); + appStatistic_->doBackupSpend_.End(); if (ret == ERR_OK) { auto end = std::chrono::system_clock::now(); auto cost = std::chrono::duration_cast(end - start).count(); @@ -1161,6 +1187,12 @@ static string GetIncrmentPartName() return to_string(milliseconds.count()) + "_part"; } +void BackupExtExtension::UpdateTarStat(uint64_t tarFileSize) +{ + appStatistic_->tarFileCount_++; + appStatistic_->tarFileSize_ += tarFileSize; +} + void BackupExtExtension::IncrementalPacket(const vector &infos, TarMap &tar, sptr proxy) { @@ -1175,7 +1207,10 @@ void BackupExtExtension::IncrementalPacket(const vector & int fdNum = 0; string partName = GetIncrmentPartName(); auto reportCb = ReportErrFileByProc(wptr {this}, curScenario_); + uint64_t tarStart = TimeUtils::GetTimeMS(); for (const auto &small : infos) { + appStatistic_->smallFileSize_ += small.size; + UpdateFileStat(small.filePath, small.size); totalSize += static_cast(small.size); fileCount += 1; packFiles.emplace_back(small.filePath); @@ -1183,6 +1218,7 @@ void BackupExtExtension::IncrementalPacket(const vector & if (totalSize >= BConstants::DEFAULT_SLICE_SIZE || fileCount >= BConstants::MAX_FILE_COUNT) { TarMap tarMap {}; TarFile::GetInstance().Packet(packFiles, partName, path, tarMap, reportCb); + UpdateTarStat(TarFile::GetInstance().GetTarFileSize()); tar.insert(tarMap.begin(), tarMap.end()); // 执行tar包回传功能 WaitToSendFd(startTime, fdNum); @@ -1199,6 +1235,7 @@ void BackupExtExtension::IncrementalPacket(const vector & // 打包回传 TarMap tarMap {}; TarFile::GetInstance().Packet(packFiles, partName, path, tarMap, reportCb); + UpdateTarStat(TarFile::GetInstance().GetTarFileSize()); IncrementalTarFileReady(tarMap, tarInfos, proxy); fdNum = 1; WaitToSendFd(startTime, fdNum); @@ -1207,6 +1244,7 @@ void BackupExtExtension::IncrementalPacket(const vector & tarInfos.clear(); RefreshTimeInfo(startTime, fdNum); } + appStatistic_->tarSpend_ = TimeUtils::GetSpendMS(tarStart); } int BackupExtExtension::DoIncrementalBackup(const vector &allFiles, diff --git a/services/backup_sa/include/module_external/bms_adapter.h b/services/backup_sa/include/module_external/bms_adapter.h index 13a7be7a1d9c0cee9d48144bd1334a1bd9de0e3c..4ebc3a5e46e81d19d8d5b419a8c19c0d73d58f52 100644 --- a/services/backup_sa/include/module_external/bms_adapter.h +++ b/services/backup_sa/include/module_external/bms_adapter.h @@ -19,6 +19,7 @@ #include #include +#include "b_radar/radar_const.h" #include "b_json/b_json_entity_caps.h" #include "bundlemgr/bundle_mgr_interface.h" #include "b_incremental_data.h" @@ -27,6 +28,16 @@ namespace OHOS::FileManagement::Backup { class InnerReceiverImpl; +struct BundleExtInfo { + BundleExtInfo(const std::string& bundleName) : bundleName_(bundleName), + error_(RadarError(BError(BError::Codes::OK))) {} + AppExecFwk::BundleInfo bundleInfo_; + const std::string bundleName_; + std::vector extensionInfos_; + RadarError error_; + uint32_t getExtSpend_ = 0; +}; + class BundleMgrAdapter { public: @@ -83,8 +94,7 @@ public: static std::vector GetBundleInfosForAppendBundles( const std::vector &incrementalDataList, int32_t userId); private: - static bool GetCurBundleExtenionInfo(AppExecFwk::BundleInfo &installedBundle, const std::string &bundleName, - std::vector &extensionInfos, sptr bms, + static bool GetCurBundleExtenionInfo(BundleExtInfo &bundleExtInfo, sptr bms, int32_t userId); }; } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index f68dd45d3752715b69e619f16faddf63b53e4b89..f0ec110d59d161c0cc25ef919a5690006de5b059 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -25,6 +25,7 @@ #include "b_json/b_json_entity_caps.h" #include "b_json/b_json_service_disposal_config.h" #include "b_radar/radar_total_statistic.h" +#include "b_radar/radar_app_statistic.h" #include "iservice_reverse.h" #include "iremote_stub.h" #include "module_sched/sched_scheduler.h" @@ -687,6 +688,42 @@ private: const std::vector &infos); ErrCode HelpToAppIncrementalFileReady(const string &bundleName, const string &fileName, sptr proxy); + vector GetRestoreBundleNames(UniqueFd fd, sptr session, + const vector &bundleNames, std::string &oldBackupVersion); + void AppStatReportErr(const string &bundleName, const string &func, RadarError err); + void SaStatReport(const string &bundleName, const string &func, RadarError err); + 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); + } + } + } + private: static sptr instance_; static std::mutex instanceLock_; @@ -722,6 +759,7 @@ private: std::atomic isScannedEnd_ {false}; std::atomic onScanning_ {false}; std::shared_ptr totalStatistic_ = nullptr; + std::shared_ptr saStatistic_ = nullptr; public: std::map> backupExtMutexMap_; std::map failedBundles_; diff --git a/services/backup_sa/include/module_ipc/svc_backup_connection.h b/services/backup_sa/include/module_ipc/svc_backup_connection.h index ff2c5a84e07313e16056202fbd783869fc2e5353..786c01f4dcd31d343073fb4dda117ebaba8dcce6 100644 --- a/services/backup_sa/include/module_ipc/svc_backup_connection.h +++ b/services/backup_sa/include/module_ipc/svc_backup_connection.h @@ -92,6 +92,7 @@ public: uint32_t GetConnectSpan() { return connectSpend_.GetSpan(); } + BError GetError() { return error_; } public: SvcBackupConnection(std::function callDied, std::function callConnected, @@ -115,6 +116,7 @@ private: std::function callConnected_; std::string bundleNameIndexInfo_; Duration connectSpend_; + BError error_; }; } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_external/bms_adapter.cpp b/services/backup_sa/src/module_external/bms_adapter.cpp index bf1a73223955568bace21fa4149e06371e54e5a6..b5b2c0204cf5d1df0a0919c2dd32d9a6e44f27e6 100644 --- a/services/backup_sa/src/module_external/bms_adapter.cpp +++ b/services/backup_sa/src/module_external/bms_adapter.cpp @@ -129,24 +129,22 @@ vector BundleMgrAdapter::GetBundleInfos(const vecto GetBundleInfoForSA(bundleName, bundleInfos); continue; } - AppExecFwk::BundleInfo installedBundle; - std::vector extensionInfos; - bool getBundleSuccess = GetCurBundleExtenionInfo(installedBundle, bundleName, extensionInfos, bms, userId); + BundleExtInfo bundleExtInfo(bundleName); + bool getBundleSuccess = GetCurBundleExtenionInfo(bundleExtInfo, bms, userId); if (!getBundleSuccess) { HILOGE("Get current extension failed, bundleName:%{public}s", bundleName.c_str()); continue; } auto [allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, extraInfo] = - GetAllowAndExtName(extensionInfos); + GetAllowAndExtName(bundleExtInfo.extensionInfos_); int64_t dataSize = 0; if (allToBackup) { dataSize = GetBundleStats(bundleName, userId); } - bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.appIndex, - installedBundle.versionCode, - installedBundle.versionName, dataSize, 0, allToBackup, - fullBackupOnly, extName, restoreDeps, supportScene, - extraInfo}); + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {bundleExtInfo.bundleInfo_.name, + bundleExtInfo.bundleInfo_.appIndex, bundleExtInfo.bundleInfo_.versionCode, + bundleExtInfo.bundleInfo_.versionName, dataSize, 0, allToBackup, fullBackupOnly, + extName, restoreDeps, supportScene, extraInfo}); } HILOGI("End, bundleInfos size:%{public}zu", bundleInfos.size()); return bundleInfos; @@ -293,15 +291,14 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement auto bms = GetBundleManager(); for (const auto &bundleNameTime : incrementalDataList) { auto bundleName = bundleNameTime.bundleName; - AppExecFwk::BundleInfo installedBundle; - std::vector extensionInfos; - bool getBundleSuccess = GetCurBundleExtenionInfo(installedBundle, bundleName, extensionInfos, bms, userId); + BundleExtInfo bundleExtInfo(bundleName); + bool getBundleSuccess = GetCurBundleExtenionInfo(bundleExtInfo, bms, userId); if (!getBundleSuccess) { HILOGE("Failed to get bundle info from bms, bundleName:%{public}s", bundleName.c_str()); continue; } struct BJsonEntityCaps::BundleBackupConfigPara backupPara; - if (!GetBackupExtConfig(extensionInfos, backupPara)) { + if (!GetBackupExtConfig(bundleExtInfo.extensionInfos_, backupPara)) { HILOGE("No backup extension ability found, bundleName:%{public}s", bundleName.c_str()); continue; } @@ -310,16 +307,13 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement HILOGE("Create bundleInteraction dir failed, bundleName:%{public}s", bundleName.c_str()); continue; } - bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.appIndex, - installedBundle.versionCode, - installedBundle.versionName, 0, 0, - backupPara.allToBackup, backupPara.fullBackupOnly, - backupPara.extensionName, - backupPara.restoreDeps, backupPara.supportScene, - backupPara.extraInfo}); - if (installedBundle.appIndex > 0) { - std::string bundleNameIndex = "+clone-" + std::to_string(installedBundle.appIndex) + "+" + - installedBundle.name; + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {bundleExtInfo.bundleInfo_.name, + bundleExtInfo.bundleInfo_.appIndex, bundleExtInfo.bundleInfo_.versionCode, + bundleExtInfo.bundleInfo_.versionName, 0, 0, backupPara.allToBackup, backupPara.fullBackupOnly, + backupPara.extensionName, backupPara.restoreDeps, backupPara.supportScene, backupPara.extraInfo}); + if (bundleExtInfo.bundleInfo_.appIndex > 0) { + std::string bundleNameIndex = "+clone-" + std::to_string(bundleExtInfo.bundleInfo_.appIndex) + "+" + + bundleExtInfo.bundleInfo_.name; bundleNames.emplace_back(bundleNameIndex); } else { bundleNames.emplace_back(bundleName); @@ -503,32 +497,36 @@ void BundleMgrAdapter::GetBundleInfoForSA(std::string bundleName, std::vector &extensionInfos, - sptr bms, int32_t userId) +bool BundleMgrAdapter::GetCurBundleExtenionInfo(BundleExtInfo &bundleExtInfo, sptr bms, + int32_t userId) { - BJsonUtil::BundleDetailInfo bundleDetailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName); + BJsonUtil::BundleDetailInfo bundleDetailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleExtInfo.bundleName_); int32_t flags = static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) | static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) | static_cast(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_METADATA); + int64_t getExtStart = TimeUtils::GetTimeMS(); ErrCode ret = bms->GetCloneBundleInfo(bundleDetailInfo.bundleName, flags, bundleDetailInfo.bundleIndex, - installedBundle, userId); + bundleExtInfo.bundleInfo_, userId); + bundleExtInfo.getExtSpend_ = TimeUtils::GetSpendMS(getExtStart); if (ret != ERR_OK) { HILOGE("bundleName:%{public}s, ret:%{public}d, current bundle info for backup/restore is empty", - bundleName.c_str(), ret); + bundleExtInfo.bundleName_.c_str(), ret); + bundleExtInfo.error_ = RadarError(MODULE_HAP, BError(BError::Codes::SA_BUNDLE_INFO_EMPTY)); return false; } - if (installedBundle.applicationInfo.codePath == HMOS_HAP_CODE_PATH || - installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { - HILOGE("Unsupported applications, name : %{public}s", installedBundle.name.data()); + if (bundleExtInfo.bundleInfo_.applicationInfo.codePath == HMOS_HAP_CODE_PATH || + bundleExtInfo.bundleInfo_.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { + HILOGE("Unsupported applications, name : %{public}s", bundleExtInfo.bundleInfo_.name.data()); + bundleExtInfo.error_ = RadarError(MODULE_HAP, BError(BError::Codes::SA_FORBID_BACKUP_RESTORE)); return false; } - std::vector hapModuleInfos = installedBundle.hapModuleInfos; + std::vector hapModuleInfos = bundleExtInfo.bundleInfo_.hapModuleInfos; for (const auto &hapModuleInfo : hapModuleInfos) { - extensionInfos.insert(extensionInfos.end(), hapModuleInfo.extensionInfos.begin(), + bundleExtInfo.extensionInfos_.insert(bundleExtInfo.extensionInfos_.end(), hapModuleInfo.extensionInfos.begin(), hapModuleInfo.extensionInfos.end()); } - HILOGI("bundleName:%{public}s, extensionInfos size:%{public}zu", bundleName.c_str(), extensionInfos.size()); + HILOGI("bundleName:%{public}s, extensionInfos size:%{public}zu", bundleExtInfo.bundleName_.c_str(), + bundleExtInfo.extensionInfos_.size()); return true; } @@ -621,23 +619,22 @@ std::vector BundleMgrAdapter::GetBundleInfosForInde vector bundleInfos; auto bms = GetBundleManager(); for (auto const &bundleName : bundleNames) { - AppExecFwk::BundleInfo installedBundle; - std::vector extensionInfos; - bool getBundleSuccess = GetCurBundleExtenionInfo(installedBundle, bundleName, extensionInfos, bms, userId); + BundleExtInfo bundleExtInfo(bundleName); + bool getBundleSuccess = GetCurBundleExtenionInfo(bundleExtInfo, bms, userId); if (!getBundleSuccess) { HILOGE("Get current extension failed, bundleName:%{public}s", bundleName.c_str()); continue; } auto [allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, extraInfo] = - GetAllowAndExtName(extensionInfos); + GetAllowAndExtName(bundleExtInfo.extensionInfos_); if (!allToBackup) { HILOGI("Not allToBackup, bundleName = %{public}s, appIndex = %{public}d", - installedBundle.name.c_str(), installedBundle.appIndex); + bundleExtInfo.bundleInfo_.name.c_str(), bundleExtInfo.bundleInfo_.appIndex); continue; } bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo { - installedBundle.name, installedBundle.appIndex, - installedBundle.versionCode, installedBundle.versionName, + bundleExtInfo.bundleInfo_.name, bundleExtInfo.bundleInfo_.appIndex, + bundleExtInfo.bundleInfo_.versionCode, bundleExtInfo.bundleInfo_.versionName, 0, 0, allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, extraInfo}); } @@ -660,15 +657,14 @@ void BundleMgrAdapter::CreatBackupEnv(const std::vector &bundl HILOGI("SA don't need creat env"); continue; } - AppExecFwk::BundleInfo installedBundle; - std::vector extensionInfos; - bool getBundleSuccess = GetCurBundleExtenionInfo(installedBundle, bundleName, extensionInfos, bms, userId); + BundleExtInfo bundleExtInfo(bundleName); + bool getBundleSuccess = GetCurBundleExtenionInfo(bundleExtInfo, bms, userId); if (!getBundleSuccess) { HILOGE("Failed to get bundle info from bms, bundleName:%{public}s", bundleName.c_str()); continue; } struct BJsonEntityCaps::BundleBackupConfigPara backupPara; - if (!GetBackupExtConfig(extensionInfos, backupPara)) { + if (!GetBackupExtConfig(bundleExtInfo.extensionInfos_, backupPara)) { HILOGE("No backup extension ability found, bundleName:%{public}s", bundleName.c_str()); continue; } @@ -689,25 +685,21 @@ std::vector BundleMgrAdapter::GetBundleInfosForAppe for (const auto &bundleIncData : incrementalDataList) { auto bundleName = bundleIncData.bundleName; HILOGE("Current bundle name is:%{public}s", bundleName.c_str()); - AppExecFwk::BundleInfo installedBundle; - std::vector extensionInfos; - bool getBundleSuccess = GetCurBundleExtenionInfo(installedBundle, bundleName, extensionInfos, bms, userId); + BundleExtInfo bundleExtInfo(bundleName); + bool getBundleSuccess = GetCurBundleExtenionInfo(bundleExtInfo, bms, userId); if (!getBundleSuccess) { HILOGE("Failed to get bundle info from bms, bundleName:%{public}s", bundleName.c_str()); continue; } struct BJsonEntityCaps::BundleBackupConfigPara backupPara; - if (!GetBackupExtConfig(extensionInfos, backupPara)) { + if (!GetBackupExtConfig(bundleExtInfo.extensionInfos_, backupPara)) { HILOGE("No backup extension ability found, bundleName:%{public}s", bundleName.c_str()); continue; } - bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.appIndex, - installedBundle.versionCode, - installedBundle.versionName, 0, 0, - backupPara.allToBackup, backupPara.fullBackupOnly, - backupPara.extensionName, - backupPara.restoreDeps, backupPara.supportScene, - backupPara.extraInfo}); + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {bundleExtInfo.bundleInfo_.name, + bundleExtInfo.bundleInfo_.appIndex, bundleExtInfo.bundleInfo_.versionCode, + bundleExtInfo.bundleInfo_.versionName, 0, 0, backupPara.allToBackup, backupPara.fullBackupOnly, + backupPara.extensionName, backupPara.restoreDeps, backupPara.supportScene, backupPara.extraInfo}); } for (const auto &info : incrementalDataList) { if (SAUtils::IsSABundleName(info.bundleName)) { diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 6e421860207f5d8109c9c4a0e3708528ba204fa0..3354808144b30f21e07054b6d0f802d7b0eb3e91 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -145,7 +145,7 @@ void Service::BundleEndRadarReport(const std::string &bundleName, ErrCode errCod const IServiceReverseType::Scenario scenario) { if (errCode == ERR_OK) { - successBundlesNum_++; + successBundlesNum_.fetch_add(1); return; } if (!IsReportBundleExecFail(bundleName)) { @@ -580,14 +580,13 @@ void Service::OnBundleStarted(BError error, sptr session, con BundleBeginRadarReport(bundleName, error.GetCode(), scenario); } -static vector GetRestoreBundleNames(UniqueFd fd, - sptr session, - const vector &bundleNames, - std::string &oldBackupVersion) +vector Service::GetRestoreBundleNames(UniqueFd fd, sptr session, + const vector &bundleNames, std::string &oldBackupVersion) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - // BundleMgrAdapter::GetBundleInfos可能耗时 + GetBundleInfoStart(); auto restoreInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session->GetSessionUserId()); + GetBundleInfoEnd(); BJsonCachedEntity cachedEntity(move(fd)); auto cache = cachedEntity.Structuralize(); oldBackupVersion = cache.GetBackupVersion(); @@ -598,19 +597,16 @@ static vector GetRestoreBundleNames(UniqueFd fd, if (!bundleInfos.size()) { throw BError(BError::Codes::SA_INVAL_ARG, "Json entity caps is empty"); } - HILOGI("restoreInfos size is:%{public}zu", restoreInfos.size()); vector restoreBundleInfos {}; for (const auto &restoreInfo : restoreInfos) { if (SAUtils::IsSABundleName(restoreInfo.name)) { - BJsonEntityCaps::BundleInfo info = {.name = restoreInfo.name, - .appIndex = restoreInfo.appIndex, - .versionCode = restoreInfo.versionCode, - .versionName = restoreInfo.versionName, - .spaceOccupied = restoreInfo.spaceOccupied, - .allToBackup = restoreInfo.allToBackup, - .fullBackupOnly = restoreInfo.fullBackupOnly, - .extensionName = restoreInfo.extensionName, - .restoreDeps = restoreInfo.restoreDeps}; + BJsonEntityCaps::BundleInfo info = { + .name = restoreInfo.name, .appIndex = restoreInfo.appIndex, + .versionCode = restoreInfo.versionCode, .versionName = restoreInfo.versionName, + .spaceOccupied = restoreInfo.spaceOccupied, .allToBackup = restoreInfo.allToBackup, + .fullBackupOnly = restoreInfo.fullBackupOnly, .extensionName = restoreInfo.extensionName, + .restoreDeps = restoreInfo.restoreDeps + }; restoreBundleInfos.emplace_back(info); continue; } @@ -621,15 +617,13 @@ static vector GetRestoreBundleNames(UniqueFd fd, HILOGE("Bundle not need restore, bundleName is %{public}s.", restoreInfo.name.c_str()); continue; } - BJsonEntityCaps::BundleInfo info = {.name = (*it).name, - .appIndex = (*it).appIndex, - .versionCode = (*it).versionCode, - .versionName = (*it).versionName, - .spaceOccupied = (*it).spaceOccupied, - .allToBackup = (*it).allToBackup, - .fullBackupOnly = (*it).fullBackupOnly, - .extensionName = restoreInfo.extensionName, - .restoreDeps = restoreInfo.restoreDeps}; + BJsonEntityCaps::BundleInfo info = { + .name = (*it).name, .appIndex = (*it).appIndex, + .versionCode = (*it).versionCode, .versionName = (*it).versionName, + .spaceOccupied = (*it).spaceOccupied, .allToBackup = (*it).allToBackup, + .fullBackupOnly = (*it).fullBackupOnly, .extensionName = restoreInfo.extensionName, + .restoreDeps = restoreInfo.restoreDeps + }; restoreBundleInfos.emplace_back(info); } HILOGI("restoreBundleInfos size is:%{public}zu", restoreInfos.size()); @@ -648,6 +642,8 @@ void Service::HandleExceptionOnAppendBundles(sptr session, [&bundleName](const auto &obj) { return obj == bundleName; }); if (it == restoreBundleNames.end()) { HILOGE("AppendBundles failed, bundleName = %{public}s.", bundleName.c_str()); + AppStatReportErr(bundleName, "HandleExceptionOnAppendBundles", + RadarError(MODULE_BMS, BError(BError::Codes::SA_BUNDLE_INFO_EMPTY))); OnBundleStarted(BError(BError::Codes::SA_BUNDLE_INFO_EMPTY), session, bundleName); } } @@ -672,9 +668,7 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, int32_t userId) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - if (totalStatistic_ != nullptr) { - totalStatistic_->totalSpendTime_.Start(); - } + TotalStart(); HILOGI("Begin"); try { if (session_ == nullptr || isOccupyingSession_.load()) { @@ -740,6 +734,8 @@ void Service::SetCurrentSessProperties(std::vector std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name, restoreInfo.appIndex); if ((!restoreInfo.allToBackup && !SpecialVersion(restoreInfo.versionName)) || (restoreInfo.extensionName.empty() && !SAUtils::IsSABundleName(restoreInfo.name))) { + AppStatReportErr(restoreInfo.name, "SetCurrentSessProperties", + RadarError(MODULE_BMS, BError(BError::Codes::SA_FORBID_BACKUP_RESTORE))); OnBundleStarted(BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), session_, bundleNameIndexInfo); session_->RemoveExtInfo(bundleNameIndexInfo); continue; @@ -773,9 +769,7 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, int32_t userId) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - if (totalStatistic_ != nullptr) { - totalStatistic_->totalSpendTime_.Start(); - } + TotalStart(); try { if (session_ == nullptr || isOccupyingSession_.load()) { HILOGE("AppendBundles restore session error, session is empty"); @@ -834,12 +828,14 @@ void Service::SetCurrentSessProperties( }); if (it == restoreBundleNames.end()) { HILOGE("Can not find current bundle, bundleName:%{public}s, appIndex:%{public}d", restoreInfo.name.c_str(), - restoreInfo.appIndex); + restoreInfo.appIndex); continue; } std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name, restoreInfo.appIndex); if ((!restoreInfo.allToBackup && !SpecialVersion(restoreInfo.versionName)) || (restoreInfo.extensionName.empty() && !SAUtils::IsSABundleName(restoreInfo.name))) { + AppStatReportErr(restoreInfo.name, "SetCurrentSessProperties", + RadarError(MODULE_BMS, BError(BError::Codes::SA_FORBID_BACKUP_RESTORE))); OnBundleStarted(BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), session_, bundleNameIndexInfo); session_->RemoveExtInfo(bundleNameIndexInfo); continue; @@ -855,15 +851,11 @@ void Service::SetCurrentSessProperties( } BJsonUtil::BundleDetailInfo broadCastInfo; BJsonUtil::BundleDetailInfo uniCastInfo; - bool broadCastRet = - BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, BROADCAST_TYPE, broadCastInfo); - if (broadCastRet) { + if (BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, BROADCAST_TYPE, broadCastInfo)) { bool notifyRet = DelayedSingleton::GetInstance()->NotifyBundleDetail(broadCastInfo); HILOGI("Publish event end, notify result is:%{public}d", notifyRet); } - bool uniCastRet = - BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, UNICAST_TYPE, uniCastInfo); - if (uniCastRet) { + 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); } @@ -876,9 +868,7 @@ void Service::SetCurrentSessProperties( ErrCode Service::AppendBundlesBackupSession(const vector &bundleNames) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - if (totalStatistic_ != nullptr) { - totalStatistic_->totalSpendTime_.Start(); - } + TotalStart(); try { if (session_ == nullptr || isOccupyingSession_.load()) { HILOGE("AppendBundles backup session error, session is empty"); @@ -893,8 +883,10 @@ 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); @@ -918,9 +910,7 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun const vector &bundleInfos) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - if (totalStatistic_ != nullptr) { - totalStatistic_->totalSpendTime_.Start(); - } + TotalStart(); try { if (session_ == nullptr || isOccupyingSession_.load()) { HILOGE("AppendBundles backup session with infos error, session is empty"); @@ -940,8 +930,10 @@ 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); @@ -987,6 +979,7 @@ ErrCode Service::ServiceResultReport(const std::string& restoreRetInfo, BackupRe { string callerName; HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + UpdateHandleCnt(errCode); try { ErrCode ret = VerifyCallerAndGetCallerName(callerName); if (ret != ERR_OK) { @@ -1023,6 +1016,7 @@ ErrCode Service::ServiceResultReport(const std::string& restoreRetInfo, BackupRe ErrCode Service::SAResultReport(const std::string bundleName, const std::string restoreRetInfo, const ErrCode errCode, const BackupRestoreScenario sennario) { + UpdateHandleCnt(errCode); SADone(errCode, bundleName); if (sennario == BackupRestoreScenario::FULL_RESTORE) { session_->GetServiceReverseProxy()->RestoreOnResultReport(restoreRetInfo, bundleName, ERR_OK); @@ -1824,6 +1818,11 @@ AAFwk::Want Service::CreateConnectWant(const BundleName &bundleName) ErrCode Service::BackupSA(std::string bundleName) { HILOGI("BackupSA begin %{public}s", bundleName.c_str()); + if (totalStatistic_ != nullptr) { + saStatistic_ = std::make_shared(bundleName, totalStatistic_->GetUniqId(), + totalStatistic_->GetBizScene()); + saStatistic_->doBackupSpend_.Start(); + } IServiceReverseType::Scenario scenario = session_->GetScenario(); auto backUpConnection = session_->GetSAExtConnection(bundleName); std::shared_ptr saConnection = backUpConnection.lock(); @@ -1848,11 +1847,12 @@ ErrCode Service::BackupSA(std::string bundleName) } void Service::OnSABackup(const std::string &bundleName, const int &fd, const std::string &result, - const ErrCode &errCode) + const ErrCode &errCode) { + SaStatReport(bundleName, "OnSABackup", RadarError(MODULE_BACKUP, errCode)); auto task = [bundleName, fd, result, errCode, this]() { HILOGI("OnSABackup bundleName: %{public}s, fd: %{public}d, result: %{public}s, err: %{public}d", - bundleName.c_str(), fd, result.c_str(), errCode); + bundleName.c_str(), fd, result.c_str(), errCode); BackupRestoreScenario scenario = BackupRestoreScenario::FULL_BACKUP; if (session_->GetIsIncrementalBackup()) { scenario = BackupRestoreScenario::INCREMENTAL_BACKUP; @@ -1875,6 +1875,7 @@ void Service::OnSABackup(const std::string &bundleName, const int &fd, const std void Service::OnSARestore(const std::string &bundleName, const std::string &result, const ErrCode &errCode) { + SaStatReport(bundleName, "OnSARestore", RadarError(MODULE_BACKUP, errCode)); auto task = [bundleName, result, errCode, this]() { HILOGI("OnSARestore bundleName: %{public}s, result: %{public}s, err: %{public}d", bundleName.c_str(), result.c_str(), errCode); diff --git a/services/backup_sa/src/module_ipc/service_incremental.cpp b/services/backup_sa/src/module_ipc/service_incremental.cpp index f0bac2704cbe55a181f76351d413ab57249b84f8..adfbf0e69ecc569dbdcc5bd8280cf44036668b68 100644 --- a/services/backup_sa/src/module_ipc/service_incremental.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental.cpp @@ -391,6 +391,7 @@ vector Service::GetBundleNameByDetails(const std::vector &bundlesToBackup) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + TotalStart(); vector bundleNames; try { if (session_ == nullptr || isOccupyingSession_.load()) { @@ -406,8 +407,10 @@ 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); @@ -438,6 +441,7 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vector &infos) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + TotalStart(); vector bundleNames; try { if (session_ == nullptr || isOccupyingSession_.load()) { @@ -458,8 +462,10 @@ 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); @@ -546,6 +552,11 @@ ErrCode Service::PublishSAIncrementalFile(const BFileInfo& fileInfo, int fd) ErrCode Service::PublishSAIncrementalFile(const BFileInfo &fileInfo, UniqueFd fd) { std::string bundleName = fileInfo.owner; + if (totalStatistic_ != nullptr) { + saStatistic_ = std::make_shared(bundleName, totalStatistic_->GetUniqId(), + totalStatistic_->GetBizScene()); + saStatistic_->doRestoreStart_ = TimeUtils::GetTimeMS(); + } ErrCode errCode = VerifyCaller(); if (errCode != ERR_OK) { HILOGE("PublishSAIncrementalFile failed, verify caller failed, bundleName:%{public}s, errCode:%{public}d", @@ -829,6 +840,11 @@ ErrCode Service::HelpToAppIncrementalFileReady(const string &bundleName, const s ErrCode Service::IncrementalBackupSA(std::string bundleName) { HILOGI("IncrementalBackupSA begin %{public}s", bundleName.c_str()); + if (totalStatistic_ != nullptr) { + saStatistic_ = std::make_shared(bundleName, totalStatistic_->GetUniqId(), + totalStatistic_->GetBizScene()); + saStatistic_->doBackupSpend_.Start(); + } IServiceReverseType::Scenario scenario = session_->GetScenario(); auto backUpConnection = session_->GetSAExtConnection(bundleName); std::shared_ptr saConnection = backUpConnection.lock(); @@ -854,6 +870,7 @@ ErrCode Service::IncrementalBackupSA(std::string bundleName) void Service::NotifyCallerCurAppIncrementDone(ErrCode errCode, const std::string &callerName) { + UpdateHandleCnt(errCode); IServiceReverseType::Scenario scenario = session_->GetScenario(); if (scenario == IServiceReverseType::Scenario::BACKUP) { HILOGI("will notify clone data, scenario is incremental backup"); diff --git a/services/backup_sa/src/module_ipc/sub_service.cpp b/services/backup_sa/src/module_ipc/sub_service.cpp index af34f0b6f25a94f62f60a401b69e83dd2acdb2fc..2ccb52d2a3727082aa1c747b0e1f97d937d009d1 100644 --- a/services/backup_sa/src/module_ipc/sub_service.cpp +++ b/services/backup_sa/src/module_ipc/sub_service.cpp @@ -45,6 +45,7 @@ #include "b_ohos/startup/backup_para.h" #include "b_process/b_multiuser.h" #include "b_radar/b_radar.h" +#include "b_radar/radar_app_statistic.h" #include "b_resources/b_constants.h" #include "b_sa/b_sa_utils.h" #include "b_utils/b_time.h" @@ -549,6 +550,8 @@ void Service::HandleNotSupportBundleNames(const std::vector &srcBun continue; } HILOGE("bundleName:%{public}s, can not find from supportBundleNames", bundleName.c_str()); + AppStatReportErr(bundleName, "HandleNotSupportBundleNames", + RadarError(MODULE_HAP, BError(BError::Codes::SA_BUNDLE_INFO_EMPTY))); if (isIncBackup) { session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted( BError(BError::Codes::SA_BUNDLE_INFO_EMPTY), bundleName); @@ -609,6 +612,33 @@ void Service::GetOldDeviceBackupVersion() HILOGI("backupVersion of old device = %{public}s", oldBackupVersion.c_str()); } +void Service::AppStatReportErr(const string &bundleName, const string &func, RadarError error) +{ + if (totalStatistic_ == nullptr) { + HILOGE("totalStat is null. appStatReport func:%{public}s, err: %{public}s", func.c_str(), + error.errMsg_.c_str()); + return; + } + RadarAppStatistic appStatistic(bundleName, totalStatistic_->GetUniqId(), totalStatistic_->GetBizScene()); + appStatistic.ReportError(func, error); +} + +void Service::SaStatReport(const string &bundleName, const string &func, RadarError err) +{ + if (totalStatistic_ == nullptr) { + HILOGE("totalStat is null. appStatReport func:%{public}s, err: %{public}s", func.c_str(), + err.errMsg_.c_str()); + return; + } + if (saStatistic_ == nullptr) { + saStatistic_ = std::make_shared(bundleName, totalStatistic_->GetUniqId(), + totalStatistic_->GetBizScene()); + } + saStatistic_->doBackupSpend_.End(); + saStatistic_->doRestoreSpend_ = TimeUtils::GetSpendMS(saStatistic_->doRestoreStart_); + saStatistic_->ReportSA(func, err); +} + void Service::ExtConnectDied(const string &callName) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); @@ -626,6 +656,8 @@ void Service::ExtConnectDied(const string &callName) auto backUpConnection = session_->GetExtConnection(callName); if (backUpConnection != nullptr && backUpConnection->IsExtAbilityConnected()) { backUpConnection->DisconnectBackupExtAbility(); + AppStatReportErr(callName, "ExtConnectDied", RadarError(MODULE_ABILITY_MGR_SVC, + backUpConnection->GetError())); } bool needCleanData = session_->GetClearDataFlag(callName); if (!needCleanData || SAUtils::IsSABundleName(callName)) { @@ -721,8 +753,6 @@ void Service::TotalStatReport(ErrCode errCode) return; } totalStatistic_->totalSpendTime_.End(); - totalStatistic_->succBundleCount_ = successBundlesNum_.load(); - totalStatistic_->failBundleCount_ = failedBundles_.size(); totalStatistic_->Report("OnAllBundlesFinished", errCode); } diff --git a/services/backup_sa/src/module_ipc/svc_backup_connection.cpp b/services/backup_sa/src/module_ipc/svc_backup_connection.cpp index 8aba251e0ce33fa4145740b958b7b9542c824e72..6ca871b1db8dc1fcfd0126bfaf38e61dea1f38b4 100644 --- a/services/backup_sa/src/module_ipc/svc_backup_connection.cpp +++ b/services/backup_sa/src/module_ipc/svc_backup_connection.cpp @@ -89,6 +89,7 @@ void SvcBackupConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName } bundleName = bundleNameIndexInfo_; if (isConnectCalled_ == true) { + error_ = BError(resultCode, BError::Codes::EXT_ABILITY_DIED); if (isCleanCalled_ == true) { HILOGE("It's error that the backup extension clean died before the backup sa. name : %{public}s", bundleName.data()); diff --git a/tests/mock/b_radar/include/hisysevent_mock.h b/tests/mock/b_radar/include/hisysevent_mock.h new file mode 100644 index 0000000000000000000000000000000000000000..c7946085b1c6d90ac9a5aa9f3424ed360d09fa28 --- /dev/null +++ b/tests/mock/b_radar/include/hisysevent_mock.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_BACKUP_HISYSEVENT_MOCK_H +#define OHOS_FILEMGMT_BACKUP_HISYSEVENT_MOCK_H + +#include +#include + +namespace OHOS::FileManagement::Backup { + +class HiSysEventMock { +public: + static void HiSysEventWriteMock(const std::string&) {} +}; +} // namespace OHOS::FileManagement::Backup +#endif // OHOS_FILEMGMT_BACKUP_HISYSEVENT_MOCK_H \ No newline at end of file diff --git a/tests/unittests/backup_ext/ext_extension_test.cpp b/tests/unittests/backup_ext/ext_extension_test.cpp index 8471b72d44daa93c1843eaff8e5f4111070be7df..4580a54b23ffa2e0a29c959c75d73eae0a06c0d2 100644 --- a/tests/unittests/backup_ext/ext_extension_test.cpp +++ b/tests/unittests/backup_ext/ext_extension_test.cpp @@ -396,96 +396,6 @@ HWTEST_F(ExtExtensionTest, Ext_Extension_Test_0603, testing::ext::TestSize.Level GTEST_LOG_(INFO) << "ExtExtensionTest-end Ext_Extension_Test_0603"; } -/** - * @tc.number: SUB_Ext_Extension_0700 - * @tc.name: Ext_Extension_Test_0700 - * @tc.desc: 测试file为空 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I9P3Y3 - */ -HWTEST_F(ExtExtensionTest, Ext_Extension_Test_0700, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ExtExtensionTest-begin Ext_Extension_Test_0700"; - try { - vector files; - TarMap result = GetIncrmentBigInfos(files); - EXPECT_TRUE(result.empty()); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ExtExtensionTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ExtExtensionTest-end Ext_Extension_Test_0700"; -} - -/** - * @tc.number: SUB_Ext_Extension_0701 - * @tc.name: Ext_Extension_Test_0701 - * @tc.desc: 测试file只有一个元素 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I9P3Y3 - */ -HWTEST_F(ExtExtensionTest, Ext_Extension_Test_0701, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ExtExtensionTest-begin Ext_Extension_Test_0701"; - try { - vector srcFiles; - struct ReportFileInfo info; - info.filePath = PATH + BUNDLE_NAME; - info.mode = "755"; - info.isDir = 0; - info.size = 1024; - info.mtime = 123456789; - info.hash = "1234567890"; - info.userTar = 1; - info.encodeFlag = false; - srcFiles.push_back(info); - TarMap result = GetIncrmentBigInfos(srcFiles); - EXPECT_EQ(result.size(), 1); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ExtExtensionTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ExtExtensionTest-end Ext_Extension_Test_0701"; -} - -/** - * @tc.number: SUB_Ext_Extension_0702 - * @tc.name: Ext_Extension_Test_0702 - * @tc.desc: 测试file有重复元素 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I9P3Y3 - */ -HWTEST_F(ExtExtensionTest, Ext_Extension_Test_0702, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ExtExtensionTest-begin Ext_Extension_Test_0702"; - try { - vector srcFiles; - struct ReportFileInfo info; - info.filePath = PATH + BUNDLE_NAME; - info.mode = "755"; - info.isDir = 0; - info.size = 1024; - info.mtime = 123456789; - info.hash = "1234567890"; - info.userTar = 1; - info.encodeFlag = false; - srcFiles.push_back(info); - srcFiles.push_back(info); - TarMap result = GetIncrmentBigInfos(srcFiles); - EXPECT_EQ(result.size(), 2); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ExtExtensionTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "ExtExtensionTest-end Ext_Extension_Test_0702"; -} - /** * @tc.number: SUB_Ext_Extension_0800 * @tc.name: Ext_Extension_Test_0800 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 5c80651bfe8ab224b4c00762099ff849795aa641..1d175cf2535e8ea6985b4a52758f9d0f15dd1cd7 100644 --- a/tests/unittests/backup_sa/module_ipc/service_other_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_other_test.cpp @@ -771,7 +771,8 @@ HWTEST_F(ServiceTest, SUB_Service_GetRestoreBundleNames_0100, TestSize.Level1) std::string backupVersion; EXPECT_CALL(*session, GetSessionUserId()).WillOnce(Return(0)); EXPECT_CALL(*bms, GetBundleInfos(_, _)).WillOnce(Return(bundleInfos)); - EXPECT_THROW(GetRestoreBundleNames(UniqueFd(-1), service->session_, bundleNames, backupVersion), BError); + EXPECT_THROW(service->GetRestoreBundleNames(UniqueFd(-1), service->session_, bundleNames, backupVersion), + BError); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetRestoreBundleNames."; diff --git a/tests/unittests/backup_utils/BUILD.gn b/tests/unittests/backup_utils/BUILD.gn index 4ef61325c94c5071922fcd4d0870c54bbba1bd75..95f06a13b4b0507da350bc59613fe62f24bdb08c 100644 --- a/tests/unittests/backup_utils/BUILD.gn +++ b/tests/unittests/backup_utils/BUILD.gn @@ -422,6 +422,45 @@ ohos_unittest("b_utils_test") { use_exceptions = true } +ohos_unittest("b_radar_test") { + module_out_path = path_module_out_tests + + sources = [ + "${path_backup}/tests/unittests/backup_utils/b_radar/b_radar_test.cpp", + ] + sources += backup_mock_parameter_src + + include_dirs = [ + "${path_backup}/utils", + "${path_backup}/tests/mock/b_radar/include", + ] + include_dirs += backup_mock_parameter_include_dirs + + deps = [ + "${path_backup}/interfaces/innerkits/native:sandbox_helper_native", + "${path_backup}/tests/utils:backup_test_utils", + "${path_backup}/utils/:backup_utils", + ] + + external_deps = [ + "cJSON:cjson", + "c_utils:utils", + "googletest:gmock_main", + "googletest:gtest_main", + "hilog:libhilog", + "jsoncpp:jsoncpp", + ] + + defines = [ + "LOG_TAG=\"app_file_service\"", + "LOG_DOMAIN=0xD004303", + "private = public", + "protected = public", + ] + + use_exceptions = true +} + group("backup_utils_test") { testonly = true @@ -435,6 +474,7 @@ group("backup_utils_test") { ":b_jsonutil_other_test", ":b_jsonutil_test", ":b_process_test", + ":b_radar_test", ":b_tarball_cmdline_test", ":b_tarball_factory_test", ":b_utils_test", diff --git a/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp b/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp index 38663e9e9767facdda24997109c97b197399e361..c1bd86ca017f04dd5d056a4a1e49b47b86694875 100644 --- a/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp +++ b/tests/unittests/backup_utils/b_filesystem/b_dir_test.cpp @@ -38,8 +38,6 @@ public: static void TearDownTestCase() {}; void SetUp() {}; void TearDown() {}; -protected: - std::shared_ptr appStatistic_ = std::make_shared(); }; /** @@ -147,7 +145,7 @@ HWTEST_F(BDirTest, b_dir_GetBigFiles_0100, testing::ext::TestSize.Level1) EXPECT_EQ(ret, 0); vector includes = {rootDir}; vector excludes = {filePath2}; - auto [errCode, mpNameToStat, smallFiles] = BDir::GetBigFiles(includes, excludes, appStatistic_); + auto [errCode, mpNameToStat, smallFiles] = BDir::GetBigFiles(includes, excludes); EXPECT_EQ(errCode, ERR_OK); EXPECT_EQ(mpNameToStat.at(filePath1).st_size, 1024 * 1024 * 3); EXPECT_EQ(mpNameToStat.find(filePath2), mpNameToStat.end()); @@ -173,7 +171,7 @@ HWTEST_F(BDirTest, b_dir_GetBigFiles_0200, testing::ext::TestSize.Level1) try { vector includes = {{}, {}}; vector excludes = {{}}; - auto [errCode, mpNameToStat, smallFiles] = BDir::GetBigFiles(includes, excludes, appStatistic_); + auto [errCode, mpNameToStat, smallFiles] = BDir::GetBigFiles(includes, excludes); EXPECT_EQ(errCode, ERR_OK); } catch (...) { EXPECT_TRUE(false); @@ -197,7 +195,7 @@ HWTEST_F(BDirTest, b_dir_GetBigFiles_0201, testing::ext::TestSize.Level1) try { vector includes = {"/data/"}; vector excludes; - auto [errCode, mpNameToStat, smallFiles] = BDir::GetBigFiles(includes, excludes, appStatistic_); + auto [errCode, mpNameToStat, smallFiles] = BDir::GetBigFiles(includes, excludes); EXPECT_EQ(errCode, ERR_OK); } catch (...) { EXPECT_TRUE(false); @@ -221,7 +219,7 @@ HWTEST_F(BDirTest, b_dir_GetBigFiles_0202, testing::ext::TestSize.Level1) try { vector includes = {"/data/app/"}; vector excludes; - auto [errCode, mpNameToStat, smallFiles] = BDir::GetBigFiles(includes, excludes, appStatistic_); + auto [errCode, mpNameToStat, smallFiles] = BDir::GetBigFiles(includes, excludes); EXPECT_EQ(errCode, ERR_OK); } catch (...) { EXPECT_TRUE(false); @@ -246,7 +244,7 @@ HWTEST_F(BDirTest, b_dir_GetBigFiles_0203, testing::ext::TestSize.Level1) vector includes; vector excludes; const string str = ""; - auto [errCode, mpNameToStat, smallFiles] = BDir::GetBigFiles(includes, excludes, appStatistic_); + auto [errCode, mpNameToStat, smallFiles] = BDir::GetBigFiles(includes, excludes); EXPECT_EQ(errCode, ERR_OK); } catch (...) { EXPECT_TRUE(false); @@ -287,7 +285,7 @@ HWTEST_F(BDirTest, b_dir_GetBigFiles_0300, testing::ext::TestSize.Level1) system(touchFilePrefix.append("c.txt").c_str()); vector includes = {preparedDir + string("/*"), preparedDir + string("test")}; vector excludes = {preparedDir + string("/test/test1/test2"), {}}; - auto [errCode, mpNameToStat, smallFiles] = BDir::GetBigFiles(includes, excludes, appStatistic_); + auto [errCode, mpNameToStat, smallFiles] = BDir::GetBigFiles(includes, excludes); EXPECT_EQ(errCode, ERR_OK); } catch (...) { EXPECT_TRUE(false); diff --git a/tests/unittests/backup_utils/b_radar/b_radar_test.cpp b/tests/unittests/backup_utils/b_radar/b_radar_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..173a0d9b4481d3605afa4f0354609b72ce9a21ad --- /dev/null +++ b/tests/unittests/backup_utils/b_radar/b_radar_test.cpp @@ -0,0 +1,227 @@ +/* + * Copyright (c) 2025-2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include + +#include +#include +#include +#include + +#include "hisysevent_mock.h" +#include "b_radar/radar_app_statistic.h" +#include "b_radar/radar_total_statistic.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; +using namespace testing; +using namespace testing::ext; + +#define HiSysEventWrite(domain, eventName, type, ...) HiSysEventMock::HiSysEventWriteMock(eventName) + +class BRadarTest : public testing::Test { +public: + static void SetUpTestCase(void) {}; + static void TearDownTestCase() {}; + void SetUp() + { + appStatistic_ = std::make_shared(); + }; + void TearDown() {}; +protected: + std::shared_ptr appStatistic_ = nullptr; + std::shared_ptr totalStatistic_ = nullptr; +}; + +HWTEST_F(BRadarTest, DURATION_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BRadarTest-begin DURATION_0100"; + try { + Duration d1 = {5, 10}; + EXPECT_EQ(d1.GetSpan(), 5); + Duration d2 = {0, 10}; + EXPECT_EQ(d2.GetSpan(), 0); + Duration d3 = {10, 5}; + EXPECT_EQ(d3.GetSpan(), 0); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BRadarTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BRadarTest-end DURATION_0100"; +} + +HWTEST_F(BRadarTest, RadarErrorCode_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BRadarTest-begin RadarErrorCode_0100"; + try { + RadarError err(BError{BError::Codes::EXT_INVAL_ARG}); + EXPECT_EQ(err.error_, 13920); + EXPECT_EQ(err.GenCode(), static_cast(((SUB_SYSTEM_ID & MASK_SYS) << MOVE_BIT_SYS) + | ((MODULE_UNKNOWN & MASK_MODULE) << MOVE_BIT_MODULE) | (13920 & MASK_ERROR))); + err.UpdateByBError(BError(139000020)); + EXPECT_EQ(err.error_, 13942); + RadarError err2(MODULE_ABILITY_MGR_SVC, BError(BError::Codes::OK)); + EXPECT_EQ(err2.GenCode(), 0); + EXPECT_EQ(err2.moduleId_, MODULE_ABILITY_MGR_SVC); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BRadarTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BRadarTest-end RadarErrorCode_0100"; +} + +HWTEST_F(BRadarTest, TOTAL_CONSTRUCTOR_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BRadarTest-begin TOTAL_CONSTRUCTOR_0100"; + try { + std::string caller = "ut_caller"; + RadarTotalStatistic totalStatistic1(BizScene::BACKUP, caller, Mode::INCREMENTAL); + EXPECT_EQ(totalStatistic1.bizScene_, BizScene::BACKUP); + EXPECT_EQ(totalStatistic1.mode_, Mode::INCREMENTAL); + 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_); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BRadarTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BRadarTest-end TOTAL_CONSTRUCTOR_0100"; +} + +HWTEST_F(BRadarTest, TOTAL_REPORT_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BRadarTest-begin TOTAL_REPORT_0100"; + try { + std::string caller = "ut_caller"; + totalStatistic_ = std::make_shared(BizScene::BACKUP, caller); + totalStatistic_->Report("TOTAL_REPORT_0100", 0); + totalStatistic_->Report("TOTAL_REPORT_0100", MODULE_INIT, 10); + totalStatistic_->Report("TOTAL_REPORT_0100", BError(), MODULE_INIT); + EXPECT_TRUE(true); + totalStatistic_ = std::make_shared(BizScene::RESTORE, caller); + totalStatistic_->Report("TOTAL_REPORT_0100", 0); + totalStatistic_->Report("TOTAL_REPORT_0100", MODULE_BMS, 20); + totalStatistic_->Report("TOTAL_REPORT_0100", BError(BError::Codes::TOOL_INVAL_ARG), MODULE_INIT); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BRadarTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BRadarTest-end TOTAL_REPORT_0100"; +} + +HWTEST_F(BRadarTest, FileTypeStat001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BRadarTest-begin FileTypeStat001"; + try { + FileTypeStat fileTypeStat; + EXPECT_EQ(fileTypeStat.GetListSize(), TYPE_DEF_COUNT); + fileTypeStat.UpdateStat("txt", 1024); + EXPECT_EQ(fileTypeStat.GetListPtr()[0].count, 1); + EXPECT_EQ(fileTypeStat.GetListPtr()[0].size, 1024); + fileTypeStat.UpdateStat("jpg", 1024); + EXPECT_EQ(fileTypeStat.GetListPtr()[1].count, 1); + EXPECT_EQ(fileTypeStat.GetListPtr()[1].size, 1024); + fileTypeStat.UpdateStat("wav", 1024); + EXPECT_EQ(fileTypeStat.GetListPtr()[2].count, 1); + EXPECT_EQ(fileTypeStat.GetListPtr()[2].size, 1024); + fileTypeStat.UpdateStat("mov", 1024); + EXPECT_EQ(fileTypeStat.GetListPtr()[3].count, 1); + EXPECT_EQ(fileTypeStat.GetListPtr()[3].size, 1024); + fileTypeStat.UpdateStat("rar", 1024); + EXPECT_EQ(fileTypeStat.GetListPtr()[4].count, 1); + EXPECT_EQ(fileTypeStat.GetListPtr()[4].size, 1024); + fileTypeStat.UpdateStat("exe", 1024); + EXPECT_EQ(fileTypeStat.GetListPtr()[5].count, 1); + EXPECT_EQ(fileTypeStat.GetListPtr()[5].size, 1024); + fileTypeStat.UpdateStat("com", 1024); + EXPECT_EQ(fileTypeStat.GetListPtr()[6].count, 1); + EXPECT_EQ(fileTypeStat.GetListPtr()[6].size, 1024); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BRadarTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BRadarTest-end FileTypeStat001"; +} + +HWTEST_F(BRadarTest, FileSizeStat001, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BRadarTest-begin FileSizeStat001"; + try { + FileSizeStat fileSizeStat; + EXPECT_EQ(fileSizeStat.GetListSize(), SIZE_DEF_COUNT); + fileSizeStat.UpdateStat(1024); + EXPECT_EQ(fileSizeStat.GetListPtr()[0].count, 1); + EXPECT_EQ(fileSizeStat.GetListPtr()[0].size, 1024); + fileSizeStat.UpdateStat(ONE_MB); + EXPECT_EQ(fileSizeStat.GetListPtr()[1].count, 1); + EXPECT_EQ(fileSizeStat.GetListPtr()[1].size, ONE_MB); + fileSizeStat.UpdateStat(ONE_MB); + EXPECT_EQ(fileSizeStat.GetListPtr()[1].count, 2); + EXPECT_EQ(fileSizeStat.GetListPtr()[1].size, TWO_MB); + fileSizeStat.UpdateStat(TWO_MB); + EXPECT_EQ(fileSizeStat.GetListPtr()[2].count, 1); + EXPECT_EQ(fileSizeStat.GetListPtr()[2].size, TWO_MB); + fileSizeStat.UpdateStat(TEN_MB); + EXPECT_EQ(fileSizeStat.GetListPtr()[3].count, 1); + EXPECT_EQ(fileSizeStat.GetListPtr()[3].size, TEN_MB); + fileSizeStat.UpdateStat(HUNDRED_MB); + EXPECT_EQ(fileSizeStat.GetListPtr()[4].count, 1); + EXPECT_EQ(fileSizeStat.GetListPtr()[4].size, HUNDRED_MB); + fileSizeStat.UpdateStat(ONE_GB); + EXPECT_EQ(fileSizeStat.GetListPtr()[5].count, 1); + EXPECT_EQ(fileSizeStat.GetListPtr()[5].size, ONE_GB); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BRadarTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BRadarTest-end FileSizeStat001"; +} + +HWTEST_F(BRadarTest, RADAR_APP_STAT_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "BRadarTest-begin RADAR_APP_STAT_0100"; + try { + appStatistic_->UpdateFileDist("txt", 1024); + EXPECT_EQ(appStatistic_->fileSizeDist_.GetListPtr()[0].count, 1); + EXPECT_EQ(appStatistic_->fileSizeDist_.GetListPtr()[0].size, 1024); + EXPECT_EQ(appStatistic_->fileTypeDist_.GetListPtr()[0].count, 1); + EXPECT_EQ(appStatistic_->fileTypeDist_.GetListPtr()[0].size, 1024); + + appStatistic_->SetUniqId(100); + EXPECT_EQ(appStatistic_->uniqId_, 100); + appStatistic_->sendRateZeroStart_ = 5; + appStatistic_->UpdateSendRateZeroSpend(); + EXPECT_EQ(appStatistic_->sendRateZeroStart_, 0); + + appStatistic_->ReportBackup("RADAR_APP_STAT_0100", BError(BError::Codes::OK)); + appStatistic_->ReportRestore("RADAR_APP_STAT_0100", BError(BError::Codes::OK)); + EXPECT_TRUE(true); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "BRadarTest-an exception occurred."; + } + GTEST_LOG_(INFO) << "BRadarTest-end RADAR_APP_STAT_0100"; +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/include/b_error/b_error.h b/utils/include/b_error/b_error.h index de3b502c3e02c52cf5355d5790ebd82360cb9c84..bf4fba516a2097c63ef023a0bf4029425a279538 100644 --- a/utils/include/b_error/b_error.h +++ b/utils/include/b_error/b_error.h @@ -42,6 +42,8 @@ namespace OHOS::FileManagement::Backup { using ErrCode = int; using ErrParam = std::function()>; +constexpr int32_t ERROR_OK = 0; + class BError : public std::exception { public: /** @@ -162,6 +164,25 @@ public: return msg_.c_str(); } + int32_t GetExternalErr() + { + return externalErr_; + } + + std::string GetExtraInfo() + { + return extraInfo_; + } + + std::string ToString() + { + std::string msg = "externalErr=" + std::to_string(externalErr_); + if (!extraInfo_.empty()) { + msg += ", extraInfo=" + extraInfo_; + } + return msg; + } + /** * @brief 归一返回备份恢复错误码 * @@ -211,6 +232,12 @@ public: msg_ = WrapMessageWithExtraInfos(fileName, lineNo, functionName, code_, {mpErrToMsg_.at(code_)}); } + explicit BError(int32_t externalErr, Codes code, std::string extraInfo = "", DEFINE_SOURCE_LOCATION) + : code_(code), externalErr_(externalErr), extraInfo_(extraInfo) + { + msg_ = WrapMessageWithExtraInfos(fileName, lineNo, functionName, code_, {mpErrToMsg_.at(code_)}); + } + /** * @brief 构造错误对象 * @@ -377,6 +404,8 @@ private: private: Codes code_ {Codes::OK}; std::string msg_; + int32_t externalErr_ = ERROR_OK; + std::string extraInfo_; private: /** diff --git a/utils/include/b_filesystem/b_dir.h b/utils/include/b_filesystem/b_dir.h index 3a50241de50a34ec7bfe95576237298de2f17159..c4d89d1c8a71c9ac39541b5955bf1d158494b8dc 100644 --- a/utils/include/b_filesystem/b_dir.h +++ b/utils/include/b_filesystem/b_dir.h @@ -59,8 +59,7 @@ public: * @return 错误码、大文件名集合 */ static std::tuple, std::map> GetBigFiles( - const std::vector &includes, const std::vector &excludes, - std::shared_ptr appStatistic); + const std::vector &includes, const std::vector &excludes); /** * @brief Get the Dirs object @@ -119,6 +118,11 @@ public: * @return 是否存在软连接 */ static bool CheckAndRmSoftLink(const EndFileInfo &filePaths); + + /** + * @brief 判断目录列表是否包含路径 + */ + static bool IsDirsMatch(const std::vector &excludePaths, const std::string &path); }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/include/b_filesystem/b_file.h b/utils/include/b_filesystem/b_file.h index 976afc300f249375689efa3480b9f08afb5bb8df..2206bd42246a9fc0ca97cbc69b9ea5989fbdf475 100644 --- a/utils/include/b_filesystem/b_file.h +++ b/utils/include/b_filesystem/b_file.h @@ -97,10 +97,11 @@ public: * @brief get file size by path * * @param path file path + * @param error 错误码 * @return 0 if path is invalid * @return file size in byte if path is valid */ - static uint64_t GetFileSize(const string &path); + static uint64_t GetFileSize(const string &path, int32_t &error); private: }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/include/b_radar/radar_app_statistic.h b/utils/include/b_radar/radar_app_statistic.h index eb3a933ac613d5098372069b3a193a5f2fb681f6..8bd071ada1dcd5fd7e23569ad11c554171de856a 100644 --- a/utils/include/b_radar/radar_app_statistic.h +++ b/utils/include/b_radar/radar_app_statistic.h @@ -114,9 +114,10 @@ public: uint64_t bigFileSize_ = 0; uint32_t tarFileCount_ = 0; uint64_t tarFileSize_ = 0; - uint32_t dirDepth_ = 0; + uint32_t dirDepth_ = BConstants::APP_BASE_PATH_DEPTH; uint64_t tarBoundSize_ = BConstants::BIG_FILE_BOUNDARY; uint64_t manageJsonSize_ = 0; + Duration getExtInfoSpend_ = {0, 0}; uint32_t extConnectSpend_ = 0; Duration onBackupSpend_ = {0, 0}; @@ -132,9 +133,12 @@ public: Duration onRestoreexSpend_ = {0, 0}; uint32_t untarSpend_ = 0; uint32_t bigFileSpend_ = 0; + uint64_t doRestoreStart_ = 0; uint32_t doRestoreSpend_ = 0; RadarAppStatistic() {}; + RadarAppStatistic(std::string appCaller, int64_t uniqId, BizScene bizScene) + : appCaller_(appCaller), uniqId_(uniqId), bizScene_(bizScene) {} ~RadarAppStatistic() = default; RadarAppStatistic(const RadarAppStatistic &) = delete; RadarAppStatistic &operator=(const RadarAppStatistic &) = delete; @@ -144,15 +148,18 @@ public: void SetUniqId(int64_t uniqId) { uniqId_ = uniqId; }; void UpdateSendRateZeroSpend(); void UpdateFileDist(std::string fileExtension, uint64_t fileSize); - void ReportBackup(const std::string &func, int32_t errorCode = ERROR_OK); + void ReportBackup(const std::string &func, int32_t errorCode, std::string errMsg = ""); void ReportBackup(const std::string &func, BError errCode); - void ReportRestore(const std::string &func, int32_t errorCode = ERROR_OK); + void ReportRestore(const std::string &func, int32_t errorCode, std::string errMsg = ""); void ReportRestore(const std::string &func, BError errCode); + void ReportError(const std::string &func, RadarError error); + void ReportSA(const std::string &func, RadarError error); private: FileSizeStat fileSizeDist_; FileTypeStat fileTypeDist_; int64_t uniqId_ = 0; + BizScene bizScene_ = BizScene::UNKNOWN; }; } // namespace OHOS::FileManagement::Backup #endif // OHOS_FILEMGMT_BACKUP_RADAR_APP_STATISTIC_H diff --git a/utils/include/b_radar/radar_const.h b/utils/include/b_radar/radar_const.h index 6951c5c253191c3776e25a790a895893483e0b59..4d6767bafb16e09556f8c0bece30812d31f6d293 100644 --- a/utils/include/b_radar/radar_const.h +++ b/utils/include/b_radar/radar_const.h @@ -63,26 +63,31 @@ constexpr uint8_t MOVE_BIT_MODULE = 16; constexpr uint8_t MOVE_BIT_SYS = MOVE_BIT_MODULE + 5; constexpr int32_t DIVIDE_BASE = 1000; +constexpr int32_t ADDITION_DIVIDE_BASE = 10; constexpr int32_t MOD_BASE = 100; +constexpr int32_t TRANSFER_BOUND = 30000; // ERROR CODE -constexpr uint32_t SUB_SYSTEM_ID = 800; +constexpr uint32_t SUB_SYSTEM_ID = 231; constexpr uint32_t MODULE_UNKNOWN = 0; constexpr uint32_t MODULE_INIT = 1; constexpr uint32_t MODULE_BACKUP = 2; constexpr uint32_t MODULE_RESTORE = 3; -constexpr uint32_t MODULE_OTHER = 4; - -constexpr int32_t ERROR_OK = 0; +constexpr uint32_t MODULE_BMS = 4; +constexpr uint32_t MODULE_ABILITY_MGR_SVC = 5; +constexpr uint32_t MODULE_KERNEL = 6; +constexpr uint32_t MODULE_HAP = 7; +constexpr uint32_t MODULE_OTHER = 9; constexpr uint16_t ERR_VERIFY_CALLER_FAIL = 1000; constexpr uint16_t ERR_ACTIVE_SESSION_FAIL = 1001; +constexpr uint16_t ERR_EXT_CONNECT_FAIL = 5001; -struct RadarErrorCode { - RadarErrorCode(BError errCode) { SetByErrCode(errCode); } - RadarErrorCode(uint32_t moduleId, BError errCode) : moduleId_(moduleId) { SetByErrCode(errCode); } - RadarErrorCode(uint32_t moduleId) : moduleId_(moduleId) {} - RadarErrorCode(uint32_t moduleId, uint16_t error) : moduleId_(moduleId), error_(error) {} +struct RadarError { + RadarError(BError errCode) { UpdateByBError(errCode); } + RadarError(uint32_t moduleId, BError errCode) : moduleId_(moduleId) { UpdateByBError(errCode); } + RadarError(uint32_t moduleId) : moduleId_(moduleId) {} + RadarError(uint32_t moduleId, uint16_t error) : moduleId_(moduleId), error_(error) {} int32_t GenCode() { if (error_ == 0) { @@ -91,16 +96,32 @@ struct RadarErrorCode { return static_cast(((SUB_SYSTEM_ID & MASK_SYS) << MOVE_BIT_SYS) | ((moduleId_ & MASK_MODULE) << MOVE_BIT_MODULE) | (error_ & MASK_ERROR)); } - void SetByErrCode(BError errCode) + void UpdateByBError(BError errCode) { int32_t code = errCode.GetCode(); - error_ = static_cast(code / DIVIDE_BASE + code % MOD_BASE); + errMsg_ = errCode.ToString(); + if (code == 0) { + error_ = 0; + return; + } + int32_t errBase = code / DIVIDE_BASE; + while (errBase > TRANSFER_BOUND) { + errBase /= ADDITION_DIVIDE_BASE; + } + error_ = static_cast(errBase + code % MOD_BASE); } uint32_t moduleId_ = MODULE_UNKNOWN; uint16_t error_ = 0; + std::string errMsg_ = ""; }; +constexpr int32_t DEFAULT_STAGE = 1; +constexpr int32_t STAGE_RES_IDLE = 0; +constexpr int32_t STAGE_RES_SUCCESS = 1; +constexpr int32_t STAGE_RES_FAIL = 2; +constexpr int32_t STAGE_RES_CANCEL = 3; + constexpr char DOMAIN[] = "APP_FILE_SVC"; const std::string DOMAIN_NAME = "APP_FILE_SVC"; const std::string BACKUP_RESTORE_APP_STATISTIC = "BACKUP_RESTORE_APP_STATISTIC"; @@ -109,8 +130,11 @@ const std::string BACKUP_RESTORE_STATISTIC = "BACKUP_RESTORE_STATISTIC"; const std::string ORG_PKG = "ORG_PKG"; const std::string FUNC = "FUNC"; const std::string BIZ_SCENE = "BIZ_SCENE"; -const std::string UNIQUE_ID = "UNIQUE_ID"; +const std::string BIZ_STAGE = "BIZ_STAGE"; +const std::string STAGE_RES = "STAGE_RES"; +const std::string CONCURRENT_ID = "CONCURRENT_ID"; const std::string ERROR_CODE = "ERROR_CODE"; +const std::string ERROR_MSG = "ERROR_MSG"; const std::string HOST_PKG = "HOST_PKG"; const std::string APP_CALLER = "APP_CALLER"; @@ -127,6 +151,7 @@ const std::string TAR_BOUND_SIZE = "TAR_BOUND_SIZE"; const std::string DIR_DEPTH = "DIR_DEPTH"; const std::string MANAGE_JSON_SIZE = "MANAGE_JSON_SIZE"; const std::string EXTENSION_CONNECT_SPEND = "EXTENSION_CONNECT_SPEND"; +const std::string GET_EXT_INFO_SPEND = "GET_EXT_INFO_SPEND"; const std::string ON_BACKUP_SPEND = "ON_BACKUP_SPEND"; const std::string ON_BACKUPEX_SPEND = "ON_BACKUPEX_SPEND"; @@ -142,6 +167,7 @@ const std::string DO_RESTORE_SPEND = "DO_RESTORE_SPEND"; const std::string UNTAR_SPEND = "UNTAR_SPEND"; const std::string BIG_FILE_SPEND = "BIG_FILE_SPEND"; +const std::string GET_BUNDLE_INFO_SPEND = "GET_BUNDLE_INFO_SPEND"; const std::string TOTAL_SPEND = "TOTAL_SPEND"; const std::string SUCC_BUNDLE_CNT = "SUCC_BUNDLE_CNT"; const std::string FAIL_BUNDLE_CNT = "FAIL_BUNDLE_CNT"; diff --git a/utils/include/b_radar/radar_total_statistic.h b/utils/include/b_radar/radar_total_statistic.h index 71ddc161b7c9c59846c8ab220dd74a04f51d0a84..372868c0c9e4beb411efe01a33128fcafca17d92 100644 --- a/utils/include/b_radar/radar_total_statistic.h +++ b/utils/include/b_radar/radar_total_statistic.h @@ -16,6 +16,7 @@ #ifndef OHOS_FILEMGMT_BACKUP_RADAR_TOTAL_STATISTIC_H #define OHOS_FILEMGMT_BACKUP_RADAR_TOTAL_STATISTIC_H +#include #include "radar_const.h" #include "b_error/b_error.h" @@ -23,8 +24,9 @@ namespace OHOS::FileManagement::Backup { class RadarTotalStatistic { public: - uint32_t succBundleCount_ = 0; - uint32_t failBundleCount_ = 0; + std::atomic succBundleCount_ = 0; + std::atomic failBundleCount_ = 0; + Duration getBundleInfoSpend_ = {0, 0}; Duration totalSpendTime_ = {0, 0}; RadarTotalStatistic(BizScene bizScene, std::string caller, Mode mode = Mode::FULL); @@ -34,9 +36,10 @@ public: RadarTotalStatistic &operator=(RadarTotalStatistic &&) = delete; ~RadarTotalStatistic() = default; - void Report(const std::string &func, int32_t error = ERROR_OK); + void Report(const std::string &func, int32_t error, std::string errMsg = ""); void Report(const std::string &func, uint32_t moduleId, uint16_t moduleErr); void Report(const std::string &func, BError errCode, uint32_t moduleId = MODULE_UNKNOWN); + BizScene GetBizScene() { return bizScene_; } int64_t GetUniqId() { return uniqId_; } private: @@ -44,6 +47,8 @@ private: std::string hostPkg_ = ""; Mode mode_ = Mode::FULL; int64_t uniqId_ = 0; + std::atomic lastSuccCnt_ = 0; + std::atomic lastFailCnt_ = 0; }; } // namespace OHOS::FileManagement::Backup #endif // OHOS_FILEMGMT_BACKUP_RADAR_TOTAL_STATISTIC_H diff --git a/utils/src/b_filesystem/b_dir.cpp b/utils/src/b_filesystem/b_dir.cpp index 185d87356eeaa1e210a2d0159b7cacbb028c7127..b1da1f0e63455ddcd09340db04f70836db005887 100644 --- a/utils/src/b_filesystem/b_dir.cpp +++ b/utils/src/b_filesystem/b_dir.cpp @@ -306,30 +306,10 @@ bool BDir::CheckAndCreateDirectory(const string &filePath) return true; } -static void UpdateFileStat(std::shared_ptr appStatistic, std::string filePath, uint64_t fileSize, - uint32_t& maxDirDepth) -{ - appStatistic->UpdateFileDist(ExtractFileExt(filePath), fileSize); - uint32_t dirDepth = 0; - const char* pstr = filePath.c_str(); - char pre = '-'; - uint32_t pathLen = filePath.size(); - for (int i = 0; i < pathLen; i++) { - if (pstr[i] == '/' && pre != '/') { - dirDepth++; - } - pre = pstr[i]; - } - if (dirDepth > maxDirDepth) { - maxDirDepth = dirDepth; - } -} - tuple, map> BDir::GetBigFiles(const vector &includes, - const vector &excludes, std::shared_ptr appStatistic) + const vector &excludes) { set inc = ExpandPathWildcard(includes, true); - map incFiles; map incSmallFiles; for (const auto &item : inc) { @@ -341,40 +321,26 @@ tuple, map> BDir::GetBigFiles( incSmallFiles.merge(move(smallFiles)); } } - vector endExcludes = excludes; - PreDealExcludes(endExcludes); if (excludes.empty()) { return {ERR_OK, move(incFiles), move(incSmallFiles)}; } - auto isMatch = [](const vector &s, const string &str) -> bool { - if (str.empty()) { - return false; - } - for (const string &item : s) { - if (fnmatch(item.data(), str.data(), FNM_LEADING_DIR) == 0) { - return true; - } - } - return false; - }; + + vector endExcludes = excludes; + PreDealExcludes(endExcludes); map resSmallFiles; - uint32_t maxDirDepth = BConstants::APP_BASE_PATH_DEPTH; for (const auto &item : incSmallFiles) { - if (!isMatch(endExcludes, item.first)) { + if (!IsDirsMatch(endExcludes, item.first)) { resSmallFiles.emplace(item); - UpdateFileStat(appStatistic, item.first, item.second, maxDirDepth); } } map bigFiles; for (const auto &item : incFiles) { - if (!isMatch(endExcludes, item.first)) { + if (!IsDirsMatch(endExcludes, item.first)) { bigFiles.emplace(item); - UpdateFileStat(appStatistic, item.first, item.second.st_size, maxDirDepth); } } - appStatistic->dirDepth_ = maxDirDepth - BConstants::APP_BASE_PATH_DEPTH; HILOGW("total number of big files is %{public}zu", bigFiles.size()); HILOGW("total number of small files is %{public}zu", resSmallFiles.size()); return {ERR_OK, move(bigFiles), move(resSmallFiles)}; @@ -589,4 +555,17 @@ bool BDir::CheckAndRmSoftLink(const EndFileInfo &filePaths) } return isSoftLink; } + +bool BDir::IsDirsMatch(const vector &excludePaths, const string &path) +{ + if (path.empty()) { + return false; + } + for (const string &item : excludePaths) { + if (fnmatch(item.data(), path.data(), FNM_LEADING_DIR) == 0) { + return true; + } + } + return false; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_filesystem/b_file.cpp b/utils/src/b_filesystem/b_file.cpp index 1456a8e9a37a88ddabf06f2a9359bc308f0d9104..f89e7e4f6707a394d7a1f036883e42907ece605f 100644 --- a/utils/src/b_filesystem/b_file.cpp +++ b/utils/src/b_filesystem/b_file.cpp @@ -219,11 +219,12 @@ bool BFile::EndsWith(const string &str, const string &suffix) return (str.rfind(suffix) == (str.length() - suffix.length())); } -uint64_t BFile::GetFileSize(const string &path) +uint64_t BFile::GetFileSize(const string &path, int32_t &error) { struct stat sta = {}; + error = errno; if (stat(path.data(), &sta) == -1) { - HILOGE("get file size fail error:%{public}s", strerror(errno)); + HILOGE("get file size fail error:%{public}s", strerror(error)); return 0; } return sta.st_size; diff --git a/utils/src/b_radar/radar_app_statistic.cpp b/utils/src/b_radar/radar_app_statistic.cpp index 6a78e9fbb6ac2e14b71d613438eed2750ab58ded..4d73a0ce8fe91b11479f33602ef517f019012ee6 100644 --- a/utils/src/b_radar/radar_app_statistic.cpp +++ b/utils/src/b_radar/radar_app_statistic.cpp @@ -73,15 +73,15 @@ void FileSizeStat::UpdateStat(uint64_t fileSize) } } -void RadarAppStatistic::ReportBackup(const std::string &func, int32_t errorCode) +void RadarAppStatistic::ReportBackup(const std::string &func, int32_t errorCode, std::string errMsg) { HiSysEventWrite( DOMAIN, BACKUP_RESTORE_APP_STATISTIC, - OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, + OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR, ORG_PKG, DOMAIN_NAME, FUNC, func, - UNIQUE_ID, uniqId_, + CONCURRENT_ID, uniqId_, BIZ_SCENE, static_cast(BizScene::BACKUP), APP_CALLER, appCaller_, FILE_SIZE_DIST, fileSizeDist_.ToJsonString(), @@ -103,23 +103,27 @@ void RadarAppStatistic::ReportBackup(const std::string &func, int32_t errorCode) SCAN_FILE_SPEND, scanFileSpend_.GetSpan(), SEND_RATE_ZERO_SPAN, sendRateZeroSpendUS_ / MS_TO_US, DO_BACKUP_SPEND, doBackupSpend_.GetSpan(), - ERROR_CODE, errorCode); + ERROR_MSG, errMsg, + ERROR_CODE, errorCode, + BIZ_STAGE, DEFAULT_STAGE, + STAGE_RES, errorCode == 0 ? STAGE_RES_SUCCESS : STAGE_RES_FAIL); } void RadarAppStatistic::ReportBackup(const std::string &func, BError errCode) { - ReportBackup(func, RadarErrorCode(MODULE_BACKUP, errCode).GenCode()); + RadarError err(MODULE_BACKUP, errCode); + ReportBackup(func, err.GenCode(), err.errMsg_); } -void RadarAppStatistic::ReportRestore(const std::string &func, int32_t errorCode) +void RadarAppStatistic::ReportRestore(const std::string &func, int32_t errorCode, std::string errMsg) { HiSysEventWrite( DOMAIN, BACKUP_RESTORE_APP_STATISTIC, - OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, + OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR, ORG_PKG, DOMAIN_NAME, FUNC, func, - UNIQUE_ID, uniqId_, + CONCURRENT_ID, uniqId_, BIZ_SCENE, static_cast(BizScene::RESTORE), APP_CALLER, appCaller_, BIG_FILE_COUNT, bigFileCount_, @@ -133,12 +137,16 @@ void RadarAppStatistic::ReportRestore(const std::string &func, int32_t errorCode UNTAR_SPEND, untarSpend_, BIG_FILE_SPEND, bigFileSpend_, DO_RESTORE_SPEND, doRestoreSpend_, - ERROR_CODE, errorCode); + ERROR_MSG, errMsg, + ERROR_CODE, errorCode, + BIZ_STAGE, DEFAULT_STAGE, + STAGE_RES, errorCode == 0 ? STAGE_RES_SUCCESS : STAGE_RES_FAIL); } void RadarAppStatistic::ReportRestore(const std::string &func, BError errCode) { - ReportRestore(func, RadarErrorCode(MODULE_RESTORE, errCode).GenCode()); + RadarError err(MODULE_RESTORE, errCode); + ReportRestore(func, err.GenCode(), err.errMsg_); } void RadarAppStatistic::UpdateSendRateZeroSpend() @@ -153,4 +161,40 @@ void RadarAppStatistic::UpdateFileDist(std::string fileExtension, uint64_t fileS fileTypeDist_.UpdateStat(fileExtension, fileSize); } +void RadarAppStatistic::ReportError(const std::string &func, RadarError error) +{ + HiSysEventWrite( + DOMAIN, + BACKUP_RESTORE_APP_STATISTIC, + OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + ORG_PKG, DOMAIN_NAME, + FUNC, func, + CONCURRENT_ID, uniqId_, + BIZ_SCENE, static_cast(bizScene_), + APP_CALLER, appCaller_, + ERROR_MSG, error.errMsg_, + ERROR_CODE, error.GenCode(), + BIZ_STAGE, DEFAULT_STAGE, + STAGE_RES, error.error_ == 0 ? STAGE_RES_SUCCESS : STAGE_RES_FAIL); +} + +void RadarAppStatistic::ReportSA(const std::string &func, RadarError error) +{ + HiSysEventWrite( + DOMAIN, + BACKUP_RESTORE_APP_STATISTIC, + OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + ORG_PKG, DOMAIN_NAME, + FUNC, func, + CONCURRENT_ID, uniqId_, + BIZ_SCENE, static_cast(bizScene_), + APP_CALLER, appCaller_, + DO_BACKUP_SPEND, doBackupSpend_.GetSpan(), + DO_RESTORE_SPEND, doRestoreSpend_, + ERROR_MSG, error.errMsg_, + ERROR_CODE, error.GenCode(), + BIZ_STAGE, DEFAULT_STAGE, + STAGE_RES, error.error_ == 0 ? STAGE_RES_SUCCESS : STAGE_RES_FAIL); +} + } // namespace OHOS::FileManagement::Backup \ 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 73d40debe2ab1958d1162e405f93a5fed8080381..1fbd74c91a95bb38c5712320359c9aabf370b375 100644 --- a/utils/src/b_radar/radar_total_statistic.cpp +++ b/utils/src/b_radar/radar_total_statistic.cpp @@ -26,31 +26,41 @@ RadarTotalStatistic::RadarTotalStatistic(BizScene bizScene, std::string callerNa uniqId_ = TimeUtils::GetTimeUS(); } -void RadarTotalStatistic::Report(const std::string &func, int32_t error) +void RadarTotalStatistic::Report(const std::string &func, int32_t error, std::string errMsg) { + uint32_t succCount = succBundleCount_.load(); + uint32_t failCount = failBundleCount_.load(); HiSysEventWrite( DOMAIN, BACKUP_RESTORE_STATISTIC, - OHOS::HiviewDFX::HiSysEvent::EventType::STATISTIC, + OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR, ORG_PKG, DOMAIN_NAME, FUNC, func, - UNIQUE_ID, uniqId_, + CONCURRENT_ID, uniqId_, BIZ_SCENE, static_cast(bizScene_), HOST_PKG, hostPkg_, MODE, static_cast(mode_), - FAIL_BUNDLE_CNT, failBundleCount_, - SUCC_BUNDLE_CNT, succBundleCount_, + FAIL_BUNDLE_CNT, failCount - lastFailCnt_.load(), + SUCC_BUNDLE_CNT, succCount - lastSuccCnt_.load(), + GET_BUNDLE_INFO_SPEND, getBundleInfoSpend_.GetSpan(), TOTAL_SPEND, totalSpendTime_.GetSpan(), - ERROR_CODE, error); + ERROR_MSG, errMsg, + ERROR_CODE, error, + BIZ_STAGE, DEFAULT_STAGE, + STAGE_RES, error == 0 ? STAGE_RES_SUCCESS : STAGE_RES_FAIL); + lastSuccCnt_.store(succCount); + lastFailCnt_.store(failCount); } void RadarTotalStatistic::Report(const std::string &func, uint32_t moduleId, uint16_t moduleErr) { - Report(func, RadarErrorCode(moduleId, moduleErr).GenCode()); + RadarError err(moduleId, moduleErr); + Report(func, err.GenCode()); } void RadarTotalStatistic::Report(const std::string &func, BError errCode, uint32_t moduleId) { - Report(func, RadarErrorCode(moduleId, errCode).GenCode()); + RadarError err(moduleId, errCode); + Report(func, err.GenCode(), err.errMsg_); } } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_utils/b_time.cpp b/utils/src/b_utils/b_time.cpp index f4ea1d3ecf118bb590775d9f9c73074a544da096..fcdbbb1bb9a9699b4a7bc3b3f90bf922d918f80c 100644 --- a/utils/src/b_utils/b_time.cpp +++ b/utils/src/b_utils/b_time.cpp @@ -47,7 +47,11 @@ uint32_t TimeUtils::GetSpendSecond(int64_t startTime) if (startTime == 0) { return 0; } - return static_cast(GetTimeS() - startTime); + int64_t endTime = GetTimeS(); + if (endTime < startTime) { + return 0; + } + return static_cast(endTime - startTime); } uint32_t TimeUtils::GetSpendMS(int64_t startTime) @@ -55,7 +59,11 @@ uint32_t TimeUtils::GetSpendMS(int64_t startTime) if (startTime == 0) { return 0; } - return static_cast(GetTimeMS() - startTime); + int64_t endTime = GetTimeMS(); + if (endTime < startTime) { + return 0; + } + return static_cast(endTime - startTime); } uint32_t TimeUtils::GetSpendUS(int64_t startTime) @@ -63,7 +71,11 @@ uint32_t TimeUtils::GetSpendUS(int64_t startTime) if (startTime == 0) { return 0; } - return static_cast(GetTimeUS() - startTime); + int64_t endTime = GetTimeUS(); + if (endTime < startTime) { + return 0; + } + return static_cast(endTime - startTime); } std::string TimeUtils::GetCurrentTime()