From 9f810a684f365d66957f07f17b49253d026bbe72 Mon Sep 17 00:00:00 2001 From: huaqingsimeng <1004904143@qq.com> Date: Wed, 29 Mar 2023 08:43:08 +0000 Subject: [PATCH] =?UTF-8?q?=E5=A4=87=E4=BB=BD=E6=81=A2=E5=A4=8D=E6=8F=90?= =?UTF-8?q?=E4=BE=9Bjs=E6=8E=A5=E5=8F=A3=E8=83=BD=E5=8A=9B-=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E7=AB=AF=E9=80=BB=E8=BE=91=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huaqingsimeng --- bundle.json | 3 +- .../backup_kit_inner/src/b_session_backup.cpp | 6 +- .../src/b_session_restore.cpp | 18 +- .../backup_kit_inner/src/service_proxy.cpp | 21 +-- .../backup_kit_inner/impl/b_session_backup.h | 7 +- .../backup_kit_inner/impl/b_session_restore.h | 14 +- .../native/backup_kit_inner/impl/i_service.h | 10 +- .../backup_kit_inner/impl/service_proxy.h | 8 +- services/backup_sa/BUILD.gn | 3 + .../backup_sa/include/module_ipc/service.h | 21 ++- .../include/module_ipc/service_stub.h | 2 +- .../include/module_ipc/svc_session_manager.h | 46 +++-- services/backup_sa/src/module_ipc/service.cpp | 106 ++++++----- .../backup_sa/src/module_ipc/service_stub.cpp | 25 +-- .../src/module_ipc/svc_session_manager.cpp | 166 +++++++++--------- tools/backup_tool/src/tools_op_backup.cpp | 37 ++-- tools/backup_tool/src/tools_op_restore.cpp | 68 ++++--- utils/include/b_json/b_json_entity_caps.h | 10 ++ utils/include/b_resources/b_constants.h | 1 + 19 files changed, 266 insertions(+), 306 deletions(-) diff --git a/bundle.json b/bundle.json index fc02fdb76..92a968337 100644 --- a/bundle.json +++ b/bundle.json @@ -74,8 +74,7 @@ ], "test": [ "//foundation/filemanagement/app_file_service/test/fuzztest:fuzztest", - "//foundation/filemanagement/app_file_service/test/unittest:unittest", - "//foundation/filemanagement/app_file_service:tgt_backup_tests" + "//foundation/filemanagement/app_file_service/test/unittest:unittest" ] } } 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 976336618..a798cd391 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_backup.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_backup.cpp @@ -40,9 +40,7 @@ BSessionBackup::~BSessionBackup() deathRecipient_ = nullptr; } -unique_ptr BSessionBackup::Init(UniqueFd remoteCap, - vector bundlesToBackup, - Callbacks callbacks) +unique_ptr BSessionBackup::Init(Callbacks callbacks) { try { auto backup = make_unique(); @@ -52,7 +50,7 @@ unique_ptr BSessionBackup::Init(UniqueFd remoteCap, return nullptr; } - int32_t res = proxy->InitBackupSession(sptr(new ServiceReverse(callbacks)), move(remoteCap), bundlesToBackup); + int32_t res = proxy->InitBackupSession(sptr(new ServiceReverse(callbacks))); if (res != 0) { HILOGE("Failed to Backup because of %{public}d", res); return nullptr; 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 6fc1db385..f640d7abf 100644 --- a/frameworks/native/backup_kit_inner/src/b_session_restore.cpp +++ b/frameworks/native/backup_kit_inner/src/b_session_restore.cpp @@ -40,7 +40,7 @@ BSessionRestore::~BSessionRestore() deathRecipient_ = nullptr; } -unique_ptr BSessionRestore::Init(std::vector bundlesToRestore, Callbacks callbacks) +unique_ptr BSessionRestore::Init(Callbacks callbacks) { try { auto restore = make_unique(); @@ -49,7 +49,7 @@ unique_ptr BSessionRestore::Init(std::vector bundle HILOGI("Failed to get backup service"); return nullptr; } - int32_t res = proxy->InitRestoreSession(new ServiceReverse(callbacks), bundlesToRestore); + int32_t res = proxy->InitRestoreSession(new ServiceReverse(callbacks)); if (res != 0) { HILOGE("Failed to Restore because of %{public}d", res); return nullptr; @@ -63,16 +63,6 @@ unique_ptr BSessionRestore::Init(std::vector bundle return nullptr; } -UniqueFd BSessionRestore::GetLocalCapabilities() -{ - auto proxy = ServiceProxy::GetInstance(); - if (proxy == nullptr) { - HILOGI("Failed to get backup service"); - return UniqueFd(-1); - } - return UniqueFd(proxy->GetLocalCapabilities()); -} - ErrCode BSessionRestore::PublishFile(BFileInfo fileInfo) { auto proxy = ServiceProxy::GetInstance(); @@ -92,14 +82,14 @@ ErrCode BSessionRestore::Start() return proxy->Start(); } -ErrCode BSessionRestore::GetExtFileName(string &bundleName, string &fileName) +ErrCode BSessionRestore::GetFileHandle(const string &bundleName, const string &fileName) { auto proxy = ServiceProxy::GetInstance(); if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to get backup service").GetCode(); } - return proxy->GetExtFileName(bundleName, fileName); + return proxy->GetFileHandle(bundleName, fileName); } ErrCode BSessionRestore::AppendBundles(UniqueFd remoteCap, vector bundlesToRestore) diff --git a/frameworks/native/backup_kit_inner/src/service_proxy.cpp b/frameworks/native/backup_kit_inner/src/service_proxy.cpp index e35abfd43..e6b2dc95c 100644 --- a/frameworks/native/backup_kit_inner/src/service_proxy.cpp +++ b/frameworks/native/backup_kit_inner/src/service_proxy.cpp @@ -26,7 +26,7 @@ namespace OHOS::FileManagement::Backup { using namespace std; using namespace BExcepUltils; -int32_t ServiceProxy::InitRestoreSession(sptr remote, const std::vector &bundleNames) +ErrCode ServiceProxy::InitRestoreSession(sptr remote) { HILOGI("Begin"); BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); @@ -44,10 +44,6 @@ int32_t ServiceProxy::InitRestoreSession(sptr remote, const std return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the reverse stub").GetCode(); } - if (!data.WriteStringVector(bundleNames)) { - return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send bundleNames").GetCode(); - } - int32_t ret = Remote()->SendRequest(IService::SERVICE_CMD_INIT_RESTORE_SESSION, data, reply, option); if (ret != NO_ERROR) { string str = "Failed to send out the request because of " + to_string(ret); @@ -56,9 +52,7 @@ int32_t ServiceProxy::InitRestoreSession(sptr remote, const std return reply.ReadInt32(); } -int32_t ServiceProxy::InitBackupSession(sptr remote, - UniqueFd fd, - const std::vector &bundleNames) +ErrCode ServiceProxy::InitBackupSession(sptr remote) { HILOGI("Begin"); BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); @@ -76,13 +70,6 @@ int32_t ServiceProxy::InitBackupSession(sptr remote, return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the reverse stub").GetCode(); } - if (!data.WriteFileDescriptor(fd)) { - return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send the fd").GetCode(); - } - if (!data.WriteStringVector(bundleNames)) { - return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send bundleNames").GetCode(); - } - int32_t ret = Remote()->SendRequest(IService::SERVICE_CMD_INIT_BACKUP_SESSION, data, reply, option); if (ret != NO_ERROR) { string str = "Failed to send out the request because of " + to_string(ret); @@ -204,7 +191,7 @@ ErrCode ServiceProxy::AppDone(ErrCode errCode) return reply.ReadInt32(); } -ErrCode ServiceProxy::GetExtFileName(string &bundleName, string &fileName) +ErrCode ServiceProxy::GetFileHandle(const string &bundleName, const string &fileName) { HILOGI("Begin"); BAssert(Remote(), BError::Codes::SDK_INVAL_ARG, "Remote is nullptr"); @@ -223,7 +210,7 @@ ErrCode ServiceProxy::GetExtFileName(string &bundleName, string &fileName) MessageParcel reply; MessageOption option; option.SetFlags(MessageOption::TF_ASYNC); - int32_t ret = Remote()->SendRequest(IService::SERVICE_CMD_GET_EXT_FILE_NAME, data, reply, option); + int32_t ret = Remote()->SendRequest(IService::SERVICE_CMD_GET_FILE_NAME, 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(); 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 7ab3e2519..059e3b798 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 @@ -40,13 +40,10 @@ public: /** * @brief 获取一个用于控制备份流程的会话 * - * @param remoteCap 已打开的保存远端设备能力的Json文件。可使用BRestoreSession的GetLocalCapabilities方法获取 - * @param bundlesToBackup 待备份应用清单 + * @param callbacks 注册回调 * @return std::unique_ptr 指向会话的智能指针。失败时为空指针 */ - static std::unique_ptr Init(UniqueFd remoteCap, - std::vector bundlesToBackup, - Callbacks callbacks); + static std::unique_ptr Init(Callbacks callbacks); /** * @brief 用于追加应用,现阶段仅支持在Start之前调用 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 308084eae..4654a7bc5 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 @@ -40,25 +40,17 @@ public: /** * @brief 获取一个用于控制恢复流程的会话 * - * @param bundlesToRestore 待恢复应用清单 * @param callbacks 注册的回调函数 * @return std::unique_ptr 指向BRestoreSession的智能指针。失败时为空指针 */ - static std::unique_ptr Init(std::vector bundlesToRestore, Callbacks callbacks); - - /** - * @brief 获取用于描述本端能力的Json文件 - * - * @return UniqueFd 文件描述符 - */ - UniqueFd GetLocalCapabilities(); + static std::unique_ptr Init(Callbacks callbacks); /** * @brief 通知备份服务文件内容已就绪 * * @param fileInfo 文件描述信息 * @return ErrCode 规范错误码 - * @see GetExtFileName + * @see GetFileHandle */ ErrCode PublishFile(BFileInfo fileInfo); @@ -68,7 +60,7 @@ public: * @param bundleName 应用名称 * @param fileName 文件名称 */ - ErrCode GetExtFileName(std::string &bundleName, std::string &fileName); + ErrCode GetFileHandle(const std::string &bundleName, const std::string &fileName); /** * @brief 用于追加应用,现阶段仅支持在Start之前调用 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 3dbe01b78..3e8af262c 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 @@ -36,22 +36,20 @@ public: SERVICE_CMD_APP_FILE_READY, SERVICE_CMD_APP_DONE, SERVICE_CMD_START, - SERVICE_CMD_GET_EXT_FILE_NAME, + SERVICE_CMD_GET_FILE_NAME, SERVICE_CMD_APPEND_BUNDLES_RESTORE_SESSION, SERVICE_CMD_APPEND_BUNDLES_BACKUP_SESSION, SERVICE_CMD_FINISH, }; - virtual ErrCode InitRestoreSession(sptr remote, const std::vector &bundleNames) = 0; - virtual ErrCode InitBackupSession(sptr remote, - UniqueFd fd, - const std::vector &bundleNames) = 0; + virtual ErrCode InitRestoreSession(sptr remote) = 0; + virtual ErrCode InitBackupSession(sptr remote) = 0; virtual ErrCode Start() = 0; virtual UniqueFd GetLocalCapabilities() = 0; virtual ErrCode PublishFile(const BFileInfo &fileInfo) = 0; virtual ErrCode AppFileReady(const std::string &fileName, UniqueFd fd) = 0; virtual ErrCode AppDone(ErrCode errCode) = 0; - virtual ErrCode GetExtFileName(std::string &bundleName, std::string &fileName) = 0; + virtual ErrCode GetFileHandle(const std::string &bundleName, const std::string &fileName) = 0; virtual ErrCode AppendBundlesRestoreSession(UniqueFd fd, const std::vector &bundleNames) = 0; virtual ErrCode AppendBundlesBackupSession(const std::vector &bundleNames) = 0; virtual ErrCode Finish() = 0; 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 18ef4a0f3..8033b7f10 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 @@ -28,16 +28,14 @@ namespace OHOS::FileManagement::Backup { class ServiceProxy : public IRemoteProxy { public: - ErrCode InitRestoreSession(sptr remote, const std::vector &bundleNames) override; - ErrCode InitBackupSession(sptr remote, - UniqueFd fd, - const std::vector &bundleNames) override; + ErrCode InitRestoreSession(sptr remote) override; + ErrCode InitBackupSession(sptr remote) override; ErrCode Start() override; UniqueFd GetLocalCapabilities() override; ErrCode PublishFile(const BFileInfo &fileInfo) override; ErrCode AppFileReady(const std::string &fileName, UniqueFd fd) override; ErrCode AppDone(ErrCode errCode) override; - ErrCode GetExtFileName(std::string &bundleName, std::string &fileName) override; + ErrCode GetFileHandle(const std::string &bundleName, const std::string &fileName) override; ErrCode AppendBundlesRestoreSession(UniqueFd fd, const std::vector &bundleNames) override; ErrCode AppendBundlesBackupSession(const std::vector &bundleNames) override; ErrCode Finish() override; diff --git a/services/backup_sa/BUILD.gn b/services/backup_sa/BUILD.gn index d71e26ba0..317fc0770 100644 --- a/services/backup_sa/BUILD.gn +++ b/services/backup_sa/BUILD.gn @@ -16,6 +16,8 @@ import("//foundation/filemanagement/app_file_service/backup.gni") ohos_shared_library("backup_sa") { sources = [ + "src/module_external/bms_adapter.cpp", + "src/module_external/sms_adapter.cpp", "src/module_ipc/service.cpp", "src/module_ipc/service_reverse_proxy.cpp", "src/module_ipc/service_stub.cpp", @@ -45,6 +47,7 @@ ohos_shared_library("backup_sa") { "ipc:ipc_core", "safwk:system_ability_fwk", "samgr:samgr_proxy", + "storage_service:storage_manager_sa_proxy", ] use_exceptions = true diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index 5b771775c..7bb1dd330 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -32,16 +32,14 @@ class Service : public SystemAbility, public ServiceStub, protected NoCopyable { // 以下都是IPC接口 public: - ErrCode InitRestoreSession(sptr remote, const std::vector &bundleNames) override; - ErrCode InitBackupSession(sptr remote, - UniqueFd fd, - const std::vector &bundleNames) override; + ErrCode InitRestoreSession(sptr remote) override; + ErrCode InitBackupSession(sptr remote) override; ErrCode Start() override; UniqueFd GetLocalCapabilities() override; ErrCode PublishFile(const BFileInfo &fileInfo) override; ErrCode AppFileReady(const std::string &fileName, UniqueFd fd) override; ErrCode AppDone(ErrCode errCode) override; - ErrCode GetExtFileName(std::string &bundleName, std::string &fileName) override; + ErrCode GetFileHandle(const std::string &bundleName, const std::string &fileName) override; ErrCode AppendBundlesRestoreSession(UniqueFd fd, const std::vector &bundleNames) override; ErrCode AppendBundlesBackupSession(const std::vector &bundleNames) override; ErrCode Finish() override; @@ -124,6 +122,19 @@ private: */ void ClearSessionAndSchedInfo(const std::string &bundleName); + /** + * @brief 整个备份恢复流程结束 + * + * @param errCode 错误码 + */ + void OnAllBundlesFinished(ErrCode errCode); + + /** + * @brief 执行调度器 + * + */ + void OnStartSched(); + private: static sptr instance_; static std::mutex instanceLock_; diff --git a/services/backup_sa/include/module_ipc/service_stub.h b/services/backup_sa/include/module_ipc/service_stub.h index fb0fc4eb8..1049e1574 100644 --- a/services/backup_sa/include/module_ipc/service_stub.h +++ b/services/backup_sa/include/module_ipc/service_stub.h @@ -41,7 +41,7 @@ private: int32_t CmdPublishFile(MessageParcel &data, MessageParcel &reply); int32_t CmdAppFileReady(MessageParcel &data, MessageParcel &reply); int32_t CmdAppDone(MessageParcel &data, MessageParcel &reply); - int32_t CmdGetExtFileName(MessageParcel &data, MessageParcel &reply); + int32_t CmdGetFileHandle(MessageParcel &data, MessageParcel &reply); int32_t CmdAppendBundlesRestoreSession(MessageParcel &data, MessageParcel &reply); int32_t CmdAppendBundlesBackupSession(MessageParcel &data, MessageParcel &reply); int32_t CmdFinish(MessageParcel &data, MessageParcel &reply); 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 0ec0f863c..6d228aa31 100644 --- a/services/backup_sa/include/module_ipc/svc_session_manager.h +++ b/services/backup_sa/include/module_ipc/svc_session_manager.h @@ -31,7 +31,6 @@ #include "b_file_info.h" #include "b_resources/b_constants.h" -#include "bundlemgr/bundle_mgr_interface.h" #include "i_service_reverse.h" #include "module_ipc/svc_backup_connection.h" #include "svc_death_recipient.h" @@ -40,6 +39,7 @@ namespace OHOS::FileManagement::Backup { struct BackupExtInfo { bool receExtManageJson {false}; bool receExtAppDone {false}; + bool isBundleFinished {false}; std::string backupExtName; sptr backUpConnection; std::set fileNameInfo; @@ -54,6 +54,7 @@ public: IServiceReverse::Scenario scenario {IServiceReverse::Scenario::UNDEFINED}; std::map backupExtNameMap; sptr clientProxy; + bool isBackupStart {false}; bool isAppendFinish {false}; }; @@ -199,6 +200,20 @@ public: */ std::string GetBackupExtName(const std::string &bundleName); + /** + * @brief 追加应用 + * + * @param bundleNames 应用名称 + */ + void AppendBundles(const std::vector &bundleNames); + + /** + * @brief 开始备份 + * + * @return ErrCode + */ + void Start(); + /** * @brief 结束追加应用 * @@ -206,29 +221,36 @@ public: */ void Finish(); -private: /** - * @brief 校验BundleName和ability type 并补全Impl.backupExtNameMap信息 + * @brief 整个备份恢复流程是否结束 + * + * @return true 备份恢复流程结束 + * @return false 备份恢复流程未结束 + */ + bool IsOnAllBundlesFinished(); + + /** + * @brief 是否启动调度器 * - * @param backupExtNameMap 客户端信息 - * @throw BError::Codes::SA_INVAL_ARG 客户端信息异常 - * @throw BError::Codes::SA_BROKEN_IPC + * @return true 启动调度器 + * @return false 不启动调度器 */ - virtual void GetBundleExtNames(std::map &backupExtNameMap); + bool IsOnOnStartSched(); +private: /** - * @brief 初始化 extension backUpConnection + * @brief 获取backup extension ability * - * @param backupExtNameMap + * @param bundleName 应用名称 */ - virtual void InitExtConn(std::map &backupExtNameMap); + sptr GetBackupExtAbility(const std::string &bundleName); /** * @brief 初始化 clientProxy * * @param newImpl */ - virtual void InitClient(Impl &newImpl); + void InitClient(Impl &newImpl); /** * @brief 获取BackupExtNameMap iterator @@ -248,8 +270,6 @@ public: ~SvcSessionManager() override = default; private: - sptr GetBundleManager(); - mutable std::shared_mutex lock_; wptr reversePtr_; sptr deathRecipient_; diff --git a/services/backup_sa/src/module_ipc/service.cpp b/services/backup_sa/src/module_ipc/service.cpp index 9ebc17913..2060897ca 100644 --- a/services/backup_sa/src/module_ipc/service.cpp +++ b/services/backup_sa/src/module_ipc/service.cpp @@ -42,11 +42,11 @@ #include "b_json/b_json_cached_entity.h" #include "b_json/b_json_entity_caps.h" #include "b_process/b_multiuser.h" -#include "b_process/b_process.h" #include "b_resources/b_constants.h" #include "bundle_mgr_client.h" #include "filemgmt_libhilog.h" #include "ipc_skeleton.h" +#include "module_external/bms_adapter.h" #include "module_ipc/svc_backup_connection.h" #include "parameter.h" #include "system_ability_definition.h" @@ -83,8 +83,6 @@ UniqueFd Service::GetLocalCapabilities() BJsonCachedEntity cachedEntity( UniqueFd(open(BConstants::SA_BUNDLE_BACKUP_ROOT_DIR.data(), O_TMPFILE | O_RDWR, 0600))); auto cache = cachedEntity.Structuralize(); - cache.SetFreeDiskSpace(fsInfo.f_bfree); - cache.SetOSFullName(GetOSFullName()); cache.SetDeviceType(GetDeviceType()); cachedEntity.Persist(); @@ -134,7 +132,7 @@ void Service::VerifyCaller() switch (tokenType) { case Security::AccessToken::ATokenTypeEnum::TOKEN_HAP: { auto multiuser = BMultiuser::ParseUid(IPCSkeleton::GetCallingUid()); - if (multiuser.userId != BConstants::DEFAULT_USER_ID) { + if ((multiuser.userId != BConstants::DEFAULT_USER_ID) && (multiuser.userId != BConstants::XTS_UID)) { throw BError(BError::Codes::SA_INVAL_ARG, string("Calling user is ") .append(to_string(multiuser.userId)) .append(", which is currently not supported")); @@ -164,21 +162,13 @@ void Service::VerifyCaller(IServiceReverse::Scenario scenario) VerifyCaller(); } -ErrCode Service::InitRestoreSession(sptr remote, const vector &bundleNames) +ErrCode Service::InitRestoreSession(sptr remote) { try { VerifyCaller(); - map backupExtNameMap; - auto setBackupExtNameMap = [](const BundleName &bundleName) { - BackupExtInfo info {}; - return make_pair(bundleName, info); - }; - transform(bundleNames.begin(), bundleNames.end(), inserter(backupExtNameMap, backupExtNameMap.end()), - setBackupExtNameMap); session_->Active({ .clientToken = IPCSkeleton::GetCallingTokenID(), .scenario = IServiceReverse::Scenario::RESTORE, - .backupExtNameMap = move(backupExtNameMap), .clientProxy = remote, }); return BError(BError::Codes::OK); @@ -194,30 +184,15 @@ ErrCode Service::InitRestoreSession(sptr remote, const vector remote, UniqueFd fd, const vector &bundleNames) +ErrCode Service::InitBackupSession(sptr remote) { try { VerifyCaller(); - map backupExtNameMap; - auto setBackupExtNameMap = [](const BundleName &bundleName) { - BackupExtInfo info {}; - return make_pair(bundleName, info); - }; - transform(bundleNames.begin(), bundleNames.end(), inserter(backupExtNameMap, backupExtNameMap.end()), - setBackupExtNameMap); session_->Active({ .clientToken = IPCSkeleton::GetCallingTokenID(), .scenario = IServiceReverse::Scenario::BACKUP, - .backupExtNameMap = move(backupExtNameMap), .clientProxy = remote, }); - - BJsonCachedEntity cachedEntity(move(fd)); - auto cache = cachedEntity.Structuralize(); - uint64_t size = cache.GetFreeDiskSpace(); - if (size == 0) { - throw BError(BError::Codes::SA_INVAL_ARG, "Invalid field FreeDiskSpace or unsufficient space"); - } return BError(BError::Codes::OK); } catch (const BError &e) { StopAll(nullptr, true); @@ -227,34 +202,21 @@ ErrCode Service::InitBackupSession(sptr remote, UniqueFd fd, co ErrCode Service::Start() { - try { - HILOGI("Begin"); - VerifyCaller(session_->GetScenario()); - for (int num = 0; num < BConstants::EXT_CONNECT_MAX_COUNT; num++) { - sched_->Sched(); - } - 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; - } catch (...) { - HILOGI("Unexpected exception"); - return EPERM; - } + HILOGI("Begin"); + VerifyCaller(session_->GetScenario()); + session_->Start(); + OnStartSched(); + return BError(BError::Codes::OK); } ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const vector &bundleNames) { HILOGI("Begin"); VerifyCaller(session_->GetScenario()); - BJsonCachedEntity cachedEntity(move(fd)); - auto cache = cachedEntity.Structuralize(); - uint64_t size = cache.GetFreeDiskSpace(); - if (size == 0) { - throw BError(BError::Codes::SA_INVAL_ARG, "Invalid field FreeDiskSpace or unsufficient space"); - } + session_->AppendBundles(bundleNames); + Start(); + Finish(); + OnStartSched(); return BError(BError::Codes::OK); } @@ -262,6 +224,10 @@ ErrCode Service::AppendBundlesBackupSession(const vector &bundleName { HILOGI("Begin"); VerifyCaller(session_->GetScenario()); + session_->AppendBundles(bundleNames); + Start(); + Finish(); + OnStartSched(); return BError(BError::Codes::OK); } @@ -270,6 +236,7 @@ ErrCode Service::Finish() HILOGI("Begin"); VerifyCaller(session_->GetScenario()); session_->Finish(); + OnAllBundlesFinished(BError(BError::Codes::OK)); return BError(BError::Codes::OK); } @@ -294,7 +261,7 @@ ErrCode Service::PublishFile(const BFileInfo &fileInfo) HILOGE("Failed to publish file for backup extension"); } - return BError(BError::Codes::OK); + return res; } catch (const BError &e) { return e.GetCode(); } catch (const exception &e) { @@ -334,6 +301,7 @@ ErrCode Service::AppFileReady(const string &fileName, UniqueFd fd) backUpConnection->DisconnectBackupExtAbility(); ClearSessionAndSchedInfo(callerName); } + OnAllBundlesFinished(BError(BError::Codes::OK)); return BError(BError::Codes::OK); } catch (const BError &e) { return e.GetCode(); // 任意异常产生,终止监听该任务 @@ -367,6 +335,7 @@ ErrCode Service::AppDone(ErrCode errCode) backUpConnection->DisconnectBackupExtAbility(); ClearSessionAndSchedInfo(callerName); } + OnAllBundlesFinished(BError(BError::Codes::OK)); return BError(BError::Codes::OK); } catch (const BError &e) { return e.GetCode(); // 任意异常产生,终止监听该任务 @@ -412,15 +381,17 @@ ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) } } -ErrCode Service::GetExtFileName(string &bundleName, string &fileName) +ErrCode Service::GetFileHandle(const string &bundleName, const string &fileName) { try { - HILOGE("begin"); + HILOGI("Begin"); VerifyCaller(IServiceReverse::Scenario::RESTORE); - if (!regex_match(fileName, regex("^[0-9a-zA-Z_.]+$"))) { - throw BError(BError::Codes::SA_INVAL_ARG, "Filename is not alphanumeric"); - } session_->SetExtFileNameRequest(bundleName, fileName); + auto action = session_->GetServiceSchedAction(bundleName); + if (action == BConstants::ServiceSchedAction::RUNNING) { + sched_->Sched(bundleName); + return BError(BError::Codes::OK); + } return BError(BError::Codes::OK); } catch (const BError &e) { return e.GetCode(); @@ -572,4 +543,25 @@ void Service::ClearSessionAndSchedInfo(const string &bundleName) return; } } + +void Service::OnAllBundlesFinished(ErrCode errCode) +{ + if (session_->IsOnAllBundlesFinished()) { + IServiceReverse::Scenario scenario = session_->GetScenario(); + if (scenario == IServiceReverse::Scenario::BACKUP) { + session_->GetServiceReverseProxy()->BackupOnAllBundlesFinished(errCode); + } else if (scenario == IServiceReverse::Scenario::RESTORE) { + session_->GetServiceReverseProxy()->RestoreOnAllBundlesFinished(errCode); + } + } +} + +void Service::OnStartSched() +{ + if (session_->IsOnOnStartSched()) { + for (int num = 0; num < BConstants::EXT_CONNECT_MAX_COUNT; num++) { + sched_->Sched(); + } + } +} } // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_ipc/service_stub.cpp b/services/backup_sa/src/module_ipc/service_stub.cpp index 4c7b48bf3..64a5a01e3 100644 --- a/services/backup_sa/src/module_ipc/service_stub.cpp +++ b/services/backup_sa/src/module_ipc/service_stub.cpp @@ -41,7 +41,7 @@ ServiceStub::ServiceStub() opToInterfaceMap_[SERVICE_CMD_APP_FILE_READY] = &ServiceStub::CmdAppFileReady; opToInterfaceMap_[SERVICE_CMD_APP_DONE] = &ServiceStub::CmdAppDone; opToInterfaceMap_[SERVICE_CMD_START] = &ServiceStub::CmdStart; - opToInterfaceMap_[SERVICE_CMD_GET_EXT_FILE_NAME] = &ServiceStub::CmdGetExtFileName; + opToInterfaceMap_[SERVICE_CMD_GET_FILE_NAME] = &ServiceStub::CmdGetFileHandle; opToInterfaceMap_[SERVICE_CMD_APPEND_BUNDLES_RESTORE_SESSION] = &ServiceStub::CmdAppendBundlesRestoreSession; opToInterfaceMap_[SERVICE_CMD_APPEND_BUNDLES_BACKUP_SESSION] = &ServiceStub::CmdAppendBundlesBackupSession; opToInterfaceMap_[SERVICE_CMD_FINISH] = &ServiceStub::CmdFinish; @@ -77,12 +77,7 @@ int32_t ServiceStub::CmdInitRestoreSession(MessageParcel &data, MessageParcel &r return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive the reverse stub"); } - std::vector bundleNames; - if (!data.ReadStringVector(&bundleNames)) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bundleNames"); - } - - int32_t res = InitRestoreSession(iremote, bundleNames); + int32_t res = InitRestoreSession(iremote); if (!reply.WriteInt32(res)) { stringstream ss; ss << "Failed to send the result " << res; @@ -103,17 +98,7 @@ int32_t ServiceStub::CmdInitBackupSession(MessageParcel &data, MessageParcel &re return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive the reverse stub"); } - UniqueFd fd(data.ReadFileDescriptor()); - if (fd < 0) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive fd"); - } - - std::vector bundleNames; - if (!data.ReadStringVector(&bundleNames)) { - return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bundleNames"); - } - - int res = InitBackupSession(iremote, move(fd), bundleNames); + int res = InitBackupSession(iremote); if (!reply.WriteInt32(res)) { stringstream ss; ss << "Failed to send the result " << res; @@ -196,7 +181,7 @@ int32_t ServiceStub::CmdAppDone(MessageParcel &data, MessageParcel &reply) return BError(BError::Codes::OK); } -int32_t ServiceStub::CmdGetExtFileName(MessageParcel &data, MessageParcel &reply) +int32_t ServiceStub::CmdGetFileHandle(MessageParcel &data, MessageParcel &reply) { HILOGI("Begin"); string bundleName; @@ -208,7 +193,7 @@ int32_t ServiceStub::CmdGetExtFileName(MessageParcel &data, MessageParcel &reply return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive fileName").GetCode(); } - return GetExtFileName(bundleName, fileName); + return GetFileHandle(bundleName, fileName); } int32_t ServiceStub::CmdAppendBundlesRestoreSession(MessageParcel &data, MessageParcel &reply) diff --git a/services/backup_sa/src/module_ipc/svc_session_manager.cpp b/services/backup_sa/src/module_ipc/svc_session_manager.cpp index db963091f..f7663495a 100644 --- a/services/backup_sa/src/module_ipc/svc_session_manager.cpp +++ b/services/backup_sa/src/module_ipc/svc_session_manager.cpp @@ -23,13 +23,10 @@ #include "b_error/b_error.h" #include "b_json/b_json_entity_ext_manage.h" -#include "b_json/b_json_entity_extension_config.h" #include "b_resources/b_constants.h" -#include "bundle_mgr_client.h" #include "filemgmt_libhilog.h" -#include "iservice_registry.h" +#include "module_external/bms_adapter.h" #include "module_ipc/service.h" -#include "system_ability_definition.h" namespace OHOS::FileManagement::Backup { using namespace std; @@ -61,10 +58,6 @@ void SvcSessionManager::Active(Impl newImpl) throw BError(BError::Codes::SA_INVAL_ARG, "No scenario was specified"); } - GetBundleExtNames(newImpl.backupExtNameMap); - - InitExtConn(newImpl.backupExtNameMap); - InitClient(newImpl); impl_ = newImpl; } @@ -123,46 +116,6 @@ IServiceReverse::Scenario SvcSessionManager::GetScenario() return impl_.scenario; } -void SvcSessionManager::GetBundleExtNames(map &backupExtNameMap) -{ - if (backupExtNameMap.empty()) { - throw BError(BError::Codes::SA_INVAL_ARG, "No app was selected"); - } - - auto bms = GetBundleManager(); - if (!bms) { - throw BError(BError::Codes::SA_BROKEN_IPC, "Bms is invalid"); - } - - for (auto &&it : backupExtNameMap) { - AppExecFwk::BundleInfo installedBundle; - if (!bms->GetBundleInfo(it.first, AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundle, - AppExecFwk::Constants::START_USERID)) { - throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get the info of bundle " + it.first); - } - for (auto &&ext : installedBundle.extensionInfos) { - if (ext.type == AppExecFwk::ExtensionAbilityType::BACKUP) { - if (ext.name.empty()) { - throw BError(BError::Codes::SA_INVAL_ARG, "Failed to get ext name of bundle " + it.first); - } - vector out; - AppExecFwk::BundleMgrClient client; - if (!client.GetResConfigFile(ext, "ohos.extension.backup", out) || out.size() == 0) { - throw BError(BError::Codes::SA_INVAL_ARG, "Failed to get resconfigfile of bundle " + it.first); - } - BJsonCachedEntity cachedEntity(out[0], it.first); - auto cache = cachedEntity.Structuralize(); - if (cache.GetAllowToBackupRestore()) { - it.second.backupExtName = ext.name; - } else { - throw BError(BError::Codes::SA_INVAL_ARG, - "Permission denied to get allowToBackupRestore of bundle " + it.first); - } - } - } - } -} - bool SvcSessionManager::OnBunleFileReady(const string &bundleName, const string &fileName) { unique_lock lock(lock_); @@ -179,6 +132,7 @@ bool SvcSessionManager::OnBunleFileReady(const string &bundleName, const string // 判断是否结束 通知EXTENTION清理资源 TOOL应用完成备份 if (impl_.scenario == IServiceReverse::Scenario::RESTORE) { + it->second.isBundleFinished = true; return true; } else if (impl_.scenario == IServiceReverse::Scenario::BACKUP) { if (!fileName.empty() && fileName != BConstants::EXT_BACKUP_MANAGE) { @@ -190,6 +144,7 @@ bool SvcSessionManager::OnBunleFileReady(const string &bundleName, const string it->second.receExtAppDone = true; } if (it->second.receExtManageJson && it->second.fileNameInfo.empty() && it->second.receExtAppDone) { + it->second.isBundleFinished = true; return true; } } @@ -248,37 +203,30 @@ wptr SvcSessionManager::GetExtConnection(const BundleName & return wptr(it->second.backUpConnection); } -void SvcSessionManager::InitExtConn(std::map &backupExtNameMap) +sptr SvcSessionManager::GetBackupExtAbility(const string &bundleName) { HILOGI("Begin"); - if (backupExtNameMap.empty()) { - throw BError(BError::Codes::SA_INVAL_ARG, "No app was selected"); - } + auto callDied = [revPtr {reversePtr_}](const string &&bundleName) { + auto revPtrStrong = revPtr.promote(); + if (!revPtrStrong) { + // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下 + HILOGW("It's curious that the backup sa dies before the backup client"); + return; + } + revPtrStrong->OnBackupExtensionDied(move(bundleName), ESRCH); + }; - for (auto &&it : backupExtNameMap) { - auto callDied = [revPtr {reversePtr_}](const string &&bundleName) { - auto revPtrStrong = revPtr.promote(); - if (!revPtrStrong) { - // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下 - HILOGW("It's curious that the backup sa dies before the backup client"); - return; - } - revPtrStrong->OnBackupExtensionDied(move(bundleName), ESRCH); - }; - - auto callConnDone = [revPtr {reversePtr_}](const string &&bundleName) { - auto revPtrStrong = revPtr.promote(); - if (!revPtrStrong) { - // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下 - HILOGW("It's curious that the backup sa dies before the backup client"); - return; - } - revPtrStrong->ExtConnectDone(move(bundleName)); - }; + auto callConnDone = [revPtr {reversePtr_}](const string &&bundleName) { + auto revPtrStrong = revPtr.promote(); + if (!revPtrStrong) { + // 服务先于客户端死亡是一种异常场景,但该场景对本流程来说也没什么影响,所以只是简单记录一下 + HILOGW("It's curious that the backup sa dies before the backup client"); + return; + } + revPtrStrong->ExtConnectDone(move(bundleName)); + }; - auto backUpConnection = sptr(new SvcBackupConnection(callDied, callConnDone)); - it.second.backUpConnection = backUpConnection; - } + return sptr(new SvcBackupConnection(callDied, callConnDone)); } void SvcSessionManager::DumpInfo(const int fd, const std::vector &args) @@ -328,7 +276,7 @@ void SvcSessionManager::SetExtFileNameRequest(const string &bundleName, const st std::set SvcSessionManager::GetExtFileNameRequest(const std::string &bundleName) { HILOGI("Begin"); - shared_lock lock(lock_); + unique_lock lock(lock_); if (!impl_.clientToken) { throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); } @@ -337,7 +285,9 @@ std::set SvcSessionManager::GetExtFileNameRequest(const std::string throw BError(BError::Codes::SA_INVAL_ARG, "Invalid Scenario"); } auto it = GetBackupExtNameMap(bundleName); - return it->second.fileNameInfo; + set fileNameInfo = it->second.fileNameInfo; + it->second.fileNameInfo.clear(); + return fileNameInfo; } map::iterator SvcSessionManager::GetBackupExtNameMap(const string &bundleName) @@ -405,21 +355,36 @@ string SvcSessionManager::GetBackupExtName(const string &bundleName) return it->second.backupExtName; } -sptr SvcSessionManager::GetBundleManager() +void SvcSessionManager::AppendBundles(const vector &bundleNames) { - auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (saMgr == nullptr) { - HILOGI("SystemAbilityManager is nullptr."); - return nullptr; + HILOGI("Begin"); + unique_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); } - auto bundleObj = saMgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - if (bundleObj == nullptr) { - HILOGI("Failed to get bundle manager service."); - return nullptr; + auto bundleInfos = BundleMgrAdapter::GetBundleInfos(bundleNames); + for (auto &&bundleInfo : bundleInfos) { + if (!bundleInfo.allToBackup || bundleInfo.extensionName.empty()) { + throw BError(BError::Codes::SA_INVAL_ARG, + string(bundleInfo.name).append(" is not allow to backup or extension name is empty")); + } + BackupExtInfo info {}; + info.backupExtName = bundleInfo.extensionName; + info.backUpConnection = GetBackupExtAbility(bundleInfo.name); + + impl_.backupExtNameMap.insert(make_pair(bundleInfo.name, info)); } +} - return iface_cast(bundleObj); +void SvcSessionManager::Start() +{ + HILOGI("Begin"); + unique_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + impl_.isBackupStart = true; } void SvcSessionManager::Finish() @@ -431,4 +396,31 @@ void SvcSessionManager::Finish() } impl_.isAppendFinish = true; } + +bool SvcSessionManager::IsOnAllBundlesFinished() +{ + shared_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + auto iter = find_if(impl_.backupExtNameMap.begin(), impl_.backupExtNameMap.end(), + [](auto &it) { return it.second.isBundleFinished == false; }); + if (iter == impl_.backupExtNameMap.end() && impl_.isAppendFinish) { + return true; + } + return false; +} + +bool SvcSessionManager::IsOnOnStartSched() +{ + shared_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + if (impl_.isBackupStart && impl_.backupExtNameMap.size()) { + return true; + } + + return false; +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tools/backup_tool/src/tools_op_backup.cpp b/tools/backup_tool/src/tools_op_backup.cpp index 72f281865..50462562f 100644 --- a/tools/backup_tool/src/tools_op_backup.cpp +++ b/tools/backup_tool/src/tools_op_backup.cpp @@ -13,6 +13,7 @@ * limitations under the License. */ +#include #include #include #include @@ -66,7 +67,7 @@ public: if (flag == true) { ready_ = true; cv_.notify_all(); - } else if (bundleStatusMap_.size() == 0 && cnt_ == 0) { + } else if (bundleStatusMap_.size() == 0 && cnt_ == 0 && isAllBundelsFinished.load()) { ready_ = true; cv_.notify_all(); } @@ -109,6 +110,9 @@ private: mutex lock_; bool ready_ = false; uint32_t cnt_ {0}; + +public: + std::atomic isAllBundelsFinished {false}; }; static string GenHelpMsg() @@ -147,6 +151,7 @@ static void OnBundleStarted(shared_ptr ctx, ErrCode err, const BundleNa { printf("BundleStarted errCode = %d, BundleName = %s\n", err, name.c_str()); if (err != 0) { + ctx->isAllBundelsFinished.store(true); ctx->UpdateBundleFinishedCount(); ctx->TryNotify(); } @@ -161,6 +166,7 @@ static void OnBundleFinished(shared_ptr ctx, ErrCode err, const BundleN static void OnAllBundlesFinished(shared_ptr ctx, ErrCode err) { + ctx->isAllBundelsFinished.store(true); if (err == 0) { printf("backup successful\n"); } else { @@ -206,34 +212,18 @@ static void BackupToolDirSoftlinkToBackupDir() } } -static int32_t InitPathCapFile(const string &isLocal, const string &pathCapFile, vector bundleNames) +static int32_t InitPathCapFile(vector bundleNames) { StartTrace(HITRACE_TAG_FILEMANAGEMENT, "InitPathCapFile"); // SELinux backup_tool工具/data/文件夹下创建文件夹 SA服务因root用户的自定义标签无写入权限 此处调整为软链接形式 BackupToolDirSoftlinkToBackupDir(); - UniqueFd fd(open(pathCapFile.data(), O_RDWR | O_CREAT, S_IRWXU)); - if (fd < 0) { - fprintf(stderr, "Failed to open file error: %d %s\n", errno, strerror(errno)); - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return -errno; - } - if (isLocal == "true") { - auto proxy = ServiceProxy::GetInstance(); - if (!proxy) { - fprintf(stderr, "Get an empty backup sa proxy\n"); - return -EFAULT; - } - BFile::SendFile(fd, proxy->GetLocalCapabilities()); - } - if (access((BConstants::BACKUP_TOOL_RECEIVE_DIR).data(), F_OK) != 0 && mkdir((BConstants::BACKUP_TOOL_RECEIVE_DIR).data(), S_IRWXU) != 0) { throw BError(BError::Codes::TOOL_INVAL_ARG, generic_category().message(errno)); } auto ctx = make_shared(); ctx->session_ = BSessionBackup::Init( - move(fd), bundleNames, BSessionBackup::Callbacks {.onFileReady = bind(OnFileReady, ctx, placeholders::_1, placeholders::_2), .onBundleStarted = bind(OnBundleStarted, ctx, placeholders::_1, placeholders::_2), .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), @@ -244,11 +234,13 @@ static int32_t InitPathCapFile(const string &isLocal, const string &pathCapFile, FinishTrace(HITRACE_TAG_FILEMANAGEMENT); return -EPERM; } - ctx->SetBundleFinishedCount(bundleNames.size()); - int ret = ctx->session_->Start(); + int ret = ctx->session_->AppendBundles(bundleNames); if (ret != 0) { - throw BError(BError::Codes::TOOL_INVAL_ARG, "backup start error"); + printf("backup append bundles error: %d", ret); + throw BError(BError::Codes::TOOL_INVAL_ARG, "backup append bundles error"); } + + ctx->SetBundleFinishedCount(bundleNames.size()); ctx->Wait(); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); return 0; @@ -260,8 +252,7 @@ static int Exec(map> &mapArgToVal) mapArgToVal.find("isLocal") == mapArgToVal.end()) { return -EPERM; } - return InitPathCapFile(*(mapArgToVal["isLocal"].begin()), *(mapArgToVal["pathCapFile"].begin()), - mapArgToVal["bundles"]); + return InitPathCapFile(mapArgToVal["bundles"]); } /** diff --git a/tools/backup_tool/src/tools_op_restore.cpp b/tools/backup_tool/src/tools_op_restore.cpp index 95ba8b840..419e315f3 100644 --- a/tools/backup_tool/src/tools_op_restore.cpp +++ b/tools/backup_tool/src/tools_op_restore.cpp @@ -70,7 +70,7 @@ public: if (flag == true) { ready_ = true; cv_.notify_all(); - } else if (bundleStatusMap_.size() == 0 && cnt_ == 0) { + } else if (bundleStatusMap_.size() == 0 && cnt_ == 0 && isAllBundelsFinished.load()) { ready_ = true; cv_.notify_all(); } @@ -113,6 +113,9 @@ private: mutex lock_; bool ready_ = false; uint32_t cnt_ {0}; + +public: + std::atomic isAllBundelsFinished {false}; }; static string GenHelpMsg() @@ -161,18 +164,23 @@ static void OnBundleFinished(shared_ptr ctx, ErrCode err, const BundleN printf("BundleFinished errCode = %d, BundleName = %s\n", err, name.c_str()); ctx->UpdateBundleFinishedCount(); if (err != 0) { + ctx->isAllBundelsFinished.store(true); ctx->ClearBundleOfMap(name); } ctx->TryNotify(); } -static void OnAllBundlesFinished(ErrCode err) +static void OnAllBundlesFinished(shared_ptr ctx, ErrCode err) { + ctx->isAllBundelsFinished.store(true); if (err == 0) { printf("Restore successful\n"); } else { printf("Failed to Unplanned Abort error: %d\n", err); + ctx->TryNotify(true); + return; } + ctx->TryNotify(); } static void OnBackupServiceDied(shared_ptr ctx) @@ -201,61 +209,49 @@ static void RestoreApp(shared_ptr restore, vector &bundleNa } for (auto &filePath : filePaths) { string fileName = filePath.substr(filePath.rfind("/") + 1); - restore->session_->GetExtFileName(bundleName, fileName); + restore->session_->GetFileHandle(bundleName, fileName); restore->UpdateBundleSendFiles(bundleName, fileName); } } FinishTrace(HITRACE_TAG_FILEMANAGEMENT); } -static int32_t Init(const string &pathCapFile, vector bundleNames) +static int32_t InitPathCapFile(const string &pathCapFile, vector bundleNames) { StartTrace(HITRACE_TAG_FILEMANAGEMENT, "Init"); + + UniqueFd fd(open(pathCapFile.data(), O_RDWR | O_CREAT, S_IRWXU)); + if (fd < 0) { + fprintf(stderr, "Failed to open file error: %d %s\n", errno, strerror(errno)); + FinishTrace(HITRACE_TAG_FILEMANAGEMENT); + return -errno; + } + auto proxy = ServiceProxy::GetInstance(); + if (!proxy) { + fprintf(stderr, "Get an empty backup sa proxy\n"); + return -EFAULT; + } + BFile::SendFile(fd, proxy->GetLocalCapabilities()); + auto ctx = make_shared(); ctx->session_ = BSessionRestore::Init( - bundleNames, BSessionRestore::Callbacks {.onFileReady = bind(OnFileReady, ctx, placeholders::_1, placeholders::_2), .onBundleStarted = bind(OnBundleStarted, ctx, placeholders::_1, placeholders::_2), .onBundleFinished = bind(OnBundleFinished, ctx, placeholders::_1, placeholders::_2), - .onAllBundlesFinished = OnAllBundlesFinished, + .onAllBundlesFinished = bind(OnAllBundlesFinished, ctx, placeholders::_1), .onBackupServiceDied = bind(OnBackupServiceDied, ctx)}); if (ctx->session_ == nullptr) { printf("Failed to init restore"); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); return -EPERM; } - UniqueFd fdRemote(ctx->session_->GetLocalCapabilities()); - if (fdRemote < 0) { - printf("Failed to receive fd"); - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return fdRemote; - } - if (lseek(fdRemote, 0, SEEK_SET) == -1) { - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return -errno; - } - struct stat stat = {}; - if (fstat(fdRemote, &stat) == -1) { - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return -errno; - } - UniqueFd fdLocal(open(pathCapFile.data(), O_WRONLY | O_CREAT, S_IRWXU)); - if (fdLocal < 0) { - fprintf(stderr, "Failed to open file. error: %d %s\n", errno, strerror(errno)); - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return -errno; - } - if (sendfile(fdLocal, fdRemote, nullptr, stat.st_size) == -1) { - fprintf(stderr, "Failed to Copy file. error: %d %s\n", errno, strerror(errno)); - FinishTrace(HITRACE_TAG_FILEMANAGEMENT); - return -errno; + int ret = ctx->session_->AppendBundles(move(fd), bundleNames); + if (ret != 0) { + printf("restore append bundles error: %d", ret); + throw BError(BError::Codes::TOOL_INVAL_ARG, "restore append bundles error"); } ctx->SetBundleFinishedCount(bundleNames.size()); RestoreApp(ctx, bundleNames); - int ret = ctx->session_->Start(); - if (ret != 0) { - throw BError(BError::Codes::TOOL_INVAL_ARG, "restore start error"); - } ctx->Wait(); return 0; } @@ -265,7 +261,7 @@ static int Exec(map> &mapArgToVal) if (mapArgToVal.find("pathCapFile") == mapArgToVal.end() || mapArgToVal.find("bundles") == mapArgToVal.end()) { return -EPERM; } - return Init(*(mapArgToVal["pathCapFile"].begin()), mapArgToVal["bundles"]); + return InitPathCapFile(*(mapArgToVal["pathCapFile"].begin()), mapArgToVal["bundles"]); } /** diff --git a/utils/include/b_json/b_json_entity_caps.h b/utils/include/b_json/b_json_entity_caps.h index 7c1c7625a..6a104f78a 100644 --- a/utils/include/b_json/b_json_entity_caps.h +++ b/utils/include/b_json/b_json_entity_caps.h @@ -21,6 +21,16 @@ namespace OHOS::FileManagement::Backup { class BJsonEntityCaps : public BJsonEntity { +public: + struct BundleInfo { + std::string name; + uint32_t versionCode; + std::string versionName; + int64_t spaceOccupied; + bool allToBackup; + std::string extensionName; + }; + public: uint64_t GetFreeDiskSpace() { diff --git a/utils/include/b_resources/b_constants.h b/utils/include/b_resources/b_constants.h index d46740f55..7acbe234b 100644 --- a/utils/include/b_resources/b_constants.h +++ b/utils/include/b_resources/b_constants.h @@ -45,6 +45,7 @@ enum EntryKey { constexpr int SPAN_USERID_UID = 20000000; constexpr int SYSTEM_UID = 0; +constexpr int XTS_UID = 1; constexpr int DEFAULT_USER_ID = 100; constexpr int BACKUP_UID = 1089; constexpr int EXTENSION_THREAD_POOL_COUNT = 1; -- Gitee