diff --git a/frameworks/native/backup_ext/BUILD.gn b/frameworks/native/backup_ext/BUILD.gn index bc32d5e264a8d4286930a3cef8083fcd334881a1..6c5b10fd21bcd21549c14e8f553e10bae6ee2972 100644 --- a/frameworks/native/backup_ext/BUILD.gn +++ b/frameworks/native/backup_ext/BUILD.gn @@ -34,6 +34,7 @@ ohos_shared_library("backup_extension_ability_native") { "src/ext_backup_loader.cpp", "src/ext_extension.cpp", "src/ext_extension_stub.cpp", + "src/sub_ext_extension.cpp", "src/tar_file.cpp", "src/untar_file.cpp", ] @@ -64,8 +65,6 @@ ohos_shared_library("backup_extension_ability_native") { "ability_runtime:abilitykit_native", "ability_runtime:app_context", "ability_runtime:appkit_native", - "ability_runtime:extensionkit_native", - "ability_runtime:napi_common", "ability_runtime:runtime", "access_token:libaccesstoken_sdk", "bundle_framework:appexecfwk_core", diff --git a/frameworks/native/backup_ext/include/ext_backup.h b/frameworks/native/backup_ext/include/ext_backup.h index dae003248c1e2b6ff501356e91946bbe82a37834..570bdac446ea509a775d3de3b2b157d448d6cfb1 100644 --- a/frameworks/native/backup_ext/include/ext_backup.h +++ b/frameworks/native/backup_ext/include/ext_backup.h @@ -26,6 +26,7 @@ namespace OHOS::FileManagement::Backup { class ExtBackup; using CreatorFunc = std::function &runtime)>; +class BackupExtExtension; class ExtBackup : public AbilityRuntime::ExtensionBase { public: @@ -146,6 +147,11 @@ public: */ virtual ErrCode GetBackupInfo(std::function callback); + /** + * @brief Called do OnProcess + */ + virtual ErrCode OnProcess(std::function callback); + /** * @brief 数据迁移判断 * @@ -181,6 +187,8 @@ public: static void SetCreator(const CreatorFunc &creator); + void SetBackupExtExtension(const wptr &extExtension); + protected: std::string appVersionStr_; std::string restoreRetInfo_; @@ -195,6 +203,7 @@ private: BConstants::ExtensionAction extAction_ {BConstants::ExtensionAction::INVALID}; ErrCode GetParament(const AAFwk::Want &want); static CreatorFunc creator_; + wptr bakExtExtension_; }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/include/ext_backup_js.h b/frameworks/native/backup_ext/include/ext_backup_js.h index cd32e0ce4c901e778ddda467c4a5a8583a449ed3..d81bd62f80b08c8c1d4f78abbbeaedc0c8fe9d4f 100644 --- a/frameworks/native/backup_ext/include/ext_backup_js.h +++ b/frameworks/native/backup_ext/include/ext_backup_js.h @@ -73,6 +73,13 @@ struct CallbackInfoEx { } }; +struct OnProcessCallBackInfo { + std::function onProcessCallback; + OnProcessCallBackInfo(std::function param) : onProcessCallback(param) + { + } +}; + class ExtBackupJs : public ExtBackup { public: /** @@ -123,6 +130,13 @@ public: */ ErrCode InvokeAppExtMethod(ErrCode, const std::string) override; + /** + * @brief get app onProcess info + * + * @param callback The callBack. + */ + ErrCode OnProcess(std::function callback) override; + public: explicit ExtBackupJs(AbilityRuntime::JsRuntime &jsRuntime) : jsRuntime_(jsRuntime) {} ~ExtBackupJs() @@ -141,7 +155,6 @@ private: std::function &argv)> ParseRestoreInfo(); std::function &argv)> ParseBackupExInfo(); - std::function &argv)> ParseBackupInfo(); ErrCode CallJSRestoreEx(); ErrCode CallJSRestore(); @@ -155,6 +168,7 @@ private: std::shared_ptr callbackInfoBackup_; std::shared_ptr callbackInfoEx_; std::shared_ptr callbackInfo_; + std::shared_ptr onProcessCallback_; std::condition_variable callJsCon_; std::mutex callJsMutex_; std::atomic callExtDefaultFunc_ {false}; // extension default method, onBackup or onRestore diff --git a/frameworks/native/backup_ext/include/ext_extension.h b/frameworks/native/backup_ext/include/ext_extension.h index b93bdbb3e3c7a906f7df550b377b5d8b5ad0d8d3..41b9b1ff82d05161b13539aef25b640ba75245ae 100644 --- a/frameworks/native/backup_ext/include/ext_extension.h +++ b/frameworks/native/backup_ext/include/ext_extension.h @@ -4,7 +4,7 @@ * 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 + * 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, @@ -27,28 +27,29 @@ #include "b_json/b_json_entity_extension_config.h" #include "b_json/b_json_entity_ext_manage.h" #include "b_json/b_report_entity.h" +#include "b_radar/b_radar.h" #include "ext_backup_js.h" #include "ext_extension_stub.h" #include "i_service.h" #include "tar_file.h" #include "thread_pool.h" +#include "timer.h" #include "unique_fd.h" namespace OHOS::FileManagement::Backup { -using CompareFilesResult = tuple, - map, - map>; +using CompareFilesResult = + tuple, map, map>; class BackupExtExtension : public ExtExtensionStub { public: UniqueFd GetFileHandle(const std::string &fileName, int32_t &errCode) override; ErrCode HandleClear() override; ErrCode PublishFile(const std::string &fileName) override; - ErrCode HandleBackup() override; - ErrCode HandleRestore() override; + ErrCode HandleBackup(bool isClearData) override; + ErrCode HandleRestore(bool isClearData) override; ErrCode GetIncrementalFileHandle(const std::string &fileName) override; ErrCode PublishIncrementalFile(const std::string &fileName) override; ErrCode HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) override; - ErrCode IncrementalOnBackup() override; + ErrCode IncrementalOnBackup(bool isClearData) override; std::tuple GetIncrementalBackupFileHandle() override; ErrCode GetBackupInfo(std::string &result) override; ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) override; @@ -56,63 +57,83 @@ public: void AsyncTaskRestoreForUpgrade(void); void ExtClear(void); void AsyncTaskIncrementalRestoreForUpgrade(void); + ErrCode User0OnBackup() override; public: - explicit BackupExtExtension(const std::shared_ptr &extension) : extension_(extension) + explicit BackupExtExtension(const std::shared_ptr &extension, + const std::string &bundleName) : extension_(extension) { + if (extension_ != nullptr) { + extension_->SetBackupExtExtension(this); + } + bundleName_ = bundleName; threadPool_.Start(BConstants::EXTENSION_THREAD_POOL_COUNT); + onProcessTaskPool_.Start(BConstants::EXTENSION_THREAD_POOL_COUNT); + SetStagingPathProperties(); } ~BackupExtExtension() { + onProcessTimeoutTimer_.Shutdown(); threadPool_.Stop(); + onProcessTaskPool_.Stop(); + if (callJsOnProcessThread_.joinable()) { + callJsOnProcessThread_.join(); + } } private: - /** + /* * * @brief verify caller uid * */ void VerifyCaller(); - /** + /* * * @brief backup * * @param usrConfig user configure */ int DoBackup(const BJsonEntityExtensionConfig &usrConfig); - /** + /* * * @brief restore * * @param fileName name of the file that to be untar */ int DoRestore(const string &fileName); - /** + /* * * @brief incremental restore * */ int DoIncrementalRestore(); - /** @brief clear backup restore data */ + /* * @brief clear backup restore data */ void DoClear(); - /** + /* * * @brief extension backup restore is done * * @param errCode */ void AppDone(ErrCode errCode); - /** + /* * * @brief extension backup restore is done * * @param restoreRetInfo app restore reportInfo */ - void AppResultReport(const std::string restoreRetInfo, BackupRestoreScenario scenario, - ErrCode errCode = 0); + void AppResultReport(const std::string restoreRetInfo, BackupRestoreScenario scenario, ErrCode errCode = 0); /** + * @brief extension process Info + * + * @param restoreRetInfo app processInfo + * @param scenario backup or restore + */ + void ReportAppProcessInfo(const std::string processInfo, BackupRestoreScenario scenario); + + /* * * @brief Executing Backup Tasks Asynchronously * * @param extAction action @@ -121,19 +142,19 @@ private: */ void AsyncTaskBackup(const std::string config); - /** + /* * * @brief Executing Restoration Tasks Asynchronously * */ void AsyncTaskRestore(std::set fileSet, const std::vector extManageInfo); - /** + /* * * @brief Executing Incremental Restoration Tasks Asynchronously * */ void AsyncTaskIncrementalRestore(); - /** + /* * * @brief Executing Incremental Restoration Tasks Asynchronously for special clone & cloud * */ @@ -141,26 +162,32 @@ private: void AsyncTaskOnBackup(); + bool IfAllowToBackupRestore(); + + void AsyncTaskUser0Backup(); + + void DoUser0Backup(const BJsonEntityExtensionConfig &usrConfig); + + int User0DoBackup(const BJsonEntityExtensionConfig &usrConfig); + int DoIncrementalBackup(const std::vector &allFiles, - const std::vector &smallFiles, - const std::vector &bigFiles); + const std::vector &smallFiles, const std::vector &bigFiles); - void CompareFiles(UniqueFd incrementalFd, - UniqueFd manifestFd, - vector &allFiles, - vector &smallFiles, - vector &bigFiles); + void CompareFiles(UniqueFd incrementalFd, UniqueFd manifestFd, vector &allFiles, + vector &smallFiles, vector &bigFiles); void AsyncTaskDoIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd); void AsyncTaskOnIncrementalBackup(); + int DoIncrementalBackupTask(UniqueFd incrementalFd, UniqueFd manifestFd); ErrCode IncrementalBigFileReady(const TarMap &pkgInfo, const vector &bigInfos, sptr proxy); - ErrCode BigFileReady(sptr proxy); + ErrCode BigFileReady(const TarMap &bigFileInfo, sptr proxy); void WaitToSendFd(std::chrono::system_clock::time_point &startTime, int &fdSendNum); void RefreshTimeInfo(std::chrono::system_clock::time_point &startTime, int &fdSendNum); void IncrementalPacket(const vector &infos, TarMap &tar, sptr proxy); + void DoPacket(const map &srcFiles, TarMap &tar, sptr proxy); - /** + /* * * @brief extension incremental backup restore is done * * @param errCode @@ -168,45 +195,103 @@ private: void AppIncrementalDone(ErrCode errCode); /** - * @brief get callbackEx for execute onRestore + * @brief start extension timer by ipc * - * @param errCode + * @param result */ - std::function RestoreResultCallbackEx(wptr obj); + void StartExtTimer(bool &isExtStart); /** - * @brief get callbackEx for execute onRestore with string param + * @brief start fwk timer by ipc * * @param errCode */ - std::function IncRestoreResultCallbackEx(wptr obj); + void StartFwkTimer(bool &isFwkStart); /** - * @brief get callbackEx for execute onRestore + * @brief get increCallbackEx for execute onRestore with string param * - * @param errCode + * @param obj */ - std::function IncAppDoneCallbackEx(wptr obj); + std::function IncreOnRestoreExCallback(wptr obj); - /** + /* * + * @brief get increCallback for execute onRestore with string param + * + * @param obj + */ + std::function IncreOnRestoreCallback(wptr obj); + + /* * + * @brief get callback for execute onRestore with string param + * + * @param obj + */ + std::function OnRestoreCallback(wptr obj); + + /* * + * @brief get callbackEx for execute onRestore with string param + * + * @param obj + */ + std::function OnRestoreExCallback(wptr obj); + + /* * * @brief get callbackEx for execute appDone */ std::function AppDoneCallbackEx(wptr obj); - std::function HandleBackupEx(wptr obj); - std::function HandleTaskBackupEx(wptr obj); + + std::function IncOnBackupExCallback(wptr obj); + std::function IncOnBackupCallback(wptr obj); + + std::function OnBackupExCallback(wptr obj); + std::function OnBackupCallback(wptr obj); + + ErrCode RestoreFilesForSpecialCloneCloud(); + void RestoreBigFiles(bool appendTargetPath); + + void StartOnProcessTaskThread(wptr obj, BackupRestoreScenario scenario); + void FinishOnProcessTask(); + void ExecCallOnProcessTask(wptr obj, BackupRestoreScenario scenario); + void AsyncCallJsOnProcessTask(wptr obj, BackupRestoreScenario scenario); + void SyncCallJsOnProcessTask(wptr obj, BackupRestoreScenario scenario); + void StartOnProcessTimeOutTimer(wptr obj, BackupRestoreScenario scenario); + void CloseOnProcessTimeOutTimer(); + + void HandleSpecialVersionRestore(wptr obj); + void DeleteBackupIncrementalTars(); + void DeleteBackupTars(); + void SetClearDataFlag(bool isClearData); + void UpdateOnStartTime(); + int32_t GetOnStartTimeCost(); + bool SetStagingPathProperties(); + private: std::shared_mutex lock_; std::shared_ptr extension_; std::string backupInfo_; OHOS::ThreadPool threadPool_; std::mutex updateSendRateLock_; - std::atomic isStopSendFd_ {false}; std::condition_variable startSendFdRateCon_; std::condition_variable waitSendFdCon_; std::mutex startSendMutex_; std::mutex waitTimeLock_; std::string bundleName_; int32_t sendRate_ = BConstants::DEFAULT_FD_SEND_RATE; + + std::thread callJsOnProcessThread_; + Utils::Timer onProcessTimeoutTimer_ {"onProcessTimeoutTimer_"}; + uint32_t onProcessTimeoutTimerId_ { 0 }; + std::atomic onProcessTimeoutCnt_; + std::atomic stopCallJsOnProcess_ {false}; + std::condition_variable execOnProcessCon_; + std::mutex onProcessLock_; + std::atomic onProcessTimeout_ {false}; + std::chrono::time_point g_onStart; + std::mutex onStartTimeLock_; + bool isClearData_ {true}; + AppRadar::DoRestoreInfo radarRestoreInfo_ { 0 }; + OHOS::ThreadPool onProcessTaskPool_; }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/include/ext_extension_stub.h b/frameworks/native/backup_ext/include/ext_extension_stub.h index 86949011af210e039bee4e19cefc7db7f562b69f..d969b3e9b80d5b8d491ced905c02ab2c7a6a9876 100644 --- a/frameworks/native/backup_ext/include/ext_extension_stub.h +++ b/frameworks/native/backup_ext/include/ext_extension_stub.h @@ -43,6 +43,7 @@ private: ErrCode CmdGetIncrementalBackupFileHandle(MessageParcel &data, MessageParcel &reply); ErrCode CmdGetBackupInfo(MessageParcel &data, MessageParcel &reply); ErrCode CmdUpdateFdSendRate(MessageParcel &data, MessageParcel &reply); + ErrCode CmdHandleUser0Backup(MessageParcel &data, MessageParcel &reply); private: using ExtensionInterface = int32_t (ExtExtensionStub::*)(MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/native/backup_ext/src/ext_backup.cpp b/frameworks/native/backup_ext/src/ext_backup.cpp index 2805185963c0be7423dfb13b6363020190c4c0c1..2bef6b2d358630a253c3e71b06d3fca1c9074649 100644 --- a/frameworks/native/backup_ext/src/ext_backup.cpp +++ b/frameworks/native/backup_ext/src/ext_backup.cpp @@ -45,6 +45,11 @@ void ExtBackup::SetCreator(const CreatorFunc &creator) creator_ = creator; } +void ExtBackup::SetBackupExtExtension(const wptr &extExtension) +{ + bakExtExtension_ = extExtension; +} + void ExtBackup::Init(const shared_ptr &record, const shared_ptr &application, shared_ptr &handler, @@ -188,13 +193,8 @@ sptr ExtBackup::OnConnect(const AAFwk::Want &want) Extension::OnConnect(want); auto remoteObject = - sptr(new BackupExtExtension(std::static_pointer_cast(shared_from_this()))); - - // 排除特殊场景 - if (!WasFromSpecialVersion() && !RestoreDataReady()) { - remoteObject->ExtClear(); - } - + sptr(new BackupExtExtension(std::static_pointer_cast(shared_from_this()), + want.GetBundle())); return remoteObject->AsObject(); } catch (const BError &e) { return nullptr; @@ -211,6 +211,10 @@ void ExtBackup::OnDisconnect(const AAFwk::Want &want) { try { HILOGI("begin disconnect"); + sptr extExtension = bakExtExtension_.promote(); + if (extExtension != nullptr) { + extExtension->ExtClear(); + } Extension::OnDisconnect(want); extAction_ = BConstants::ExtensionAction::INVALID; HILOGI("end"); @@ -291,4 +295,10 @@ ErrCode ExtBackup::InvokeAppExtMethod(ErrCode errCode, const std::string result) return ERR_OK; } +ErrCode ExtBackup::OnProcess(std::function callback) +{ + HILOGI("BackupExtensionAbility(base) OnProcess."); + return ERR_OK; +} + } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/ext_backup_context.cpp b/frameworks/native/backup_ext/src/ext_backup_context.cpp index 87a8a03ddb2ab4ae805533871ac0b2c7b52703c6..3df12d334c76ba820e9388b8ba3533540f5a8fc2 100644 --- a/frameworks/native/backup_ext/src/ext_backup_context.cpp +++ b/frameworks/native/backup_ext/src/ext_backup_context.cpp @@ -15,6 +15,7 @@ #include "ext_backup_context.h" +#include "b_filesystem/b_file.h" #include "b_resources/b_constants.h" namespace OHOS::FileManagement::Backup { @@ -24,7 +25,16 @@ const std::string ExtBackupContext::GetBackupDir() if (area > 1) { // 1 : el2 area return ""; } - return std::string(BConstants::BACKUP_DIR_PRE) + std::string(BConstants::CONTEXT_ELS[area]) + + + std::string path = std::string(BConstants::BACKUP_DIR_PRE) + std::string(BConstants::CONTEXT_ELS[area]) + std::string(BConstants::BACKUP_DIR_END); + std::string bundleName = GetBundleName(); + if (BFile::EndsWith(bundleName, BConstants::BUNDLE_FILE_MANAGER) && bundleName.size() == BConstants::FM_LEN) { + path = std::string(BConstants::PATH_FILEMANAGE_BACKUP_HOME) + BConstants::FILE_SEPARATOR_CHAR; + } else if (bundleName == BConstants::BUNDLE_MEDIAL_DATA) { + path = std::string(BConstants::PATH_MEDIALDATA_BACKUP_HOME) + BConstants::FILE_SEPARATOR_CHAR; + } + + return path; } } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_ext/src/ext_backup_js.cpp b/frameworks/native/backup_ext/src/ext_backup_js.cpp index bb3de776cd0ab285aa9396914da0812a13d0afc3..c0fecddaa0b0f3d0045eb884fa996a871548e455 100644 --- a/frameworks/native/backup_ext/src/ext_backup_js.cpp +++ b/frameworks/native/backup_ext/src/ext_backup_js.cpp @@ -84,12 +84,10 @@ static napi_status DealNapiStrValue(napi_env env, const napi_value napi_StrValue return status; } -static napi_status DealNapiException(napi_env env, std::string &exceptionInfo) +static napi_status DealNapiException(napi_env env, napi_value &exception, std::string &exceptionInfo) { HILOGI("call DealNapiException start."); - napi_status status; - napi_value exception; - status = napi_get_and_clear_last_exception(env, &exception); + napi_status status = napi_get_and_clear_last_exception(env, &exception); if (status != napi_ok) { HILOGE("call napi_get_and_clear_last_exception failed."); return status; @@ -124,7 +122,7 @@ static napi_value PromiseCallback(napi_env env, napi_callback_info info) static napi_value PromiseCatchCallback(napi_env env, napi_callback_info info) { - HILOGI("Promise catch callback."); + HILOGI("Promise catch callback begin."); size_t argc = 1; napi_value argv = {nullptr}; void *data = nullptr; @@ -137,8 +135,14 @@ static napi_value PromiseCatchCallback(napi_env env, napi_callback_info info) HILOGE("CallbackInfo is nullptr"); return nullptr; } + napi_status throwStatus = napi_fatal_exception(env, argv); + if (throwStatus != napi_ok) { + HILOGE("Failed to throw an exception, %{public}d", throwStatus); + return nullptr; + } callbackInfo->callback(BError(BError::Codes::EXT_THROW_EXCEPTION), exceptionInfo); data = nullptr; + HILOGI("Promise catch callback end."); return nullptr; } @@ -163,7 +167,7 @@ static napi_value PromiseCallbackEx(napi_env env, napi_callback_info info) static napi_value PromiseCatchCallbackEx(napi_env env, napi_callback_info info) { - HILOGI("PromiseEx catch callback."); + HILOGI("PromiseEx catch callback begin."); void *data = nullptr; size_t argc = 1; napi_value argv = {nullptr}; @@ -176,8 +180,14 @@ static napi_value PromiseCatchCallbackEx(napi_env env, napi_callback_info info) HILOGE("CallbackInfo is nullPtr"); return nullptr; } + napi_status throwStatus = napi_fatal_exception(env, argv); + if (throwStatus != napi_ok) { + HILOGE("Failed to throw an exception, %{public}d", throwStatus); + return nullptr; + } callbackInfoEx->callbackParam(BError(BError::Codes::EXT_THROW_EXCEPTION), exceptionInfo); data = nullptr; + HILOGI("PromiseEx catch callback end."); return nullptr; } @@ -499,7 +509,9 @@ ErrCode ExtBackupJs::CallJsOnBackupEx() napi_is_exception_pending(envir, &isExceptionPending); HILOGI("napi exception pending = %{public}d.", isExceptionPending); if (isExceptionPending) { - DealNapiException(envir, str); + napi_value exception; + DealNapiException(envir, exception, str); + napi_fatal_exception(envir, exception); callbackInfoEx->callbackParam(BError(BError::Codes::EXT_THROW_EXCEPTION), str); } else { DealNapiStrValue(envir, result, str); @@ -537,7 +549,9 @@ ErrCode ExtBackupJs::CallJsOnBackup() napi_is_exception_pending(env, &isExceptionPending); HILOGI("napi exception pending = %{public}d.", isExceptionPending); if (isExceptionPending) { - DealNapiException(env, str); + napi_value exception; + DealNapiException(env, exception, str); + napi_fatal_exception(env, exception); callbackInfo->callback(BError(BError::Codes::EXT_THROW_EXCEPTION), str); } else { callbackInfo->callback(BError(BError::Codes::OK), str); @@ -580,7 +594,9 @@ ErrCode ExtBackupJs::CallJSRestoreEx() napi_is_exception_pending(envir, &isExceptionPending); HILOGI("napi exception pending = %{public}d.", isExceptionPending); if (isExceptionPending) { - DealNapiException(envir, str); + napi_value exception; + DealNapiException(envir, exception, str); + napi_fatal_exception(envir, exception); callbackInfoEx->callbackParam(BError(BError::Codes::EXT_THROW_EXCEPTION), str); } else { DealNapiStrValue(envir, result, str); @@ -617,7 +633,9 @@ ErrCode ExtBackupJs::CallJSRestore() napi_is_exception_pending(env, &isExceptionPending); HILOGI("napi exception pending = %{public}d.", isExceptionPending); if (isExceptionPending) { - DealNapiException(env, str); + napi_value exception; + DealNapiException(env, exception, str); + napi_fatal_exception(env, exception); callbackInfo->callback(BError(BError::Codes::EXT_THROW_EXCEPTION), str); } else { callbackInfo->callback(BError(BError::Codes::OK), str); @@ -644,6 +662,16 @@ ErrCode ExtBackupJs::GetBackupInfo(std::function bool { if (!CheckPromise(env, result)) { + bool isExceptionPending; + napi_is_exception_pending(env, &isExceptionPending); + HILOGI("napi exception pending = %{public}d.", isExceptionPending); + if (isExceptionPending) { + string str; + napi_value exception; + DealNapiException(env, exception, str); + callBackInfo->callbackParam(BError(BError::Codes::EXT_THROW_EXCEPTION), str); + return false; + } size_t strLen = 0; napi_status status = napi_get_value_string_utf8(env, result, nullptr, -1, &strLen); if (status != napi_ok) { @@ -706,7 +734,7 @@ static int DoCallJsMethod(CallJsParam *param) return EINVAL; } napi_value result; - HILOGI("Extension start do call current js method"); + HILOGI("Extension start do call current js method, methodName:%{public}s", param->funcName.c_str()); napi_call_function(env, value, method, argv.size(), argv.data(), &result); if (!param->retParser(env, handleEscape.Escape(result))) { HILOGE("Parser js result fail."); @@ -753,8 +781,9 @@ int ExtBackupJs::CallJsMethod(const std::string &funcName, } } while (false); HILOGI("will notify current thread info"); + std::unique_lock lock(param->backupOperateMutex); param->isReady.store(true); - param->backupOperateCondition.notify_one(); + param->backupOperateCondition.notify_all(); }); if (ret != 0) { HILOGE("failed to exec uv_queue_work."); @@ -838,4 +867,34 @@ ErrCode ExtBackupJs::InvokeAppExtMethod(ErrCode errCode, const std::string resul HILOGI("End Get App onBackupEx/onRestoreEx method result"); return ERR_OK; } + +ErrCode ExtBackupJs::OnProcess(std::function callback) +{ + HILOGI("BackupExtensionAbility(JS) OnProcess begin."); + BExcepUltils::BAssert(jsObj_, BError::Codes::EXT_BROKEN_FRAMEWORK, + "The app does not provide the OnProcess interface."); + onProcessCallback_ = std::make_shared(callback); + auto retParser = [jsRuntime {&jsRuntime_}, callBackInfo {onProcessCallback_}](napi_env env, + napi_value result) -> bool { + string processStr; + bool isExceptionPending; + napi_is_exception_pending(env, &isExceptionPending); + HILOGI("napi exception pending = %{public}d.", isExceptionPending); + if (isExceptionPending) { + napi_value exception; + napi_get_and_clear_last_exception(env, &exception); + callBackInfo->onProcessCallback(BError(BError::Codes::EXT_THROW_EXCEPTION), processStr); + } else { + DealNapiStrValue(env, result, processStr); + callBackInfo->onProcessCallback(BError(BError::Codes::OK), processStr); + } + return true; + }; + auto errCode = CallJsMethod("onProcess", jsRuntime_, jsObj_.get(), {}, retParser); + if (errCode != ERR_OK) { + HILOGE("CallJsMethod error, code:%{public}d.", errCode); + } + HILOGI("BackupExtensionAbulity(JS) OnProcess end."); + return errCode; +} } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/ext_extension.cpp b/frameworks/native/backup_ext/src/ext_extension.cpp index 071569fdddcb02111e4cac70bc71abf7ae9cfebd..e96eb551ef8c31ae88785f11edbef050c5be1ace 100644 --- a/frameworks/native/backup_ext/src/ext_extension.cpp +++ b/frameworks/native/backup_ext/src/ext_extension.cpp @@ -46,6 +46,7 @@ #include "b_filesystem/b_file_hash.h" #include "b_json/b_json_cached_entity.h" #include "b_jsonutil/b_jsonutil.h" +#include "b_ohos/startup/backup_para.h" #include "b_tarball/b_tarball_factory.h" #include "filemgmt_libhilog.h" #include "hitrace_meter.h" @@ -57,7 +58,6 @@ #include "b_anony/b_anony.h" namespace OHOS::FileManagement::Backup { -const string DEFAULT_TAR_PKG = "1.tar"; const string INDEX_FILE_BACKUP = string(BConstants::PATH_BUNDLE_BACKUP_HOME). append(BConstants::SA_BUNDLE_BACKUP_BACKUP). append(BConstants::EXT_BACKUP_MANAGE); @@ -66,20 +66,62 @@ const string INDEX_FILE_RESTORE = string(BConstants::PATH_BUNDLE_BACKUP_HOME). append(BConstants::EXT_BACKUP_MANAGE); const string INDEX_FILE_INCREMENTAL_BACKUP = string(BConstants::PATH_BUNDLE_BACKUP_HOME). append(BConstants::SA_BUNDLE_BACKUP_BACKUP); +const string MEDIA_LIBRARY_BUNDLE_NAME = "com.ohos.medialibrary.medialibrarydata"; +const string FILE_MANAGER_BUNDLE_NAME = "com.ohos.filepicker"; using namespace std; -namespace { -const int64_t DEFAULT_SLICE_SIZE = 100 * 1024 * 1024; // 分片文件大小为100M -const uint32_t MAX_FILE_COUNT = 6000; // 单个tar包最多包含6000个文件 -const uint32_t MAX_FD_GROUP_USE_TIME = 1000; // 每组打开最大时间1000ms -const int FILE_AND_MANIFEST_FD_COUNT = 2; // 每组文件和简报数量统计 +static void RecordDoRestoreRes(const std::string &bundleName, const std::string &func, + AppRadar::DoRestoreInfo &restoreInfo) +{ + std::stringstream ss; + ss << "\"bigFileNums\": " << restoreInfo.bigFileNum << ", "; + ss << "\"bigFileSize\": " << restoreInfo.bigFileSize << ", "; + ss << "\"RestoreBigFileTime\": " << restoreInfo.bigFileSpendTime << ", "; + ss << "\"unTarFileNums\": " << restoreInfo.tarFileNum << ", "; + ss << "\"unTarFileSize\": " << restoreInfo.tarFileSize << ", "; + ss << "\"unTarTime\": " << restoreInfo.tarFileSpendTime << ", "; + ss << "\"totalFileNum\": " << restoreInfo.bigFileNum + restoreInfo.tarFileNum << ", "; + ss << "\"totalFileSize\": " << restoreInfo.bigFileSize + restoreInfo.tarFileSize << ", "; + ss << "\"restoreAllFileTime\": " << restoreInfo.totalFileSpendTime; + int32_t err = static_cast(BError::Codes::OK); + AppRadar::Info info (bundleName, "", ss.str()); + AppRadar::GetInstance().RecordRestoreFuncRes(info, func, AppRadar::GetInstance().GetUserId(), + BizStageRestore::BIZ_STAGE_DO_RESTORE, err); +} + +static string GetIndexFileRestorePath(const string &bundleName) +{ + if (BFile::EndsWith(bundleName, BConstants::BUNDLE_FILE_MANAGER) && bundleName.size() == BConstants::FM_LEN) { + return string(BConstants::PATH_FILEMANAGE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE). + append(BConstants::EXT_BACKUP_MANAGE); + } else if (bundleName == BConstants::BUNDLE_MEDIAL_DATA) { + return string(BConstants::PATH_MEDIALDATA_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE). + append(BConstants::EXT_BACKUP_MANAGE); + } + return INDEX_FILE_RESTORE; +} + +static string GetRestoreTempPath(const string &bundleName) +{ + string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + if (BFile::EndsWith(bundleName, BConstants::BUNDLE_FILE_MANAGER) && bundleName.size() == BConstants::FM_LEN) { + if (mkdir(string(BConstants::PATH_FILEMANAGE_BACKUP_HOME).data(), S_IRWXU) && errno != EEXIST) { + string str = string("Failed to create .backup folder. ").append(std::generic_category().message(errno)); + throw BError(BError::Codes::EXT_INVAL_ARG, str); + } + path = string(BConstants::PATH_FILEMANAGE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + } else if (bundleName == BConstants::BUNDLE_MEDIAL_DATA) { + path = string(BConstants::PATH_MEDIALDATA_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + } + return path; } -static std::set GetIdxFileData() +static std::set GetIdxFileData(const string &bundleName) { - UniqueFd idxFd(open(INDEX_FILE_RESTORE.data(), O_RDONLY)); + string indexFileRestorePath = GetIndexFileRestorePath(bundleName); + UniqueFd idxFd(open(indexFileRestorePath.data(), O_RDONLY)); if (idxFd < 0) { - HILOGE("Failed to open idxFile = %{private}s, err = %{public}d", INDEX_FILE_RESTORE.c_str(), errno); + HILOGE("Failed to open idxFile = %{private}s, err = %{public}d", indexFileRestorePath.c_str(), errno); return std::set(); } BJsonCachedEntity cachedEntity(std::move(idxFd)); @@ -87,9 +129,10 @@ static std::set GetIdxFileData() return cache.GetExtManage(); } -static std::vector GetExtManageInfo() +static std::vector GetExtManageInfo(const string &bundleName) { - string filePath = BExcepUltils::Canonicalize(INDEX_FILE_RESTORE); + string indexFileRestorePath = GetIndexFileRestorePath(bundleName); + string filePath = BExcepUltils::Canonicalize(indexFileRestorePath); UniqueFd idxFd(open(filePath.data(), O_RDONLY)); if (idxFd < 0) { HILOGE("Failed to open cano_idxFile = %{private}s, err = %{public}d", filePath.c_str(), errno); @@ -105,12 +148,20 @@ void BackupExtExtension::VerifyCaller() uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID(); int tokenType = Security::AccessToken::AccessTokenKit::GetTokenType(tokenCaller); if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE) { + AppRadar::Info info(bundleName_, "", "{\"reason\":\"Calling tokenType error\"}"); + AppRadar::GetInstance().RecordDefaultFuncRes( + info, "BackupExtExtension::VerifyCaller", AppRadar::GetInstance().GetUserId(), + BizStageBackup::BIZ_STAGE_PERMISSION_CHECK_FAIL, BError(BError::Codes::EXT_BROKEN_IPC).GetCode()); throw BError(BError::Codes::EXT_BROKEN_IPC, - string("Calling tokenType is error, token type is ").append(to_string(tokenType))); + string("Calling tokenType is error, token type is ").append(to_string(tokenType))); } if (IPCSkeleton::GetCallingUid() != BConstants::BACKUP_UID) { + AppRadar::Info info(bundleName_, "", "{\"reason\":\"Calling uid invalid\"}"); + AppRadar::GetInstance().RecordDefaultFuncRes( + info, "BackupExtExtension::VerifyCaller", AppRadar::GetInstance().GetUserId(), + BizStageBackup::BIZ_STAGE_PERMISSION_CHECK_FAIL, BError(BError::Codes::EXT_BROKEN_IPC).GetCode()); throw BError(BError::Codes::EXT_BROKEN_IPC, - string("Calling uid is invalid, calling uid is ").append(to_string(IPCSkeleton::GetCallingUid()))); + string("Calling uid is invalid, calling uid is ").append(to_string(IPCSkeleton::GetCallingUid()))); } } @@ -141,14 +192,14 @@ static UniqueFd GetFileHandleForSpecialCloneCloud(const string &fileName) size_t filePathPrefix = filePath.find_last_of(BConstants::FILE_SEPARATOR_CHAR); if (filePathPrefix == string::npos) { HILOGE("GetFileHandleForSpecialCloneCloud: Invalid fileName"); - throw BError(BError::Codes::EXT_INVAL_ARG, fileName); + return UniqueFd(-1); } string path = filePath.substr(0, filePathPrefix); if (access(path.c_str(), F_OK) != 0) { bool created = ForceCreateDirectory(path.data()); if (!created) { - string str = string("Failed to create restore folder."); - throw BError(BError::Codes::EXT_INVAL_ARG, str); + HILOGE("Failed to create restore folder."); + return UniqueFd(-1); } } UniqueFd fd(open(fileName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); @@ -182,7 +233,7 @@ UniqueFd BackupExtExtension::GetFileHandle(const string &fileName, int32_t &errC return fd; } - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + string path = GetRestoreTempPath(bundleName_); if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { string str = string("Failed to create restore folder. ").append(std::generic_category().message(errno)); throw BError(BError::Codes::EXT_INVAL_ARG, str); @@ -214,43 +265,55 @@ static string GetReportFileName(const string &fileName) static ErrCode GetIncreFileHandleForSpecialVersion(const string &fileName) { + ErrCode errCode = ERR_OK; UniqueFd fd = GetFileHandleForSpecialCloneCloud(fileName); if (fd < 0) { HILOGE("Failed to open file = %{private}s, err = %{public}d", fileName.c_str(), errno); - throw BError(BError::Codes::EXT_INVAL_ARG, string("open tar file failed")); + errCode = errno; } string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { - string str = string("Failed to create restore folder. ").append(std::generic_category().message(errno)); - throw BError(BError::Codes::EXT_INVAL_ARG, str); + HILOGE("Failed to create restore folder : %{private}s, err = %{public}d", path.c_str(), errno); + errCode = errno; } string reportName = path + BConstants::BLANK_REPORT_NAME; UniqueFd reportFd(open(reportName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); if (reportFd < 0) { HILOGE("Failed to open report file = %{private}s, err = %{public}d", reportName.c_str(), errno); - throw BError(BError::Codes::EXT_INVAL_ARG, string("open report file failed")); + errCode = errno; } auto proxy = ServiceProxy::GetInstance(); if (proxy == nullptr) { - throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); + HILOGE("Failed to get file handle for special version clone"); + return BError(BError::Codes::EXT_BROKEN_BACKUP_SA).GetCode(); } - auto ret = proxy->AppIncrementalFileReady(fileName, move(fd), move(reportFd), ERR_OK); + auto ret = proxy->AppIncrementalFileReady(fileName, move(fd), move(reportFd), errCode); if (ret != ERR_OK) { HILOGE("Failed to AppIncrementalFileReady %{public}d", ret); } return ERR_OK; } -static string GetIncrementalFileHandlePath() +static string GetIncrementalFileHandlePath(const string &fileName, const string &bundleName) { string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + if (BFile::EndsWith(bundleName, BConstants::BUNDLE_FILE_MANAGER) && bundleName.size() == BConstants::FM_LEN) { + if (mkdir(string(BConstants::PATH_FILEMANAGE_BACKUP_HOME).data(), S_IRWXU) && errno != EEXIST) { + string str = string("Failed to create .backup folder. ").append(std::generic_category().message(errno)); + throw BError(BError::Codes::EXT_INVAL_ARG, str); + } + path = string(BConstants::PATH_FILEMANAGE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + } else if (bundleName == BConstants::BUNDLE_MEDIAL_DATA) { + path = string(BConstants::PATH_MEDIALDATA_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + } if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { string str = string("Failed to create restore folder. ").append(std::generic_category().message(errno)); throw BError(BError::Codes::EXT_INVAL_ARG, str); } - return path; + string tarName = path + fileName; + return tarName; } ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) @@ -262,19 +325,18 @@ ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) extension_->GetExtensionAction()); throw BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid"); } - HILOGI("extension: Start GetIncrementalFileHandle"); VerifyCaller(); if (extension_->SpecialVersionForCloneAndCloud()) { return GetIncreFileHandleForSpecialVersion(fileName); } - HILOGI("extension: single to single fileName:%{public}s", fileName.c_str()); - string path = GetIncrementalFileHandlePath(); - string tarName = path + fileName; + HILOGI("extension: GetIncrementalFileHandle single to single Name:%{public}s", GetAnonyPath(fileName).c_str()); + string tarName = GetIncrementalFileHandlePath(fileName, bundleName_); + int32_t errCode = ERR_OK; if (access(tarName.c_str(), F_OK) == 0) { - throw BError(BError::Codes::EXT_INVAL_ARG, string("The file already exists")); + HILOGE("The file already exists, tarname = %{private}s, err =%{public}d", tarName.c_str(), errno); + errCode = errno; } - int32_t errCode = ERR_OK; UniqueFd fd(open(tarName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); if (fd < 0) { HILOGE("Failed to open tar file = %{private}s, err = %{public}d", tarName.c_str(), errno); @@ -283,7 +345,8 @@ ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) // 对应的简报文件 string reportName = GetReportFileName(tarName); if (access(reportName.c_str(), F_OK) == 0) { - throw BError(BError::Codes::EXT_INVAL_ARG, string("The report file already exists")); + HILOGE("The report file already exists, Name = %{private}s, err =%{public}d", reportName.c_str(), errno); + errCode = errno; } UniqueFd reportFd(open(reportName.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); if (reportFd < 0) { @@ -303,24 +366,29 @@ ErrCode BackupExtExtension::GetIncrementalFileHandle(const string &fileName) } catch (...) { HILOGE("Failed to get incremental file handle"); DoClear(); - return BError(BError::Codes::EXT_INVAL_ARG).GetCode(); + return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); } } ErrCode BackupExtExtension::HandleClear() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - HILOGI("begin clear"); - if (extension_ == nullptr) { - HILOGE("Failed to handle clear, 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 { + HILOGI("begin clear"); + if (extension_ == nullptr) { + HILOGE("Failed to handle clear, 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(); + } + VerifyCaller(); + DoClear(); + return ERR_OK; + } catch (...) { + HILOGE("Failed to handle clear"); + return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); } - VerifyCaller(); - DoClear(); - return ERR_OK; } static ErrCode IndexFileReady(const TarMap &pkgInfo, sptr proxy) @@ -352,36 +420,26 @@ static ErrCode IndexFileReady(const TarMap &pkgInfo, sptr proxy) return ret; } -ErrCode BackupExtExtension::BigFileReady(sptr proxy) +ErrCode BackupExtExtension::BigFileReady(const TarMap &bigFileInfo, sptr proxy) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - UniqueFd fd(open(INDEX_FILE_BACKUP.data(), O_RDONLY)); - if (fd < 0) { - HILOGE("Failed to open index json file = %{private}s, err = %{public}d", INDEX_FILE_BACKUP.c_str(), errno); - return BError::GetCodeByErrno(errno); - } - BJsonCachedEntity cachedEntity(move(fd)); - auto cache = cachedEntity.Structuralize(); - auto pkgInfo = cache.GetExtManageInfo(); - HILOGI("BigFileReady Begin: pkgInfo file size is: %{public}zu", pkgInfo.size()); + HILOGI("BigFileReady Begin: bigFileInfo file size is: %{public}zu", bigFileInfo.size()); ErrCode ret {ERR_OK}; auto startTime = std::chrono::system_clock::now(); int fdNum = 0; - for (auto &item : pkgInfo) { - if (item.hashName.empty() || item.fileName.empty()) { - continue; - } + for (auto &item : bigFileInfo) { WaitToSendFd(startTime, fdNum); int32_t errCode = ERR_OK; - UniqueFd fd(open(item.fileName.data(), O_RDONLY)); + string fllePath = std::get<0>(item.second); + UniqueFd fd(open(fllePath.data(), O_RDONLY)); if (fd < 0) { - HILOGE("open file failed, file name is %{public}s, err = %{public}d", item.fileName.c_str(), errno); + HILOGE("open file failed, file name is %{public}s, err = %{public}d", fllePath.c_str(), errno); errCode = errno; } - ret = proxy->AppFileReady(item.hashName, std::move(fd), errCode); + ret = proxy->AppFileReady(item.first, std::move(fd), errCode); if (SUCCEEDED(ret)) { - HILOGI("The application is packaged successfully, package name is %{public}s", item.hashName.c_str()); + HILOGI("The application is packaged successfully, package name is %{public}s", item.first.c_str()); } else { HILOGW("Current file execute app file ready interface failed, ret is:%{public}d", ret); } @@ -408,7 +466,7 @@ ErrCode BackupExtExtension::PublishFile(const std::string &fileName) VerifyCaller(); // 异步执行解压操作 if (extension_->AllowToBackupRestore()) { - AsyncTaskRestore(GetIdxFileData(), GetExtManageInfo()); + AsyncTaskRestore(GetIdxFileData(bundleName_), GetExtManageInfo(bundleName_)); } HILOGI("End publish file"); return ERR_OK; @@ -466,23 +524,16 @@ ErrCode BackupExtExtension::PublishIncrementalFile(const string &fileName) } } -ErrCode BackupExtExtension::HandleBackup() +ErrCode BackupExtExtension::HandleBackup(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - if (extension_ == nullptr) { - HILOGE("Failed to handle backup, extension is nullptr"); - return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); - } - string usrConfig = extension_->GetUsrConfig(); - BJsonCachedEntity cachedEntity(usrConfig); - auto cache = cachedEntity.Structuralize(); - if (!cache.GetAllowToBackupRestore()) { - HILOGE("Application does not allow backup or restore"); + SetClearDataFlag(isClearData); + if (!IfAllowToBackupRestore()) { return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") .GetCode(); } AsyncTaskOnBackup(); - return 0; + return ERR_OK; } static bool IsUserTar(const string &tarFile, const std::vector &extManageInfo) @@ -501,7 +552,7 @@ static bool IsUserTar(const string &tarFile, const std::vector &e return false; } -static pair> GetFileInfos(const vector &includes, const vector &excludes) +static pair> GetFileInfos(const vector &includes, const vector &excludes) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); auto [errCode, files, smallFiles] = BDir::GetBigFiles(includes, excludes); @@ -537,6 +588,76 @@ static pair> GetFileInfos(const vector &includes, return {bigFiles, smallFiles}; } +/** + * 全量tar包回传 + */ +static ErrCode TarFileReady(const TarMap &tarFileInfo, sptr proxy) +{ + if (tarFileInfo.empty()) { + HILOGI("TarFileReady: No tar file found"); + return ERR_OK; + } + string tarName = tarFileInfo.begin()->first; + string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); + string tarPath = path + tarName; + int32_t errCode = ERR_OK; + UniqueFd fd(open(tarPath.data(), O_RDONLY)); + if (fd < 0) { + HILOGE("TarFileReady open file failed, file name is %{public}s, err = %{public}d", tarName.c_str(), errno); + errCode = errno; + } + int ret = proxy->AppFileReady(tarName, std::move(fd), errCode); + if (SUCCEEDED(ret)) { + HILOGI("TarFileReady: AppFileReady success for %{public}s", tarName.c_str()); + // 删除文件 + RemoveFile(tarPath); + } else { + HILOGE("TarFileReady AppFileReady fail to be invoked for %{public}s: ret = %{public}d", tarName.c_str(), ret); + } + return ret; +} + +void BackupExtExtension::DoPacket(const map &srcFiles, TarMap &tar, sptr proxy) +{ + HILOGI("DoPacket begin, infos count: %{public}zu", srcFiles.size()); + string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); + uint64_t totalSize = 0; + uint32_t fileCount = 0; + vector packFiles; + TarFile::GetInstance().SetPacketMode(true); // 设置下打包模式 + auto startTime = std::chrono::system_clock::now(); + int fdNum = 0; + for (auto small : srcFiles) { + totalSize += small.second; + fileCount += 1; + packFiles.emplace_back(small.first); + if (totalSize >= BConstants::DEFAULT_SLICE_SIZE || fileCount >= BConstants::MAX_FILE_COUNT) { + TarMap tarMap {}; + TarFile::GetInstance().Packet(packFiles, "part", path, tarMap); + tar.insert(tarMap.begin(), tarMap.end()); + // 执行tar包回传功能 + WaitToSendFd(startTime, fdNum); + TarFileReady(tarMap, proxy); + totalSize = 0; + fileCount = 0; + packFiles.clear(); + fdNum += BConstants::FILE_AND_MANIFEST_FD_COUNT; + RefreshTimeInfo(startTime, fdNum); + } + } + if (fileCount > 0) { + // 打包回传 + TarMap tarMap {}; + TarFile::GetInstance().Packet(packFiles, "part", path, tarMap); + TarFileReady(tarMap, proxy); + fdNum = 1; + WaitToSendFd(startTime, fdNum); + tar.insert(tarMap.begin(), tarMap.end()); + packFiles.clear(); + RefreshTimeInfo(startTime, fdNum); + } +} + int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); @@ -557,6 +678,11 @@ int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig) vector includes = usrConfig.GetIncludes(); vector excludes = usrConfig.GetExcludes(); + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); + } + // 大文件处理 HILOGI("Start packet bigfiles and small files"); auto [bigFileInfo, smallFiles] = GetFileInfos(includes, excludes); @@ -567,21 +693,22 @@ int BackupExtExtension::DoBackup(const BJsonEntityExtensionConfig &usrConfig) } } + // 回传大文件 + HILOGI("Will notify BigFileReady"); + auto res = BigFileReady(bigFileInfo, proxy); + HILOGI("Start packet Tar files"); - // 分片打包 + // 分片打包, 回传tar包 TarMap tarMap {}; - TarFile::GetInstance().Packet(smallFiles, "part", path, tarMap); + DoPacket(smallFiles, tarMap, proxy); bigFileInfo.insert(tarMap.begin(), tarMap.end()); - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); - } + HILOGI("Do backup, DoPacket end"); + HILOGI("Will notify IndexFileReady"); if (auto ret = IndexFileReady(bigFileInfo, proxy); ret) { return ret; } - HILOGI("Will notify BigFileReady"); - auto res = BigFileReady(proxy); + HILOGI("HandleBackup finish, ret = %{public}d", res); return res; } @@ -599,14 +726,22 @@ int BackupExtExtension::DoRestore(const string &fileName) } // REM: 给定version // REM: 解压启动Extension时即挂载好的备份目录中的数据 - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + string path = GetRestoreTempPath(bundleName_); string tarName = path + fileName; // 当用户指定fullBackupOnly字段或指定版本的恢复,解压目录当前在/backup/restore if (extension_->SpecialVersionForCloneAndCloud() || extension_->UseFullBackupOnly()) { - UntarFile::GetInstance().UnPacket(tarName, path); + ErrCode err = UntarFile::GetInstance().UnPacket(tarName, path); + if (err != 0) { + HILOGE("Failed to untar file = %{public}s, err = %{public}d", tarName.c_str(), err); + return err; + } } else { - UntarFile::GetInstance().UnPacket(tarName, "/"); + ErrCode err = UntarFile::GetInstance().UnPacket(tarName, "/"); + if (err != 0) { + HILOGE("Failed to untar file = %{public}s, err = %{public}d", tarName.c_str(), err); + return err; + } } HILOGI("Application recovered successfully, package path is %{public}s", tarName.c_str()); @@ -636,28 +771,41 @@ int BackupExtExtension::DoIncrementalRestore() HILOGE("Failed to do incremental restore, extension is nullptr"); throw BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr"); } - auto fileSet = GetIdxFileData(); - auto extManageInfo = GetExtManageInfo(); + auto fileSet = GetIdxFileData(bundleName_); + auto extManageInfo = GetExtManageInfo(bundleName_); + ErrCode err = ERR_OK; + auto startTime = std::chrono::system_clock::now(); for (auto item : fileSet) { // 处理要解压的tar文件 + off_t tarFileSize = 0; if (ExtractFileExt(item) == "tar" && !IsUserTar(item, extManageInfo)) { if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { return EPERM; } + auto iter = find_if(extManageInfo.begin(), extManageInfo.end(), + [&item](const auto &itemManage) { return itemManage.hashName == item; }); + if (iter != extManageInfo.end()) { + tarFileSize = iter->sta.st_size; + } + radarRestoreInfo_.tarFileNum++; + radarRestoreInfo_.tarFileSize += static_cast(tarFileSize); // REM: 给定version // REM: 解压启动Extension时即挂载好的备份目录中的数据 - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + string path = GetRestoreTempPath(bundleName_); string tarName = path + item; // 当用户指定fullBackupOnly字段或指定版本的恢复,解压目录当前在/backup/restore if (extension_->SpecialVersionForCloneAndCloud() || extension_->UseFullBackupOnly()) { - UntarFile::GetInstance().IncrementalUnPacket(tarName, path, GetTarIncludes(tarName)); + err = UntarFile::GetInstance().IncrementalUnPacket(tarName, path, GetTarIncludes(tarName)); } else { - UntarFile::GetInstance().IncrementalUnPacket(tarName, "/", GetTarIncludes(tarName)); + err = UntarFile::GetInstance().IncrementalUnPacket(tarName, "/", GetTarIncludes(tarName)); } HILOGI("Application recovered successfully, package path is %{public}s", tarName.c_str()); } } - return ERR_OK; + auto endTime = std::chrono::system_clock::now(); + radarRestoreInfo_.tarFileSpendTime = + std::chrono::duration_cast(endTime - startTime).count(); + return err; } void BackupExtExtension::AsyncTaskBackup(const string config) @@ -667,9 +815,23 @@ void BackupExtExtension::AsyncTaskBackup(const string config) auto ptr = obj.promote(); BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); try { + HILOGI("Do backup, start fwk timer begin."); + bool isFwkStart; + ptr->StartFwkTimer(isFwkStart); + if (!isFwkStart) { + HILOGE("Do backup, start fwk timer fail."); + return; + } + HILOGI("Do backup, start fwk timer end."); BJsonCachedEntity cachedEntity(config); auto cache = cachedEntity.Structuralize(); + auto start = std::chrono::system_clock::now(); auto ret = ptr->DoBackup(cache); + auto end = std::chrono::system_clock::now(); + auto cost = to_string(std::chrono::duration_cast(end - start).count()); + AppRadar::Info info(ptr->bundleName_, "", string("\"spend_time\":").append(cost).append(string("ms\""))); + AppRadar::GetInstance().RecordBackupFuncRes(info, "BackupExtExtension::AsyncTaskBackup", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_DO_BACKUP, static_cast(ret)); // REM: 处理返回结果 ret ptr->AppDone(ret); HILOGI("backup app done %{public}d", ret); @@ -731,15 +893,20 @@ static ErrCode RestoreTarForSpecialCloneCloud(ExtManageInfo item) if (untarPath.back() != BConstants::FILE_SEPARATOR_CHAR) { untarPath += BConstants::FILE_SEPARATOR_CHAR; } - UntarFile::GetInstance().UnPacket(tarName, untarPath); - + HILOGI("Start to untar file = %{public}s, untarPath = %{public}s", GetAnonyPath(item.hashName).c_str(), + GetAnonyPath(untarPath).c_str()); + ErrCode err = UntarFile::GetInstance().UnPacket(tarName, untarPath); + if (err != ERR_OK) { + HILOGE("Failed to untar file = %{public}s, err = %{public}d", tarName.c_str(), err); + return err; + } if (!RemoveFile(tarName)) { HILOGE("Failed to delete the backup tar %{public}s", tarName.c_str()); } return ERR_OK; } -static ErrCode RestoreFilesForSpecialCloneCloud() +ErrCode BackupExtExtension::RestoreFilesForSpecialCloneCloud() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); // 获取索引文件内容 @@ -753,15 +920,20 @@ static ErrCode RestoreFilesForSpecialCloneCloud() auto cache = cachedEntity.Structuralize(); auto info = cache.GetExtManageInfo(); HILOGI("Start do restore for SpecialCloneCloud."); + auto startTime = std::chrono::system_clock::now(); for (auto &item : info) { if (item.hashName.empty()) { continue; } if (item.isUserTar || item.isBigFile) { // 大文件处理 + radarRestoreInfo_.bigFileNum++; + radarRestoreInfo_.bigFileSize += static_cast(item.sta.st_size); RestoreBigFilesForSpecialCloneCloud(item); } else { // 待解压tar文件处理 + radarRestoreInfo_.tarFileNum++; + radarRestoreInfo_.tarFileSize += static_cast(item.sta.st_size); if (RestoreTarForSpecialCloneCloud(item) != ERR_OK) { HILOGE("Failed to restore tar file %{public}s", item.hashName.c_str()); return ERR_INVALID_VALUE; @@ -771,6 +943,10 @@ static ErrCode RestoreFilesForSpecialCloneCloud() if (!RemoveFile(INDEX_FILE_RESTORE)) { HILOGE("Failed to delete the backup index %{public}s", INDEX_FILE_RESTORE.c_str()); } + auto endTime = std::chrono::system_clock::now(); + radarRestoreInfo_.totalFileSpendTime = static_cast( + std::chrono::duration_cast(endTime - startTime).count()); + RecordDoRestoreRes(bundleName_, "BackupExtExtension::RestoreFilesForSpecialCloneCloud", radarRestoreInfo_); HILOGI("End do restore for SpecialCloneCloud."); return ERR_OK; } @@ -812,25 +988,28 @@ static void RestoreBigFileAfter(const string &filePath, const struct stat &sta) } } -static void RestoreBigFiles(bool appendTargetPath) +void BackupExtExtension::RestoreBigFiles(bool appendTargetPath) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); // 获取索引文件内容 - string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); - UniqueFd fd(open(INDEX_FILE_RESTORE.data(), O_RDONLY)); + string path = GetRestoreTempPath(bundleName_); + string indexFileRestorePath = GetIndexFileRestorePath(bundleName_); + UniqueFd fd(open(indexFileRestorePath.data(), O_RDONLY)); if (fd < 0) { - HILOGE("Failed to open index json file = %{private}s, err = %{public}d", INDEX_FILE_RESTORE.c_str(), errno); + HILOGE("Failed to open index json file = %{private}s, err = %{public}d", indexFileRestorePath.c_str(), errno); return; } BJsonCachedEntity cachedEntity(move(fd)); auto cache = cachedEntity.Structuralize(); auto info = cache.GetExtManageInfo(); HILOGI("Start Restore Big Files"); + auto start = std::chrono::system_clock::now(); for (auto &item : info) { if (item.hashName.empty() || (!item.isUserTar && !item.isBigFile)) { continue; } - + radarRestoreInfo_.bigFileNum++; + radarRestoreInfo_.bigFileSize += static_cast(item.sta.st_size); string itemHashName = item.hashName; string itemFileName = item.fileName; // check if item.hasName and fileName need decode by report item attribute @@ -857,23 +1036,31 @@ static void RestoreBigFiles(bool appendTargetPath) RestoreBigFileAfter(filePath, item.sta); } + auto end = std::chrono::system_clock::now(); + radarRestoreInfo_.bigFileSpendTime = + static_cast(std::chrono::duration_cast(end - start).count()); HILOGI("End Restore Big Files"); } -static void DeleteBackupTars() +void BackupExtExtension::DeleteBackupTars() { + if (!isClearData_) { + HILOGI("configured not clear data."); + return; + } HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - UniqueFd fd(open(INDEX_FILE_RESTORE.data(), O_RDONLY)); + string indexFileRestorePath = GetIndexFileRestorePath(bundleName_); + UniqueFd fd(open(indexFileRestorePath.data(), O_RDONLY)); if (fd < 0) { - HILOGE("Failed to open index json file = %{private}s, err = %{public}d", INDEX_FILE_RESTORE.c_str(), errno); + HILOGE("Failed to open index json file = %{private}s, err = %{public}d", indexFileRestorePath.c_str(), errno); return; } // The directory include tars and manage.json which would be deleted BJsonCachedEntity cachedEntity(move(fd)); auto cache = cachedEntity.Structuralize(); auto info = cache.GetExtManage(); - auto path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); - auto extManageInfo = GetExtManageInfo(); + auto path = GetRestoreTempPath(bundleName_); + auto extManageInfo = GetExtManageInfo(bundleName_); for (auto &item : info) { if (ExtractFileExt(item) != "tar" || IsUserTar(item, extManageInfo)) { continue; @@ -883,25 +1070,30 @@ static void DeleteBackupTars() HILOGE("Failed to delete the backup tar %{public}s", tarPath.c_str()); } } - if (!RemoveFile(INDEX_FILE_RESTORE)) { - HILOGE("Failed to delete the backup index %{public}s", INDEX_FILE_RESTORE.c_str()); + if (!RemoveFile(indexFileRestorePath)) { + HILOGE("Failed to delete the backup index %{public}s", indexFileRestorePath.c_str()); } HILOGI("End execute DeleteBackupTars"); } -static void DeleteBackupIncrementalTars() +void BackupExtExtension::DeleteBackupIncrementalTars() { - UniqueFd fd(open(INDEX_FILE_RESTORE.data(), O_RDONLY)); + if (!isClearData_) { + HILOGI("configured not clear data."); + return; + } + string indexFileRestorePath = GetIndexFileRestorePath(bundleName_); + UniqueFd fd(open(indexFileRestorePath.data(), O_RDONLY)); if (fd < 0) { - HILOGE("Failed to open index json file = %{private}s, err = %{public}d", INDEX_FILE_RESTORE.c_str(), errno); + HILOGE("Failed to open index json file = %{private}s, err = %{public}d", indexFileRestorePath.c_str(), errno); return; } // The directory include tars and manage.json which would be deleted BJsonCachedEntity cachedEntity(move(fd)); auto cache = cachedEntity.Structuralize(); auto info = cache.GetExtManage(); - auto path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); - auto extManageInfo = GetExtManageInfo(); + auto path = GetRestoreTempPath(bundleName_); + auto extManageInfo = GetExtManageInfo(bundleName_); for (auto &item : info) { if (ExtractFileExt(item) != "tar" || IsUserTar(item, extManageInfo)) { continue; @@ -916,15 +1108,28 @@ static void DeleteBackupIncrementalTars() HILOGE("Failed to delete the backup report %{private}s, err = %{public}d", reportPath.c_str(), errno); } } - if (!RemoveFile(INDEX_FILE_RESTORE)) { - HILOGE("Failed to delete the backup index %{public}s", INDEX_FILE_RESTORE.c_str()); + if (!RemoveFile(indexFileRestorePath)) { + HILOGE("Failed to delete the backup index %{public}s", indexFileRestorePath.c_str()); } - string reportManagePath = GetReportFileName(INDEX_FILE_RESTORE); // GetIncrementalFileHandle创建的空fd + string reportManagePath = GetReportFileName(indexFileRestorePath); // GetIncrementalFileHandle创建的空fd if (!RemoveFile(reportManagePath)) { HILOGE("Failed to delete the backup report index %{public}s", reportManagePath.c_str()); } } +void BackupExtExtension::HandleSpecialVersionRestore(wptr obj) +{ + auto ptr = obj.promote(); + BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); + auto ret = RestoreFilesForSpecialCloneCloud(); + if (ret == ERR_OK) { + ptr->AsyncTaskRestoreForUpgrade(); + } else { + ptr->AppDone(ret); + ptr->DoClear(); + } +} + void BackupExtExtension::AsyncTaskRestore(std::set fileSet, const std::vector extManageInfo) { @@ -935,13 +1140,7 @@ void BackupExtExtension::AsyncTaskRestore(std::set fileSet, try { int ret = ERR_OK; if (ptr->extension_->SpecialVersionForCloneAndCloud()) { - ret = RestoreFilesForSpecialCloneCloud(); - if (ret == ERR_OK) { - ptr->AsyncTaskRestoreForUpgrade(); - } else { - ptr->AppDone(ret); - ptr->DoClear(); - } + ptr->HandleSpecialVersionRestore(obj); return; } // 解压 @@ -954,8 +1153,8 @@ void BackupExtExtension::AsyncTaskRestore(std::set fileSet, // 目的地址是否需要拼接path(临时目录),FullBackupOnly为true并且非特殊场景 bool appendTargetPath = ptr->extension_->UseFullBackupOnly() && !ptr->extension_->SpecialVersionForCloneAndCloud(); - RestoreBigFiles(appendTargetPath); - DeleteBackupTars(); + ptr->RestoreBigFiles(appendTargetPath); + ptr->DeleteBackupTars(); if (ret == ERR_OK) { ptr->AsyncTaskRestoreForUpgrade(); } else { @@ -991,17 +1190,21 @@ void BackupExtExtension::AsyncTaskIncrementalRestore() BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); BExcepUltils::BAssert(ptr->extension_, BError::Codes::EXT_INVAL_ARG, "Extension handle have been released"); try { + auto startTime = std::chrono::system_clock::now(); // 解压 int ret = ptr->DoIncrementalRestore(); // 恢复用户tar包以及大文件 // 目的地址是否需要拼接path(临时目录),FullBackupOnly为true并且非特殊场景 bool appendTargetPath = ptr->extension_->UseFullBackupOnly() && !ptr->extension_->SpecialVersionForCloneAndCloud(); - RestoreBigFiles(appendTargetPath); - + ptr->RestoreBigFiles(appendTargetPath); // delete 1.tar/manage.json - DeleteBackupIncrementalTars(); - + ptr->DeleteBackupIncrementalTars(); + auto endTime = std::chrono::system_clock::now(); + ptr->radarRestoreInfo_.totalFileSpendTime = static_cast( + std::chrono::duration_cast(endTime - startTime).count()); + RecordDoRestoreRes(ptr->bundleName_, "BackupExtExtension::AsyncTaskIncrementalRestore", + ptr->radarRestoreInfo_); if (ret == ERR_OK) { HILOGI("after extra, do incremental restore."); ptr->AsyncTaskIncrementalRestoreForUpgrade(); @@ -1038,7 +1241,7 @@ void BackupExtExtension::AsyncTaskIncreRestoreSpecialVersion() auto ptr = obj.promote(); BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); try { - int ret = RestoreFilesForSpecialCloneCloud(); + int ret = ptr->RestoreFilesForSpecialCloneCloud(); if (ret == ERR_OK) { ptr->AsyncTaskIncrementalRestoreForUpgrade(); } else { @@ -1072,29 +1275,27 @@ void BackupExtExtension::AsyncTaskRestoreForUpgrade() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); auto task = [obj {wptr(this)}]() { - auto callBackup = [obj](ErrCode errCode, std::string errMsg) { - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - HILOGI("Current bundle will execute app done"); - if (errMsg.empty()) { - extensionPtr->AppDone(errCode); - } else { - std::string errInfo; - BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, errMsg); - extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::FULL_RESTORE, errCode); - } - extensionPtr->DoClear(); - }; auto ptr = obj.promote(); BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); BExcepUltils::BAssert(ptr->extension_, BError::Codes::EXT_INVAL_ARG, "Extension handle have been released"); try { - auto callBackupEx = ptr->RestoreResultCallbackEx(obj); + HILOGI("On restore, start ext timer begin."); + bool isExtStart; + ptr->StartExtTimer(isExtStart); + if (!isExtStart) { + HILOGE("On restore, start ext timer fail."); + return; + } + HILOGI("On restore, start ext timer end."); + ptr->StartOnProcessTaskThread(obj, BackupRestoreScenario::FULL_RESTORE); + auto callBackup = ptr->OnRestoreCallback(obj); + auto callBackupEx = ptr->OnRestoreExCallback(obj); + ptr->UpdateOnStartTime(); ErrCode err = ptr->extension_->OnRestore(callBackup, callBackupEx); - HILOGI("OnRestore done err = %{public}d", err); + if (err != ERR_OK) { + ptr->AppDone(BError::GetCodeByErrno(err)); + ptr->DoClear(); + } } catch (const BError &e) { ptr->AppDone(e.GetCode()); ptr->DoClear(); @@ -1126,29 +1327,28 @@ void BackupExtExtension::ExtClear() void BackupExtExtension::AsyncTaskIncrementalRestoreForUpgrade() { auto task = [obj {wptr(this)}]() { - auto callBackup = [obj](ErrCode errCode, std::string errMsg) { - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - HILOGI("Current bundle will execute app done"); - if (errMsg.empty()) { - extensionPtr->AppIncrementalDone(errCode); - } else { - std::string errInfo; - BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, errMsg); - extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::INCREMENTAL_RESTORE, errCode); - } - extensionPtr->DoClear(); - }; auto ptr = obj.promote(); BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); BExcepUltils::BAssert(ptr->extension_, BError::Codes::EXT_INVAL_ARG, "Extension handle have been released"); try { - auto callBackupEx = ptr->IncRestoreResultCallbackEx(obj); + HILOGI("On incrementalRestore, start ext timer begin."); + bool isExtStart; + ptr->StartExtTimer(isExtStart); + if (!isExtStart) { + HILOGE("On incrementalRestore, start ext timer fail."); + return; + } + HILOGI("On incrementalRestore, start ext timer end."); + ptr->StartOnProcessTaskThread(obj, BackupRestoreScenario::INCREMENTAL_RESTORE); + auto callBackup = ptr->IncreOnRestoreCallback(obj); + auto callBackupEx = ptr->IncreOnRestoreExCallback(obj); + ptr->UpdateOnStartTime(); ErrCode err = ptr->extension_->OnRestore(callBackup, callBackupEx); - HILOGI("OnRestore done err = %{public}d", err); + if (err != ERR_OK) { + HILOGE("OnRestore done, err = %{pubilc}d", err); + ptr->AppIncrementalDone(BError::GetCodeByErrno(err)); + ptr->DoClear(); + } } catch (const BError &e) { ptr->AppIncrementalDone(e.GetCode()); ptr->DoClear(); @@ -1179,8 +1379,13 @@ void BackupExtExtension::DoClear() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { + if (!isClearData_) { + HILOGI("configured not clear data."); + return; + } string backupCache = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); string restoreCache = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE); + string specialRestoreCache = GetRestoreTempPath(bundleName_); if (!ForceRemoveDirectory(backupCache)) { HILOGI("Failed to delete the backup cache %{public}s", backupCache.c_str()); @@ -1189,11 +1394,28 @@ void BackupExtExtension::DoClear() if (!ForceRemoveDirectory(restoreCache)) { HILOGI("Failed to delete the restore cache %{public}s", restoreCache.c_str()); } + + if (!ForceRemoveDirectory(specialRestoreCache)) { + HILOGI("Failed to delete cache for filemanager or medialibrary %{public}s", specialRestoreCache.c_str()); + } // delete el1 backup/restore ForceRemoveDirectory( string(BConstants::PATH_BUNDLE_BACKUP_HOME_EL1).append(BConstants::SA_BUNDLE_BACKUP_BACKUP)); ForceRemoveDirectory( string(BConstants::PATH_BUNDLE_BACKUP_HOME_EL1).append(BConstants::SA_BUNDLE_BACKUP_RESTORE)); + // delete special directory + if (bundleName_.compare(MEDIA_LIBRARY_BUNDLE_NAME) == 0) { + ForceRemoveDirectory( + string(BConstants::PATH_MEDIALDATA_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP)); + ForceRemoveDirectory( + string(BConstants::PATH_MEDIALDATA_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE)); + } + if (bundleName_.compare(FILE_MANAGER_BUNDLE_NAME) == 0) { + ForceRemoveDirectory( + string(BConstants::PATH_FILEMANAGE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP)); + ForceRemoveDirectory( + string(BConstants::PATH_FILEMANAGE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_RESTORE)); + } unique_lock lock(lock_); } catch (...) { HILOGE("Failed to clear"); @@ -1205,7 +1427,11 @@ void BackupExtExtension::AppDone(ErrCode errCode) HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("AppDone Begin."); auto proxy = ServiceProxy::GetInstance(); - BExcepUltils::BAssert(proxy, BError::Codes::EXT_BROKEN_IPC, "Failed to obtain the ServiceProxy handle"); + if (proxy == nullptr) { + HILOGE("Failed to obtain the ServiceProxy handle"); + DoClear(); + return; + } auto ret = proxy->AppDone(errCode); if (ret != ERR_OK) { HILOGE("Failed to notify the app done. err = %{public}d", ret); @@ -1224,29 +1450,51 @@ void BackupExtExtension::AppResultReport(const std::string restoreRetInfo, } } +void BackupExtExtension::StartExtTimer(bool &isExtStart) +{ + auto proxy = ServiceProxy::GetInstance(); + BExcepUltils::BAssert(proxy, BError::Codes::EXT_BROKEN_IPC, "Failed to obtain the ServiceProxy handle"); + HILOGI("Start ext timer by ipc."); + auto ret = proxy->StartExtTimer(isExtStart); + if (ret != ERR_OK) { + HILOGE("Start ext timer failed, errCode: %{public}d", ret); + } +} + +void BackupExtExtension::StartFwkTimer(bool &isFwkStart) +{ + auto proxy = ServiceProxy::GetInstance(); + BExcepUltils::BAssert(proxy, BError::Codes::EXT_BROKEN_IPC, "Failed to obtain the ServiceProxy handle"); + HILOGI("Start fwk timer by ipc."); + auto ret = proxy->StartFwkTimer(isFwkStart); + if (ret != ERR_OK) { + HILOGE("Start fwk timer failed, errCode: %{public}d", ret); + } +} + +void BackupExtExtension::UpdateOnStartTime() +{ + std::lock_guard lock(onStartTimeLock_); + g_onStart = std::chrono::system_clock::now(); +} + void BackupExtExtension::AsyncTaskOnBackup() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); auto task = [obj {wptr(this)}]() { - auto callBackup = [obj](ErrCode errCode, std::string errMsg) { - HILOGI("begin call backup"); - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - if (extensionPtr->extension_ == nullptr) { - HILOGE("Extension handle have been released"); - return; - } - extensionPtr->AsyncTaskBackup(extensionPtr->extension_->GetUsrConfig()); - }; auto ptr = obj.promote(); BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); BExcepUltils::BAssert(ptr->extension_, BError::Codes::EXT_INVAL_ARG, "Extension handle have been released"); try { - auto callBackupEx = ptr->HandleTaskBackupEx(obj); - ptr->extension_->OnBackup(callBackup, callBackupEx); + ptr->StartOnProcessTaskThread(obj, BackupRestoreScenario::FULL_BACKUP); + auto callBackup = ptr->OnBackupCallback(obj); + auto callBackupEx = ptr->OnBackupExCallback(obj); + ptr->UpdateOnStartTime(); + ErrCode err = ptr->extension_->OnBackup(callBackup, callBackupEx); + if (err != ERR_OK) { + HILOGE("OnBackup done, err = %{pubilc}d", err); + ptr->AppDone(BError::GetCodeByErrno(err)); + } } catch (const BError &e) { ptr->AppDone(e.GetCode()); } catch (const exception &e) { @@ -1267,32 +1515,37 @@ void BackupExtExtension::AsyncTaskOnBackup() }); } -ErrCode BackupExtExtension::HandleRestore() +ErrCode BackupExtExtension::HandleRestore(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - VerifyCaller(); - if (extension_ == nullptr) { - HILOGE("Failed to handle restore, extension is nullptr"); - throw BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr"); - } - if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { - HILOGE("Failed to get file handle, because action is %{public}d invalid", extension_->GetExtensionAction()); - throw BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid"); - } - // read backup_config is allow to backup or restore - if (!extension_->AllowToBackupRestore()) { - HILOGE("Application does not allow backup or restore"); - return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") - .GetCode(); - } + try { + VerifyCaller(); + SetClearDataFlag(isClearData); + if (extension_ == nullptr) { + HILOGE("Failed to handle restore, extension is nullptr"); + return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); + } + if (extension_->GetExtensionAction() != BConstants::ExtensionAction::RESTORE) { + HILOGE("Failed to get file handle, because action is %{public}d invalid", extension_->GetExtensionAction()); + return BError(BError::Codes::EXT_INVAL_ARG, "Action is invalid").GetCode(); + } + // read backup_config is allow to backup or restore + if (!extension_->AllowToBackupRestore()) { + HILOGE("Application does not allow backup or restore"); + return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") + .GetCode(); + } - // async do restore. - if (extension_->WasFromSpecialVersion() && extension_->RestoreDataReady()) { - HILOGI("Restore directly when upgrading."); - AsyncTaskRestoreForUpgrade(); + // async do restore. + if (extension_->WasFromSpecialVersion() && extension_->RestoreDataReady()) { + HILOGI("Restore directly when upgrading."); + AsyncTaskRestoreForUpgrade(); + } + return ERR_OK; + } catch (...) { + HILOGE("Failed to handle restore"); + return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); } - - return 0; } static bool CheckTar(const string &fileName) @@ -1374,41 +1627,31 @@ void BackupExtExtension::CompareFiles(UniqueFd incrementalFd, ErrCode BackupExtExtension::HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) { - HILOGI("Start HandleIncrementalBackup"); HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - if (extension_ == nullptr) { - HILOGE("Failed to handle incremental backup, extension is nullptr"); - return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); - } - string usrConfig = extension_->GetUsrConfig(); - BJsonCachedEntity cachedEntity(usrConfig); - auto cache = cachedEntity.Structuralize(); - if (!cache.GetAllowToBackupRestore()) { - HILOGE("Application does not allow backup or restore"); - return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") - .GetCode(); + try { + HILOGI("Start HandleIncrementalBackup"); + if (!IfAllowToBackupRestore()) { + return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") + .GetCode(); + } + AsyncTaskDoIncrementalBackup(move(incrementalFd), move(manifestFd)); + return ERR_OK; + } catch (...) { + HILOGE("Failed to handle incremental backup"); + return BError(BError::Codes::EXT_INVAL_ARG).GetCode(); } - AsyncTaskDoIncrementalBackup(move(incrementalFd), move(manifestFd)); - return 0; } -ErrCode BackupExtExtension::IncrementalOnBackup() +ErrCode BackupExtExtension::IncrementalOnBackup(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - if (extension_ == nullptr) { - HILOGE("Failed to handle incremental onBackup, extension is nullptr"); - return BError(BError::Codes::EXT_INVAL_ARG, "Extension is nullptr").GetCode(); - } - string usrConfig = extension_->GetUsrConfig(); - BJsonCachedEntity cachedEntity(usrConfig); - auto cache = cachedEntity.Structuralize(); - if (!cache.GetAllowToBackupRestore()) { - HILOGE("Application does not allow backup or restore"); + SetClearDataFlag(isClearData); + if (!IfAllowToBackupRestore()) { return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") .GetCode(); } AsyncTaskOnIncrementalBackup(); - return 0; + return ERR_OK; } tuple BackupExtExtension::GetIncrementalBackupFileHandle() @@ -1546,16 +1789,39 @@ ErrCode BackupExtExtension::IncrementalBigFileReady(const TarMap &pkgInfo, } else { HILOGE("IncrementalBigFileReady interface fails to be invoked: %{public}d", ret); } - fdNum += FILE_AND_MANIFEST_FD_COUNT; + fdNum += BConstants::FILE_AND_MANIFEST_FD_COUNT; RefreshTimeInfo(startTime, fdNum); } HILOGI("IncrementalBigFileReady End"); return ret; } +int BackupExtExtension::DoIncrementalBackupTask(UniqueFd incrementalFd, UniqueFd manifestFd) +{ + auto start = std::chrono::system_clock::now(); + vector allFiles; + vector smallFiles; + vector bigFiles; + CompareFiles(move(incrementalFd), move(manifestFd), allFiles, smallFiles, bigFiles); + auto ret = DoIncrementalBackup(allFiles, smallFiles, bigFiles); + auto end = std::chrono::system_clock::now(); + auto cost = to_string(std::chrono::duration_cast(end - start).count()); + AppRadar::Info info(bundleName_, "", string("\"spend_time\":").append(cost).append(string("ms\""))); + AppRadar::GetInstance().RecordBackupFuncRes(info, "BackupExtExtension::AsyncTaskDoIncrementalBackup", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_DO_BACKUP, static_cast(ret)); + return ret; +} + void BackupExtExtension::AsyncTaskDoIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) { - HILOGI("Start AsyncTaskDoIncrementalBackup"); + HILOGI("Do IncrementalBackup, start fwk timer begin."); + bool isFwkStart; + StartFwkTimer(isFwkStart); + if (!isFwkStart) { + HILOGE("Do IncrementalBackup, start fwk timer fail."); + return; + } + HILOGI("Do IncrementalBackup, start fwk timer end."); int incrementalFdDup = dup(incrementalFd); int manifestFdDup = dup(manifestFd); if (incrementalFdDup < 0) { @@ -1572,11 +1838,7 @@ void BackupExtExtension::AsyncTaskDoIncrementalBackup(UniqueFd incrementalFd, Un } close(incrementalFdDup); close(manifestFdDup); - vector allFiles; - vector smallFiles; - vector bigFiles; - ptr->CompareFiles(move(incrementalDupFd), move(manifestDupFd), allFiles, smallFiles, bigFiles); - auto ret = ptr->DoIncrementalBackup(allFiles, smallFiles, bigFiles); + auto ret = ptr->DoIncrementalBackupTask(move(incrementalDupFd), move(manifestDupFd)); ptr->AppIncrementalDone(ret); HILOGI("Incremental backup app done %{public}d", ret); } catch (const BError &e) { @@ -1602,21 +1864,19 @@ void BackupExtExtension::AsyncTaskDoIncrementalBackup(UniqueFd incrementalFd, Un void BackupExtExtension::AsyncTaskOnIncrementalBackup() { auto task = [obj {wptr(this)}]() { - auto callBackup = [obj](ErrCode errCode, std::string errMsg) { - HILOGI("App onbackup end"); - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); - } - HILOGI("Start GetAppLocalListAndDoIncrementalBackup"); - proxy->GetAppLocalListAndDoIncrementalBackup(); - }; auto ptr = obj.promote(); BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); BExcepUltils::BAssert(ptr->extension_, BError::Codes::EXT_INVAL_ARG, "Extension handle have been released"); try { - auto callBackupEx = ptr->HandleBackupEx(obj); - ptr->extension_->OnBackup(callBackup, callBackupEx); + ptr->StartOnProcessTaskThread(obj, BackupRestoreScenario::INCREMENTAL_BACKUP); + auto callBackup = ptr->IncOnBackupCallback(obj); + auto callBackupEx = ptr->IncOnBackupExCallback(obj); + ptr->UpdateOnStartTime(); + ErrCode err = ptr->extension_->OnBackup(callBackup, callBackupEx); + if (err != ERR_OK) { + HILOGE("OnBackup done, err = %{pubilc}d", err); + ptr->AppIncrementalDone(BError::GetCodeByErrno(err)); + } } catch (const BError &e) { ptr->AppIncrementalDone(e.GetCode()); } catch (const exception &e) { @@ -1651,7 +1911,7 @@ void BackupExtExtension::IncrementalPacket(const vector & { HILOGI("IncrementalPacket begin, infos count: %{public}zu", infos.size()); string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); - int64_t totalSize = 0; + uint64_t totalSize = 0; uint32_t fileCount = 0; vector packFiles; vector tarInfos; @@ -1660,11 +1920,11 @@ void BackupExtExtension::IncrementalPacket(const vector & int fdNum = 0; string partName = GetIncrmentPartName(); for (auto small : infos) { - totalSize += small.size; + totalSize += static_cast(small.size); fileCount += 1; packFiles.emplace_back(small.filePath); tarInfos.emplace_back(small); - if (totalSize >= DEFAULT_SLICE_SIZE || fileCount >= MAX_FILE_COUNT) { + if (totalSize >= BConstants::DEFAULT_SLICE_SIZE || fileCount >= BConstants::MAX_FILE_COUNT) { TarMap tarMap {}; TarFile::GetInstance().Packet(packFiles, partName, path, tarMap); tar.insert(tarMap.begin(), tarMap.end()); @@ -1675,7 +1935,7 @@ void BackupExtExtension::IncrementalPacket(const vector & fileCount = 0; packFiles.clear(); tarInfos.clear(); - fdNum += FILE_AND_MANIFEST_FD_COUNT; + fdNum += BConstants::FILE_AND_MANIFEST_FD_COUNT; RefreshTimeInfo(startTime, fdNum); } } @@ -1748,9 +2008,9 @@ int BackupExtExtension::DoIncrementalBackup(const vector if (smallFiles.size() == 0 && bigFiles.size() == 0) { // 没有增量,则不需要上传 TarMap tMap; - IncrementalAllFileReady(tMap, allFiles, proxy); + ErrCode err = IncrementalAllFileReady(tMap, allFiles, proxy); HILOGI("Do increment backup, IncrementalAllFileReady end, file empty"); - return ERR_OK; + return err; } // tar包数据 TarMap tarMap; @@ -1762,230 +2022,135 @@ int BackupExtExtension::DoIncrementalBackup(const vector HILOGI("Do increment backup, IncrementalBigFileReady end"); bigMap.insert(tarMap.begin(), tarMap.end()); // 回传manage.json和全量文件 - IncrementalAllFileReady(bigMap, allFiles, proxy); + ErrCode err = IncrementalAllFileReady(bigMap, allFiles, proxy); HILOGI("End, bigFiles num:%{public}zu, smallFiles num:%{public}zu, allFiles num:%{public}zu", bigFiles.size(), smallFiles.size(), allFiles.size()); - return ERR_OK; -} - -void BackupExtExtension::AppIncrementalDone(ErrCode errCode) -{ - HILOGI("Begin"); - auto proxy = ServiceProxy::GetInstance(); - BExcepUltils::BAssert(proxy, BError::Codes::EXT_BROKEN_IPC, "Failed to obtain the ServiceProxy handle"); - auto ret = proxy->AppIncrementalDone(errCode); - if (ret != ERR_OK) { - HILOGE("Failed to notify the app done. err = %{public}d", ret); - } + return err; } -ErrCode BackupExtExtension::GetBackupInfo(std::string &result) +bool BackupExtExtension::IfAllowToBackupRestore() { - auto obj = wptr(this); - auto ptr = obj.promote(); - if (ptr == nullptr) { - HILOGE("Failed to get ext extension."); - return BError(BError::Codes::EXT_INVAL_ARG, "extension getBackupInfo exception").GetCode(); - } - if (ptr->extension_ == nullptr) { - HILOGE("Failed to get extension."); - return BError(BError::Codes::EXT_INVAL_ARG, "extension getBackupInfo exception").GetCode(); + if (extension_ == nullptr) { + HILOGE("Failed to handle backup, extension is nullptr"); + return false; } - auto callBackup = [ptr](ErrCode errCode, const std::string result) { - if (ptr == nullptr) { - HILOGE("Failed to get ext extension."); - return; - } - HILOGI("GetBackupInfo callBackup start. result = %{public}s", result.c_str()); - ptr->backupInfo_ = result; - }; - auto ret = ptr->extension_->GetBackupInfo(callBackup); - if (ret != ERR_OK) { - HILOGE("Failed to get backupInfo. err = %{public}d", ret); - return BError(BError::Codes::EXT_INVAL_ARG, "extension getBackupInfo exception").GetCode(); + string usrConfig = extension_->GetUsrConfig(); + BJsonCachedEntity cachedEntity(usrConfig); + auto cache = cachedEntity.Structuralize(); + if (!cache.GetAllowToBackupRestore()) { + HILOGE("Application does not allow backup or restore"); + return false; } - HILOGD("backupInfo = %s", backupInfo_.c_str()); - result = backupInfo_; - backupInfo_.clear(); - - return ERR_OK; + return true; } -ErrCode BackupExtExtension::UpdateFdSendRate(std::string &bundleName, int32_t sendRate) +ErrCode BackupExtExtension::User0OnBackup() { - std::lock_guard lock(updateSendRateLock_); - HILOGI("Update SendRate, bundleName:%{public}s, sendRate:%{public}d", bundleName.c_str(), sendRate); - VerifyCaller(); - bundleName_ = bundleName; - sendRate_ = sendRate; - if (sendRate > 0) { - startSendFdRateCon_.notify_one(); + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + if (!IfAllowToBackupRestore()) { + return BError(BError::Codes::EXT_FORBID_BACKUP_RESTORE, "Application does not allow backup or restore") + .GetCode(); } + AsyncTaskUser0Backup(); return ERR_OK; } -std::function BackupExtExtension::RestoreResultCallbackEx(wptr obj) +void BackupExtExtension::AsyncTaskUser0Backup() { - HILOGI("Begin get callbackEx"); - return [obj](ErrCode errCode, const std::string restoreRetInfo) { - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - if (extensionPtr->extension_ == nullptr) { - HILOGE("Extension handle have been released"); - return; - } - extensionPtr->extension_->InvokeAppExtMethod(errCode, restoreRetInfo); - if (errCode == ERR_OK) { - if (restoreRetInfo.size()) { - HILOGI("Will notify restore result report"); - extensionPtr->AppResultReport(restoreRetInfo, BackupRestoreScenario::FULL_RESTORE); + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + auto task = [obj {wptr(this)}]() { + auto ptr = obj.promote(); + BExcepUltils::BAssert(ptr, BError::Codes::EXT_BROKEN_FRAMEWORK, "Ext extension handle have been released"); + const string config = ptr->extension_->GetUsrConfig(); + try { + HILOGI("Do backup, start fwk timer begin."); + bool isFwkStart; + ptr->StartFwkTimer(isFwkStart); + if (!isFwkStart) { + HILOGE("Do backup, start fwk timer fail."); + return; } - return; - } - if (restoreRetInfo.empty()) { - extensionPtr->AppDone(errCode); - extensionPtr->DoClear(); - } else { - std::string errInfo; - BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, restoreRetInfo); - extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::FULL_RESTORE, errCode); - extensionPtr->DoClear(); - } - }; -} - -std::function BackupExtExtension::AppDoneCallbackEx(wptr obj) -{ - HILOGI("Begin get callback for appDone"); - return [obj](ErrCode errCode, std::string errMsg) { - HILOGI("begin call callBackupExAppDone"); - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - extensionPtr->AppDone(errCode); - extensionPtr->DoClear(); - }; -} - -std::function BackupExtExtension::IncRestoreResultCallbackEx(wptr obj) -{ - HILOGI("Begin get callback for onRestore"); - return [obj](ErrCode errCode, const std::string restoreRetInfo) { - HILOGI("begin call restoreEx"); - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - if (extensionPtr->extension_ == nullptr) { - HILOGE("Extension handle have been released"); - return; - } - extensionPtr->extension_->InvokeAppExtMethod(errCode, restoreRetInfo); - if (errCode == ERR_OK) { - if (restoreRetInfo.size()) { - extensionPtr->AppResultReport(restoreRetInfo, BackupRestoreScenario::INCREMENTAL_RESTORE); + HILOGI("Do backup, start fwk timer end."); + BJsonCachedEntity cachedEntity(config); + auto cache = cachedEntity.Structuralize(); + auto ret = ptr->User0DoBackup(cache); + if (ret != ERR_OK) { + HILOGE("User0DoBackup, err = %{pubilc}d", ret); + ptr->AppIncrementalDone(BError::GetCodeByErrno(ret)); } - return; - } - if (restoreRetInfo.empty()) { - extensionPtr->AppIncrementalDone(errCode); - extensionPtr->DoClear(); - } else { - std::string errInfo; - BJsonUtil::BuildRestoreErrInfo(errInfo, errCode, restoreRetInfo); - extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::INCREMENTAL_RESTORE, errCode); - extensionPtr->DoClear(); + } catch (const BError &e) { + HILOGE("extension: AsyncTaskBackup error, err code:%{public}d", e.GetCode()); + ptr->AppIncrementalDone(e.GetCode()); + } catch (const exception &e) { + HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); + ptr->AppIncrementalDone(BError(BError::Codes::EXT_INVAL_ARG).GetCode()); + } catch (...) { + HILOGE("Failed to restore the ext bundle"); + ptr->AppIncrementalDone(BError(BError::Codes::EXT_INVAL_ARG).GetCode()); } }; -} -std::function BackupExtExtension::HandleBackupEx(wptr obj) -{ - HILOGI("Begin get HandleBackupEx"); - return [obj](ErrCode errCode, const std::string backupExRetInfo) { - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); - } - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - if (extensionPtr->extension_ == nullptr) { - HILOGE("Extension handle have been released"); - return; - } - extensionPtr->extension_->InvokeAppExtMethod(errCode, backupExRetInfo); - if (backupExRetInfo.size()) { - HILOGI("Start GetAppLocalListAndDoIncrementalBackup"); - proxy->GetAppLocalListAndDoIncrementalBackup(); - HILOGI("Will notify backup result report"); - extensionPtr->AppResultReport(backupExRetInfo, BackupRestoreScenario::INCREMENTAL_BACKUP); + threadPool_.AddTask([task]() { + try { + task(); + } catch (...) { + HILOGE("Failed to add task to thread pool"); } - }; + }); } -std::function BackupExtExtension::HandleTaskBackupEx(wptr obj) +void BackupExtExtension::DoUser0Backup(const BJsonEntityExtensionConfig &usrConfig) { - HILOGI("Begin get HandleTaskBackupEx"); - return [obj](ErrCode errCode, const std::string backupExRetInfo) { - HILOGI("begin call backup"); - auto extensionPtr = obj.promote(); - if (extensionPtr == nullptr) { - HILOGE("Ext extension handle have been released"); - return; - } - if (extensionPtr->extension_ == nullptr) { - HILOGE("Extension handle have been released"); - return; - } - extensionPtr->extension_->InvokeAppExtMethod(errCode, backupExRetInfo); - if (backupExRetInfo.size()) { - extensionPtr->AsyncTaskBackup(extensionPtr->extension_->GetUsrConfig()); - HILOGI("Will notify backup result report"); - extensionPtr->AppResultReport(backupExRetInfo, BackupRestoreScenario::FULL_BACKUP); + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + string path = string(BConstants::PATH_BUNDLE_BACKUP_HOME).append(BConstants::SA_BUNDLE_BACKUP_BACKUP); + if (mkdir(path.data(), S_IRWXU) && errno != EEXIST) { + throw BError(errno); + } + vector includes = usrConfig.GetIncludes(); + vector excludes = usrConfig.GetExcludes(); + 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"); + try { + auto [bigFile, smallFile] = BDir::GetBackupList(includes, excludes); + vector allFiles; + vector smallFiles; + vector bigFiles; + BDir::GetUser0FileStat(move(bigFile), move(smallFile), allFiles, smallFiles, bigFiles); + auto ret = ptr->DoIncrementalBackup(allFiles, smallFiles, bigFiles); + ptr->AppIncrementalDone(ret); + HILOGI("User0 backup app done %{public}d", ret); + } catch (const BError &e) { + ptr->AppIncrementalDone(e.GetCode()); + } catch (const exception &e) { + ptr->AppIncrementalDone(BError(BError::Codes::EXT_INVAL_ARG).GetCode()); + } catch (...) { + HILOGE("Failed to restore the ext bundle"); + ptr->AppIncrementalDone(BError(BError::Codes::EXT_INVAL_ARG).GetCode()); } }; -} -void BackupExtExtension::WaitToSendFd(std::chrono::system_clock::time_point &startTime, int &fdSendNum) -{ - HILOGD("WaitToSendFd Begin"); - std::unique_lock lock(startSendMutex_); - startSendFdRateCon_.wait(lock, [this] { return sendRate_ > 0; }); - if (fdSendNum >= sendRate_) { - HILOGI("current time fd num is max rate, bundle name:%{public}s, rate:%{public}d", bundleName_.c_str(), - sendRate_); - auto curTime = std::chrono::system_clock::now(); - auto useTimeMs = std::chrono::duration_cast(curTime - startTime).count(); - if (useTimeMs < MAX_FD_GROUP_USE_TIME) { - int32_t sleepTime = MAX_FD_GROUP_USE_TIME - useTimeMs; - HILOGI("will wait time:%{public}d ms", sleepTime); - std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime)); - } else { - HILOGW("current fd send num exceeds one second"); + threadPool_.AddTask([task]() { + try { + task(); + } catch (...) { + HILOGE("Failed to add task to thread pool"); } - fdSendNum = 0; - startTime = std::chrono::system_clock::now(); - } - HILOGD("WaitToSendFd End"); + }); } -void BackupExtExtension::RefreshTimeInfo(std::chrono::system_clock::time_point &startTime, int &fdSendNum) +int BackupExtExtension::User0DoBackup(const BJsonEntityExtensionConfig &usrConfig) { - auto currentTime = std::chrono::system_clock::now(); - auto useTime = std::chrono::duration_cast(currentTime - startTime).count(); - if (useTime >= MAX_FD_GROUP_USE_TIME) { - HILOGI("RefreshTimeInfo Begin, fdSendNum is:%{public}d", fdSendNum); - startTime = std::chrono::system_clock::now(); - fdSendNum = 0; + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + HILOGI("Start Do User0Backup"); + if (extension_ == nullptr) { + HILOGE("Failed to do backup, extension is nullptr"); + return BError(BError::Codes::EXT_INVAL_ARG); + } + if (extension_->GetExtensionAction() != BConstants::ExtensionAction::BACKUP) { + return EPERM; } + DoUser0Backup(usrConfig); + return ERR_OK; } } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_ext/src/ext_extension_stub.cpp b/frameworks/native/backup_ext/src/ext_extension_stub.cpp index 6930c2982442cc28ec4a863fde44fee1ac5d4be0..9e7b43539084af27b2601d54a57ab45be298fd74 100644 --- a/frameworks/native/backup_ext/src/ext_extension_stub.cpp +++ b/frameworks/native/backup_ext/src/ext_extension_stub.cpp @@ -51,6 +51,8 @@ ExtExtensionStub::ExtExtensionStub() &ExtExtensionStub::CmdIncrementalOnBackup; opToInterfaceMap_[static_cast(IExtensionInterfaceCode::CMD_UPDATE_FD_SENDRATE)] = &ExtExtensionStub::CmdUpdateFdSendRate; + opToInterfaceMap_[static_cast(IExtensionInterfaceCode::CMD_HANDLE_USER_0_BACKUP)] = + &ExtExtensionStub::CmdHandleUser0Backup; } int32_t ExtExtensionStub::OnRemoteRequest(uint32_t code, @@ -106,7 +108,9 @@ ErrCode ExtExtensionStub::CmdHandleClear(MessageParcel &data, MessageParcel &rep ErrCode ExtExtensionStub::CmdHandleBackup(MessageParcel &data, MessageParcel &reply) { - ErrCode res = HandleBackup(); + bool isClearData = true; + isClearData = data.ReadBool(); + ErrCode res = HandleBackup(isClearData); if (!reply.WriteInt32(res)) { stringstream ss; ss << "Failed to send the result " << res; @@ -133,7 +137,9 @@ ErrCode ExtExtensionStub::CmdPublishFile(MessageParcel &data, MessageParcel &rep ErrCode ExtExtensionStub::CmdHandleRestore(MessageParcel &data, MessageParcel &reply) { - ErrCode res = HandleRestore(); + bool isClearData = true; + isClearData = data.ReadBool(); + ErrCode res = HandleRestore(isClearData); if (!reply.WriteInt32(res)) { stringstream ss; ss << "Failed to send the result " << res; @@ -187,7 +193,9 @@ ErrCode ExtExtensionStub::CmdHandleIncrementalBackup(MessageParcel &data, Messag ErrCode ExtExtensionStub::CmdIncrementalOnBackup(MessageParcel &data, MessageParcel &reply) { - ErrCode res = IncrementalOnBackup(); + bool isClearData = true; + isClearData = data.ReadBool(); + ErrCode res = IncrementalOnBackup(isClearData); if (!reply.WriteInt32(res)) { stringstream ss; ss << "Failed to send the result " << res; @@ -239,4 +247,14 @@ ErrCode ExtExtensionStub::CmdUpdateFdSendRate(MessageParcel &data, MessageParcel } return BError(BError::Codes::OK); } + +ErrCode ExtExtensionStub::CmdHandleUser0Backup(MessageParcel &data, MessageParcel &reply) +{ + HILOGD("CmdHandleUser0Backup Begin"); + int ret = User0OnBackup(); + if (!reply.WriteInt32(ret)) { + return BError(BError::Codes::EXT_BROKEN_IPC, "Failed to send out the ret").GetCode(); + } + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/frameworks/native/backup_ext/src/sub_ext_extension.cpp b/frameworks/native/backup_ext/src/sub_ext_extension.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f2edcb26220324dd8959bb9de15322f1b2591297 --- /dev/null +++ b/frameworks/native/backup_ext/src/sub_ext_extension.cpp @@ -0,0 +1,695 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ext_extension.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#include +#include + +#include "accesstoken_kit.h" +#include "bundle_mgr_client.h" +#include "errors.h" +#include "ipc_skeleton.h" + +#include "b_error/b_error.h" +#include "b_error/b_excep_utils.h" +#include "b_filesystem/b_dir.h" +#include "b_filesystem/b_file.h" +#include "b_filesystem/b_file_hash.h" +#include "b_json/b_json_cached_entity.h" +#include "b_jsonutil/b_jsonutil.h" +#include "b_ohos/startup/backup_para.h" +#include "b_radar/b_radar.h" +#include "b_tarball/b_tarball_factory.h" +#include "filemgmt_libhilog.h" +#include "hitrace_meter.h" +#include "i_service.h" +#include "sandbox_helper.h" +#include "service_proxy.h" +#include "tar_file.h" +#include "b_anony/b_anony.h" + +namespace OHOS::FileManagement::Backup { +const uint32_t MAX_FD_GROUP_USE_TIME = 1000; // 每组打开最大时间1000ms + +void BackupExtExtension::WaitToSendFd(std::chrono::system_clock::time_point &startTime, int &fdSendNum) +{ + HILOGD("WaitToSendFd Begin"); + std::unique_lock lock(startSendMutex_); + startSendFdRateCon_.wait(lock, [this] { return sendRate_ > 0; }); + if (fdSendNum >= sendRate_) { + HILOGI("current time fd num is max rate, bundle name:%{public}s, rate:%{public}d", bundleName_.c_str(), + sendRate_); + auto curTime = std::chrono::system_clock::now(); + auto useTimeMs = std::chrono::duration_cast(curTime - startTime).count(); + if (useTimeMs < MAX_FD_GROUP_USE_TIME) { + int32_t sleepTime = MAX_FD_GROUP_USE_TIME - useTimeMs; + HILOGI("will wait time:%{public}d ms", sleepTime); + std::this_thread::sleep_for(std::chrono::milliseconds(sleepTime)); + } else { + HILOGW("current fd send num exceeds one second"); + } + fdSendNum = 0; + startTime = std::chrono::system_clock::now(); + } + HILOGD("WaitToSendFd End"); +} + +void BackupExtExtension::RefreshTimeInfo(std::chrono::system_clock::time_point &startTime, int &fdSendNum) +{ + auto currentTime = std::chrono::system_clock::now(); + auto useTime = std::chrono::duration_cast(currentTime - startTime).count(); + if (useTime >= MAX_FD_GROUP_USE_TIME) { + HILOGI("RefreshTimeInfo Begin, fdSendNum is:%{public}d", fdSendNum); + startTime = std::chrono::system_clock::now(); + fdSendNum = 0; + } +} + +void BackupExtExtension::SetClearDataFlag(bool isClearData) +{ + isClearData_ = isClearData; + HILOGI("set clear data flag:%{public}d", isClearData); + if (extension_ == nullptr) { + HILOGE("Extension handle have been released"); + return; + } + if (!extension_->WasFromSpecialVersion() && !extension_->RestoreDataReady()) { + DoClear(); + } +} + +void BackupExtExtension::AppIncrementalDone(ErrCode errCode) +{ + HILOGI("Begin"); + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + HILOGE("Failed to obtain the ServiceProxy handle"); + DoClear(); + return; + } + auto ret = proxy->AppIncrementalDone(errCode); + if (ret != ERR_OK) { + HILOGE("Failed to notify the app done. err = %{public}d", ret); + } +} + +ErrCode BackupExtExtension::GetBackupInfo(std::string &result) +{ + auto obj = wptr(this); + auto ptr = obj.promote(); + if (ptr == nullptr) { + HILOGE("Failed to get ext extension."); + return BError(BError::Codes::EXT_INVAL_ARG, "extension getBackupInfo exception").GetCode(); + } + if (ptr->extension_ == nullptr) { + HILOGE("Failed to get extension."); + return BError(BError::Codes::EXT_INVAL_ARG, "extension getBackupInfo exception").GetCode(); + } + auto callBackup = [ptr](ErrCode errCode, const std::string result) { + if (ptr == nullptr) { + HILOGE("Failed to get ext extension."); + return; + } + HILOGI("GetBackupInfo callBackup start. errCode = %{public}d, result = %{public}s", errCode, result.c_str()); + if (errCode == ERR_OK) { + ptr->backupInfo_ = result; + } + }; + auto ret = ptr->extension_->GetBackupInfo(callBackup); + if (ret != ERR_OK) { + HILOGE("Failed to get backupInfo. err = %{public}d", ret); + return BError(BError::Codes::EXT_INVAL_ARG, "extension getBackupInfo exception").GetCode(); + } + HILOGD("backupInfo = %s", backupInfo_.c_str()); + result = backupInfo_; + backupInfo_.clear(); + + return ERR_OK; +} + +ErrCode BackupExtExtension::UpdateFdSendRate(std::string &bundleName, int32_t sendRate) +{ + try { + std::lock_guard lock(updateSendRateLock_); + HILOGI("Update SendRate, bundleName:%{public}s, sendRate:%{public}d", bundleName.c_str(), sendRate); + VerifyCaller(); + bundleName_ = bundleName; + sendRate_ = sendRate; + if (sendRate > 0) { + startSendFdRateCon_.notify_one(); + } + return ERR_OK; + } catch (...) { + HILOGE("Failed to UpdateFdSendRate"); + return BError(BError::Codes::EXT_BROKEN_IPC).GetCode(); + } +} + +std::function BackupExtExtension::OnRestoreCallback(wptr obj) +{ + HILOGI("Begin get full restore onRestore callback"); + return [obj](ErrCode errCode, std::string errMsg) { + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + HILOGI("Current bundle will execute app done"); + if (errCode == ERR_OK) { + auto spendTime = extensionPtr->GetOnStartTimeCost(); + std::stringstream ss; + ss << "\"spend_time\": \"" << spendTime << "ms\""; + AppRadar::Info info (extensionPtr->bundleName_, "", ss.str()); + AppRadar::GetInstance().RecordRestoreFuncRes(info, "BackupExtExtension::OnRestoreCallback", + AppRadar::GetInstance().GetUserId(), BizStageRestore::BIZ_STAGE_ON_RESTORE, ERR_OK); + } + extensionPtr->FinishOnProcessTask(); + if (errMsg.empty()) { + extensionPtr->AppDone(errCode); + } else { + std::string errInfo; + BJsonUtil::BuildExtensionErrInfo(errInfo, errCode, errMsg); + extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::FULL_RESTORE, errCode); + } + extensionPtr->DoClear(); + }; +} + +std::function BackupExtExtension::OnRestoreExCallback(wptr obj) +{ + HILOGI("Begin get full restore onRestoreEx callback"); + return [obj](ErrCode errCode, const std::string restoreRetInfo) { + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + if (extensionPtr->extension_ == nullptr) { + HILOGE("Extension handle have been released"); + return; + } + if (errCode == ERR_OK && !restoreRetInfo.empty()) { + auto spendTime = extensionPtr->GetOnStartTimeCost(); + std::stringstream ss; + ss << "\"spend_time\": \"" << 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()) { + HILOGI("Will notify restore result report"); + extensionPtr->AppResultReport(restoreRetInfo, BackupRestoreScenario::FULL_RESTORE); + } + return; + } + if (restoreRetInfo.empty()) { + extensionPtr->AppDone(errCode); + extensionPtr->DoClear(); + } else { + std::string errInfo; + BJsonUtil::BuildExtensionErrInfo(errInfo, errCode, restoreRetInfo); + extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::FULL_RESTORE, errCode); + extensionPtr->DoClear(); + } + }; +} + +std::function BackupExtExtension::AppDoneCallbackEx(wptr obj) +{ + HILOGI("Begin get callback for appDone"); + return [obj](ErrCode errCode, std::string errMsg) { + HILOGI("begin call callBackupExAppDone"); + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + extensionPtr->AppDone(errCode); + extensionPtr->DoClear(); + }; +} + +std::function BackupExtExtension::IncreOnRestoreExCallback(wptr obj) +{ + HILOGI("Begin get callback for increment onRestoreEx"); + return [obj](ErrCode errCode, const std::string restoreRetInfo) { + HILOGI("begin call increment restoreEx"); + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + if (extensionPtr->extension_ == nullptr) { + HILOGE("Extension handle have been released"); + return; + } + if (errCode == ERR_OK && !restoreRetInfo.empty()) { + auto spendTime = extensionPtr->GetOnStartTimeCost(); + std::stringstream ss; + ss << "\"spend_time\": \"" << 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()) { + extensionPtr->AppResultReport(restoreRetInfo, BackupRestoreScenario::INCREMENTAL_RESTORE); + } + return; + } + if (restoreRetInfo.empty()) { + extensionPtr->AppIncrementalDone(errCode); + extensionPtr->DoClear(); + } else { + std::string errInfo; + BJsonUtil::BuildExtensionErrInfo(errInfo, errCode, restoreRetInfo); + extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::INCREMENTAL_RESTORE, errCode); + extensionPtr->DoClear(); + } + }; +} + +std::function BackupExtExtension::IncreOnRestoreCallback(wptr obj) +{ + return [obj](ErrCode errCode, std::string errMsg) { + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + HILOGI("Current bundle will execute app done"); + if (errCode == ERR_OK) { + auto spendTime = extensionPtr->GetOnStartTimeCost(); + std::stringstream ss; + ss << "\"spend_time\": \"" << spendTime << "ms\""; + AppRadar::Info info (extensionPtr->bundleName_, "", ss.str()); + AppRadar::GetInstance().RecordRestoreFuncRes(info, "BackupExtExtension::IncreOnRestoreCallback", + AppRadar::GetInstance().GetUserId(), BizStageRestore::BIZ_STAGE_ON_RESTORE, ERR_OK); + } + extensionPtr->FinishOnProcessTask(); + if (errMsg.empty()) { + extensionPtr->AppIncrementalDone(errCode); + } else { + std::string errInfo; + BJsonUtil::BuildExtensionErrInfo(errInfo, errCode, errMsg); + extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::INCREMENTAL_RESTORE, errCode); + } + extensionPtr->DoClear(); + }; +} + +int32_t BackupExtExtension::GetOnStartTimeCost() +{ + auto onBackupRestoreEnd = std::chrono::system_clock::now(); + std::lock_guard lock(onStartTimeLock_); + auto spendTime = std::chrono::duration_cast(onBackupRestoreEnd - g_onStart).count(); + return spendTime; +} + +std::function BackupExtExtension::OnBackupCallback(wptr obj) +{ + HILOGI("Begin get HandleFullBackupCallbackEx"); + return [obj](ErrCode errCode, std::string errMsg) { + HILOGI("begin call backup"); + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + if (extensionPtr->extension_ == nullptr) { + HILOGE("Extension handle have been released"); + return; + } + extensionPtr->FinishOnProcessTask(); + if (errCode == ERR_OK) { + auto spendTime = extensionPtr->GetOnStartTimeCost(); + AppRadar::Info info(extensionPtr->bundleName_, "", string("\"spend_time\":\" "). + append(to_string(spendTime)).append(string("ms\""))); + AppRadar::GetInstance().RecordBackupFuncRes(info, "BackupExtExtension::OnBackupCallback", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_ON_BACKUP, + static_cast(ERR_OK)); + extensionPtr->AsyncTaskBackup(extensionPtr->extension_->GetUsrConfig()); + return; + } + HILOGE("Call extension onBackup failed, errInfo = %{public}s", errMsg.c_str()); + if (!errMsg.empty()) { + std::string errInfo; + BJsonUtil::BuildExtensionErrInfo(errInfo, errCode, errMsg); + extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::FULL_BACKUP, errCode); + } + extensionPtr->AppDone(errCode); + extensionPtr->DoClear(); + }; +} + +std::function BackupExtExtension::OnBackupExCallback(wptr obj) +{ + HILOGI("Begin get HandleFullBackupCallbackEx"); + return [obj](ErrCode errCode, const std::string backupExRetInfo) { + HILOGI("begin call backup"); + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + if (extensionPtr->extension_ == nullptr) { + HILOGE("Extension handle have been released"); + return; + } + extensionPtr->extension_->InvokeAppExtMethod(errCode, backupExRetInfo); + if (errCode == ERR_OK) { + if (backupExRetInfo.size()) { + auto spendTime = extensionPtr->GetOnStartTimeCost(); + AppRadar::Info info(extensionPtr->bundleName_, "", string("\"spend_time\":\" "). + append(to_string(spendTime)).append(string("ms\""))); + AppRadar::GetInstance().RecordBackupFuncRes(info, "BackupExtExtension::OnBackupExCallback", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_ON_BACKUP, + static_cast(ERR_OK)); + HILOGI("Will notify backup result report"); + extensionPtr->FinishOnProcessTask(); + extensionPtr->AsyncTaskBackup(extensionPtr->extension_->GetUsrConfig()); + extensionPtr->AppResultReport(backupExRetInfo, BackupRestoreScenario::FULL_BACKUP); + } + return; + } + HILOGE("Call extension onBackupEx failed, errInfo = %{public}s", backupExRetInfo.c_str()); + extensionPtr->FinishOnProcessTask(); + if (!backupExRetInfo.empty()) { + std::string errInfo; + BJsonUtil::BuildExtensionErrInfo(errInfo, errCode, backupExRetInfo); + extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::FULL_BACKUP, errCode); + } + extensionPtr->AppDone(errCode); + extensionPtr->DoClear(); + }; +} + +std::function BackupExtExtension::IncOnBackupCallback(wptr obj) +{ + HILOGI("Begin get IncOnBackupCallback"); + return [obj](ErrCode errCode, std::string errMsg) { + HILOGI("App onbackup end"); + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); + } + auto extPtr = obj.promote(); + if (extPtr == nullptr) { + HILOGE("Current extension execute call backup error, extPtr is empty"); + return; + } + HILOGI("Start GetAppLocalListAndDoIncrementalBackup"); + extPtr->FinishOnProcessTask(); + if (errCode == ERR_OK) { + auto spendTime = extPtr->GetOnStartTimeCost(); + AppRadar::Info info(extPtr->bundleName_, "", string("\"spend_time\":\" "). + append(to_string(spendTime)).append(string("ms\""))); + AppRadar::GetInstance().RecordBackupFuncRes(info, "BackupExtExtension::IncOnBackupCallback", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_ON_BACKUP, + static_cast(ERR_OK)); + proxy->GetAppLocalListAndDoIncrementalBackup(); + return; + } + HILOGE("Call extension IncOnBackup failed, errInfo = %{public}s", errMsg.c_str()); + if (!errMsg.empty()) { + std::string errInfo; + BJsonUtil::BuildExtensionErrInfo(errInfo, errCode, errMsg); + extPtr->AppResultReport(errInfo, BackupRestoreScenario::INCREMENTAL_BACKUP, errCode); + } + extPtr->AppIncrementalDone(errCode); + extPtr->DoClear(); + }; +} + +std::function BackupExtExtension::IncOnBackupExCallback(wptr obj) +{ + HILOGI("Begin get HandleIncBackupEx callback"); + return [obj](ErrCode errCode, const std::string backupExRetInfo) { + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + throw BError(BError::Codes::EXT_BROKEN_BACKUP_SA, std::generic_category().message(errno)); + } + auto extensionPtr = obj.promote(); + if (extensionPtr == nullptr) { + HILOGE("Ext extension handle have been released"); + return; + } + if (extensionPtr->extension_ == nullptr) { + HILOGE("Extension handle have been released"); + return; + } + extensionPtr->extension_->InvokeAppExtMethod(errCode, backupExRetInfo); + if (errCode == ERR_OK) { + if (backupExRetInfo.size()) { + auto spendTime = extensionPtr->GetOnStartTimeCost(); + AppRadar::Info info(extensionPtr->bundleName_, "", string("\"spend_time\":\" "). + append(to_string(spendTime)).append(string("ms\""))); + AppRadar::GetInstance().RecordBackupFuncRes(info, "BackupExtExtension::IncOnBackupExCallback", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_ON_BACKUP, + static_cast(ERR_OK)); + HILOGI("Start GetAppLocalListAndDoIncrementalBackup"); + extensionPtr->FinishOnProcessTask(); + proxy->GetAppLocalListAndDoIncrementalBackup(); + HILOGI("Will notify backup result report"); + extensionPtr->AppResultReport(backupExRetInfo, BackupRestoreScenario::INCREMENTAL_BACKUP); + } + return; + } + HILOGE("Call extension IncOnBackupEx failed, errInfo = %{public}s", backupExRetInfo.c_str()); + extensionPtr->FinishOnProcessTask(); + if (!backupExRetInfo.empty()) { + std::string errInfo; + BJsonUtil::BuildExtensionErrInfo(errInfo, errCode, backupExRetInfo); + extensionPtr->AppResultReport(errInfo, BackupRestoreScenario::INCREMENTAL_BACKUP, errCode); + } + extensionPtr->AppIncrementalDone(errCode); + extensionPtr->DoClear(); + }; +} + +void BackupExtExtension::ReportAppProcessInfo(const std::string processInfo, BackupRestoreScenario scenario) +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + HILOGE("Report app process error, proxy is empty"); + return; + } + auto ret = proxy->ReportAppProcessInfo(processInfo, scenario); + if (ret != ERR_OK) { + HILOGE("Report app process error, ipc failed, ret:%{public}d", ret); + return; + } +} + +void BackupExtExtension::StartOnProcessTaskThread(wptr obj, BackupRestoreScenario scenario) +{ + HILOGI("Begin Create onProcess Task Thread"); + onProcessTimeoutTimer_.Setup(); + StartOnProcessTimeOutTimer(obj, scenario); + SyncCallJsOnProcessTask(obj, scenario); + callJsOnProcessThread_ = std::thread([obj, scenario]() { + auto extPtr = obj.promote(); + if (extPtr == nullptr) { + HILOGE("Create onProcess Task thread failed, extPtr is empty"); + return; + } + extPtr->ExecCallOnProcessTask(obj, scenario); + }); + HILOGI("End Create onProcess Task End"); +} + +void BackupExtExtension::ExecCallOnProcessTask(wptr obj, BackupRestoreScenario scenario) +{ + HILOGI("Begin"); + while (!stopCallJsOnProcess_.load()) { + std::unique_lock lock(onProcessLock_); + execOnProcessCon_.wait_for(lock, std::chrono::seconds(BConstants::CALL_APP_ON_PROCESS_TIME_INTERVAL), + [this] { return this->stopCallJsOnProcess_.load(); }); + if (stopCallJsOnProcess_.load()) { + HILOGE("Current extension execute js onProcess method finished"); + return; + } + HILOGI("Continue call js method onProcess"); + AsyncCallJsOnProcessTask(obj, scenario); + StartOnProcessTimeOutTimer(obj, scenario); + } + HILOGI("End"); +} + +void BackupExtExtension::AsyncCallJsOnProcessTask(wptr obj, BackupRestoreScenario scenario) +{ + HILOGI("Begin"); + if (stopCallJsOnProcess_.load()) { + HILOGE("Current extension execute finished"); + return; + } + auto task = [obj, scenario]() { + auto extPtr = obj.promote(); + if (extPtr == nullptr) { + HILOGE("Async Call js onProcess error, extPtr is empty"); + return; + } + extPtr->SyncCallJsOnProcessTask(obj, scenario); + }; + onProcessTaskPool_.AddTask([task]() { task(); }); + HILOGI("End"); +} + +void BackupExtExtension::SyncCallJsOnProcessTask(wptr obj, BackupRestoreScenario scenario) +{ + HILOGI("Begin"); + if (stopCallJsOnProcess_.load()) { + HILOGE("Current extension execute finished"); + return; + } + auto callBack = [obj, scenario](ErrCode errCode, const std::string processInfo) { + auto extPtr = obj.promote(); + if (extPtr == nullptr) { + HILOGE("Async call js onPreocess callback failed, exPtr is empty"); + return; + } + extPtr->CloseOnProcessTimeOutTimer(); + extPtr->onProcessTimeout_.store(false); + if (extPtr->onProcessTimeoutCnt_.load() > 0) { + extPtr->onProcessTimeoutCnt_ = 0; + HILOGI("onProcess execute success, reset onProcessTimeoutCnt"); + } + if (processInfo.size() == 0) { + HILOGE("Current extension has no js method named onProcess."); + std::unique_lock lock(extPtr->onProcessLock_); + extPtr->stopCallJsOnProcess_.store(true); + extPtr->execOnProcessCon_.notify_one(); + lock.unlock(); + return; + } + std::string processInfoJsonStr; + BJsonUtil::BuildOnProcessRetInfo(processInfoJsonStr, processInfo); + HILOGI("Will notify backup sa process result"); + extPtr->ReportAppProcessInfo(processInfoJsonStr, scenario); + }; + auto extenionPtr = obj.promote(); + if (extenionPtr == nullptr) { + HILOGE("Async call js onProcess failed, extenionPtr is empty"); + return; + } + ErrCode ret = extenionPtr->extension_->OnProcess(callBack); + if (ret != ERR_OK) { + HILOGE("Call OnProcess Failed, ret:%{public}d", ret); + return; + } + HILOGI("End"); +} + +void BackupExtExtension::FinishOnProcessTask() +{ + HILOGI("Begin"); + std::unique_lock lock(onProcessLock_); + stopCallJsOnProcess_.store(true); + onProcessTimeoutCnt_ = 0; + execOnProcessCon_.notify_one(); + lock.unlock(); + if (callJsOnProcessThread_.joinable()) { + callJsOnProcessThread_.join(); + } + HILOGI("End"); +} + +void BackupExtExtension::StartOnProcessTimeOutTimer(wptr obj, BackupRestoreScenario scenario) +{ + HILOGI("Begin"); + if (stopCallJsOnProcess_.load()) { + HILOGE("Current extension execute finished"); + return; + } + auto timeoutCallback = [obj, scenario]() { + auto extPtr = obj.promote(); + if (extPtr == nullptr) { + HILOGE("Start Create timeout callback failed, extPtr is empty"); + return; + } + if (extPtr->onProcessTimeoutCnt_.load() >= BConstants::APP_ON_PROCESS_TIMEOUT_MAX_COUNT) { + HILOGE("Current extension onProcess timeout more than three times"); + std::unique_lock lock(extPtr->onProcessLock_); + extPtr->stopCallJsOnProcess_.store(true); + extPtr->onProcessTimeoutCnt_ = 0; + extPtr->execOnProcessCon_.notify_one(); + lock.unlock(); + if (scenario == BackupRestoreScenario::FULL_BACKUP || scenario == BackupRestoreScenario::FULL_RESTORE) { + extPtr->AppDone(BError(BError::Codes::EXT_ABILITY_TIMEOUT)); + } else if (scenario == BackupRestoreScenario::INCREMENTAL_BACKUP || + scenario == BackupRestoreScenario::INCREMENTAL_RESTORE) { + extPtr->AppIncrementalDone(BError(BError::Codes::EXT_ABILITY_TIMEOUT)); + } + return; + } + extPtr->onProcessTimeoutCnt_++; + extPtr->onProcessTimeout_.store(true); + HILOGE("Extension onProcess timeout, Increase cnt:%{public}d", extPtr->onProcessTimeoutCnt_.load()); + }; + uint32_t timerId = onProcessTimeoutTimer_.Register(timeoutCallback, BConstants::APP_ON_PROCESS_MAX_TIMEOUT, true); + onProcessTimeoutTimerId_ = timerId; + HILOGI("End"); +} + +void BackupExtExtension::CloseOnProcessTimeOutTimer() +{ + HILOGI("Begin"); + onProcessTimeoutTimer_.Unregister(onProcessTimeoutTimerId_); + HILOGI("End"); +} + +bool BackupExtExtension::SetStagingPathProperties() +{ + struct stat curBundleStat {}; + if (lstat(BConstants::BUNDLE_BASE_DIR.c_str(), &curBundleStat) != 0) { + HILOGE("Failed to lstat, err = %{public}d", errno); + return false; + } + if (lchown(string(BConstants::PATH_BUNDLE_BACKUP_HOME).c_str(), + curBundleStat.st_uid, curBundleStat.st_gid) != 0) { + HILOGE("Failed to lchown, err = %{public}d", errno); + return false; + } + if (lchown(string(BConstants::PATH_BUNDLE_BACKUP_HOME_EL1).c_str(), + curBundleStat.st_uid, curBundleStat.st_gid) != 0) { + HILOGE("Failed to lchown, err = %{public}d", errno); + return false; + } + return true; +} +} // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_kit_inner/include/service_reverse.h b/frameworks/native/backup_kit_inner/include/service_reverse.h index 178bac3c98f7ec62ea4522414b87db51a16def82..3ecb58eaba5dd9964310ca15013e99b5ab85b291 100644 --- a/frameworks/native/backup_kit_inner/include/service_reverse.h +++ b/frameworks/native/backup_kit_inner/include/service_reverse.h @@ -30,6 +30,7 @@ public: void BackupOnResultReport(std::string result, std::string bundleName) override; void BackupOnBundleFinished(int32_t errCode, std::string bundleName) override; void BackupOnAllBundlesFinished(int32_t errCode) override; + void BackupOnProcessInfo(std::string bundleName, std::string processInfo) override; void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) override; @@ -37,6 +38,7 @@ public: void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int32_t errCode) override; void RestoreOnResultReport(std::string result, std::string bundleName, ErrCode errCode = 0) override; + void RestoreOnProcessInfo(std::string bundleName, std::string processInfo) override; void IncrementalBackupOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd, int32_t errCode) override; @@ -44,6 +46,7 @@ public: void IncrementalBackupOnResultReport(std::string result, std::string bundleName) override; void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) override; void IncrementalBackupOnAllBundlesFinished(int32_t errCode) override; + void IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) override; void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) override; @@ -52,6 +55,7 @@ public: int32_t errCode) override; void IncrementalRestoreOnResultReport(std::string result, std::string bundleName, ErrCode errCode = 0) override; + void IncrementalRestoreOnProcessInfo(std::string bundleName, std::string processInfo) override; public: ServiceReverse() = delete; diff --git a/frameworks/native/backup_kit_inner/include/service_reverse_stub.h b/frameworks/native/backup_kit_inner/include/service_reverse_stub.h index 879eccf1bca385f72eeae8a53ca1174671b5ab9b..0384c01307b7dc005646472fa9105d499dab1525 100644 --- a/frameworks/native/backup_kit_inner/include/service_reverse_stub.h +++ b/frameworks/native/backup_kit_inner/include/service_reverse_stub.h @@ -39,24 +39,29 @@ private: int32_t CmdBackupOnResultReport(MessageParcel &data, MessageParcel &reply); int32_t CmdBackupOnBundleFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdBackupOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); + int32_t CmdBackupOnProcessInfo(MessageParcel &data, MessageParcel &reply); int32_t CmdRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply); int32_t CmdRestoreOnBundleFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdRestoreOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdRestoreOnFileReady(MessageParcel &data, MessageParcel &reply); int32_t CmdRestoreOnResultReport(MessageParcel &data, MessageParcel &reply); + int32_t CmdRestoreOnProcessInfo(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalBackupOnFileReady(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalBackupOnBundleStarted(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalBackupOnResultReport(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalBackupOnBundleFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalBackupOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); + int32_t CmdIncrementalBackupOnProcessInfo(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalRestoreOnBundleFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalRestoreOnAllBundlesFinished(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalRestoreOnFileReady(MessageParcel &data, MessageParcel &reply); int32_t CmdIncrementalRestoreOnResultReport(MessageParcel &data, MessageParcel &reply); + int32_t CmdIncrementalRestoreOnProcessInfo(MessageParcel &data, MessageParcel &reply); + void ServiceReverseStubSupplement(); }; } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp index f747d28c7662c0b22edf870320e7253fee023ee2..cfaaf5ef5b51eba86f25e3e869a1a578992bcdf8 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_backup_session.cpp @@ -16,6 +16,7 @@ #include "b_incremental_backup_session.h" #include "b_error/b_error.h" +#include "b_radar/b_radar.h" #include "filemgmt_libhilog.h" #include "service_proxy.h" #include "service_reverse.h" @@ -29,7 +30,7 @@ BIncrementalBackupSession::~BIncrementalBackupSession() HILOGI("Death Recipient is nullptr"); return; } - auto proxy = ServiceProxy::GetInstance(); + auto proxy = ServiceProxy::GetServiceProxyPointer(); if (proxy == nullptr) { return; } @@ -55,6 +56,9 @@ unique_ptr BIncrementalBackupSession::Init(Callbacks int32_t res = proxy->InitIncrementalBackupSession(sptr(new ServiceReverse(callbacks))); if (res != 0) { HILOGE("Failed to Backup because of %{public}d", res); + AppRadar::Info info("", "", ""); + AppRadar::GetInstance().RecordBackupFuncRes(info, "BIncrementalBackupSession::Init", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_CREATE_BACKUP_SESSION_FAIL, res); return nullptr; } @@ -93,7 +97,17 @@ ErrCode BIncrementalBackupSession::AppendBundles(vector bundle return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } - return proxy->AppendBundlesIncrementalBackupSession(bundlesToBackup); + int32_t res = proxy->AppendBundlesIncrementalBackupSession(bundlesToBackup); + if (res != 0) { + std::string ss; + for (const auto &bundle : bundlesToBackup) { + ss += bundle.bundleName + ", "; + } + AppRadar::Info info(ss.c_str(), "", ""); + AppRadar::GetInstance().RecordBackupFuncRes(info, "BIncrementalBackupSession::AppendBundles", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_APPEND_BUNDLES_FAIL, res); + } + return res; } ErrCode BIncrementalBackupSession::AppendBundles(vector bundlesToBackup, @@ -104,7 +118,17 @@ ErrCode BIncrementalBackupSession::AppendBundles(vector bundle return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } - return proxy->AppendBundlesIncrementalBackupSession(bundlesToBackup, infos); + int32_t res = proxy->AppendBundlesIncrementalBackupSession(bundlesToBackup, infos); + if (res != 0) { + std::string ss; + for (const auto &bundle : bundlesToBackup) { + ss += bundle.bundleName + ", "; + } + AppRadar::Info info(ss.c_str(), "", "AppendBundles with infos"); + AppRadar::GetInstance().RecordBackupFuncRes(info, "BIncrementalBackupSession::AppendBundles", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_APPEND_BUNDLES_FAIL, res); + } + return res; } ErrCode BIncrementalBackupSession::Release() diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp index 000241ad00fa33ddcf07acdfb1e09ba657c34a52..ed51e8cb9d9f36ff35ab1fa049558da2ae8f5bf2 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_restore_session.cpp @@ -16,6 +16,7 @@ #include "b_incremental_restore_session.h" #include "b_error/b_error.h" +#include "b_radar/b_radar.h" #include "filemgmt_libhilog.h" #include "service_proxy.h" #include "service_reverse.h" @@ -29,7 +30,7 @@ BIncrementalRestoreSession::~BIncrementalRestoreSession() HILOGI("Death Recipient is nullptr"); return; } - auto proxy = ServiceProxy::GetInstance(); + auto proxy = ServiceProxy::GetServiceProxyPointer(); if (proxy == nullptr) { return; } @@ -54,6 +55,10 @@ unique_ptr BIncrementalRestoreSession::Init(Callback int32_t res = proxy->InitRestoreSession(sptr(new ServiceReverse(callbacks))); if (res != 0) { HILOGE("Failed to Restore because of %{public}d", res); + AppRadar::Info info ("", "", "create restore session failed"); + AppRadar::GetInstance().RecordRestoreFuncRes(info, "BIncrementalRestoreSession::Init", + AppRadar::GetInstance().GetUserId(), + BizStageRestore::BIZ_STAGE_CREATE_RESTORE_SESSION_FAIL, res); return nullptr; } diff --git a/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp b/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp index 84f75d66efc567dbca2fd01b5de3c13ab20f57d3..75c7e3cbcd54dada7b498c614fd72659b24428a6 100644 --- a/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp +++ b/frameworks/native/backup_kit_inner/src/b_incremental_session_restore_async.cpp @@ -16,6 +16,7 @@ #include "b_incremental_session_restore_async.h" #include "b_error/b_error.h" +#include "b_radar/b_radar.h" #include "b_resources/b_constants.h" #include "filemgmt_libhilog.h" #include "service_proxy.h" @@ -30,7 +31,7 @@ BIncrementalSessionRestoreAsync::~BIncrementalSessionRestoreAsync() HILOGE("Death Recipient is nullptr"); return; } - auto proxy = ServiceProxy::GetInstance(); + auto proxy = ServiceProxy::GetServiceProxyPointer(); if (proxy == nullptr) { return; } @@ -62,6 +63,10 @@ shared_ptr BIncrementalSessionRestoreAsync::Ini int32_t res = proxy->InitRestoreSession(sptr(new ServiceReverse(callbacksTmp))); if (res != 0) { HILOGE("Failed to Restore because of %{public}d", res); + AppRadar::Info info ("", "", "create restore session failed"); + AppRadar::GetInstance().RecordRestoreFuncRes(info, "BIncrementalSessionRestoreAsync::Init", + AppRadar::GetInstance().GetUserId(), + BizStageRestore::BIZ_STAGE_CREATE_RESTORE_SESSION_FAIL, res); return nullptr; } diff --git a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp index 04176686bd8da61518fe2d153cc41f938d62503d..f20285515766b6ea0c189b588ec5dd5d75b19864 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp @@ -16,6 +16,7 @@ #include "b_session_backup.h" #include "b_error/b_error.h" +#include "b_radar/b_radar.h" #include "filemgmt_libhilog.h" #include "service_proxy.h" #include "service_reverse.h" @@ -29,7 +30,7 @@ BSessionBackup::~BSessionBackup() HILOGI("Death Recipient is nullptr"); return; } - auto proxy = ServiceProxy::GetInstance(); + auto proxy = ServiceProxy::GetServiceProxyPointer(); if (proxy == nullptr) { return; } @@ -55,6 +56,9 @@ unique_ptr BSessionBackup::Init(Callbacks callbacks) int32_t res = proxy->InitBackupSession(sptr(new ServiceReverse(callbacks))); if (res != 0) { HILOGE("Failed to Backup because of %{public}d", res); + AppRadar::Info info("", "", ""); + AppRadar::GetInstance().RecordBackupFuncRes(info, "BSessionBackup::Init", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_CREATE_BACKUP_SESSION_FAIL, res); return nullptr; } @@ -103,7 +107,17 @@ ErrCode BSessionBackup::AppendBundles(vector bundlesToBackup) return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } - return proxy->AppendBundlesBackupSession(bundlesToBackup); + int32_t res = proxy->AppendBundlesBackupSession(bundlesToBackup); + if (res != 0) { + std::string ss; + for (const auto &bundleName:bundlesToBackup) { + ss += bundleName + ", "; + } + AppRadar::Info info(ss.c_str(), "", ""); + AppRadar::GetInstance().RecordBackupFuncRes(info, "BSessionBackup::AppendBundles", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_APPEND_BUNDLES_FAIL, res); + } + return res; } ErrCode BSessionBackup::AppendBundles(vector bundlesToBackup, vector detailInfos) @@ -113,7 +127,17 @@ ErrCode BSessionBackup::AppendBundles(vector bundlesToBackup, vector return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } - return proxy->AppendBundlesDetailsBackupSession(bundlesToBackup, detailInfos); + int32_t res = proxy->AppendBundlesDetailsBackupSession(bundlesToBackup, detailInfos); + if (res != 0) { + std::string ss; + for (const auto &bundleName:bundlesToBackup) { + ss += bundleName + ", "; + } + AppRadar::Info info(ss.c_str(), "", ""); + AppRadar::GetInstance().RecordBackupFuncRes(info, "BSessionBackup::AppendBundles", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_APPEND_BUNDLES_FAIL, res); + } + return res; } ErrCode BSessionBackup::Finish() diff --git a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp index 250d68bc7f24b8124536264115c5d79964f7599a..0c37d260361e7e01f255690eb351f1004cc42362 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp @@ -16,6 +16,7 @@ #include "b_session_restore.h" #include "b_error/b_error.h" +#include "b_radar/b_radar.h" #include "filemgmt_libhilog.h" #include "service_proxy.h" #include "service_reverse.h" @@ -29,7 +30,7 @@ BSessionRestore::~BSessionRestore() HILOGI("Death Recipient is nullptr"); return; } - auto proxy = ServiceProxy::GetInstance(); + auto proxy = ServiceProxy::GetServiceProxyPointer(); if (proxy == nullptr) { return; } @@ -54,6 +55,10 @@ unique_ptr BSessionRestore::Init(Callbacks callbacks) int32_t res = proxy->InitRestoreSession(new ServiceReverse(callbacks)); if (res != 0) { HILOGE("Failed to Restore because of %{public}d", res); + AppRadar::Info info ("", "", "create restore session failed"); + AppRadar::GetInstance().RecordRestoreFuncRes(info, "BSessionRestore::Init", + AppRadar::GetInstance().GetUserId(), + BizStageRestore::BIZ_STAGE_CREATE_RESTORE_SESSION_FAIL, res); return nullptr; } diff --git a/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp b/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp index 10c388fb58b468f1ea7bf402fa39527ec0d55a50..b3cea05e1fd1a036aa43eb8d86d6e5ec39c08ba7 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore_async.cpp @@ -16,6 +16,7 @@ #include "b_session_restore_async.h" #include "b_error/b_error.h" +#include "b_radar/b_radar.h" #include "b_resources/b_constants.h" #include "b_session_restore.h" #include "filemgmt_libhilog.h" @@ -31,7 +32,7 @@ BSessionRestoreAsync::~BSessionRestoreAsync() HILOGI("Death Recipient is nullptr"); return; } - auto proxy = ServiceProxy::GetInstance(); + auto proxy = ServiceProxy::GetServiceProxyPointer(); if (proxy == nullptr) { return; } @@ -58,10 +59,15 @@ shared_ptr BSessionRestoreAsync::Init(Callbacks callbacks) .onBundleFinished = callbacks.onBundleFinished, .onAllBundlesFinished = callbacks.onAllBundlesFinished, .onResultReport = callbacks.onResultReport, - .onBackupServiceDied = callbacks.onBackupServiceDied}; + .onBackupServiceDied = callbacks.onBackupServiceDied, + .onProcess = callbacks.onProcess}; int32_t res = proxy->InitRestoreSession(sptr(new ServiceReverse(callbacksTmp))); if (res != 0) { HILOGE("Failed to Restore because of %{public}d", res); + AppRadar::Info info ("", "", "create restore session failed"); + AppRadar::GetInstance().RecordRestoreFuncRes(info, "BSessionRestoreAsync::Init", + AppRadar::GetInstance().GetUserId(), + BizStageRestore::BIZ_STAGE_CREATE_RESTORE_SESSION_FAIL, res); return nullptr; } diff --git a/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp b/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp index 8c5f4c465643f249622016915befb57b4069b5c0..ec842c43283f26fb25cf3bac5788038aeb5efb5e 100644 --- a/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp +++ b/frameworks/native/backup_kit_inner/src/service_incremental_reverse.cpp @@ -70,6 +70,16 @@ void ServiceReverse::IncrementalBackupOnAllBundlesFinished(int32_t errCode) callbacksIncrementalBackup_.onAllBundlesFinished(errCode); } +void ServiceReverse::IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) +{ + HILOGI("bundleName = %{public}s", bundleName.c_str()); + if (scenario_ != Scenario::BACKUP || !callbacksIncrementalBackup_.onProcess) { + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); + return; + } + callbacksIncrementalBackup_.onProcess(bundleName, processInfo); +} + void ServiceReverse::IncrementalRestoreOnBundleStarted(int32_t errCode, string bundleName) { if (scenario_ != Scenario::RESTORE || !callbacksIncrementalRestore_.onBundleStarted) { @@ -125,6 +135,16 @@ void ServiceReverse::IncrementalRestoreOnResultReport(std::string result, std::s callbacksIncrementalRestore_.onBundleFinished(errCode, bundleName); } +void ServiceReverse::IncrementalRestoreOnProcessInfo(std::string bundleName, std::string processInfo) +{ + HILOGI("begin incremental report processInfo, bundleName:%{public}s", bundleName.c_str()); + if (scenario_ != Scenario::RESTORE || !callbacksIncrementalRestore_.onProcess) { + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); + return; + } + callbacksIncrementalRestore_.onProcess(bundleName, processInfo); +} + ServiceReverse::ServiceReverse(BIncrementalBackupSession::Callbacks callbacks) : scenario_(Scenario::BACKUP), callbacksIncrementalBackup_(callbacks) { diff --git a/frameworks/native/backup_kit_inner/src/service_proxy.cpp b/frameworks/native/backup_kit_inner/src/service_proxy.cpp index 1d004e4f16e346181588c601b4cbfce81328748d..27b30aaaeed46d3024baf6a9ef765015b90d86e3 100644 --- a/frameworks/native/backup_kit_inner/src/service_proxy.cpp +++ b/frameworks/native/backup_kit_inner/src/service_proxy.cpp @@ -13,15 +13,16 @@ * limitations under the License. */ -#include "service_proxy.h" - -#include "iservice_registry.h" -#include "system_ability_definition.h" +#include #include "b_error/b_error.h" #include "b_error/b_excep_utils.h" +#include "b_radar/b_radar.h" #include "b_resources/b_constants.h" #include "filemgmt_libhilog.h" +#include "iservice_registry.h" +#include "service_proxy.h" +#include "system_ability_definition.h" #include "svc_death_recipient.h" #include "hitrace_meter.h" @@ -119,6 +120,9 @@ UniqueFd ServiceProxy::GetLocalCapabilities() static_cast(IServiceInterfaceCode::SERVICE_CMD_GET_LOCAL_CAPABILITIES), data, reply, option); if (ret != NO_ERROR) { HILOGE("Received error %{public}d when doing IPC", ret); + AppRadar::Info resInfo("", "", ""); + AppRadar::GetInstance().RecordDefaultFuncRes(resInfo, "ServiceProxy::GetLocalCapabilities", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_GET_LOCAL_CAPABILITIES_FAIL, ret); return UniqueFd(-ret); } UniqueFd fd(reply.ReadFileDescriptor()); @@ -297,6 +301,13 @@ ErrCode ServiceProxy::AppendBundlesRestoreSession(UniqueFd fd, const vector(IServiceInterfaceCode::SERVICE_CMD_APPEND_BUNDLES_RESTORE_SESSION), data, reply, option); if (ret != NO_ERROR) { string str = "Failed to send out the request because of " + to_string(ret); + std::string ss; + for (const auto &bundleName : bundleNames) { + ss += bundleName + ", "; + } + AppRadar::Info info(ss.c_str(), "", str); + AppRadar::GetInstance().RecordRestoreFuncRes(info, "ServiceProxy::AppendBundlesRestoreSession", userId, + BizStageRestore::BIZ_STAGE_APPEND_BUNDLES_FAIL, ret); return BError(BError::Codes::SDK_INVAL_ARG, str.data()).GetCode(); } return reply.ReadInt32(); @@ -415,6 +433,12 @@ ErrCode ServiceProxy::Finish() return reply.ReadInt32(); } +sptr ServiceProxy::GetServiceProxyPointer() +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + return serviceProxy_; +} + sptr ServiceProxy::GetInstance() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); @@ -446,6 +470,10 @@ sptr ServiceProxy::GetInstance() [loadCallback]() { return loadCallback->isLoadSuccess_.load(); }); if (!waitStatus) { HILOGE("Load backup sa timeout"); + AppRadar::Info info("", "", "\"reason\":\"Load backup sa timeout\""); + AppRadar::GetInstance().RecordBackupFuncRes(info, "ServiceProxy::GetInstance", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_BOOT_BACKUP_SA_FAIL, + static_cast(BError::Codes::SA_INVAL_ARG)); return nullptr; } return serviceProxy_; @@ -502,6 +530,10 @@ void ServiceProxy::ServiceProxyLoadCallback::OnLoadSystemAbilityFail(int32_t sys unique_lock lock(proxyMutex_); serviceProxy_ = nullptr; isLoadSuccess_.store(false); + AppRadar::Info info("", "", "\"reason\":\"Load backup sa fail\""); + AppRadar::GetInstance().RecordBackupFuncRes(info, "ServiceProxyLoadCallback::OnLoadSystemAbilityFail", + AppRadar::GetInstance().GetUserId(), BizStageBackup::BIZ_STAGE_BOOT_BACKUP_SA_FAIL, + static_cast(BError::Codes::SA_INVAL_ARG)); proxyConVar_.notify_one(); } @@ -530,7 +562,7 @@ ErrCode ServiceProxy::GetBackupInfo(BundleName &bundleName, std::string &result) return BError(BError::Codes::OK, "success"); } -ErrCode ServiceProxy::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) +ErrCode ServiceProxy::UpdateTimer(BundleName &bundleName, uint32_t timeout, bool &result) { HILOGI("ServiceProxy UpdateTimer Begin."); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); @@ -541,8 +573,8 @@ ErrCode ServiceProxy::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool if (!data.WriteString(bundleName)) { return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send bundleName").GetCode(); } - if (!data.WriteUint32(timeOut)) { - return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send timeOut").GetCode(); + if (!data.WriteUint32(timeout)) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send timeout").GetCode(); } MessageParcel reply; MessageOption option; @@ -585,4 +617,75 @@ ErrCode ServiceProxy::UpdateSendRate(std::string &bundleName, int32_t sendRate, HILOGI("ServiceProxy UpdateSendRate end. ret = %{public}d", ret); return BError(BError::Codes::OK, "success"); } + +ErrCode ServiceProxy::ReportAppProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario) +{ + HILOGD("ServiceProxy NotifyBundleProcessInfo Begin."); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to write descriptor").GetCode(); + } + if (!data.WriteString(processInfo)) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send bundleName").GetCode(); + } + if (!data.WriteInt32(static_cast(sennario))) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the scenario").GetCode(); + } + MessageParcel reply; + MessageOption option; + option.SetWaitTime(BConstants::IPC_MAX_WAIT_TIME); + int32_t ret = Remote()-> SendRequest(static_cast( + IServiceInterfaceCode::SERVICE_CMD_REPORT_APP_PROCESS_INFO), data, reply, option); + if (ret != NO_ERROR) { + string str = "Failed to send out the request because of " + to_string(ret); + return BError(BError::Codes::SDK_INVAL_ARG, str.data()).GetCode(); + } + HILOGI("ServiceProxy NotifyBundleProcessInfo end. ret = %{public}d", ret); + return BError(BError::Codes::OK, "success"); +} + +ErrCode ServiceProxy::StartExtTimer(bool &isExtStart) +{ + HILOGI("ServiceProxy StartExtTimer Begin."); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to write descriptor").GetCode(); + } + MessageParcel reply; + MessageOption option; + option.SetWaitTime(BConstants::IPC_MAX_WAIT_TIME); + int32_t ret = Remote()->SendRequest(static_cast(IServiceInterfaceCode::SERVICE_CMD_START_EXT_TIMER), + data, reply, option); + if (ret != NO_ERROR) { + string str = "Failed to send out the request because of " + to_string(ret); + return BError(BError::Codes::SDK_INVAL_ARG, str.data()).GetCode(); + } + reply.ReadBool(isExtStart); + HILOGI("ServiceProxy StartExtTimer end. isExtStart = %d", isExtStart); + return BError(BError::Codes::OK, "success"); +} + +ErrCode ServiceProxy::StartFwkTimer(bool &isFwkStart) +{ + HILOGI("ServiceProxy StartFwkTimer Begin."); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor())) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to write descriptor").GetCode(); + } + MessageParcel reply; + MessageOption option; + option.SetWaitTime(BConstants::IPC_MAX_WAIT_TIME); + int32_t ret = Remote()->SendRequest(static_cast(IServiceInterfaceCode::SERVICE_CMD_START_FWK_TIMER), + data, reply, option); + if (ret != NO_ERROR) { + string str = "Failed to send out the request because of " + to_string(ret); + return BError(BError::Codes::SDK_INVAL_ARG, str.data()).GetCode(); + } + reply.ReadBool(isFwkStart); + HILOGI("ServiceProxy StartFwkTimer end. isFwkStart = %d", isFwkStart); + return BError(BError::Codes::OK, "success"); +} } // namespace OHOS::FileManagement::Backup diff --git a/frameworks/native/backup_kit_inner/src/service_reverse.cpp b/frameworks/native/backup_kit_inner/src/service_reverse.cpp index f2e2eb71622403472dda9ca56f61e0fc4af33a40..6328cb70ea63730224ee61a943a8dba13482ed20 100644 --- a/frameworks/native/backup_kit_inner/src/service_reverse.cpp +++ b/frameworks/native/backup_kit_inner/src/service_reverse.cpp @@ -24,7 +24,7 @@ using namespace std; void ServiceReverse::BackupOnFileReady(string bundleName, string fileName, int fd, int32_t errCode) { if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onFileReady) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } BFileInfo bFileInfo(bundleName, fileName, 0); @@ -34,7 +34,7 @@ void ServiceReverse::BackupOnFileReady(string bundleName, string fileName, int f void ServiceReverse::BackupOnBundleStarted(int32_t errCode, string bundleName) { if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onBundleStarted) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } callbacksBackup_.onBundleStarted(errCode, bundleName); @@ -43,7 +43,7 @@ void ServiceReverse::BackupOnBundleStarted(int32_t errCode, string bundleName) void ServiceReverse::BackupOnResultReport(std::string result, std::string bundleName) { if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onResultReport) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } callbacksBackup_.onResultReport(bundleName, result); @@ -52,7 +52,7 @@ void ServiceReverse::BackupOnResultReport(std::string result, std::string bundle void ServiceReverse::BackupOnBundleFinished(int32_t errCode, string bundleName) { if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onBundleFinished) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } HILOGI("errCode = %{public}d, bundleName = %{public}s", errCode, bundleName.c_str()); @@ -63,16 +63,26 @@ void ServiceReverse::BackupOnAllBundlesFinished(int32_t errCode) { HILOGI("errCode = %{public}d", errCode); if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onAllBundlesFinished) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } callbacksBackup_.onAllBundlesFinished(errCode); } +void ServiceReverse::BackupOnProcessInfo(std::string bundleName, std::string processInfo) +{ + HILOGI("bundleName = %{public}s", bundleName.c_str()); + if (scenario_ != Scenario::BACKUP || !callbacksBackup_.onProcess) { + HILOGI("Error scenario or callback is nullptr"); + return; + } + callbacksBackup_.onProcess(bundleName, processInfo); +} + void ServiceReverse::RestoreOnBundleStarted(int32_t errCode, string bundleName) { if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onBundleStarted) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } callbacksRestore_.onBundleStarted(errCode, bundleName); @@ -81,7 +91,7 @@ void ServiceReverse::RestoreOnBundleStarted(int32_t errCode, string bundleName) void ServiceReverse::RestoreOnBundleFinished(int32_t errCode, string bundleName) { if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onBundleFinished) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } HILOGI("errCode = %{public}d, bundleName = %{public}s", errCode, bundleName.c_str()); @@ -92,7 +102,7 @@ void ServiceReverse::RestoreOnAllBundlesFinished(int32_t errCode) { HILOGI("errCode = %{public}d", errCode); if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onAllBundlesFinished) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } callbacksRestore_.onAllBundlesFinished(errCode); @@ -102,7 +112,7 @@ void ServiceReverse::RestoreOnFileReady(string bundleName, string fileName, int { HILOGD("begin, bundleName is:%{public}s", bundleName.c_str()); if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onFileReady) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } BFileInfo bFileInfo(bundleName, fileName, 0); @@ -114,17 +124,27 @@ void ServiceReverse::RestoreOnResultReport(string result, std::string bundleName HILOGI("ServiceReverse RestoreOnResultReport bundle %{public}s begin with result: %{public}s", bundleName.c_str(), result.c_str()); if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onResultReport) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } callbacksRestore_.onResultReport(bundleName, result); if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onBundleFinished) { - HILOGI("Error scenario or callback is nullptr"); + HILOGE("Error scenario or callback is nullptr, scenario = %{public}d", scenario_); return; } callbacksRestore_.onBundleFinished(errCode, bundleName); } +void ServiceReverse::RestoreOnProcessInfo(std::string bundleName, std::string processInfo) +{ + HILOGI("bundleName = %{public}s", bundleName.c_str()); + if (scenario_ != Scenario::RESTORE || !callbacksRestore_.onProcess) { + HILOGI("Error scenario or callback is nullptr"); + return; + } + callbacksRestore_.onProcess(bundleName, processInfo); +} + ServiceReverse::ServiceReverse(BSessionBackup::Callbacks callbacks) : scenario_(Scenario::BACKUP), callbacksBackup_(callbacks) { diff --git a/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp b/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp index 0fdeed6c8687a7a16ccd7f6c96914dc55fb6a1d9..8f970cab4fa55ba8f94401d47d6efc36a92f2a52 100644 --- a/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp +++ b/frameworks/native/backup_kit_inner/src/service_reverse_stub.cpp @@ -43,6 +43,26 @@ int32_t ServiceReverseStub::OnRemoteRequest(uint32_t code, } return (this->*(interfaceIndex->second))(data, reply); } +void ServiceReverseStub::ServiceReverseStubSupplement() +{ + opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_FILE_READY)] = + &ServiceReverseStub::CmdIncrementalRestoreOnFileReady; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_STARTED)] = + &ServiceReverseStub::CmdIncrementalRestoreOnBundleStarted; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_RESULT_REPORT)] = + &ServiceReverseStub::CmdIncrementalRestoreOnResultReport; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_FINISHED)] = + &ServiceReverseStub::CmdIncrementalRestoreOnBundleFinished; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_TASK_FINISHED)] = + &ServiceReverseStub::CmdIncrementalRestoreOnAllBundlesFinished; + opToInterfaceMap_[static_cast( + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_PROCESS_INFO)] = + &ServiceReverseStub::CmdIncrementalRestoreOnProcessInfo; +} ServiceReverseStub::ServiceReverseStub() { @@ -56,6 +76,8 @@ ServiceReverseStub::ServiceReverseStub() &ServiceReverseStub::CmdBackupOnBundleFinished; opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_BACKUP_ON_TASK_FINISHED)] = &ServiceReverseStub::CmdBackupOnAllBundlesFinished; + opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_BACKUP_ON_PROCESS_INFO)] = + &ServiceReverseStub::CmdBackupOnProcessInfo; opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_RESTORE_ON_FILE_READY)] = &ServiceReverseStub::CmdRestoreOnFileReady; @@ -67,6 +89,8 @@ ServiceReverseStub::ServiceReverseStub() &ServiceReverseStub::CmdRestoreOnBundleFinished; opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_RESTORE_ON_TASK_FINISHED)] = &ServiceReverseStub::CmdRestoreOnAllBundlesFinished; + opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_RESTORE_ON_PROCESS_INFO)] = + &ServiceReverseStub::CmdRestoreOnProcessInfo; opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_FILE_READY)] = &ServiceReverseStub::CmdIncrementalBackupOnFileReady; @@ -81,21 +105,10 @@ ServiceReverseStub::ServiceReverseStub() opToInterfaceMap_[static_cast( IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_TASK_FINISHED)] = &ServiceReverseStub::CmdIncrementalBackupOnAllBundlesFinished; - - opToInterfaceMap_[static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_FILE_READY)] = - &ServiceReverseStub::CmdIncrementalRestoreOnFileReady; - opToInterfaceMap_[static_cast( - IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_STARTED)] = - &ServiceReverseStub::CmdIncrementalRestoreOnBundleStarted; - opToInterfaceMap_[static_cast( - IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_RESULT_REPORT)] = - &ServiceReverseStub::CmdIncrementalRestoreOnResultReport; opToInterfaceMap_[static_cast( - IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_FINISHED)] = - &ServiceReverseStub::CmdIncrementalRestoreOnBundleFinished; - opToInterfaceMap_[static_cast( - IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_TASK_FINISHED)] = - &ServiceReverseStub::CmdIncrementalRestoreOnAllBundlesFinished; + IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_PROCESS_INFO)] = + &ServiceReverseStub::CmdIncrementalBackupOnProcessInfo; + ServiceReverseStubSupplement(); } int32_t ServiceReverseStub::CmdBackupOnFileReady(MessageParcel &data, MessageParcel &reply) @@ -143,6 +156,14 @@ int32_t ServiceReverseStub::CmdBackupOnAllBundlesFinished(MessageParcel &data, M return BError(BError::Codes::OK); } +int32_t ServiceReverseStub::CmdBackupOnProcessInfo(MessageParcel &data, MessageParcel &reply) +{ + std::string bundleName = data.ReadString(); + std::string processInfo = data.ReadString(); + BackupOnProcessInfo(bundleName, processInfo); + return BError(BError::Codes::OK); +} + int32_t ServiceReverseStub::CmdRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply) { int32_t errCode = data.ReadInt32(); @@ -198,6 +219,14 @@ int32_t ServiceReverseStub::CmdRestoreOnResultReport(MessageParcel &data, Messag return BError(BError::Codes::OK); } +int32_t ServiceReverseStub::CmdRestoreOnProcessInfo(MessageParcel &data, MessageParcel &reply) +{ + std::string bundleName = data.ReadString(); + std::string processInfo = data.ReadString(); + RestoreOnProcessInfo(bundleName, processInfo); + return BError(BError::Codes::OK); +} + int32_t ServiceReverseStub::CmdIncrementalBackupOnFileReady(MessageParcel &data, MessageParcel &reply) { auto bundleName = data.ReadString(); @@ -245,6 +274,14 @@ int32_t ServiceReverseStub::CmdIncrementalBackupOnAllBundlesFinished(MessageParc return BError(BError::Codes::OK); } +int32_t ServiceReverseStub::CmdIncrementalBackupOnProcessInfo(MessageParcel &data, MessageParcel &reply) +{ + std::string bundleName = data.ReadString(); + std::string processInfo = data.ReadString(); + IncrementalBackupOnProcessInfo(bundleName, processInfo); + return BError(BError::Codes::OK); +} + int32_t ServiceReverseStub::CmdIncrementalRestoreOnBundleStarted(MessageParcel &data, MessageParcel &reply) { int32_t errCode = data.ReadInt32(); @@ -292,4 +329,12 @@ int32_t ServiceReverseStub::CmdIncrementalRestoreOnResultReport(MessageParcel &d IncrementalRestoreOnResultReport(result, bundleName, errCode); return BError(BError::Codes::OK); } + +int32_t ServiceReverseStub::CmdIncrementalRestoreOnProcessInfo(MessageParcel &data, MessageParcel &reply) +{ + auto bundleName = data.ReadString(); + auto processInfo = data.ReadString(); + IncrementalRestoreOnProcessInfo(bundleName, processInfo); + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/interfaces/api/js/napi/backup_ext/backup_extension_ability.js b/interfaces/api/js/napi/backup_ext/backup_extension_ability.js index b1801058f4390d545007974492a97ac627a44b1c..acc2b49713e371ac7acf78511ccd8e7dd4396204 100644 --- a/interfaces/api/js/napi/backup_ext/backup_extension_ability.js +++ b/interfaces/api/js/napi/backup_ext/backup_extension_ability.js @@ -29,6 +29,10 @@ class BackupExtensionAbility { onRestoreEx(versionBackupedBundle, restoreInfo) { console.log(); } + + onProcess() { + console.log(); + } } export default BackupExtensionAbility \ No newline at end of file diff --git a/interfaces/inner_api/native/backup_kit_inner/BUILD.gn b/interfaces/inner_api/native/backup_kit_inner/BUILD.gn index c84d227f23979db6436a0793c0b705f4ce0d7a81..2ee1a876dd7b91829c20172f45856f18b82206e9 100644 --- a/interfaces/inner_api/native/backup_kit_inner/BUILD.gn +++ b/interfaces/inner_api/native/backup_kit_inner/BUILD.gn @@ -27,6 +27,7 @@ config("private_config") { "${path_backup}/frameworks/native/backup_kit_inner/include", "${path_backup}/interfaces/inner_api/native/backup_kit_inner", "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", + "${path_backup}/utils/include", ] } diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h index f37aa190e9b9fc802ee1d7d6f11db5d092e020dc..c7c40df0a3ea6bb0c478ab667a438a074c85c3ef 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_backup_session.h @@ -37,6 +37,7 @@ public: std::function onAllBundlesFinished; // 当整个备份流程结束或意外中止时执行的回调函数 std::function onResultReport; // 某个应用备份流程中自定义错误信息的上报的回调函数 std::function onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数 + std::function onProcess; // 上报备份恢复过程中的进度和异常 }; public: diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_restore_session.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_restore_session.h index 54b3a25b16ef5b18ca1a56511184024ebc2565b9..2a4d6c2ffedafb727268de3b2a4ddb03cbae8ab9 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_restore_session.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_incremental_restore_session.h @@ -37,6 +37,7 @@ public: std::function onAllBundlesFinished; // 当整个恢复流程结束或意外中止时执行的回调函数 std::function onResultReport; // 某个应用恢复流程中自定义错误信息的上报的回调函数 std::function onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数 + std::function onProcess; // 上报备份恢复过程中的进度和异常 }; public: diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h index 46a6e24b1be69d4be5433a7b94e012190ea4ae66..f08c340be0704f1ec09ab923c9d085fa1dedc527 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_backup.h @@ -35,6 +35,7 @@ public: std::function onAllBundlesFinished; // 当整个备份流程结束或意外中止时执行的回调函数 std::function onResultReport; // 某个应用备份流程中自定义错误信息的上报的回调函数 std::function onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数 + std::function onProcess; // 上报备份恢复过程中的进度和异常 }; public: diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore.h index 06e8332303fa170d02170f96cab0b6a78843015d..cdb72d3260090ecf549b68aded023a952bed12ef 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore.h @@ -35,6 +35,7 @@ public: std::function onAllBundlesFinished; // 当整个恢复流程结束或意外中止时执行的回调函数 std::function onResultReport; // 某个应用恢复流程中自定义错误信息的上报的回调函数 std::function onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数 + std::function onProcess; // 上报备份恢复过程中的进度和异常 }; public: diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore_async.h b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore_async.h index 4d4cdad10cbf52f889485deaddc81c1286fc35b2..482c6409e6b488d3f4c1e7539c5a36f9249a6f93 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore_async.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/b_session_restore_async.h @@ -39,6 +39,7 @@ public: std::function onAllBundlesFinished; // 当整个恢复流程结束或意外中止时执行的回调函数 std::function onResultReport; // 某个应用恢复流程中自定义错误信息的上报的回调函数 std::function onBackupServiceDied; // 当备份服务意外死亡时执行的回调函数 + std::function onProcess; // 上报备份恢复过程中的进度和异常 }; struct AppendBundleInfo { diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h index 364214d2d0c1b70b45b61062c23b6ba20b9358b5..a20fb4cdd8388441513338395e6db6281c5a4387 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension.h @@ -30,16 +30,17 @@ public: virtual ~IExtension() = default; virtual UniqueFd GetFileHandle(const std::string &fileName, int32_t &errCode) = 0; virtual ErrCode HandleClear() = 0; - virtual ErrCode HandleBackup() = 0; + virtual ErrCode HandleBackup(bool isClearData) = 0; virtual ErrCode PublishFile(const std::string &fileName) = 0; - virtual ErrCode HandleRestore() = 0; + virtual ErrCode HandleRestore(bool isClearData) = 0; virtual ErrCode GetIncrementalFileHandle(const std::string &fileName) = 0; virtual ErrCode PublishIncrementalFile(const std::string &fileName) = 0; virtual ErrCode HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) = 0; - virtual ErrCode IncrementalOnBackup() = 0; + virtual ErrCode IncrementalOnBackup(bool isClearData) = 0; virtual std::tuple GetIncrementalBackupFileHandle() = 0; virtual ErrCode GetBackupInfo(std::string &result) = 0; virtual ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) = 0; + virtual ErrCode User0OnBackup() = 0; }; } // namespace OHOS::FileManagement::Backup diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension_ipc_interface_code.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension_ipc_interface_code.h index 15478e015881ba14a66b3d7f0ef6999acd109665..40c2f120845951b4931cc39a33e58f5bae6afdef 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_extension_ipc_interface_code.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_extension_ipc_interface_code.h @@ -31,6 +31,7 @@ enum class IExtensionInterfaceCode { CMD_GET_BACKUP_INFO, CMD_INCREMENTAL_ON_BACKUP, CMD_UPDATE_FD_SENDRATE, + CMD_HANDLE_USER_0_BACKUP, }; } // namespace OHOS::FileManagement::Backup diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h index 49348fb58591984d27a328c01487941ac9d8e4ea..6dee18fc376fc35c1ec94c80b39bf7f4593fdf50 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service.h @@ -83,8 +83,11 @@ public: virtual ErrCode AppIncrementalDone(ErrCode errCode) = 0; virtual ErrCode GetIncrementalFileHandle(const std::string &bundleName, const std::string &fileName) = 0; virtual ErrCode GetBackupInfo(BundleName &bundleName, std::string &result) = 0; - virtual ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) = 0; + virtual ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeout, bool &result) = 0; virtual ErrCode UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) = 0; + virtual ErrCode ReportAppProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario) = 0; + virtual ErrCode StartExtTimer(bool &isExtStart) = 0; + virtual ErrCode StartFwkTimer(bool &isFwkStart) = 0; DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Backup.IService") }; diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h index 1de4b9c45934275547880b510fcdbaed86101a9b..2332a6b0973d977584f0cc541968f209cd6da135 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_ipc_interface_code.h @@ -45,8 +45,11 @@ enum class IServiceInterfaceCode { SERVICE_CMD_GET_INCREMENTAL_FILE_NAME, SERVICE_CMD_GET_BACKUP_INFO, SERVICE_CMD_UPDATE_TIMER, + SERVICE_CMD_START_EXT_TIMER, + SERVICE_CMD_START_FWK_TIMER, SERVICE_CMD_UPDATE_SENDRATE, SERVICE_CMD_GET_APP_LOCAL_LIST_AND_DO_INCREMENTAL_BACKUP, + SERVICE_CMD_REPORT_APP_PROCESS_INFO, }; } // namespace OHOS::FileManagement::Backup diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h index 8791c26b2514a21e8ed21978ba1046ac8364d2d1..52311dde514d0a45fab11942877f2722f8c9cb1c 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse.h @@ -28,6 +28,7 @@ public: UNDEFINED, BACKUP, RESTORE, + CLEAN, }; public: @@ -37,6 +38,7 @@ public: virtual void BackupOnResultReport(std::string result, std::string bundleName) = 0; virtual void BackupOnBundleFinished(int32_t errCode, std::string bundleName) = 0; virtual void BackupOnAllBundlesFinished(int32_t errCode) = 0; + virtual void BackupOnProcessInfo(std::string bundleName, std::string processInfo) = 0; virtual void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) = 0; virtual void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int32_t errCode) = 0; @@ -44,6 +46,7 @@ public: ErrCode errCode = 0) = 0; virtual void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) = 0; virtual void RestoreOnAllBundlesFinished(int32_t errCode) = 0; + virtual void RestoreOnProcessInfo(std::string bundleName, std::string processInfo) = 0; virtual void IncrementalBackupOnBundleStarted(int32_t errCode, std::string bundleName) = 0; virtual void IncrementalBackupOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd, @@ -51,6 +54,7 @@ public: virtual void IncrementalBackupOnResultReport(std::string result, std::string bundleName) = 0; virtual void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) = 0; virtual void IncrementalBackupOnAllBundlesFinished(int32_t errCode) = 0; + virtual void IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) = 0; virtual void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) = 0; virtual void IncrementalRestoreOnFileReady(std::string bundleName, @@ -61,6 +65,7 @@ public: ErrCode errCode = 0) = 0; virtual void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) = 0; virtual void IncrementalRestoreOnAllBundlesFinished(int32_t errCode) = 0; + virtual void IncrementalRestoreOnProcessInfo(const std::string bundleName, const std::string processInfo) = 0; DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.FileManagement.Backup.IServiceReverse") }; diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h index a41ec673f0ede4d5870070b3873176113e109b5a..5d991d6fbd88212b1989695ad6fe100a586f0441 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/i_service_reverse_ipc_interface_code.h @@ -24,21 +24,25 @@ enum class IServiceReverseInterfaceCode { SERVICER_BACKUP_ON_SUB_TASK_FINISHED, SERVICER_BACKUP_ON_TASK_FINISHED, SERVICER_BACKUP_ON_RESULT_REPORT, + SERVICER_BACKUP_ON_PROCESS_INFO, SERVICER_RESTORE_ON_SUB_TASK_STARTED, SERVICER_RESTORE_ON_SUB_TASK_FINISHED, SERVICER_RESTORE_ON_TASK_FINISHED, SERVICER_RESTORE_ON_FILE_READY, SERVICER_RESTORE_ON_RESULT_REPORT, + SERVICER_RESTORE_ON_PROCESS_INFO, SERVICER_INCREMENTAL_BACKUP_ON_FILE_READY, SERVICER_INCREMENTAL_BACKUP_ON_SUB_TASK_STARTED, SERVICER_INCREMENTAL_BACKUP_ON_SUB_TASK_FINISHED, SERVICER_INCREMENTAL_BACKUP_ON_TASK_FINISHED, SERVICER_INCREMENTAL_BACKUP_ON_RESULT_REPORT, + SERVICER_INCREMENTAL_BACKUP_ON_PROCESS_INFO, SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_STARTED, SERVICER_INCREMENTAL_RESTORE_ON_SUB_TASK_FINISHED, SERVICER_INCREMENTAL_RESTORE_ON_TASK_FINISHED, SERVICER_INCREMENTAL_RESTORE_ON_FILE_READY, SERVICER_INCREMENTAL_RESTORE_ON_RESULT_REPORT, + SERVICER_INCREMENTAL_RESTORE_ON_PROCESS_INFO, }; } // namespace OHOS::FileManagement::Backup diff --git a/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h b/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h index d0845087ee63d5148626174e238c488aafeb1f2b..21c676d85ffc5d35c95911bc877cc7bff311a926 100644 --- a/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h +++ b/interfaces/inner_api/native/backup_kit_inner/impl/service_proxy.h @@ -66,8 +66,11 @@ public: ErrCode AppIncrementalDone(ErrCode errCode) override; ErrCode GetIncrementalFileHandle(const std::string &bundleName, const std::string &fileName) override; ErrCode GetBackupInfo(BundleName &bundleName, std::string &result) override; - ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) override; + ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeout, bool &result) override; ErrCode UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) override; + ErrCode ReportAppProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario) override; + ErrCode StartExtTimer(bool &isExtStart) override; + ErrCode StartFwkTimer(bool &isFwkStart) override; public: explicit ServiceProxy(const sptr &impl) : IRemoteProxy(impl) {} @@ -76,6 +79,7 @@ public: public: template bool WriteParcelableVector(const std::vector &parcelableVector, Parcel &data); + static sptr GetServiceProxyPointer(); static sptr GetInstance(); static void InvaildInstance(); diff --git a/interfaces/kits/js/BUILD.gn b/interfaces/kits/js/BUILD.gn index 57417adbf2f489f51b28af8caba30d08bc64c6a3..1fe26f359d662f627c4611baa89f66420b3ee4d2 100644 --- a/interfaces/kits/js/BUILD.gn +++ b/interfaces/kits/js/BUILD.gn @@ -43,7 +43,6 @@ ohos_shared_library("fileshare") { "ability_base:want", "ability_base:zuri", "ability_runtime:abilitykit_native", - "ability_runtime:extensionkit_native", "ability_runtime:uri_permission_mgr", "access_token:libaccesstoken_sdk", "access_token:libtokenid_sdk", diff --git a/interfaces/kits/js/backup/general_callbacks.cpp b/interfaces/kits/js/backup/general_callbacks.cpp index 63170425fabd7de54062b103b31940121f2ea357..c7253d551f221c8bfec2f8884aced18868417afc 100644 --- a/interfaces/kits/js/backup/general_callbacks.cpp +++ b/interfaces/kits/js/backup/general_callbacks.cpp @@ -114,11 +114,7 @@ void BackupRestoreCallback::CallJsMethod(InputArgsParser argParser) HILOGE("failed to get uv event loop."); return; } - struct WorkArgs { - BackupRestoreCallback *ptr = nullptr; - InputArgsParser argParser; - }; - auto workArgs = make_unique(); + auto workArgs = make_shared(); auto work = make_unique(); if (workArgs == nullptr || work == nullptr) { HILOGE("failed to new workArgs or uv_work_t."); @@ -134,21 +130,25 @@ void BackupRestoreCallback::CallJsMethod(InputArgsParser argParser) auto workArgs = reinterpret_cast(work->data); do { if (workArgs == nullptr) { - HILOGE("failed to get CallJsParam."); + HILOGE("failed to get workArgs."); break; } DoCallJsMethod(workArgs->ptr->env_, workArgs->ptr->ctx_, workArgs->argParser); } while (false); - delete workArgs; + HILOGI("will notify current thread info"); + std::unique_lock lock(workArgs->callbackMutex); + workArgs->isReady.store(true); + workArgs->callbackCondition.notify_all(); delete work; }); if (ret != 0) { HILOGE("failed to exec uv_queue_work."); - workArgs.reset(); work.reset(); return; } - workArgs.release(); + std::unique_lock lock(workArgs->callbackMutex); + HILOGI("Wait execute callback method end"); + workArgs->callbackCondition.wait(lock, [workArgs]() { return workArgs->isReady.load(); }); work.release(); HILOGI("call BackupRestoreCallback CallJsMethod end."); } diff --git a/interfaces/kits/js/backup/general_callbacks.h b/interfaces/kits/js/backup/general_callbacks.h index 04956ac668675c339e731d5df5a1c92f88c68792..4fc20530f00b834dac7edaf6c68580f0a53213b9 100644 --- a/interfaces/kits/js/backup/general_callbacks.h +++ b/interfaces/kits/js/backup/general_callbacks.h @@ -35,6 +35,14 @@ private: LibN::NAsyncContextCallback *ctx_ = nullptr; }; +struct WorkArgs { + std::mutex callbackMutex; + std::condition_variable callbackCondition; + std::atomic isReady {false}; + BackupRestoreCallback *ptr = nullptr; + InputArgsParser argParser; +}; + class GeneralCallbacks { public: GeneralCallbacks(const napi_env &env, const LibN::NVal &thisPtr, const LibN::NVal &jsCallbacks) @@ -43,7 +51,8 @@ public: onBundleEnd(env, thisPtr, jsCallbacks.GetProp("onBundleEnd")), onAllBundlesEnd(env, thisPtr, jsCallbacks.GetProp("onAllBundlesEnd")), onBackupServiceDied(env, thisPtr, jsCallbacks.GetProp("onBackupServiceDied")), - onResultReport(env, thisPtr, jsCallbacks.GetProp("onResultReport")) {}; + onResultReport(env, thisPtr, jsCallbacks.GetProp("onResultReport")), + onProcess(env, thisPtr, jsCallbacks.GetProp("onProcess")) {}; public: LibN::NAsyncWorkCallback onFileReady; @@ -52,6 +61,7 @@ public: LibN::NAsyncWorkCallback onAllBundlesEnd; LibN::NAsyncWorkCallback onBackupServiceDied; BackupRestoreCallback onResultReport; + BackupRestoreCallback onProcess; }; } // namespace OHOS::FileManagement::Backup #endif // INTERFACES_KITS_JS_SRC_MOD_BACKUP_PROPERTIES_GENERAL_CALLBACKS_H \ No newline at end of file diff --git a/interfaces/kits/js/backup/prop_n_operation.cpp b/interfaces/kits/js/backup/prop_n_operation.cpp index d059dc95f201b774a0e0e800ce46a7ecca384723..80edd1a771ae3a57210318537f1c5dc8169e198a 100644 --- a/interfaces/kits/js/backup/prop_n_operation.cpp +++ b/interfaces/kits/js/backup/prop_n_operation.cpp @@ -17,6 +17,7 @@ #include "b_error/b_error.h" #include "b_incremental_data.h" #include "b_resources/b_constants.h" +#include "b_sa/b_sa_utils.h" #include "filemgmt_libhilog.h" #include "filemgmt_libn.h" #include "incremental_backup_data.h" @@ -30,21 +31,6 @@ namespace OHOS::FileManagement::Backup { using namespace std; using namespace LibN; -const int32_t H_TO_MS = 3600 * 1000; - -static bool CheckPermission(const string &permission) -{ - Security::AccessToken::AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); - return Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission) == - Security::AccessToken::PermissionState::PERMISSION_GRANTED; -} - -static bool IsSystemApp() -{ - uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID(); - return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId); -} - static napi_value AsyncCallback(napi_env env, const NFuncArg& funcArg) { HILOGD("called LocalCapabilities::AsyncCallback begin"); @@ -182,6 +168,16 @@ static napi_value AsyncDataList(napi_env env, const NFuncArg& funcArg) napi_value PropNOperation::Async(napi_env env, napi_callback_info info) { HILOGD("called LocalCapabilities::Async begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, info); if (!funcArg.InitArgs(NARG_CNT::ZERO, NARG_CNT::ONE)) { HILOGE("Number of arguments unmatched."); @@ -203,6 +199,16 @@ napi_value PropNOperation::Async(napi_env env, napi_callback_info info) napi_value PropNOperation::DoGetBackupInfo(napi_env env, napi_callback_info info) { HILOGD("called DoGetBackupInfo begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } std::string result; NFuncArg funcArg(env, info); if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { @@ -241,7 +247,7 @@ napi_value PropNOperation::DoGetBackupInfo(napi_env env, napi_callback_info info return nResult; } -bool PropNOperation::UpdateTimer(std::string &bundleName, uint32_t timeOut) +bool PropNOperation::UpdateTimer(std::string &bundleName, uint32_t timeout) { bool result = false; ServiceProxy::InvaildInstance(); @@ -250,7 +256,7 @@ bool PropNOperation::UpdateTimer(std::string &bundleName, uint32_t timeOut) HILOGE("called DoUpdateTimer,failed to get proxy"); return result; } - ErrCode errcode = proxy->UpdateTimer(bundleName, timeOut, result); + ErrCode errcode = proxy->UpdateTimer(bundleName, timeout, result); if (errcode != 0) { HILOGE("proxy->UpdateTimer faild."); return result; @@ -278,12 +284,12 @@ bool PropNOperation::UpdateSendRate(std::string &bundleName, int32_t sendRate) napi_value PropNOperation::DoUpdateTimer(napi_env env, napi_callback_info info) { HILOGD("called DoUpdateTimer begin"); - if (!CheckPermission("ohos.permission.BACKUP")) { - HILOGE("has not permission!"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); NError(E_PERMISSION).ThrowErr(env); return nullptr; } - if (!IsSystemApp()) { + if (!SAUtils::IsSystemApp()) { HILOGE("System App check fail!"); NError(E_PERMISSION_SYS).ThrowErr(env); return nullptr; @@ -303,15 +309,15 @@ napi_value PropNOperation::DoUpdateTimer(napi_env env, napi_callback_info info) } NVal jsBundleInt(env, funcArg[NARG_POS::SECOND]); auto [succInt, time] = jsBundleInt.ToInt32(); - if (!succInt || time <= 0 || time > H_TO_MS) { + if (!succInt || time <= 0 || time > static_cast(BConstants::MAX_UPDATE_TIMER)) { HILOGE("Second argument is not number."); NError(E_PARAMS).ThrowErr(env); return nullptr; } std::string bundleName = bundle.get(); - uint32_t timeOut = static_cast(time); - bool result = UpdateTimer(bundleName, timeOut); + uint32_t timeout = static_cast(time); + bool result = UpdateTimer(bundleName, timeout); napi_value nResult; napi_status status = napi_get_boolean(env, result, &nResult); @@ -326,12 +332,12 @@ napi_value PropNOperation::DoUpdateTimer(napi_env env, napi_callback_info info) napi_value PropNOperation::DoUpdateSendRate(napi_env env, napi_callback_info info) { HILOGD("called DoUpdateSendRate begin"); - if (!CheckPermission("ohos.permission.BACKUP")) { - HILOGE("has not permission!"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); NError(E_PERMISSION).ThrowErr(env); return nullptr; } - if (!IsSystemApp()) { + if (!SAUtils::IsSystemApp()) { HILOGE("System App check fail!"); NError(E_PERMISSION_SYS).ThrowErr(env); return nullptr; diff --git a/interfaces/kits/js/backup/prop_n_operation.h b/interfaces/kits/js/backup/prop_n_operation.h index b6d746f00db10c7db72408c4ea83f3bbffcf0fed..7137d8d14d7ac98fc9586306a4e0781752d61b04 100644 --- a/interfaces/kits/js/backup/prop_n_operation.h +++ b/interfaces/kits/js/backup/prop_n_operation.h @@ -26,7 +26,7 @@ public: static napi_value DoUpdateTimer(napi_env env, napi_callback_info info); static napi_value DoUpdateSendRate(napi_env env, napi_callback_info info); private: - static bool UpdateTimer(std::string &bundleName, uint32_t timeOut); + static bool UpdateTimer(std::string &bundleName, uint32_t timeout); static bool UpdateSendRate(std::string &bundleName, int32_t sendRate); }; diff --git a/interfaces/kits/js/backup/session_backup_n_exporter.cpp b/interfaces/kits/js/backup/session_backup_n_exporter.cpp index 0d84c030833a28891d5f0c1de5ca0ccd484ecd7f..7976c8fdb85e6088bd6982b6f1fe569039a57577 100644 --- a/interfaces/kits/js/backup/session_backup_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_backup_n_exporter.cpp @@ -68,13 +68,20 @@ static void OnFileReady(weak_ptr pCallbacks, const BFileInfo & }; if (std::get<0>(errInfo) != 0) { obj = NVal {env, NError(errorParam).GetNapiErr(env)}; + napi_status status = napi_set_named_property(env, obj.val_, FILEIO_TAG_ERR_DATA.c_str(), + NVal::CreateUTF8String(env, bundleName).val_); + if (status != napi_ok) { + HILOGE("Failed to set data property, status %{public}d, bundleName %{public}s", + status, bundleName.c_str()); + } } else { obj = NVal::CreateObject(env); + obj.AddProp({ + NVal::DeclareNapiProperty(BConstants::BUNDLE_NAME.c_str(), + NVal::CreateUTF8String(env, bundleName).val_), + NVal::DeclareNapiProperty(BConstants::URI.c_str(), NVal::CreateUTF8String(env, fileName).val_), + NVal::DeclareNapiProperty(BConstants::FD.c_str(), NVal::CreateInt32(env, fd->Release()).val_)}); } - obj.AddProp({ - NVal::DeclareNapiProperty(BConstants::BUNDLE_NAME.c_str(), NVal::CreateUTF8String(env, bundleName).val_), - NVal::DeclareNapiProperty(BConstants::URI.c_str(), NVal::CreateUTF8String(env, fileName).val_), - NVal::DeclareNapiProperty(BConstants::FD.c_str(), NVal::CreateInt32(env, fd->Release()).val_)}); return {obj}; }; @@ -83,7 +90,7 @@ static void OnFileReady(weak_ptr pCallbacks, const BFileInfo & static void onBundleBegin(weak_ptr pCallbacks, ErrCode err, const BundleName name) { - HILOGI("Callback onBundleBegin, bundleName=%{public}s", name.c_str()); + HILOGI("Callback onBundleBegin, bundleName=%{public}s, errCode=%{public}d", name.c_str(), err); if (pCallbacks.expired()) { HILOGI("callbacks is unbound"); return; @@ -98,17 +105,23 @@ static void onBundleBegin(weak_ptr pCallbacks, ErrCode err, co return; } - auto cbCompl = [name {name}, errCode {err}](napi_env env, NError err) -> NVal { + ErrCode errCode = BError::GetBackupCodeByErrno(err); + std::string errMsg = BError::GetBackupMsgByErrno(errCode) + ", origin errno: " + to_string(err); + std::tuple errInfo = std::make_tuple(errCode, errMsg); + + auto cbCompl = [name {name}, errCode {err}, errInfo](napi_env env, NError err) -> NVal { NVal bundleName = NVal::CreateUTF8String(env, name); if (!err && errCode == 0) { return bundleName; } - + ErrParam errorParam = [ errInfo ]() { + return errInfo; + }; NVal res; if (err) { res = NVal {env, err.GetNapiErr(env)}; } else { - res = NVal {env, NError(errCode).GetNapiErr(env)}; + res = NVal {env, NError(errorParam).GetNapiErr(env)}; } napi_status status = napi_set_named_property(env, res.val_, FILEIO_TAG_ERR_DATA.c_str(), bundleName.val_); if (status != napi_ok) { @@ -123,7 +136,7 @@ static void onBundleBegin(weak_ptr pCallbacks, ErrCode err, co static void onBundleEnd(weak_ptr pCallbacks, ErrCode err, const BundleName name) { - HILOGI("Callback onBundleEnd, bundleName=%{public}s", name.c_str()); + HILOGI("Callback onBundleEnd, bundleName=%{public}s, errCode=%{public}d", name.c_str(), err); if (pCallbacks.expired()) { HILOGI("callbacks is unbound"); return; @@ -138,17 +151,23 @@ static void onBundleEnd(weak_ptr pCallbacks, ErrCode err, cons return; } - auto cbCompl = [name {name}, errCode {err}](napi_env env, NError err) -> NVal { + ErrCode errCode = BError::GetBackupCodeByErrno(err); + std::string errMsg = BError::GetBackupMsgByErrno(errCode) + ", origin errno: " + to_string(err); + std::tuple errInfo = std::make_tuple(errCode, errMsg); + + auto cbCompl = [name {name}, errCode {err}, errInfo](napi_env env, NError err) -> NVal { NVal bundleName = NVal::CreateUTF8String(env, name); if (!err && errCode == 0) { return bundleName; } - + ErrParam errorParam = [ errInfo ]() { + return errInfo; + }; NVal res; if (err) { res = NVal {env, err.GetNapiErr(env)}; } else { - res = NVal {env, NError(errCode).GetNapiErr(env)}; + res = NVal {env, NError(errorParam).GetNapiErr(env)}; } napi_status status = napi_set_named_property(env, res.val_, FILEIO_TAG_ERR_DATA.c_str(), bundleName.val_); if (status != napi_ok) { @@ -177,16 +196,22 @@ static void onAllBundlesEnd(weak_ptr pCallbacks, ErrCode err) return; } - auto cbCompl = [errCode {err}](napi_env env, NError err) -> NVal { + ErrCode errCode = BError::GetBackupCodeByErrno(err); + std::string errMsg = BError::GetBackupMsgByErrno(errCode) + ", origin errno: " + to_string(err); + std::tuple errInfo = std::make_tuple(errCode, errMsg); + + auto cbCompl = [errCode {err}, errInfo](napi_env env, NError err) -> NVal { if (!err && errCode == 0) { return NVal::CreateUndefined(env); } - + ErrParam errorParam = [ errInfo ]() { + return errInfo; + }; NVal res; if (err) { res = NVal {env, err.GetNapiErr(env)}; } else { - res = NVal {env, NError(errCode).GetNapiErr(env)}; + res = NVal {env, NError(errorParam).GetNapiErr(env)}; } return res; @@ -248,9 +273,47 @@ static void OnBackupServiceDied(weak_ptr pCallbacks) callbacks->onBackupServiceDied.ThreadSafeSchedule(cbCompl); } +static void OnProcess(weak_ptr pCallbacks, const BundleName name, const std::string processInfo) +{ + HILOGI("Callback OnProcess, bundleName=%{public}s", name.c_str()); + if (pCallbacks.expired()) { + HILOGI("callbacks is unbound"); + return; + } + auto callbacks = pCallbacks.lock(); + if (!callbacks) { + HILOGI("callback function OnProcess has already been released"); + return; + } + if (!bool(callbacks->onProcess)) { + HILOGI("callback function OnProcess is undefined"); + return; + } + auto cbCompl = [bundleName {name}, process {processInfo}](napi_env env, vector &argv) -> bool { + napi_value napi_bName = nullptr; + napi_create_string_utf8(env, bundleName.c_str(), bundleName.size(), &napi_bName); + argv.push_back(napi_bName); + napi_value napi_process = nullptr; + napi_create_string_utf8(env, process.c_str(), process.size(), &napi_process); + argv.push_back(napi_process); + return true; + }; + callbacks->onProcess.CallJsMethod(cbCompl); +} + napi_value SessionBackupNExporter::Constructor(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionBackup::Constructor begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ONE)) { HILOGE("Number of arguments unmatched."); @@ -274,7 +337,8 @@ napi_value SessionBackupNExporter::Constructor(napi_env env, napi_callback_info .onBundleFinished = bind(onBundleEnd, backupEntity->callbacks, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(onAllBundlesEnd, backupEntity->callbacks, placeholders::_1), .onResultReport = bind(OnResultReport, backupEntity->callbacks, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, backupEntity->callbacks)}); + .onBackupServiceDied = bind(OnBackupServiceDied, backupEntity->callbacks), + .onProcess = bind(OnProcess, backupEntity->callbacks, placeholders::_1, placeholders::_2)}); if (!backupEntity->session) { NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to init backup").GetCode()).ThrowErr(env); return nullptr; @@ -326,6 +390,16 @@ static bool VerifyParamSuccess(NFuncArg &funcArg, std::vector &bund napi_value SessionBackupNExporter::AppendBundles(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionBackup::AppendBundles begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } std::vector bundleNames; std::vector bundleInfos; NFuncArg funcArg(env, cbinfo); @@ -369,6 +443,16 @@ napi_value SessionBackupNExporter::AppendBundles(napi_env env, napi_callback_inf napi_value SessionBackupNExporter::Release(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionBackup::Release begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ZERO)) { HILOGE("Number of arguments unmatched."); diff --git a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp index 8d386e094d8806deb24bc1a724e6d76b531f0eb8..1a3d9bd95cd4cde1fc4f01031ef7b247a09c914c 100644 --- a/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_incremental_backup_n_exporter.cpp @@ -22,6 +22,7 @@ #include "b_incremental_backup_session.h" #include "b_incremental_data.h" #include "b_resources/b_constants.h" +#include "b_sa/b_sa_utils.h" #include "backup_kit_inner.h" #include "directory_ex.h" #include "filemgmt_libhilog.h" @@ -72,15 +73,21 @@ static void OnFileReady(weak_ptr pCallbacks, const BFileInfo & }; if (std::get<0>(errInfo) != 0) { obj = NVal {env, NError(errorParam).GetNapiErr(env)}; + napi_status status = napi_set_named_property(env, obj.val_, FILEIO_TAG_ERR_DATA.c_str(), + NVal::CreateUTF8String(env, bundleName).val_); + if (status != napi_ok) { + HILOGE("Failed to set data, status %{public}d, bundleName %{public}s", status, bundleName.c_str()); + } } else { obj = NVal::CreateObject(env); + obj.AddProp({ + NVal::DeclareNapiProperty(BConstants::BUNDLE_NAME.c_str(), + NVal::CreateUTF8String(env, bundleName).val_), + NVal::DeclareNapiProperty(BConstants::URI.c_str(), NVal::CreateUTF8String(env, fileName).val_), + NVal::DeclareNapiProperty(BConstants::FD.c_str(), NVal::CreateInt32(env, fd->Release()).val_), + NVal::DeclareNapiProperty(BConstants::MANIFEST_FD.c_str(), + NVal::CreateInt32(env, manifestFd->Release()).val_)}); } - obj.AddProp({ - NVal::DeclareNapiProperty(BConstants::BUNDLE_NAME.c_str(), NVal::CreateUTF8String(env, bundleName).val_), - NVal::DeclareNapiProperty(BConstants::URI.c_str(), NVal::CreateUTF8String(env, fileName).val_), - NVal::DeclareNapiProperty(BConstants::FD.c_str(), NVal::CreateInt32(env, fd->Release()).val_), - NVal::DeclareNapiProperty(BConstants::MANIFEST_FD.c_str(), - NVal::CreateInt32(env, manifestFd->Release()).val_)}); return {obj}; }; @@ -89,7 +96,7 @@ static void OnFileReady(weak_ptr pCallbacks, const BFileInfo & static void onBundleBegin(weak_ptr pCallbacks, ErrCode err, const BundleName name) { - HILOGI("Callback onBundleBegin, bundleName=%{public}s", name.c_str()); + HILOGI("Callback onBundleBegin, bundleName=%{public}s, errCode=%{public}d", name.c_str(), err); if (pCallbacks.expired()) { HILOGI("callbacks is unbound"); return; @@ -104,17 +111,23 @@ static void onBundleBegin(weak_ptr pCallbacks, ErrCode err, co return; } - auto cbCompl = [name {name}, errCode {err}](napi_env env, NError err) -> NVal { + ErrCode errCode = BError::GetBackupCodeByErrno(err); + std::string errMsg = BError::GetBackupMsgByErrno(errCode) + ", origin errno: " + to_string(err); + std::tuple errInfo = std::make_tuple(errCode, errMsg); + + auto cbCompl = [name {name}, errCode {err}, errInfo](napi_env env, NError err) -> NVal { NVal bundleName = NVal::CreateUTF8String(env, name); if (!err && errCode == 0) { return bundleName; } - + ErrParam errorParam = [ errInfo ]() { + return errInfo; + }; NVal res; if (err) { res = NVal {env, err.GetNapiErr(env)}; } else { - res = NVal {env, NError(errCode).GetNapiErr(env)}; + res = NVal {env, NError(errorParam).GetNapiErr(env)}; } napi_status status = napi_set_named_property(env, res.val_, FILEIO_TAG_ERR_DATA.c_str(), bundleName.val_); if (status != napi_ok) { @@ -129,7 +142,7 @@ static void onBundleBegin(weak_ptr pCallbacks, ErrCode err, co static void onBundleEnd(weak_ptr pCallbacks, ErrCode err, const BundleName name) { - HILOGI("Callback onBundleEnd, bundleName=%{public}s", name.c_str()); + HILOGI("Callback onBundleEnd, bundleName=%{public}s, errCode=%{public}d", name.c_str(), err); if (pCallbacks.expired()) { HILOGI("callbacks is unbound"); return; @@ -144,17 +157,23 @@ static void onBundleEnd(weak_ptr pCallbacks, ErrCode err, cons return; } - auto cbCompl = [name {name}, errCode {err}](napi_env env, NError err) -> NVal { + ErrCode errCode = BError::GetBackupCodeByErrno(err); + std::string errMsg = BError::GetBackupMsgByErrno(errCode) + ", origin errno: " + to_string(err); + std::tuple errInfo = std::make_tuple(errCode, errMsg); + + auto cbCompl = [name {name}, errCode {err}, errInfo](napi_env env, NError err) -> NVal { NVal bundleName = NVal::CreateUTF8String(env, name); if (!err && errCode == 0) { return bundleName; } - + ErrParam errorParam = [ errInfo ]() { + return errInfo; + }; NVal res; if (err) { res = NVal {env, err.GetNapiErr(env)}; } else { - res = NVal {env, NError(errCode).GetNapiErr(env)}; + res = NVal {env, NError(errorParam).GetNapiErr(env)}; } napi_status status = napi_set_named_property(env, res.val_, FILEIO_TAG_ERR_DATA.c_str(), bundleName.val_); if (status != napi_ok) { @@ -183,16 +202,22 @@ static void onAllBundlesEnd(weak_ptr pCallbacks, ErrCode err) return; } - auto cbCompl = [errCode {err}](napi_env env, NError err) -> NVal { + ErrCode errCode = BError::GetBackupCodeByErrno(err); + std::string errMsg = BError::GetBackupMsgByErrno(errCode) + ", origin errno: " + to_string(err); + std::tuple errInfo = std::make_tuple(errCode, errMsg); + + auto cbCompl = [errCode {err}, errInfo](napi_env env, NError err) -> NVal { if (!err && errCode == 0) { return NVal::CreateUndefined(env); } - + ErrParam errorParam = [ errInfo ]() { + return errInfo; + }; NVal res; if (err) { res = NVal {env, err.GetNapiErr(env)}; } else { - res = NVal {env, NError(errCode).GetNapiErr(env)}; + res = NVal {env, NError(errorParam).GetNapiErr(env)}; } return res; @@ -254,9 +279,47 @@ static void OnBackupServiceDied(weak_ptr pCallbacks) callbacks->onBackupServiceDied.ThreadSafeSchedule(cbCompl); } +static void OnProcess(weak_ptr pCallbacks, const BundleName name, const std::string processInfo) +{ + HILOGI("Callback OnProcess, bundleName=%{public}s", name.c_str()); + if (pCallbacks.expired()) { + HILOGI("callbacks is unbound"); + return; + } + auto callbacks = pCallbacks.lock(); + if (!callbacks) { + HILOGI("callback function OnProcess has already been released"); + return; + } + if (!bool(callbacks->onProcess)) { + HILOGI("callback function OnProcess is undefined"); + return; + } + auto cbCompl = [bundleName {name}, process {processInfo}](napi_env env, vector &argv) -> bool { + napi_value napi_bName = nullptr; + napi_create_string_utf8(env, bundleName.c_str(), bundleName.size(), &napi_bName); + argv.push_back(napi_bName); + napi_value napi_process = nullptr; + napi_create_string_utf8(env, process.c_str(), process.size(), &napi_process); + argv.push_back(napi_process); + return true; + }; + callbacks->onProcess.CallJsMethod(cbCompl); +} + napi_value SessionIncrementalBackupNExporter::Constructor(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionIncrementalBackup::Constructor begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ONE)) { HILOGE("Number of arguments unmatched"); @@ -281,7 +344,8 @@ napi_value SessionIncrementalBackupNExporter::Constructor(napi_env env, napi_cal .onBundleFinished = bind(onBundleEnd, backupEntity->callbacks, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(onAllBundlesEnd, backupEntity->callbacks, placeholders::_1), .onResultReport = bind(OnResultReport, backupEntity->callbacks, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, backupEntity->callbacks)}); + .onBackupServiceDied = bind(OnBackupServiceDied, backupEntity->callbacks), + .onProcess = bind(OnProcess, backupEntity->callbacks, placeholders::_1, placeholders::_2)}); if (!backupEntity->session) { NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to init backup").GetCode()).ThrowErr(env); return nullptr; @@ -391,6 +455,16 @@ static bool VerifyParamSuccess(NFuncArg &funcArg, std::vector napi_value SessionIncrementalBackupNExporter::AppendBundles(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionIncrementalBackup::AppendBundles begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } std::vector backupBundles; std::vector bundleInfos; NFuncArg funcArg(env, cbinfo); @@ -431,6 +505,16 @@ napi_value SessionIncrementalBackupNExporter::AppendBundles(napi_env env, napi_c napi_value SessionIncrementalBackupNExporter::Release(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionIncrementalBackup::Release begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ZERO)) { HILOGE("Number of arguments unmatched."); diff --git a/interfaces/kits/js/backup/session_restore_n_exporter.cpp b/interfaces/kits/js/backup/session_restore_n_exporter.cpp index 71d362b8d3c33947f8ddfebf01cec256f3bea86d..81347476aa7b13de8c33740fbbac0d041e89ac16 100644 --- a/interfaces/kits/js/backup/session_restore_n_exporter.cpp +++ b/interfaces/kits/js/backup/session_restore_n_exporter.cpp @@ -41,10 +41,8 @@ struct RestoreEntity { shared_ptr callbacks; }; -static void OnFileReadySheet(weak_ptr pCallbacks, - const BFileInfo &fileInfo, - UniqueFd fd, - UniqueFd manifestFd, int32_t sysErrno) +static void OnFileReadySheet(weak_ptr pCallbacks, const BFileInfo &fileInfo, + UniqueFd fd, UniqueFd manifestFd, int32_t sysErrno) { if (pCallbacks.expired()) { HILOGI("callbacks is unbound"); @@ -63,8 +61,7 @@ static void OnFileReadySheet(weak_ptr pCallbacks, std::string errMsg = "system errno: " + to_string(sysErrno); std::tuple errInfo = std::make_tuple(errCode, errMsg); - auto cbCompl = [bundleName {fileInfo.owner}, - fileName {fileInfo.fileName}, + auto cbCompl = [bundleName {fileInfo.owner}, fileName {fileInfo.fileName}, fd {make_shared(fd.Release())}, manifestFd {make_shared(manifestFd.Release())}, errInfo](napi_env env, NError err) -> NVal { @@ -78,15 +75,21 @@ static void OnFileReadySheet(weak_ptr pCallbacks, }; if (std::get<0>(errInfo) != 0) { obj = NVal {env, NError(errorParam).GetNapiErr(env)}; + napi_status status = napi_set_named_property(env, obj.val_, FILEIO_TAG_ERR_DATA.c_str(), + NVal::CreateUTF8String(env, bundleName).val_); + if (status != napi_ok) { + HILOGE("Failed to set data, status %{public}d, bundleName %{public}s", status, bundleName.c_str()); + } } else { obj = NVal::CreateObject(env); + obj.AddProp({ + NVal::DeclareNapiProperty(BConstants::BUNDLE_NAME.c_str(), + NVal::CreateUTF8String(env, bundleName).val_), + NVal::DeclareNapiProperty(BConstants::URI.c_str(), NVal::CreateUTF8String(env, fileName).val_), + NVal::DeclareNapiProperty(BConstants::FD.c_str(), NVal::CreateInt32(env, fd->Release()).val_), + NVal::DeclareNapiProperty(BConstants::MANIFEST_FD.c_str(), + NVal::CreateInt32(env, manifestFd->Release()).val_)}); } - obj.AddProp({ - NVal::DeclareNapiProperty(BConstants::BUNDLE_NAME.c_str(), NVal::CreateUTF8String(env, bundleName).val_), - NVal::DeclareNapiProperty(BConstants::URI.c_str(), NVal::CreateUTF8String(env, fileName).val_), - NVal::DeclareNapiProperty(BConstants::FD.c_str(), NVal::CreateInt32(env, fd->Release()).val_), - NVal::DeclareNapiProperty(BConstants::MANIFEST_FD.c_str(), - NVal::CreateInt32(env, manifestFd->Release()).val_)}); return {obj}; }; @@ -95,7 +98,7 @@ static void OnFileReadySheet(weak_ptr pCallbacks, static void onBundleBegin(weak_ptr pCallbacks, ErrCode err, const BundleName name) { - HILOGI("Callback onBundleBegin, bundleName=%{public}s", name.c_str()); + HILOGI("Callback onBundleBegin, bundleName=%{public}s, errCode=%{public}d", name.c_str(), err); if (pCallbacks.expired()) { HILOGI("callbacks is unbound"); return; @@ -110,17 +113,23 @@ static void onBundleBegin(weak_ptr pCallbacks, ErrCode err, co return; } - auto cbCompl = [name {name}, errCode {err}](napi_env env, NError err) -> NVal { + ErrCode errCode = BError::GetBackupCodeByErrno(err); + std::string errMsg = BError::GetBackupMsgByErrno(errCode) + ", origin errno: " + to_string(err); + std::tuple errInfo = std::make_tuple(errCode, errMsg); + + auto cbCompl = [name {name}, errCode {err}, errInfo](napi_env env, NError err) -> NVal { NVal bundleName = NVal::CreateUTF8String(env, name); if (!err && errCode == 0) { return bundleName; } - + ErrParam errorParam = [ errInfo ]() { + return errInfo; + }; NVal res; if (err) { res = NVal {env, err.GetNapiErr(env)}; } else { - res = NVal {env, NError(errCode).GetNapiErr(env)}; + res = NVal {env, NError(errorParam).GetNapiErr(env)}; } napi_status status = napi_set_named_property(env, res.val_, FILEIO_TAG_ERR_DATA.c_str(), bundleName.val_); if (status != napi_ok) { @@ -135,7 +144,7 @@ static void onBundleBegin(weak_ptr pCallbacks, ErrCode err, co static void onBundleEnd(weak_ptr pCallbacks, ErrCode err, const BundleName name) { - HILOGI("Callback onBundleEnd, bundleName=%{public}s", name.c_str()); + HILOGI("Callback onBundleEnd, bundleName=%{public}s, errCode=%{public}d", name.c_str(), err); if (pCallbacks.expired()) { HILOGI("callbacks is unbound"); return; @@ -150,17 +159,23 @@ static void onBundleEnd(weak_ptr pCallbacks, ErrCode err, cons return; } - auto cbCompl = [name {name}, errCode {err}](napi_env env, NError err) -> NVal { + ErrCode errCode = BError::GetBackupCodeByErrno(err); + std::string errMsg = BError::GetBackupMsgByErrno(errCode) + ", origin errno: " + to_string(err); + std::tuple errInfo = std::make_tuple(errCode, errMsg); + + auto cbCompl = [name {name}, errCode {err}, errInfo](napi_env env, NError err) -> NVal { NVal bundleName = NVal::CreateUTF8String(env, name); if (!err && errCode == 0) { return bundleName; } - + ErrParam errorParam = [ errInfo ]() { + return errInfo; + }; NVal res; if (err) { res = NVal {env, err.GetNapiErr(env)}; } else { - res = NVal {env, NError(errCode).GetNapiErr(env)}; + res = NVal {env, NError(errorParam).GetNapiErr(env)}; } napi_status status = napi_set_named_property(env, res.val_, FILEIO_TAG_ERR_DATA.c_str(), bundleName.val_); if (status != napi_ok) { @@ -189,16 +204,22 @@ static void onAllBundlesEnd(weak_ptr pCallbacks, ErrCode err) return; } - auto cbCompl = [errCode {err}](napi_env env, NError err) -> NVal { + ErrCode errCode = BError::GetBackupCodeByErrno(err); + std::string errMsg = BError::GetBackupMsgByErrno(errCode) + ", origin errno: " + to_string(err); + std::tuple errInfo = std::make_tuple(errCode, errMsg); + + auto cbCompl = [errCode {err}, errInfo](napi_env env, NError err) -> NVal { if (!err && errCode == 0) { return NVal::CreateUndefined(env); } - + ErrParam errorParam = [ errInfo ]() { + return errInfo; + }; NVal res; if (err) { res = NVal {env, err.GetNapiErr(env)}; } else { - res = NVal {env, NError(errCode).GetNapiErr(env)}; + res = NVal {env, NError(errorParam).GetNapiErr(env)}; } return res; @@ -260,6 +281,34 @@ static void OnResultReport(weak_ptr pCallbacks, const std::str callbacks->onResultReport.CallJsMethod(cbCompl); } +static void OnProcess(weak_ptr pCallbacks, const BundleName name, const std::string processInfo) +{ + HILOGI("Callback OnProcess, bundleName=%{public}s", name.c_str()); + if (pCallbacks.expired()) { + HILOGI("callbacks is unbound"); + return; + } + auto callbacks = pCallbacks.lock(); + if (!callbacks) { + HILOGI("callback function OnProcess has already been released"); + return; + } + if (!bool(callbacks->onProcess)) { + HILOGI("callback function OnProcess is undefined"); + return; + } + auto cbCompl = [bundleName {name}, process {processInfo}](napi_env env, vector &argv) -> bool { + napi_value napi_bName = nullptr; + napi_create_string_utf8(env, bundleName.c_str(), bundleName.size(), &napi_bName); + argv.push_back(napi_bName); + napi_value napi_process = nullptr; + napi_create_string_utf8(env, process.c_str(), process.size(), &napi_process); + argv.push_back(napi_process); + return true; + }; + callbacks->onProcess.CallJsMethod(cbCompl); +} + static bool VerifyAppendBundlesParam(NFuncArg &funcArg, int32_t &fd, std::vector &bundleNames, std::vector &bundleInfos, napi_env env) { @@ -371,6 +420,16 @@ static bool VerifyNarg(napi_env env, NVal &callbacks) napi_value SessionRestoreNExporter::Constructor(napi_env env, napi_callback_info cbinfo) { HILOGI("called SessionRestore::Constructor begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (VerifyNapiObject(env, funcArg)) { return nullptr; @@ -391,7 +450,8 @@ napi_value SessionRestoreNExporter::Constructor(napi_env env, napi_callback_info .onBundleFinished = bind(onBundleEnd, restoreEntity->callbacks, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(onAllBundlesEnd, restoreEntity->callbacks, placeholders::_1), .onResultReport = bind(OnResultReport, restoreEntity->callbacks, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, restoreEntity->callbacks)}); + .onBackupServiceDied = bind(OnBackupServiceDied, restoreEntity->callbacks), + .onProcess = bind(OnProcess, restoreEntity->callbacks, placeholders::_1, placeholders::_2)}); if (!restoreEntity->sessionSheet) { NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to init restore").GetCode()).ThrowErr(env); return nullptr; @@ -405,23 +465,16 @@ napi_value SessionRestoreNExporter::Constructor(napi_env env, napi_callback_info return funcArg.GetThisVar(); } -napi_value SessionRestoreNExporter::AppendBundles(napi_env env, napi_callback_info cbinfo) +static NContextCBExec GetAppendBundlesCBExec(napi_env env, NFuncArg &funcArg, const int32_t fdRestore, + const std::vector &bundleNames, const std::vector &bundleInfos) { - HILOGI("called SessionRestore::AppendBundles begin"); - int32_t fdRestore = BConstants::INVALID_FD_NUM; - std::vector bundleNames; - std::vector bundleInfos; - NFuncArg funcArg(env, cbinfo); - if (!VerifyAppendBundlesParam(funcArg, fdRestore, bundleNames, bundleInfos, env)) { - return nullptr; - } auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { HILOGE("Failed to get RestoreSession entity."); NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get RestoreSession entity.").GetCode()).ThrowErr(env); return nullptr; } - auto cbExec = [entity {restoreEntity}, fd {fdRestore}, bundles {bundleNames}, infos {bundleInfos}]() -> NError { + return [entity {restoreEntity}, fd {fdRestore}, bundles {bundleNames}, infos {bundleInfos}]() -> NError { if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); } @@ -440,10 +493,38 @@ napi_value SessionRestoreNExporter::AppendBundles(napi_env env, napi_callback_in } return NError(entity->sessionSheet->AppendBundles(UniqueFd(fd), bundles)); }; +} + +napi_value SessionRestoreNExporter::AppendBundles(napi_env env, napi_callback_info cbinfo) +{ + HILOGI("called SessionRestore::AppendBundles begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } + int32_t fdRestore = BConstants::INVALID_FD_NUM; + std::vector bundleNames; + std::vector bundleInfos; + NFuncArg funcArg(env, cbinfo); + if (!VerifyAppendBundlesParam(funcArg, fdRestore, bundleNames, bundleInfos, env)) { + return nullptr; + } + auto cbExec = GetAppendBundlesCBExec(env, funcArg, fdRestore, bundleNames, bundleInfos); + if (cbExec == nullptr) { + HILOGE("GetAppendBundlesCBExec fail!"); + return nullptr; + } auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); }; HILOGD("Called SessionRestore::AppendBundles end."); + NVal thisVar(env, funcArg.GetThisVar()); if (funcArg.GetArgc() == NARG_CNT::TWO) { return NAsyncWorkPromise(env, thisVar).Schedule(className, cbExec, cbCompl).val_; @@ -457,24 +538,16 @@ napi_value SessionRestoreNExporter::AppendBundles(napi_env env, napi_callback_in } } -napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info cbinfo) +static NContextCBExec GetPublishFileCBExec(napi_env env, NFuncArg &funcArg, const std::string &bundleName, + const std::string &fileName) { - HILOGD("called SessionRestore::PublishFile begin"); - std::string bundleName; - std::string fileName; - NFuncArg funcArg(env, cbinfo); - if (!VerifyPublishFileParam(funcArg, bundleName, fileName, env)) { - return nullptr; - } - auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { HILOGE("Failed to get RestoreSession entity."); NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get RestoreSession entity.").GetCode()).ThrowErr(env); return nullptr; } - - auto cbExec = [entity {restoreEntity}, bundleName {bundleName}, fileName {fileName}]() -> NError { + return [entity {restoreEntity}, bundleName {bundleName}, fileName {fileName}]() -> NError { if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); } @@ -492,10 +565,35 @@ napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info } return NError(entity->sessionSheet->PublishFile(fileInfo)); }; +} + +napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info cbinfo) +{ + HILOGD("called SessionRestore::PublishFile begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } + std::string bundleName; + std::string fileName; + NFuncArg funcArg(env, cbinfo); + if (!VerifyPublishFileParam(funcArg, bundleName, fileName, env)) { + return nullptr; + } + auto cbExec = GetPublishFileCBExec(env, funcArg, bundleName, fileName); + if (cbExec == nullptr) { + HILOGE("GetPublishFileCBExec fail!"); + return nullptr; + } auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); }; - HILOGD("Called SessionRestore::PublishFile end."); NVal thisVar(env, funcArg.GetThisVar()); @@ -507,9 +605,42 @@ napi_value SessionRestoreNExporter::PublishFile(napi_env env, napi_callback_info } } +static NContextCBExec GetFileHandleCBExec(napi_env env, NFuncArg &funcArg, std::unique_ptr bundleName, + std::unique_ptr fileName) +{ + auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); + if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { + HILOGE("Failed to get RestoreSession entity."); + NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get RestoreSession entity.").GetCode()).ThrowErr(env); + return nullptr; + } + return [entity {restoreEntity}, bundleName {string(bundleName.get())}, + fileName {string(fileName.get())}]() -> NError { + if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { + return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); + } + string bundle = bundleName; + string file = fileName; + if (entity->sessionWhole) { + return NError(entity->sessionWhole->GetFileHandle(bundle, file)); + } + return NError(entity->sessionSheet->GetFileHandle(bundle, file)); + }; +} + napi_value SessionRestoreNExporter::GetFileHandle(napi_env env, napi_callback_info cbinfo) { HILOGD("called SessionRestore::GetFileHandle begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) { HILOGE("Number of arguments unmatched."); @@ -531,29 +662,14 @@ napi_value SessionRestoreNExporter::GetFileHandle(napi_env env, napi_callback_in return nullptr; } - auto restoreEntity = NClass::GetEntityOf(env, funcArg.GetThisVar()); - if (!(restoreEntity && (restoreEntity->sessionWhole || restoreEntity->sessionSheet))) { - HILOGE("Failed to get RestoreSession entity."); - NError(BError(BError::Codes::SDK_INVAL_ARG, "Failed to get RestoreSession entity.").GetCode()).ThrowErr(env); + auto cbExec = GetFileHandleCBExec(env, funcArg, move(bundleName), move(fileName)); + if (cbExec == nullptr) { + HILOGE("GetFileHandleCBExec fail!"); return nullptr; } - - auto cbExec = [entity {restoreEntity}, bundleName {string(bundleName.get())}, - fileName {string(fileName.get())}]() -> NError { - if (!(entity && (entity->sessionWhole || entity->sessionSheet))) { - return NError(BError(BError::Codes::SDK_INVAL_ARG, "restore session is nullptr").GetCode()); - } - string bundle = bundleName; - string file = fileName; - if (entity->sessionWhole) { - return NError(entity->sessionWhole->GetFileHandle(bundle, file)); - } - return NError(entity->sessionSheet->GetFileHandle(bundle, file)); - }; auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); }; - HILOGD("Called SessionRestore::GetFileHandle end."); NVal thisVar(env, funcArg.GetThisVar()); @@ -568,6 +684,16 @@ napi_value SessionRestoreNExporter::GetFileHandle(napi_env env, napi_callback_in napi_value SessionRestoreNExporter::Release(napi_env env, napi_callback_info cbinfo) { HILOGI("called SessionRestore::Release begin"); + if (!SAUtils::CheckBackupPermission()) { + HILOGE("Has not permission!"); + NError(E_PERMISSION).ThrowErr(env); + return nullptr; + } + if (!SAUtils::IsSystemApp()) { + HILOGE("System App check fail!"); + NError(E_PERMISSION_SYS).ThrowErr(env); + return nullptr; + } NFuncArg funcArg(env, cbinfo); if (!funcArg.InitArgs(NARG_CNT::ZERO)) { HILOGE("Number of arguments unmatched."); @@ -594,7 +720,6 @@ napi_value SessionRestoreNExporter::Release(napi_env env, napi_callback_info cbi auto cbCompl = [](napi_env env, NError err) -> NVal { return err ? NVal {env, err.GetNapiErr(env)} : NVal::CreateUndefined(env); }; - HILOGI("Called SessionRestore::Release end."); NVal thisVar(env, funcArg.GetThisVar()); diff --git a/interfaces/kits/ndk/fileuri/src/oh_file_uri.cpp b/interfaces/kits/ndk/fileuri/src/oh_file_uri.cpp index db175595eff1a8c27f5684fc99e3797c21da34b4..213aba11c4241c65de3d7f5c2c4b37854daf097f 100644 --- a/interfaces/kits/ndk/fileuri/src/oh_file_uri.cpp +++ b/interfaces/kits/ndk/fileuri/src/oh_file_uri.cpp @@ -30,7 +30,7 @@ static FileManagement_ErrCode GetValue(std::string_view resultStr, char **result } if (count > OHOS::FileManagement::Backup::BConstants::PARAM_STARING_MAX_MEMORY) { LOGE("The param resultStr is too big"); - return ERR_UNKNOWN; + return ERR_PARAMS; } *result = static_cast(malloc(sizeof(char) * (count + 1))); if (*result == nullptr) { @@ -84,9 +84,9 @@ FileManagement_ErrCode OH_FileUri_GetFullDirectoryUri(const char *uri, unsigned bool OH_FileUri_IsValidUri(const char *uri, unsigned int length) { if (uri == nullptr || strlen(uri) != length) { - return ERR_PARAMS; + return false; } std::string uriStr(uri, length); OHOS::AppFileService::ModuleFileUri::FileUri fileUri(uriStr); return fileUri.CheckUriFormat(uriStr); -} \ No newline at end of file +} diff --git a/services/5203.json b/services/5203.json index a38a55395fbb8eaa757307132fa566256b2f6476..758a56c823fca675133a65b1bee0bfb51a1d2454 100644 --- a/services/5203.json +++ b/services/5203.json @@ -5,6 +5,7 @@ "name": 5203, "libpath": "libbackup_sa.z.so", "run-on-create": false, + "auto-restart": true, "distributed": false, "dump_level": 1, "start-on-demand": { diff --git a/services/backup_sa/BUILD.gn b/services/backup_sa/BUILD.gn index 5bf8af4f0b7e9cbf0969c91096f98810ece90515..9a713d379de420e933191490cec3c558a71cd57d 100644 --- a/services/backup_sa/BUILD.gn +++ b/services/backup_sa/BUILD.gn @@ -63,9 +63,9 @@ ohos_shared_library("backup_sa") { external_deps = [ "ability_base:want", - "ability_runtime:ability_connect_callback_stub", "ability_runtime:ability_manager", "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", diff --git a/services/backup_sa/include/module_external/bms_adapter.h b/services/backup_sa/include/module_external/bms_adapter.h index 5f106294c5aaaa772ef420eb703849c2eb79ca28..4e94ebfeae4c76eb75f872296405615f69a29a7c 100644 --- a/services/backup_sa/include/module_external/bms_adapter.h +++ b/services/backup_sa/include/module_external/bms_adapter.h @@ -58,11 +58,19 @@ public: static std::vector GetBundleInfosForIncremental(int32_t userId, const std::vector &extraIncreData = {}); + static std::vector GetFullBundleInfos(int32_t userId); + static std::string GetExtName(string bundleName, int32_t userId); static std::vector GetBundleInfosForSA(); static void GetBundleInfoForSA(std::string bundleName, std::vector &bundleInfos); + + static bool IsUser0BundleName(std::string bundleName, int32_t userId); +private: + static bool GetCurBundleExtenionInfo(AppExecFwk::BundleInfo &installedBundle, const std::string &bundleName, + std::vector &extensionInfos, sptr bms, + int32_t userId); }; } // namespace OHOS::FileManagement::Backup #endif // OHOS_FILEMGMT_BACKUP_BUNDLE_MGR_ADAPTER_H diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index 7f81017326ff54077016134af12535c32b098248..040974d2bf45e791e3d2bff0ad578edf95d596f8 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -20,6 +20,7 @@ #include #include "b_jsonutil/b_jsonutil.h" +#include "b_json/b_json_clear_data_config.h" #include "b_json/b_json_entity_caps.h" #include "b_json/b_json_service_disposal_config.h" #include "i_service_reverse.h" @@ -75,8 +76,11 @@ public: ErrCode AppIncrementalDone(ErrCode errCode) override; ErrCode GetIncrementalFileHandle(const std::string &bundleName, const std::string &fileName) override; ErrCode GetBackupInfo(BundleName &bundleName, std::string &result) override; - ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) override; + ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeout, bool &result) override; ErrCode UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) override; + ErrCode ReportAppProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario) override; + ErrCode StartExtTimer(bool &isExtStart) override; + ErrCode StartFwkTimer(bool &isFwkStart) override; ErrCode SAResultReport(const std::string bundleName, const std::string resultInfo, const ErrCode errCode, const BackupRestoreScenario sennario); @@ -173,6 +177,7 @@ public: * */ void SessionDeactive(); + /** * @brief 构造拉起应用所需的want * @@ -220,12 +225,53 @@ public: */ std::function GetBackupInfoConnectDied(wptr obj, std::string &bundleName); + /** + * @brief timeout callback + * + * @param ptr 当前对象 + * @param bundleName 应用名称 + */ + std::function TimeOutCallback(wptr ptr, std::string bundleName); + + /** + * @brief do timeout + * + * @param ptr 当前对象 + * @param bundleName 应用名称 + */ + void DoTimeout(wptr ptr, std::string bundleName); + + /** + * @brief 清理残留数据 + * + * @param bundleName 应用名称 + * + */ + void ClearResidualBundleData(const std::string &bundleName); + + /** + * @brief 添加清理记录 + * + * @param bundleName 应用名称 + * + */ + void AddClearBundleRecord(const std::string &bundleName); + + /** + * @brief 删除清理记录 + * + * @param bundleName 应用名称 + * + */ + void DelClearBundleRecord(const std::vector &bundleNames); + public: explicit Service(int32_t saID, bool runOnCreate = false) : SystemAbility(saID, runOnCreate) { threadPool_.Start(BConstants::EXTENSION_THREAD_POOL_COUNT); session_ = sptr(new SvcSessionManager(wptr(this))); disposal_ = make_shared(); + clearRecorder_ = make_shared(); }; ~Service() override { @@ -311,12 +357,43 @@ private: * @param restoreBundleInfos 待恢复的应用 * @param restoreBundleNames 待恢复的应用包信息 * @param bundleNameDetailMap bundle和detail的对应关系 + * @param isClearDataFlags 清理数据标志集合 * @param restoreType 任务类型 */ void SetCurrentSessProperties(std::vector &restoreBundleInfos, std::vector &restoreBundleNames, std::map> &bundleNameDetailMap, - RestoreTypeEnum restoreType); + std::map &isClearDataFlags, RestoreTypeEnum restoreType); + + /** + * @brief set session info + * + * @param restoreBundleInfos: bundles to be restored + * @param restoreBundleNames: bundles info to be restored + * @param restoreType: retore type + */ + void SetCurrentSessProperties(std::vector &restoreBundleInfos, + std::vector &restoreBundleNames, RestoreTypeEnum restoreType); + + void SetCurrentSessProperties(BJsonEntityCaps::BundleInfo &info, std::map &isClearDataFlags); + + /** + * @brief add useridinfo to current backup session + * + * @param bundleNames: bundleNames list + * @param userId: userId + * + */ + void SetCurrentBackupSessProperties(const std::vector &bundleNames, int32_t userId); + + /** + * @brief send userid to app + * + * @param bundleName: bundleName + * @param userId: userId + * + */ + void SendUserIdToApp(std::string &bundleName, int32_t userId); /** * @brief 通知权限模块 @@ -324,7 +401,7 @@ private: * @param bundleName 包名称 * */ - void NotifyCloneBundleFinish(std::string bundleName); + void NotifyCloneBundleFinish(std::string bundleName, const BackupRestoreScenario sennario); /** * @brief SA 备份恢复结束 @@ -362,6 +439,28 @@ private: */ void NotifyCallerCurAppIncrementDone(ErrCode errCode, const std::string &callerName); + void SetWant(AAFwk::Want &want, const BundleName &bundleName, const BConstants::ExtensionAction &action); + /** + * @brief GetBackupInfo 任务执行 + * + * @param bundleName 应用名称 + * @param result 业务结果出参 + * + */ + ErrCode GetBackupInfoCmdHandle(BundleName &bundleName, std::string &result); + + /** + * @brief 添加需要清理的Session + * + * @param bundleNames 需要清理的应用包信息 + * + */ + ErrCode AppendBundlesClearSession(const std::vector &bundleNames); + + void ReportOnExtConnectFailed(const IServiceReverse::Scenario scenario, + const std::string &bundleName, const ErrCode ret); + + void ReleaseOnException(); private: static sptr instance_; static std::mutex instanceLock_; @@ -369,11 +468,14 @@ private: std::condition_variable getBackupInfoCondition_; static inline std::atomic seed {1}; std::atomic isConnectDied_ {false}; + std::atomic isCleanService_ {false}; sptr session_; sptr sched_; std::shared_ptr disposal_; - + std::shared_ptr clearRecorder_; + std::atomic isInRelease_ {false}; + std::atomic isRmConfigFile_ {true}; friend class ServiceTest; OHOS::ThreadPool threadPool_; diff --git a/services/backup_sa/include/module_ipc/service_reverse_proxy.h b/services/backup_sa/include/module_ipc/service_reverse_proxy.h index 43d4e13bb459722e5e5c129537270b5f245ccc40..3e6667d8d2164de1810494a428131faabc668b52 100644 --- a/services/backup_sa/include/module_ipc/service_reverse_proxy.h +++ b/services/backup_sa/include/module_ipc/service_reverse_proxy.h @@ -27,6 +27,7 @@ public: void BackupOnResultReport(std::string result, std::string bundleName) override; void BackupOnBundleFinished(int32_t errCode, std::string bundleName) override; void BackupOnAllBundlesFinished(int32_t errCode) override; + void BackupOnProcessInfo(std::string bundleName, std::string processInfo) override; void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int32_t errCode) override; @@ -34,6 +35,7 @@ public: ErrCode errCode = 0) override; void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) override; void RestoreOnAllBundlesFinished(int32_t errCode) override; + void RestoreOnProcessInfo(std::string bundleName, std::string processInfo) override; void IncrementalBackupOnBundleStarted(int32_t errCode, std::string bundleName) override; void IncrementalBackupOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd, @@ -41,6 +43,7 @@ public: void IncrementalBackupOnResultReport(std::string result, std::string bundleName) override; void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) override; void IncrementalBackupOnAllBundlesFinished(int32_t errCode) override; + void IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) override; void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) override; void IncrementalRestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd, @@ -49,6 +52,7 @@ public: ErrCode errCode = 0) override; void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) override; void IncrementalRestoreOnAllBundlesFinished(int32_t errCode) override; + void IncrementalRestoreOnProcessInfo(std::string bundleName, std::string processInfo) override; public: explicit ServiceReverseProxy(const sptr &impl) : IRemoteProxy(impl) {} diff --git a/services/backup_sa/include/module_ipc/service_stub.h b/services/backup_sa/include/module_ipc/service_stub.h index bd40fdd1ea400b1baa92db978454e426720eb89b..5aeba27525c9cade76a2d09643be1ae2e392825b 100644 --- a/services/backup_sa/include/module_ipc/service_stub.h +++ b/services/backup_sa/include/module_ipc/service_stub.h @@ -62,6 +62,9 @@ private: int32_t CmdGetBackupInfo(MessageParcel &data, MessageParcel &reply); int32_t CmdUpdateTimer(MessageParcel &data, MessageParcel &reply); int32_t CmdUpdateSendRate(MessageParcel &data, MessageParcel &reply); + int32_t CmdReportAppProcessInfo(MessageParcel &data, MessageParcel &reply); + int32_t CmdStartExtTimer(MessageParcel &data, MessageParcel &reply); + int32_t CmdStartFwkTimer(MessageParcel &data, MessageParcel &reply); void ServiceStubSupplement(); void ServiceStubSuppAppendBundles(); 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 379721abd3dbbb7b6608f5ba3a51aeda5f1fb8d7..1958fcb8cd3c639ea8c0b71aef5cad17e8aeb4a4 100644 --- a/services/backup_sa/include/module_ipc/svc_backup_connection.h +++ b/services/backup_sa/include/module_ipc/svc_backup_connection.h @@ -76,7 +76,7 @@ public: * @param callConnected */ void SetCallback(std::function callConnected); - + /** * @brief Set the CallDied object * @@ -84,23 +84,32 @@ public: */ void SetCallDied(std::function callDied); + /** + * @brief wait disconnect done + */ + bool WaitDisconnectDone(); + public: SvcBackupConnection(std::function callDied, - std::function callConnected) - : callDied_(callDied), callConnected_(callConnected) + std::function callConnected, + std::string bundleNameIndexInfo) + : callDied_(callDied), callConnected_(callConnected), bundleNameIndexInfo_(bundleNameIndexInfo) { } ~SvcBackupConnection() override {}; private: std::mutex mutex_; + std::mutex waitMutex_; std::condition_variable condition_; + std::condition_variable waitCondition_; std::atomic isConnected_ = {false}; std::atomic isConnectedDone_ = {false}; sptr backupProxy_; std::function callDied_; std::function callConnected_; + std::string bundleNameIndexInfo_; }; } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/include/module_ipc/svc_extension_proxy.h b/services/backup_sa/include/module_ipc/svc_extension_proxy.h index e817810ae7d36c609b20e2af954357235def8d2f..4e5b9932a424e392df16219593f29ec56ac91b66 100644 --- a/services/backup_sa/include/module_ipc/svc_extension_proxy.h +++ b/services/backup_sa/include/module_ipc/svc_extension_proxy.h @@ -25,16 +25,17 @@ class SvcExtensionProxy : public IRemoteProxy { public: UniqueFd GetFileHandle(const std::string &fileName, int32_t &errCode) override; ErrCode HandleClear() override; - ErrCode HandleBackup() override; + ErrCode HandleBackup(bool isClearData) override; ErrCode PublishFile(const std::string &fileName) override; - ErrCode HandleRestore() override; + ErrCode HandleRestore(bool isClearData) override; ErrCode GetIncrementalFileHandle(const std::string &fileName) override; ErrCode PublishIncrementalFile(const std::string &fileName) override; ErrCode HandleIncrementalBackup(UniqueFd incrementalFd, UniqueFd manifestFd) override; - ErrCode IncrementalOnBackup() override; + ErrCode IncrementalOnBackup(bool isClearData) override; std::tuple GetIncrementalBackupFileHandle() override; ErrCode GetBackupInfo(std::string &result) override; ErrCode UpdateFdSendRate(std::string &bundleName, int32_t sendRate) override; + ErrCode User0OnBackup() override; public: explicit SvcExtensionProxy(const sptr &remote) : IRemoteProxy(remote) {} 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 737116a6c84041c2f5729054eb4e53b9c0204df7..e420dc5fccfbf0c7f1d6db24208e5a5fa4f298a7 100644 --- a/services/backup_sa/include/module_ipc/svc_session_manager.h +++ b/services/backup_sa/include/module_ipc/svc_session_manager.h @@ -56,15 +56,21 @@ struct BackupExtInfo { /* Clone App: old device app versionCode */ std::string versionName; /* Ext Ability APP process time */ - uint32_t extTimerId; + uint32_t timerId; /* Timer Status: true is start & false is stop */ - bool timerStatus {false}; + bool extTimerStatus {false}; + bool fwkTimerStatus {false}; + uint32_t timeout; + uint32_t startTime; int64_t dataSize; int64_t lastIncrementalTime; int32_t manifestFd; std::string backupParameters; int32_t backupPriority; std::string extInfo; + int32_t appendNum {1}; + bool isClearData {true}; + bool isInPublishFile {false}; }; class Service; @@ -102,7 +108,7 @@ public: * * @param impl 客户端信息 */ - ErrCode Active(Impl newImpl); + ErrCode Active(Impl newImpl, bool force = false); /** * @brief 关闭会话 @@ -382,51 +388,70 @@ public: void SetBundleDataSize(const std::string &bundleName, int64_t dataSize); /** - * @brief 启动应用扩展能力定时器 + * @brief 启动框架定时器 * * @param bundleName 应用名称 - * @return + * @param callback 超时回调 + * @return bool */ - void BundleExtTimerStart(const std::string &bundleName, const Utils::Timer::TimerCallback &callback); + bool StartFwkTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback); /** - * @brief 重新设置定时器 + * @brief 停止框架定时器 * * @param bundleName 应用名称 - * @param timeOut 超时时间 - * @return true - * @return false + * @param callback 超时回调 + * @return bool */ - bool UpdateTimer(const std::string &bundleName, uint32_t timeOut, - const Utils::Timer::TimerCallback &callback); + bool StopFwkTimer(const std::string &bundleName); /** - * @brief 取消/暂停应用扩展能力定时器 + * @brief 启动extension定时器 * * @param bundleName 应用名称 - * @return + * @param callback 超时回调 + * @return bool */ - void BundleExtTimerStop(const std::string &bundleName); + bool StartExtTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback); + + /** + * @brief 停止extension定时器 + * + * @param bundleName 应用名称 + * @return bool + */ + bool StopExtTimer(const std::string &bundleName); + + /** + * @brief 重新设置定时器 + * + * @param bundleName 应用名称 + * @param timeout 超时时间 + * @return true + * @return false + */ + bool UpdateTimer(const std::string &bundleName, uint32_t timeout, + const Utils::Timer::TimerCallback &callback); /** * @brief sessionCnt加计数 * * @param sessionCnt */ - void IncreaseSessionCnt(); + void IncreaseSessionCnt(const std::string funcName); /** * @brief sessionCnt加计数 * * @param sessionCnt */ - void DecreaseSessionCnt(); + void DecreaseSessionCnt(const std::string funcName); /** * @brief clear session data * */ - void ClearSessionData(); + ErrCode ClearSessionData(); /** * @brief Get the Is Incremental Backup object @@ -475,6 +500,14 @@ public: bool ValidRestoreDataType(RestoreTypeEnum restoreType); Impl GetImpl(); + int GetSessionCnt(); + + void SetClearDataFlag(const std::string &bundleName, bool isClearData); + bool GetClearDataFlag(const std::string &bundleName); + + bool CleanAndCheckIfNeedWait(ErrCode &ret, std::vector &bundleNameList); + + void SetPublishFlag(const std::string &bundleName); private: /** @@ -526,11 +559,11 @@ public: */ explicit SvcSessionManager(wptr reversePtr) : reversePtr_(reversePtr) { - extBundleTimer.Setup(); + timer_.Setup(); } ~SvcSessionManager() override { - extBundleTimer.Shutdown(); + timer_.Shutdown(); } private: @@ -539,7 +572,7 @@ private: sptr deathRecipient_; Impl impl_; uint32_t extConnectNum_ {0}; - Utils::Timer extBundleTimer {"backupBundleExtTimer"}; + Utils::Timer timer_ {"backupTimer"}; std::atomic sessionCnt_ {0}; int32_t memoryParaCurSize_ {BConstants::DEFAULT_VFS_CACHE_PRESSURE}; }; diff --git a/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp b/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp index 34f60aed333205220e16870eace44006c9b9af1a..76d04d6a34cb9bcba22c1c8c9eff1ef4ab946a7c 100644 --- a/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp +++ b/services/backup_sa/src/module_app_gallery/app_gallery_dispose_proxy.cpp @@ -13,15 +13,16 @@ * limitations under the License. */ -#include "module_app_gallery/app_gallery_dispose_proxy.h" - #include +#include "b_radar/b_radar.h" +#include "b_sa/b_sa_utils.h" +#include "b_jsonutil/b_jsonutil.h" +#include "filemgmt_libhilog.h" #include "message_parcel.h" -#include "want.h" - +#include "module_app_gallery/app_gallery_dispose_proxy.h" #include "module_app_gallery/app_gallery_service_connection.h" -#include "filemgmt_libhilog.h" +#include "want.h" namespace OHOS::FileManagement::Backup { using namespace std; @@ -75,16 +76,50 @@ DisposeErr AppGalleryDisposeProxy::EndBackup(const std::string &bundleName) DisposeErr AppGalleryDisposeProxy::StartRestore(const std::string &bundleName) { + if (SAUtils::IsSABundleName(bundleName)) { + HILOGI("SA does not need to StartRestore"); + return DisposeErr::OK; + } HILOGI("StartRestore, app %{public}s", bundleName.c_str()); return DoDispose(bundleName, DisposeOperation::START_RESTORE); } DisposeErr AppGalleryDisposeProxy::EndRestore(const std::string &bundleName) { + if (SAUtils::IsSABundleName(bundleName)) { + HILOGI("SA does not need to EndRestore"); + return DisposeErr::OK; + } HILOGI("EndRestore, app %{public}s", bundleName.c_str()); return DoDispose(bundleName, DisposeOperation::END_RESTORE); } +void RecordDoDisposeRes(const std::string &bundleName, + AppGalleryDisposeProxy::DisposeOperation disposeOperation, int32_t err) +{ + AppRadar::Info info (bundleName, "", ""); + switch (disposeOperation) { + case AppGalleryDisposeProxy::DisposeOperation::START_BACKUP: + AppRadar::GetInstance().RecordBackupFuncRes(info, "StartBackup", AppRadar::GetInstance().GetUserId(), + BizStageBackup::BIZ_STAGE_START_DISPOSE_FAIL, err); + break; + case AppGalleryDisposeProxy::DisposeOperation::END_BACKUP: + AppRadar::GetInstance().RecordBackupFuncRes(info, "EndBackup", AppRadar::GetInstance().GetUserId(), + BizStageBackup::BIZ_STAGE_END_DISPOSE_FAIL, err); + break; + case AppGalleryDisposeProxy::DisposeOperation::START_RESTORE: + AppRadar::GetInstance().RecordRestoreFuncRes(info, "StartRestore", AppRadar::GetInstance().GetUserId(), + BizStageRestore::BIZ_STAGE_START_DISPOSE_FAIL, err); + break; + case AppGalleryDisposeProxy::DisposeOperation::END_RESTORE: + AppRadar::GetInstance().RecordRestoreFuncRes(info, "EndRestore", AppRadar::GetInstance().GetUserId(), + BizStageRestore::BIZ_STAGE_END_DISPOSE_FAIL, err); + break; + default: + break; + } +} + DisposeErr AppGalleryDisposeProxy::DoDispose(const std::string &bundleName, DisposeOperation disposeOperation) { HILOGI("DoDispose, app %{public}s, operation %{public}d", bundleName.c_str(), disposeOperation); @@ -93,19 +128,19 @@ DisposeErr AppGalleryDisposeProxy::DoDispose(const std::string &bundleName, Disp return DisposeErr::CONN_FAIL; } + BJsonUtil::BundleDetailInfo bundleDetailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName); MessageParcel data; - if (!data.WriteString16(Str8ToStr16(bundleName))) { - HILOGI("write ownerInfo and bundleName failed"); + const auto interfaceToken = APP_FOUNDATION_SERVICE; + if (!data.WriteInterfaceToken(interfaceToken)) { + HILOGI("write WriteInterfaceToken failed"); return DisposeErr::IPC_FAIL; } - - if (!data.WriteRemoteObject(this)) { - HILOGI("write RemoteObject failed"); + if (!data.WriteString16(Str8ToStr16(bundleDetailInfo.bundleName))) { + HILOGI("write bundleName failed"); return DisposeErr::IPC_FAIL; } - const auto interfaceToken = APP_FOUNDATION_SERVICE; - if (!data.WriteInterfaceToken(interfaceToken)) { - HILOGI("write WriteInterfaceToken failed"); + if (!data.WriteInt32(static_cast(bundleDetailInfo.bundleIndex))) { + HILOGI("write bundleIndex failed"); return DisposeErr::IPC_FAIL; } @@ -113,11 +148,14 @@ DisposeErr AppGalleryDisposeProxy::DoDispose(const std::string &bundleName, Disp MessageOption option(MessageOption::TF_ASYNC); int32_t ret = appRemoteObj_->SendRequest(static_cast(disposeOperation), data, reply, option); if (ret != ERR_NONE) { - HILOGI("SendRequest error, code=%{public}d, bundleName=%{public}s", ret, bundleName.c_str()); + HILOGI("SendRequest error, code=%{public}d, bundleName=%{public}s , appindex =%{public}d", + ret, bundleDetailInfo.bundleName.c_str(), bundleDetailInfo.bundleIndex); + RecordDoDisposeRes(bundleName, disposeOperation, ret); return DisposeErr::REQUEST_FAIL; } - HILOGI("SendRequest success, dispose=%{public}d, bundleName=%{public}s", disposeOperation, bundleName.c_str()); + HILOGI("SendRequest success, dispose=%{public}d, bundleName=%{public}s, appindex =%{public}d", + disposeOperation, bundleDetailInfo.bundleName.c_str(), bundleDetailInfo.bundleIndex); return DisposeErr::OK; } diff --git a/services/backup_sa/src/module_external/bms_adapter.cpp b/services/backup_sa/src/module_external/bms_adapter.cpp index 87b1cfda47483c7014681a2048df70ddc83ef0ff..59b73f550f38125ae37c2af4fdc915450809e241 100644 --- a/services/backup_sa/src/module_external/bms_adapter.cpp +++ b/services/backup_sa/src/module_external/bms_adapter.cpp @@ -22,6 +22,7 @@ #include "b_error/b_error.h" #include "b_file_info.h" +#include "b_jsonutil/b_jsonutil.h" #include "b_json/b_json_entity_extension_config.h" #include "b_resources/b_constants.h" #include "b_sa/b_sa_utils.h" @@ -47,7 +48,6 @@ const string LINUX_HAP_CODE_PATH = "2"; const string MEDIA_LIBRARY_HAP = "com.ohos.medialibrary.medialibrarydata"; const string EXTERNAL_FILE_HAP = "com.ohos.UserFile.ExternalFileManager"; const int E_ERR = -1; -const int SINGLE_BUNDLE_NUM = 1; const vector dataDir = {"app", "local", "distributed", "database", "cache"}; } // namespace @@ -95,7 +95,8 @@ static int64_t GetBundleStats(const string &bundleName, int32_t userId) } auto bms = GetBundleManager(); vector bundleStats; - bool res = bms->GetBundleStats(bundleName, userId, bundleStats); + BJsonUtil::BundleDetailInfo bundleDetailInfo = BJsonUtil::ParseBundleNameIndexStr(bundleName); + bool res = bms->GetBundleStats(bundleDetailInfo.bundleName, userId, bundleStats, bundleDetailInfo.bundleIndex); if (!res || bundleStats.size() != dataDir.size()) { HILOGE("An error occurred in querying bundle stats. name:%{public}s", bundleName.c_str()); return 0; @@ -122,25 +123,20 @@ vector BundleMgrAdapter::GetBundleInfos(const vecto continue; } AppExecFwk::BundleInfo installedBundle; - if (!bms->GetBundleInfo(bundleName, AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundle, userId)) { - if (bundleNames.size() != SINGLE_BUNDLE_NUM) { - HILOGE("bundleName:%{public}s, current bundle info for backup/restore is empty", bundleName.c_str()); - continue; - } - throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Failed to get bundle info"); - } - if (installedBundle.applicationInfo.codePath == HMOS_HAP_CODE_PATH || - installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { - HILOGI("Unsupported applications, name : %{public}s", installedBundle.name.data()); + std::vector extensionInfos; + bool getBundleSuccess = GetCurBundleExtenionInfo(installedBundle, bundleName, extensionInfos, bms, userId); + if (!getBundleSuccess) { + HILOGE("Get current extension failed"); continue; } auto [allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, extraInfo] = - GetAllowAndExtName(installedBundle.extensionInfos); + GetAllowAndExtName(extensionInfos); int64_t dataSize = 0; if (allToBackup) { dataSize = GetBundleStats(installedBundle.name, userId); } - bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.versionCode, + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.appIndex, + installedBundle.versionCode, installedBundle.versionName, dataSize, 0, allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, extraInfo}); @@ -199,7 +195,7 @@ static bool CreateIPCInteractionFiles(int32_t userId, const string &bundleName, bundleName + BConstants::FILE_SEPARATOR_CHAR; if (access(backupSaBundleDir.data(), F_OK) != 0) { int32_t err = mkdir(backupSaBundleDir.data(), S_IRWXU | S_IRWXG); - if (err != 0) { + if (err != 0 && errno != EEXIST) { HILOGE("Failed to create folder in backup_sa bundleName:%{public}s, sys err:%{public}d", bundleName.c_str(), errno); return false; @@ -258,6 +254,7 @@ static bool GenerateBundleStatsIncrease(int32_t userId, const vector &bu std::string curBundleName = bundleInfos[i].name; HILOGD("BundleMgrAdapter name for %{public}s", curBundleName.c_str()); BJsonEntityCaps::BundleInfo newBundleInfo = {.name = curBundleName, + .appIndex = bundleInfos[i].appIndex, .versionCode = bundleInfos[i].versionCode, .versionName = bundleInfos[i].versionName, .spaceOccupied = pkgFileSizes[i], @@ -284,16 +281,14 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement auto bundleName = bundleNameTime.bundleName; HILOGD("Begin get bundleName:%{private}s", bundleName.c_str()); AppExecFwk::BundleInfo installedBundle; - if (!bms->GetBundleInfo(bundleName, AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundle, userId)) { - throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get bundle info"); - } - if (installedBundle.applicationInfo.codePath == HMOS_HAP_CODE_PATH || - installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { - HILOGI("Unsupported applications, name : %{private}s", installedBundle.name.data()); + std::vector extensionInfos; + bool getBundleSuccess = GetCurBundleExtenionInfo(installedBundle, bundleName, extensionInfos, 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(installedBundle.extensionInfos, backupPara)) { + if (!GetBackupExtConfig(extensionInfos, backupPara)) { HILOGE("No backup extension ability found"); continue; } @@ -301,7 +296,8 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement backupPara.excludes)) { continue; } - bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.versionCode, + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.appIndex, + installedBundle.versionCode, installedBundle.versionName, 0, 0, backupPara.allToBackup, backupPara.fullBackupOnly, backupPara.extensionName, @@ -315,7 +311,6 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement HILOGE("Failed to get bundleStats result"); return {}; } - HILOGI("BundleMgrAdapter GetBundleInfosForIncremental end "); return newBundleInfos; } @@ -342,9 +337,9 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement auto [allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, extraInfo] = GetAllowAndExtName(installedBundle.extensionInfos); if (!allToBackup) { - bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.versionCode, - installedBundle.versionName, 0, 0, allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, - extraInfo}); + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.appIndex, + installedBundle.versionCode, installedBundle.versionName, 0, 0, allToBackup, fullBackupOnly, extName, + restoreDeps, supportScene, extraInfo}); continue; } auto it = std::find_if(extraIncreData.begin(), extraIncreData.end(), @@ -365,6 +360,42 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement return bundleInfos; } +vector BundleMgrAdapter::GetFullBundleInfos(int32_t userId) +{ + vector installedBundles; + HILOGI("Begin GetFullBundleInfos"); + auto bms = GetBundleManager(); + if (!bms->GetBundleInfos(AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundles, userId)) { + throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get bundle infos"); + } + vector bundleNames; + vector bundleInfos; + for (auto const &installedBundle : installedBundles) { + HILOGI("Begin get bundle infos, bundleName = %{public}s", installedBundle.name.data()); + if (installedBundle.applicationInfo.codePath == HMOS_HAP_CODE_PATH || + installedBundle.applicationInfo.codePath == LINUX_HAP_CODE_PATH) { + HILOGI("Unsupported applications, name : %{public}s", installedBundle.name.data()); + continue; + } + auto [allToBackup, fullBackupOnly, extName, restoreDeps, supportScene, extraInfo] = + GetAllowAndExtName(installedBundle.extensionInfos); + if (!allToBackup) { + HILOGI("Not allToBackup, bundleName = %{public}s", installedBundle.name.data()); + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.appIndex, + installedBundle.versionCode, installedBundle.versionName, 0, 0, allToBackup, fullBackupOnly, extName, + restoreDeps, supportScene, extraInfo}); + continue; + } + bundleNames.emplace_back(installedBundle.name); + } + auto bundleInfosNew = BundleMgrAdapter::GetBundleInfos(bundleNames, userId); + auto bundleInfosSA = BundleMgrAdapter::GetBundleInfosForSA(); + copy(bundleInfosNew.begin(), bundleInfosNew.end(), back_inserter(bundleInfos)); + copy(bundleInfosSA.begin(), bundleInfosSA.end(), back_inserter(bundleInfos)); + HILOGI("End GetFullBundleInfos, bundleInfos size: %{public}zu", bundleInfos.size()); + return bundleInfos; +} + string BundleMgrAdapter::GetExtName(string bundleName, int32_t userId) { vector installedBundles; @@ -405,7 +436,7 @@ std::vector BundleMgrAdapter::GetBundleInfosForSA() int32_t ret = samgrProxy->GetExtensionSaIds(BConstants::EXTENSION_BACKUP, saIds); HILOGI("GetExtensionSaIds ret: %{public}d", ret); for (auto saId : saIds) { - saBundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {std::to_string(saId), 0, "", 0, 0, true, false, + saBundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {std::to_string(saId), 0, 0, "", 0, 0, true, false, "", "", "", ""}); } return saBundleInfos; @@ -435,7 +466,54 @@ void BundleMgrAdapter::GetBundleInfoForSA(std::string bundleName, std::vector &extensionInfos, + sptr bms, int32_t userId) +{ + BJsonUtil::BundleDetailInfo bundleDetailInfo = BJsonUtil::ParseBundleNameIndexStr(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); + ErrCode ret = bms->GetCloneBundleInfo(bundleDetailInfo.bundleName, flags, bundleDetailInfo.bundleIndex, + installedBundle, userId); + if (ret != ERR_OK) { + HILOGE("bundleName:%{public}s, ret:%{public}d, current bundle info for backup/restore is empty", + bundleName.c_str(), ret); + 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()); + return false; + } + HILOGI("bundleName:%{public}s, hapMoudleInfos size:%{public}zu", bundleName.c_str(), + installedBundle.hapModuleInfos.size()); + std::vector hapModuleInfos = installedBundle.hapModuleInfos; + for (auto &hapModuleInfo : hapModuleInfos) { + extensionInfos.insert(extensionInfos.end(), hapModuleInfo.extensionInfos.begin(), + hapModuleInfo.extensionInfos.end()); + } + HILOGI("bundleName:%{public}s, extensionInfos size:%{public}zu", bundleName.c_str(), extensionInfos.size()); + return true; +} + +bool BundleMgrAdapter::IsUser0BundleName(std::string bundleName, int32_t userId) +{ + auto bms = GetBundleManager(); + AppExecFwk::BundleInfo installedBundle; + if (!bms->GetBundleInfo(bundleName, AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundle, userId)) { + HILOGI("GetBundleInfo failed, bundleName:%{public}s", bundleName.c_str()); + return false; + } + if (installedBundle.applicationInfo.singleton == true) { + HILOGI("bundleName:%{public}s is zero user bundle", bundleName.c_str()); + return true; + } + HILOGI("bundleName:%{public}s is not zero user bundle", bundleName.c_str()); + return false; +} } // 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 952aeefa0aaf082835e66a5fa900ea53edd3703d..71c623458edfec4f5b9679ba9feb451601829dba 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -47,6 +47,7 @@ #include "b_jsonutil/b_jsonutil.h" #include "b_ohos/startup/backup_para.h" #include "b_process/b_multiuser.h" +#include "b_radar/b_radar.h" #include "b_resources/b_constants.h" #include "b_sa/b_sa_utils.h" #include "bundle_mgr_client.h" @@ -54,6 +55,8 @@ #include "hisysevent.h" #include "hitrace_meter.h" #include "ipc_skeleton.h" +#include "access_token.h" +#include "tokenid_kit.h" #include "module_app_gallery/app_gallery_dispose_proxy.h" #include "module_external/bms_adapter.h" #include "module_external/sms_adapter.h" @@ -73,6 +76,7 @@ namespace { constexpr int32_t DEBUG_ID = 100; constexpr int32_t INDEX = 3; constexpr int32_t MS_1000 = 1000; +constexpr int DEFAULT_FD_SEND_RATE = 60; const static string BROADCAST_TYPE = "broadcast"; const std::string FILE_BACKUP_EVENTS = "FILE_BACKUP_EVENTS"; const static string UNICAST_TYPE = "unicast"; @@ -80,6 +84,7 @@ const int32_t CONNECT_WAIT_TIME_S = 15; const std::string BACKUPSERVICE_WORK_STATUS_KEY = "persist.backupservice.workstatus"; const std::string BACKUPSERVICE_WORK_STATUS_ON = "true"; const std::string BACKUPSERVICE_WORK_STATUS_OFF = "false"; +const std::string BACKUP_PERMISSION = "ohos.permission.BACKUP"; } // namespace /* Shell/Xts user id equal to 0/1, we need set default 100 */ @@ -101,17 +106,34 @@ void Service::OnStart() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("SA OnStart Begin."); - ClearDisposalOnSaStart(); + std::vector bundleNameList; + if (disposal_ != nullptr) { + bundleNameList = disposal_->GetBundleNameFromConfigFile(); + } + std::vector residualBundleNameList; + if (clearRecorder_ != nullptr) { + residualBundleNameList = clearRecorder_->GetAllClearBundleRecords(); + } + if (!bundleNameList.empty() || !residualBundleNameList.empty()) { + session_->Active( + { + .clientToken = IPCSkeleton::GetCallingTokenID(), + .scenario = IServiceReverse::Scenario::CLEAN, + .clientProxy = nullptr, + .userId = GetUserIdDefault(), + }, + true); + isCleanService_.store(true); + HILOGI("SA OnStart, cleaning up backup data"); + } bool res = SystemAbility::Publish(sptr(this)); sched_ = sptr(new SchedScheduler(wptr(this), wptr(session_))); sched_->StartTimer(); - string work_status = system::GetParameter(BACKUPSERVICE_WORK_STATUS_KEY, ""); - HILOGI("Param %{public}s value is %{public}s", BACKUPSERVICE_WORK_STATUS_KEY.c_str(), work_status.c_str()); - if (work_status.compare(BACKUPSERVICE_WORK_STATUS_ON) == 0) { - bool isSetSucc = system::SetParameter(BACKUPSERVICE_WORK_STATUS_KEY, BACKUPSERVICE_WORK_STATUS_OFF); - HILOGI("SetParameter %{public}s false end, result %{public}d.", BACKUPSERVICE_WORK_STATUS_KEY.c_str(), - isSetSucc); - sched_->TryUnloadService(); + ClearDisposalOnSaStart(); + auto ret = AppendBundlesClearSession(residualBundleNameList); + if (isCleanService_.load() && ret) { + isCleanService_.store(false); + StopAll(nullptr, true); } HILOGI("SA OnStart End, res = %{public}d", res); } @@ -125,13 +147,6 @@ void Service::OnStop() oldMemoryParaSize = session_->GetMemParaCurSize(); } StorageMgrAdapter::UpdateMemPara(oldMemoryParaSize); - string work_status = system::GetParameter(BACKUPSERVICE_WORK_STATUS_KEY, ""); - HILOGI("Param %{public}s value is %{public}s", BACKUPSERVICE_WORK_STATUS_KEY.c_str(), work_status.c_str()); - if (work_status.compare(BACKUPSERVICE_WORK_STATUS_ON) == 0) { - bool isSetSucc = system::SetParameter(BACKUPSERVICE_WORK_STATUS_KEY, BACKUPSERVICE_WORK_STATUS_OFF); - HILOGI("SetParameter %{public}s false end, result %{public}d.", BACKUPSERVICE_WORK_STATUS_KEY.c_str(), - isSetSucc); - } HILOGI("SA OnStop End."); } @@ -144,7 +159,11 @@ UniqueFd Service::GetLocalCapabilities() so there must be set init userId. */ HILOGI("Begin"); - session_->IncreaseSessionCnt(); + if (session_ == nullptr || isCleanService_.load()) { + HILOGE("GetLocalCapabilities error, session is empty."); + return UniqueFd(-EPERM); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); session_->SetSessionUserId(GetUserIdDefault()); VerifyCaller(); string path = BConstants::GetSaBundleBackupRootDir(session_->GetSessionUserId()); @@ -152,7 +171,8 @@ UniqueFd Service::GetLocalCapabilities() UniqueFd fd(open(path.data(), O_TMPFILE | O_RDWR, S_IRUSR | S_IWUSR)); if (fd < 0) { HILOGE("Failed to open config file = %{private}s, err = %{public}d", path.c_str(), errno); - return UniqueFd(-1); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return UniqueFd(-EPERM); } BJsonCachedEntity cachedEntity(std::move(fd)); @@ -160,22 +180,22 @@ UniqueFd Service::GetLocalCapabilities() cache.SetSystemFullName(GetOSFullName()); cache.SetDeviceType(GetDeviceType()); - auto bundleInfos = BundleMgrAdapter::GetBundleInfosForIncremental(session_->GetSessionUserId()); + auto bundleInfos = BundleMgrAdapter::GetFullBundleInfos(session_->GetSessionUserId()); cache.SetBundleInfos(bundleInfos); cachedEntity.Persist(); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("End"); return move(cachedEntity.GetFd()); } catch (const BError &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("GetLocalCapabilities failed, errCode = %{public}d", e.GetCode()); return UniqueFd(-e.GetCode()); } catch (const exception &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); return UniqueFd(-EPERM); } catch (...) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return UniqueFd(-EPERM); } @@ -187,6 +207,15 @@ void Service::StopAll(const wptr &obj, bool force) session_->Deactive(obj, force); } +static inline void PermissionCheckFailRadar(const std::string &info, const std::string &func) +{ + std::string funcPos = "Service::"; + AppRadar::Info resInfo("", "", info); + AppRadar::GetInstance().RecordDefaultFuncRes(resInfo, funcPos.append(func), + GetUserIdDefault(), BizStageBackup::BIZ_STAGE_PERMISSION_CHECK_FAIL, + BError(BError::Codes::SA_REFUSED_ACT).GetCode()); +} + string Service::VerifyCallerAndGetCallerName() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); @@ -195,13 +224,18 @@ string Service::VerifyCallerAndGetCallerName() if (tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) { Security::AccessToken::HapTokenInfo hapTokenInfo; if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(tokenCaller, hapTokenInfo) != 0) { + PermissionCheckFailRadar("Get hap token info failed", "VerifyCallerAndGetCallerName"); throw BError(BError::Codes::SA_INVAL_ARG, "Get hap token info failed"); } - session_->VerifyBundleName(hapTokenInfo.bundleName); - return hapTokenInfo.bundleName; + std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(hapTokenInfo.bundleName, + hapTokenInfo.instIndex); + session_->VerifyBundleName(bundleNameIndexInfo); + return bundleNameIndexInfo; } else { string str = to_string(tokenCaller); HILOGE("tokenID = %{private}s", GetAnonyString(str).c_str()); + std::string info = string("Invalid token type").append(to_string(tokenType)).append(string("\"}")); + PermissionCheckFailRadar(info, "VerifyCallerAndGetCallerName"); throw BError(BError::Codes::SA_INVAL_ARG, string("Invalid token type ").append(to_string(tokenType))); } } @@ -212,23 +246,44 @@ void Service::VerifyCaller() uint32_t tokenCaller = IPCSkeleton::GetCallingTokenID(); int tokenType = Security::AccessToken::AccessTokenKit::GetTokenType(tokenCaller); switch (tokenType) { - case Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE: /* Update Service */ + case Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE: { /* Update Service */ + if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, BACKUP_PERMISSION) != + Security::AccessToken::PermissionState::PERMISSION_GRANTED) { + std::string info = "Permission denied, token type is " + to_string(tokenType); + PermissionCheckFailRadar(info, "VerifyCaller"); + throw BError(BError::Codes::SA_REFUSED_ACT, + string("Permission denied, token type is ").append(to_string(tokenType))); + } + break; + } case Security::AccessToken::ATokenTypeEnum::TOKEN_HAP: { - const string permission = "ohos.permission.BACKUP"; - if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission) == - Security::AccessToken::TypePermissionState::PERMISSION_DENIED) { - throw BError(BError::Codes::SA_INVAL_ARG, - string("Permission denied, token type is ").append(to_string(tokenType))); + if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, BACKUP_PERMISSION) != + Security::AccessToken::PermissionState::PERMISSION_GRANTED) { + std::string info = "Permission denied, token type is " + to_string(tokenType); + PermissionCheckFailRadar(info, "VerifyCaller"); + throw BError(BError::Codes::SA_REFUSED_ACT, + string("Permission denied, token type is ").append(to_string(tokenType))); + } + uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID(); + if (!Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) { + std::string info = "Permission denied, token type is " + to_string(tokenType); + PermissionCheckFailRadar(info, "VerifyCaller"); + throw BError(BError::Codes::SA_REFUSED_ACT, + string("Permission denied, token type is ").append(to_string(tokenType))); } break; } case Security::AccessToken::ATokenTypeEnum::TOKEN_SHELL: if (IPCSkeleton::GetCallingUid() != BConstants::SYSTEM_UID) { - throw BError(BError::Codes::SA_INVAL_ARG, "Calling uid is invalid"); + std::string info = "invalid calling uid"; + PermissionCheckFailRadar(info, "VerifyCaller"); + throw BError(BError::Codes::SA_REFUSED_ACT, "Calling uid is invalid"); } break; default: - throw BError(BError::Codes::SA_INVAL_ARG, string("Invalid token type ").append(to_string(tokenType))); + std::string info = "Permission denied, token type is " + to_string(tokenType); + PermissionCheckFailRadar(info, "VerifyCaller"); + throw BError(BError::Codes::SA_REFUSED_ACT, string("Invalid token type ").append(to_string(tokenType))); break; } } @@ -280,16 +335,27 @@ ErrCode Service::InitBackupSession(sptr remote) } catch (const BError &e) { StopAll(nullptr, true); return e.GetCode(); + } catch (const exception &e) { + HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); + return EPERM; + } catch (...) { + HILOGI("Unexpected exception"); + return EPERM; } } ErrCode Service::Start() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - VerifyCaller(session_->GetScenario()); - session_->Start(); - OnStartSched(); - return BError(BError::Codes::OK); + try { + VerifyCaller(session_->GetScenario()); + session_->Start(); + OnStartSched(); + return BError(BError::Codes::OK); + } catch (const BError &e) { + HILOGE("Failde to Start"); + return e.GetCode(); + } } static bool SpecialVersion(const string &versionName) @@ -333,6 +399,7 @@ static vector GetRestoreBundleNames(UniqueFd fd, for (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, @@ -350,6 +417,7 @@ static vector GetRestoreBundleNames(UniqueFd fd, continue; } BJsonEntityCaps::BundleInfo info = {.name = (*it).name, + .appIndex = (*it).appIndex, .versionCode = (*it).versionCode, .versionName = (*it).versionName, .spaceOccupied = (*it).spaceOccupied, @@ -367,7 +435,8 @@ static void HandleExceptionOnAppendBundles(sptr session, const vector &appendBundleNames, const vector &restoreBundleNames) { if (appendBundleNames.size() != restoreBundleNames.size()) { - HILOGE("AppendBundleNames not equal restoreBundleNames."); + HILOGE("AppendBundleNames not equal restoreBundleNames, appendBundleNames size:%{public}zu," + "restoreBundleNames size:%{public}zu", appendBundleNames.size(), restoreBundleNames.size()); for (auto bundleName : appendBundleNames) { auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), [&bundleName](const auto &obj) { return obj == bundleName; }); @@ -385,41 +454,80 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vectorIncreaseSessionCnt(); + if (session_ == nullptr || isCleanService_.load()) { + HILOGE("Init Incremental backup session error, session is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); if (userId != DEFAULT_INVAL_VALUE) { /* multi user scenario */ session_->SetSessionUserId(userId); + } else { + session_->SetSessionUserId(GetUserIdDefault()); } VerifyCaller(IServiceReverse::Scenario::RESTORE); std::vector bundleNamesOnly; + std::map isClearDataFlags; std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, userId); - auto restoreInfos = GetRestoreBundleNames(move(fd), session_, bundleNamesOnly); + BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + session_->GetSessionUserId(), isClearDataFlags); + auto restoreInfos = GetRestoreBundleNames(move(fd), session_, bundleNames); auto restoreBundleNames = SvcRestoreDepsManager::GetInstance().GetRestoreBundleNames(restoreInfos, restoreType); HandleExceptionOnAppendBundles(session_, bundleNames, restoreBundleNames); if (restoreBundleNames.empty()) { HILOGE("AppendBundlesRestoreSession failed, restoreBundleNames is empty."); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } session_->AppendBundles(restoreBundleNames); - SetCurrentSessProperties(restoreInfos, restoreBundleNames, bundleNameDetailMap, restoreType); + SetCurrentSessProperties(restoreInfos, restoreBundleNames, bundleNameDetailMap, + isClearDataFlags, restoreType); OnStartSched(); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("End"); return BError(BError::Codes::OK); } catch (const BError &e) { HILOGE("Catch exception"); HandleExceptionOnAppendBundles(session_, bundleNames, {}); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return e.GetCode(); } catch (...) { HILOGE("Unexpected exception"); HandleExceptionOnAppendBundles(session_, bundleNames, {}); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return EPERM; } } +void Service::SetCurrentSessProperties(std::vector &restoreBundleInfos, + std::vector &restoreBundleNames, RestoreTypeEnum restoreType) +{ + HILOGI("Start"); + for (auto restoreInfo : restoreBundleInfos) { + auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), + [&restoreInfo](const auto &bundleName) { return bundleName == restoreInfo.name; }); + if (it == restoreBundleNames.end()) { + throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Can't find bundle name"); + } + HILOGI("bundleName: %{public}s, extensionName: %{public}s", restoreInfo.name.c_str(), + restoreInfo.extensionName.c_str()); + if ((restoreInfo.allToBackup == false && !SpecialVersion(restoreInfo.versionName)) || + (restoreInfo.extensionName.empty() && !SAUtils::IsSABundleName(restoreInfo.name))) { + OnBundleStarted(BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), session_, restoreInfo.name); + session_->RemoveExtInfo(restoreInfo.name); + continue; + } + session_->SetBundleRestoreType(restoreInfo.name, restoreType); + session_->SetBundleVersionCode(restoreInfo.name, restoreInfo.versionCode); + session_->SetBundleVersionName(restoreInfo.name, restoreInfo.versionName); + session_->SetBundleDataSize(restoreInfo.name, restoreInfo.spaceOccupied); + session_->SetBackupExtName(restoreInfo.name, restoreInfo.extensionName); + if (BundleMgrAdapter::IsUser0BundleName(restoreInfo.name, session_->GetSessionUserId())) { + SendUserIdToApp(restoreInfo.name, session_->GetSessionUserId()); + } + } + HILOGI("End"); +} + ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vector &bundleNames, RestoreTypeEnum restoreType, @@ -427,103 +535,123 @@ ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { - session_->IncreaseSessionCnt(); + if (session_ == nullptr || isCleanService_.load()) { + HILOGE("Init Incremental backup session error, session is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); if (userId != DEFAULT_INVAL_VALUE) { /* multi user scenario */ session_->SetSessionUserId(userId); + } else { + session_->SetSessionUserId(GetUserIdDefault()); } VerifyCaller(IServiceReverse::Scenario::RESTORE); auto restoreInfos = GetRestoreBundleNames(move(fd), session_, bundleNames); auto restoreBundleNames = SvcRestoreDepsManager::GetInstance().GetRestoreBundleNames(restoreInfos, restoreType); + HandleExceptionOnAppendBundles(session_, bundleNames, restoreBundleNames); if (restoreBundleNames.empty()) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGW("RestoreBundleNames is empty."); return BError(BError::Codes::OK); } session_->AppendBundles(restoreBundleNames); - for (auto restoreInfo : restoreInfos) { - auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), - [&restoreInfo](const auto &bundleName) { return bundleName == restoreInfo.name; }); - if (it == restoreBundleNames.end()) { - throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Can't find bundle name"); - } - HILOGI("bundleName: %{public}s, extensionName: %{public}s", restoreInfo.name.c_str(), - restoreInfo.extensionName.c_str()); - if ((restoreInfo.allToBackup == false && !SpecialVersion(restoreInfo.versionName)) || - (restoreInfo.extensionName.empty() && !SAUtils::IsSABundleName(restoreInfo.name))) { - OnBundleStarted(BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), session_, restoreInfo.name); - session_->RemoveExtInfo(restoreInfo.name); - continue; - } - session_->SetBundleRestoreType(restoreInfo.name, restoreType); - session_->SetBundleVersionCode(restoreInfo.name, restoreInfo.versionCode); - session_->SetBundleVersionName(restoreInfo.name, restoreInfo.versionName); - session_->SetBundleDataSize(restoreInfo.name, restoreInfo.spaceOccupied); - session_->SetBackupExtName(restoreInfo.name, restoreInfo.extensionName); - } + SetCurrentSessProperties(restoreInfos, restoreBundleNames, restoreType); OnStartSched(); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (const BError &e) { - session_->DecreaseSessionCnt(); + HILOGE("Catch exception"); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return e.GetCode(); } catch (...) { - session_->DecreaseSessionCnt(); - HILOGI("Unexpected exception"); + HILOGE("Unexpected exception"); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return EPERM; } } void Service::SetCurrentSessProperties(std::vector &restoreBundleInfos, std::vector &restoreBundleNames, - std::map> &bundleNameDetailMap, RestoreTypeEnum restoreType) + std::map> &bundleNameDetailMap, + std::map &isClearDataFlags, RestoreTypeEnum restoreType) { HILOGI("Start"); for (auto restoreInfo : restoreBundleInfos) { auto it = find_if(restoreBundleNames.begin(), restoreBundleNames.end(), - [&restoreInfo](const auto &bundleName) { return bundleName == restoreInfo.name; }); + [&restoreInfo](const auto &bundleName) { + std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name, + restoreInfo.appIndex); + return bundleName == bundleNameIndexInfo; + }); if (it == restoreBundleNames.end()) { throw BError(BError::Codes::SA_BUNDLE_INFO_EMPTY, "Can't find bundle name"); } HILOGD("bundleName: %{public}s, extensionName: %{public}s", restoreInfo.name.c_str(), restoreInfo.extensionName.c_str()); + std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(restoreInfo.name, restoreInfo.appIndex); if ((restoreInfo.allToBackup == false && !SpecialVersion(restoreInfo.versionName)) || (restoreInfo.extensionName.empty() && !SAUtils::IsSABundleName(restoreInfo.name))) { OnBundleStarted(BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), session_, restoreInfo.name); - session_->RemoveExtInfo(restoreInfo.name); + session_->RemoveExtInfo(bundleNameIndexInfo); continue; } - session_->SetBundleRestoreType(restoreInfo.name, restoreType); - session_->SetBundleVersionCode(restoreInfo.name, restoreInfo.versionCode); - session_->SetBundleVersionName(restoreInfo.name, restoreInfo.versionName); - session_->SetBundleDataSize(restoreInfo.name, restoreInfo.spaceOccupied); - session_->SetBackupExtName(restoreInfo.name, restoreInfo.extensionName); + session_->SetBundleRestoreType(bundleNameIndexInfo, restoreType); + session_->SetBundleVersionCode(bundleNameIndexInfo, restoreInfo.versionCode); + session_->SetBundleVersionName(bundleNameIndexInfo, restoreInfo.versionName); + session_->SetBundleDataSize(bundleNameIndexInfo, restoreInfo.spaceOccupied); + session_->SetBackupExtName(bundleNameIndexInfo, restoreInfo.extensionName); + auto iter = isClearDataFlags.find(bundleNameIndexInfo); + if (iter != isClearDataFlags.end()) { + session_->SetClearDataFlag(bundleNameIndexInfo, iter->second); + } BJsonUtil::BundleDetailInfo broadCastInfo; BJsonUtil::BundleDetailInfo uniCastInfo; - bool broadCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, restoreInfo.name, BROADCAST_TYPE, + bool broadCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, BROADCAST_TYPE, broadCastInfo); if (broadCastRet) { bool notifyRet = DelayedSingleton::GetInstance()->NotifyBundleDetail(broadCastInfo); HILOGI("Publish event end, notify result is:%{public}d", notifyRet); } - bool uniCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, restoreInfo.name, UNICAST_TYPE, + bool uniCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, bundleNameIndexInfo, UNICAST_TYPE, uniCastInfo); if (uniCastRet) { HILOGI("current bundle, unicast info:%{public}s", GetAnonyString(uniCastInfo.detail).c_str()); - session_->SetBackupExtInfo(restoreInfo.name, uniCastInfo.detail); + session_->SetBackupExtInfo(bundleNameIndexInfo, uniCastInfo.detail); } } HILOGI("End"); } +void Service::SetCurrentSessProperties(BJsonEntityCaps::BundleInfo &info, + std::map &isClearDataFlags) +{ + if (session_ == nullptr) { + return; + } + session_->SetBundleDataSize(info.name, info.spaceOccupied); + session_->SetBackupExtName(info.name, info.extensionName); + auto iter = isClearDataFlags.find(info.name); + if (iter != isClearDataFlags.end()) { + session_->SetClearDataFlag(info.name, iter->second); + } +} + ErrCode Service::AppendBundlesBackupSession(const vector &bundleNames) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { - session_->IncreaseSessionCnt(); // BundleMgrAdapter::GetBundleInfos可能耗时 + if (session_ == nullptr || isCleanService_.load()) { + HILOGE("Init Incremental backup session error, session is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 VerifyCaller(IServiceReverse::Scenario::BACKUP); auto backupInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session_->GetSessionUserId()); session_->AppendBundles(bundleNames); + SetCurrentBackupSessProperties(bundleNames, session_->GetSessionUserId()); for (auto info : backupInfos) { session_->SetBundleDataSize(info.name, info.spaceOccupied); session_->SetBackupExtName(info.name, info.extensionName); @@ -534,19 +662,22 @@ ErrCode Service::AppendBundlesBackupSession(const vector &bundleName } } OnStartSched(); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (const BError &e) { - session_->DecreaseSessionCnt(); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("Failed, errCode = %{public}d", e.GetCode()); return e.GetCode(); } catch (const exception &e) { - session_->DecreaseSessionCnt(); - HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); return EPERM; } catch (...) { - session_->DecreaseSessionCnt(); - HILOGI("Unexpected exception"); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + HILOGE("Unexpected exception"); return EPERM; } } @@ -556,43 +687,49 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { - session_->IncreaseSessionCnt(); // BundleMgrAdapter::GetBundleInfos可能耗时 + if (session_ == nullptr || isCleanService_.load()) { + HILOGE("Init Incremental backup session error, session is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 VerifyCaller(IServiceReverse::Scenario::BACKUP); std::vector bundleNamesOnly; + std::map isClearDataFlags; std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, session_->GetSessionUserId()); + BJsonUtil::BuildBundleInfos(bundleNames, bundleInfos, bundleNamesOnly, + session_->GetSessionUserId(), isClearDataFlags); auto backupInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session_->GetSessionUserId()); session_->AppendBundles(bundleNames); for (auto info : backupInfos) { - session_->SetBundleDataSize(info.name, info.spaceOccupied); - session_->SetBackupExtName(info.name, info.extensionName); + SetCurrentSessProperties(info, isClearDataFlags); if (info.allToBackup == false) { session_->GetServiceReverseProxy()->BackupOnBundleStarted( BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), info.name); session_->RemoveExtInfo(info.name); } BJsonUtil::BundleDetailInfo uniCastInfo; - bool uniCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, info.name, UNICAST_TYPE, - uniCastInfo); - if (uniCastRet) { + if (BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, info.name, UNICAST_TYPE, uniCastInfo)) { HILOGI("current bundle, unicast info:%{public}s", GetAnonyString(uniCastInfo.detail).c_str()); session_->SetBackupExtInfo(info.name, uniCastInfo.detail); } } OnStartSched(); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (const BError &e) { - session_->DecreaseSessionCnt(); HILOGE("Failed, errCode = %{public}d", e.GetCode()); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return e.GetCode(); } catch (const exception &e) { - session_->DecreaseSessionCnt(); HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return EPERM; } catch(...) { - session_->DecreaseSessionCnt(); HILOGE("Unexpected exception"); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return EPERM; } } @@ -600,10 +737,16 @@ ErrCode Service::AppendBundlesDetailsBackupSession(const vector &bun ErrCode Service::Finish() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - VerifyCaller(session_->GetScenario()); - session_->Finish(); - OnAllBundlesFinished(BError(BError::Codes::OK)); - return BError(BError::Codes::OK); + try { + VerifyCaller(session_->GetScenario()); + session_->Finish(); + OnAllBundlesFinished(BError(BError::Codes::OK)); + return BError(BError::Codes::OK); + } catch (const BError &e) { + ReleaseOnException(); + HILOGE("Failde to Finish"); + return e.GetCode(); + } } ErrCode Service::PublishFile(const BFileInfo &fileInfo) @@ -671,7 +814,8 @@ ErrCode Service::AppFileReady(const string &fileName, UniqueFd fd, int32_t errCo // 通知extension清空缓存 proxy->HandleClear(); // 清除Timer - session_->BundleExtTimerStop(callerName); + session_->StopFwkTimer(callerName); + session_->StopExtTimer(callerName); // 通知TOOL 备份完成 session_->GetServiceReverseProxy()->BackupOnBundleFinished(BError(BError::Codes::OK), callerName); // 断开extension @@ -712,17 +856,20 @@ ErrCode Service::AppDone(ErrCode errCode) throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); } proxy->HandleClear(); - session_->BundleExtTimerStop(callerName); - NotifyCallerCurAppDone(errCode, callerName); + session_->StopFwkTimer(callerName); + session_->StopExtTimer(callerName); backUpConnection->DisconnectBackupExtAbility(); ClearSessionAndSchedInfo(callerName); + NotifyCallerCurAppDone(errCode, callerName); } OnAllBundlesFinished(BError(BError::Codes::OK)); return BError(BError::Codes::OK); } catch (const BError &e) { + ReleaseOnException(); HILOGE("AppDone error, err code is: %{public}d", e.GetCode()); return e.GetCode(); // 任意异常产生,终止监听该任务 } catch (const exception &e) { + ReleaseOnException(); HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); return EPERM; } catch (...) { @@ -734,28 +881,31 @@ ErrCode Service::AppDone(ErrCode errCode) ErrCode Service::ServiceResultReport(const std::string restoreRetInfo, BackupRestoreScenario sennario, ErrCode errCode) { + string callerName = ""; HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { - string callerName = VerifyCallerAndGetCallerName(); + callerName = VerifyCallerAndGetCallerName(); if (sennario == BackupRestoreScenario::FULL_RESTORE) { session_->GetServiceReverseProxy()->RestoreOnResultReport(restoreRetInfo, callerName, errCode); - NotifyCloneBundleFinish(callerName); + NotifyCloneBundleFinish(callerName, sennario); } else if (sennario == BackupRestoreScenario::INCREMENTAL_RESTORE) { session_->GetServiceReverseProxy()->IncrementalRestoreOnResultReport(restoreRetInfo, callerName, errCode); - NotifyCloneBundleFinish(callerName); + NotifyCloneBundleFinish(callerName, sennario); } else if (sennario == BackupRestoreScenario::FULL_BACKUP) { session_->GetServiceReverseProxy()->BackupOnResultReport(restoreRetInfo, callerName); } else if (sennario == BackupRestoreScenario::INCREMENTAL_BACKUP) { session_->GetServiceReverseProxy()->IncrementalBackupOnResultReport(restoreRetInfo, callerName); } - return BError(BError::Codes::OK); } catch (const BError &e) { + NotifyCloneBundleFinish(callerName, sennario); return e.GetCode(); // 任意异常产生,终止监听该任务 } catch (const exception &e) { + NotifyCloneBundleFinish(callerName, sennario); HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); return EPERM; } catch (...) { + NotifyCloneBundleFinish(callerName, sennario); HILOGI("Unexpected exception"); return EPERM; } @@ -777,24 +927,55 @@ ErrCode Service::SAResultReport(const std::string bundleName, const std::string return SADone(errCode, bundleName); } -void Service::NotifyCloneBundleFinish(std::string bundleName) +void Service::NotifyCloneBundleFinish(std::string bundleName, const BackupRestoreScenario sennario) { - if (session_->OnBundleFileReady(bundleName)) { - auto backUpConnection = session_->GetExtConnection(bundleName); - if (backUpConnection == nullptr) { - throw BError(BError::Codes::SA_INVAL_ARG, "backUpConnection is empty"); + try { + if (sennario != BackupRestoreScenario::FULL_RESTORE && + sennario != BackupRestoreScenario::INCREMENTAL_RESTORE) { + return; } - auto proxy = backUpConnection->GetBackupExtProxy(); - if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + if (session_->OnBundleFileReady(bundleName)) { + auto backUpConnection = session_->GetExtConnection(bundleName); + if (backUpConnection == nullptr) { + throw BError(BError::Codes::SA_INVAL_ARG, "backUpConnection is empty"); + } + auto proxy = backUpConnection->GetBackupExtProxy(); + if (!proxy) { + throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + } + proxy->HandleClear(); + session_->StopFwkTimer(bundleName); + session_->StopExtTimer(bundleName); + backUpConnection->DisconnectBackupExtAbility(); + ClearSessionAndSchedInfo(bundleName); } - proxy->HandleClear(); - session_->BundleExtTimerStop(bundleName); - backUpConnection->DisconnectBackupExtAbility(); - ClearSessionAndSchedInfo(bundleName); + SendEndAppGalleryNotify(bundleName); + OnAllBundlesFinished(BError(BError::Codes::OK)); + } catch (...) { + HILOGI("Unexpected exception"); + ReleaseOnException(); } - SendEndAppGalleryNotify(bundleName); - OnAllBundlesFinished(BError(BError::Codes::OK)); +} + +void Service::SetWant(AAFwk::Want &want, const BundleName &bundleName, const BConstants::ExtensionAction &action) +{ + BJsonUtil::BundleDetailInfo bundleDetail = BJsonUtil::ParseBundleNameIndexStr(bundleName); + string backupExtName = session_->GetBackupExtName(bundleName); /* new device app ext name */ + HILOGI("BackupExtName: %{public}s, bundleName: %{public}s", backupExtName.data(), bundleName.data()); + string versionName = session_->GetBundleVersionName(bundleName); /* old device app version name */ + int64_t versionCode = session_->GetBundleVersionCode(bundleName); /* old device app version code */ + RestoreTypeEnum restoreType = session_->GetBundleRestoreType(bundleName); /* app restore type */ + string bundleExtInfo = session_->GetBackupExtInfo(bundleName); + HILOGI("BundleExtInfo is:%{public}s", GetAnonyString(bundleExtInfo).c_str()); + + want.SetElementName(bundleDetail.bundleName, backupExtName); + want.SetParam(BConstants::EXTENSION_ACTION_PARA, static_cast(action)); + want.SetParam(BConstants::EXTENSION_VERSION_CODE_PARA, static_cast(versionCode)); + want.SetParam(BConstants::EXTENSION_RESTORE_TYPE_PARA, static_cast(restoreType)); + want.SetParam(BConstants::EXTENSION_VERSION_NAME_PARA, versionName); + want.SetParam(BConstants::EXTENSION_RESTORE_EXT_INFO_PARA, bundleExtInfo); + want.SetParam(BConstants::EXTENSION_BACKUP_EXT_INFO_PARA, bundleExtInfo); + want.SetParam(BConstants::EXTENSION_APP_CLONE_INDEX_PARA, bundleDetail.bundleIndex); } ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) @@ -804,7 +985,7 @@ ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) HILOGI("begin %{public}s", bundleName.data()); IServiceReverse::Scenario scenario = session_->GetScenario(); BConstants::ExtensionAction action; - if (scenario == IServiceReverse::Scenario::BACKUP) { + if (scenario == IServiceReverse::Scenario::BACKUP || scenario == IServiceReverse::Scenario::CLEAN) { action = BConstants::ExtensionAction::BACKUP; } else if (scenario == IServiceReverse::Scenario::RESTORE) { action = BConstants::ExtensionAction::RESTORE; @@ -815,29 +996,22 @@ ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) return LaunchBackupSAExtension(bundleName); } AAFwk::Want want; - string backupExtName = session_->GetBackupExtName(bundleName); /* new device app ext name */ - HILOGD("backupExtName: %{public}s, bundleName: %{public}s", backupExtName.data(), bundleName.data()); - string versionName = session_->GetBundleVersionName(bundleName); /* old device app version name */ - int64_t versionCode = session_->GetBundleVersionCode(bundleName); /* old device app version code */ - RestoreTypeEnum restoreType = session_->GetBundleRestoreType(bundleName); /* app restore type */ - string bundleExtInfo = session_->GetBackupExtInfo(bundleName); - HILOGI("bundleExtInfo is:%{public}s", GetAnonyString(bundleExtInfo).c_str()); - - want.SetElementName(bundleName, backupExtName); - want.SetParam(BConstants::EXTENSION_ACTION_PARA, static_cast(action)); - want.SetParam(BConstants::EXTENSION_VERSION_CODE_PARA, static_cast(versionCode)); - want.SetParam(BConstants::EXTENSION_RESTORE_TYPE_PARA, static_cast(restoreType)); - want.SetParam(BConstants::EXTENSION_VERSION_NAME_PARA, versionName); - want.SetParam(BConstants::EXTENSION_RESTORE_EXT_INFO_PARA, bundleExtInfo); - want.SetParam(BConstants::EXTENSION_BACKUP_EXT_INFO_PARA, bundleExtInfo); - + SetWant(want, bundleName, action); auto backUpConnection = session_->GetExtConnection(bundleName); if (backUpConnection == nullptr) { HILOGE("LaunchBackupExtension error, backUpConnection is empty"); return BError(BError::Codes::SA_INVAL_ARG); } + if (backUpConnection->IsExtAbilityConnected() && !backUpConnection->WaitDisconnectDone()) { + HILOGE("LaunchBackupExtension error, WaitDisconnectDone failed"); + return BError(BError::Codes::SA_INVAL_ARG); + } ErrCode ret = backUpConnection->ConnectBackupExtAbility(want, session_->GetSessionUserId()); - return ret; + if (ret) { + HILOGE("ConnectBackupExtAbility faild, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), ret); + return BError(BError::Codes::SA_BOOT_EXT_FAIL); + } + return BError(BError::Codes::OK); } catch (const BError &e) { return e.GetCode(); } catch (const exception &e) { @@ -893,6 +1067,11 @@ ErrCode Service::GetFileHandle(const string &bundleName, const string &fileName) } int32_t errCode = 0; UniqueFd fd = proxy->GetFileHandle(fileName, errCode); + if (errCode != ERR_OK) { + AppRadar::Info info (bundleName, "", ""); + AppRadar::GetInstance().RecordRestoreFuncRes(info, "Service::GetFileHandle", GetUserIdDefault(), + BizStageRestore::BIZ_STAGE_GET_FILE_HANDLE_FAIL, errCode); + } session_->GetServiceReverseProxy()->RestoreOnFileReady(bundleName, fileName, move(fd), errCode); } else { session_->SetExtFileNameRequest(bundleName, fileName); @@ -912,41 +1091,21 @@ ErrCode Service::GetFileHandle(const string &bundleName, const string &fileName) void Service::OnBackupExtensionDied(const string &&bundleName) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + AppRadar::Info info (bundleName, "", ""); + if (session_->GetScenario() == IServiceReverse::Scenario::BACKUP) { + AppRadar::GetInstance().RecordBackupFuncRes(info, "Service::OnBackupExtensionDied", GetUserIdDefault(), + BizStageBackup::BIZ_STAGE_EXTENSION_ABNORMAL_EXIT, BError(BError::Codes::EXT_ABILITY_DIED).GetCode()); + } else if (session_->GetScenario() == IServiceReverse::Scenario::RESTORE) { + AppRadar::GetInstance().RecordRestoreFuncRes(info, "Service::OnBackupExtensionDied", GetUserIdDefault(), + BizStageRestore::BIZ_STAGE_EXTENSION_ABNORMAL_EXIT, BError(BError::Codes::EXT_ABILITY_DIED).GetCode()); + } try { string callName = move(bundleName); HILOGE("Backup <%{public}s> Extension Process Died", callName.c_str()); session_->VerifyBundleName(callName); - string versionName = session_->GetBundleVersionName(bundleName); /* old device app version name */ - string versionNameFlag = - versionName.substr(0, versionName.find_first_of(BConstants::VERSION_NAME_SEPARATOR_CHAR)); - if (versionNameFlag == BConstants::DEFAULT_VERSION_NAME && - session_->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_READDY)) { - ExtConnectDied(bundleName); - return; - } // 重新连接清理缓存 - HILOGE("Clear backup extension data, bundleName: %{public}s", bundleName.data()); - auto backUpConnection = session_->GetExtConnection(bundleName); - auto callConnected = [ptr {wptr(this)}](const string &&bundleName) { - HILOGE("OnBackupExtensionDied callConnected <%{public}s>", bundleName.c_str()); - auto thisPtr = ptr.promote(); - if (!thisPtr) { - HILOGW("this pointer is null."); - return; - } - thisPtr->ExtConnectDied(bundleName); - }; - if (backUpConnection == nullptr) { - HILOGE("OnBackupExtensionDied error. backUpConnection is empty"); - ExtConnectDied(bundleName); - return; - } - backUpConnection->SetCallback(callConnected); - auto ret = LaunchBackupExtension(bundleName); - if (ret) { - ExtConnectDied(bundleName); - return; - } + HILOGI("Clear backup extension data, bundleName: %{public}s", callName.c_str()); + ExtConnectDied(callName); } catch (...) { HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str()); ExtConnectDied(bundleName); @@ -960,13 +1119,18 @@ void Service::ExtConnectDied(const string &callName) try { HILOGI("Begin, bundleName: %{public}s", callName.c_str()); /* Clear Timer */ - session_->BundleExtTimerStop(callName); + session_->StopFwkTimer(callName); + session_->StopExtTimer(callName); auto backUpConnection = session_->GetExtConnection(callName); if (backUpConnection != nullptr && backUpConnection->IsExtAbilityConnected()) { backUpConnection->DisconnectBackupExtAbility(); } - /* Clear Session before notice client finish event */ - ClearSessionAndSchedInfo(callName); + session_->SetServiceSchedAction(callName, BConstants::ServiceSchedAction::CLEAN); + auto ret = LaunchBackupExtension(callName); + if (ret) { + /* Clear Session before notice client finish event */ + ClearSessionAndSchedInfo(callName); + } /* Notice Client Ext Ability Process Died */ NoticeClientFinish(callName, BError(BError::Codes::EXT_ABILITY_DIED)); } catch (...) { @@ -998,8 +1162,10 @@ void Service::ExtStart(const string &bundleName) if (!proxy) { throw BError(BError::Codes::SA_INVAL_ARG, "ExtStart bundle task error, Extension backup Proxy is empty"); } + std::string name = bundleName; + proxy->UpdateFdSendRate(name, DEFAULT_FD_SEND_RATE); if (scenario == IServiceReverse::Scenario::BACKUP) { - auto ret = proxy->HandleBackup(); + auto ret = proxy->HandleBackup(session_->GetClearDataFlag(bundleName)); session_->GetServiceReverseProxy()->BackupOnBundleStarted(ret, bundleName); if (ret) { ClearSessionAndSchedInfo(bundleName); @@ -1010,7 +1176,7 @@ void Service::ExtStart(const string &bundleName) if (scenario != IServiceReverse::Scenario::RESTORE) { throw BError(BError::Codes::SA_INVAL_ARG, "Failed to scenario"); } - auto ret = proxy->HandleRestore(); + auto ret = proxy->HandleRestore(session_->GetClearDataFlag(bundleName)); session_->GetServiceReverseProxy()->RestoreOnBundleStarted(ret, bundleName); auto fileNameVec = session_->GetExtFileNameRequest(bundleName); for (auto &fileName : fileNameVec) { @@ -1038,12 +1204,14 @@ int Service::Dump(int fd, const vector &args) return 0; } -void Service::ExtConnectFailed(const string &bundleName, ErrCode ret) +void Service::ReportOnExtConnectFailed(const IServiceReverse::Scenario scenario, + const std::string &bundleName, const ErrCode ret) { - HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { - HILOGE("begin %{public}s", bundleName.data()); - IServiceReverse::Scenario scenario = session_->GetScenario(); + if (session_ == nullptr) { + HILOGE("Report extConnectfailed error, session info is empty"); + return; + } if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted(ret, bundleName); } else if (scenario == IServiceReverse::Scenario::RESTORE && @@ -1058,11 +1226,31 @@ void Service::ExtConnectFailed(const string &bundleName, ErrCode ret) session_->GetServiceReverseProxy()->BackupOnBundleStarted(ret, bundleName); } else if (scenario == IServiceReverse::Scenario::RESTORE) { session_->GetServiceReverseProxy()->RestoreOnBundleStarted(ret, bundleName); - DisposeErr disposeErr = AppGalleryDisposeProxy::GetInstance()->EndRestore(bundleName); HILOGI("ExtConnectFailed EndRestore, code=%{public}d, bundleName=%{public}s", disposeErr, bundleName.c_str()); } + } catch (...) { + HILOGE("Report extConnectfailed error"); + } +} + +void Service::ExtConnectFailed(const string &bundleName, ErrCode ret) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + IServiceReverse::Scenario scenario = IServiceReverse::Scenario::UNDEFINED; + try { + HILOGE("begin %{public}s", bundleName.data()); + scenario = session_->GetScenario(); + AppRadar::Info info (bundleName, "", ""); + if (scenario == IServiceReverse::Scenario::BACKUP) { + AppRadar::GetInstance().RecordBackupFuncRes(info, "Service::ExtConnectFailed", GetUserIdDefault(), + BizStageBackup::BIZ_STAGE_CONNECT_EXTENSION_FAIL, ret); + } else if (scenario == IServiceReverse::Scenario::RESTORE) { + AppRadar::GetInstance().RecordRestoreFuncRes(info, "Service::ExtConnectFailed", GetUserIdDefault(), + BizStageRestore::BIZ_STAGE_CONNECT_EXTENSION_FAIL, ret); + } + ReportOnExtConnectFailed(scenario, bundleName, ret); ClearSessionAndSchedInfo(bundleName); NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_DIED)); return; @@ -1096,7 +1284,10 @@ void Service::NoticeClientFinish(const string &bundleName, ErrCode errCode) }; /* If all bundle ext process finish, notice client. */ OnAllBundlesFinished(BError(BError::Codes::OK)); + } catch(const BError &e) { + ReleaseOnException(); } catch (...) { + ReleaseOnException(); HILOGI("Unexpected exception"); return; } @@ -1105,45 +1296,28 @@ void Service::NoticeClientFinish(const string &bundleName, ErrCode errCode) void Service::ExtConnectDone(string bundleName) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); - auto timeoutCallback = [ptr {wptr(this)}, bundleName]() { - HILOGI("begin timeoutCallback bundleName = %{public}s", bundleName.c_str()); - auto thisPtr = ptr.promote(); - if (!thisPtr) { - HILOGE("ServicePtr is nullptr."); - return; + try { + HILOGE("begin %{public}s", bundleName.data()); + auto timeoutCallback = TimeOutCallback(wptr(this), bundleName); + auto scenario = session_->GetScenario(); + if (scenario == IServiceReverse::Scenario::BACKUP) { + session_->StartExtTimer(bundleName, timeoutCallback); + } else if (scenario == IServiceReverse::Scenario::RESTORE) { + session_->StartFwkTimer(bundleName, timeoutCallback); } - auto sessionPtr = ptr->session_; - if (sessionPtr == nullptr) { - HILOGE("SessionPtr is nullptr."); + + BConstants::ServiceSchedAction curSchedAction = session_->GetServiceSchedAction(bundleName); + if (curSchedAction == BConstants::ServiceSchedAction::CLEAN) { + sched_->Sched(bundleName); return; } - try { - if (SAUtils::IsSABundleName(bundleName)) { - auto sessionConnection = sessionPtr->GetSAExtConnection(bundleName); - shared_ptr saConnection = sessionConnection.lock(); - if (saConnection == nullptr) { - HILOGE("lock sa connection ptr is nullptr"); - return; - } - sessionPtr->BundleExtTimerStop(bundleName); - saConnection->DisconnectBackupSAExt(); - } else { - auto sessionConnection = sessionPtr->GetExtConnection(bundleName); - sessionPtr->BundleExtTimerStop(bundleName); - sessionConnection->DisconnectBackupExtAbility(); - } - thisPtr->ClearSessionAndSchedInfo(bundleName); - thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT)); - } catch (...) { - HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str()); - thisPtr->ClearSessionAndSchedInfo(bundleName); - thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT)); + if (curSchedAction == BConstants::ServiceSchedAction::START && + clearRecorder_->FindClearBundleRecord(bundleName)) { + session_->SetServiceSchedAction(bundleName, BConstants::ServiceSchedAction::CLEAN); + } else { + session_->SetServiceSchedAction(bundleName, BConstants::ServiceSchedAction::RUNNING); + AddClearBundleRecord(bundleName); } - }; - try { - HILOGE("begin %{public}s", bundleName.data()); - session_->BundleExtTimerStart(bundleName, timeoutCallback); - session_->SetServiceSchedAction(bundleName, BConstants::ServiceSchedAction::RUNNING); sched_->Sched(bundleName); } catch (...) { HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str()); @@ -1161,6 +1335,7 @@ void Service::ClearSessionAndSchedInfo(const string &bundleName) session_->RemoveExtInfo(bundleName); sched_->RemoveExtConn(bundleName); HandleRestoreDepsBundle(bundleName); + DelClearBundleRecord({bundleName}); sched_->Sched(); } catch (const BError &e) { return; @@ -1219,6 +1394,9 @@ void Service::OnAllBundlesFinished(ErrCode errCode) HILOGI("called begin."); if (session_->IsOnAllBundlesFinished()) { IServiceReverse::Scenario scenario = session_->GetScenario(); + if (isInRelease_.load() && (scenario == IServiceReverse::Scenario::RESTORE)) { + SessionDeactive(); + } if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { session_->GetServiceReverseProxy()->IncrementalBackupOnAllBundlesFinished(errCode); } else if (scenario == IServiceReverse::Scenario::RESTORE && @@ -1250,17 +1428,14 @@ void Service::OnStartSched() void Service::SendStartAppGalleryNotify(const BundleName &bundleName) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + if (SAUtils::IsSABundleName(bundleName)) { + HILOGI("SA does not need to StartRestore"); + return ; + } IServiceReverse::Scenario scenario = session_->GetScenario(); if (scenario != IServiceReverse::Scenario::RESTORE) { return ; } - string work_status = system::GetParameter(BACKUPSERVICE_WORK_STATUS_KEY, ""); - HILOGI("Param %{public}s value is %{public}s", BACKUPSERVICE_WORK_STATUS_KEY.c_str(), work_status.c_str()); - if (work_status.compare(BACKUPSERVICE_WORK_STATUS_OFF) == 0) { - bool isSetSucc = system::SetParameter(BACKUPSERVICE_WORK_STATUS_KEY, BACKUPSERVICE_WORK_STATUS_ON); - HILOGI("SetParameter %{public}s true end, result %{public}d.", BACKUPSERVICE_WORK_STATUS_KEY.c_str(), - isSetSucc); - } if (!disposal_->IfBundleNameInDisposalConfigFile(bundleName)) { HILOGE("WriteDisposalConfigFile Failed"); return ; @@ -1274,6 +1449,10 @@ void Service::SendStartAppGalleryNotify(const BundleName &bundleName) void Service::SendEndAppGalleryNotify(const BundleName &bundleName) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + if (SAUtils::IsSABundleName(bundleName)) { + HILOGI("SA does not need to EndRestore"); + return ; + } IServiceReverse::Scenario scenario = session_->GetScenario(); if (scenario != IServiceReverse::Scenario::RESTORE) { return ; @@ -1310,7 +1489,11 @@ void Service::SendErrAppGalleryNotify() HILOGI("EndRestore, code=%{public}d, bundleName=%{public}s", disposeErr, bundleName.c_str()); if (disposeErr != DisposeErr::OK) { - HILOGE("Error,disposal will be clear in the end"); + HILOGE("Error, disposal will be clear in the end"); + return ; + } + if (!disposal_->DeleteFromDisposalConfigFile(bundleName)) { + HILOGE("DeleteFromDisposalConfigFile Failed, bundleName=%{public}s", bundleName.c_str()); return ; } } @@ -1326,6 +1509,14 @@ void Service::ClearDisposalOnSaStart() DisposeErr disposeErr = AppGalleryDisposeProxy::GetInstance()->EndRestore(bundleName); HILOGI("EndRestore, code=%{public}d, bundleName=%{public}s", disposeErr, bundleName.c_str()); + if (disposeErr != DisposeErr::OK) { + HILOGE("Error, disposal will be clear in the end"); + return ; + } + if (!disposal_->DeleteFromDisposalConfigFile(bundleName)) { + HILOGE("DeleteFromDisposalConfigFile Failed, bundleName=%{public}s", bundleName.c_str()); + return ; + } } } HILOGI("SA start, All Errdisposal pasitions have been cleared"); @@ -1353,7 +1544,27 @@ void Service::SessionDeactive() HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { HILOGI("Begin"); + isInRelease_.store(true); //清理处置状态 + if (session_ == nullptr) { + HILOGE("Session deactive error, session is empty"); + return; + } + ErrCode ret = BError(BError::Codes::OK); + std::vector bundleNameList; + if (session_->GetScenario() == IServiceReverse::Scenario::RESTORE && + session_->CleanAndCheckIfNeedWait(ret, bundleNameList)) { + if (ret != ERR_OK) { + isRmConfigFile_.store(false); + } + if (!bundleNameList.empty()) { + DelClearBundleRecord(bundleNameList); + } + return; + } + if (!bundleNameList.empty()) { + DelClearBundleRecord(bundleNameList); + } SendErrAppGalleryNotify(); DeleteDisConfigFile(); // 结束定时器 @@ -1367,9 +1578,16 @@ void Service::SessionDeactive() HILOGE("Session deactive error, session is empty"); return; } - session_->ClearSessionData(); - // 卸载服务 - sched_->TryUnloadService(); + ret = session_->ClearSessionData(); + if (clearRecorder_ != nullptr && !ret && isRmConfigFile_.load()) { + clearRecorder_->DeleteConfigFile(); + } + // close session + StopAll(nullptr, true); + if (session_->GetSessionCnt() <= 0) { + HILOGI("do unload Service."); + sched_->TryUnloadService(); + } } catch (...) { HILOGE("Unexpected exception"); return; @@ -1403,59 +1621,190 @@ std::function Service::GetBackupInfoConnectDied(wptr }; } +void Service::ClearResidualBundleData(const std::string &bundleName) +{ + if (session_ == nullptr) { + return ; + } + auto backUpConnection = session_->GetExtConnection(bundleName); + if (backUpConnection == nullptr) { + throw BError(BError::Codes::SA_INVAL_ARG, "backUpConnection is empty"); + } + auto proxy = backUpConnection->GetBackupExtProxy(); + if (!proxy) { + throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + } + // 通知ext清理 + proxy->HandleClear(); + if (backUpConnection->IsExtAbilityConnected()) { + backUpConnection->DisconnectBackupExtAbility(); + } + ClearSessionAndSchedInfo(bundleName); + if (isCleanService_.load() && session_->IsOnAllBundlesFinished()) { + isCleanService_.store(false); + StopAll(nullptr, true); + return ; + } + // 非清理任务,需要上报 + if (session_->GetScenario() != IServiceReverse::Scenario::CLEAN) { + OnAllBundlesFinished(BError(BError::Codes::OK)); + } +} + +ErrCode Service::GetBackupInfoCmdHandle(BundleName &bundleName, std::string &result) +{ + if (session_ == nullptr) { + HILOGE("Get BackupInfo error, session is empty."); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->SetSessionUserId(GetUserIdDefault()); + auto backupConnection = session_->CreateBackupConnection(bundleName); + if (backupConnection == nullptr) { + HILOGE("backupConnection is null. bundleName: %{public}s", bundleName.c_str()); + return BError(BError::Codes::SA_INVAL_ARG); + } + auto callConnected = GetBackupInfoConnectDone(wptr(this), bundleName); + auto callDied = GetBackupInfoConnectDied(wptr(this), bundleName); + backupConnection->SetCallback(callConnected); + backupConnection->SetCallDied(callDied); + AAFwk::Want want = CreateConnectWant(bundleName); + auto ret = backupConnection->ConnectBackupExtAbility(want, session_->GetSessionUserId()); + if (ret) { + HILOGE("ConnectBackupExtAbility faild, bundleName:%{public}s, ret:%{public}d", bundleName.c_str(), ret); + return BError(BError::Codes::SA_BOOT_EXT_FAIL); + } + std::unique_lock lock(getBackupInfoMutx_); + getBackupInfoCondition_.wait_for(lock, std::chrono::seconds(CONNECT_WAIT_TIME_S)); + if (isConnectDied_.load()) { + HILOGE("GetBackupInfoConnectDied, please check bundleName: %{public}s", bundleName.c_str()); + isConnectDied_.store(false); + return BError(BError::Codes::EXT_ABILITY_DIED); + } + auto proxy = backupConnection->GetBackupExtProxy(); + if (!proxy) { + HILOGE("Extension backup Proxy is empty."); + return BError(BError::Codes::SA_INVAL_ARG); + } + ret = proxy->GetBackupInfo(result); + backupConnection->DisconnectBackupExtAbility(); + if (ret != ERR_OK) { + HILOGE("Call Ext GetBackupInfo faild."); + AppRadar::Info info(bundleName, "", "Call Ext GetBackupInfo faild"); + Backup::AppRadar::GetInstance().RecordBackupFuncRes(info, "Service::GetBackupInfoCmdHandle", GetUserIdDefault(), + BizStageBackup::BIZ_STAGE_GET_BACKUP_INFO_FAIL, ret); + return BError(BError::Codes::SA_INVAL_ARG); + } + + return BError(BError::Codes::OK); +} + ErrCode Service::GetBackupInfo(BundleName &bundleName, std::string &result) { try { HILOGI("Service::GetBackupInfo begin."); + if (session_ == nullptr || isCleanService_.load()) { + HILOGE("Get BackupInfo error, session is empty."); + return BError(BError::Codes::SA_INVAL_ARG); + } if (session_->GetImpl().clientToken) { return BError(BError::Codes::SA_REFUSED_ACT, "Already have an active session"); } - session_->IncreaseSessionCnt(); - session_->SetSessionUserId(GetUserIdDefault()); - auto backupConnection = session_->CreateBackupConnection(bundleName); - if (backupConnection == nullptr) { - HILOGE("backupConnection is null. bundleName: %{public}s", bundleName.c_str()); + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); + auto ret = GetBackupInfoCmdHandle(bundleName, result); + HILOGI("Service::GetBackupInfo end. result: %s", result.c_str()); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return ret; + } catch (...) { + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + HILOGI("Unexpected exception"); + return EPERM; + } +} + +ErrCode Service::StartExtTimer(bool &isExtStart) +{ + try { + HILOGI("Service::StartExtTimer begin."); + string bundleName = VerifyCallerAndGetCallerName(); + if (session_ == nullptr) { + HILOGE("StartExtTimer error, session_ is nullptr."); + isExtStart = false; return BError(BError::Codes::SA_INVAL_ARG); } - auto callConnected = GetBackupInfoConnectDone(wptr(this), bundleName); - auto callDied = GetBackupInfoConnectDied(wptr(this), bundleName); - backupConnection->SetCallback(callConnected); - backupConnection->SetCallDied(callDied); - AAFwk::Want want = CreateConnectWant(bundleName); - auto ret = backupConnection->ConnectBackupExtAbility(want, session_->GetSessionUserId()); - if (ret) { - HILOGE("ConnectBackupExtAbility faild, please check bundleName: %{public}s", bundleName.c_str()); - return BError(BError::Codes::EXT_ABILITY_DIED); - } - std::unique_lock lock(getBackupInfoMutx_); - getBackupInfoCondition_.wait_for(lock, std::chrono::seconds(CONNECT_WAIT_TIME_S)); - if (isConnectDied_.load()) { - HILOGE("GetBackupInfoConnectDied, please check bundleName: %{public}s", bundleName.c_str()); - isConnectDied_.store(false); - return BError(BError::Codes::EXT_ABILITY_DIED); - } - auto proxy = backupConnection->GetBackupExtProxy(); - if (!proxy) { - HILOGE("Extension backup Proxy is empty."); + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); + auto timeoutCallback = TimeOutCallback(wptr(this), bundleName); + session_->StopFwkTimer(bundleName); + isExtStart = session_->StartExtTimer(bundleName, timeoutCallback); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return BError(BError::Codes::OK); + } catch (...) { + isExtStart = false; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + HILOGI("Unexpected exception"); + return EPERM; + } +} + +ErrCode Service::StartFwkTimer(bool &isFwkStart) +{ + try { + HILOGI("Service::StartFwkTimer begin."); + string bundleName = VerifyCallerAndGetCallerName(); + if (session_ == nullptr) { + HILOGE("StartFwkTimer error, session_ is nullptr."); + isFwkStart = false; return BError(BError::Codes::SA_INVAL_ARG); } - ret = proxy->GetBackupInfo(result); - backupConnection->DisconnectBackupExtAbility(); - if (ret != ERR_OK) { - HILOGE("Call Ext GetBackupInfo faild."); + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); + auto timeoutCallback = TimeOutCallback(wptr(this), bundleName); + session_->StopExtTimer(bundleName); + isFwkStart = session_->StartFwkTimer(bundleName, timeoutCallback); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return BError(BError::Codes::OK); + } catch (...) { + isFwkStart = false; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + HILOGI("Unexpected exception"); + return EPERM; + } +} + +ErrCode Service::AppendBundlesClearSession(const std::vector &bundleNames) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + try { + if (bundleNames.empty() || session_ == nullptr) { + HILOGE("Init Incremental backup session error, session is empty"); return BError(BError::Codes::SA_INVAL_ARG); } - HILOGI("Service::GetBackupInfo end. result: %s", result.c_str()); - session_->DecreaseSessionCnt(); + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 + auto backupInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session_->GetSessionUserId()); + session_->AppendBundles(bundleNames); + for (auto info : backupInfos) { + session_->SetBackupExtName(info.name, info.extensionName); + } + OnStartSched(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); + } catch (const BError &e) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + HILOGE("Failed, errCode = %{public}d", e.GetCode()); + return e.GetCode(); + } catch (const exception &e) { + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); + return EPERM; } catch (...) { - session_->DecreaseSessionCnt(); - HILOGI("Unexpected exception"); + HandleExceptionOnAppendBundles(session_, bundleNames, {}); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + HILOGE("Unexpected exception"); return EPERM; } } -ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) +ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeout, bool &result) { auto timeoutCallback = [ptr {wptr(this)}, bundleName]() { HILOGE("Backup <%{public}s> Extension Process Timeout", bundleName.c_str()); @@ -1471,7 +1820,8 @@ ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &res } try { auto sessionConnection = sessionPtr->GetExtConnection(bundleName); - sessionPtr->BundleExtTimerStop(bundleName); + sessionPtr->StopFwkTimer(bundleName); + sessionPtr->StopExtTimer(bundleName); sessionConnection->DisconnectBackupExtAbility(); thisPtr->ClearSessionAndSchedInfo(bundleName); thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT)); @@ -1483,14 +1833,19 @@ ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &res }; try { HILOGI("Service::UpdateTimer begin."); + if (session_ == nullptr || isCleanService_.load()) { + HILOGE("Update Timer error, session is empty."); + result = false; + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); VerifyCaller(); - session_->IncreaseSessionCnt(); - result = session_->UpdateTimer(bundleName, timeOut, timeoutCallback); - session_->DecreaseSessionCnt(); + result = session_->UpdateTimer(bundleName, timeout, timeoutCallback); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (...) { result = false; - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return EPERM; } @@ -1498,25 +1853,42 @@ ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &res ErrCode Service::UpdateSendRate(std::string &bundleName, int32_t sendRate, bool &result) { - HILOGI("Begin, bundle name:%{public}s, sendRate is:%{public}d", bundleName.c_str(), sendRate); - VerifyCaller(); - IServiceReverse::Scenario scenario = session_ -> GetScenario(); - if (scenario != IServiceReverse::Scenario::BACKUP) { - HILOGE("This method is applicable to the backup scenario"); - return BError(BError::Codes::SA_INVAL_ARG); - } - auto backupConnection = session_->GetExtConnection(bundleName); - auto proxy = backupConnection->GetBackupExtProxy(); - if (!proxy) { - throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); - } - auto ret = proxy->UpdateFdSendRate(bundleName, sendRate); - if (ret != NO_ERROR) { + try { + HILOGI("Begin, bundle name:%{public}s, sendRate is:%{public}d", bundleName.c_str(), sendRate); + if (session_ == nullptr || isCleanService_.load()) { + HILOGE("Update Send Rate error, session is empty."); + result = false; + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); + VerifyCaller(); + IServiceReverse::Scenario scenario = session_ -> GetScenario(); + if (scenario != IServiceReverse::Scenario::BACKUP) { + HILOGE("This method is applicable to the backup scenario"); + result = false; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return BError(BError::Codes::SA_INVAL_ARG); + } + auto backupConnection = session_->GetExtConnection(bundleName); + auto proxy = backupConnection->GetBackupExtProxy(); + if (!proxy) { + throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); + } + auto ret = proxy->UpdateFdSendRate(bundleName, sendRate); + if (ret != NO_ERROR) { + result = false; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return BError(BError::Codes::EXT_BROKEN_IPC); + } + result = true; + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + return BError(BError::Codes::OK); + } catch (...) { result = false; - return BError(BError::Codes::EXT_BROKEN_IPC); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); + HILOGI("Unexpected exception"); + return EPERM; } - result = true; - return BError(BError::Codes::OK); } AAFwk::Want Service::CreateConnectWant (BundleName &bundleName) @@ -1581,18 +1953,22 @@ ErrCode Service::SADone(ErrCode errCode, std::string bundleName) HILOGE("lock sa connection ptr is nullptr"); return BError(BError::Codes::SA_INVAL_ARG); } - session_->BundleExtTimerStop(bundleName); + session_->StopFwkTimer(bundleName); + session_->StopExtTimer(bundleName); saConnection->DisconnectBackupSAExt(); ClearSessionAndSchedInfo(bundleName); } OnAllBundlesFinished(BError(BError::Codes::OK)); return BError(BError::Codes::OK); } catch (const BError &e) { + ReleaseOnException(); return e.GetCode(); // 任意异常产生,终止监听该任务 } catch (const exception &e) { + ReleaseOnException(); HILOGE("Catched an unexpected low-level exception %{public}s", e.what()); return EPERM; } catch(...) { + ReleaseOnException(); HILOGE("Unexpected exception"); return EPERM; } @@ -1624,4 +2000,129 @@ void Service::NotifyCallerCurAppDone(ErrCode errCode, const std::string &callerN session_->GetServiceReverseProxy()->RestoreOnBundleFinished(errCode, callerName); } } + +ErrCode Service::ReportAppProcessInfo(const std::string processInfo, BackupRestoreScenario sennario) +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + try { + string bundleName = VerifyCallerAndGetCallerName(); + if (sennario == BackupRestoreScenario::FULL_RESTORE) { + session_->GetServiceReverseProxy()->RestoreOnProcessInfo(bundleName, processInfo); + } else if (sennario == BackupRestoreScenario::INCREMENTAL_RESTORE) { + session_->GetServiceReverseProxy()->IncrementalRestoreOnProcessInfo(bundleName, processInfo); + } else if (sennario == BackupRestoreScenario::FULL_BACKUP) { + session_->GetServiceReverseProxy()->BackupOnProcessInfo(bundleName, processInfo); + } else if (sennario == BackupRestoreScenario::INCREMENTAL_BACKUP) { + session_->GetServiceReverseProxy()->IncrementalBackupOnProcessInfo(bundleName, processInfo); + } + return BError(BError::Codes::OK); + } catch (const BError &e) { + return e.GetCode(); // 任意异常产生,终止监听该任务 + } catch (const exception &e) { + HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); + return EPERM; + } +} + +std::function Service::TimeOutCallback(wptr ptr, std::string bundleName) +{ + return [ptr, bundleName, this]() { + HILOGI("begin timeoutCallback bundleName = %{public}s", bundleName.c_str()); + auto thisPtr = ptr.promote(); + if (!thisPtr) { + HILOGE("ServicePtr is nullptr."); + return; + } + try { + DoTimeout(thisPtr, bundleName); + } catch (...) { + HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str()); + thisPtr->ClearSessionAndSchedInfo(bundleName); + thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT)); + } + }; +} + +void Service::DoTimeout(wptr ptr, std::string bundleName) +{ + auto thisPtr = ptr.promote(); + if (!thisPtr) { + HILOGE("ServicePtr is nullptr."); + return; + } + auto sessionPtr = thisPtr->session_; + if (sessionPtr == nullptr) { + HILOGE("SessionPtr is nullptr."); + return; + } + IServiceReverse::Scenario scenario = sessionPtr->GetScenario(); + int32_t errCode = BError(BError::Codes::EXT_ABILITY_TIMEOUT).GetCode(); + if (scenario == IServiceReverse::Scenario::BACKUP) { + AppRadar::Info info(bundleName, "", "on backup timeout"); + AppRadar::GetInstance().RecordBackupFuncRes(info, "Service::TimeOutCallback", GetUserIdDefault(), + BizStageBackup::BIZ_STAGE_ON_BACKUP, errCode); + } else if (scenario == IServiceReverse::Scenario::RESTORE) { + AppRadar::Info info(bundleName, "", "on restore timeout"); + AppRadar::GetInstance().RecordRestoreFuncRes(info, "Service::TimeOutCallback", GetUserIdDefault(), + BizStageRestore::BIZ_STAGE_ON_RESTORE, errCode); + } + try { + if (SAUtils::IsSABundleName(bundleName)) { + auto sessionConnection = sessionPtr->GetSAExtConnection(bundleName); + shared_ptr saConnection = sessionConnection.lock(); + if (saConnection == nullptr) { + HILOGE("lock sa connection ptr is nullptr"); + return; + } + saConnection->DisconnectBackupSAExt(); + } else { + auto sessionConnection = sessionPtr->GetExtConnection(bundleName); + sessionConnection->DisconnectBackupExtAbility(); + } + sessionPtr->StopFwkTimer(bundleName); + sessionPtr->StopExtTimer(bundleName); + thisPtr->ClearSessionAndSchedInfo(bundleName); + thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT)); + } catch (...) { + HILOGE("Unexpected exception, bundleName: %{public}s", bundleName.c_str()); + thisPtr->ClearSessionAndSchedInfo(bundleName); + thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_TIMEOUT)); + } +} + +void Service::AddClearBundleRecord(const std::string &bundleName) +{ + // 添加清理记录 + if (!clearRecorder_->InsertClearBundleRecord(bundleName)) { + HILOGE("Failed to add clear bundle record, bundleName=%{public}s", bundleName.c_str()); + return; + } + HILOGI("Add clear bundle record OK, bundleName=%{public}s", bundleName.c_str()); +} + +void Service::DelClearBundleRecord(const std::vector &bundleNames) +{ + // 删除清理记录 + for (const auto &it : bundleNames) { + if (!clearRecorder_->DeleteClearBundleRecord(it)) { + HILOGE("Failed to delete clear bundle record, bundleName=%{public}s", it.c_str()); + continue; + } + HILOGI("Delete clear bundle record OK, bundleName=%{public}s", it.c_str()); + } +} + +void Service::ReleaseOnException() +{ + try { + if (session_->IsOnAllBundlesFinished()) { + IServiceReverse::Scenario scenario = session_->GetScenario(); + if (isInRelease_.load() && (scenario == IServiceReverse::Scenario::RESTORE)) { + SessionDeactive(); + } + } + } catch (...) { + HILOGE("Unexpected exception"); + } +} } // 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 07c6f6f87fca4c4faf3a9a15925f0158964ead74..850f6247ec7975281f6b2838968911b3b5db6e79 100644 --- a/services/backup_sa/src/module_ipc/service_incremental.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental.cpp @@ -38,6 +38,7 @@ #include "b_json/b_json_entity_caps.h" #include "b_ohos/startup/backup_para.h" #include "b_process/b_multiuser.h" +#include "b_radar/b_radar.h" #include "b_resources/b_constants.h" #include "b_sa/b_sa_utils.h" #include "filemgmt_libhilog.h" @@ -93,11 +94,11 @@ UniqueFd Service::GetLocalCapabilitiesIncremental(const std::vectorIncreaseSessionCnt(); + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); session_->SetSessionUserId(GetUserIdDefault()); VerifyCaller(); string path = BConstants::GetSaBundleBackupRootDir(session_->GetSessionUserId()); @@ -105,7 +106,7 @@ UniqueFd Service::GetLocalCapabilitiesIncremental(const std::vectorDecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return UniqueFd(-ENOENT); } BJsonCachedEntity cachedEntity(move(fd)); @@ -117,19 +118,19 @@ UniqueFd Service::GetLocalCapabilitiesIncremental(const std::vectorDecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("End, bundleInfos size:%{public}zu", bundleInfos.size()); return move(cachedEntity.GetFd()); } catch (const BError &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("GetLocalCapabilitiesIncremental failed, errCode = %{public}d", e.GetCode()); return UniqueFd(-e.GetCode()); } catch (const exception &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); return UniqueFd(-EPERM); } catch (...) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return UniqueFd(-EPERM); } @@ -154,6 +155,15 @@ void Service::StartGetFdTask(std::string bundleName, wptr ptr) if (!proxy) { throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); } + // distinguish whether it is 0 user + if (BundleMgrAdapter::IsUser0BundleName(bundleName, session_->GetSessionUserId())) { + auto ret = proxy->User0OnBackup(); + if (ret) { + thisPtr->ClearSessionAndSchedInfo(bundleName); + thisPtr->NoticeClientFinish(bundleName, BError(BError::Codes::EXT_ABILITY_DIED)); + } + return; + } int64_t lastTime = session->GetLastIncrementalTime(bundleName); std::vector bundleNames; bundleNames.emplace_back(BIncrementalData {bundleName, lastTime}); @@ -181,11 +191,11 @@ ErrCode Service::GetAppLocalListAndDoIncrementalBackup() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); try { - if (session_ == nullptr) { + if (session_ == nullptr || isCleanService_.load()) { HILOGE("session is nullptr"); return BError(BError::Codes::SA_INVAL_ARG); } - session_->IncreaseSessionCnt(); + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); session_->SetSessionUserId(GetUserIdDefault()); std::string bundleName = VerifyCallerAndGetCallerName(); auto task = [this, bundleName]() { @@ -202,18 +212,18 @@ ErrCode Service::GetAppLocalListAndDoIncrementalBackup() HILOGI("Unexpected exception"); } }); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (const BError &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("GetAppLocalListAndDoIncrementalBackup failed, errCode = %{public}d", e.GetCode()); return e.GetCode(); } catch (const exception &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Catched an unexpected low-level exception %{public}s", e.what()); return EPERM; } catch (...) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return EPERM; } @@ -243,11 +253,11 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vectorIncreaseSessionCnt(); // BundleMgrAdapter::GetBundleInfos可能耗时 + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 VerifyCaller(IServiceReverse::Scenario::BACKUP); vector bundleNames {}; for (auto &bundle : bundlesToBackup) { @@ -255,6 +265,7 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vectorGetSessionUserId()); session_->AppendBundles(bundleNames); + SetCurrentBackupSessProperties(bundleNames, session_->GetSessionUserId()); for (auto info : backupInfos) { session_->SetBundleDataSize(info.name, info.spaceOccupied); session_->SetBackupExtName(info.name, info.extensionName); @@ -268,14 +279,14 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vectorSetIncrementalData(bundleInfo); } OnStartSched(); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (const BError &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("Failed, errCode = %{public}d", e.GetCode()); return e.GetCode(); } catch (...) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return EPERM; } @@ -286,29 +297,32 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vectorIncreaseSessionCnt(); // BundleMgrAdapter::GetBundleInfos可能耗时 + if (session_ == nullptr || isCleanService_.load()) { + HILOGE("Init Incremental backup session error, session is empty"); + return BError(BError::Codes::SA_INVAL_ARG); + } + session_->IncreaseSessionCnt(__PRETTY_FUNCTION__); // BundleMgrAdapter::GetBundleInfos可能耗时 VerifyCaller(IServiceReverse::Scenario::BACKUP); vector bundleNames {}; for (auto &bundle : bundlesToBackup) { bundleNames.emplace_back(bundle.bundleName); } std::vector bundleNamesOnly; + std::map isClearDataFlags; std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, infos, bundleNamesOnly, session_->GetSessionUserId()); + BJsonUtil::BuildBundleInfos(bundleNames, infos, bundleNamesOnly, + session_->GetSessionUserId(), isClearDataFlags); auto backupInfos = BundleMgrAdapter::GetBundleInfos(bundleNames, session_->GetSessionUserId()); session_->AppendBundles(bundleNames); for (auto info : backupInfos) { - session_->SetBundleDataSize(info.name, info.spaceOccupied); - session_->SetBackupExtName(info.name, info.extensionName); + SetCurrentSessProperties(info, isClearDataFlags); if (info.allToBackup == false) { session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted( BError(BError::Codes::SA_FORBID_BACKUP_RESTORE), info.name); session_->RemoveExtInfo(info.name); } BJsonUtil::BundleDetailInfo uniCastInfo; - bool uniCastRet = BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, info.name, UNICAST_TYPE, - uniCastInfo); - if (uniCastRet) { + if (BJsonUtil::FindBundleInfoByName(bundleNameDetailMap, info.name, UNICAST_TYPE, uniCastInfo)) { HILOGI("current bundle, unicast info:%{public}s", GetAnonyString(uniCastInfo.detail).c_str()); session_->SetBackupExtInfo(info.name, uniCastInfo.detail); } @@ -317,14 +331,14 @@ ErrCode Service::AppendBundlesIncrementalBackupSession(const std::vectorSetIncrementalData(bundleInfo); } OnStartSched(); - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } catch (const BError &e) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGE("Failed, errCode = %{public}d", e.GetCode()); return e.GetCode(); } catch (...) { - session_->DecreaseSessionCnt(); + session_->DecreaseSessionCnt(__PRETTY_FUNCTION__); HILOGI("Unexpected exception"); return EPERM; } @@ -340,6 +354,9 @@ ErrCode Service::PublishIncrementalFile(const BFileInfo &fileInfo) HILOGE("Forbit to use PublishIncrementalFile with fileName for App"); return EPERM; } + if (session_ != nullptr) { + session_->SetPublishFlag(fileInfo.owner); + } auto backUpConnection = session_->GetExtConnection(fileInfo.owner); if (backUpConnection == nullptr) { HILOGE("PublishIncrementalFile error, backUpConnection is empty"); @@ -409,7 +426,8 @@ ErrCode Service::AppIncrementalFileReady(const std::string &fileName, UniqueFd f // 通知extension清空缓存 proxy->HandleClear(); // 清除Timer - session_->BundleExtTimerStop(callerName); + session_->StopFwkTimer(callerName); + session_->StopExtTimer(callerName); // 通知TOOL 备份完成 HILOGI("reverse: Will notify IncrementalBackupOnBundleFinished"); session_->GetServiceReverseProxy()->IncrementalBackupOnBundleFinished(BError(BError::Codes::OK), @@ -453,17 +471,20 @@ ErrCode Service::AppIncrementalDone(ErrCode errCode) return BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); } proxy->HandleClear(); - session_->BundleExtTimerStop(callerName); - NotifyCallerCurAppIncrementDone(errCode, callerName); + session_->StopFwkTimer(callerName); + session_->StopExtTimer(callerName); backUpConnection->DisconnectBackupExtAbility(); ClearSessionAndSchedInfo(callerName); + NotifyCallerCurAppIncrementDone(errCode, callerName); } OnAllBundlesFinished(BError(BError::Codes::OK)); return BError(BError::Codes::OK); } catch (const BError &e) { + ReleaseOnException(); HILOGE("AppIncrementalDone error, err code is:%{public}d", e.GetCode()); return e.GetCode(); // 任意异常产生,终止监听该任务 } catch (...) { + ReleaseOnException(); HILOGI("Unexpected exception"); return EPERM; } @@ -489,6 +510,9 @@ ErrCode Service::GetIncrementalFileHandle(const std::string &bundleName, const s int res = proxy->GetIncrementalFileHandle(fileName); if (res) { HILOGE("Failed to extension file handle"); + AppRadar::Info info (bundleName, "", ""); + AppRadar::GetInstance().RecordRestoreFuncRes(info, "Service::GetIncrementalFileHandle", + GetUserIdDefault(), BizStageRestore::BIZ_STAGE_GET_FILE_HANDLE_FAIL, res); } } else { SvcRestoreDepsManager::GetInstance().UpdateToRestoreBundleMap(bundleName, fileName); @@ -519,7 +543,7 @@ bool Service::IncrementalBackup(const string &bundleName) throw BError(BError::Codes::SA_INVAL_ARG, "Extension backup Proxy is empty"); } if (scenario == IServiceReverse::Scenario::BACKUP && session_->GetIsIncrementalBackup()) { - auto ret = proxy->IncrementalOnBackup(); + auto ret = proxy->IncrementalOnBackup(session_->GetClearDataFlag(bundleName)); session_->GetServiceReverseProxy()->IncrementalBackupOnBundleStarted(ret, bundleName); if (ret) { ClearSessionAndSchedInfo(bundleName); @@ -528,7 +552,7 @@ bool Service::IncrementalBackup(const string &bundleName) return true; } else if (scenario == IServiceReverse::Scenario::RESTORE && BackupPara().GetBackupOverrideIncrementalRestore() && session_->ValidRestoreDataType(RestoreTypeEnum::RESTORE_DATA_WAIT_SEND)) { - auto ret = proxy->HandleRestore(); + auto ret = proxy->HandleRestore(session_->GetClearDataFlag(bundleName)); session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleStarted(ret, bundleName); auto fileNameVec = session_->GetExtFileNameRequest(bundleName); for (auto &fileName : fileNameVec) { @@ -567,4 +591,35 @@ void Service::NotifyCallerCurAppIncrementDone(ErrCode errCode, const std::string session_->GetServiceReverseProxy()->IncrementalRestoreOnBundleFinished(errCode, callerName); } } + +void Service::SendUserIdToApp(string &bundleName, int32_t userId) +{ + if (session_ == nullptr) { + HILOGI("session_ is nullptr"); + return; + } + HILOGI("SetCurrentBackupSessProperties bundleName : %{public}s", bundleName.c_str()); + string detailInfo; + if (!BJsonUtil::BuildBundleInfoJson(userId, detailInfo)) { + HILOGI("BuildBundleInfoJson failed, bundleName : %{public}s", bundleName.c_str()); + return; + } + HILOGI("current bundle, unicast info: %{public}s", detailInfo.c_str()); + session_->SetBackupExtInfo(bundleName, detailInfo); +} + +void Service::SetCurrentBackupSessProperties(const vector &bundleNames, int32_t userId) +{ + HILOGI("start SetCurrentBackupSessProperties"); + std::map> bundleNameDetailMap; + std::vector bundleDetailInfos; + for (auto item : bundleNames) { + std::string bundleName = item; + if (!BundleMgrAdapter::IsUser0BundleName(bundleName, userId)) { + continue; + } + SendUserIdToApp(bundleName, userId); + } + HILOGI("end SetCurrentBackupSessProperties"); +} } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/service_incremental_reverse_proxy.cpp b/services/backup_sa/src/module_ipc/service_incremental_reverse_proxy.cpp index 6a9cd7560323e766662da0b26105a72ab2c3b006..39a5251735fa091aae44b67af2269334bac5f19a 100644 --- a/services/backup_sa/src/module_ipc/service_incremental_reverse_proxy.cpp +++ b/services/backup_sa/src/module_ipc/service_incremental_reverse_proxy.cpp @@ -121,6 +121,24 @@ void ServiceReverseProxy::IncrementalBackupOnAllBundlesFinished(int32_t errCode) } } +void ServiceReverseProxy::IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) +{ + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteString(bundleName) || !data.WriteString(processInfo)) { + throw BError(BError::Codes::SA_BROKEN_IPC); + } + + MessageParcel reply; + MessageOption option; + if (int err = Remote()->SendRequest( + static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_BACKUP_ON_PROCESS_INFO), data, + reply, option); + err != ERR_OK) { + throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); + } +} + void ServiceReverseProxy::IncrementalRestoreOnBundleStarted(int32_t errCode, string bundleName) { BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); @@ -217,4 +235,22 @@ void ServiceReverseProxy::IncrementalRestoreOnFileReady(string bundleName, strin throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); } } + +void ServiceReverseProxy::IncrementalRestoreOnProcessInfo(std::string bundleName, std::string processInfo) +{ + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteString(bundleName) || !data.WriteString(processInfo)) { + throw BError(BError::Codes::SA_BROKEN_IPC); + } + + MessageParcel reply; + MessageOption option; + if (int err = Remote()->SendRequest( + static_cast(IServiceReverseInterfaceCode::SERVICER_INCREMENTAL_RESTORE_ON_PROCESS_INFO), data, + reply, option); + err != ERR_OK) { + throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); + } +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/services/backup_sa/src/module_ipc/service_reverse_proxy.cpp b/services/backup_sa/src/module_ipc/service_reverse_proxy.cpp index fdb44c962536785c4752db8cc966f103dfbbf6af..b1f7a6e6c210a1c879dbb4e04371110d30efa941 100644 --- a/services/backup_sa/src/module_ipc/service_reverse_proxy.cpp +++ b/services/backup_sa/src/module_ipc/service_reverse_proxy.cpp @@ -113,6 +113,23 @@ void ServiceReverseProxy::BackupOnAllBundlesFinished(int32_t errCode) } } +void ServiceReverseProxy::BackupOnProcessInfo(std::string bundleName, std::string processInfo) +{ + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteString(bundleName) || !data.WriteString(processInfo)) { + throw BError(BError::Codes::SA_BROKEN_IPC); + } + + MessageParcel reply; + MessageOption option; + if (int err = Remote()->SendRequest( + static_cast(IServiceReverseInterfaceCode::SERVICER_BACKUP_ON_PROCESS_INFO), data, reply, option); + err != ERR_OK) { + throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); + } +} + void ServiceReverseProxy::RestoreOnBundleStarted(int32_t errCode, string bundleName) { BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); @@ -209,4 +226,21 @@ void ServiceReverseProxy::RestoreOnResultReport(string result, std::string bundl throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); } } + +void ServiceReverseProxy::RestoreOnProcessInfo(std::string bundleName, std::string processInfo) +{ + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteString(bundleName) || !data.WriteString(processInfo)) { + throw BError(BError::Codes::SA_BROKEN_IPC); + } + + MessageParcel reply; + MessageOption option; + if (int err = Remote()->SendRequest( + static_cast(IServiceReverseInterfaceCode::SERVICER_RESTORE_ON_PROCESS_INFO), data, reply, option); + err != ERR_OK) { + throw BError(BError::Codes::SA_BROKEN_IPC, to_string(err)); + } +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/services/backup_sa/src/module_ipc/service_stub.cpp b/services/backup_sa/src/module_ipc/service_stub.cpp index bd6d1be91a849d22d0c7c3cb718783bdaeb34bbf..ed8b298abc71bc619f06376baad4b41526f5ce73 100644 --- a/services/backup_sa/src/module_ipc/service_stub.cpp +++ b/services/backup_sa/src/module_ipc/service_stub.cpp @@ -43,6 +43,13 @@ void ServiceStub::ServiceStubSupplement() opToInterfaceMap_[static_cast( IServiceInterfaceCode::SERVICE_CMD_GET_APP_LOCAL_LIST_AND_DO_INCREMENTAL_BACKUP)] = &ServiceStub::CmdGetAppLocalListAndDoIncrementalBackup; + opToInterfaceMap_[static_cast( + IServiceInterfaceCode::SERVICE_CMD_REPORT_APP_PROCESS_INFO)] = + &ServiceStub::CmdReportAppProcessInfo; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_START_EXT_TIMER)] = + &ServiceStub::CmdStartExtTimer; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_START_FWK_TIMER)] = + &ServiceStub::CmdStartFwkTimer; } void ServiceStub::ServiceStubSuppAppendBundles() @@ -407,12 +414,12 @@ int32_t ServiceStub::CmdUpdateTimer(MessageParcel &data, MessageParcel &reply) if (!data.ReadString(bundleName)) { return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to recive bundleName")); } - uint32_t timeOut; - if (!data.ReadUint32(timeOut)) { - return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to recive timeOut")); + uint32_t timeout; + if (!data.ReadUint32(timeout)) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to recive timeout")); } bool result; - ret = UpdateTimer(bundleName, timeOut, result); + ret = UpdateTimer(bundleName, timeout, result); if (ret != ERR_OK) { return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to call UpdateTimer")); } @@ -447,6 +454,38 @@ int32_t ServiceStub::CmdUpdateSendRate(MessageParcel &data, MessageParcel &reply return BError(BError::Codes::OK); } +int32_t ServiceStub::CmdStartExtTimer(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("ServiceStub::CmdStartExtTimer Begin."); + int ret = ERR_OK; + bool isExtStart; + ret = StartExtTimer(isExtStart); + if (ret != ERR_OK) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to call UpdateTimer")); + } + if (!reply.WriteBool(isExtStart)) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to write result")); + } + HILOGI("ServiceStub::CmdStartExtTimer end."); + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdStartFwkTimer(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("ServiceStub::CmdStartFwkTimer Begin."); + int ret = ERR_OK; + bool isFwkStart; + ret = StartFwkTimer(isFwkStart); + if (ret != ERR_OK) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to call UpdateTimer")); + } + if (!reply.WriteBool(isFwkStart)) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to write result")); + } + HILOGI("ServiceStub::CmdStartFwkTimer end."); + return BError(BError::Codes::OK); +} + int32_t ServiceStub::CmdRelease(MessageParcel &data, MessageParcel &reply) { int res = Release(); @@ -622,6 +661,20 @@ int32_t ServiceStub::CmdGetIncrementalFileHandle(MessageParcel &data, MessagePar return GetIncrementalFileHandle(bundleName, fileName); } +int32_t ServiceStub::CmdReportAppProcessInfo(MessageParcel &data, MessageParcel &reply) +{ + string processInfo; + if (!data.ReadString(processInfo)) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bundleName").GetCode(); + } + int32_t scenario; + if (!data.ReadInt32(scenario)) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive errCode"); + } + BackupRestoreScenario secenrioInfo = static_cast(scenario); + return ReportAppProcessInfo(processInfo, secenrioInfo); +} + template bool ServiceStub::ReadParcelableVector(std::vector &parcelableInfos, MessageParcel &data) { 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 a44451272684c93085e4468067b75608543c35e3..f9dc891c68e4e3a66a3c688717c2df9aab531e34 100644 --- a/services/backup_sa/src/module_ipc/svc_backup_connection.cpp +++ b/services/backup_sa/src/module_ipc/svc_backup_connection.cpp @@ -63,7 +63,12 @@ void SvcBackupConnection::OnAbilityConnectDone(const AppExecFwk::ElementName &el "PID", getpid(), "TIME", strTime.str() ); - callConnected_(move(bundleName)); + if (bundleNameIndexInfo_.find(bundleName) == string::npos) { + HILOGE("Current bundle name is wrong, bundleNameIndexInfo:%{public}s, bundleName:%{public}s", + bundleNameIndexInfo_.c_str(), bundleName.c_str()); + return; + } + callConnected_(move(bundleNameIndexInfo_)); HILOGI("called end"); } @@ -79,6 +84,7 @@ void SvcBackupConnection::OnAbilityDisconnectDone(const AppExecFwk::ElementName callDied_(move(bundleName)); } condition_.notify_all(); + waitCondition_.notify_all(); HILOGI("called end, name: %{public}s", bundleName.c_str()); } @@ -112,6 +118,17 @@ ErrCode SvcBackupConnection::DisconnectBackupExtAbility() return ret; } +bool SvcBackupConnection::WaitDisconnectDone() +{ + std::unique_lock lock(waitMutex_); + if (waitCondition_.wait_for(lock, std::chrono::seconds(WAIT_TIME), + [this]() { return isConnected_.load() == false; })) { + HILOGI("Wait disconnected done success"); + return true; + } + return false; +} + bool SvcBackupConnection::IsExtAbilityConnected() { return isConnected_.load(); diff --git a/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp b/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp index c4355e6aa43a0cc28a328383abbd922a1ec295d8..03dbb4fe3133fdaf0f030579646aeaa0c6626272 100644 --- a/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp +++ b/services/backup_sa/src/module_ipc/svc_extension_incremental_proxy.cpp @@ -101,13 +101,15 @@ ErrCode SvcExtensionProxy::HandleIncrementalBackup(UniqueFd incrementalFd, Uniqu return reply.ReadInt32(); } -ErrCode SvcExtensionProxy::IncrementalOnBackup() +ErrCode SvcExtensionProxy::IncrementalOnBackup(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGD("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteBool(isClearData)) { + return BError(BError::Codes::SDK_INVAL_ARG, "build param fail."); + } MessageParcel reply; MessageOption option; @@ -122,6 +124,27 @@ ErrCode SvcExtensionProxy::IncrementalOnBackup() return BError(BError::Codes::OK); } +ErrCode SvcExtensionProxy::User0OnBackup() +{ + HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); + HILOGD("Start"); + BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); + MessageParcel data; + data.WriteInterfaceToken(GetDescriptor()); + + MessageParcel reply; + MessageOption option; + int32_t ret = Remote()->SendRequest(static_cast(IExtensionInterfaceCode::CMD_HANDLE_USER_0_BACKUP), + data, reply, option); + if (ret != NO_ERROR) { + HILOGE("Received error %{public}d when doing IPC", ret); + return ErrCode(ret); + } + + HILOGD("Successful"); + return reply.ReadInt32(); +} + tuple SvcExtensionProxy::GetIncrementalBackupFileHandle() { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); diff --git a/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp b/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp index 57e126eb35275538bcb63f56b1928035df7e478a..ce2bfcc36b75865ade94bba5f7cac9cd889af247 100644 --- a/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp +++ b/services/backup_sa/src/module_ipc/svc_extension_proxy.cpp @@ -79,13 +79,15 @@ ErrCode SvcExtensionProxy::HandleClear() return reply.ReadInt32(); } -ErrCode SvcExtensionProxy::HandleBackup() +ErrCode SvcExtensionProxy::HandleBackup(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteBool(isClearData)) { + return BError(BError::Codes::SDK_INVAL_ARG, "build param fail."); + } MessageParcel reply; MessageOption option; @@ -126,13 +128,15 @@ ErrCode SvcExtensionProxy::PublishFile(const string &fileName) return reply.ReadInt32(); } -ErrCode SvcExtensionProxy::HandleRestore() +ErrCode SvcExtensionProxy::HandleRestore(bool isClearData) { HITRACE_METER_NAME(HITRACE_TAG_FILEMANAGEMENT, __PRETTY_FUNCTION__); HILOGI("Start"); BExcepUltils::BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); MessageParcel data; - data.WriteInterfaceToken(GetDescriptor()); + if (!data.WriteInterfaceToken(GetDescriptor()) || !data.WriteBool(isClearData)) { + return BError(BError::Codes::SDK_INVAL_ARG, "build param fail."); + } MessageParcel reply; MessageOption option; diff --git a/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp b/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp index 115db71c495443b2d8149ecec32c30ac24481fba..70879196a310d2eff12400e017c4bb4832d96ab4 100644 --- a/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_restore_deps_manager.cpp @@ -15,6 +15,7 @@ #include "module_ipc/svc_restore_deps_manager.h" +#include "b_jsonutil/b_jsonutil.h" #include "filemgmt_libhilog.h" namespace OHOS::FileManagement::Backup { @@ -28,23 +29,16 @@ vector SvcRestoreDepsManager::GetRestoreBundleNames(const vector &bundleInfos) { for (auto &bundleInfo : bundleInfos) { - if (depsMap_.find(bundleInfo.name) != depsMap_.end()) { + std::string bundleNameIndexInfo = BJsonUtil::BuildBundleNameIndexInfo(bundleInfo.name, bundleInfo.appIndex); + if (depsMap_.find(bundleNameIndexInfo) != depsMap_.end()) { continue; } allBundles_.emplace_back(bundleInfo); @@ -100,7 +95,7 @@ void SvcRestoreDepsManager::BuildDepsMap(const vector lock(lock_); if (impl_.scenario != scenario) { + HILOGE("Inconsistent scenario, impl scenario:%{public}d", impl_.scenario); + AppRadar::Info info("", "", "Inconsistent scenario"); + AppRadar::GetInstance().RecordDefaultFuncRes(info, "SvcSessionManager::VerifyCallerAndScenario", impl_.userId, + BizStageBackup::BIZ_STAGE_PERMISSION_CHECK_FAIL, + BError(BError::Codes::SDK_MIXED_SCENARIO).GetCode()); throw BError(BError::Codes::SDK_MIXED_SCENARIO); } if (impl_.clientToken != clientToken) { + AppRadar::Info info2("", "", "Caller mismatched"); + AppRadar::GetInstance().RecordDefaultFuncRes(info2, "SvcSessionManager::VerifyCallerAndScenario", impl_.userId, + BizStageBackup::BIZ_STAGE_PERMISSION_CHECK_FAIL, + BError(BError::Codes::SDK_MIXED_SCENARIO).GetCode()); throw BError(BError::Codes::SA_REFUSED_ACT, "Caller mismatched"); } HILOGD("Succeed to verify the caller"); @@ -53,7 +64,12 @@ SvcSessionManager::Impl SvcSessionManager::GetImpl() return impl_; } -ErrCode SvcSessionManager::Active(Impl newImpl) +int SvcSessionManager::GetSessionCnt() +{ + return sessionCnt_.load(); +} + +ErrCode SvcSessionManager::Active(Impl newImpl, bool force) { unique_lock lock(lock_); const Impl &oldImpl = impl_; @@ -62,30 +78,32 @@ ErrCode SvcSessionManager::Active(Impl newImpl) return BError(BError::Codes::SA_REFUSED_ACT); } - if (!newImpl.clientToken) { + if (!force && !newImpl.clientToken) { throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); } - if (newImpl.scenario == IServiceReverse::Scenario::UNDEFINED) { + if (!force && newImpl.scenario == IServiceReverse::Scenario::UNDEFINED) { throw BError(BError::Codes::SA_INVAL_ARG, "No scenario was specified"); } - InitClient(newImpl); + if (!force) { + InitClient(newImpl); + } impl_ = newImpl; + IncreaseSessionCnt(__PRETTY_FUNCTION__); return BError(BError::Codes::OK); } void SvcSessionManager::Deactive(const wptr &remoteInAction, bool force) { unique_lock lock(lock_); - if (!impl_.clientToken || !impl_.clientProxy) { + if (!impl_.clientToken) { HILOGI("Empty session"); return; } if (!force && (!impl_.clientToken || !impl_.clientProxy)) { - throw BError(BError::Codes::SA_REFUSED_ACT, "Try to deactive an empty session"); + return; } - auto remoteHeldByProxy = impl_.clientProxy->AsObject(); - if (!force && (remoteInAction != remoteHeldByProxy)) { + if (!force && (remoteInAction != impl_.clientProxy->AsObject())) { throw BError(BError::Codes::SA_INVAL_ARG, "Only the client actived the session can deactive it"); } @@ -93,6 +111,7 @@ void SvcSessionManager::Deactive(const wptr &remoteInAction, bool HILOGI("Succeed to deactive a session"); impl_ = {}; extConnectNum_ = 0; + DecreaseSessionCnt(__PRETTY_FUNCTION__); } void SvcSessionManager::VerifyBundleName(string &bundleName) @@ -205,12 +224,18 @@ void SvcSessionManager::RemoveExtInfo(const string &bundleName) unique_lock lock(lock_); auto it = impl_.backupExtNameMap.find(bundleName); if (it == impl_.backupExtNameMap.end()) { + HILOGI("BackupExtNameMap not contain %{public}s", bundleName.c_str()); return; } - impl_.backupExtNameMap.erase(it); if (extConnectNum_) { extConnectNum_--; } + int32_t &appendNum = impl_.backupExtNameMap[bundleName].appendNum; + if (--appendNum > 0) { + HILOGI("No need remove bundleName:%{public}s, appendNum=%{public}d", bundleName.c_str(), appendNum); + return; + } + impl_.backupExtNameMap.erase(it); } wptr SvcSessionManager::GetExtConnection(const BundleName &bundleName) @@ -267,7 +292,7 @@ sptr SvcSessionManager::GetBackupAbilityExt(const string &b revPtrStrong->ExtConnectDone(move(bundleName)); }; - return sptr(new SvcBackupConnection(callDied, callConnected)); + return sptr(new SvcBackupConnection(callDied, callConnected, bundleName)); } std::shared_ptr SvcSessionManager::GetBackupSAExt(const std::string &bundleName) @@ -342,6 +367,11 @@ void SvcSessionManager::InitClient(Impl &newImpl) HILOGW("It's curious that the backup sa dies before the backup client"); return; } + AppRadar::Info info ("", "", "client died"); + AppRadar::GetInstance().RecordDefaultFuncRes(info, "SvcSessionManager::InitClient", + AppRadar::GetInstance().GetUserId(), + BizStageBackup::BIZ_STAGE_CLIENT_ABNORMAL_EXIT, + BError(BError::Codes::SA_BROKEN_IPC).GetCode()); (void)revPtrStrong->SessionDeactive(); }; deathRecipient_ = sptr(new SvcDeathRecipient(callback)); @@ -483,6 +513,15 @@ void SvcSessionManager::AppendBundles(const vector &bundleNames) for (auto &&bundleName : bundleNames) { HILOGD("bundleName: %{public}s", bundleName.c_str()); BackupExtInfo info {}; + auto it = impl_.backupExtNameMap.find(bundleName); + if (it != impl_.backupExtNameMap.end()) { + HILOGI("BackupExtNameMap already contain %{public}s", bundleName.c_str()); + info.backUpConnection = impl_.backupExtNameMap[bundleName].backUpConnection; + info.saBackupConnection = impl_.backupExtNameMap[bundleName].saBackupConnection; + info.appendNum = impl_.backupExtNameMap[bundleName].appendNum + 1; + impl_.backupExtNameMap[bundleName] = info; + continue; + } if (SAUtils::IsSABundleName(bundleName)) { info.saBackupConnection = GetBackupSAExt(bundleName); } else { @@ -661,107 +700,170 @@ uint32_t SvcSessionManager::CalAppProcessTime(const std::string &bundleName) } timeout = timeout < minTimeout ? minTimeout : timeout; resTimeoutMs = (uint32_t)(timeout * invertMillisecond % UINT_MAX); /* conver second to millisecond */ - HILOGI("Calculate App extension process run timeout=%{public}u(us), bundleName=%{public}s ", resTimeoutMs, + HILOGI("Calculate App extension process run timeout=%{public}u(ms), bundleName=%{public}s ", resTimeoutMs, bundleName.c_str()); return resTimeoutMs; } -void SvcSessionManager::BundleExtTimerStart(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) +bool SvcSessionManager::StartFwkTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) { unique_lock lock(lock_); + HILOGI("StartFwkTimer begin bundleName %{public}s", bundleName.c_str()); if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + HILOGE("No caller token was specified"); + return false; + } + auto it = GetBackupExtNameMap(bundleName); + if (it->second.fwkTimerStatus == true) { + HILOGE("FwkTimer is registered, unregister first."); + return false; } uint32_t timeout = CalAppProcessTime(bundleName); + it->second.fwkTimerStatus = true; + it->second.timerId = timer_.Register(callback, timeout, true); + HILOGI("StartFwkTimer end bundleName %{public}s", bundleName.c_str()); + return true; +} + +bool SvcSessionManager::StopFwkTimer(const std::string &bundleName) +{ + unique_lock lock(lock_); + HILOGI("StopFwkTimer begin bundleName %{public}s", bundleName.c_str()); + if (!impl_.clientToken) { + HILOGE("No caller token was specified"); + return false; + } auto it = GetBackupExtNameMap(bundleName); - if (it->second.timerStatus == false) { - it->second.timerStatus = true; - it->second.extTimerId = extBundleTimer.Register(callback, timeout, true); + if (it->second.fwkTimerStatus == false) { + HILOGE("FwkTimer is unregistered, register first."); + return true; } + + it->second.fwkTimerStatus = false; + timer_.Unregister(it->second.timerId); + HILOGI("StopFwkTimer end bundleName %{public}s", bundleName.c_str()); + return true; } -bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t timeOut, - const Utils::Timer::TimerCallback &callback) +bool SvcSessionManager::StartExtTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) { unique_lock lock(lock_); + HILOGI("StartExtTimer begin bundleName %{public}s", bundleName.c_str()); if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + HILOGE("No caller token was specified"); + return false; + } + auto it = GetBackupExtNameMap(bundleName); + if (it->second.extTimerStatus == true) { + HILOGE("ExtTimer is registered, unregister first."); + return false; } + uint32_t timeout = it->second.timeout; + timeout = (timeout != BConstants::TIMEOUT_INVALID) ? timeout : BConstants::DEFAULT_TIMEOUT; + it->second.extTimerStatus = true; + it->second.timerId = timer_.Register(callback, timeout, true); + HILOGI("StartExtTimer end, timeout %{public}u(ms), bundleName %{public}s", timeout, bundleName.c_str()); + return true; +} +bool SvcSessionManager::StopExtTimer(const std::string &bundleName) +{ + unique_lock lock(lock_); + HILOGI("StopExtTimer begin bundleName %{public}s", bundleName.c_str()); + if (!impl_.clientToken) { + HILOGE("No caller token was specified"); + return false; + } auto it = GetBackupExtNameMap(bundleName); - if (it->second.timerStatus == true) { - // 定时器已存在,则先销毁,再重新注册 - it->second.timerStatus = false; - extBundleTimer.Unregister(it->second.extTimerId); - HILOGI("UpdateTimer timeout=%{public}u(ms), bundleName=%{public}s ", - timeOut, bundleName.c_str()); - it->second.extTimerId = extBundleTimer.Register(callback, timeOut, true); - it->second.timerStatus = true; + if (it->second.extTimerStatus == false) { + HILOGE("ExtTimer is unregistered, register first."); return true; } - return false; + + it->second.extTimerStatus = false; + it->second.timeout = BConstants::TIMEOUT_INVALID; + timer_.Unregister(it->second.timerId); + HILOGI("StopExtTimer end bundleName %{public}s", bundleName.c_str()); + return true; } -void SvcSessionManager::BundleExtTimerStop(const std::string &bundleName) +bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t timeout, + const Utils::Timer::TimerCallback &callback) { unique_lock lock(lock_); + HILOGI("UpdateTimer begin bundleName %{public}s", bundleName.c_str()); if (!impl_.clientToken) { - throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + HILOGE("No caller token was specified"); + return false; } - auto it = GetBackupExtNameMap(bundleName); - if (it->second.timerStatus == true) { - it->second.timerStatus = false; - extBundleTimer.Unregister(it->second.extTimerId); + it->second.timeout = timeout; + if (it->second.extTimerStatus == false) { + HILOGI("ExtTimer is unregistered, just store timeout %{public}u(ms)", timeout); + return true; } + + timer_.Unregister(it->second.timerId); + HILOGI("UpdateTimer timeout %{public}u(ms), bundleName %{public}s ", timeout, bundleName.c_str()); + it->second.timerId = timer_.Register(callback, timeout, true); + it->second.extTimerStatus = true; + HILOGI("UpdateTimer end bundleName %{public}s", bundleName.c_str()); + return true; } -void SvcSessionManager::IncreaseSessionCnt() +void SvcSessionManager::IncreaseSessionCnt(const std::string funcName) { sessionCnt_++; + HILOGI("func name:%{public}s, %{public}d.", funcName.c_str(), sessionCnt_.load()); } -void SvcSessionManager::DecreaseSessionCnt() +void SvcSessionManager::DecreaseSessionCnt(const std::string funcName) { - unique_lock lock(lock_); if (sessionCnt_.load() > 0) { sessionCnt_--; } else { HILOGE("Invalid sessionCount."); } + HILOGI("func name:%{public}s, %{public}d.", funcName.c_str(), sessionCnt_.load()); } -void SvcSessionManager::ClearSessionData() +ErrCode SvcSessionManager::ClearSessionData() { unique_lock lock(lock_); + ErrCode ret = BError(BError::Codes::OK); for (auto &&it : impl_.backupExtNameMap) { // clear timer - if (it.second.timerStatus == true) { - it.second.timerStatus = false; - extBundleTimer.Unregister(it.second.extTimerId); + if (it.second.fwkTimerStatus == true || it.second.extTimerStatus == true) { + it.second.fwkTimerStatus = false; + it.second.extTimerStatus = false; + timer_.Unregister(it.second.timerId); } // disconnect extension if (it.second.schedAction == BConstants::ServiceSchedAction::RUNNING) { auto backUpConnection = it.second.backUpConnection; if (backUpConnection == nullptr) { HILOGE("Clear session error, backUpConnection is empty"); - return; + return BError(BError::Codes::SA_INVAL_ARG); } auto proxy = backUpConnection->GetBackupExtProxy(); if (proxy == nullptr) { HILOGE("Clear session error, proxy is empty"); - return; + return BError(BError::Codes::EXT_INVAL_ARG); } if (impl_.restoreDataType != RestoreTypeEnum::RESTORE_DATA_READDY) { - proxy->HandleClear(); + ret = proxy->HandleClear(); } backUpConnection->DisconnectBackupExtAbility(); } + if (ret != BError(BError::Codes::OK)) { + return ret; + } // clear data it.second.schedAction = BConstants::ServiceSchedAction::FINISH; } impl_.backupExtNameMap.clear(); + return BError(BError::Codes::OK); } bool SvcSessionManager::GetIsIncrementalBackup() @@ -816,8 +918,90 @@ void SvcSessionManager::SetMemParaCurSize(int32_t size) memoryParaCurSize_ = size; } +void SvcSessionManager::SetClearDataFlag(const std::string &bundleName, bool isClearData) +{ + unique_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + auto it = GetBackupExtNameMap(bundleName); + it->second.isClearData = isClearData; + HILOGI("bundleName:%{public}s, set clear data flag:%{public}d.", bundleName.c_str(), isClearData); +} +bool SvcSessionManager::GetClearDataFlag(const std::string &bundleName) +{ + unique_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + auto it = GetBackupExtNameMap(bundleName); + return it->second.isClearData; +} + bool SvcSessionManager::ValidRestoreDataType(RestoreTypeEnum restoreDataType) { return impl_.restoreDataType == restoreDataType; } + +bool SvcSessionManager::CleanAndCheckIfNeedWait(ErrCode &ret, std::vector &bundleNameList) +{ + unique_lock lock(lock_); + for (auto it = impl_.backupExtNameMap.begin(); it != impl_.backupExtNameMap.end();) { + if (it->second.schedAction == BConstants::ServiceSchedAction::WAIT) { + it = impl_.backupExtNameMap.erase(it); + } else if (it->second.schedAction == BConstants::ServiceSchedAction::START || + (it->second.schedAction == BConstants::ServiceSchedAction::RUNNING && !it->second.isInPublishFile)) { + if (it->second.fwkTimerStatus == true || it->second.extTimerStatus == true) { + it->second.fwkTimerStatus = false; + it->second.extTimerStatus = false; + timer_.Unregister(it->second.timerId); + } + auto backUpConnection = it->second.backUpConnection; + if (backUpConnection == nullptr) { + HILOGE("Clear session error, backUpConnection is empty"); + it = impl_.backupExtNameMap.erase(it); + continue; + } + auto proxy = backUpConnection->GetBackupExtProxy(); + // start action + if (proxy == nullptr) { + HILOGE("Clear session error, backUpConnection is empty"); + backUpConnection->DisconnectBackupExtAbility(); + it = impl_.backupExtNameMap.erase(it); + continue; + } + // running action + ErrCode retTmp = ERR_OK; + if (impl_.restoreDataType != RestoreTypeEnum::RESTORE_DATA_READDY) { + retTmp = proxy->HandleClear(); + } + if (retTmp == ERR_OK) { + bundleNameList.push_back(it->first); + } else { + ret = retTmp; + } + backUpConnection->DisconnectBackupExtAbility(); + it = impl_.backupExtNameMap.erase(it); + } else { + ++it; + } + } + if (impl_.backupExtNameMap.empty()) { + HILOGI("Release normally, no need wait"); + return false; + } + HILOGI("Release abnormally, need wait for restore"); + return true; +} + +void SvcSessionManager::SetPublishFlag(const std::string &bundleName) +{ + unique_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + auto it = GetBackupExtNameMap(bundleName); + it->second.isInPublishFile = true; + HILOGE("Set PublishFile success, bundleName = %{public}s", bundleName.c_str()); +} } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_sched/sched_scheduler.cpp b/services/backup_sa/src/module_sched/sched_scheduler.cpp index 726c742d466df94cb84b64c6a2ba80cff02bdf2b..8d85731b3f3e1d6d8cd2a5f723f7bfbe75b03525 100644 --- a/services/backup_sa/src/module_sched/sched_scheduler.cpp +++ b/services/backup_sa/src/module_sched/sched_scheduler.cpp @@ -72,28 +72,30 @@ void SchedScheduler::Sched(string bundleName) void SchedScheduler::ExecutingQueueTasks(const string &bundleName) { - HILOGE("start"); if (sessionPtr_ == nullptr) { HILOGE("ExecutingQueueTasks bundle %{public}s error, sessionPtr is empty", bundleName.c_str()); return; } BConstants::ServiceSchedAction action = sessionPtr_->GetServiceSchedAction(bundleName); if (action == BConstants::ServiceSchedAction::START) { - // 注册启动定时器 + // register timer for connect extension auto callStart = [reversePtr {reversePtr_}, bundleName]() { HILOGE("Extension connect failed = %{public}s", bundleName.data()); auto ptr = reversePtr.promote(); if (ptr) { - ptr->ExtConnectFailed(bundleName, BError(BError::Codes::SA_BOOT_TIMEOUT)); + ptr->ExtConnectFailed(bundleName, BError(BError::Codes::SA_BOOT_EXT_TIMEOUT)); } }; auto iTime = extTime_.Register(callStart, BConstants::EXT_CONNECT_MAX_TIME, true); unique_lock lock(lock_); bundleTimeVec_.emplace_back(make_tuple(bundleName, iTime)); lock.unlock(); - // 启动extension + // launch extension if (reversePtr_ != nullptr) { - reversePtr_->LaunchBackupExtension(bundleName); + ErrCode errCode = reversePtr_->LaunchBackupExtension(bundleName); + if (errCode) { + reversePtr_->ExtConnectFailed(bundleName, errCode); + } } } else if (action == BConstants::ServiceSchedAction::RUNNING) { HILOGI("Current bundle %{public}s process is running", bundleName.data()); @@ -106,16 +108,17 @@ void SchedScheduler::ExecutingQueueTasks(const string &bundleName) throw BError(BError::Codes::SA_INVAL_ARG, "Failed to find timer"); } auto &[bName, iTime] = *iter; - // 移除启动定时器 当前逻辑无启动成功后的ext心跳检测 + // unregister timer extTime_.Unregister(iTime); lock.unlock(); - // 开始执行备份恢复流程 - HILOGI("Current bundle %{public}s extension start", bundleName.data()); - //通知应用市场设置处置 + //notify AppGallery to start restore if (reversePtr_ != nullptr) { reversePtr_->SendStartAppGalleryNotify(bundleName); reversePtr_->ExtStart(bundleName); } + } else if (action == BConstants::ServiceSchedAction::CLEAN) { + HILOGI("Current bundle %{public}s process is cleaning", bundleName.data()); + reversePtr_->ClearResidualBundleData(bundleName); } } @@ -137,16 +140,14 @@ void SchedScheduler::RemoveExtConn(const string &bundleName) void SchedScheduler::StartTimer() { extTime_.Setup(); - if (!BackupPara().GetBackupOverrideBackupSARelease()) { - TryUnloadServiceTimer(); - } + TryUnloadServiceTimer(); } void SchedScheduler::TryUnloadServiceTimer(bool force) { auto tryUnload = [sessionPtr {sessionPtr_}]() { auto ptr = sessionPtr.promote(); - if (ptr && !ptr->NeedToUnloadService()) { + if (ptr && ptr->GetSessionCnt() > 0) { return; } HILOGI("Unload system ability"); diff --git a/services/backupservice.para b/services/backupservice.para index b2d857b67d47afa32f6c827f5811be12a6f6652d..f87a8b1a6a5f84f4c4d0f621d513b120577b9eb3 100644 --- a/services/backupservice.para +++ b/services/backupservice.para @@ -11,4 +11,4 @@ # See the License for the specific language governing permissions and # limitations under the License. -persist.backupservice.workstatus=false \ No newline at end of file +persist.backupservice.workstatus=true \ No newline at end of file diff --git a/test/fuzztest/backupext_fuzzer/BUILD.gn b/test/fuzztest/backupext_fuzzer/BUILD.gn index b406dbcd5abcaaecf629daaae384b75e6e03c970..5d32a6bd681a5347f6590ec3cf19485f855f612a 100644 --- a/test/fuzztest/backupext_fuzzer/BUILD.gn +++ b/test/fuzztest/backupext_fuzzer/BUILD.gn @@ -42,6 +42,7 @@ ohos_fuzztest("BackupExtFuzzTest") { "${path_backup}/frameworks/native/backup_ext/src/ext_backup_loader.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_extension.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_extension_stub.cpp", + "${path_backup}/frameworks/native/backup_ext/src/sub_ext_extension.cpp", "${path_backup}/frameworks/native/backup_ext/src/tar_file.cpp", "${path_backup}/frameworks/native/backup_ext/src/untar_file.cpp", "backupext_fuzzer.cpp", diff --git a/test/fuzztest/backupext_fuzzer/backupext_fuzzer.cpp b/test/fuzztest/backupext_fuzzer/backupext_fuzzer.cpp index 2528f0082b50f842a0afae2763c90b061983ce2b..d00abd06b85291998fde89fecb04c02d5267fd01 100644 --- a/test/fuzztest/backupext_fuzzer/backupext_fuzzer.cpp +++ b/test/fuzztest/backupext_fuzzer/backupext_fuzzer.cpp @@ -273,7 +273,7 @@ extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { /* Run your code on data */ auto extBackup = std::make_shared(); - auto extension = std::make_shared(extBackup); + auto extension = std::make_shared(extBackup, ""); OHOS::OnRemoteRequestFuzzTest(extension, data, size); OHOS::InitFuzzTest(extBackup, data, size); diff --git a/test/fuzztest/backupservicestub_fuzzer/backupservicestub_fuzzer.cpp b/test/fuzztest/backupservicestub_fuzzer/backupservicestub_fuzzer.cpp index 854692d2cacdcf8b82c861016d8d9f75590ced0c..b3c714e657930d70deb33921cba61a1f83e6e395 100644 --- a/test/fuzztest/backupservicestub_fuzzer/backupservicestub_fuzzer.cpp +++ b/test/fuzztest/backupservicestub_fuzzer/backupservicestub_fuzzer.cpp @@ -574,9 +574,9 @@ bool CmdUpdateTimerFuzzTest(sptr service, const uint8_t *data, size_t s try { int pos = 0; - int32_t timeOut = TypeCast(data, &pos); + int32_t timeout = TypeCast(data, &pos); msg.WriteString(string(reinterpret_cast(data + pos), size - pos)); - msg.WriteInt32(timeOut); + msg.WriteInt32(timeout); service->CmdUpdateTimer(msg, reply); } catch (OHOS::FileManagement::Backup::BError &err) { // Only filter BError errors, Other results are not expected. diff --git a/tests/mock/accesstoken/accesstoken_kit_mock.cpp b/tests/mock/accesstoken/accesstoken_kit_mock.cpp index 1531837704a37124fc2d4f1f7bb08ae806b07081..f2c5795cc147ff1ce70e97cd0ba0b5561a790999 100644 --- a/tests/mock/accesstoken/accesstoken_kit_mock.cpp +++ b/tests/mock/accesstoken/accesstoken_kit_mock.cpp @@ -14,6 +14,7 @@ */ #include "accesstoken_kit.h" +#include "tokenid_kit.h" namespace OHOS::Security::AccessToken { ATokenTypeEnum AccessTokenKit::GetTokenType(AccessTokenID tokenID) @@ -31,4 +32,9 @@ int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string & { return 0; } + +bool TokenIdKit::IsSystemAppByFullTokenID(uint64_t tokenId) +{ + return true; +} } // namespace OHOS::Security::AccessToken diff --git a/tests/mock/backup_ext/include/ext_backup_mock.h b/tests/mock/backup_ext/include/ext_backup_mock.h index 1ef89adfe95ac3212e63660902a568f9ba722e15..76826057ba1cb173b13d8003330277e47cf5959b 100644 --- a/tests/mock/backup_ext/include/ext_backup_mock.h +++ b/tests/mock/backup_ext/include/ext_backup_mock.h @@ -51,6 +51,7 @@ public: virtual BConstants::ExtensionAction VerifyAndGetAction(const AAFwk::Want &, std::shared_ptr) = 0; virtual ErrCode GetParament(const AAFwk::Want &) = 0; + virtual ErrCode OnProcess(std::function callback) = 0; public: virtual std::unique_ptr LoadSystemModuleByEngine(napi_env, const std::string&, const napi_value*, size_t) = 0; @@ -86,6 +87,7 @@ public: std::function)); MOCK_METHOD(ErrCode, OnRestore, (std::function)); MOCK_METHOD(ErrCode, GetBackupInfo, (std::function)); + MOCK_METHOD(ErrCode, OnProcess, (std::function)); MOCK_METHOD(bool, WasFromSpecialVersion, ()); MOCK_METHOD(bool, SpecialVersionForCloneAndCloud, ()); MOCK_METHOD(bool, RestoreDataReady, ()); diff --git a/tests/mock/backup_ext/src/ext_backup_mock.cpp b/tests/mock/backup_ext/src/ext_backup_mock.cpp index 457d01de6da96a0d05717a47936c62931de0b116..16d6f55b5f87d21699d7fc81342b68ce95755ff5 100644 --- a/tests/mock/backup_ext/src/ext_backup_mock.cpp +++ b/tests/mock/backup_ext/src/ext_backup_mock.cpp @@ -133,4 +133,9 @@ ErrCode ExtBackup::InvokeAppExtMethod(ErrCode errCode, const std::string result) { return BExtBackup::extBackup->InvokeAppExtMethod(errCode, result); } + +ErrCode ExtBackup::OnProcess(function callback) +{ + return BExtBackup::extBackup->OnProcess(callback); +} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp b/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp index dd71f134c5a737fb93400b6073b8aa5b7b292854..b1b7b6b2b9587543ec892203481f66fbc9701c79 100644 --- a/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp +++ b/tests/mock/backup_kit_inner/b_session_restore_async_mock.cpp @@ -89,6 +89,7 @@ ErrCode BSessionRestoreAsync::AppendBundles(UniqueFd remoteCap, vector ServiceProxy::GetServiceProxyPointer() +{ + return serviceProxy_; +} + sptr ServiceProxy::GetInstance() { if (!GetMockGetInstance()) { diff --git a/tests/mock/cJson/include/cJsonMock.h b/tests/mock/cJson/include/cJsonMock.h deleted file mode 100644 index 6d47050cd8f046f0a327eae5b9be8bfc7719545b..0000000000000000000000000000000000000000 --- a/tests/mock/cJson/include/cJsonMock.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * 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_CJSON_MOCK_H -#define OHOS_FILEMGMT_BACKUP_CJSON_MOCK_H - -#include -#include - -namespace OHOS::FileManagement::Backup { -class CJson { -public: - CJson() = default; - virtual ~CJson() = default; - -public: - virtual cJSON *cJSON_CreateArray() = 0; - virtual cJSON *cJSON_CreateObject() = 0; - virtual char *cJSON_Print(const cJSON *item) = 0; - virtual cJSON *cJSON_Parse(const char *value) = 0; - virtual cJSON *cJSON_GetObjectItem(const cJSON *const object, const char *const string) = 0; - virtual void cJSON_Delete(cJSON *item) = 0; - virtual cJSON_bool cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) = 0; - virtual int cJSON_GetArraySize(const cJSON *array) = 0; - virtual cJSON_bool cJSON_AddItemToArray(cJSON *array, cJSON *item); - virtual cJSON *cJSON_AddStringToObject(cJSON *const object, const char *const name, const char *const string); - -public: - static inline std::shared_ptr cJsonPtr = nullptr; -}; - -class CJsonMock : public CJson { -public: - MOCK_METHOD3(cJSON_AddItemToObject, cJSON_bool(cJSON *object, const char *string, cJSON *item)); - MOCK_METHOD1(cJSON_Delete, void(cJSON *item)); - MOCK_METHOD0(cJSON_CreateObject, cJSON *()); - MOCK_METHOD0(cJSON_CreateArray, cJSON *()); - MOCK_METHOD1(cJSON_Print, char *(const cJSON *item)); - MOCK_METHOD1(cJSON_Parse, cJSON *(const char *value)); - MOCK_METHOD2(cJSON_GetObjectItem, cJSON *(const cJSON *const object, const char *const string)); - MOCK_METHOD1(cJSON_GetArraySize, int(const cJSON *array)); - MOCK_METHOD2(cJSON_AddItemToArray, cJSON_bool(cJSON *array, cJSON *item)); - MOCK_METHOD3(cJSON_AddStringToObject, - cJSON *(cJSON *const object, const char *const name, const char *const string)); -}; -} // namespace OHOS::FileManagement::Backup -#endif \ No newline at end of file diff --git a/tests/mock/cJson/src/cJsonMock.cpp b/tests/mock/cJson/src/cJsonMock.cpp deleted file mode 100644 index 8aa2427dd9bb1a7b0be9618bc5f35dbd5c78662e..0000000000000000000000000000000000000000 --- a/tests/mock/cJson/src/cJsonMock.cpp +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright (C) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -#include - -#include "cJsonMock.h" - -using namespace OHOS::FileManagement::Backup; - -CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void) -{ - return CJson::cJsonPtr->cJSON_CreateArray(); -} - -CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void) -{ - return CJson::cJsonPtr->cJSON_CreateObject(); -} - -CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item) -{ - return CJson::cJsonPtr->cJSON_Print(item); -} - -CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value) -{ - return CJson::cJsonPtr->cJSON_Parse(value); -} - -CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON *const object, const char *const string) -{ - return CJson::cJsonPtr->cJSON_GetObjectItem(object, string); -} - -CJSON_PUBLIC(void) cJSON_Delete(cJSON *item) -{ - return CJson::cJsonPtr->cJSON_Delete(item); -} - -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item) -{ - return CJson::cJsonPtr->cJSON_AddItemToObject(object, string, item); -} - -CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array) -{ - return CJson::cJsonPtr->cJSON_GetArraySize(array); -} - -CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item) -{ - return CJson::cJsonPtr->cJSON_AddItemToArray(array, item); -} - -CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string) -{ - return CJson::cJsonPtr->cJSON_AddStringToObject(object, name, string); -} \ No newline at end of file diff --git a/tests/mock/module_external/bms_adapter_mock.cpp b/tests/mock/module_external/bms_adapter_mock.cpp index cef59d5f1921af0494ce638b98d1fe311cb02154..2a1232d0319805467290771917b4dc5b6d7bab20 100644 --- a/tests/mock/module_external/bms_adapter_mock.cpp +++ b/tests/mock/module_external/bms_adapter_mock.cpp @@ -32,7 +32,8 @@ vector BundleMgrAdapter::GetBundleInfos(const vecto { vector bundleInfos; bundleInfos.emplace_back( - BJsonEntityCaps::BundleInfo {"com.example.app2backup", {}, {}, 0, 0, true, false, "com.example.app2backup"}); + BJsonEntityCaps::BundleInfo {"com.example.app2backup", 0, {}, {}, 0, 0, true, false, + "com.example.app2backup"}); return bundleInfos; } @@ -46,7 +47,8 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement { vector bundleInfos; bundleInfos.emplace_back( - BJsonEntityCaps::BundleInfo {"com.example.app2backup", {}, {}, 0, 0, true, false, "com.example.app2backup"}); + BJsonEntityCaps::BundleInfo {"com.example.app2backup", 0, {}, {}, 0, 0, true, false, + "com.example.app2backup"}); return bundleInfos; } @@ -55,7 +57,17 @@ vector BundleMgrAdapter::GetBundleInfosForIncrement { vector bundleInfos; bundleInfos.emplace_back( - BJsonEntityCaps::BundleInfo {"com.example.app2backup", {}, {}, 0, 0, true, false, "com.example.app2backup"}); + BJsonEntityCaps::BundleInfo {"com.example.app2backup", 0, {}, {}, 0, 0, true, false, + "com.example.app2backup"}); + return bundleInfos; +} + +vector BundleMgrAdapter::GetFullBundleInfos(int32_t userId) +{ + vector bundleInfos; + bundleInfos.emplace_back( + BJsonEntityCaps::BundleInfo {"com.example.app2backup", 0, {}, {}, 0, 0, true, false, + "com.example.app2backup"}); return bundleInfos; } @@ -63,4 +75,9 @@ string BundleMgrAdapter::GetExtName(string bundleName, int32_t userId) { return "BackupExtensionAbility"; } + +bool BundleMgrAdapter::IsUser0BundleName(std::string bundleName, int32_t userId) +{ + return true; +} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/service_mock.cpp b/tests/mock/module_ipc/service_mock.cpp index c058c5e8365192df93ca1661178718dc278033a4..f762791b9e75b80ebea8f280ebb1dc6c9fa982c8 100644 --- a/tests/mock/module_ipc/service_mock.cpp +++ b/tests/mock/module_ipc/service_mock.cpp @@ -216,7 +216,17 @@ ErrCode Service::GetBackupInfo(BundleName &bundleName, std::string &result) return BError(BError::Codes::OK); } -ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) +ErrCode Service::StartExtTimer(bool &isExtStart) +{ + return BError(BError::Codes::OK); +} + +ErrCode Service::StartFwkTimer(bool &isFwkStart) +{ + return BError(BError::Codes::OK); +} + +ErrCode Service::UpdateTimer(BundleName &bundleName, uint32_t timeout, bool &result) { return BError(BError::Codes::OK); } @@ -226,6 +236,11 @@ ErrCode Service::UpdateSendRate(std::string &bundleName, int32_t sendRate, bool return BError(BError::Codes::OK); } +ErrCode Service::ReportAppProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario) +{ + return BError(BError::Codes::OK); +} + void Service::OnSABackup(const std::string &bundleName, const int &fd, const std::string &result, @@ -234,4 +249,8 @@ void Service::OnSABackup(const std::string &bundleName, } void Service::OnSARestore(const std::string &bundleName, const std::string &result, const ErrCode &errCode) {} + +void Service::ClearResidualBundleData(const std::string &bundleName) +{ +} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/service_reverse_proxy_mock.cpp b/tests/mock/module_ipc/service_reverse_proxy_mock.cpp index 1d7b598d4ce821942ecae41db23bb2ea2126d414..1b224076d31f04363b8035c384aa14f4a4214132 100644 --- a/tests/mock/module_ipc/service_reverse_proxy_mock.cpp +++ b/tests/mock/module_ipc/service_reverse_proxy_mock.cpp @@ -30,6 +30,8 @@ void ServiceReverseProxy::BackupOnBundleFinished(int32_t errCode, string bundleN void ServiceReverseProxy::BackupOnAllBundlesFinished(int32_t errCode) {} +void ServiceReverseProxy::BackupOnProcessInfo(std::string bundleName, std::string processInfo) {} + void ServiceReverseProxy::RestoreOnBundleStarted(int32_t errCode, string bundleName) {} void ServiceReverseProxy::RestoreOnBundleFinished(int32_t errCode, string bundleName) {} @@ -40,6 +42,8 @@ void ServiceReverseProxy::RestoreOnFileReady(string bundleName, string fileName, void ServiceReverseProxy::RestoreOnResultReport(string result, string bundleName, ErrCode errCode) {} +void ServiceReverseProxy::RestoreOnProcessInfo(std::string bundleName, std::string processInfo) {} + void ServiceReverseProxy::IncrementalBackupOnFileReady(string bundleName, string fileName, int fd, int manifestFd, int32_t errCode) {} @@ -51,6 +55,8 @@ void ServiceReverseProxy::IncrementalBackupOnBundleFinished(int32_t errCode, str void ServiceReverseProxy::IncrementalBackupOnAllBundlesFinished(int32_t errCode) {} +void ServiceReverseProxy::IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) {} + void ServiceReverseProxy::IncrementalRestoreOnBundleStarted(int32_t errCode, string bundleName) {} void ServiceReverseProxy::IncrementalRestoreOnBundleFinished(int32_t errCode, string bundleName) {} @@ -61,4 +67,6 @@ void ServiceReverseProxy::IncrementalRestoreOnFileReady(string bundleName, strin int32_t errCode) {} void ServiceReverseProxy::IncrementalRestoreOnResultReport(string result, string bundleName, ErrCode errCode) {} + +void ServiceReverseProxy::IncrementalRestoreOnProcessInfo(std::string bundleName, std::string processInfo) {} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/module_ipc/service_stub_mock.cpp b/tests/mock/module_ipc/service_stub_mock.cpp index 9d4b055697a1c411c87b79d51e27bf7fbd47fd5d..dfc837dbf625db53329eb16993eded3e6d5fa3f5 100644 --- a/tests/mock/module_ipc/service_stub_mock.cpp +++ b/tests/mock/module_ipc/service_stub_mock.cpp @@ -81,6 +81,8 @@ void ServiceStub::ServiceStubSupplement() &ServiceStub::CmdUpdateTimer; opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_UPDATE_SENDRATE)] = &ServiceStub::CmdUpdateSendRate; + opToInterfaceMap_[static_cast(IServiceInterfaceCode::SERVICE_CMD_REPORT_APP_PROCESS_INFO)] = + &ServiceStub::CmdReportAppProcessInfo; } int32_t ServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -240,12 +242,12 @@ int32_t ServiceStub::CmdUpdateTimer(MessageParcel &data, MessageParcel &reply) if (!data.ReadString(bundleName)) { return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to recive bundleName")); } - uint32_t timeOut; - if (!data.ReadUint32(timeOut)) { - return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to recive timeOut")); + uint32_t timeout; + if (!data.ReadUint32(timeout)) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to recive timeout")); } bool result; - ret = UpdateTimer(bundleName, timeOut, result); + ret = UpdateTimer(bundleName, timeout, result); return BError(BError::Codes::OK); } @@ -311,4 +313,9 @@ int32_t ServiceStub::CmdGetIncrementalFileHandle(MessageParcel &data, MessagePar { return BError(BError::Codes::OK); } + +int32_t ServiceStub::CmdReportAppProcessInfo(MessageParcel &data, MessageParcel &reply) +{ + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/svc_backup_connection_mock.cpp b/tests/mock/module_ipc/svc_backup_connection_mock.cpp index 1d007fa7c4cb0baad931ed09c09b08a3a9a8d477..0af352b4e188d2f89e68547ec3ac03775b6bac0e 100644 --- a/tests/mock/module_ipc/svc_backup_connection_mock.cpp +++ b/tests/mock/module_ipc/svc_backup_connection_mock.cpp @@ -55,6 +55,11 @@ ErrCode SvcBackupConnection::DisconnectBackupExtAbility() return 0; } +bool SvcBackupConnection::WaitDisconnectDone() +{ + return true; +} + bool SvcBackupConnection::IsExtAbilityConnected() { bool bFlag = g_bExtAbilityConnected; diff --git a/tests/mock/module_ipc/svc_extension_proxy_mock.cpp b/tests/mock/module_ipc/svc_extension_proxy_mock.cpp index bd20c461fc5470db4ea6772b7349e89a44991845..bb000e0900a90ffe5f8b665150286f646df861f2 100644 --- a/tests/mock/module_ipc/svc_extension_proxy_mock.cpp +++ b/tests/mock/module_ipc/svc_extension_proxy_mock.cpp @@ -28,7 +28,7 @@ ErrCode SvcExtensionProxy::HandleClear() return 0; } -ErrCode SvcExtensionProxy::HandleBackup() +ErrCode SvcExtensionProxy::HandleBackup(bool isClearData) { return 0; } @@ -38,7 +38,7 @@ ErrCode SvcExtensionProxy::PublishFile(const string &fileName) return 0; } -ErrCode SvcExtensionProxy::HandleRestore() +ErrCode SvcExtensionProxy::HandleRestore(bool isClearData) { return 0; } @@ -63,7 +63,7 @@ ErrCode SvcExtensionProxy::HandleIncrementalBackup(UniqueFd incrementalFd, Uniqu return 0; } -ErrCode SvcExtensionProxy::IncrementalOnBackup() +ErrCode SvcExtensionProxy::IncrementalOnBackup(bool isClearData) { return 0; } @@ -73,6 +73,11 @@ ErrCode SvcExtensionProxy::UpdateFdSendRate(std::string &bundleName, int32_t sen return 0; } +ErrCode SvcExtensionProxy::User0OnBackup() +{ + return 0; +} + tuple SvcExtensionProxy::GetIncrementalBackupFileHandle() { return {UniqueFd(-1), UniqueFd(-1)}; diff --git a/tests/mock/module_ipc/svc_session_manager_mock.cpp b/tests/mock/module_ipc/svc_session_manager_mock.cpp index 320bdd66cd0b298fe6873337d3f87cbc6899116f..0c1665b82af8650fc5c0e0065e904927b9665b85 100644 --- a/tests/mock/module_ipc/svc_session_manager_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_mock.cpp @@ -41,7 +41,7 @@ void SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceRe GTEST_LOG_(INFO) << "VerifyCallerAndScenario"; } -ErrCode SvcSessionManager::Active(Impl newImpl) +ErrCode SvcSessionManager::Active(Impl newImpl, bool force) { GTEST_LOG_(INFO) << "Active"; extConnectNum_ = 0; @@ -104,7 +104,8 @@ wptr SvcSessionManager::GetExtConnection(const BundleName & if (!it->second.backUpConnection) { auto callDied = [](const string &&bundleName) {}; auto callConnected = [](const string &&bundleName) {}; - it->second.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnected)); + it->second.backUpConnection = sptr(new SvcBackupConnection(callDied, callConnected, + bundleName)); sptr mock = sptr(new BackupExtExtensionMock()); it->second.backUpConnection->OnAbilityConnectDone({}, mock->AsObject(), 0); } @@ -114,7 +115,7 @@ wptr SvcSessionManager::GetExtConnection(const BundleName & sptr SvcSessionManager::GetBackupAbilityExt(const string &bundleName) { GTEST_LOG_(INFO) << "GetBackupAbilityExt"; - return sptr(new SvcBackupConnection(nullptr, nullptr)); + return sptr(new SvcBackupConnection(nullptr, nullptr, bundleName)); } void SvcSessionManager::DumpInfo(const int fd, const std::vector &args) @@ -353,21 +354,35 @@ void SvcSessionManager::SetBundleDataSize(const std::string &bundleName, int64_t it->second.dataSize = dataSize; } -void SvcSessionManager::BundleExtTimerStart(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) +bool SvcSessionManager::StartFwkTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) { + return true; } -bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t timeOut, - const Utils::Timer::TimerCallback &callback) +bool SvcSessionManager::StopFwkTimer(const std::string &bundleName) { return true; } -void SvcSessionManager::BundleExtTimerStop(const std::string &bundleName) {} +bool SvcSessionManager::StartExtTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) +{ + return true; +} -void SvcSessionManager::IncreaseSessionCnt() {} +bool SvcSessionManager::StopExtTimer(const std::string &bundleName) +{ + return true; +} -void SvcSessionManager::DecreaseSessionCnt() {} +bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t timeout, + const Utils::Timer::TimerCallback &callback) +{ + return true; +} + +void SvcSessionManager::IncreaseSessionCnt(const std::string funcName) {} + +void SvcSessionManager::DecreaseSessionCnt(const std::string funcName) {} int32_t SvcSessionManager::GetMemParaCurSize() { @@ -376,7 +391,10 @@ int32_t SvcSessionManager::GetMemParaCurSize() void SvcSessionManager::SetMemParaCurSize(int32_t size) {} -void SvcSessionManager::ClearSessionData() {} +ErrCode SvcSessionManager::ClearSessionData() +{ + return 0; +} bool SvcSessionManager::GetIsIncrementalBackup() { @@ -393,6 +411,18 @@ SvcSessionManager::Impl SvcSessionManager::GetImpl() return impl_; } +int SvcSessionManager::GetSessionCnt() +{ + return sessionCnt_.load(); +} + +void SvcSessionManager::SetClearDataFlag(const std::string &bundleName, bool isNotClear) {} + +bool SvcSessionManager::GetClearDataFlag(const std::string &bundleName) +{ + return true; +} + void SvcSessionManager::SetIncrementalData(const BIncrementalData &incrementalData) {} int32_t SvcSessionManager::GetIncrementalManifestFd(const string &bundleName) @@ -404,4 +434,11 @@ int64_t SvcSessionManager::GetLastIncrementalTime(const string &bundleName) { return 0; } + +bool SvcSessionManager::CleanAndCheckIfNeedWait(ErrCode &ret, std::vector &bundleNameList) +{ + return false; +} + +void SvcSessionManager::SetPublishFlag(const std::string &bundleName) {} } // 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 9ba4687b8fa3a87246f3cb89c89a259c7f5dab32..e444a01b9a8462d80085de17802611d34d4676a9 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.cpp @@ -24,7 +24,7 @@ void SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceRe BackupSvcSessionManager::session->VerifyCallerAndScenario(clientToken, scenario); } -ErrCode SvcSessionManager::Active(Impl newImpl) +ErrCode SvcSessionManager::Active(Impl newImpl, bool force) { return BackupSvcSessionManager::session->Active(newImpl); } @@ -219,30 +219,40 @@ void SvcSessionManager::SetBundleDataSize(const std::string &bundleName, int64_t BackupSvcSessionManager::session->SetBundleDataSize(bundleName, dataSize); } -void SvcSessionManager::BundleExtTimerStart(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) +bool SvcSessionManager::StartFwkTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) { - BackupSvcSessionManager::session->BundleExtTimerStart(bundleName, callback); + return BackupSvcSessionManager::session->StartFwkTimer(bundleName, callback); } -bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t timeOut, - const Utils::Timer::TimerCallback &callback) +bool SvcSessionManager::StopFwkTimer(const std::string &bundleName) +{ + return BackupSvcSessionManager::session->StopFwkTimer(bundleName); +} + +bool SvcSessionManager::StartExtTimer(const std::string &bundleName, const Utils::Timer::TimerCallback &callback) { - return BackupSvcSessionManager::session->UpdateTimer(bundleName, timeOut, callback); + return BackupSvcSessionManager::session->StartExtTimer(bundleName, callback); } -void SvcSessionManager::BundleExtTimerStop(const std::string &bundleName) +bool SvcSessionManager::StopExtTimer(const std::string &bundleName) { - BackupSvcSessionManager::session->BundleExtTimerStop(bundleName); + return BackupSvcSessionManager::session->StopExtTimer(bundleName); } -void SvcSessionManager::IncreaseSessionCnt() +bool SvcSessionManager::UpdateTimer(const std::string &bundleName, uint32_t timeout, + const Utils::Timer::TimerCallback &callback) { - BackupSvcSessionManager::session->IncreaseSessionCnt(); + return BackupSvcSessionManager::session->UpdateTimer(bundleName, timeout, callback); } -void SvcSessionManager::DecreaseSessionCnt() +void SvcSessionManager::IncreaseSessionCnt(const std::string funcName) { - BackupSvcSessionManager::session->DecreaseSessionCnt(); + BackupSvcSessionManager::session->IncreaseSessionCnt(funcName); +} + +void SvcSessionManager::DecreaseSessionCnt(const std::string funcName) +{ + BackupSvcSessionManager::session->DecreaseSessionCnt(funcName); } int32_t SvcSessionManager::GetMemParaCurSize() @@ -255,9 +265,9 @@ void SvcSessionManager::SetMemParaCurSize(int32_t size) BackupSvcSessionManager::session->SetMemParaCurSize(size); } -void SvcSessionManager::ClearSessionData() +ErrCode SvcSessionManager::ClearSessionData() { - BackupSvcSessionManager::session->ClearSessionData(); + return BackupSvcSessionManager::session->ClearSessionData(); } bool SvcSessionManager::GetIsIncrementalBackup() @@ -275,6 +285,21 @@ SvcSessionManager::Impl SvcSessionManager::GetImpl() return BackupSvcSessionManager::session->GetImpl(); } +int SvcSessionManager::GetSessionCnt() +{ + return BackupSvcSessionManager::session->GetSessionCnt(); +} + +void SvcSessionManager::SetClearDataFlag(const std::string &bundleName, bool isNotClear) +{ + BackupSvcSessionManager::session->SetClearDataFlag(bundleName, isNotClear); +} + +bool SvcSessionManager::GetClearDataFlag(const std::string &bundleName) +{ + return BackupSvcSessionManager::session->GetClearDataFlag(bundleName); +} + void SvcSessionManager::SetIncrementalData(const BIncrementalData &incrementalData) { BackupSvcSessionManager::session->SetIncrementalData(incrementalData); @@ -289,4 +314,11 @@ int64_t SvcSessionManager::GetLastIncrementalTime(const string &bundleName) { return BackupSvcSessionManager::session->GetLastIncrementalTime(bundleName); } + +bool SvcSessionManager::CleanAndCheckIfNeedWait(ErrCode &ret, std::vector &bundleNameList) +{ + return false; +} + +void SvcSessionManager::SetPublishFlag(const std::string &bundleName) {} } // 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 670bef53b5a5f69288fc3c03c021f0c6e0b716a3..41360d52577932babdec82acf767eac12e285db4 100644 --- a/tests/mock/module_ipc/svc_session_manager_throw_mock.h +++ b/tests/mock/module_ipc/svc_session_manager_throw_mock.h @@ -67,20 +67,27 @@ public: virtual void SetBundleVersionName(const std::string &, std::string) = 0; virtual std::string GetBundleVersionName(const std::string &) = 0; virtual void SetBundleDataSize(const std::string &, int64_t) = 0; - virtual void BundleExtTimerStart(const std::string &, const Utils::Timer::TimerCallback &) = 0; + virtual bool StartFwkTimer(const std::string &, const Utils::Timer::TimerCallback &) = 0; + virtual bool StopFwkTimer(const std::string &) = 0; + virtual bool StartExtTimer(const std::string &, const Utils::Timer::TimerCallback &) = 0; + virtual bool StopExtTimer(const std::string &) = 0; virtual bool UpdateTimer(const std::string &, uint32_t, const Utils::Timer::TimerCallback &) = 0; - virtual void BundleExtTimerStop(const std::string &) = 0; - virtual void IncreaseSessionCnt() = 0; - virtual void DecreaseSessionCnt() = 0; + virtual void IncreaseSessionCnt(const std::string) = 0; + virtual void DecreaseSessionCnt(const std::string) = 0; virtual int32_t GetMemParaCurSize() = 0; virtual void SetMemParaCurSize(int32_t) = 0; - virtual void ClearSessionData() = 0; + virtual ErrCode ClearSessionData() = 0; virtual bool GetIsIncrementalBackup() = 0; virtual bool ValidRestoreDataType(RestoreTypeEnum) = 0; virtual SvcSessionManager::Impl GetImpl() = 0; + virtual int GetSessionCnt() = 0; + virtual void SetClearDataFlag(const std::string &bundleName, bool isNotClear) = 0; + virtual bool GetClearDataFlag(const std::string &bundleName) = 0; virtual void SetIncrementalData(const BIncrementalData &) = 0; virtual int32_t GetIncrementalManifestFd(const std::string &) = 0; virtual int64_t GetLastIncrementalTime(const std::string &) = 0; + virtual bool CleanAndCheckIfNeedWait(ErrCode &ret, std::vector &bundleNameList) = 0; + virtual void SetPublishFlag(const std::string &bundleName) = 0; public: static inline std::shared_ptr session = nullptr; }; @@ -127,20 +134,27 @@ public: MOCK_METHOD(void, SetBundleVersionName, (const std::string &, std::string)); MOCK_METHOD(std::string, GetBundleVersionName, (const std::string &)); MOCK_METHOD(void, SetBundleDataSize, (const std::string &, int64_t)); - MOCK_METHOD(void, BundleExtTimerStart, (const std::string &, const Utils::Timer::TimerCallback &)); + MOCK_METHOD(bool, StartFwkTimer, (const std::string &, const Utils::Timer::TimerCallback &)); + MOCK_METHOD(bool, StopFwkTimer, (const std::string &)); + MOCK_METHOD(bool, StartExtTimer, (const std::string &, const Utils::Timer::TimerCallback &)); + MOCK_METHOD(bool, StopExtTimer, (const std::string &)); MOCK_METHOD(bool, UpdateTimer, (const std::string &, uint32_t, const Utils::Timer::TimerCallback &)); - MOCK_METHOD(void, BundleExtTimerStop, (const std::string &)); - MOCK_METHOD(void, IncreaseSessionCnt, ()); - MOCK_METHOD(void, DecreaseSessionCnt, ()); + MOCK_METHOD(void, IncreaseSessionCnt, (const std::string)); + MOCK_METHOD(void, DecreaseSessionCnt, (const std::string)); MOCK_METHOD(int32_t, GetMemParaCurSize, ()); MOCK_METHOD(void, SetMemParaCurSize, (int32_t)); - MOCK_METHOD(void, ClearSessionData, ()); + MOCK_METHOD(ErrCode, ClearSessionData, ()); MOCK_METHOD(bool, GetIsIncrementalBackup, ()); MOCK_METHOD(bool, ValidRestoreDataType, (RestoreTypeEnum)); MOCK_METHOD(SvcSessionManager::Impl, GetImpl, ()); + MOCK_METHOD(int, GetSessionCnt, ()); + MOCK_METHOD(void, SetClearDataFlag, (const std::string &, bool)); + MOCK_METHOD(bool, GetClearDataFlag, (const std::string &)); MOCK_METHOD(void, SetIncrementalData, (const BIncrementalData &)); MOCK_METHOD(int32_t, GetIncrementalManifestFd, (const std::string &)); MOCK_METHOD(int64_t, GetLastIncrementalTime, (const std::string &)); + MOCK_METHOD(bool, CleanAndCheckIfNeedWait, (ErrCode &, std::vector &)); + MOCK_METHOD(void, SetPublishFlag, (const std::string &)); }; } // namespace OHOS::FileManagement::Backup diff --git a/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h b/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h index 7484d1b8c64bf208e376adaf37dc8998a8fc84fc..b5070b41f53fc228b3471e56955304860c2de76a 100644 --- a/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h +++ b/tests/unittests/backup_api/backup_impl/include/ext_extension_mock.h @@ -79,7 +79,7 @@ public: return BError(BError::Codes::OK); }; - ErrCode HandleBackup() override + ErrCode HandleBackup(bool isClearData) override { GTEST_LOG_(INFO) << "HandleBackup"; if (nHandleBackupNum_ == 1) { @@ -99,7 +99,7 @@ public: return BError(BError::Codes::OK); }; - ErrCode HandleRestore() override + ErrCode HandleRestore(bool isClearData) override { return BError(BError::Codes::OK); }; @@ -119,7 +119,7 @@ public: return BError(BError::Codes::OK); }; - ErrCode IncrementalOnBackup() override + ErrCode IncrementalOnBackup(bool isClearData) override { return BError(BError::Codes::OK); }; @@ -139,6 +139,11 @@ public: return BError(BError::Codes::OK); }; + ErrCode User0OnBackup() override + { + return BError(BError::Codes::OK); + }; + private: int32_t nHandleBackupNum_ = 0; }; diff --git a/tests/unittests/backup_api/backup_impl/include/i_service_mock.h b/tests/unittests/backup_api/backup_impl/include/i_service_mock.h index 0a0ffa7e8217f72fd5116723bb041dc0093140a3..ec2a2867f161d07687a5110db764a1564a6ba81f 100644 --- a/tests/unittests/backup_api/backup_impl/include/i_service_mock.h +++ b/tests/unittests/backup_api/backup_impl/include/i_service_mock.h @@ -138,7 +138,17 @@ public: return BError(BError::Codes::OK); } - ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) override + ErrCode UpdateTimer(BundleName &bundleName, uint32_t timeout, bool &result) override + { + return BError(BError::Codes::OK); + } + + ErrCode StartExtTimer(bool &isExtStart) override + { + return BError(BError::Codes::OK); + } + + ErrCode StartFwkTimer(bool &isFwkStart) override { return BError(BError::Codes::OK); } @@ -203,6 +213,11 @@ public: { return BError(BError::Codes::OK); } + + ErrCode ReportAppProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario) + { + return BError(BError::Codes::OK); + } }; } // namespace OHOS::FileManagement::Backup #endif // MOCK_I_SERVICE_MOCK_H \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h b/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h index 4ea6262fdc045a4bc65ec2d45105c5eef2572145..7b1bf2f9b96749795245ae35d3dbf962146f7f45 100644 --- a/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h +++ b/tests/unittests/backup_api/backup_impl/include/service_reverse_mock.h @@ -41,12 +41,14 @@ public: void BackupOnResultReport(std::string result, std::string bundleName) override {}; void BackupOnBundleFinished(int32_t errCode, std::string bundleName) override {} void BackupOnAllBundlesFinished(int32_t errCode) override {} + void BackupOnProcessInfo(std::string bundleName, std::string processInfo) override {} void RestoreOnBundleStarted(int32_t errCode, std::string bundleName) override {} void RestoreOnBundleFinished(int32_t errCode, std::string bundleName) override {} void RestoreOnAllBundlesFinished(int32_t errCode) override {} void RestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int32_t errCode) override {} void RestoreOnResultReport(std::string result, std::string bundleName, ErrCode errCode) override {} + void RestoreOnProcessInfo(std::string bundleName, std::string processInfo) override {} void IncrementalBackupOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd, int32_t errCode) override {} @@ -54,6 +56,7 @@ public: void IncrementalBackupOnResultReport(std::string result, std::string bundleName) override {} void IncrementalBackupOnBundleFinished(int32_t errCode, std::string bundleName) override {} void IncrementalBackupOnAllBundlesFinished(int32_t errCode) override {} + void IncrementalBackupOnProcessInfo(std::string bundleName, std::string processInfo) override {} void IncrementalRestoreOnBundleStarted(int32_t errCode, std::string bundleName) override {} void IncrementalRestoreOnBundleFinished(int32_t errCode, std::string bundleName) override {} @@ -61,6 +64,7 @@ public: void IncrementalRestoreOnFileReady(std::string bundleName, std::string fileName, int fd, int manifestFd, int32_t errCode) override {} void IncrementalRestoreOnResultReport(std::string result, std::string bundleName, ErrCode errCode) override {}; + void IncrementalRestoreOnProcessInfo(std::string bundleName, std::string processInfo) override {} }; } // namespace OHOS::FileManagement::Backup #endif // MOCK_SERVICE_REVERSE_MOCK_H \ No newline at end of file diff --git a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp index f95584e61d204e60609cb74b85bad115a9010f73..17f01f4f5d4d5f4c70d2ea72f2720fb5991d4bc7 100644 --- a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp +++ b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp @@ -896,8 +896,8 @@ HWTEST_F(ServiceProxyTest, SUB_Service_proxy_UpdateTimer_0100, testing::ext::Tes .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)); bool result; std::string bundleName = "com.example.app2backup"; - uint32_t timeOut = 30000; - int32_t ret = proxy_->UpdateTimer(bundleName, timeOut, result); + uint32_t timeout = 30000; + int32_t ret = proxy_->UpdateTimer(bundleName, timeout, result); EXPECT_EQ(ret, BError(BError::Codes::OK)); GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_UpdateTimer_0100"; } diff --git a/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp b/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp index b69f91d463fcc9657d6242d96f30b46e1a373b7c..d5c75557cd2fa4b3e2140081a7e65b87be28b14b 100644 --- a/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp +++ b/tests/unittests/backup_api/backup_impl/service_reverse_stub_test.cpp @@ -45,23 +45,27 @@ public: MOCK_METHOD2(BackupOnResultReport, void(string result, std::string bundleName)); MOCK_METHOD2(BackupOnBundleFinished, void(int32_t errCode, string bundleName)); MOCK_METHOD1(BackupOnAllBundlesFinished, void(int32_t errCode)); + MOCK_METHOD2(BackupOnProcessInfo, void(std::string bundleName, std::string processInfo)); MOCK_METHOD2(RestoreOnBundleStarted, void(int32_t errCode, std::string bundleName)); MOCK_METHOD2(RestoreOnBundleFinished, void(int32_t errCode, string bundleName)); MOCK_METHOD1(RestoreOnAllBundlesFinished, void(int32_t errCode)); MOCK_METHOD4(RestoreOnFileReady, void(string bundleName, string fileName, int fd, int32_t errCode)); MOCK_METHOD3(RestoreOnResultReport, void(string result, string bundleName, ErrCode errCode)); + MOCK_METHOD2(RestoreOnProcessInfo, void(std::string bundleName, std::string processInfo)); MOCK_METHOD5(IncrementalBackupOnFileReady, void(string bundleName, string fileName, int fd, int manifestFd, int32_t errCode)); MOCK_METHOD2(IncrementalBackupOnBundleStarted, void(int32_t errCode, string bundleName)); MOCK_METHOD2(IncrementalBackupOnResultReport, void(string result, std::string bundleName)); MOCK_METHOD2(IncrementalBackupOnBundleFinished, void(int32_t errCode, string bundleName)); MOCK_METHOD1(IncrementalBackupOnAllBundlesFinished, void(int32_t errCode)); + MOCK_METHOD2(IncrementalBackupOnProcessInfo, void(std::string bundleName, std::string processInfo)); MOCK_METHOD2(IncrementalRestoreOnBundleStarted, void(int32_t errCode, std::string bundleName)); MOCK_METHOD2(IncrementalRestoreOnBundleFinished, void(int32_t errCode, string bundleName)); MOCK_METHOD1(IncrementalRestoreOnAllBundlesFinished, void(int32_t errCode)); MOCK_METHOD5(IncrementalRestoreOnFileReady, void(string bundleName, string fileName, int fd, int manifestFd, int32_t errCode)); MOCK_METHOD3(IncrementalRestoreOnResultReport, void(string result, string bundleName, ErrCode errCode)); + MOCK_METHOD2(IncrementalRestoreOnProcessInfo, void(std::string bundleName, std::string processInfo)); }; class ServiceReverseStubTest : public testing::Test { diff --git a/tests/unittests/backup_ext/BUILD.gn b/tests/unittests/backup_ext/BUILD.gn index 7ab377141aaaf2f03300b45dd6d8184fb8552e5b..a565d18ca69ef37dc00e652e4096068dd597c0b2 100644 --- a/tests/unittests/backup_ext/BUILD.gn +++ b/tests/unittests/backup_ext/BUILD.gn @@ -139,6 +139,7 @@ ohos_unittest("tar_file_test") { "${path_backup}/frameworks/native/backup_ext/src/ext_backup_loader.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_extension.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_extension_stub.cpp", + "${path_backup}/frameworks/native/backup_ext/src/sub_ext_extension.cpp", "${path_backup}/frameworks/native/backup_ext/src/tar_file.cpp", "${path_backup}/frameworks/native/backup_ext/src/untar_file.cpp", "tar_file_test.cpp", @@ -211,6 +212,7 @@ ohos_unittest("untar_file_test") { "${path_backup}/frameworks/native/backup_ext/src/ext_backup_loader.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_extension.cpp", "${path_backup}/frameworks/native/backup_ext/src/ext_extension_stub.cpp", + "${path_backup}/frameworks/native/backup_ext/src/sub_ext_extension.cpp", "${path_backup}/frameworks/native/backup_ext/src/tar_file.cpp", "${path_backup}/frameworks/native/backup_ext/src/untar_file.cpp", "untar_file_test.cpp", diff --git a/tests/unittests/backup_ext/ext_backup_js_test.cpp b/tests/unittests/backup_ext/ext_backup_js_test.cpp index 4e23ad233323ae150ed7387390ff2538d3fb61ef..80a9aee6e1b2c2a8259843f3b03a9815ca7085ef 100644 --- a/tests/unittests/backup_ext/ext_backup_js_test.cpp +++ b/tests/unittests/backup_ext/ext_backup_js_test.cpp @@ -194,18 +194,19 @@ HWTEST_F(ExtBackupJsTest, SUB_backup_ext_js_DealNapiException_0100, testing::ext try { napi_env env = nullptr; string exceptionInfo = ""; + napi_value exception; EXPECT_CALL(*napiMock, napi_get_and_clear_last_exception(_, _)).WillOnce(Return(napi_invalid_arg)); - auto ret = DealNapiException(env, exceptionInfo); + auto ret = DealNapiException(env, exception, exceptionInfo); EXPECT_EQ(ret, napi_invalid_arg); EXPECT_CALL(*napiMock, napi_get_and_clear_last_exception(_, _)).WillOnce(Return(napi_ok)); EXPECT_CALL(*napiMock, napi_get_value_string_utf8(_, _, _, _, _)).WillOnce(Return(napi_invalid_arg)); - ret = DealNapiException(env, exceptionInfo); + ret = DealNapiException(env, exception, exceptionInfo); EXPECT_EQ(ret, napi_invalid_arg); EXPECT_CALL(*napiMock, napi_get_and_clear_last_exception(_, _)).WillOnce(Return(napi_ok)); EXPECT_CALL(*napiMock, napi_get_value_string_utf8(_, _, _, _, _)).WillOnce(Return(napi_ok)); - ret = DealNapiException(env, exceptionInfo); + ret = DealNapiException(env, exception, exceptionInfo); EXPECT_EQ(ret, napi_ok); } catch (...) { EXPECT_TRUE(false); diff --git a/tests/unittests/backup_ext/ext_extension_stub_test.cpp b/tests/unittests/backup_ext/ext_extension_stub_test.cpp index 413212265d6d6ff246ebc15e8eb3b9e4c1ee673a..8755506fc2e192586689373755a52d2f0f756586 100644 --- a/tests/unittests/backup_ext/ext_extension_stub_test.cpp +++ b/tests/unittests/backup_ext/ext_extension_stub_test.cpp @@ -28,16 +28,17 @@ class ExtExtensionStubMock : public ExtExtensionStub { public: MOCK_METHOD(UniqueFd, GetFileHandle, (const std::string &fileName, int32_t &errCode)); MOCK_METHOD(ErrCode, HandleClear, ()); - MOCK_METHOD(ErrCode, HandleBackup, ()); + MOCK_METHOD(ErrCode, HandleBackup, (bool isClearData)); MOCK_METHOD(ErrCode, PublishFile, (const std::string &fileName)); - MOCK_METHOD(ErrCode, HandleRestore, ()); + MOCK_METHOD(ErrCode, HandleRestore, (bool isClearData)); MOCK_METHOD(ErrCode, GetIncrementalFileHandle, (const std::string &fileName)); MOCK_METHOD(ErrCode, PublishIncrementalFile, (const std::string &fileName)); MOCK_METHOD(ErrCode, HandleIncrementalBackup, (UniqueFd incrementalFd, UniqueFd manifestFd)); - MOCK_METHOD(ErrCode, IncrementalOnBackup, ()); + MOCK_METHOD(ErrCode, IncrementalOnBackup, (bool isClearData)); MOCK_METHOD((std::tuple), GetIncrementalBackupFileHandle, ()); MOCK_METHOD(ErrCode, GetBackupInfo, (std::string &result)); MOCK_METHOD(ErrCode, UpdateFdSendRate, (std::string &bundleName, int32_t sendRate)); + MOCK_METHOD(ErrCode, User0OnBackup, ()); }; class ExtExtensionStubTest : public testing::Test { @@ -201,13 +202,13 @@ HWTEST_F(ExtExtensionStubTest, SUB_backup_ext_ExtExtensionStub_CmdHandleBackup_0 try { MessageParcel data; MessageParcel reply; - EXPECT_CALL(*stub, HandleBackup()).WillOnce(Return(0)); + EXPECT_CALL(*stub, HandleBackup(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(false)); EXPECT_TRUE(stub != nullptr); auto err = stub->CmdHandleBackup(data, reply); EXPECT_EQ(err, BError(BError::Codes::EXT_BROKEN_IPC)); - EXPECT_CALL(*stub, HandleBackup()).WillOnce(Return(0)); + EXPECT_CALL(*stub, HandleBackup(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(true)); err = stub->CmdHandleBackup(data, reply); EXPECT_EQ(err, BError(BError::Codes::OK)); @@ -271,13 +272,13 @@ HWTEST_F(ExtExtensionStubTest, SUB_backup_ext_ExtExtensionStub_CmdHandleRestore_ try { MessageParcel data; MessageParcel reply; - EXPECT_CALL(*stub, HandleRestore()).WillOnce(Return(0)); + EXPECT_CALL(*stub, HandleRestore(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(false)); EXPECT_TRUE(stub != nullptr); auto err = stub->CmdHandleRestore(data, reply); EXPECT_EQ(err, BError(BError::Codes::EXT_BROKEN_IPC)); - EXPECT_CALL(*stub, HandleRestore()).WillOnce(Return(0)); + EXPECT_CALL(*stub, HandleRestore(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(true)); err = stub->CmdHandleRestore(data, reply); EXPECT_EQ(err, BError(BError::Codes::OK)); @@ -417,13 +418,13 @@ HWTEST_F(ExtExtensionStubTest, SUB_backup_ext_ExtExtensionStub_CmdIncrementalOnB try { MessageParcel data; MessageParcel reply; - EXPECT_CALL(*stub, IncrementalOnBackup()).WillOnce(Return(0)); + EXPECT_CALL(*stub, IncrementalOnBackup(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(false)); EXPECT_TRUE(stub != nullptr); auto err = stub->CmdIncrementalOnBackup(data, reply); EXPECT_EQ(err, BError(BError::Codes::EXT_BROKEN_IPC)); - EXPECT_CALL(*stub, IncrementalOnBackup()).WillOnce(Return(0)); + EXPECT_CALL(*stub, IncrementalOnBackup(_)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(true)); err = stub->CmdIncrementalOnBackup(data, reply); EXPECT_EQ(err, BError(BError::Codes::OK)); @@ -560,4 +561,36 @@ HWTEST_F(ExtExtensionStubTest, SUB_backup_ext_ExtExtensionStub_CmdUpdateSendRate } GTEST_LOG_(INFO) << "ExtExtensionStubTest-end SUB_backup_ext_ExtExtensionStub_CmdUpdateSendRate_0100"; } + +/** + * @tc.number: SUB_backup_ext_ExtExtensionStub_CmdUser0_0100 + * @tc.name: SUB_backup_ext_ExtExtensionStub_CmdUser0_0100 + * @tc.desc: 测试 CmdHandleUser0Backup 各个分支成功与失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: issues + */ +HWTEST_F(ExtExtensionStubTest, SUB_backup_ext_ExtExtensionStub_CmdUser0_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ExtExtensionStubTest-begin SUB_backup_ext_ExtExtensionStub_CmdUser0_0100"; + try { + MessageParcel data; + MessageParcel reply; + EXPECT_CALL(*stub, User0OnBackup()).WillOnce(Return(0)); + EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(false)); + EXPECT_TRUE(stub != nullptr); + auto err = stub->CmdHandleUser0Backup(data, reply); + EXPECT_EQ(err, BError(BError::Codes::EXT_BROKEN_IPC)); + + EXPECT_CALL(*stub, User0OnBackup()).WillOnce(Return(0)); + EXPECT_CALL(*messageParcelMock, WriteInt32(_)).WillOnce(Return(true)); + err = stub->CmdHandleUser0Backup(data, reply); + EXPECT_EQ(err, BError(BError::Codes::OK)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ExtExtensionStubTest-an exception occurred by CmdHandleClear."; + } + GTEST_LOG_(INFO) << "ExtExtensionStubTest-end SUB_backup_ext_ExtExtensionStub_CmdUser0_0100"; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp index 9b9947fcbdd92014cd1c73cc32bd0e429cd56b8b..7fb8b7e48ad38dbcf45a2e9070cc1df7d2087d96 100644 --- a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp @@ -79,8 +79,11 @@ public: MOCK_METHOD1(AppIncrementalDone, ErrCode(ErrCode errCode)); MOCK_METHOD2(GetIncrementalFileHandle, ErrCode(const std::string &bundleName, const std::string &fileName)); MOCK_METHOD2(GetBackupInfo, ErrCode(string &bundleName, string &result)); - MOCK_METHOD3(UpdateTimer, ErrCode(BundleName &bundleName, uint32_t timeOut, bool &result)); + MOCK_METHOD3(UpdateTimer, ErrCode(BundleName &bundleName, uint32_t timeout, bool &result)); + MOCK_METHOD1(StartExtTimer, ErrCode(bool &isExtStart)); + MOCK_METHOD1(StartFwkTimer, ErrCode(bool &isFwkStart)); MOCK_METHOD3(UpdateSendRate, ErrCode(std::string &bundleName, int32_t sendRate, bool &result)); + MOCK_METHOD2(ReportAppProcessInfo, ErrCode(const std::string processInfo, BackupRestoreScenario sennario)); }; class ServiceStubTest : public testing::Test { diff --git a/tests/unittests/backup_sa/module_ipc/service_test.cpp b/tests/unittests/backup_sa/module_ipc/service_test.cpp index f2e6511c836431e60978f9761538af5bdf55046a..32c8d0fd17133ec931fcc99071206d7e6bd575f4 100644 --- a/tests/unittests/backup_sa/module_ipc/service_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_test.cpp @@ -936,9 +936,9 @@ HWTEST_F(ServiceTest, SUB_Service_UpdateTimer_0100, testing::ext::TestSize.Level try { std::string bundleName = "com.example.app2backup"; bool result = true; - uint32_t timeOut = 30000; + uint32_t timeout = 30000; EXPECT_TRUE(servicePtr_ != nullptr); - servicePtr_->UpdateTimer(bundleName, timeOut, result); + servicePtr_->UpdateTimer(bundleName, timeout, result); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by UpdateTimer."; diff --git a/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp b/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp index 06dc18af33722d59bdebe3c3a1c0a98a8bd7613b..3ae9f67116196e9e7ab710b8b1c0dbf439be02a1 100644 --- a/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_throw_test.cpp @@ -67,24 +67,24 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_GetLocalCapabilities_0100, testing: GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_GetLocalCapabilities_0100"; try { EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->GetLocalCapabilities(); EXPECT_EQ(-ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw runtime_error("运行时错误"); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->GetLocalCapabilities(); EXPECT_EQ(-ret, EPERM); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->GetLocalCapabilities(); EXPECT_EQ(-ret, EPERM); } catch (...) { @@ -177,17 +177,17 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppendBundlesRestoreSession_0100, t GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_AppendBundlesRestoreSession_0100"; try { EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->AppendBundlesRestoreSession(UniqueFd(-1), {}, {}, RESTORE_DATA_WAIT_SEND, 0); EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesRestoreSession(UniqueFd(-1), {}, {}, RESTORE_DATA_WAIT_SEND, 0); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -211,17 +211,17 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppendBundlesRestoreSession_0200, t GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_AppendBundlesRestoreSession_0200"; try { EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->AppendBundlesRestoreSession(UniqueFd(-1), {}, RESTORE_DATA_WAIT_SEND, 0); EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesRestoreSession(UniqueFd(-1), {}, RESTORE_DATA_WAIT_SEND, 0); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -245,24 +245,24 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppendBundlesBackupSession_0100, te GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_AppendBundlesBackupSession_0100"; try { EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->AppendBundlesBackupSession({}); EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw runtime_error("运行时错误"); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesBackupSession({}); EXPECT_EQ(ret, EPERM); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesBackupSession({}); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -286,24 +286,24 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppendBundlesDetailsBackupSession_0 GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_AppendBundlesDetailsBackupSession_0100"; try { EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->AppendBundlesDetailsBackupSession({}, {}); EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw runtime_error("运行时错误"); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesDetailsBackupSession({}, {}); EXPECT_EQ(ret, EPERM); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesDetailsBackupSession({}, {}); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -526,19 +526,22 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_OnBackupExtensionDied_0100, testing try { EXPECT_NE(service, nullptr); string bundleName; + EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Return(IServiceReverse::Scenario::UNDEFINED)) + .WillOnce(Return(IServiceReverse::Scenario::UNDEFINED)) + .WillOnce(Invoke([]() { + throw "未知错误"; + return IServiceReverse::Scenario::UNDEFINED; + })); EXPECT_CALL(*sessionMock, VerifyBundleName(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, BundleExtTimerStop(_)).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, StopFwkTimer(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); + return true; })); EXPECT_CALL(*sessionMock, RemoveExtInfo(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - return IServiceReverse::Scenario::UNDEFINED; - })); service->OnBackupExtensionDied("bundleName"); EXPECT_TRUE(true); } catch (...) { @@ -548,40 +551,6 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_OnBackupExtensionDied_0100, testing GTEST_LOG_(INFO) << "ServiceThrowTest-end SUB_Service_throw_OnBackupExtensionDied_0100"; } -/** - * @tc.number: SUB_Service_throw_ExtConnectDied_0100 - * @tc.name: SUB_Service_throw_ExtConnectDied_0100 - * @tc.desc: 测试 ExtConnectDied 接口的 catch 分支 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: issuesIAC04T - */ -HWTEST_F(ServiceThrowTest, SUB_Service_throw_ExtConnectDied_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_ExtConnectDied_0100"; - try { - EXPECT_NE(service, nullptr); - string callName; - EXPECT_CALL(*sessionMock, BundleExtTimerStop(_)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); - EXPECT_CALL(*sessionMock, RemoveExtInfo(_)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); - EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - return IServiceReverse::Scenario::UNDEFINED; - })); - service->ExtConnectDied(callName); - EXPECT_TRUE(true); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by ExtConnectDied."; - } - GTEST_LOG_(INFO) << "ServiceThrowTest-end SUB_Service_throw_ExtConnectDied_0100"; -} - /** * @tc.number: SUB_Service_throw_ExtStart_0100 * @tc.name: SUB_Service_throw_ExtStart_0100 @@ -606,6 +575,10 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_ExtStart_0100, testing::ext::TestSi })); EXPECT_CALL(*sessionMock, RemoveExtInfo(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); + })).WillOnce(Invoke([]() { + throw BError(BError::Codes::EXT_THROW_EXCEPTION); + })).WillOnce(Invoke([]() { + throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); service->ExtStart(bundleName); EXPECT_TRUE(true); @@ -634,6 +607,9 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_ExtConnectFailed_0100, testing::ext EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); return IServiceReverse::Scenario::UNDEFINED; + })).WillOnce(Invoke([]() { + throw BError(BError::Codes::EXT_THROW_EXCEPTION); + return IServiceReverse::Scenario::UNDEFINED; })); service->ExtConnectFailed(bundleName, 0); EXPECT_TRUE(true); @@ -641,6 +617,9 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_ExtConnectFailed_0100, testing::ext EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Invoke([]() { throw runtime_error("运行时错误"); return IServiceReverse::Scenario::UNDEFINED; + })).WillOnce(Invoke([]() { + throw runtime_error("运行时错误"); + return IServiceReverse::Scenario::UNDEFINED; })); service->ExtConnectFailed(bundleName, 0); EXPECT_TRUE(true); @@ -648,6 +627,9 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_ExtConnectFailed_0100, testing::ext EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Invoke([]() { throw "未知错误"; return IServiceReverse::Scenario::UNDEFINED; + })).WillOnce(Invoke([]() { + throw "未知错误"; + return IServiceReverse::Scenario::UNDEFINED; })); service->ExtConnectFailed(bundleName, 0); EXPECT_TRUE(true); @@ -687,40 +669,6 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_NoticeClientFinish_0100, testing::e GTEST_LOG_(INFO) << "ServiceThrowTest-end SUB_Service_throw_NoticeClientFinish_0100"; } -/** - * @tc.number: SUB_Service_throw_ExtConnectDone_0100 - * @tc.name: SUB_Service_throw_ExtConnectDone_0100 - * @tc.desc: 测试 ExtConnectDone 接口的 catch 分支 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: issuesIAC04T - */ -HWTEST_F(ServiceThrowTest, SUB_Service_throw_ExtConnectDone_0100, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_ExtConnectDone_0100"; - try { - EXPECT_NE(service, nullptr); - string bundleName; - EXPECT_CALL(*sessionMock, BundleExtTimerStart(_, _)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); - EXPECT_CALL(*sessionMock, RemoveExtInfo(_)).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - })); - EXPECT_CALL(*sessionMock, GetScenario()).WillOnce(Invoke([]() { - throw BError(BError::Codes::EXT_THROW_EXCEPTION); - return IServiceReverse::Scenario::UNDEFINED; - })); - service->ExtConnectDone(bundleName); - EXPECT_TRUE(true); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceThrowTest-an exception occurred by ExtConnectDone."; - } - GTEST_LOG_(INFO) << "ServiceThrowTest-end SUB_Service_throw_ExtConnectDone_0100"; -} - /** * @tc.number: SUB_Service_throw_ClearSessionAndSchedInfo_0100 * @tc.name: SUB_Service_throw_ClearSessionAndSchedInfo_0100 @@ -776,10 +724,11 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_GetBackupInfo_0100, testing::ext::T EXPECT_NE(service, nullptr); BundleName bundleName; string result; - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, GetImpl()).WillOnce(Invoke([]() { throw "未知错误"; + return SvcSessionManager::Impl(); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->GetBackupInfo(bundleName, result); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -805,10 +754,10 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_UpdateTimer_0100, testing::ext::Tes EXPECT_NE(service, nullptr); BundleName bundleName; bool result = false; - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->UpdateTimer(bundleName, 0, result); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -876,24 +825,24 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_GetLocalCapabilitiesIncremental_010 try { EXPECT_NE(service, nullptr); vector bundleNames; - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->GetLocalCapabilitiesIncremental(bundleNames); EXPECT_EQ(-ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw runtime_error("运行时错误"); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->GetLocalCapabilitiesIncremental(bundleNames); EXPECT_EQ(-ret, EPERM); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->GetLocalCapabilitiesIncremental(bundleNames); EXPECT_EQ(-ret, EPERM); } catch (...) { @@ -917,24 +866,24 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_GetAppLocalListAndDoIncrementalBack GTEST_LOG_(INFO) << "ServiceThrowTest-begin SUB_Service_throw_GetAppLocalListAndDoIncrementalBackup_0100"; try { EXPECT_NE(service, nullptr); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->GetAppLocalListAndDoIncrementalBackup(); EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw runtime_error("运行时错误"); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->GetAppLocalListAndDoIncrementalBackup(); EXPECT_EQ(ret, EPERM); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->GetAppLocalListAndDoIncrementalBackup(); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -987,17 +936,17 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppendBundlesIncrementalBackupSessi try { EXPECT_NE(service, nullptr); vector bundlesToBackup; - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->AppendBundlesIncrementalBackupSession(bundlesToBackup); EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesIncrementalBackupSession(bundlesToBackup); EXPECT_EQ(ret, EPERM); } catch (...) { @@ -1023,17 +972,17 @@ HWTEST_F(ServiceThrowTest, SUB_Service_throw_AppendBundlesIncrementalBackupSessi EXPECT_NE(service, nullptr); vector bundlesToBackup; vector infos; - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw BError(BError::Codes::EXT_THROW_EXCEPTION); })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); auto ret = service->AppendBundlesIncrementalBackupSession(bundlesToBackup, infos); EXPECT_EQ(ret, BError(BError::Codes::EXT_THROW_EXCEPTION).GetCode()); - EXPECT_CALL(*sessionMock, IncreaseSessionCnt()).WillOnce(Invoke([]() { + EXPECT_CALL(*sessionMock, IncreaseSessionCnt(_)).WillOnce(Invoke([]() { throw "未知错误"; })); - EXPECT_CALL(*sessionMock, DecreaseSessionCnt()).WillOnce(Return()); + EXPECT_CALL(*sessionMock, DecreaseSessionCnt(_)).WillOnce(Return()); ret = service->AppendBundlesIncrementalBackupSession(bundlesToBackup, infos); EXPECT_EQ(ret, EPERM); } catch (...) { diff --git a/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp index cfdfacc4c82a08e4edf864075401808661d4821b..772053763ae73bf6abd5b0d62bbe84ef64cf706d 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_backup_connection_test.cpp @@ -53,7 +53,7 @@ static void CallDone(const std::string &&name) void SvcBackupConnectionTest::SetUpTestCase() { - backupCon_ = sptr(new SvcBackupConnection(CallDied, CallDone)); + backupCon_ = sptr(new SvcBackupConnection(CallDied, CallDone, "com.example.app")); castMock = std::make_shared(); IfaceCastMock::cast = castMock; } diff --git a/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp index 0e54994bfe2084ae4db8eb254a31798a8b67ac9f..23df5b143aac2a4cef44e8847952eb5008af2c32 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_extension_proxy_test.cpp @@ -148,15 +148,17 @@ HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_HandleBackup_0100, testi GTEST_LOG_(INFO) << "SvcExtensionProxyTest-begin SUB_Ext_Extension_proxy_HandleBackup_0100"; try { EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(EPERM)); EXPECT_TRUE(proxy_ != nullptr); - ErrCode ret = proxy_->HandleBackup(); + ErrCode ret = proxy_->HandleBackup(true); EXPECT_EQ(EPERM, ret); EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock_, ReadInt32()).WillOnce(Return(0)); - ret = proxy_->HandleBackup(); + ret = proxy_->HandleBackup(true); EXPECT_EQ(BError(BError::Codes::OK), ret); } catch (...) { EXPECT_TRUE(false); @@ -218,15 +220,17 @@ HWTEST_F(SvcExtensionProxyTest, SUB_Ext_Extension_proxy_HandleRestore_0100, test GTEST_LOG_(INFO) << "SvcExtensionProxyTest-begin SUB_Ext_Extension_proxy_HandleRestore_0100"; try { EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(EPERM)); EXPECT_TRUE(proxy_ != nullptr); - ErrCode ret = proxy_->HandleRestore(); + ErrCode ret = proxy_->HandleRestore(true); EXPECT_EQ(EPERM, ret); EXPECT_CALL(*messageParcelMock_, WriteInterfaceToken(_)).WillOnce(Return(true)); + EXPECT_CALL(*messageParcelMock_, WriteBool(_)).WillOnce(Return(true)); EXPECT_CALL(*mock_, SendRequest(_, _, _, _)).WillOnce(Return(0)); EXPECT_CALL(*messageParcelMock_, ReadInt32()).WillOnce(Return(0)); - ret = proxy_->HandleRestore(); + ret = proxy_->HandleRestore(true); EXPECT_EQ(BError(BError::Codes::OK), ret); } catch (...) { EXPECT_TRUE(false); diff --git a/tests/unittests/backup_sa/module_ipc/svc_restore_deps_manager_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_restore_deps_manager_test.cpp index 6668c0246e9ec39a457cfdc117a7b0f74d440bf8..3cb2a0082767bfbc57f06253ecaec7921afef187 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_restore_deps_manager_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_restore_deps_manager_test.cpp @@ -107,8 +107,8 @@ HWTEST_F(SvcRestoreDepsManagerTest, SUB_SvcRestoreDepsManager_GetRestoreBundleNa vector bundleInfos {info1, info2}; RestoreTypeEnum restoreType = RESTORE_DATA_WAIT_SEND; auto bundleNames = SvcRestoreDepsManager::GetInstance().GetRestoreBundleNames(bundleInfos, restoreType); - EXPECT_EQ(bundleNames.size(), 1); - EXPECT_FALSE(SvcRestoreDepsManager::GetInstance().IsAllBundlesRestored()); + EXPECT_EQ(bundleNames.size(), 2); + EXPECT_TRUE(SvcRestoreDepsManager::GetInstance().IsAllBundlesRestored()); ClearCache(); GTEST_LOG_(INFO) << "SvcRestoreDepsManagerTest-end SUB_SvcRestoreDepsManager_GetRestoreBundleNames_0200"; } diff --git a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp index a60ac156d26b7ba0f3b9153cb248b7d331808718..6f0703be3ee39a9b0fe69243e87222b73e2e1c89 100644 --- a/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/svc_session_manager_test.cpp @@ -668,7 +668,7 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_GetExtConnection_0100, tes } BackupExtInfo info; - info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr)); + info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr, BUNDLE_NAME)); sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; auto ret = sessionManagerPtr_->GetExtConnection(BUNDLE_NAME); @@ -1618,47 +1618,47 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_SetBundleDataSize_0100, te } /** - * @tc.number: SUB_backup_sa_session_BundleExtTimerStart_0100 - * @tc.name: SUB_backup_sa_session_BundleExtTimerStart_0100 - * @tc.desc: 测试 BundleExtTimerStart + * @tc.number: SUB_backup_sa_session_StartFwkTimer_0100 + * @tc.name: SUB_backup_sa_session_StartFwkTimer_0100 + * @tc.desc: 测试 StartFwkTimer * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 * @tc.require: I6F3GV */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_BundleExtTimerStart_0100, testing::ext::TestSize.Level1) +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_StartFwkTimer_0100, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_BundleExtTimerStart_0100"; + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_StartFwkTimer_0100"; try { auto callback = []() -> void {}; - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->BundleExtTimerStart(BUNDLE_NAME, callback); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + auto ret = sessionManagerPtr_->StartFwkTimer(BUNDLE_NAME, callback); + EXPECT_FALSE(ret); BackupExtInfo info; - info.timerStatus = false; + info.fwkTimerStatus = false; sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; - sessionManagerPtr_->BundleExtTimerStart(BUNDLE_NAME, callback); - EXPECT_TRUE(true); + ret = sessionManagerPtr_->StartFwkTimer(BUNDLE_NAME, callback); + EXPECT_TRUE(ret); + ret = sessionManagerPtr_->StopFwkTimer(BUNDLE_NAME); + EXPECT_TRUE(ret); - info.timerStatus = true; + info.fwkTimerStatus = true; sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; - sessionManagerPtr_->BundleExtTimerStart(BUNDLE_NAME, callback); - EXPECT_TRUE(true); + ret = sessionManagerPtr_->StartFwkTimer(BUNDLE_NAME, callback); + EXPECT_FALSE(ret); + ret = sessionManagerPtr_->StopFwkTimer(BUNDLE_NAME); + EXPECT_TRUE(ret); } catch (...) { EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by BundleExtTimerStart."; + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by StartFwkTimer."; } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_BundleExtTimerStart_0100"; + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_StartFwkTimer_0100"; } /** @@ -1675,29 +1675,35 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_UpdateTimer_0100, testing: GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_UpdateTimer_0100"; try { auto callback = []() -> void {}; - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->UpdateTimer(BUNDLE_NAME, 30, callback); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + auto ret = sessionManagerPtr_->UpdateTimer(BUNDLE_NAME, 30, callback); + EXPECT_FALSE(ret); BackupExtInfo info; - info.timerStatus = false; + info.extTimerStatus = false; sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; - auto ret = sessionManagerPtr_->UpdateTimer(BUNDLE_NAME, 30, callback); - EXPECT_FALSE(ret); + ret = sessionManagerPtr_->UpdateTimer(BUNDLE_NAME, 30, callback); + EXPECT_TRUE(ret); - info.timerStatus = true; sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; + ret = sessionManagerPtr_->StartExtTimer(BUNDLE_NAME, callback); + EXPECT_TRUE(ret); ret = sessionManagerPtr_->UpdateTimer(BUNDLE_NAME, 30, callback); EXPECT_TRUE(ret); + ret = sessionManagerPtr_->StopExtTimer(BUNDLE_NAME); + EXPECT_TRUE(ret); + + info.extTimerStatus = true; + sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; + sessionManagerPtr_->impl_.backupExtNameMap.clear(); + sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; + ret = sessionManagerPtr_->UpdateTimer(BUNDLE_NAME, 30, callback); + EXPECT_FALSE(ret); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by UpdateTimer."; @@ -1706,46 +1712,42 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_UpdateTimer_0100, testing: } /** - * @tc.number: SUB_backup_sa_session_BundleExtTimerStop_0100 - * @tc.name: SUB_backup_sa_session_BundleExtTimerStop_0100 - * @tc.desc: 测试 BundleExtTimerStop + * @tc.number: SUB_backup_sa_session_StopFwkTimer_0100 + * @tc.name: SUB_backup_sa_session_StopFwkTimer_0100 + * @tc.desc: 测试 StopFwkTimer * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 * @tc.require: I6F3GV */ -HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_BundleExtTimerStop_0100, testing::ext::TestSize.Level1) +HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_StopFwkTimer_0100, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_BundleExtTimerStop_0100"; + GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_StopFwkTimer_0100"; try { - try { - EXPECT_TRUE(sessionManagerPtr_ != nullptr); - sessionManagerPtr_->impl_.clientToken = 0; - sessionManagerPtr_->BundleExtTimerStop(BUNDLE_NAME); - EXPECT_TRUE(false); - } catch (BError &err) { - EXPECT_EQ(err.GetRawCode(), BError::Codes::SA_INVAL_ARG); - } + EXPECT_TRUE(sessionManagerPtr_ != nullptr); + sessionManagerPtr_->impl_.clientToken = 0; + auto ret = sessionManagerPtr_->StopFwkTimer(BUNDLE_NAME); + EXPECT_FALSE(ret); BackupExtInfo info; - info.timerStatus = false; + info.fwkTimerStatus = false; sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; - sessionManagerPtr_->BundleExtTimerStop(BUNDLE_NAME); - EXPECT_TRUE(true); + ret = sessionManagerPtr_->StopFwkTimer(BUNDLE_NAME); + EXPECT_TRUE(ret); - info.timerStatus = true; + info.fwkTimerStatus = true; sessionManagerPtr_->impl_.clientToken = CLIENT_TOKEN_ID; sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; - sessionManagerPtr_->BundleExtTimerStop(BUNDLE_NAME); - EXPECT_TRUE(true); + ret = sessionManagerPtr_->StopFwkTimer(BUNDLE_NAME); + EXPECT_TRUE(ret); } catch (...) { EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by BundleExtTimerStop."; + GTEST_LOG_(INFO) << "SvcSessionManagerTest-an exception occurred by StopFwkTimer."; } - GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_BundleExtTimerStop_0100"; + GTEST_LOG_(INFO) << "SvcSessionManagerTest-end SUB_backup_sa_session_StopFwkTimer_0100"; } /** @@ -1762,16 +1764,16 @@ HWTEST_F(SvcSessionManagerTest, SUB_backup_sa_session_ClearSessionData_0100, tes GTEST_LOG_(INFO) << "SvcSessionManagerTest-begin SUB_backup_sa_session_ClearSessionData_0100"; try { BackupExtInfo info; - info.timerStatus = true; + info.fwkTimerStatus = true; info.schedAction = BConstants::ServiceSchedAction::RUNNING; - info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr)); + info.backUpConnection = sptr(new SvcBackupConnection(nullptr, nullptr, BUNDLE_NAME)); EXPECT_TRUE(sessionManagerPtr_ != nullptr); sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; sessionManagerPtr_->ClearSessionData(); EXPECT_TRUE(true); - info.timerStatus = false; + info.fwkTimerStatus = false; info.schedAction = BConstants::ServiceSchedAction::WAIT; sessionManagerPtr_->impl_.backupExtNameMap.clear(); sessionManagerPtr_->impl_.backupExtNameMap[BUNDLE_NAME] = info; diff --git a/tests/unittests/backup_sa/session/service_proxy_mock.cpp b/tests/unittests/backup_sa/session/service_proxy_mock.cpp index 7220842562c3aafab49350bf5e33da678c37ed05..ebcf680de3908d865e9a8acc87deccb01a729d56 100644 --- a/tests/unittests/backup_sa/session/service_proxy_mock.cpp +++ b/tests/unittests/backup_sa/session/service_proxy_mock.cpp @@ -157,7 +157,17 @@ ErrCode ServiceProxy::GetBackupInfo(std::string &bundleName, std::string &result return BError(BError::Codes::OK); } -ErrCode ServiceProxy::UpdateTimer(BundleName &bundleName, uint32_t timeOut, bool &result) +ErrCode ServiceProxy::UpdateTimer(BundleName &bundleName, uint32_t timeout, bool &result) +{ + return BError(BError::Codes::OK); +} + +ErrCode ServiceProxy::StartExtTimer(bool &isExtStart) +{ + return BError(BError::Codes::OK); +} + +ErrCode ServiceProxy::StartFwkTimer(bool &isFwkStart) { return BError(BError::Codes::OK); } @@ -167,6 +177,16 @@ ErrCode ServiceProxy::UpdateSendRate(std::string &bundleName, int32_t sendRate, return BError(BError::Codes::OK); } +ErrCode ServiceProxy::ReportAppProcessInfo(const std::string processInfo, const BackupRestoreScenario sennario) +{ + return BError(BError::Codes::OK); +} + +sptr ServiceProxy::GetServiceProxyPointer() +{ + return serviceProxy_; +} + sptr ServiceProxy::GetInstance() { return serviceProxy_; diff --git a/tests/unittests/backup_sa/session/service_proxy_mock.h b/tests/unittests/backup_sa/session/service_proxy_mock.h index 9bbf0ba3c8cea709822c58e8b7f197487fba5bee..946043b332eb1876807cefb6740d47cd8863682b 100644 --- a/tests/unittests/backup_sa/session/service_proxy_mock.h +++ b/tests/unittests/backup_sa/session/service_proxy_mock.h @@ -57,7 +57,7 @@ public: MOCK_METHOD1(AppIncrementalDone, ErrCode(ErrCode errCode)); MOCK_METHOD2(GetIncrementalFileHandle, ErrCode(const std::string &bundleName, const std::string &fileName)); MOCK_METHOD2(GetBackupInfo, ErrCode(BundleName &bundleName, std::string &result)); - MOCK_METHOD3(UpdateTimer, ErrCode(BundleName &bundleName, uint32_t timeOut, bool &result)); + MOCK_METHOD3(UpdateTimer, ErrCode(BundleName &bundleName, uint32_t timeout, bool &result)); MOCK_METHOD0(GetAppLocalListAndDoIncrementalBackup, ErrCode()); }; } // End of namespace OHOS::FileManagement::Backup diff --git a/tests/unittests/backup_utils/BUILD.gn b/tests/unittests/backup_utils/BUILD.gn index 40476eb1bc07c723cb250aff488ce0299725b90a..f2fff48e6d09360d7af063ef012db5879072508e 100644 --- a/tests/unittests/backup_utils/BUILD.gn +++ b/tests/unittests/backup_utils/BUILD.gn @@ -244,54 +244,12 @@ ohos_unittest("b_process_test") { use_exceptions = true } -ohos_unittest("b_json_other_test") { - module_out_path = path_module_out_tests - - sources = [ - "${path_backup}/tests/mock/cJson/src/cJsonMock.cpp", - "${path_backup}/tests/unittests/backup_utils/b_json/b_json_service_disposal_config_other_test.cpp", - "${path_backup}/utils/src/b_json/b_json_service_disposal_config.cpp", - ] - sources += backup_mock_parameter_src - - include_dirs = [ - "${path_backup}/utils", - "${path_base}/include", - "${path_backup}/tests/mock/cJson/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", - "${path_googletest}:gmock_main", - "${path_jsoncpp}:jsoncpp", - ] - - external_deps = [ - "cJSON:cjson", - "c_utils:utils", - "hilog:libhilog", - ] - - defines = [ - "LOG_TAG=\"app_file_service\"", - "LOG_DOMAIN=0xD004303", - "private = public", - "protected = public", - ] - - use_exceptions = true -} - group("backup_test") { testonly = true deps = [ ":b_error_test", ":b_file_test", - ":b_json_other_test", ":b_json_test", ":b_process_test", ":b_tarball_cmdline_test", diff --git a/tests/unittests/backup_utils/b_json/b_json_service_disposal_config_other_test.cpp b/tests/unittests/backup_utils/b_json/b_json_service_disposal_config_other_test.cpp deleted file mode 100644 index 10b967f402bcf627d73d1615ff9d1a1737018769..0000000000000000000000000000000000000000 --- a/tests/unittests/backup_utils/b_json/b_json_service_disposal_config_other_test.cpp +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include -#include -#include -#include - -#include "json/value.h" -#include - -#include "b_error/b_error.h" -#include "b_error/b_excep_utils.h" -#include "b_json/b_json_service_disposal_config.h" -#include "cJsonMock.h" - -namespace OHOS::FileManagement::Backup { -using namespace std; -using namespace testing; - -namespace { -const string PATH = "/data/service/el2/100/backup/"; -const string CONFIG_NAME = "RestoreDisposalConfig.json"; -} // namespace - -class BJsonServiceDisposalConfigTest : public testing::Test { -public: - // 所有测试用例执行之前执行 - static void SetUpTestCase(void); - // 所有测试用例执行之后执行 - static void TearDownTestCase(void); - // 每次测试用例执行之前执行 - void SetUp(); - // 每次测试用例执行之后执行 - void TearDown(); - - static inline shared_ptr cJsonMock = nullptr; -}; - -void BJsonServiceDisposalConfigTest::TearDown() {} - -void BJsonServiceDisposalConfigTest::SetUp() -{ - string filePath = PATH + CONFIG_NAME; - bool result = remove(filePath.c_str()); - if (result) { - GTEST_LOG_(INFO) << "delete file success."; - } else { - GTEST_LOG_(INFO) << "delete file failed."; - } -} - -void BJsonServiceDisposalConfigTest::SetUpTestCase() -{ - cJsonMock = make_shared(); - CJson::cJsonPtr = cJsonMock; -} - -void BJsonServiceDisposalConfigTest::TearDownTestCase() -{ - CJson::cJsonPtr = nullptr; - cJsonMock = nullptr; -} - -/* * - * @tc.number: SUB_Disposal_Config_Test_0102 - * @tc.name: SUB_Disposal_Config_Test_0102 - * @tc.desc: 测试print返回空指针情况 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: IAAMIK - */ -HWTEST_F(BJsonServiceDisposalConfigTest, SUB_Disposal_Config_Test_0102, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-begin SUB_Disposal_Config_Test_0102"; - try { - int cjson = 0; - EXPECT_CALL(*cJsonMock, cJSON_CreateObject()).WillOnce(Return(reinterpret_cast(&cjson))); - EXPECT_CALL(*cJsonMock, cJSON_CreateArray()).WillOnce(Return(reinterpret_cast(&cjson))); - EXPECT_CALL(*cJsonMock, cJSON_AddItemToObject(_, _, _)).WillOnce(Return(true)); - EXPECT_CALL(*cJsonMock, cJSON_Print(_)).WillOnce(Return(nullptr)); - EXPECT_CALL(*cJsonMock, cJSON_Delete(_)).WillOnce(Return()); - BJsonDisposalConfig config; - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-end SUB_Disposal_Config_Test_0102"; -} - -/* * - * @tc.number: SUB_Disposal_Config_Test_0103 - * @tc.name: SUB_Disposal_Config_Test_0103 - * @tc.desc: 测试配置文件存在的情况 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: IAAMIK - */ -HWTEST_F(BJsonServiceDisposalConfigTest, SUB_Disposal_Config_Test_0103, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-begin SUB_Disposal_Config_Test_0103"; - try { - EXPECT_CALL(*cJsonMock, cJSON_CreateObject()).WillOnce(Return(nullptr)); - BJsonDisposalConfig config; - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-end SUB_Disposal_Config_Test_0103"; -} - -/* * - * @tc.number: SUB_Disposal_Config_Test_0104 - * @tc.name: SUB_Disposal_Config_Test_0104 - * @tc.desc: 测试creatArray返回空指针情况 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: IAAMIK - */ -HWTEST_F(BJsonServiceDisposalConfigTest, SUB_Disposal_Config_Test_0104, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-begin SUB_Disposal_Config_Test_0104"; - try { - int cjson = 0; - EXPECT_CALL(*cJsonMock, cJSON_CreateObject()).WillOnce(Return(reinterpret_cast(&cjson))); - EXPECT_CALL(*cJsonMock, cJSON_CreateArray()).WillOnce(Return(nullptr)); - EXPECT_CALL(*cJsonMock, cJSON_Delete(_)).WillOnce(Return()); - BJsonDisposalConfig config; - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-end SUB_Disposal_Config_Test_0104"; -} - -/* * - * @tc.number: SUB_Disposal_Config_Test_0202 - * @tc.name: Disposal_Config_Test_0202 - * @tc.desc: 测试修改config文件时print返回空指针 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: IAAMIK - */ -HWTEST_F(BJsonServiceDisposalConfigTest, Disposal_Config_Test_0202, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-begin Disposal_Config_Test_0202"; - try { - string filePath = PATH + CONFIG_NAME; - int cjson = 0; - string str = "test"; - EXPECT_CALL(*cJsonMock, cJSON_CreateObject()).WillOnce(Return(reinterpret_cast(&cjson))); - EXPECT_CALL(*cJsonMock, cJSON_CreateArray()).WillOnce(Return(reinterpret_cast(&cjson))); - EXPECT_CALL(*cJsonMock, cJSON_AddItemToObject(_, _, _)).WillOnce(Return(true)); - EXPECT_CALL(*cJsonMock, cJSON_Print(_)).WillOnce(Return(nullptr)); - EXPECT_CALL(*cJsonMock, cJSON_Delete(_)).WillOnce(Return()); - BJsonDisposalConfig config; - EXPECT_EQ(access(filePath.c_str(), F_OK), 0); - const string bundleName = "test1"; - EXPECT_CALL(*cJsonMock, cJSON_Parse(_)).WillOnce(Return(reinterpret_cast(&cjson))); - EXPECT_CALL(*cJsonMock, cJSON_GetObjectItem(_, _)).WillOnce(Return(reinterpret_cast(&cjson))); - EXPECT_CALL(*cJsonMock, cJSON_CreateObject()).WillOnce(Return(reinterpret_cast(&cjson))); - EXPECT_CALL(*cJsonMock, cJSON_AddStringToObject(_, _, _)).WillOnce(Return(nullptr)); - EXPECT_CALL(*cJsonMock, cJSON_AddItemToArray(_, _)).WillOnce(Return(true)); - EXPECT_CALL(*cJsonMock, cJSON_Print(_)).WillOnce(Return(nullptr)); - EXPECT_CALL(*cJsonMock, cJSON_Delete(_)).WillOnce(Return()); - bool retAdd = config.AppendIntoDisposalConfigFile(bundleName); - EXPECT_FALSE(retAdd); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-end Disposal_Config_Test_0202"; -} - -/* * - * @tc.number: SUB_Disposal_Config_Test_0203 - * @tc.name: Disposal_Config_Test_0203 - * @tc.desc: 测试修改config文件时parse返回空指针的情况 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: IAAMIK - */ -HWTEST_F(BJsonServiceDisposalConfigTest, Disposal_Config_Test_0203, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-begin Disposal_Config_Test_0203"; - try { - string filePath = PATH + CONFIG_NAME; - int cjson = 0; - string str = "test"; - EXPECT_CALL(*cJsonMock, cJSON_CreateObject()).WillOnce(Return(reinterpret_cast(&cjson))); - EXPECT_CALL(*cJsonMock, cJSON_CreateArray()).WillOnce(Return(reinterpret_cast(&cjson))); - EXPECT_CALL(*cJsonMock, cJSON_AddItemToObject(_, _, _)).WillOnce(Return(true)); - EXPECT_CALL(*cJsonMock, cJSON_Print(_)).WillOnce(Return(nullptr)); - EXPECT_CALL(*cJsonMock, cJSON_Delete(_)).WillOnce(Return()); - BJsonDisposalConfig config; - EXPECT_EQ(access(filePath.c_str(), F_OK), 0); - const string bundleName = "test1"; - EXPECT_CALL(*cJsonMock, cJSON_Parse(_)).WillOnce(Return(nullptr)); - EXPECT_CALL(*cJsonMock, cJSON_Delete(_)).WillOnce(Return()); - bool retAdd = config.AppendIntoDisposalConfigFile(bundleName); - EXPECT_FALSE(retAdd); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-an exception occurred by construction."; - } - GTEST_LOG_(INFO) << "BJsonServiceDisposalConfigTest-end Disposal_Config_Test_0203"; -} -} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp b/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp index e21b944df14a0dca02301b77c6246491a6e061e1..936de04fa7020d4abb6d4d283b19bdf4336d683d 100644 --- a/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp +++ b/tests/unittests/backup_utils/b_jsonutil/b_jsonutil_test.cpp @@ -93,8 +93,10 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0100, testing::ext::TestSize detailInfos.push_back(""); int32_t userId = 100; std::vector realBundleNames; + std::map isClearDataFlags; std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, detailInfos, realBundleNames, userId); + BJsonUtil::BuildBundleInfos(bundleNames, detailInfos, realBundleNames, + userId, isClearDataFlags); std::string key = "com.hos.app01"; EXPECT_EQ("com.hos.app01", bundleNameDetailMap[key].bundleName[0]); } catch (...) { @@ -127,8 +129,10 @@ HWTEST_F(BJsonUtilTest, b_jsonutil_BuildBundleInfos_0101, testing::ext::TestSize detailInfos.push_back(""); int32_t userId = 100; std::vector realBundleNames; + std::map isClearDataFlags; std::map> bundleNameDetailMap = - BJsonUtil::BuildBundleInfos(bundleNames, detailInfos, realBundleNames, userId); + BJsonUtil::BuildBundleInfos(bundleNames, detailInfos, realBundleNames, + userId, isClearDataFlags); EXPECT_EQ(0, bundleNameDetailMap.size()); } catch (...) { EXPECT_TRUE(false); diff --git a/tools/backup_tool/src/tools_op_backup.cpp b/tools/backup_tool/src/tools_op_backup.cpp index fcf892a4b20ff9e9d17e5dbf09020e5ff751ad0b..966827301d66a03fbb68745f6eaad4e02eab9e3a 100644 --- a/tools/backup_tool/src/tools_op_backup.cpp +++ b/tools/backup_tool/src/tools_op_backup.cpp @@ -189,6 +189,11 @@ static void OnBackupServiceDied(shared_ptr ctx) ctx->TryNotify(true); } +static void OnProcess(shared_ptr ctx, const std::string bundleName, const std::string processInfo) +{ + printf("OnProcess bundleName = %s, result = %s\n", bundleName.c_str(), processInfo.c_str()); +} + static void BackupToolDirSoftlinkToBackupDir() { // 判断BConstants::BACKUP_TOOL_LINK_DIR 是否是软链接 @@ -249,7 +254,8 @@ static int32_t InitPathCapFile(const string &pathCapFile, vector bundleN .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), .onResultReport = bind(OnResultReport, ctx, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); + .onBackupServiceDied = bind(OnBackupServiceDied, ctx), + .onProcess = bind(OnProcess, ctx, placeholders::_1, placeholders::_2)}); if (ctx->session_ == nullptr) { printf("Failed to init backup\n"); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); diff --git a/tools/backup_tool/src/tools_op_incremental_backup.cpp b/tools/backup_tool/src/tools_op_incremental_backup.cpp index 2be218c800ada8a4224c0b62cb7dfe62708eb175..32312082d56d756ab334699b9936f45e5d6b0269 100644 --- a/tools/backup_tool/src/tools_op_incremental_backup.cpp +++ b/tools/backup_tool/src/tools_op_incremental_backup.cpp @@ -224,6 +224,11 @@ static void OnBackupServiceDied(shared_ptr ctx) ctx->TryNotify(true); } +static void OnProcess(shared_ptr ctx, const std::string &bundleName, const std::string &processInfo) +{ + printf("OnProcess bundleName = %s, processInfo = %s\n", bundleName.c_str(), processInfo.c_str()); +} + static void BackupToolDirSoftlinkToBackupDir() { // 判断BConstants::BACKUP_TOOL_LINK_DIR 是否是软链接 @@ -308,7 +313,8 @@ static int32_t Init(const string &pathCapFile, const vector& bundleNames .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), .onResultReport = bind(OnResultReport, ctx, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); + .onBackupServiceDied = bind(OnBackupServiceDied, ctx), + .onProcess = bind(OnProcess, ctx, placeholders::_1, placeholders::_2)}); if (ctx->session_ == nullptr) { printf("Failed to init backup\n"); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); diff --git a/tools/backup_tool/src/tools_op_incremental_restore.cpp b/tools/backup_tool/src/tools_op_incremental_restore.cpp index a713c36424df282d5aa18b0fb886f271e0606250..64619efc9d26fd8ffd7e154a0257ec6e916d6a6b 100644 --- a/tools/backup_tool/src/tools_op_incremental_restore.cpp +++ b/tools/backup_tool/src/tools_op_incremental_restore.cpp @@ -219,6 +219,11 @@ static void OnResultReport(shared_ptr ctx, const std::string &bu printf("OnResultReport bundleName = %s, resultInfo = %s\n", bundleName.c_str(), resultInfo.c_str()); } +static void OnProcess(shared_ptr ctx, const std::string bundleName, const std::string processInfo) +{ + printf("OnProcess bundleName = %s, processInfo = %s\n", bundleName.c_str(), processInfo.c_str()); +} + static void RestoreApp(shared_ptr restore) { StartTrace(HITRACE_TAG_FILEMANAGEMENT, "RestoreApp"); @@ -272,7 +277,8 @@ static int32_t InitRestoreSession(shared_ptr ctx, .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), .onResultReport = bind(OnResultReport, ctx, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); + .onBackupServiceDied = bind(OnBackupServiceDied, ctx), + .onProcess = bind(OnProcess, ctx, placeholders::_1, placeholders::_2)}); if (ctx->session_ == nullptr) { printf("Failed to init restore\n"); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); diff --git a/tools/backup_tool/src/tools_op_incremental_restore_async.cpp b/tools/backup_tool/src/tools_op_incremental_restore_async.cpp index a2ff6d7d1b0b1335957a0e0677d0ff4946e83ba6..f39f53196a7688e059dbbf7cb48401246304a2e0 100644 --- a/tools/backup_tool/src/tools_op_incremental_restore_async.cpp +++ b/tools/backup_tool/src/tools_op_incremental_restore_async.cpp @@ -246,6 +246,11 @@ static void OnResultReport(shared_ptr ctx, const std::st printf("OnResultReport bundleName = %s, resultInfo = %s\n", bundleName.c_str(), resultInfo.c_str()); } +static void OnProcess(shared_ptr ctx, const std::string bundleName, const std::string processInfo) +{ + printf("OnProcess bundleName = %s, processInfo = %s\n", bundleName.c_str(), processInfo.c_str()); +} + static void RestoreApp(shared_ptr restore, vector &bundleNames) { StartTrace(HITRACE_TAG_FILEMANAGEMENT, "RestoreApp"); @@ -402,7 +407,8 @@ static int32_t InitArg(const string &pathCapFile, .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), .onResultReport = bind(OnResultReport, ctx, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); + .onBackupServiceDied = bind(OnBackupServiceDied, ctx), + .onProcess = bind(OnProcess, ctx, placeholders::_1, placeholders::_2)}); if (ctx->session_ == nullptr) { printf("Failed to init restore\n"); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); diff --git a/tools/backup_tool/src/tools_op_restore.cpp b/tools/backup_tool/src/tools_op_restore.cpp index e9c172426397c364c216df94fb40f2e90cbb1b24..bcf4075e88a7e7272cb22a2c1cb5a7cda860bb4e 100644 --- a/tools/backup_tool/src/tools_op_restore.cpp +++ b/tools/backup_tool/src/tools_op_restore.cpp @@ -197,6 +197,11 @@ static void OnBackupServiceDied(shared_ptr ctx) ctx->TryNotify(true); } +static void OnProcess(shared_ptr ctx, const std::string bundleName, const std::string processInfo) +{ + printf("OnProcess bundleName = %s, processInfo = %s\n", bundleName.c_str(), processInfo.c_str()); +} + static void RestoreApp(shared_ptr restore, vector &bundleNames, bool updateSendFiles) { StartTrace(HITRACE_TAG_FILEMANAGEMENT, "RestoreApp"); @@ -257,7 +262,8 @@ static int32_t InitRestoreSession(shared_ptr ctx) .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), .onResultReport = bind(OnResultReport, ctx, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); + .onBackupServiceDied = bind(OnBackupServiceDied, ctx), + .onProcess = bind(OnProcess, ctx, placeholders::_1, placeholders::_2)}); if (ctx->session_ == nullptr) { printf("Failed to init restore\n"); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); diff --git a/tools/backup_tool/src/tools_op_restore_async.cpp b/tools/backup_tool/src/tools_op_restore_async.cpp index a12a600f08e399b2d46b5b5a481742fe9f1d12ba..c87462f695277adc87d3b820a687ed80956946de 100644 --- a/tools/backup_tool/src/tools_op_restore_async.cpp +++ b/tools/backup_tool/src/tools_op_restore_async.cpp @@ -170,6 +170,11 @@ static void OnBackupServiceDied(shared_ptr ctx) ctx->TryNotify(true); } +static void OnProcess(shared_ptr ctx, const std::string bundleName, const std::string processInfo) +{ + printf("OnProcess bundleName = %s, processInfo = %s\n", bundleName.c_str(), processInfo.c_str()); +} + static map> ReadyExtManage(const string &path, std::vector& pkgInfo) { @@ -385,7 +390,8 @@ static int32_t InitArg(const string &pathCapFile, .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), .onResultReport = bind(OnResultReport, ctx, placeholders::_1, placeholders::_2), - .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); + .onBackupServiceDied = bind(OnBackupServiceDied, ctx), + .onProcess = bind(OnProcess, ctx, placeholders::_1, placeholders::_2)}); if (ctx->session_ == nullptr) { printf("Failed to init restore\n"); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); diff --git a/utils/BUILD.gn b/utils/BUILD.gn index 632b98ae19d07e3f5b0b2cba10d0607a7e2cd9fd..bb735177f50a48d20285bcf95305d35d7abc34a3 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -65,6 +65,7 @@ ohos_shared_library("backup_utils") { "src/b_filesystem/b_dir.cpp", "src/b_filesystem/b_file.cpp", "src/b_filesystem/b_file_hash.cpp", + "src/b_json/b_json_clear_data_config.cpp", "src/b_json/b_json_entity_ext_manage.cpp", "src/b_json/b_json_entity_extension_config.cpp", "src/b_json/b_json_service_disposal_config.cpp", @@ -74,26 +75,33 @@ ohos_shared_library("backup_utils") { "src/b_process/b_guard_cwd.cpp", "src/b_process/b_guard_signal.cpp", "src/b_process/b_process.cpp", + "src/b_radar/b_radar.cpp", "src/b_sa/b_sa_utils.cpp", "src/b_tarball/b_tarball_cmdline.cpp", "src/b_tarball/b_tarball_factory.cpp", + "src/b_utils/b_time.cpp", ] configs = [ ":utils_private_config" ] public_configs = [ ":utils_public_config" ] external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", "cJSON:cjson", "c_utils:utils", "faultloggerd:libdfx_dumpcatcher", "hilog:libhilog", + "hisysevent:libhisysevent", "hitrace:hitrace_meter", "init:libbegetutil", + "ipc:ipc_core", ] include_dirs = [ "${path_init}/interfaces/innerkits/include/syspara", "${path_backup}/interfaces/inner_api/native/backup_kit_inner/impl", + "${path_backup}/utils/include", ] deps = [ diff --git a/utils/include/b_error/b_error.h b/utils/include/b_error/b_error.h index 02bd0440ef0a0fee58fc295e28e33e799135a652..4cded015bb8f53cc90a51bb1079b6bd0c7b398d0 100644 --- a/utils/include/b_error/b_error.h +++ b/utils/include/b_error/b_error.h @@ -70,8 +70,9 @@ public: SA_REFUSED_ACT = 0x3002, SA_BROKEN_ROOT_DIR = 0x3003, SA_FORBID_BACKUP_RESTORE = 0x3004, - SA_BOOT_TIMEOUT = 0x3005, + SA_BOOT_EXT_TIMEOUT = 0x3005, SA_BUNDLE_INFO_EMPTY = 0x3006, + SA_BOOT_EXT_FAIL = 0x3007, // 0x4000~0x4999 backup_SDK错误 SDK_INVAL_ARG = 0x4000, @@ -89,6 +90,7 @@ public: EXT_BACKUP_PACKET_ERROR = 0x5007, EXT_METHOD_NOT_EXIST = 0x5008, EXT_THROW_EXCEPTION = 0x5009, + EXT_BACKUP_UNPACKET_ERROR = 0x5010, // 0x6000~0x6999 sa_ext错误 SA_EXT_ERR_CALL = 0x6000, @@ -112,6 +114,8 @@ public: E_EMPTY = 13500005, E_PACKET = 13500006, E_EXCEPTION = 13500007, + E_UNPACKET = 13500008, + E_BEF = 13500009, }; public: @@ -149,6 +153,19 @@ public: return msg_.c_str(); } + /** + * @brief 归一返回备份恢复错误码 + * + * @return ErrCode 备份恢复错误码 + */ + static ErrCode GetBackupCodeByErrno(ErrCode err); + + /** + * @brief 归一返回备份恢复错误信息 + * + * @return string 备份恢复错误信息 + */ + static std::string GetBackupMsgByErrno(ErrCode err); public: /** * @brief 重载bool操作符,判断当前错误是否是错误 @@ -227,8 +244,9 @@ private: {Codes::SA_REFUSED_ACT, "SA refuse to act"}, {Codes::SA_BROKEN_ROOT_DIR, "SA failed to operate on the given root dir"}, {Codes::SA_FORBID_BACKUP_RESTORE, "SA forbid backup or restore"}, - {Codes::SA_BOOT_TIMEOUT, "SA boot application extension time out"}, + {Codes::SA_BOOT_EXT_TIMEOUT, "SA boot application extension time out"}, {Codes::SA_BUNDLE_INFO_EMPTY, "SA the bundle info for backup/restore is empty"}, + {Codes::SA_BOOT_EXT_FAIL, "SA failed to boot application extension"}, {Codes::SDK_INVAL_ARG, "SDK received invalid arguments"}, {Codes::SDK_BROKEN_IPC, "SDK failed to do IPC"}, {Codes::SDK_MIXED_SCENARIO, "SDK involed backup/restore when doing the contrary"}, @@ -240,7 +258,12 @@ private: {Codes::EXT_ABILITY_DIED, "Extension process died"}, {Codes::EXT_FORBID_BACKUP_RESTORE, "forbid backup or restore"}, {Codes::EXT_BACKUP_PACKET_ERROR, "Backup packet error"}, + {Codes::EXT_METHOD_NOT_EXIST, "Extension method not exist"}, {Codes::EXT_THROW_EXCEPTION, "Extension throw exception"}, + {Codes::EXT_BACKUP_UNPACKET_ERROR, "Backup unpacket error"}, + {Codes::SA_EXT_ERR_CALL, "SA Extension received invalid arguments"}, + {Codes::SA_EXT_ERR_SAMGR, "SA Extension get samgr failed"}, + {Codes::SA_EXT_RELOAD_FAIL, "SA Extension reload failed"}, }; static inline const std::map errCodeTable_ { @@ -256,8 +279,9 @@ private: {static_cast(Codes::SA_REFUSED_ACT), BackupErrorCode::E_PERM}, {static_cast(Codes::SA_BROKEN_ROOT_DIR), BackupErrorCode::E_UKERR}, {static_cast(Codes::SA_FORBID_BACKUP_RESTORE), BackupErrorCode::E_FORBID}, - {static_cast(Codes::SA_BOOT_TIMEOUT), BackupErrorCode::E_BTO}, + {static_cast(Codes::SA_BOOT_EXT_TIMEOUT), BackupErrorCode::E_BTO}, {static_cast(Codes::SA_BUNDLE_INFO_EMPTY), BackupErrorCode::E_EMPTY}, + {static_cast(Codes::SA_BOOT_EXT_FAIL), BackupErrorCode::E_BEF}, {static_cast(Codes::SDK_INVAL_ARG), BackupErrorCode::E_INVAL}, {static_cast(Codes::SDK_BROKEN_IPC), BackupErrorCode::E_IPCSS}, {static_cast(Codes::SDK_MIXED_SCENARIO), BackupErrorCode::E_INVAL}, @@ -269,7 +293,12 @@ private: {static_cast(Codes::EXT_ABILITY_TIMEOUT), BackupErrorCode::E_ETO}, {static_cast(Codes::EXT_FORBID_BACKUP_RESTORE), BackupErrorCode::E_FORBID}, {static_cast(Codes::EXT_BACKUP_PACKET_ERROR), BackupErrorCode::E_PACKET}, + {static_cast(Codes::EXT_METHOD_NOT_EXIST), BackupErrorCode::E_INVAL}, {static_cast(Codes::EXT_THROW_EXCEPTION), BackupErrorCode::E_EXCEPTION}, + {static_cast(Codes::EXT_BACKUP_UNPACKET_ERROR), BackupErrorCode::E_UNPACKET}, + {static_cast(Codes::SA_EXT_ERR_CALL), BackupErrorCode::E_INVAL}, + {static_cast(Codes::SA_EXT_ERR_SAMGR), BackupErrorCode::E_IPCSS}, + {static_cast(Codes::SA_EXT_RELOAD_FAIL), BackupErrorCode::E_BEF}, {BackupErrorCode::E_IPCSS, BackupErrorCode::E_IPCSS}, {BackupErrorCode::E_INVAL, BackupErrorCode::E_INVAL}, {BackupErrorCode::E_NOTEXIST, BackupErrorCode::E_NOTEXIST}, @@ -285,10 +314,12 @@ private: {BackupErrorCode::E_EMPTY, BackupErrorCode::E_EMPTY}, {BackupErrorCode::E_PACKET, BackupErrorCode::E_PACKET}, {BackupErrorCode::E_EXCEPTION, BackupErrorCode::E_EXCEPTION}, + {BackupErrorCode::E_UNPACKET, BackupErrorCode::E_UNPACKET}, + {BackupErrorCode::E_BEF, BackupErrorCode::E_BEF}, }; static inline const std::map sysErrnoCodeTable_ { - {EPERM, BackupErrorCode::E_IPCSS}, + {EPERM, BackupErrorCode::E_PERM}, {EIO, BackupErrorCode::E_IO}, {EBADF, BackupErrorCode::E_IO}, {EACCES, BackupErrorCode::E_IO}, @@ -302,6 +333,26 @@ private: {ENOSPC, BackupErrorCode::E_NOSPC}, }; + static inline const std::map backupErrorMsgTable_ { + {BackupErrorCode::E_IPCSS, "IPC error"}, + {BackupErrorCode::E_INVAL, "Invalid argument"}, + {BackupErrorCode::E_NOTEXIST, "Method not exist"}, + {BackupErrorCode::E_UKERR, "Unknown error"}, + {BackupErrorCode::E_PERM, "Operation not permitted"}, + {BackupErrorCode::E_NOMEM, "Out of memory"}, + {BackupErrorCode::E_NOSPC, "No space left on device"}, + {BackupErrorCode::E_IO, "I/O error"}, + {BackupErrorCode::E_FORBID, "Not support backup/restore"}, + {BackupErrorCode::E_BTO, "SA boot extension timeout"}, + {BackupErrorCode::E_ETO, "Extension process timeout"}, + {BackupErrorCode::E_DIED, "Extension process died"}, + {BackupErrorCode::E_EMPTY, "SA the bundle info for backup/restore is empty"}, + {BackupErrorCode::E_PACKET, "Tar failed"}, + {BackupErrorCode::E_EXCEPTION, "Extension throw exception"}, + {BackupErrorCode::E_UNPACKET, "Untar failed"}, + {BackupErrorCode::E_BEF, "SA failed to boot application extension"}, + }; + private: Codes code_ {Codes::OK}; std::string msg_; diff --git a/utils/include/b_filesystem/b_dir.h b/utils/include/b_filesystem/b_dir.h index 753529cb63e2eb48567c061412314a7ceb966072..576cbc80e01b9df4fe60abfe0740e1d3f2806380 100644 --- a/utils/include/b_filesystem/b_dir.h +++ b/utils/include/b_filesystem/b_dir.h @@ -26,6 +26,7 @@ #include #include +#include "b_json/b_report_entity.h" #include "errors.h" namespace OHOS::FileManagement::Backup { @@ -46,7 +47,7 @@ public: * @param excludes 需要排除的文件及目录集合 * @return 错误码、大文件名集合 */ - static std::tuple, std::vector> GetBigFiles( + static std::tuple, std::map> GetBigFiles( const std::vector &includes, const std::vector &excludes); /** @@ -56,6 +57,32 @@ public: * @return std::vector 目录集合 */ static std::vector GetDirs(const std::vector &paths); + + /** + * @brief 从给定的includes和excludes目录中获取所有的大文件和小文件 + * + * @param includes 需要包含的文件及目录集合 + * @param excludes 需要排除的文件及目录集合 + * @return 大文件和小文件的集合 + */ + static std::tuple, std::vector> GetBackupList( + const std::vector &includes, const std::vector &excludes); + + /** + * @brief 获取bigfile和smaillfile的文件信息并生成清单 + * + * @param bigFile 需要包含的文件及目录集合 + * @param smallFile 需要排除的文件及目录集合 + * @param allFiles 生成的所有文件信息清单 + * @param smallFiles 生成的小文件信息清单 + * @param bigFiles 生成的大文件信息清单 + * @return + */ + static void GetUser0FileStat(std::vector bigFile, + std::vector smallFile, + std::vector &allFiles, + std::vector &smallFiles, + std::vector &bigFiles); }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/include/b_filesystem/b_file.h b/utils/include/b_filesystem/b_file.h index 2d69e75fdf09cf070018f38bef7c84d6ee6fd9f7..c2cc3c8af2f59f3b8e04cde0c92bc8675fe93d94 100644 --- a/utils/include/b_filesystem/b_file.h +++ b/utils/include/b_filesystem/b_file.h @@ -82,6 +82,16 @@ public: * @return false some error occur */ static bool GetRealPath(const string &path, string &realPath); + + /** + * @brief check if string is endswith suffix + * + * @param str str + * @param suffix suffix str + * @return true str is endswith suffix + * @return false str is not endswith suffix + */ + static bool EndsWith(const string &str, const string &suffix); private: }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/include/b_json/b_json_clear_data_config.h b/utils/include/b_json/b_json_clear_data_config.h new file mode 100644 index 0000000000000000000000000000000000000000..1f60863fcc3e2be9d8f3fad8c485cdb9d67c2fde --- /dev/null +++ b/utils/include/b_json/b_json_clear_data_config.h @@ -0,0 +1,86 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_BACKUP_B_JSON_CLEAR_DATA_CONFIG_H +#define OHOS_FILEMGMT_BACKUP_B_JSON_CLEAR_DATA_CONFIG_H + +#include +#include +#include + +namespace OHOS::FileManagement::Backup { +class BJsonClearDataConfig { +public: + /** + * @brief 判断配置文件中是否有记录 + * + */ + bool HasClearBundleRecord(); + + /** + * @brief 判断配置文件中是否存在bundleName记录 + * + * @param bundlename + */ + bool FindClearBundleRecord(const std::string& bundleName); + + /** + * @brief 配置文件中插入bundleName记录 + * + * @param bundlename + */ + bool InsertClearBundleRecord(const std::string& bundleName); + + /** + * @brief 配置文件中删除bundleName记录 + * + * @param bundlename + */ + bool DeleteClearBundleRecord(const std::string& bundleName); + + /** + * @brief 配置文件中获取bundlename + * + */ + std::vector GetAllClearBundleRecords(); + + /** + * @brief 删除配置文件 + * + * + */ + bool DeleteConfigFile(); + +public: + /** + * @brief 构造方法 + * + * + */ + BJsonClearDataConfig(); +private: + /** + * @brief 配置文件中删除bundleName记录 + * + * @param bundlename + */ + bool WriteClearBundleRecord(const std::string& bundleName); + +private: + std::mutex fileMutex_; +}; + +} // namespace OHOS::FileManagement::Backup +#endif // OHOS_FILEMGMT_BACKUP_B_JSON_CLEAR_DATA_CONFIG_H \ No newline at end of file diff --git a/utils/include/b_json/b_json_entity_caps.h b/utils/include/b_json/b_json_entity_caps.h index 548beef14028f335b4138673c18544a286212624..e641077e010be6bec3657ce1e2f5891d498bfdc7 100644 --- a/utils/include/b_json/b_json_entity_caps.h +++ b/utils/include/b_json/b_json_entity_caps.h @@ -24,6 +24,7 @@ class BJsonEntityCaps : public BJsonEntity { public: struct BundleInfo { std::string name; + int appIndex; int64_t versionCode; std::string versionName; int64_t spaceOccupied; @@ -74,6 +75,7 @@ public: for (const auto &item : bundleInfos) { Json::Value arrObj; arrObj["name"] = item.name; + arrObj["appIndex"] = item.appIndex; arrObj["versionCode"] = item.versionCode; arrObj["versionName"] = item.versionName; arrObj["spaceOccupied"] = item.spaceOccupied; @@ -146,7 +148,7 @@ public: return obj_["extraInfo"]; } - bool CheckBundlePropertiesIsValid(const Json::Value &bundleInfo) + bool CheckBundlePropertiesValid(const Json::Value &bundleInfo) { if (!bundleInfo) { HILOGE("Failed Check bundleInfo"); @@ -187,7 +189,7 @@ public: } std::vector bundleInfos; for (const auto &item : obj_["bundleInfos"]) { - if (!CheckBundlePropertiesIsValid(item)) { + if (!CheckBundlePropertiesValid(item)) { return {}; } string restoreDeps(""); @@ -210,7 +212,11 @@ public: if (item.isMember("fullBackupOnly") && item["fullBackupOnly"].isBool()) { fullBackupOnly = item["fullBackupOnly"].asBool(); } - bundleInfos.emplace_back(BundleInfo {item["name"].asString(), item["versionCode"].asInt64(), + int appIndex = 0; + if (item.isMember("appIndex") && item["appIndex"].isInt()) { + appIndex = item["appIndex"].asInt(); + } + bundleInfos.emplace_back(BundleInfo {item["name"].asString(), appIndex, item["versionCode"].asInt64(), item["versionName"].asString(), item["spaceOccupied"].asInt64(), increSpaceOccupied, item["allToBackup"].asBool(), fullBackupOnly, diff --git a/utils/include/b_jsonutil/b_jsonutil.h b/utils/include/b_jsonutil/b_jsonutil.h index 9efa19376a7aefef8919af267bb726b03d044de9..910a19704d01fb92e273b7c3c0566ceec9e46156 100644 --- a/utils/include/b_jsonutil/b_jsonutil.h +++ b/utils/include/b_jsonutil/b_jsonutil.h @@ -34,11 +34,10 @@ public: * @brief 带有拼接字符的bundleName按照拼接字符进行分割 * * @param bundleNameStr bundleName拼接index的字符串 - * @param patternInfo 拼接字符串 * * @return 分割好的结果赋值给结构体 */ - static BundleDetailInfo ParseBundleNameIndexStr (const std::string &bundleNameStr, const std::string &patternInfo); + static BundleDetailInfo ParseBundleNameIndexStr (const std::string &bundleNameStr); /** * @brief 将传进来的bundleNames的集合进行按照拼接字符分割处理 @@ -48,26 +47,28 @@ public: * @param patternInfo 拼接的字符 * @param realBundleNames 分割后真正的bundleNames * @param userId userId + * @param isClearDataFlags 框架是否清理标志集合 * * @return 包名和解析结果的对应关系集合 * */ static std::map> BuildBundleInfos( const std::vector &bundleNames, const std::vector &details, - std::vector &realBundleNames, int32_t userId); + std::vector &realBundleNames, int32_t userId, + std::map &isClearDataFlags); /** * @brief 解析单个bundle对应的json串 * - * @param bundleDetailInfo json串 - * @param bundleDetail 结构体对象 - * @param bundleNameOnly bundle名称 - * @param bundleIndex bundle对应的索引 + * @param bundleInfo json串 + * @param bundleDetails 结构体对象 + * @param bundleDetailInfo bundle信息 + * @param isClearData 框架是否清理标志 * @param userId userId * */ static void ParseBundleInfoJson(const std::string &bundleInfo, std::vector &bundleDetails, - std::string &bundleNameOnly, int bundleIndex, int32_t userId); + BJsonUtil::BundleDetailInfo bundleDetailInfo, bool &isClearData, int32_t userId); /** * @brief 根据业务类型和bundleName确定唯一的bundleInfo @@ -93,7 +94,60 @@ public: * @return 是否组建成功 * */ - static bool BuildRestoreErrInfo(std::string &jsonStr, int errCode, std::string errMsg); + static bool BuildExtensionErrInfo(std::string &jsonStr, int errCode, std::string errMsg); + + /** + * @brief 拼接包名和分身对应的索引 + * + * @param bundleName 包名 + * @param bundleIndex 索引 + * + * @return 拼接结果 + */ + static std::string BuildBundleNameIndexInfo(const std::string &bundleName, int bundleIndex); + + /** + * @brief 组建恢复文件错误信息的json + * + * @param jsonStr 组建结果 + * @param errCode 错误码 + * + * @return 是否组建成功 + * + */ + static bool BuildExtensionErrInfo(std::string &jsonStr, std::map> errFileInfo); + + /** + * @brief 组建App进度返回的信息 + * + * @param jsonStr 组建结果 + * @param onProcessRet onProcess接口返回值 + * + * @return 是否组建成功 + * + */ + static bool BuildOnProcessRetInfo(std::string &jsonStr, std::string onProcessRet); + + /** + * @brief 构建包含userId的detailInfo + * + * @param userId userId + * @param detailInfo 包含userId的detailInfo + * + * @return 是否组建成功 + * + */ + static bool BuildBundleInfoJson(int32_t userId, std::string &detailInfo); + + /** + * @brief 判断传入的bundleinfo中是否包含unicast字段 + * + * @param bundleinfo json串 + * + * @return 是否包含unicast字段 + * + */ + static bool HasUnicastInfo(std::string &bundleInfo); }; } // namespace OHOS::FileManagement::Backup diff --git a/utils/include/b_radar/b_radar.h b/utils/include/b_radar/b_radar.h new file mode 100644 index 0000000000000000000000000000000000000000..87fd5ac4e38a892e6701e3fad0bcb7537955018a --- /dev/null +++ b/utils/include/b_radar/b_radar.h @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_FILEMGMT_BACKUP_B_RADAR_H +#define OHOS_FILEMGMT_BACKUP_B_RADAR_H +#include +#include + +namespace OHOS::FileManagement::Backup { +enum class BizStageBackup : int32_t { + BIZ_STAGE_DEFAULT = 0, + BIZ_STAGE_BOOT_BACKUP_SA_FAIL, + BIZ_STAGE_GET_LOCAL_CAPABILITIES_FAIL, + BIZ_STAGE_CREATE_BACKUP_SESSION_FAIL, + BIZ_STAGE_APPEND_BUNDLES_FAIL, + BIZ_STAGE_CONNECT_EXTENSION_FAIL, + BIZ_STAGE_START_DISPOSE_FAIL, + BIZ_STAGE_EXTENSION_ABNORMAL_EXIT, + BIZ_STAGE_GET_BACKUP_INFO_FAIL, + BIZ_STAGE_ON_BACKUP, + BIZ_STAGE_DO_BACKUP, + BIZ_STAGE_CHECK_DATA_FAIL, + BIZ_STAGE_END_DISPOSE_FAIL, + BIZ_STAGE_CLIENT_ABNORMAL_EXIT, + BIZ_STAGE_PERMISSION_CHECK_FAIL +}; + +enum class BizStageRestore : int32_t { + BIZ_STAGE_DEFAULT = 0, + BIZ_STAGE_BOOT_BACKUP_SA_FAIL, + BIZ_STAGE_GET_LOCAL_CAPABILITIES_FAIL, + BIZ_STAGE_CREATE_RESTORE_SESSION_FAIL, + BIZ_STAGE_APPEND_BUNDLES_FAIL, + BIZ_STAGE_CONNECT_EXTENSION_FAIL, + BIZ_STAGE_START_DISPOSE_FAIL, + BIZ_STAGE_EXTENSION_ABNORMAL_EXIT, + BIZ_STAGE_GET_FILE_HANDLE_FAIL, + BIZ_STAGE_DO_RESTORE, + BIZ_STAGE_CHECK_DATA_FAIL, + BIZ_STAGE_ON_RESTORE, + BIZ_STAGE_END_DISPOSE_FAIL, + BIZ_STAGE_CLIENT_ABNORMAL_EXIT, + BIZ_STAGE_PERMISSION_CHECK_FAIL +}; + +class AppRadar { +public: + static AppRadar &GetInstance() + { + static AppRadar instance; + return instance; + } + +public: + struct Info { + std::string bundleName; + std::string status; + std::string resInfo; + + Info(const std::string &bundleName, const std::string &status, const std::string &resInfo) + : bundleName(bundleName), status(status), resInfo(resInfo) {} + }; + + struct DoRestoreInfo { + uint32_t bigFileNum; + uint64_t bigFileSize; + uint32_t bigFileSpendTime; + uint32_t tarFileNum; + uint64_t tarFileSize; + uint32_t tarFileSpendTime; + uint32_t totalFileSpendTime; + }; + +public: + int32_t GetUserId(); + void RecordDefaultFuncRes(Info &info, const std::string &func, int32_t userId, + enum BizStageBackup bizStage, int32_t resultCode); + void RecordBackupFuncRes(Info &info, const std::string &func, int32_t userId, + enum BizStageBackup bizStage, int32_t resultCode); + void RecordRestoreFuncRes(Info &info, const std::string &func, int32_t userId, + enum BizStageRestore bizStage, int32_t resultCode); +private: + AppRadar() = default; + ~AppRadar() = default; + AppRadar(const AppRadar &) = delete; + AppRadar &operator=(const AppRadar &) = delete; + AppRadar(AppRadar &&) = delete; + AppRadar &operator=(AppRadar &&) = delete; +}; +} // namespace OHOS::FileManagement::AppRadar +#endif // OHOS_FILEMGMT_BACKUP_B_RADAR_H diff --git a/utils/include/b_resources/b_constants.h b/utils/include/b_resources/b_constants.h index 512526b5caba6b5f2a9c5910abd550148247f969..849f07ecf4a44f2f7fb61d54bfc9961a8ac6035f 100644 --- a/utils/include/b_resources/b_constants.h +++ b/utils/include/b_resources/b_constants.h @@ -30,6 +30,7 @@ static inline const char *EXTENSION_VERSION_CODE_PARA = "versionCode"; static inline const char *EXTENSION_VERSION_NAME_PARA = "versionName"; 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"; enum class ExtensionAction { INVALID = 0, @@ -42,6 +43,7 @@ enum ServiceSchedAction { START = 1, RUNNING = 2, FINISH = 3, + CLEAN = 4, }; constexpr int SPAN_USERID_UID = 200000; @@ -67,6 +69,11 @@ constexpr int IPC_MAX_WAIT_TIME = 3000; // IPC通讯最大等待时间(s) constexpr int MAX_PARCELABLE_VECTOR_NUM = 10000; constexpr char FILE_SEPARATOR_CHAR = '/'; +// 分片打包常量 +const uint64_t DEFAULT_SLICE_SIZE = 100 * 1024 * 1024; // 分片文件大小为100M +const uint32_t MAX_FILE_COUNT = 6000; // 单个tar包最多包含6000个文件 +const int FILE_AND_MANIFEST_FD_COUNT = 2; // 每组文件和简报数量统计 + constexpr int DEFAULT_VFS_CACHE_PRESSURE = 100; // 默认内存回收参数 constexpr int BACKUP_VFS_CACHE_PRESSURE = 10000; // 备份过程修改参数 @@ -76,6 +83,14 @@ constexpr int MAX_FD_SEND_RATE = 800; // 允许应用申请的最大FD数量 constexpr int MIN_FD_SEND_RATE = 0; // 允许应用申请的最小FD数量 constexpr int DEFAULT_FD_SEND_RATE = 60; // 框架默认的FD数量 constexpr int32_t PARAM_STARING_MAX_MEMORY = 2 * 1024 * 1024; +constexpr uint32_t H2MS = 60 * 60 * 1000; +constexpr uint32_t MAX_UPDATE_TIMER = 4 * H2MS; +constexpr uint32_t DEFAULT_TIMEOUT = 15 * 60 * 1000; +constexpr uint32_t TIMEOUT_INVALID = UINT32_MAX; + +constexpr int CALL_APP_ON_PROCESS_TIME_INTERVAL = 5; // 框架每隔5s去调用应用的onProcess +constexpr int APP_ON_PROCESS_MAX_TIMEOUT = 1000; // 应用的onProcess接口最大超时时间为1秒 +constexpr int APP_ON_PROCESS_TIMEOUT_MAX_COUNT = 3; // 应用的onProcess接口超时的上限次数 // backup.para内配置项的名称,该配置项值为true时可在不更新hap包的情况下,可以读取包管理元数据配置文件的内容 static inline std::string BACKUP_DEBUG_OVERRIDE_EXTENSION_CONFIG_KEY = "backup.debug.overrideExtensionConfig"; @@ -105,6 +120,8 @@ static inline std::string_view SA_BUNDLE_BACKUP_TMP_DIR = "/tmp/"; static inline std::string_view BACKUP_TOOL_RECEIVE_DIR = "/data/backup/received/"; static inline std::string_view PATH_BUNDLE_BACKUP_HOME_EL1 = "/data/storage/el1/base/.backup"; static inline std::string_view PATH_BUNDLE_BACKUP_HOME = "/data/storage/el2/base/.backup"; +static inline std::string_view PATH_FILEMANAGE_BACKUP_HOME = "/storage/Users/currentUser/.backup"; +static inline std::string_view PATH_MEDIALDATA_BACKUP_HOME = "/storage/media/local/files/.backup"; static inline std::string_view BACKUP_TOOL_LINK_DIR = "/data/backup"; static inline std::string_view BACKUP_TOOL_INCREMENTAL_RECEIVE_DIR = "/data/backup/incrementalreceived/"; static inline std::string_view BACKUP_TOOL_MANIFEST = "/manifest"; @@ -112,6 +129,14 @@ static inline std::string_view BACKUP_TOOL_INCREMENTAL = "/incremental"; static inline std::string BACKUP_DIR_PRE = "/data/storage/"; static inline std::string CONTEXT_ELS[] = {"el1", "el2"}; static inline std::string BACKUP_DIR_END = "/base/.backup/"; +static inline std::string BUNDLE_BASE_DIR = "/data/storage/el2/base"; + +// 文管bundleName +static inline std::string BUNDLE_FILE_MANAGER = "hmos.filemanager"; +// 文管bundleNameSize +constexpr size_t FM_LEN = 27; +// 媒体库数据bundleName +static inline std::string BUNDLE_MEDIAL_DATA = "com.ohos.medialibrary.medialibrarydata"; // SA Ext constexpr int BACKUP_DEFAULT_SA_ID = -1; constexpr int BACKUP_SA_RELOAD_MAX = 2; @@ -194,6 +219,14 @@ static inline std::string MANIFEST_FD = "manifestFd"; static inline std::string LAST_INCREMENTAL_TIME = "lastIncrementalTime"; static inline std::string PARAMETERS = "parameters"; static inline std::string PRIORITY = "priority"; + +// unicast +const std::string UNICAST_TYPE = "unicast"; + +// 雷达打点引用到的常量 +constexpr int32_t MS_1000 = 1000; +constexpr uint8_t INDEX = 3; +static inline std::string FILE_BACKUP_RESTORE_EVENTS = "FILE_BACKUP_RESTORE_EVENTS"; } // namespace OHOS::FileManagement::Backup::BConstants #endif // OHOS_FILEMGMT_BACKUP_B_CONSTANTS_H diff --git a/utils/include/b_sa/b_sa_utils.h b/utils/include/b_sa/b_sa_utils.h index 1548fed1e68e7450da4138c4eb273a70e8e1eb21..b8d3edf4cb048d937f4a5b73fd27ad6ce7fcea33 100644 --- a/utils/include/b_sa/b_sa_utils.h +++ b/utils/include/b_sa/b_sa_utils.h @@ -21,6 +21,9 @@ namespace OHOS::FileManagement::Backup { class SAUtils { public: static bool IsSABundleName(std::string bundleName); + static bool CheckBackupPermission(); + static bool CheckPermission(const std::string &permission); + static bool IsSystemApp(); }; -} // namespace OHOS::FileManagement::Backup::BEncryption +} // namespace OHOS::FileManagement::Backup::SAUtils #endif // OHOS_FILEMGMT_BACKUP_B_SA_H \ No newline at end of file diff --git a/utils/include/b_utils/b_time.h b/utils/include/b_utils/b_time.h new file mode 100644 index 0000000000000000000000000000000000000000..840e5e5b7254686b3a850069f91692e5041d4611 --- /dev/null +++ b/utils/include/b_utils/b_time.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_B_TIME_H +#define OHOS_FILEMGMT_BACKUP_B_TIME_H +#include + +namespace OHOS::FileManagement::Backup { +class TimeUtils { +public: + static int64_t GetTimeS(); + static int64_t GetTimeMS(); + static int64_t GetTimeUS(); + static std::string GetCurrentTime(); +}; +} // namespace OHOS::FileManagement::TimeUtils +#endif // OHOS_FILEMGMT_BACKUP_B_TIME_H \ No newline at end of file diff --git a/utils/src/b_error/b_error.cpp b/utils/src/b_error/b_error.cpp index d99d3e62e83b2a882b9cf10ca0a3de5a7374cb64..7026b6a9e560e2416ae28ce4de74e7b41fd80ad2 100644 --- a/utils/src/b_error/b_error.cpp +++ b/utils/src/b_error/b_error.cpp @@ -52,6 +52,7 @@ string BError::WrapMessageWithExtraInfos(const char *fileName, (void)HILOG_IMPL(LOG_CORE, LOG_DEBUG, LOG_DOMAIN, LOG_TAG, "%{public}s", res.c_str()); return res; } + int BError::GetCode() const { int code = static_cast(GetRawCode()); @@ -73,4 +74,23 @@ int BError::GetCodeByErrno(int32_t errnoSys) } return BackupErrorCode::E_UKERR; } + +ErrCode BError::GetBackupCodeByErrno(ErrCode err) +{ + if (err == 0) { + return 0; + } + if (errCodeTable_.find(err) != errCodeTable_.end()) { + return errCodeTable_.at(err); + } + return BackupErrorCode::E_UKERR; +} + +string BError::GetBackupMsgByErrno(ErrCode err) +{ + if (backupErrorMsgTable_.find(err) != backupErrorMsgTable_.end()) { + return backupErrorMsgTable_.at(err); + } + return backupErrorMsgTable_.at(BackupErrorCode::E_UKERR); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_filesystem/b_dir.cpp b/utils/src/b_filesystem/b_dir.cpp index f8c70da1be67c17dba8c26707d7512478710d751..37c40224a530924ec4a0522b0e2e531e5a2ba0f9 100644 --- a/utils/src/b_filesystem/b_dir.cpp +++ b/utils/src/b_filesystem/b_dir.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -27,6 +28,7 @@ #include #include "b_error/b_error.h" +#include "b_filesystem/b_file_hash.h" #include "b_resources/b_constants.h" #include "directory_ex.h" #include "errors.h" @@ -40,6 +42,7 @@ static bool IsEmptyDirectory(const string &path) { DIR *dir = opendir(path.c_str()); if (dir == nullptr) { + HILOGE("Opendir failed, errno:%{public}d", errno); return false; } bool isEmpty = true; @@ -54,10 +57,10 @@ static bool IsEmptyDirectory(const string &path) return isEmpty; } -static tuple, vector> GetFile(const string &path, off_t size = -1) +static tuple, map> GetFile(const string &path, off_t size = -1) { map files; - vector smallFiles; + map smallFiles; struct stat sta = {}; if (stat(path.data(), &sta) == -1) { return {BError(errno).GetCode(), files, smallFiles}; @@ -66,7 +69,7 @@ static tuple, vector> GetFile(const st return {BError(BError::Codes::OK).GetCode(), files, smallFiles}; } if (sta.st_size <= size) { - smallFiles.emplace_back(path); + smallFiles.insert(make_pair(path, sta.st_size)); } else { files.try_emplace(path, sta); } @@ -77,26 +80,26 @@ static uint32_t CheckOverLongPath(const string &path) { uint32_t len = path.length(); if (len >= PATH_MAX_LEN) { - size_t found = path.find_last_of('/'); + size_t found = path.find_last_of(BConstants::FILE_SEPARATOR_CHAR); string sub = path.substr(found + 1); HILOGE("Path over long, length:%{public}d, fileName:%{public}s.", len, sub.c_str()); } return len; } -static tuple, vector> GetDirFilesDetail(const string &path, - bool recursion, - off_t size = -1) +static tuple, map> GetDirFilesDetail(const string &path, + bool recursion, + off_t size = -1) { map files; - vector smallFiles; + map smallFiles; if (IsEmptyDirectory(path)) { string newPath = path; - if (path.at(path.size()-1) != '/') { - newPath += '/'; + if (path.at(path.size()-1) != BConstants::FILE_SEPARATOR_CHAR) { + newPath += BConstants::FILE_SEPARATOR_CHAR; } - smallFiles.emplace_back(newPath); + smallFiles.insert(make_pair(newPath, 0)); return {ERR_OK, files, smallFiles}; } @@ -110,32 +113,33 @@ static tuple, vector> GetDirFilesDetai // current dir OR parent dir if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) { continue; - } else if (ptr->d_type == DT_DIR) { - if (!recursion) { - continue; - } - auto [errCode, subFiles, subSmallFiles] = - GetDirFilesDetail(IncludeTrailingPathDelimiter(path) + string(ptr->d_name), recursion, size); - if (errCode != 0) { - return {errCode, files, smallFiles}; - } - files.merge(subFiles); - smallFiles.insert(smallFiles.end(), subSmallFiles.begin(), subSmallFiles.end()); - } else if (ptr->d_type == DT_LNK) { - continue; - } else { + } else if (ptr->d_type == DT_REG) { struct stat sta = {}; string fileName = IncludeTrailingPathDelimiter(path) + string(ptr->d_name); if (CheckOverLongPath(fileName) >= PATH_MAX_LEN || stat(fileName.data(), &sta) == -1) { continue; } if (sta.st_size <= size) { - smallFiles.emplace_back(fileName); + smallFiles.insert(make_pair(fileName, sta.st_size)); continue; } files.try_emplace(fileName, sta); + } else if (ptr->d_type != DT_DIR) { + HILOGE("Not support file type"); + continue; + } + // DT_DIR type + if (!recursion) { + continue; + } + auto [errCode, subFiles, subSmallFiles] = + GetDirFilesDetail(IncludeTrailingPathDelimiter(path) + string(ptr->d_name), recursion, size); + if (errCode != 0) { + return {errCode, files, smallFiles}; } + files.merge(subFiles); + smallFiles.insert(subSmallFiles.begin(), subSmallFiles.end()); } return {ERR_OK, files, smallFiles}; } @@ -184,7 +188,7 @@ static set ExpandPathWildcard(const vector &vec, bool onlyPath) for (auto it = expandPath.begin(); it != expandPath.end(); ++it) { filteredPath.insert(*it); - if (onlyPath && *it->rbegin() != '/') { + if (onlyPath && *it->rbegin() != BConstants::FILE_SEPARATOR_CHAR) { continue; } auto jt = it; @@ -197,20 +201,20 @@ static set ExpandPathWildcard(const vector &vec, bool onlyPath) return filteredPath; } -tuple, vector> BDir::GetBigFiles(const vector &includes, - const vector &excludes) +tuple, map> BDir::GetBigFiles(const vector &includes, + const vector &excludes) { set inc = ExpandPathWildcard(includes, false); map incFiles; - vector incSmallFiles; + map incSmallFiles; for (const auto &item : inc) { auto [errCode, files, smallFiles] = GetDirFilesDetail(item, true, BConstants::BIG_FILE_BOUNDARY); if (errCode == 0) { int32_t num = static_cast(files.size()); incFiles.merge(move(files)); HILOGI("big files: %{public}d; small files: %{public}d", num, static_cast(smallFiles.size())); - incSmallFiles.insert(incSmallFiles.end(), smallFiles.begin(), smallFiles.end()); + incSmallFiles.insert(smallFiles.begin(), smallFiles.end()); } } @@ -223,7 +227,7 @@ tuple, vector> BDir::GetBigFiles(const continue; } string excludeItem = item; - if (excludeItem.at(item.size() - 1) == '/') { + if (excludeItem.at(item.size() - 1) == BConstants::FILE_SEPARATOR_CHAR) { excludeItem += "*"; } if (fnmatch(excludeItem.data(), str.data(), FNM_LEADING_DIR) == 0) { @@ -233,10 +237,10 @@ tuple, vector> BDir::GetBigFiles(const return false; }; - vector resSmallFiles; + map resSmallFiles; for (const auto &item : incSmallFiles) { - if (!isMatch(excludes, item)) { - resSmallFiles.emplace_back(item); + if (!isMatch(excludes, item.first)) { + resSmallFiles.insert(make_pair(item.first, item.second)); } } @@ -251,6 +255,180 @@ tuple, vector> BDir::GetBigFiles(const return {ERR_OK, move(bigFiles), move(resSmallFiles)}; } +void BDir::GetUser0FileStat(vector bigFile, + vector smallFile, + vector &allFiles, + vector &smallFiles, + vector &bigFiles) +{ + for (const auto &item : smallFile) { + struct ReportFileInfo storageFiles; + storageFiles.filePath = item; + if (filesystem::is_directory(item)) { + storageFiles.isDir = 1; + storageFiles.userTar = 0; + } else { + storageFiles.isDir = 0; + auto [res, fileHash] = BackupFileHash::HashWithSHA256(item); + if (fileHash.empty()) { + continue; + } + storageFiles.hash = fileHash; + storageFiles.userTar = 1; + } + struct stat sta = {}; + if (stat(item.c_str(), &sta) != 0) { + throw BError(BError::Codes::EXT_INVAL_ARG, "Get file stat failed"); + } + storageFiles.size = sta.st_size; + storageFiles.mode = to_string(static_cast(sta.st_mode)); + int64_t lastUpdateTime = static_cast(sta.st_mtime); + storageFiles.mtime = lastUpdateTime; + allFiles.push_back(storageFiles); + smallFiles.push_back(storageFiles); + } + for (const auto &item : bigFile) { + struct ReportFileInfo storageFiles; + storageFiles.filePath = item; + auto [res, fileHash] = BackupFileHash::HashWithSHA256(item); + if (fileHash.empty()) { + continue; + } + storageFiles.hash = fileHash; + struct stat sta = {}; + if (stat(item.c_str(), &sta) != 0) { + throw BError(BError::Codes::EXT_INVAL_ARG, "Get file stat failed"); + } + storageFiles.size = sta.st_size; + storageFiles.mode = to_string(static_cast(sta.st_mode)); + int64_t lastUpdateTime = static_cast(sta.st_mtime); + storageFiles.mtime = lastUpdateTime; + storageFiles.userTar = 1; + allFiles.push_back(storageFiles); + bigFiles.push_back(storageFiles); + } + HILOGI("get FileStat end, bigfiles = %{public}zu, smallFiles = %{public}zu, allFiles = %{public}zu,", + bigFiles.size(), smallFiles.size(), allFiles.size()); +} + +static tuple, vector> IsNotPath(const string &path, vector &bigFiles, + vector &smallFiles, off_t size) +{ + struct stat sta = {}; + if (CheckOverLongPath(path) >= PATH_MAX_LEN || stat(path.data(), &sta) == -1) { + return {}; + } + if (sta.st_size <= size) { + smallFiles.push_back(path); + HILOGI("bigfiles = %{public}zu, smallfiles = %{public}zu", bigFiles.size(), smallFiles.size()); + return {bigFiles, smallFiles}; + } + bigFiles.push_back(path); + HILOGI("bigfiles = %{public}zu, smallfiles = %{public}zu", bigFiles.size(), smallFiles.size()); + return {bigFiles, smallFiles}; +} + +static tuple, vector> GetUser0DirFilesDetail(const string &path, off_t size = -1) +{ + vector bigFiles; + vector smallFiles; + if (IsEmptyDirectory(path)) { + string newPath = path; + if (path.at(path.size()-1) != BConstants::FILE_SEPARATOR_CHAR) { + newPath += BConstants::FILE_SEPARATOR_CHAR; + } + smallFiles.push_back(path); + return {bigFiles, smallFiles}; + } + if (filesystem::is_regular_file(path)) { + return IsNotPath(path, bigFiles, smallFiles, size); + } + unique_ptr> dir = {opendir(path.c_str()), closedir}; + if (!dir) { + HILOGE("Invalid directory path: %{private}s", path.c_str()); + return {}; + } + struct dirent *ptr = nullptr; + while (!!(ptr = readdir(dir.get()))) { + // current dir OR parent dir + if ((strcmp(ptr->d_name, ".") == 0) || (strcmp(ptr->d_name, "..") == 0)) { + continue; + } else if (ptr->d_type == DT_REG) { + struct stat sta = {}; + string fileName = IncludeTrailingPathDelimiter(path) + string(ptr->d_name); + if (CheckOverLongPath(fileName) >= PATH_MAX_LEN || stat(fileName.data(), &sta) == -1) { + continue; + } + if (sta.st_size <= size) { + smallFiles.push_back(fileName); + continue; + } + + bigFiles.push_back(fileName); + } else if (ptr->d_type != DT_DIR) { + HILOGE("Not support file type"); + continue; + } + // DT_DIR type + auto [subBigFiles, subSmallFiles] = + GetUser0DirFilesDetail(IncludeTrailingPathDelimiter(path) + string(ptr->d_name), size); + bigFiles.insert(bigFiles.end(), subBigFiles.begin(), subBigFiles.end()); + smallFiles.insert(smallFiles.end(), subSmallFiles.begin(), subSmallFiles.end()); + } + HILOGI("bigfiles = %{public}zu, smallfiles = %{public}zu", bigFiles.size(), smallFiles.size()); + return {bigFiles, smallFiles}; +} + +tuple, vector> BDir::GetBackupList(const vector &includes, + const vector &excludes) +{ + HILOGI("start get bigfiles and smallfiles"); + set inc = ExpandPathWildcard(includes, false); + vector bigFiles; + vector smallFiles; + for (const auto &item : inc) { + auto [bigFile, smallFile] = GetUser0DirFilesDetail(item, BConstants::BIG_FILE_BOUNDARY); + bigFiles.insert(bigFiles.end(), bigFile.begin(), bigFile.end()); + smallFiles.insert(smallFiles.end(), smallFile.begin(), smallFile.end()); + } + HILOGI("end bigfiles = %{public}zu, smallfiles = %{public}zu", bigFiles.size(), smallFiles.size()); + auto isMatch = [](const vector &s, const string &str) -> bool { + if (str.empty()) { + return false; + } + for (const string &item : s) { + if (item.empty()) { + continue; + } + string excludeItem = item; + if (excludeItem.at(item.size() - 1) == BConstants::FILE_SEPARATOR_CHAR) { + excludeItem += "*"; + } + if (fnmatch(excludeItem.data(), str.data(), FNM_LEADING_DIR) == 0) { + return true; + } + } + return false; + }; + + for (auto item = bigFiles.begin(); item != bigFiles.end();) { + if (isMatch(excludes, *item)) { + item = bigFiles.erase(item); + } else { + ++item; + } + } + for (auto item = smallFiles.begin(); item != smallFiles.end();) { + if (isMatch(excludes, *item)) { + item = smallFiles.erase(item); + } else { + ++item; + } + } + HILOGI("End compare bigfiles = %{public}zu, smallfiles = %{public}zu", bigFiles.size(), smallFiles.size()); + return {bigFiles, smallFiles}; +} + vector BDir::GetDirs(const vector &paths) { vector wildcardPath(paths.begin(), paths.end()); diff --git a/utils/src/b_filesystem/b_file.cpp b/utils/src/b_filesystem/b_file.cpp index f5828df41e84daca1131cc0b3cf2c4b9487a225a..27b91007816ab6efdd72c8b1000bfbd5c4d37eb1 100644 --- a/utils/src/b_filesystem/b_file.cpp +++ b/utils/src/b_filesystem/b_file.cpp @@ -186,10 +186,19 @@ bool BFile::MoveFile(const string &from, const string &to) throw BError(errno); } newPath.append("/").append(basename(name.get())); - if (rename(oldPath.c_str(), newPath.c_str())) { - HILOGE("failed to rename path, oldPath:%{public}s ,newPath: %{public}s", - GetAnonyPath(oldPath).c_str(), GetAnonyPath(newPath).c_str()); - throw BError(errno); + if (rename(oldPath.c_str(), newPath.c_str()) != 0) { + HILOGI("rename err,try copy errno: %{public}d", errno); + UniqueFd fdFrom(open(oldPath.data(), O_RDONLY)); + if (fdFrom == -1) { // -1: fd error code + HILOGE("failed to open the file %{public}s", GetAnonyPath(from).c_str()); + throw BError(errno); + } + UniqueFd fdTo(open(newPath.data(), O_RDWR | O_CREAT | O_TRUNC, S_IRUSR | S_IWUSR)); + if (fdTo == -1) { // -1: fd error code + HILOGE("failed to open the file %{public}s", GetAnonyPath(to).c_str()); + throw BError(errno); + } + SendFile(fdTo, fdFrom); } return true; } catch (const BError &e) { @@ -201,4 +210,12 @@ bool BFile::MoveFile(const string &from, const string &to) } return false; } + +bool BFile::EndsWith(const string &str, const string &suffix) +{ + if (suffix.length() > str.length()) { + return false; + } + return (str.rfind(suffix) == (str.length() - suffix.length())); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_json/b_json_clear_data_config.cpp b/utils/src/b_json/b_json_clear_data_config.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8210c139780417d2a0e9e1530fddb6608b627253 --- /dev/null +++ b/utils/src/b_json/b_json_clear_data_config.cpp @@ -0,0 +1,356 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "b_json/b_json_clear_data_config.h" + +#include +#include +#include +#include +#include "unique_fd.h" +#include "filemgmt_libhilog.h" + +#include "cJSON.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +namespace { + const string PATH_BUNDLE_BACKUP_HOME = "/data/service/el2/100/backup/"; + const string CONFIG_NAME = "ClearDataConfig.json"; +} + +BJsonClearDataConfig::BJsonClearDataConfig() +{ + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + if (access(filePath.c_str(), F_OK) == 0) { + HILOGI("file exist filePath:%{public}s", filePath.c_str()); + return ; + } + HILOGI("Failed to access filePath :%{public}s", filePath.c_str()); + UniqueFd fd(open(filePath.c_str(), O_RDWR | O_CREAT, S_IRUSR | S_IWUSR)); + if (fd < 0) { + HILOGE("Failed to creat filePath :%{public}s", filePath.c_str()); + return ; + } + cJSON *jsonObjectDis = cJSON_CreateObject(); + if (jsonObjectDis == nullptr) { + HILOGE("Creat json failed"); + return ; + } + cJSON *jsonArray = cJSON_CreateArray(); + if (jsonArray == nullptr) { + HILOGE("Creat json failed"); + cJSON_Delete(jsonObjectDis); + return ; + } + cJSON_AddItemToObject(jsonObjectDis, "ClearDataConfigFile", jsonArray); + + char *newStr = cJSON_Print(jsonObjectDis); + if (newStr == nullptr) { + HILOGE("cJSON_Print json failed"); + cJSON_Delete(jsonObjectDis); + return ; + } + ofstream outFile(filePath); + if (!outFile.is_open()) { + HILOGE("open json failed"); + cJSON_free(newStr); + cJSON_Delete(jsonObjectDis); + return ; + } + outFile << newStr; + outFile.close(); + cJSON_free(newStr); + cJSON_Delete(jsonObjectDis); + HILOGI("Creat filePath ok :%{public}s", filePath.c_str()); +} + +bool BJsonClearDataConfig::HasClearBundleRecord() +{ + lock_guard autoLock(fileMutex_); + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + ifstream inFile(filePath); + if (!inFile.is_open()) { + HILOGE("open json failed"); + return false; + } + + string jsonString((istreambuf_iterator(inFile)), istreambuf_iterator()); + inFile.close(); + + cJSON *jsonObjectDis = cJSON_Parse(jsonString.c_str()); + if (jsonObjectDis == nullptr) { + HILOGE("parse json failed"); + return false; + } + + cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "ClearDataConfigFile"); + if (configArray == nullptr) { + HILOGE("parse json failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + + int recordSize = cJSON_GetArraySize(configArray); + cJSON_Delete(jsonObjectDis); + return recordSize > 0; +} + +bool BJsonClearDataConfig::FindClearBundleRecord(const string& bundleName) +{ + lock_guard autoLock(fileMutex_); + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + ifstream inFile(filePath); + if (!inFile.is_open()) { + HILOGE("open json failed"); + return false; + } + + string jsonString((istreambuf_iterator(inFile)), istreambuf_iterator()); + inFile.close(); + + cJSON *jsonObjectDis = cJSON_Parse(jsonString.c_str()); + if (jsonObjectDis == nullptr) { + HILOGE("parse json failed"); + return false; + } + + cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "ClearDataConfigFile"); + if (configArray == nullptr) { + HILOGE("parse json failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + bool ifBundlename = false; + for (int i = 0; i < cJSON_GetArraySize(configArray); ++i) { + cJSON *item = cJSON_GetArrayItem(configArray, i); + if (item != nullptr && cJSON_GetObjectItem(item, "bundleName") != nullptr && + cJSON_GetObjectItem(item, "bundleName")->type == cJSON_String && + cJSON_GetObjectItem(item, "bundleName")->valuestring == bundleName) { + ifBundlename = true; + } + } + + cJSON_Delete(jsonObjectDis); + return ifBundlename; +} + +bool BJsonClearDataConfig::InsertClearBundleRecord(const string& bundleName) +{ + lock_guard autoLock(fileMutex_); + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + ifstream inFile(filePath); + if (!inFile.is_open()) { + HILOGE("open json failed"); + return false; + } + + string jsonString((istreambuf_iterator(inFile)), istreambuf_iterator()); + inFile.close(); + + cJSON *jsonObjectDis = cJSON_Parse(jsonString.c_str()); + if (jsonObjectDis == nullptr) { + HILOGE("parse json failed"); + return false; + } + + cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "ClearDataConfigFile"); + if (configArray == nullptr) { + HILOGE("parse json failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + + for (int i = 0; i < cJSON_GetArraySize(configArray); ++i) { + cJSON *item = cJSON_GetArrayItem(configArray, i); + if (item != nullptr && cJSON_GetObjectItem(item, "bundleName") != nullptr && + cJSON_GetObjectItem(item, "bundleName")->type == cJSON_String && + cJSON_GetObjectItem(item, "bundleName")->valuestring == bundleName) { + HILOGI("record already exist, bundleName=%{public}s", bundleName.c_str()); + cJSON_Delete(jsonObjectDis); + return true; + } + } + + if (!WriteClearBundleRecord(bundleName)) { + HILOGE("InsertClearBundleRecord Failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + + HILOGI("InsertClearBundleRecord Ok"); + cJSON_Delete(jsonObjectDis); + return true; +} + +bool BJsonClearDataConfig::DeleteClearBundleRecord(const string& bundleName) +{ + lock_guard autoLock(fileMutex_); + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + ifstream input(filePath); + if (!input.is_open()) { + HILOGE("open json failed"); + return false; + } + + string jsonString((istreambuf_iterator(input)), istreambuf_iterator()); + input.close(); + + cJSON *jsonObjectDis = cJSON_Parse(jsonString.c_str()); + if (jsonObjectDis == nullptr) { + HILOGE("parse json failed"); + return false; + } + + cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "ClearDataConfigFile"); + if (configArray == nullptr) { + cJSON_Delete(jsonObjectDis); + return false; + } + for (int i = 0; i < cJSON_GetArraySize(configArray); ++i) { + cJSON *item = cJSON_GetArrayItem(configArray, i); + if (item != nullptr && cJSON_GetObjectItem(item, "bundleName") != nullptr && + cJSON_GetObjectItem(item, "bundleName")->type == cJSON_String && + cJSON_GetObjectItem(item, "bundleName")->valuestring == bundleName) { + cJSON_DeleteItemFromArray(configArray, i); + break; + } + } + char *newStr = cJSON_Print(jsonObjectDis); + if (newStr == nullptr) { + HILOGE("cJSON_Print json failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + ofstream output(filePath); + if (!output.is_open()) { + HILOGE("open json failed"); + cJSON_free(newStr); + cJSON_Delete(jsonObjectDis); + return false; + } + output << newStr; + output.close(); + + cJSON_free(newStr); + cJSON_Delete(jsonObjectDis); + return true; +} + +vector BJsonClearDataConfig::GetAllClearBundleRecords() +{ + lock_guard autoLock(fileMutex_); + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + vector bundleNameList; + ifstream inFile(filePath); + if (!inFile.is_open()) { + HILOGE("open json failed"); + return {}; + } + string jsonString((istreambuf_iterator(inFile)), istreambuf_iterator()); + inFile.close(); + + cJSON *jsonObjectDis = cJSON_Parse(jsonString.c_str()); + if (jsonObjectDis == nullptr) { + HILOGE("parse json failed"); + return {}; + } + + cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "ClearDataConfigFile"); + if (configArray == nullptr) { + HILOGE("parse json failed"); + cJSON_Delete(jsonObjectDis); + return {}; + } + for (int i = 0; i < cJSON_GetArraySize(configArray); ++i) { + cJSON *item = cJSON_GetArrayItem(configArray, i); + if (item != nullptr && cJSON_GetObjectItem(item, "bundleName") != nullptr && + cJSON_GetObjectItem(item, "bundleName")->type == cJSON_String) { + bundleNameList.push_back(cJSON_GetObjectItem(item, "bundleName")->valuestring); + } + } + cJSON_Delete(jsonObjectDis); + return bundleNameList; +} + +bool BJsonClearDataConfig::DeleteConfigFile() +{ + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + if (access(filePath.c_str(), F_OK) != 0) { + HILOGE("File is not exist"); + return false; + } + if (remove(filePath.c_str()) != 0) { + HILOGE("Delete ClearDataConfigFile failed"); + return false; + } + HILOGI("All Restore Finished, Delete ClearDataConfigFile OK"); + return true; +} + +bool BJsonClearDataConfig::WriteClearBundleRecord(const string& bundleName) +{ + string filePath = PATH_BUNDLE_BACKUP_HOME + CONFIG_NAME; + ifstream inFile(filePath); + if (!inFile.is_open()) { + HILOGE("open json failed"); + return false; + } + string jsonString((istreambuf_iterator(inFile)), istreambuf_iterator()); + inFile.close(); + + cJSON *jsonObjectDis = cJSON_Parse(jsonString.c_str()); + if (jsonObjectDis == nullptr) { + HILOGE("parse json failed"); + return false; + } + + cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "ClearDataConfigFile"); + if (configArray == nullptr) { + HILOGE("parse json failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + cJSON *newItem = cJSON_CreateObject(); + if (configArray == nullptr || newItem == nullptr) { + HILOGE("parse json failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + + cJSON_AddStringToObject(newItem, "bundleName", bundleName.c_str()); + cJSON_AddItemToArray(configArray, newItem); + char *newStr = cJSON_Print(jsonObjectDis); + if (newStr == nullptr) { + HILOGE("cJSON_Print json failed"); + cJSON_Delete(jsonObjectDis); + return false; + } + ofstream outFile(filePath); + if (!outFile.is_open()) { + HILOGE("open json failed"); + cJSON_free(newStr); + cJSON_Delete(jsonObjectDis); + return false; + } + outFile << newStr; + outFile.close(); + + cJSON_free(newStr); + cJSON_Delete(jsonObjectDis); + return true; +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_json/b_json_service_disposal_config.cpp b/utils/src/b_json/b_json_service_disposal_config.cpp index ca94e2112e32f880c6ddf073061c50918a7e043f..5ab1644b87c8f632a170c8a50d665da237ac14f8 100644 --- a/utils/src/b_json/b_json_service_disposal_config.cpp +++ b/utils/src/b_json/b_json_service_disposal_config.cpp @@ -93,13 +93,13 @@ bool BJsonDisposalConfig::AppendIntoDisposalConfigFile(const string& bundleName) } cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "DispoasalConfigFile"); - if (configArray == nullptr) { + if (configArray == nullptr || !cJSON_IsArray(configArray)) { HILOGE("parse json failed"); cJSON_Delete(jsonObjectDis); return false; } cJSON *newItem = cJSON_CreateObject(); - if (configArray == nullptr || newItem == nullptr) { + if (newItem == nullptr) { HILOGE("parse json failed"); cJSON_Delete(jsonObjectDis); return false; @@ -148,7 +148,7 @@ bool BJsonDisposalConfig::DeleteFromDisposalConfigFile(const string& bundleName) } cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "DispoasalConfigFile"); - if (configArray == nullptr) { + if (configArray == nullptr || !cJSON_IsArray(configArray)) { cJSON_Delete(jsonObjectDis); return false; } @@ -202,7 +202,7 @@ bool BJsonDisposalConfig::IfBundleNameInDisposalConfigFile(const string& bundleN } cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "DispoasalConfigFile"); - if (configArray == nullptr) { + if (configArray == nullptr || !cJSON_IsArray(configArray)) { HILOGE("parse json failed"); cJSON_Delete(jsonObjectDis); return false; @@ -246,7 +246,7 @@ vector BJsonDisposalConfig::GetBundleNameFromConfigFile() } cJSON *configArray = cJSON_GetObjectItem(jsonObjectDis, "DispoasalConfigFile"); - if (configArray == nullptr) { + if (configArray == nullptr || !cJSON_IsArray(configArray)) { HILOGE("parse json failed"); cJSON_Delete(jsonObjectDis); return {}; diff --git a/utils/src/b_json/b_report_entity.cpp b/utils/src/b_json/b_report_entity.cpp index 7acdd932a631921c8f1eafb71272caae7d6c5b5b..fb5d342c1838aa648f3d5a8af73e7ffcdc84cf3a 100644 --- a/utils/src/b_json/b_report_entity.cpp +++ b/utils/src/b_json/b_report_entity.cpp @@ -257,7 +257,8 @@ void BReportEntity::CheckAndUpdateIfReportLineEncoded(std::string &path) } unordered_map infos = GetReportInfos(); - if (infos.size() == 1) { + constexpr int BIG_FILE_REPORT_INFO_NUM = 1; + if (infos.size() == BIG_FILE_REPORT_INFO_NUM) { auto info = infos.begin(); path = info->first; } else { diff --git a/utils/src/b_jsonutil/b_jsonutil.cpp b/utils/src/b_jsonutil/b_jsonutil.cpp index 578be2fd88434d25ac0cc544aed426a17ade112f..381caeafa1b307a40da0ca9e759ce3cf6d31da37 100644 --- a/utils/src/b_jsonutil/b_jsonutil.cpp +++ b/utils/src/b_jsonutil/b_jsonutil.cpp @@ -16,10 +16,15 @@ #include "b_jsonutil/b_jsonutil.h" #include +#include +#include +#include #include "cJSON.h" #include "b_error/b_error.h" +#include "b_resources/b_constants.h" #include "filemgmt_libhilog.h" +#include "b_utils/b_time.h" namespace OHOS::FileManagement::Backup { using namespace std; @@ -28,11 +33,10 @@ namespace { const static std::string BUNDLE_INDEX_SPLICE = ":"; } -BJsonUtil::BundleDetailInfo BJsonUtil::ParseBundleNameIndexStr(const std::string &bundleNameStr, - const std::string &patternInfo) +BJsonUtil::BundleDetailInfo BJsonUtil::ParseBundleNameIndexStr(const std::string &bundleNameStr) { HILOGI("Start parse bundle name and index"); - size_t hasPos = bundleNameStr.find(patternInfo); + size_t hasPos = bundleNameStr.find(BUNDLE_INDEX_SPLICE); BundleDetailInfo bundleDetailInfo; if (hasPos == std::string::npos) { bundleDetailInfo.bundleName = bundleNameStr; @@ -40,17 +44,23 @@ BJsonUtil::BundleDetailInfo BJsonUtil::ParseBundleNameIndexStr(const std::string return bundleDetailInfo; } std::string bundleName = bundleNameStr.substr(0, hasPos); - std::string indexStr = bundleNameStr.substr(hasPos + 1); - int index = std::stoi(indexStr); + std::string indexStr = ""; + if (to_string(bundleNameStr.back()) != BUNDLE_INDEX_SPLICE) { + indexStr = bundleNameStr.substr(hasPos + 1); + int index = std::stoi(indexStr); + bundleDetailInfo.bundleIndex = index; + } else { + bundleDetailInfo.bundleIndex = BUNDLE_INDEX_DEFAULT_VAL; + } bundleDetailInfo.bundleName = bundleName; - bundleDetailInfo.bundleIndex = index; HILOGI("End parse bundle name and index"); return bundleDetailInfo; } std::map> BJsonUtil::BuildBundleInfos( const std::vector &bundleNames, const std::vector &bundleInfos, - std::vector &bundleNamesOnly, int32_t userId) + std::vector &bundleNamesOnly, int32_t userId, + std::map &isClearDataFlags) { std::map> bundleNameDetailMap; if (bundleNames.size() != bundleInfos.size()) { @@ -74,64 +84,178 @@ std::map> BJsonUtil::Build bundleNamesOnly.emplace_back(bundleName); } else { std::string bundleNameSplit = bundleName.substr(0, pos); - std::string indexSplit = bundleName.substr(pos, bundleName.size() - 1); - int index = std::stoi(indexSplit); + std::string indexSplit = ""; + if (to_string(bundleName.back()) != BUNDLE_INDEX_SPLICE) { + indexSplit = bundleName.substr(pos + 1); + int index = std::stoi(indexSplit); + bundleIndex = index; + } else { + bundleIndex = BUNDLE_INDEX_DEFAULT_VAL; + } bundleNameOnly = bundleNameSplit; - bundleIndex = index; bundleNamesOnly.emplace_back(bundleNameSplit); } std::string bundleInfo = bundleInfos[i]; - ParseBundleInfoJson(bundleInfo, bundleDetailInfos, bundleNameOnly, bundleIndex, userId); - bundleNameDetailMap[bundleNameOnly] = bundleDetailInfos; + bool isClearData = true; + BJsonUtil::BundleDetailInfo bundleDetailInfo; + bundleDetailInfo.bundleName = bundleNameOnly; + bundleDetailInfo.bundleIndex = bundleIndex; + bundleDetailInfo.userId = userId; + ParseBundleInfoJson(bundleInfo, bundleDetailInfos, bundleDetailInfo, isClearData, userId); + isClearDataFlags[bundleName] = isClearData; + bundleNameDetailMap[bundleName] = bundleDetailInfos; } HILOGI("End BuildBundleInfos"); return bundleNameDetailMap; } -void BJsonUtil::ParseBundleInfoJson(const std::string &bundleInfo, std::vector &bundleDetails, - std::string &bundleNameOnly, int bundleIndex, int32_t userId) +// 传递的bundleinfo不包含unicast字段时 需要拼接unicast字段 +static bool AddUnicastInfo(std::string &bundleInfo) { cJSON *root = cJSON_Parse(bundleInfo.c_str()); if (root == nullptr) { HILOGE("Parse json error,root is null"); - return; + return false; + } + cJSON *info = cJSON_CreateObject(); + if (info == nullptr) { + cJSON_Delete(root); + return false; + } + cJSON_AddStringToObject(info, "type", "unicast"); + cJSON *details = cJSON_CreateArray(); + if (details == nullptr) { + cJSON_Delete(root); + cJSON_Delete(info); + return false; + } + cJSON_AddItemToArray(details, {}); + cJSON_AddItemToObject(info, "details", details); + cJSON *infos = cJSON_GetObjectItem(root, "infos"); + if (infos == nullptr || !cJSON_IsArray(infos)) { + cJSON_Delete(root); + cJSON_Delete(info); + return false; + } + cJSON_AddItemToArray(infos, info); + char *jsonStr = cJSON_Print(root); + if (jsonStr == nullptr) { + cJSON_Delete(root); + return false; + } + bundleInfo = string(jsonStr); + cJSON_Delete(root); + free(jsonStr); + return true; +} + +bool BJsonUtil::HasUnicastInfo(std::string &bundleInfo) +{ + cJSON *root = cJSON_Parse(bundleInfo.c_str()); + if (root == nullptr) { + HILOGE("Parse json error,root is null"); + return false; } cJSON *infos = cJSON_GetObjectItem(root, "infos"); if (infos == nullptr || !cJSON_IsArray(infos) || cJSON_GetArraySize(infos) == 0) { HILOGE("Parse json error, infos is not array"); cJSON_Delete(root); - return; + return false; } int infosCount = cJSON_GetArraySize(infos); for (int i = 0; i < infosCount; i++) { - BJsonUtil::BundleDetailInfo bundleDetailInfo; - bundleDetailInfo.bundleName = bundleNameOnly; - bundleDetailInfo.bundleIndex = bundleIndex; - bundleDetailInfo.userId = userId; cJSON *infoItem = cJSON_GetArrayItem(infos, i); if (!cJSON_IsObject(infoItem)) { HILOGE("Parse json error, info item is not an object"); cJSON_Delete(root); - return; + continue; } cJSON *type = cJSON_GetObjectItem(infoItem, "type"); if (type == nullptr || !cJSON_IsString(type) || (type->valuestring == nullptr)) { HILOGE("Parse json type element error"); cJSON_Delete(root); + continue; + } + if (string(type->valuestring).compare(BConstants::UNICAST_TYPE) == 0) { + cJSON_Delete(root); + return true; + } + } + cJSON_Delete(root); + return false; +} + +static void InsertBundleDetailInfo(cJSON *infos, int infosCount, + std::vector &bundleDetails, + BJsonUtil::BundleDetailInfo bundleDetailInfo, + int32_t userId) +{ + for (int i = 0; i < infosCount; i++) { + cJSON *infoItem = cJSON_GetArrayItem(infos, i); + if (!cJSON_IsObject(infoItem)) { + HILOGE("Parse json error, info item is not an object"); + return; + } + cJSON *type = cJSON_GetObjectItem(infoItem, "type"); + if (type == nullptr || !cJSON_IsString(type) || (type->valuestring == nullptr)) { + HILOGE("Parse json type element error"); return; } bundleDetailInfo.type = type->valuestring; cJSON *details = cJSON_GetObjectItem(infoItem, "details"); if (details == nullptr || !cJSON_IsArray(details)) { HILOGE("Parse json details element error"); - cJSON_Delete(root); return; } + if (bundleDetailInfo.type.compare(BConstants::UNICAST_TYPE) == 0) { + cJSON *detail = cJSON_CreateObject(); + if (detail == nullptr) { + HILOGE("creat json error"); + return; + } + const char *const zeroUserId = static_cast(to_string(userId).c_str()); + cJSON_AddStringToObject(detail, "type", "userId"); + cJSON_AddStringToObject(detail, "detail", zeroUserId); + cJSON_AddItemToArray(details, detail); + } char *detailInfos = cJSON_Print(details); bundleDetailInfo.detail = std::string(detailInfos); bundleDetails.emplace_back(bundleDetailInfo); cJSON_free(detailInfos); } +} + +void BJsonUtil::ParseBundleInfoJson(const std::string &bundleInfo, std::vector &bundleDetails, + BJsonUtil::BundleDetailInfo bundleDetailInfo, bool &isClearData, int32_t userId) +{ + string bundleInfoCopy = move(bundleInfo); + if (!HasUnicastInfo(bundleInfoCopy)) { + if (!AddUnicastInfo(bundleInfoCopy)) { + HILOGE("AddUnicastInfo failed"); + return; + } + } + cJSON *root = cJSON_Parse(bundleInfoCopy.c_str()); + if (root == nullptr) { + HILOGE("Parse json error,root is null"); + return; + } + cJSON *clearBackupData = cJSON_GetObjectItem(root, "clearBackupData"); + if (clearBackupData == nullptr || !cJSON_IsString(clearBackupData) || (clearBackupData->valuestring == nullptr)) { + HILOGE("Parse json 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 *infos = cJSON_GetObjectItem(root, "infos"); + if (infos == nullptr || !cJSON_IsArray(infos) || cJSON_GetArraySize(infos) == 0) { + HILOGE("Parse json error, infos is not array"); + cJSON_Delete(root); + return; + } + int infosCount = cJSON_GetArraySize(infos); + InsertBundleDetailInfo(infos, infosCount, bundleDetails, bundleDetailInfo, userId); cJSON_Delete(root); } @@ -152,7 +276,7 @@ bool BJsonUtil::FindBundleInfoByName(std::map> errFileInfo) +{ + cJSON *errJson = cJSON_CreateObject(); + if (errJson == nullptr) { + HILOGE("Creat json failed"); + return false; + } + cJSON *arrJson = cJSON_CreateArray(); + if (arrJson == nullptr) { + cJSON_Delete(errJson); + return false; + } + for (const auto &it : errFileInfo) { + for (const auto &codeIt : it.second) { + cJSON *eleJson = cJSON_CreateObject(); + if (eleJson == nullptr) { + HILOGE("Creat eleJson failed"); + continue; + } + cJSON_AddStringToObject(eleJson, "type", "ErrorInfo"); + cJSON_AddStringToObject(eleJson, "errorInfo", it.first.c_str()); + cJSON_AddNumberToObject(eleJson, "errorCode", codeIt); + cJSON_AddItemToArray(arrJson, eleJson); + } + } + cJSON_AddItemToObject(errJson, "resultInfo", arrJson); + char *data = cJSON_Print(errJson); + if (data == nullptr) { + cJSON_Delete(errJson); + return false; + } + jsonStr = std::string(data); + cJSON_Delete(errJson); + cJSON_free(data); + return true; +} +} + +bool OHOS::FileManagement::Backup::BJsonUtil::BuildOnProcessRetInfo(std::string &jsonStr, std::string onProcessRet) +{ + cJSON *info = cJSON_CreateObject(); + if (info == nullptr) { + return false; + } + cJSON *processInfo = cJSON_CreateObject(); + if (processInfo == nullptr) { + cJSON_Delete(info); + return false; + } + std::string timeInfo = std::to_string(TimeUtils::GetTimeS()); + cJSON_AddStringToObject(processInfo, "timeInfo", timeInfo.c_str()); + cJSON_AddStringToObject(processInfo, "resultInfo", onProcessRet.c_str()); + cJSON_AddItemToObject(info, "processResult", processInfo); + char *data = cJSON_Print(info); + if (data == nullptr) { + cJSON_Delete(info); + return false; + } + jsonStr = std::string(data); + cJSON_Delete(info); + cJSON_free(data); + return true; +} + +bool OHOS::FileManagement::Backup::BJsonUtil::BuildBundleInfoJson(int32_t userId, string &detailInfo) +{ + cJSON *root = cJSON_CreateObject(); + if (root == nullptr) { + return false; + } + cJSON *infos = cJSON_CreateArray(); + if (infos == nullptr) { + cJSON_Delete(root); + return false; + } + cJSON_AddItemToObject(root, "infos", infos); + cJSON *info = cJSON_CreateObject(); + if (info == nullptr) { + cJSON_Delete(root); + return false; + } + cJSON_AddStringToObject(info, "type", "unicast"); + cJSON_AddItemToArray(infos, info); + cJSON *details = cJSON_CreateArray(); + if (details == nullptr) { + cJSON_Delete(root); + return false; + } + cJSON_AddItemToObject(info, "details", details); + cJSON *detail = cJSON_CreateObject(); + if (detail == nullptr) { + cJSON_Delete(root); + return false; + } + const char *const zeroUserId = static_cast(to_string(userId).c_str()); + cJSON_AddStringToObject(detail, "type", "userId"); + cJSON_AddStringToObject(detail, "detail", zeroUserId); + cJSON_AddItemToArray(details, detail); + char *jsonStr = cJSON_Print(root); + if (jsonStr == nullptr) { + cJSON_Delete(root); + return false; + } + detailInfo = string(jsonStr); + cJSON_Delete(root); + free(jsonStr); + return true; +} diff --git a/utils/src/b_ohos/startup/backup_para.cpp b/utils/src/b_ohos/startup/backup_para.cpp index c5f9c1d9dc4fa4c3a5681681e837b769aebab22b..46754c5dcd3da1741ca2c0b562dbd7cf900e3413 100644 --- a/utils/src/b_ohos/startup/backup_para.cpp +++ b/utils/src/b_ohos/startup/backup_para.cpp @@ -38,7 +38,6 @@ using namespace std; static tuple GetConfigParameterValue(const string &key, uint32_t len) { int handle = static_cast(FindParameter(key.c_str())); - HILOGI("start get config param value."); if (handle == -1) { HILOGI("Fail to find parameter."); return {false, ""}; @@ -50,7 +49,6 @@ static tuple GetConfigParameterValue(const string &key, uint32_t l HILOGI("Fail to get parameter value."); return {false, ""}; } - HILOGI("end get config param value."); return {true, buffer.get()}; } catch (const bad_alloc &e) { HILOGE("Fail to get parameter value: %{public}s.", e.what()); diff --git a/utils/src/b_radar/b_radar.cpp b/utils/src/b_radar/b_radar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..31ef80f3df37c713bea1937c7d336221d33aa92a --- /dev/null +++ b/utils/src/b_radar/b_radar.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "b_process/b_multiuser.h" +#include "b_radar/b_radar.h" +#include "b_resources/b_constants.h" +#include "b_utils/b_time.h" +#include "hisysevent.h" +#include "i_service_reverse.h" + +namespace OHOS::FileManagement::Backup { +int32_t AppRadar::GetUserId() +{ + auto multiuser = BMultiuser::ParseUid(getuid()); + if ((multiuser.userId == BConstants::SYSTEM_UID) || (multiuser.userId == BConstants::XTS_UID)) { + return BConstants::DEFAULT_USER_ID; + } + return multiuser.userId; +} + +void AppRadar::RecordDefaultFuncRes(Info &info, const std::string &func, int32_t userId, + enum BizStageBackup bizStage, int32_t resultCode) +{ + std::stringstream ss; + ss << "{\"result_info\": {" << info.resInfo << "}}"; + HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::FILEMANAGEMENT, + BConstants::FILE_BACKUP_RESTORE_EVENTS, + OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "BUNDLE_NAME", info.bundleName, + "USER_ID", userId, + "PID", getpid(), + "FUNC", func, + "TIME", TimeUtils::GetCurrentTime(), + "BIZ_SCENE", static_cast(IServiceReverse::Scenario::UNDEFINED), + "BIZ_STAGE", static_cast(bizStage), + "EXEC_STATUS", info.status, + "RESULT_CODE", resultCode, + "RESULT_INFO", ss.str()); +} + +void AppRadar::RecordBackupFuncRes(Info &info, const std::string &func, int32_t userId, + enum BizStageBackup bizStage, int32_t resultCode) +{ + std::stringstream ss; + ss << "{\"result_info\": {" << info.resInfo << "}}"; + HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::FILEMANAGEMENT, + BConstants::FILE_BACKUP_RESTORE_EVENTS, + OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "BUNDLE_NAME", info.bundleName, + "USER_ID", userId, + "PID", getpid(), + "FUNC", func, + "TIME", TimeUtils::GetCurrentTime(), + "BIZ_SCENE", static_cast(IServiceReverse::Scenario::BACKUP), + "BIZ_STAGE", static_cast(bizStage), + "EXEC_STATUS", info.status, + "RESULT_CODE", resultCode, + "RESULT_INFO", ss.str()); +} + +void AppRadar::RecordRestoreFuncRes(Info &info, const std::string &func, int32_t userId, + enum BizStageRestore bizStage, int32_t resultCode) +{ + std::stringstream ss; + ss << "{\"result_info\": {" << info.resInfo << "}}"; + HiSysEventWrite( + OHOS::HiviewDFX::HiSysEvent::Domain::FILEMANAGEMENT, + BConstants::FILE_BACKUP_RESTORE_EVENTS, + OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR, + "BUNDLE_NAME", info.bundleName, + "USER_ID", userId, + "PID", getpid(), + "FUNC", func, + "TIME", TimeUtils::GetCurrentTime(), + "BIZ_SCENE", static_cast(IServiceReverse::Scenario::RESTORE), + "BIZ_STAGE", static_cast(bizStage), + "EXEC_STATUS", info.status, + "RESULT_CODE", resultCode, + "RESULT_INFO", ss.str()); +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/utils/src/b_sa/b_sa_utils.cpp b/utils/src/b_sa/b_sa_utils.cpp index 05d090e81c1edb26c4ab53827ecf582ef9ebdc71..399cb10269a26f1a124ea9d4957ea154737e1b20 100644 --- a/utils/src/b_sa/b_sa_utils.cpp +++ b/utils/src/b_sa/b_sa_utils.cpp @@ -14,9 +14,17 @@ */ #include "b_sa/b_sa_utils.h" +#include "access_token.h" +#include "accesstoken_kit.h" +#include "ipc_skeleton.h" +#include "tokenid_kit.h" namespace OHOS::FileManagement::Backup { +namespace { + const std::string BACKUP_PERMISSION = "ohos.permission.BACKUP"; +} + bool SAUtils::IsSABundleName(std::string bundleName) { if (bundleName.empty()) { @@ -29,4 +37,24 @@ bool SAUtils::IsSABundleName(std::string bundleName) } return true; } + +bool SAUtils::CheckBackupPermission() +{ + Security::AccessToken::AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + return Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, BACKUP_PERMISSION) == + Security::AccessToken::PermissionState::PERMISSION_GRANTED; +} + +bool SAUtils::CheckPermission(const std::string &permission) +{ + Security::AccessToken::AccessTokenID tokenCaller = IPCSkeleton::GetCallingTokenID(); + return Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenCaller, permission) == + Security::AccessToken::PermissionState::PERMISSION_GRANTED; +} + +bool SAUtils::IsSystemApp() +{ + uint64_t fullTokenId = OHOS::IPCSkeleton::GetCallingFullTokenID(); + return Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId); +} } // 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 new file mode 100644 index 0000000000000000000000000000000000000000..e6f49f7ced521c92252671b406e5126bf05df7e8 --- /dev/null +++ b/utils/src/b_utils/b_time.cpp @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "b_resources/b_constants.h" +#include "b_utils/b_time.h" +#include +#include +#include +#include + +namespace OHOS::FileManagement::Backup { +int64_t TimeUtils::GetTimeS() +{ + std::chrono::seconds nowS = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()); + return nowS.count(); +} + +int64_t TimeUtils::GetTimeMS() +{ + std::chrono::milliseconds nowMs = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()); + return nowMs.count(); +} + +int64_t TimeUtils::GetTimeUS() +{ + std::chrono::microseconds nowUs = std::chrono::duration_cast( + std::chrono::system_clock::now().time_since_epoch()); + return nowUs.count(); +} + +std::string TimeUtils::GetCurrentTime() +{ + auto now = std::chrono::system_clock::now(); + auto time = std::chrono::system_clock::to_time_t(now); + auto ms = std::chrono::duration_cast(now.time_since_epoch()); + std::stringstream strTime; + strTime << (std::put_time(std::localtime(&time), "%Y-%m-%d %H:%M:%S:")) << (std::setfill('0')) + << (std::setw(BConstants::INDEX)) << (ms.count() % BConstants::MS_1000); + return strTime.str(); +} +} // namespace OHOS::FileManagement::Backup \ No newline at end of file