From 4ebce0db5fcc4733cc296a04110bf5e74171ad41 Mon Sep 17 00:00:00 2001 From: huaqingsimeng <1004904143@qq.com> Date: Thu, 9 Mar 2023 09:07:05 +0000 Subject: [PATCH] =?UTF-8?q?=E5=A4=87=E4=BB=BD=E6=81=A2=E5=A4=8D=E5=BA=94?= =?UTF-8?q?=E7=94=A8=E6=8F=90=E4=BE=9Bjs=E6=8E=A5=E5=8F=A3=E8=83=BD?= =?UTF-8?q?=E5=8A=9B-=E6=9C=8D=E5=8A=A1=E7=AB=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: huaqingsimeng --- backup.gni | 6 +- .../backup_kit_inner/src/b_session_backup.cpp | 26 +- .../src/b_session_restore.cpp | 34 ++- .../backup_kit_inner/src/service_proxy.cpp | 88 +++++-- .../backup_kit_inner/impl/b_session_backup.h | 22 +- .../backup_kit_inner/impl/b_session_restore.h | 30 ++- .../native/backup_kit_inner/impl/i_service.h | 19 +- .../backup_kit_inner/impl/service_proxy.h | 11 +- services/backup.cfg | 3 +- services/backup_sa/BUILD.gn | 3 + .../include/module_external/bms_adapter.h | 44 ++++ .../include/module_external/sms_adapter.h | 34 +++ .../backup_sa/include/module_ipc/service.h | 24 +- .../include/module_ipc/service_stub.h | 5 +- .../include/module_ipc/svc_session_manager.h | 57 +++-- .../src/module_external/bms_adapter.cpp | 101 ++++++++ .../src/module_external/sms_adapter.cpp | 52 ++++ services/backup_sa/src/module_ipc/service.cpp | 124 ++++++---- .../backup_sa/src/module_ipc/service_stub.cpp | 78 ++++-- .../src/module_ipc/svc_session_manager.cpp | 171 +++++++------ tests/mock/affwk/service_registry_mock.cpp | 10 + .../b_session_backup_mock.cpp | 14 +- .../b_session_restore_mock.cpp | 31 +-- .../backup_kit_inner/service_proxy_mock.cpp | 23 +- .../include/mock_bundle_manager.h | 4 + .../src/mock_bundle_manager.cpp | 10 + .../mock/module_external/bms_adapter_mock.cpp | 42 ++++ .../mock/module_external/sms_adapter_mock.cpp | 31 +++ tests/mock/module_ipc/service_mock.cpp | 25 +- tests/mock/module_ipc/service_stub_mock.cpp | 48 +++- .../module_ipc/svc_session_manager_mock.cpp | 42 +++- .../storage_manager_service_mock.h | 225 ++++++++++++++++++ .../b_session_backup_test.cpp | 12 +- .../b_session_restore_test.cpp | 49 +--- .../unittests/backup_api/backup_impl/BUILD.gn | 2 +- .../backup_impl/include/i_service_mock.h | 23 +- .../backup_impl/service_proxy_test.cpp | 118 +++++++-- tests/unittests/backup_sa/module_ipc/BUILD.gn | 7 + .../module_ipc/service_stub_test.cpp | 148 +++++++++--- .../backup_sa/module_ipc/service_test.cpp | 36 ++- .../module_ipc/svc_session_manager_test.cpp | 19 +- .../backup_tool/tools_op_backup_test.cpp | 8 - .../backup_tool/tools_op_restore_test.cpp | 10 - tests/unittests/backup_utils/BUILD.gn | 5 +- .../b_json/b_json_cached_entity_test.cpp | 14 +- tools/backup_tool/src/tools_op_backup.cpp | 41 ++-- tools/backup_tool/src/tools_op_restore.cpp | 70 +++--- utils/BUILD.gn | 4 + utils/include/b_error/b_error.h | 55 ++++- utils/include/b_json/b_json_entity_caps.h | 75 ++++-- utils/src/b_error/b_error.cpp | 8 + 51 files changed, 1605 insertions(+), 536 deletions(-) create mode 100644 services/backup_sa/include/module_external/bms_adapter.h create mode 100644 services/backup_sa/include/module_external/sms_adapter.h create mode 100644 services/backup_sa/src/module_external/bms_adapter.cpp create mode 100644 services/backup_sa/src/module_external/sms_adapter.cpp create mode 100644 tests/mock/module_external/bms_adapter_mock.cpp create mode 100644 tests/mock/module_external/sms_adapter_mock.cpp create mode 100644 tests/mock/storage_manager/storage_manager_service_mock.h diff --git a/backup.gni b/backup.gni index 7dc5c0e87..2cd7586e9 100644 --- a/backup.gni +++ b/backup.gni @@ -25,7 +25,7 @@ path_jsoncpp = "//third_party/jsoncpp" path_napi = "//foundation/arkui/napi" path_samgr = "//foundation/systemabilitymgr/samgr" path_init = "//base/startup/init" - +path_filemgmt_libn = "//foundation/filemanagement/file_api/utils/filemgmt_libn" path_backup_mock = "//foundation/filemanagement/app_file_service/tests/mock" backup_mock_parcel_include_dirs = [ "$path_backup_mock/parcel/include" ] @@ -42,6 +42,10 @@ backup_mock_session_manager_src = [ "$path_backup_mock/module_ipc/svc_session_manager_mock.cpp" ] backup_mock_scheduler_src = [ "$path_backup_mock/module_sched/sched_scheduler_mock.cpp" ] +backup_mock_module_external_src = [ + "$path_backup_mock/module_external/bms_adapter_mock.cpp", + "$path_backup_mock/module_external/sms_adapter_mock.cpp", +] backup_mock_service_src = [ "$path_backup_mock/module_ipc/service_mock.cpp" ] backup_mock_utils_include = [ "$path_backup_mock/utils_mock/include" ] backup_mock_proxy_src = [ 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 7da9c9716..c171c3c37 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; @@ -94,4 +92,24 @@ ErrCode BSessionBackup::Start() return proxy->Start(); } + +ErrCode BSessionBackup::AppendBundles(vector bundlesToBackup) +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to proxy because of is empty").GetCode(); + } + + return proxy->AppendBundlesBackupSession(bundlesToBackup); +} + +ErrCode BSessionBackup::Finish() +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to proxy because of is empty").GetCode(); + } + + return proxy->Finish(); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file 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 34ef872a5..317a62ab2 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,43 +63,53 @@ unique_ptr BSessionRestore::Init(std::vector bundle return nullptr; } -UniqueFd BSessionRestore::GetLocalCapabilities() +ErrCode BSessionRestore::PublishFile(BFileInfo fileInfo) { auto proxy = ServiceProxy::GetInstance(); if (proxy == nullptr) { - HILOGI("Failed to proxy because of is empty"); - return UniqueFd(-1); + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to proxy because of is empty").GetCode(); } - return UniqueFd(proxy->GetLocalCapabilities()); + return proxy->PublishFile(fileInfo); } -ErrCode BSessionRestore::PublishFile(BFileInfo fileInfo) +ErrCode BSessionRestore::Start() { auto proxy = ServiceProxy::GetInstance(); if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to proxy because of is empty").GetCode(); } - return proxy->PublishFile(fileInfo); + + return proxy->Start(); } -ErrCode BSessionRestore::Start() +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 proxy because of is empty").GetCode(); } - return proxy->Start(); + return proxy->GetFileHandle(bundleName, fileName); +} + +ErrCode BSessionRestore::AppendBundles(UniqueFd remoteCap, vector bundlesToRestore) +{ + auto proxy = ServiceProxy::GetInstance(); + if (proxy == nullptr) { + return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to proxy because of is empty").GetCode(); + } + + return proxy->AppendBundlesRestoreSession(move(remoteCap), bundlesToRestore); } -ErrCode BSessionRestore::GetExtFileName(string &bundleName, string &fileName) +ErrCode BSessionRestore::Finish() { auto proxy = ServiceProxy::GetInstance(); if (proxy == nullptr) { return BError(BError::Codes::SDK_BROKEN_IPC, "Failed to proxy because of is empty").GetCode(); } - return proxy->GetExtFileName(bundleName, fileName); + return proxy->Finish(); } void BSessionRestore::RegisterBackupServiceDied(std::function functor) diff --git a/frameworks/native/backup_kit_inner/src/service_proxy.cpp b/frameworks/native/backup_kit_inner/src/service_proxy.cpp index 1bc9826b1..d3a1d38a4 100644 --- a/frameworks/native/backup_kit_inner/src/service_proxy.cpp +++ b/frameworks/native/backup_kit_inner/src/service_proxy.cpp @@ -27,7 +27,7 @@ namespace OHOS::FileManagement::Backup { using namespace std; -int32_t ServiceProxy::InitRestoreSession(sptr remote, const std::vector &bundleNames) +ErrCode ServiceProxy::InitRestoreSession(sptr remote) { HILOGI("Start"); MessageParcel data; @@ -42,10 +42,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) { stringstream ss; @@ -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("Start"); MessageParcel data; @@ -73,13 +67,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) { stringstream ss; @@ -199,7 +186,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("Start"); MessageParcel data; @@ -215,16 +202,81 @@ 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) { stringstream ss; ss << "Failed to send out the request because of " << ret; - BError(BError::Codes::SDK_INVAL_ARG, ss.str()); + return BError(BError::Codes::SDK_INVAL_ARG, ss.str()).GetCode(); } HILOGI("Successful"); return ret; } +ErrCode ServiceProxy::AppendBundlesRestoreSession(UniqueFd fd, const vector &bundleNames) +{ + HILOGI("Start"); + MessageParcel data; + data.WriteInterfaceToken(GetDescriptor()); + MessageParcel reply; + MessageOption option; + + 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_APPEND_BUNDLES_RESTORE_SESSION, data, reply, option); + if (ret != NO_ERROR) { + stringstream ss; + ss << "Failed to send out the request because of " << ret; + return BError(BError::Codes::SDK_INVAL_ARG, ss.str()).GetCode(); + } + HILOGI("Successful"); + return reply.ReadInt32(); +} + +ErrCode ServiceProxy::AppendBundlesBackupSession(const vector &bundleNames) +{ + HILOGI("Start"); + MessageParcel data; + data.WriteInterfaceToken(GetDescriptor()); + MessageParcel reply; + MessageOption option; + + if (!data.WriteStringVector(bundleNames)) { + return BError(BError::Codes::SDK_INVAL_ARG, "Failed to send bundleNames").GetCode(); + } + + int32_t ret = Remote()->SendRequest(IService::SERVICE_CMD_APPEND_BUNDLES_BACKUP_SESSION, data, reply, option); + if (ret != NO_ERROR) { + stringstream ss; + ss << "Failed to send out the request because of " << ret; + return BError(BError::Codes::SDK_INVAL_ARG, ss.str()).GetCode(); + } + HILOGI("Successful"); + return reply.ReadInt32(); +} + +ErrCode ServiceProxy::Finish() +{ + HILOGI("Start"); + MessageParcel data; + data.WriteInterfaceToken(GetDescriptor()); + + MessageParcel reply; + MessageOption option; + int32_t ret = Remote()->SendRequest(IService::SERVICE_CMD_FINISH, data, reply, option); + if (ret != NO_ERROR) { + stringstream ss; + ss << "Failed to send out the request because of " << ret; + return BError(BError::Codes::SDK_INVAL_ARG, ss.str()).GetCode(); + } + HILOGI("Successful"); + return reply.ReadInt32(); +} + sptr ServiceProxy::GetInstance() { unique_lock lock(proxyMutex_); 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 d5e40d47d..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,25 @@ 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之前调用 + * + * @param bundlesToBackup 待备份的应用清单 + * @return ErrCode 规范错误码 + */ + ErrCode AppendBundles(std::vector bundlesToBackup); + + /** + * @brief 用于结束追加应用,结束后不可在调用AppendBundles + * + * @return ErrCode 规范错误码 + */ + ErrCode Finish(); /** * @brief 用于启动备份流程 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 33b38274e..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,23 @@ 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之前调用 + * + * @param remoteCap 已打开的保存远端设备能力的Json文件。可使用GetLocalCapabilities方法获取 + * @param bundlesToRestore 待恢复的应用清单 + * @return ErrCode 规范错误码 + */ + ErrCode AppendBundles(UniqueFd remoteCap, std::vector bundlesToRestore); + + /** + * @brief 用于结束追加应用,结束后不可在调用AppendBundles + * + * @return ErrCode 规范错误码 + */ + ErrCode Finish(); /** * @brief 用于启动恢复流程 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 bc240c71b..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 @@ -19,10 +19,11 @@ #include #include +#include + #include "b_file_info.h" #include "i_service_reverse.h" #include "iremote_broker.h" -#include "unique_fd.h" namespace OHOS::FileManagement::Backup { class IService : public IRemoteBroker { @@ -35,19 +36,23 @@ 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; DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Filemanagement.Backup.IService") }; 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 9b3c8688c..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,17 @@ 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; public: explicit ServiceProxy(const sptr &impl) : IRemoteProxy(impl) {} diff --git a/services/backup.cfg b/services/backup.cfg index 84d391ce6..40c460399 100644 --- a/services/backup.cfg +++ b/services/backup.cfg @@ -5,7 +5,8 @@ "ondemand" : true, "uid" : "backup", "gid" : ["backup"], - "secon" : "u:r:backup_sa:s0" + "secon" : "u:r:backup_sa:s0", + "permission": ["ohos.permission.STORAGE_MANAGER"] } ] } \ No newline at end of file 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_external/bms_adapter.h b/services/backup_sa/include/module_external/bms_adapter.h new file mode 100644 index 000000000..10dc599ee --- /dev/null +++ b/services/backup_sa/include/module_external/bms_adapter.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2023 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_BUNDLE_MGR_ADAPTER_H +#define OHOS_FILEMGMT_BACKUP_BUNDLE_MGR_ADAPTER_H + +#include +#include + +#include "b_json/b_json_entity_caps.h" +#include "bundlemgr/bundle_mgr_interface.h" + +namespace OHOS::FileManagement::Backup { +class BundleMgrAdapter { +public: + /** + * @brief Get the Bundle Infos object + * + * @return std::vector + */ + static std::vector GetBundleInfos(); + + /** + * @brief Get the bundle infos object + * + * @param bundleNames bundle names + * @return std::vector + */ + static std::vector GetBundleInfos(const std::vector &bundleNames); +}; +} // namespace OHOS::FileManagement::Backup +#endif // OHOS_FILEMGMT_BACKUP_BUNDLE_MGR_ADAPTER_H \ No newline at end of file diff --git a/services/backup_sa/include/module_external/sms_adapter.h b/services/backup_sa/include/module_external/sms_adapter.h new file mode 100644 index 000000000..ff59b8164 --- /dev/null +++ b/services/backup_sa/include/module_external/sms_adapter.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2023 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_STORAGE_MGR_ADAPTER_H +#define OHOS_FILEMGMT_BACKUP_STORAGE_MGR_ADAPTER_H + +#include + +#include "istorage_manager.h" + +namespace OHOS::FileManagement::Backup { +class StorageMgrAdapter { +public: + /** + * @brief Get the bundle stats object + * + * @param bundleName bundle name + */ + static StorageManager::BundleStats GetBundleStats(const std::string &bundleName); +}; +} // namespace OHOS::FileManagement::Backup +#endif // OHOS_FILEMGMT_BACKUP_STORAGE_MGR_ADAPTER_H \ No newline at end of file diff --git a/services/backup_sa/include/module_ipc/service.h b/services/backup_sa/include/module_ipc/service.h index 1a1ba2dec..7bb1dd330 100644 --- a/services/backup_sa/include/module_ipc/service.h +++ b/services/backup_sa/include/module_ipc/service.h @@ -32,16 +32,17 @@ 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; // 以下都是非IPC接口 public: @@ -121,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 fb2e0782b..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,10 @@ 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); }; } // namespace OHOS::FileManagement::Backup 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 48c2b3fba..6d228aa31 100644 --- a/services/backup_sa/include/module_ipc/svc_session_manager.h +++ b/services/backup_sa/include/module_ipc/svc_session_manager.h @@ -24,13 +24,13 @@ #include #include -#include #include #include +#include + #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" @@ -39,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; @@ -53,6 +54,8 @@ public: IServiceReverse::Scenario scenario {IServiceReverse::Scenario::UNDEFINED}; std::map backupExtNameMap; sptr clientProxy; + bool isBackupStart {false}; + bool isAppendFinish {false}; }; public: @@ -197,29 +200,57 @@ public: */ std::string GetBackupExtName(const std::string &bundleName); -private: /** - * @brief 校验BundleName和ability type 并补全Impl.backupExtNameMap信息 + * @brief 追加应用 + * + * @param bundleNames 应用名称 + */ + void AppendBundles(const std::vector &bundleNames); + + /** + * @brief 开始备份 + * + * @return ErrCode + */ + void Start(); + + /** + * @brief 结束追加应用 + * + * @return ErrCode + */ + void Finish(); + + /** + * @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 IsOnAllBundlesFinished(); /** - * @brief 初始化 extension backUpConnection + * @brief 是否启动调度器 * - * @param backupExtNameMap + * @return true 启动调度器 + * @return false 不启动调度器 + */ + bool IsOnOnStartSched(); + +private: + /** + * @brief 获取backup extension ability + * + * @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 @@ -239,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_external/bms_adapter.cpp b/services/backup_sa/src/module_external/bms_adapter.cpp new file mode 100644 index 000000000..ad443f0ce --- /dev/null +++ b/services/backup_sa/src/module_external/bms_adapter.cpp @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2023 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 "module_external/bms_adapter.h" + +#include + +#include "b_error/b_error.h" +#include "b_json/b_json_entity_extension_config.h" +#include "bundle_mgr_client.h" +#include "filemgmt_libhilog.h" +#include "iservice_registry.h" +#include "module_external/sms_adapter.h" +#include "system_ability_definition.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +static sptr GetBundleManager() +{ + auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (saMgr == nullptr) { + throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get system ability manager"); + } + + auto bundleObj = saMgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (bundleObj == nullptr) { + throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get bundle manager service"); + } + + return iface_cast(bundleObj); +} + +static tuple GetAllowAndExtName(const vector &extensionInfos) +{ + for (auto &&ext : extensionInfos) { + if (ext.type != AppExecFwk::ExtensionAbilityType::BACKUP) { + continue; + } + 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 " + ext.bundleName); + } + BJsonCachedEntity cachedEntity(out[0], ext.bundleName); + auto cache = cachedEntity.Structuralize(); + return {cache.GetAllowToBackupRestore(), ext.name}; + } + return {false, ""}; +} + +vector BundleMgrAdapter::GetBundleInfos() +{ + vector bundleInfos; + vector installedBundles; + auto bms = GetBundleManager(); + if (!bms->GetBundleInfos(AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundles, + AppExecFwk::Constants::START_USERID)) { + throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get bundle infos"); + } + for (auto const &installedBundle : installedBundles) { + auto [allToBackup, extName] = GetAllowAndExtName(installedBundle.extensionInfos); + auto bundleStats = StorageMgrAdapter::GetBundleStats(installedBundle.name); + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.versionCode, + installedBundle.versionName, bundleStats.dataSize_, + allToBackup, extName}); + } + return bundleInfos; +} + +vector BundleMgrAdapter::GetBundleInfos(const vector &bundleNames) +{ + vector bundleInfos; + auto bms = GetBundleManager(); + for (auto const &bundleName : bundleNames) { + AppExecFwk::BundleInfo installedBundle; + if (!bms->GetBundleInfo(bundleName, AppExecFwk::GET_BUNDLE_WITH_EXTENSION_INFO, installedBundle, + AppExecFwk::Constants::START_USERID)) { + throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get bundle info"); + } + auto [allToBackup, extName] = GetAllowAndExtName(installedBundle.extensionInfos); + auto bundleStats = StorageMgrAdapter::GetBundleStats(installedBundle.name); + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {installedBundle.name, installedBundle.versionCode, + installedBundle.versionName, bundleStats.dataSize_, + allToBackup, extName}); + } + return bundleInfos; +} +} // namespace OHOS::FileManagement::Backup diff --git a/services/backup_sa/src/module_external/sms_adapter.cpp b/services/backup_sa/src/module_external/sms_adapter.cpp new file mode 100644 index 000000000..ce378162b --- /dev/null +++ b/services/backup_sa/src/module_external/sms_adapter.cpp @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2023 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 "module_external/sms_adapter.h" + +#include + +#include "b_error/b_error.h" +#include "filemgmt_libhilog.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +static sptr GetStorageManager() +{ + auto saMgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (saMgr == nullptr) { + throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get system ability manager"); + } + + auto storageObj = saMgr->GetSystemAbility(STORAGE_MANAGER_MANAGER_ID); + if (storageObj == nullptr) { + throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get storage manager service"); + } + + return iface_cast(storageObj); +} + +StorageManager::BundleStats StorageMgrAdapter::GetBundleStats(const string &bundleName) +{ + StorageManager::BundleStats bundleStats; + auto storageMgr = GetStorageManager(); + if (storageMgr->GetBundleStats(bundleName, bundleStats)) { + throw BError(BError::Codes::SA_BROKEN_IPC, "Failed to get bundle stats"); + } + return bundleStats; +} +} // 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 b6debaa69..c83249239 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" @@ -74,18 +74,16 @@ void Service::OnStop() UniqueFd Service::GetLocalCapabilities() { try { + HILOGI("Begin"); VerifyCaller(); - struct statfs fsInfo = {}; - if (statfs(BConstants::SA_BUNDLE_BACKUP_ROOT_DIR.data(), &fsInfo) == -1) { - throw BError(errno); - } - 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.SetSystemFullName(GetOSFullName()); cache.SetDeviceType(GetDeviceType()); + auto bundleInfos = BundleMgrAdapter::GetBundleInfos(); + cache.SetBundleInfos(bundleInfos); cachedEntity.Persist(); return move(cachedEntity.GetFd()); @@ -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,22 +202,44 @@ 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(); + auto bundleInfos = cache.GetBundleInfos(); + if (!bundleInfos.size()) { + throw BError(BError::Codes::SA_INVAL_ARG, "Json entity caps is empty"); } + session_->AppendBundles(bundleNames); + OnStartSched(); + return BError(BError::Codes::OK); +} + +ErrCode Service::AppendBundlesBackupSession(const vector &bundleNames) +{ + HILOGI("Begin"); + VerifyCaller(session_->GetScenario()); + session_->AppendBundles(bundleNames); + OnStartSched(); + return BError(BError::Codes::OK); +} + +ErrCode Service::Finish() +{ + HILOGI("Begin"); + VerifyCaller(session_->GetScenario()); + session_->Finish(); + OnAllBundlesFinished(BError(BError::Codes::OK)); + return BError(BError::Codes::OK); } ErrCode Service::PublishFile(const BFileInfo &fileInfo) @@ -266,7 +263,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) { @@ -281,7 +278,7 @@ ErrCode Service::PublishFile(const BFileInfo &fileInfo) ErrCode Service::AppFileReady(const string &fileName, UniqueFd fd) { try { - HILOGE("begin %{public}s", fileName.data()); + HILOGI("Begin"); string callerName = VerifyCallerAndGetCallerName(); if (!regex_match(fileName, regex("^[0-9a-zA-Z_.]+$"))) { throw BError(BError::Codes::SA_INVAL_ARG, "Filename is not alphanumeric"); @@ -306,6 +303,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(); // 任意异常产生,终止监听该任务 @@ -339,6 +337,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(); // 任意异常产生,终止监听该任务 @@ -384,10 +383,10 @@ 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); session_->SetExtFileNameRequest(bundleName, fileName); return BError(BError::Codes::OK); @@ -541,4 +540,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 8134ca92a..51e1576ac 100644 --- a/services/backup_sa/src/module_ipc/service_stub.cpp +++ b/services/backup_sa/src/module_ipc/service_stub.cpp @@ -39,7 +39,10 @@ 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; } int32_t ServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -58,7 +61,7 @@ int32_t ServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Message return BError(BError::Codes::SA_INVAL_ARG, "Invalid remote descriptor"); } - return (this->*(interfaceIndex->second))(data, reply); + return BError::ExceptionCatcherLocked([&]() { return ErrCode((this->*(interfaceIndex->second))(data, reply)); }); } int32_t ServiceStub::CmdInitRestoreSession(MessageParcel &data, MessageParcel &reply) @@ -73,12 +76,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; @@ -95,21 +93,11 @@ int32_t ServiceStub::CmdInitBackupSession(MessageParcel &data, MessageParcel &re return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive the reverse stub"); } auto iremote = iface_cast(remote); - if (!remote) { + if (!iremote) { 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; @@ -120,6 +108,7 @@ int32_t ServiceStub::CmdInitBackupSession(MessageParcel &data, MessageParcel &re int32_t ServiceStub::CmdStart(MessageParcel &data, MessageParcel &reply) { + HILOGI("Begin"); int res = Start(); if (!reply.WriteInt32(res)) { stringstream ss; @@ -192,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; @@ -204,6 +193,51 @@ 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) +{ + HILOGI("Begin"); + UniqueFd fd(data.ReadFileDescriptor()); + if (fd < 0) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive fd"); + } + + vector bundleNames; + if (!data.ReadStringVector(&bundleNames)) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bundleNames"); + } + + int res = AppendBundlesRestoreSession(move(fd), bundleNames); + if (!reply.WriteInt32(res)) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to send the result ") + to_string(res)); + } + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdAppendBundlesBackupSession(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("Begin"); + vector bundleNames; + if (!data.ReadStringVector(&bundleNames)) { + return BError(BError::Codes::SA_INVAL_ARG, "Failed to receive bundleNames"); + } + + int32_t res = AppendBundlesBackupSession(bundleNames); + if (!reply.WriteInt32(res)) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to send the result ") + to_string(res)); + } + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdFinish(MessageParcel &data, MessageParcel &reply) +{ + HILOGI("Begin"); + int res = Finish(); + if (!reply.WriteInt32(res)) { + return BError(BError::Codes::SA_BROKEN_IPC, string("Failed to send the result ") + to_string(res)); + } + return BError(BError::Codes::OK); } } // namespace OHOS::FileManagement::Backup 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 286dddbc7..190f3e5f4 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; } @@ -124,46 +117,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_); @@ -178,8 +131,8 @@ bool SvcSessionManager::OnBunleFileReady(const string &bundleName, const string throw BError(BError::Codes::SA_REFUSED_ACT, ss.str()); } - // 判断是否结束 通知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) { @@ -191,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; } } @@ -249,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) @@ -409,20 +356,72 @@ 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)); } +} + +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() +{ + HILOGI("Begin"); + unique_lock lock(lock_); + if (!impl_.clientToken) { + throw BError(BError::Codes::SA_INVAL_ARG, "No caller token was specified"); + } + 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; +} - return iface_cast(bundleObj); +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/tests/mock/affwk/service_registry_mock.cpp b/tests/mock/affwk/service_registry_mock.cpp index 9ec473467..5378faae8 100644 --- a/tests/mock/affwk/service_registry_mock.cpp +++ b/tests/mock/affwk/service_registry_mock.cpp @@ -16,12 +16,15 @@ #include #include "iservice_registry.h" +#include "istorage_manager.h" #include "mock_bundle_manager.h" +#include "storage_manager_service_mock.h" #include "system_ability_definition.h" #include "system_ability_manager_proxy.h" namespace OHOS { static sptr g_appMgrService = nullptr; +static sptr g_storageMgrService = nullptr; SystemAbilityManagerClient &SystemAbilityManagerClient::GetInstance() { @@ -40,6 +43,13 @@ sptr SystemAbilityManagerProxy::GetSystemAbility(int32_t systemAb } remote = g_appMgrService; break; + case STORAGE_MANAGER_MANAGER_ID: + if (!g_storageMgrService) { + GTEST_LOG_(INFO) << "GetSystemAbility(" << systemAbilityId << "): return Mock"; + g_storageMgrService = new StorageManager::StorageManagerServiceMock(); + } + remote = g_storageMgrService; + break; default: GTEST_LOG_(INFO) << "This service is not dummy!!!!" << systemAbilityId; break; diff --git a/tests/mock/backup_kit_inner/b_session_backup_mock.cpp b/tests/mock/backup_kit_inner/b_session_backup_mock.cpp index a5b65ccb4..7c8dd5f7a 100644 --- a/tests/mock/backup_kit_inner/b_session_backup_mock.cpp +++ b/tests/mock/backup_kit_inner/b_session_backup_mock.cpp @@ -34,9 +34,7 @@ static BSessionBackup::Callbacks callbacks_ = {}; BSessionBackup::~BSessionBackup() {} -unique_ptr BSessionBackup::Init(UniqueFd remoteCap, - vector bundlesToBackup, - Callbacks callbacks) +unique_ptr BSessionBackup::Init(Callbacks callbacks) { try { callbacks_ = callbacks; @@ -83,4 +81,14 @@ ErrCode BSessionBackup::Start() callbacks_.onBackupServiceDied(); return BError(BError::Codes::OK); } + +ErrCode BSessionBackup::AppendBundles(vector bundlesToBackup) +{ + return BError(BError::Codes::OK); +} + +ErrCode BSessionBackup::Finish() +{ + return BError(BError::Codes::OK); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/backup_kit_inner/b_session_restore_mock.cpp b/tests/mock/backup_kit_inner/b_session_restore_mock.cpp index 3cfad611f..cafc03392 100644 --- a/tests/mock/backup_kit_inner/b_session_restore_mock.cpp +++ b/tests/mock/backup_kit_inner/b_session_restore_mock.cpp @@ -35,11 +35,10 @@ static vector bundlesToRestore_ = {}; BSessionRestore::~BSessionRestore() {} -unique_ptr BSessionRestore::Init(vector bundlesToRestore, Callbacks callbacks) +unique_ptr BSessionRestore::Init(Callbacks callbacks) { try { callbacks_ = move(callbacks); - bundlesToRestore_ = move(bundlesToRestore); auto restore = make_unique(); return restore; } catch (const exception &e) { @@ -48,22 +47,6 @@ unique_ptr BSessionRestore::Init(vector bundlesToRe return nullptr; } -UniqueFd BSessionRestore::GetLocalCapabilities() -{ - string bundleName = "test"; - auto iter = find_if(bundlesToRestore_.begin(), bundlesToRestore_.end(), [&bundleName](auto &obj) { - const auto &bName = obj; - return bName == bundleName; - }); - if (iter != bundlesToRestore_.end()) { - return UniqueFd(-1); - } - TestManager tm("BSessionRestoreMock_GetFd_0100"); - string filePath = tm.GetRootDirCurTest().append("tmp"); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - return fd; -} - ErrCode BSessionRestore::PublishFile(BFileInfo fileInfo) { return BError(BError::Codes::OK); @@ -97,7 +80,17 @@ ErrCode BSessionRestore::Start() return BError(BError::Codes::OK); } -ErrCode BSessionRestore::GetExtFileName(string &bundleName, string &fileName) +ErrCode BSessionRestore::GetFileHandle(const string &bundleName, const string &fileName) +{ + return BError(BError::Codes::OK); +} + +ErrCode BSessionRestore::AppendBundles(UniqueFd remoteCap, vector bundlesToRestore) +{ + return BError(BError::Codes::OK); +} + +ErrCode BSessionRestore::Finish() { return BError(BError::Codes::OK); } diff --git a/tests/mock/backup_kit_inner/service_proxy_mock.cpp b/tests/mock/backup_kit_inner/service_proxy_mock.cpp index 5c4bdc226..6844d16bc 100644 --- a/tests/mock/backup_kit_inner/service_proxy_mock.cpp +++ b/tests/mock/backup_kit_inner/service_proxy_mock.cpp @@ -31,7 +31,7 @@ namespace OHOS::FileManagement::Backup { using namespace std; -int32_t ServiceProxy::InitRestoreSession(sptr remote, const vector &bundleNames) +int32_t ServiceProxy::InitRestoreSession(sptr remote) { if (!GetMockInitBackupOrRestoreSession()) { return 1; @@ -39,9 +39,7 @@ int32_t ServiceProxy::InitRestoreSession(sptr remote, const vec return 0; } -int32_t ServiceProxy::InitBackupSession(sptr remote, - UniqueFd fd, - const vector &bundleNames) +int32_t ServiceProxy::InitBackupSession(sptr remote) { if (!GetMockInitBackupOrRestoreSession()) { return 1; @@ -77,7 +75,22 @@ ErrCode ServiceProxy::AppDone(ErrCode errCode) return BError(BError::Codes::OK); } -ErrCode ServiceProxy::GetExtFileName(string &bundleName, string &fileName) +ErrCode ServiceProxy::GetFileHandle(const string &bundleName, const string &fileName) +{ + return BError(BError::Codes::OK); +} + +ErrCode ServiceProxy::AppendBundlesRestoreSession(UniqueFd fd, const vector &bundleNames) +{ + return BError(BError::Codes::OK); +} + +ErrCode ServiceProxy::AppendBundlesBackupSession(const vector &bundleNames) +{ + return BError(BError::Codes::OK); +} + +ErrCode ServiceProxy::Finish() { return BError(BError::Codes::OK); } diff --git a/tests/mock/bundle_manager/include/mock_bundle_manager.h b/tests/mock/bundle_manager/include/mock_bundle_manager.h index b50908b42..bbd1638f4 100644 --- a/tests/mock/bundle_manager/include/mock_bundle_manager.h +++ b/tests/mock/bundle_manager/include/mock_bundle_manager.h @@ -56,6 +56,10 @@ public: int32_t flags, BundleInfo &bundleInfo, int32_t userId = Constants::UNSPECIFIED_USERID) override; + + virtual bool GetApplicationInfos(const ApplicationFlag flag, + int userId, + std::vector &appInfos) override; }; } // namespace AppExecFwk } // namespace OHOS diff --git a/tests/mock/bundle_manager/src/mock_bundle_manager.cpp b/tests/mock/bundle_manager/src/mock_bundle_manager.cpp index 4b397ee2a..ee5cca248 100644 --- a/tests/mock/bundle_manager/src/mock_bundle_manager.cpp +++ b/tests/mock/bundle_manager/src/mock_bundle_manager.cpp @@ -70,6 +70,16 @@ bool BundleMgrStub::GetBundleInfo(const string &bundleName, int32_t flags, Bundl return true; } +bool BundleMgrStub::GetApplicationInfos(const ApplicationFlag flag, int userId, vector &appInfos) +{ + GTEST_LOG_(INFO) << "GetApplicationInfos is ok"; + ApplicationInfo appInfo {}; + appInfo.bundleName = "com.example.app2backup"; + appInfo.versionName = "1.0.0"; + appInfos.push_back(appInfo); + return true; +} + BundleMgrClient::BundleMgrClient() {} BundleMgrClient::~BundleMgrClient() {} diff --git a/tests/mock/module_external/bms_adapter_mock.cpp b/tests/mock/module_external/bms_adapter_mock.cpp new file mode 100644 index 000000000..c7883a328 --- /dev/null +++ b/tests/mock/module_external/bms_adapter_mock.cpp @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2023 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 "module_external/bms_adapter.h" + +#include +#include + +#include "b_error/b_error.h" +#include "b_json/b_json_entity_extension_config.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +vector BundleMgrAdapter::GetBundleInfos() +{ + vector bundleInfos; + bundleInfos.emplace_back( + BJsonEntityCaps::BundleInfo {"com.example.app2backup", {}, {}, 0, true, "com.example.app2backup"}); + return bundleInfos; +} + +vector BundleMgrAdapter::GetBundleInfos(const vector &bundleNames) +{ + vector bundleInfos; + bundleInfos.emplace_back( + BJsonEntityCaps::BundleInfo {"com.example.app2backup", {}, {}, 0, true, "com.example.app2backup"}); + return bundleInfos; +} +} // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_external/sms_adapter_mock.cpp b/tests/mock/module_external/sms_adapter_mock.cpp new file mode 100644 index 000000000..151331d31 --- /dev/null +++ b/tests/mock/module_external/sms_adapter_mock.cpp @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2023 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 "module_external/sms_adapter.h" + +#include +#include + +#include "b_error/b_error.h" + +namespace OHOS::FileManagement::Backup { +using namespace std; + +StorageManager::BundleStats StorageMgrAdapter::GetBundleStats(const string &bundleName) +{ + StorageManager::BundleStats bundleStats; + return bundleStats; +} +} // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/service_mock.cpp b/tests/mock/module_ipc/service_mock.cpp index c324bd3fe..1af44b43d 100644 --- a/tests/mock/module_ipc/service_mock.cpp +++ b/tests/mock/module_ipc/service_mock.cpp @@ -42,12 +42,12 @@ string Service::VerifyCallerAndGetCallerName() return ""; } -ErrCode Service::InitRestoreSession(sptr remote, const vector &bundleNames) +ErrCode Service::InitRestoreSession(sptr remote) { return BError(BError::Codes::OK); } -ErrCode Service::InitBackupSession(sptr remote, UniqueFd fd, const vector &bundleNames) +ErrCode Service::InitBackupSession(sptr remote) { return BError(BError::Codes::OK); } @@ -72,12 +72,27 @@ ErrCode Service::AppDone(ErrCode errCode) return BError(BError::Codes::OK); } +ErrCode Service::AppendBundlesRestoreSession(UniqueFd fd, const std::vector &bundleNames) +{ + return BError(BError::Codes::OK); +} + +ErrCode Service::AppendBundlesBackupSession(const std::vector &bundleNames) +{ + return BError(BError::Codes::OK); +} + +ErrCode Service::Finish() +{ + return BError(BError::Codes::OK); +} + ErrCode Service::LaunchBackupExtension(const BundleName &bundleName) { return BError(BError::Codes::OK); } -ErrCode Service::GetExtFileName(string &bundleName, string &fileName) +ErrCode Service::GetFileHandle(const string &bundleName, const string &fileName) { return BError(BError::Codes::OK); } @@ -103,4 +118,8 @@ void Service::ClearSessionAndSchedInfo(const string &bundleName) {} void Service::VerifyCaller() {} void Service::VerifyCaller(IServiceReverse::Scenario scenario) {} + +void Service::OnAllBundlesFinished(ErrCode errCode) {} + +void Service::OnStartSched() {} } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/service_stub_mock.cpp b/tests/mock/module_ipc/service_stub_mock.cpp index 313a9d2e2..8581b2cd4 100644 --- a/tests/mock/module_ipc/service_stub_mock.cpp +++ b/tests/mock/module_ipc/service_stub_mock.cpp @@ -32,7 +32,10 @@ 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; } int32_t ServiceStub::OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) @@ -55,9 +58,7 @@ int32_t ServiceStub::CmdInitRestoreSession(MessageParcel &data, MessageParcel &r auto remote = data.ReadRemoteObject(); auto iremote = iface_cast(remote); - std::vector bundleNames; - data.ReadStringVector(&bundleNames); - int32_t res = InitRestoreSession(iremote, bundleNames); + int32_t res = InitRestoreSession(iremote); reply.WriteInt32(res); return BError(BError::Codes::OK); } @@ -67,12 +68,7 @@ int32_t ServiceStub::CmdInitBackupSession(MessageParcel &data, MessageParcel &re auto remote = data.ReadRemoteObject(); auto iremote = iface_cast(remote); - UniqueFd fd(data.ReadFileDescriptor()); - - std::vector bundleNames; - data.ReadStringVector(&bundleNames); - - int res = InitBackupSession(iremote, move(fd), bundleNames); + int res = InitBackupSession(iremote); reply.WriteInt32(res); return BError(BError::Codes::OK); } @@ -118,13 +114,41 @@ 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) { string bundleName; data.ReadString(bundleName); string fileName; data.ReadString(fileName); - return GetExtFileName(bundleName, fileName); + return GetFileHandle(bundleName, fileName); +} + +int32_t ServiceStub::CmdAppendBundlesRestoreSession(MessageParcel &data, MessageParcel &reply) +{ + UniqueFd fd(data.ReadFileDescriptor()); + std::vector bundleNames; + data.ReadStringVector(&bundleNames); + + int res = AppendBundlesRestoreSession(move(fd), bundleNames); + reply.WriteInt32(res); + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdAppendBundlesBackupSession(MessageParcel &data, MessageParcel &reply) +{ + std::vector bundleNames; + data.ReadStringVector(&bundleNames); + + int res = AppendBundlesBackupSession(bundleNames); + reply.WriteInt32(res); + return BError(BError::Codes::OK); +} + +int32_t ServiceStub::CmdFinish(MessageParcel &data, MessageParcel &reply) +{ + int res = Finish(); + reply.WriteInt32(res); + return BError(BError::Codes::OK); } } // namespace OHOS::FileManagement::Backup diff --git a/tests/mock/module_ipc/svc_session_manager_mock.cpp b/tests/mock/module_ipc/svc_session_manager_mock.cpp index e5105627c..6ee084174 100644 --- a/tests/mock/module_ipc/svc_session_manager_mock.cpp +++ b/tests/mock/module_ipc/svc_session_manager_mock.cpp @@ -33,6 +33,7 @@ namespace { constexpr int SCHED_NUM = 1; constexpr int FILE_NUM = 2; static int32_t g_nFileReadyNum = 0; +static int32_t g_nAllBundlesFinished = 0; } // namespace void SvcSessionManager::VerifyCallerAndScenario(uint32_t clientToken, IServiceReverse::Scenario scenario) const @@ -69,11 +70,6 @@ IServiceReverse::Scenario SvcSessionManager::GetScenario() return impl_.scenario; } -void SvcSessionManager::GetBundleExtNames(map &backupExtNameMap) -{ - GTEST_LOG_(INFO) << "GetBundleExtNames"; -} - bool SvcSessionManager::OnBunleFileReady(const string &bundleName, const string &fileName) { GTEST_LOG_(INFO) << "OnBunleFileReady"; @@ -114,9 +110,10 @@ wptr SvcSessionManager::GetExtConnection(const BundleName & return wptr(it->second.backUpConnection); } -void SvcSessionManager::InitExtConn(std::map &backupExtNameMap) +sptr SvcSessionManager::GetBackupExtAbility(const string &bundleName) { - GTEST_LOG_(INFO) << "InitExtConn"; + GTEST_LOG_(INFO) << "GetBackupExtAbility"; + return nullptr; } void SvcSessionManager::DumpInfo(const int fd, const std::vector &args) @@ -194,6 +191,35 @@ void SvcSessionManager::SetServiceSchedAction(const string &bundleName, BConstan string SvcSessionManager::GetBackupExtName(const string &bundleName) { GTEST_LOG_(INFO) << "GetBackupExtName " << bundleName; - return ""; + return "com.example.app2backup"; +} + +void SvcSessionManager::AppendBundles(const vector &bundleNames) +{ + GTEST_LOG_(INFO) << "AppendBundles"; + BackupExtInfo info {}; + info.backupExtName = "com.example.app2backup"; + impl_.backupExtNameMap.insert(make_pair("com.example.app2backup", info)); +} + +void SvcSessionManager::Start() {} + +void SvcSessionManager::Finish() {} + +bool SvcSessionManager::IsOnAllBundlesFinished() +{ + GTEST_LOG_(INFO) << "IsOnAllBundlesFinished"; + g_nAllBundlesFinished++; + if (g_nAllBundlesFinished % FILE_NUM == SCHED_NUM) { + GTEST_LOG_(INFO) << "IsOnAllBundlesFinished is true"; + return true; + } + GTEST_LOG_(INFO) << "IsOnAllBundlesFinished is false"; + return false; +} + +bool SvcSessionManager::IsOnOnStartSched() +{ + return true; } } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/mock/storage_manager/storage_manager_service_mock.h b/tests/mock/storage_manager/storage_manager_service_mock.h new file mode 100644 index 000000000..483c12a84 --- /dev/null +++ b/tests/mock/storage_manager/storage_manager_service_mock.h @@ -0,0 +1,225 @@ +/* + * Copyright (c) 2023 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 MOCK_STORAGE_MANAGER_SERVICE_MOCK_H +#define MOCK_STORAGE_MANAGER_SERVICE_MOCK_H + +#include + +#include "iremote_stub.h" +#include "istorage_manager.h" + +namespace OHOS { +namespace StorageManager { +class StorageManagerServiceMock : public IRemoteStub { +public: + int code_ = 0; + StorageManagerServiceMock() : code_(0) {} + virtual ~StorageManagerServiceMock() {} + + virtual int32_t GetBundleStats(std::string pkgName, BundleStats &bundleStats) override + { + GTEST_LOG_(INFO) << "GetBundleStats is ok"; + bundleStats.dataSize_ = 1; + return 0; + } + + virtual int32_t RemoveUser(int32_t userId, uint32_t flags) override + { + return 0; + } + + virtual int32_t PrepareAddUser(int32_t userId, uint32_t flags) override + { + return 0; + } + + virtual int32_t PrepareStartUser(int32_t userId) override + { + return 0; + } + + virtual int32_t GetFreeSizeOfVolume(std::string volumeUuid, int64_t &freeSize) override + { + return 0; + } + + virtual int32_t StopUser(int32_t userId) override + { + return 0; + } + + virtual int32_t GetTotalSizeOfVolume(std::string volumeUuid, int64_t &totalSize) override + { + return 0; + } + + virtual int32_t GetTotalSize(int64_t &totalSize) override + { + return 0; + } + + virtual int32_t GetSystemSize(int64_t &systemSize) override + { + return 0; + } + + virtual int32_t GetFreeSize(int64_t &freeSize) override + { + return 0; + } + + virtual int32_t GetUserStorageStats(int32_t userId, StorageStats &storageStats) override + { + return 0; + } + + virtual int32_t GetUserStorageStats(StorageStats &storageStats) override + { + return 0; + } + + virtual int32_t GetCurrentBundleStats(BundleStats &bundleStats) override + { + return 0; + } + + virtual int32_t NotifyVolumeMounted(std::string volumeId, + int fsType, + std::string fsUuid, + std::string path, + std::string description) override + { + return 0; + } + + virtual int32_t NotifyVolumeCreated(VolumeCore vc) override + { + return 0; + } + + virtual int32_t NotifyVolumeDestroyed(std::string volumeId) override + { + return 0; + } + + virtual int32_t Unmount(std::string volumeId) override + { + return 0; + } + + virtual int32_t GetAllVolumes(std::vector &vecOfVol) override + { + return 0; + } + + virtual int32_t Mount(std::string volumeId) override + { + return 0; + } + + virtual int32_t NotifyDiskCreated(Disk disk) override + { + return 0; + } + + virtual int32_t Partition(std::string diskId, int32_t type) override + { + return 0; + } + + virtual int32_t NotifyDiskDestroyed(std::string diskId) override + { + return 0; + } + + virtual int32_t GetAllDisks(std::vector &vecOfDisk) override + { + return 0; + } + + virtual int32_t GetVolumeById(std::string volumeId, VolumeExternal &vc) override + { + return 0; + } + + virtual int32_t GetVolumeByUuid(std::string fsUuid, VolumeExternal &vc) override + { + return 0; + } + + virtual int32_t SetVolumeDescription(std::string fsUuid, std::string description) override + { + return 0; + } + + virtual int32_t GetDiskById(std::string diskId, Disk &disk) override + { + return 0; + } + + virtual int32_t Format(std::string volumeId, std::string fsType) override + { + return 0; + } + + virtual int32_t GenerateUserKeys(uint32_t userId, uint32_t flags) override + { + return 0; + } + + virtual int32_t UpdateUserAuth(uint32_t userId, + const std::vector &token, + const std::vector &oldSecret, + const std::vector &newSecret) override + { + return 0; + } + + virtual int32_t DeleteUserKeys(uint32_t userId) override + { + return 0; + } + + virtual int32_t ActiveUserKey(uint32_t userId, + const std::vector &token, + const std::vector &secret) override + { + return 0; + } + + virtual int32_t UpdateKeyContext(uint32_t userId) override + { + return 0; + } + + virtual int32_t InactiveUserKey(uint32_t userId) override + { + return 0; + } + + virtual int32_t CreateShareFile(std::string uri, int32_t tokenId, int32_t flag) override + { + return 0; + } + + virtual int32_t DeleteShareFile(int32_t tokenId, std::vector sharePathList) override + { + return 0; + } +}; +} // namespace StorageManager +} // namespace OHOS +#endif // MOCK_STORAGE_MANAGER_SERVICE_MOCK_H \ No newline at end of file diff --git a/tests/moduletests/backup_kit_inner/b_session_backup_test.cpp b/tests/moduletests/backup_kit_inner/b_session_backup_test.cpp index 0f1f5a685..2e4990bfa 100644 --- a/tests/moduletests/backup_kit_inner/b_session_backup_test.cpp +++ b/tests/moduletests/backup_kit_inner/b_session_backup_test.cpp @@ -153,19 +153,18 @@ HWTEST_F(BSessionBackupTest, SUB_backup_b_session_backup_0300, testing::ext::Tes try { GTEST_LOG_(INFO) << "GetInstance is false"; SetMockGetInstance(false); - vector bundlesToBackup; - auto backupPtr = BSessionBackup::Init(UniqueFd(-1), bundlesToBackup, BSessionBackup::Callbacks {}); + auto backupPtr = BSessionBackup::Init(BSessionBackup::Callbacks {}); EXPECT_EQ(backupPtr, nullptr); GTEST_LOG_(INFO) << "GetInstance is true"; GTEST_LOG_(INFO) << "InitBackupSession is false"; SetMockGetInstance(true); SetMockInitBackupOrRestoreSession(false); - backupPtr = BSessionBackup::Init(UniqueFd(-1), bundlesToBackup, BSessionBackup::Callbacks {}); + backupPtr = BSessionBackup::Init(BSessionBackup::Callbacks {}); EXPECT_EQ(backupPtr, nullptr); GTEST_LOG_(INFO) << "InitBackupSession is true"; SetMockInitBackupOrRestoreSession(true); Init(); - backupPtr = BSessionBackup::Init(UniqueFd(-1), bundlesToBackup, callbacks_); + backupPtr = BSessionBackup::Init(callbacks_); EXPECT_NE(backupPtr, nullptr); } catch (...) { EXPECT_TRUE(false); @@ -215,9 +214,8 @@ HWTEST_F(BSessionBackupTest, SUB_backup_b_session_backup_0500, testing::ext::Tes try { SetMockGetInstance(true); SetMockLoadSystemAbility(true); - vector bundlesToBackup; Init(); - auto backupPtr = BSessionBackup::Init(UniqueFd(-1), bundlesToBackup, callbacks_); + auto backupPtr = BSessionBackup::Init(callbacks_); EXPECT_NE(backupPtr, nullptr); GTEST_LOG_(INFO) << "GetInstance is false"; @@ -226,7 +224,7 @@ HWTEST_F(BSessionBackupTest, SUB_backup_b_session_backup_0500, testing::ext::Tes SetMockGetInstance(true); SetMockLoadSystemAbility(true); - backupPtr = BSessionBackup::Init(UniqueFd(-1), bundlesToBackup, callbacks_); + backupPtr = BSessionBackup::Init(callbacks_); EXPECT_NE(backupPtr, nullptr); GTEST_LOG_(INFO) << "LoadSystemAbility is false"; diff --git a/tests/moduletests/backup_kit_inner/b_session_restore_test.cpp b/tests/moduletests/backup_kit_inner/b_session_restore_test.cpp index bdd3325ff..d00f90d0f 100644 --- a/tests/moduletests/backup_kit_inner/b_session_restore_test.cpp +++ b/tests/moduletests/backup_kit_inner/b_session_restore_test.cpp @@ -154,19 +154,19 @@ HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0300, testing::ext::T try { GTEST_LOG_(INFO) << "GetInstance is false"; SetMockGetInstance(false); - vector bundlesToBackup; - auto restorePtr = BSessionRestore::Init(bundlesToBackup, {}); + vector bundlesToRestore; + auto restorePtr = BSessionRestore::Init({}); EXPECT_EQ(restorePtr, nullptr); GTEST_LOG_(INFO) << "GetInstance is true"; GTEST_LOG_(INFO) << "InitBackupSession is false"; SetMockGetInstance(true); SetMockInitBackupOrRestoreSession(false); - restorePtr = BSessionRestore::Init(bundlesToBackup, {}); + restorePtr = BSessionRestore::Init({}); EXPECT_EQ(restorePtr, nullptr); GTEST_LOG_(INFO) << "InitBackupSession is true"; SetMockInitBackupOrRestoreSession(true); Init(); - restorePtr = BSessionRestore::Init(bundlesToBackup, callbacks_); + restorePtr = BSessionRestore::Init(callbacks_); EXPECT_NE(restorePtr, nullptr); } catch (...) { EXPECT_TRUE(false); @@ -175,34 +175,6 @@ HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0300, testing::ext::T GTEST_LOG_(INFO) << "BSessionRestoreTest-end SUB_backup_b_session_restore_0300"; } -/** - * @tc.number: SUB_backup_b_session_restore_0400 - * @tc.name: SUB_backup_b_session_restore_0400 - * @tc.desc: 测试GetLocalCapabilities接口 - * @tc.size: MEDIUM - * @tc.type: FUNC - * @tc.level Level 1 - * @tc.require: I6F3GV - */ -HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0400, testing::ext::TestSize.Level1) -{ - GTEST_LOG_(INFO) << "BSessionRestoreTest-begin SUB_backup_b_session_restore_0400"; - try { - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - auto fd = restorePtr_->GetLocalCapabilities(); - EXPECT_NE(fd, 0); - GTEST_LOG_(INFO) << "GetInstance is true"; - SetMockGetInstance(true); - fd = restorePtr_->GetLocalCapabilities(); - EXPECT_NE(fd, 0); - } catch (...) { - EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionRestoreTest-an exception occurred by GetLocalCapabilities."; - } - GTEST_LOG_(INFO) << "BSessionRestoreTest-end SUB_backup_b_session_restore_0400"; -} - /** * @tc.number: SUB_backup_b_session_restore_0500 * @tc.name: SUB_backup_b_session_restore_0500 @@ -235,7 +207,7 @@ HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0500, testing::ext::T /** * @tc.number: SUB_backup_b_session_restore_0600 * @tc.name: SUB_backup_b_session_restore_0600 - * @tc.desc: 测试GetExtFileName接口 + * @tc.desc: 测试GetFileHandle接口 * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 @@ -249,15 +221,15 @@ HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0600, testing::ext::T SetMockGetInstance(false); string bundleName = ""; string fileName = ""; - auto ret = restorePtr_->GetExtFileName(bundleName, fileName); + auto ret = restorePtr_->GetFileHandle(bundleName, fileName); EXPECT_NE(ret, ErrCode(BError::Codes::OK)); GTEST_LOG_(INFO) << "GetInstance is true"; SetMockGetInstance(true); - ret = restorePtr_->GetExtFileName(bundleName, fileName); + ret = restorePtr_->GetFileHandle(bundleName, fileName); EXPECT_EQ(ret, ErrCode(BError::Codes::OK)); } catch (...) { EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "BSessionRestoreTest-an exception occurred by GetExtFileName."; + GTEST_LOG_(INFO) << "BSessionRestoreTest-an exception occurred by GetFileHandle."; } GTEST_LOG_(INFO) << "BSessionRestoreTest-end SUB_backup_b_session_restore_0600"; } @@ -301,11 +273,10 @@ HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0800, testing::ext::T { GTEST_LOG_(INFO) << "BSessionRestoreTest-begin SUB_backup_b_session_restore_0800"; try { - vector bundlesToBackup; SetMockGetInstance(true); SetMockLoadSystemAbility(true); Init(); - auto restorePtr = BSessionRestore::Init(bundlesToBackup, callbacks_); + auto restorePtr = BSessionRestore::Init(callbacks_); EXPECT_NE(restorePtr, nullptr); GTEST_LOG_(INFO) << "GetInstance is false"; @@ -314,7 +285,7 @@ HWTEST_F(BSessionRestoreTest, SUB_backup_b_session_restore_0800, testing::ext::T SetMockGetInstance(true); SetMockLoadSystemAbility(true); - restorePtr = BSessionRestore::Init(bundlesToBackup, callbacks_); + restorePtr = BSessionRestore::Init(callbacks_); EXPECT_NE(restorePtr, nullptr); GTEST_LOG_(INFO) << "LoadSystemAbility is false"; diff --git a/tests/unittests/backup_api/backup_impl/BUILD.gn b/tests/unittests/backup_api/backup_impl/BUILD.gn index 2692698a1..ae43e6680 100644 --- a/tests/unittests/backup_api/backup_impl/BUILD.gn +++ b/tests/unittests/backup_api/backup_impl/BUILD.gn @@ -36,7 +36,7 @@ ohos_unittest("b_file_info_test") { } ohos_unittest("backup_sa_impl_test") { - module_out_path = "filemanagement/backup" + module_out_path = path_module_out_tests sources = [ "${path_backup_mock}/system_ability_manager/service_registry_mock.cpp", 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 5fe4f5057..c1e0faa1f 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 @@ -53,14 +53,12 @@ public: return BError(BError::Codes::OK); } - ErrCode InitRestoreSession(sptr remote, const std::vector &bundleNames) override + ErrCode InitRestoreSession(sptr remote) override { return BError(BError::Codes::OK); } - ErrCode InitBackupSession(sptr remote, - UniqueFd fd, - const std::vector &bundleNames) override + ErrCode InitBackupSession(sptr remote) override { return BError(BError::Codes::OK); } @@ -90,7 +88,22 @@ public: return BError(BError::Codes::OK); } - ErrCode GetExtFileName(std::string &bundleName, std::string &fileName) override + ErrCode GetFileHandle(const std::string &bundleName, const std::string &fileName) override + { + return BError(BError::Codes::OK); + } + + ErrCode AppendBundlesRestoreSession(UniqueFd fd, const std::vector &bundleNames) override + { + return BError(BError::Codes::OK); + } + + ErrCode AppendBundlesBackupSession(const std::vector &bundleNames) override + { + return BError(BError::Codes::OK); + } + + ErrCode Finish() override { return BError(BError::Codes::OK); } 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 417a1ecbb..76b785e77 100644 --- a/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp +++ b/tests/unittests/backup_api/backup_impl/service_proxy_test.cpp @@ -75,16 +75,13 @@ HWTEST_F(ServiceProxyTest, SUB_Service_proxy_InitRestoreSession_0100, testing::e { GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_InitRestoreSession_0100"; EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(2) + .Times(1) .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) .WillOnce(Return(EPERM)); - std::vector bundleNames; - int32_t result = proxy_->InitRestoreSession(remote_, bundleNames); + int32_t result = proxy_->InitRestoreSession(remote_); EXPECT_EQ(result, BError(BError::Codes::OK)); - result = proxy_->InitRestoreSession(remote_, bundleNames); - EXPECT_NE(result, BError(BError::Codes::OK)); - result = proxy_->InitRestoreSession(nullptr, bundleNames); + result = proxy_->InitRestoreSession(nullptr); EXPECT_NE(result, BError(BError::Codes::OK)); GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_InitRestoreSession_0100"; } @@ -102,22 +99,14 @@ HWTEST_F(ServiceProxyTest, SUB_Service_proxy_InitBackupSession_0100, testing::ex { GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_InitBackupSession_0100"; EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) - .Times(2) + .Times(1) .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) .WillOnce(Return(EPERM)); - std::vector bundleNames; - TestManager tm("BackupSession_GetFd_0100"); - std::string filePath = tm.GetRootDirCurTest().append(FILE_NAME); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); - int32_t result = proxy_->InitBackupSession(remote_, move(fd), bundleNames); + int32_t result = proxy_->InitBackupSession(remote_); EXPECT_EQ(result, BError(BError::Codes::OK)); - result = proxy_->InitRestoreSession(remote_, bundleNames); - EXPECT_NE(result, BError(BError::Codes::OK)); - result = proxy_->InitBackupSession(nullptr, move(fd), bundleNames); - EXPECT_NE(result, BError(BError::Codes::OK)); - result = proxy_->InitBackupSession(remote_, UniqueFd(-1), bundleNames); + result = proxy_->InitBackupSession(nullptr); EXPECT_NE(result, BError(BError::Codes::OK)); GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_InitBackupSession_0100"; } @@ -256,29 +245,108 @@ HWTEST_F(ServiceProxyTest, SUB_Service_proxy_AppDone_0100, testing::ext::TestSiz } /** - * @tc.number: SUB_Service_proxy_GetExtFileName_0100 - * @tc.name: SUB_Service_proxy_GetExtFileName_0100 - * @tc.desc: 测试 GetExtFileName 获取真实文件调用成功和失败 + * @tc.number: SUB_Service_proxy_GetFileHandle_0100 + * @tc.name: SUB_Service_proxy_GetFileHandle_0100 + * @tc.desc: 测试 GetFileHandle 获取真实文件调用成功和失败 * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 * @tc.require: I6F3GV */ -HWTEST_F(ServiceProxyTest, SUB_Service_proxy_GetExtFileName_0100, testing::ext::TestSize.Level1) +HWTEST_F(ServiceProxyTest, SUB_Service_proxy_GetFileHandle_0100, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_GetExtFileName_0100"; + GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_GetFileHandle_0100"; EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) .Times(2) .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) .WillOnce(Return(EPERM)); string bundleName = "com.example.app2backup"; string fileName = "1.tar"; - int32_t result = proxy_->GetExtFileName(bundleName, fileName); + int32_t result = proxy_->GetFileHandle(bundleName, fileName); + EXPECT_EQ(result, BError(BError::Codes::OK)); + + result = proxy_->GetFileHandle(bundleName, fileName); + EXPECT_NE(result, BError(BError::Codes::OK)); + GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_GetFileHandle_0100"; +} + +/** + * @tc.number: SUB_Service_proxy_AppendBundlesRestoreSession_0100 + * @tc.name: SUB_Service_proxy_AppendBundlesRestoreSession_0100 + * @tc.desc: 测试 AppendBundlesRestoreSession 获取真实文件调用成功和失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceProxyTest, SUB_Service_proxy_AppendBundlesRestoreSession_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_AppendBundlesRestoreSession_0100"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(1) + .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) + .WillOnce(Return(EPERM)); + + std::vector bundleNames; + TestManager tm("BackupSession_GetFd_0100"); + std::string filePath = tm.GetRootDirCurTest().append(FILE_NAME); + UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); + + int32_t result = proxy_->AppendBundlesRestoreSession(move(fd), bundleNames); + EXPECT_EQ(result, BError(BError::Codes::OK)); + result = proxy_->AppendBundlesRestoreSession(UniqueFd(-1), bundleNames); + EXPECT_NE(result, BError(BError::Codes::OK)); + GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_AppendBundlesRestoreSession_0100"; +} + +/** + * @tc.number: SUB_Service_proxy_AppendBundlesBackupSession_0100 + * @tc.name: SUB_Service_proxy_AppendBundlesBackupSession_0100 + * @tc.desc: 测试 AppendBundlesBackupSession 获取真实文件调用成功和失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceProxyTest, SUB_Service_proxy_AppendBundlesBackupSession_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_AppendBundlesBackupSession_0100"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(2) + .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) + .WillOnce(Return(EPERM)); + + std::vector bundleNames; + + int32_t result = proxy_->AppendBundlesBackupSession(bundleNames); EXPECT_EQ(result, BError(BError::Codes::OK)); + result = proxy_->AppendBundlesBackupSession(bundleNames); + EXPECT_NE(result, BError(BError::Codes::OK)); + GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_AppendBundlesBackupSession_0100"; +} + +/** + * @tc.number: SUB_Service_proxy_Finish_0100 + * @tc.name: SUB_Service_proxy_Finish_0100 + * @tc.desc: 测试 Finish 获取真实文件调用成功和失败 + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 1 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceProxyTest, SUB_Service_proxy_Finish_0100, testing::ext::TestSize.Level1) +{ + GTEST_LOG_(INFO) << "ServiceProxyTest-begin SUB_Service_proxy_Finish_0100"; + EXPECT_CALL(*mock_, SendRequest(_, _, _, _)) + .Times(2) + .WillOnce(Invoke(mock_.GetRefPtr(), &IServiceMock::InvokeSendRequest)) + .WillOnce(Return(EPERM)); - result = proxy_->GetExtFileName(bundleName, fileName); + int32_t result = proxy_->Finish(); + EXPECT_EQ(result, BError(BError::Codes::OK)); + result = proxy_->Finish(); EXPECT_NE(result, BError(BError::Codes::OK)); - GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_GetExtFileName_0100"; + GTEST_LOG_(INFO) << "ServiceProxyTest-end SUB_Service_proxy_Finish_0100"; } /** diff --git a/tests/unittests/backup_sa/module_ipc/BUILD.gn b/tests/unittests/backup_sa/module_ipc/BUILD.gn index 14d50d98c..e3296e51d 100644 --- a/tests/unittests/backup_sa/module_ipc/BUILD.gn +++ b/tests/unittests/backup_sa/module_ipc/BUILD.gn @@ -45,6 +45,7 @@ ohos_unittest("module_ipc_test") { "c_utils:utils", "safwk:system_ability_fwk", "samgr:samgr_proxy", + "storage_service:storage_manager_sa_proxy", ] use_exceptions = true @@ -61,6 +62,7 @@ ohos_unittest("backup_service_test") { sources += backup_mock_src sources += backup_mock_session_manager_src sources += backup_mock_scheduler_src + sources += backup_mock_module_external_src include_dirs = [ "${path_backup}/services/backup_sa/include", @@ -83,6 +85,7 @@ ohos_unittest("backup_service_test") { "init:libbegetutil", "safwk:system_ability_fwk", "samgr:samgr_proxy", + "storage_service:storage_manager_sa_proxy", ] use_exceptions = true @@ -100,6 +103,7 @@ ohos_unittest("backup_service_session_test") { sources += backup_mock_src sources += backup_mock_scheduler_src sources += backup_mock_service_src + sources += backup_mock_module_external_src include_dirs = [ "${path_backup}/services/backup_sa/include", @@ -107,6 +111,7 @@ ohos_unittest("backup_service_session_test") { "${path_backup}/tests/unittests/backup_api/backup_impl/include", "${path_base}/include", "${path_backup_mock}/bundle_manager/include", + "${path_backup_mock}/storage_manager", ] deps = [ @@ -124,6 +129,7 @@ ohos_unittest("backup_service_session_test") { "c_utils:utils", "safwk:system_ability_fwk", "samgr:samgr_proxy", + "storage_service:storage_manager_sa_proxy", ] use_exceptions = true @@ -159,6 +165,7 @@ ohos_unittest("backup_service_scheduler_test") { "app_file_service:backup_kit_inner", "safwk:system_ability_fwk", "samgr:samgr_proxy", + "storage_service:storage_manager_sa_proxy", ] use_exceptions = true 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 8a982e086..b52151eac 100644 --- a/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_stub_test.cpp @@ -40,15 +40,17 @@ const string FILE_NAME = "1.tar"; class MockService final : public ServiceStub { public: - MOCK_METHOD2(InitRestoreSession, ErrCode(sptr remote, const vector &bundleNames)); - MOCK_METHOD3(InitBackupSession, - ErrCode(sptr remote, UniqueFd fd, const vector &bundleNames)); + MOCK_METHOD1(InitRestoreSession, ErrCode(sptr remote)); + MOCK_METHOD1(InitBackupSession, ErrCode(sptr remote)); MOCK_METHOD0(Start, ErrCode()); MOCK_METHOD0(GetLocalCapabilities, UniqueFd()); MOCK_METHOD1(PublishFile, ErrCode(const BFileInfo &fileInfo)); MOCK_METHOD2(AppFileReady, ErrCode(const string &fileName, UniqueFd fd)); MOCK_METHOD1(AppDone, ErrCode(ErrCode errCode)); - MOCK_METHOD2(GetExtFileName, ErrCode(string &bundleName, string &fileName)); + MOCK_METHOD2(GetFileHandle, ErrCode(const string &bundleName, const string &fileName)); + MOCK_METHOD2(AppendBundlesRestoreSession, ErrCode(UniqueFd fd, const std::vector &bundleNames)); + MOCK_METHOD1(AppendBundlesBackupSession, ErrCode(const std::vector &bundleNames)); + MOCK_METHOD0(Finish, ErrCode()); UniqueFd InvokeGetLocalCapabilities() { if (bCapabilities_) { @@ -87,7 +89,7 @@ HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_InitRestoreSession_0100, tes GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_InitRestoreSession_0100"; try { MockService service; - EXPECT_CALL(service, InitRestoreSession(_, _)).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(service, InitRestoreSession(_)).WillOnce(Return(BError(BError::Codes::OK))); MessageParcel data; MessageParcel reply; MessageOption option; @@ -95,9 +97,6 @@ HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_InitRestoreSession_0100, tes EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); sptr remote = sptr(new ServiceReverseMock()); EXPECT_TRUE(data.WriteRemoteObject(remote->AsObject().GetRefPtr())); - vector bundleNames; - bundleNames.push_back(BUNDLE_NAME); - EXPECT_TRUE(data.WriteStringVector(bundleNames)); EXPECT_EQ(BError(BError::Codes::OK), service.OnRemoteRequest(IService::SERVICE_CMD_INIT_RESTORE_SESSION, data, reply, option)); @@ -123,31 +122,17 @@ HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_InitBackupSession_0100, test GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_InitBackupSession_0100"; try { MockService service; - EXPECT_CALL(service, InitBackupSession(_, _, _)).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(service, InitBackupSession(_)).WillOnce(Return(BError(BError::Codes::OK))); MessageParcel data; MessageParcel reply; MessageOption option; - - vector bundleNames; - bundleNames.push_back(BUNDLE_NAME); sptr remote = sptr(new ServiceReverseMock()); - TestManager tm("ServiceStub_GetFd_0100"); - std::string filePath = tm.GetRootDirCurTest().append(FILE_NAME); - UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); EXPECT_TRUE(data.WriteRemoteObject(remote->AsObject().GetRefPtr())); - EXPECT_TRUE(data.WriteFileDescriptor(fd)); - EXPECT_TRUE(data.WriteStringVector(bundleNames)); EXPECT_EQ(BError(BError::Codes::OK), service.OnRemoteRequest(IService::SERVICE_CMD_INIT_BACKUP_SESSION, data, reply, option)); - GTEST_LOG_(INFO) << "ServiceStubTest-CmdInitBackupSession Brances"; - MessageParcel brances; - EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); - EXPECT_TRUE(data.WriteRemoteObject(remote->AsObject().GetRefPtr())); - EXPECT_NE(BError(BError::Codes::OK), - service.OnRemoteRequest(IService::SERVICE_CMD_INIT_BACKUP_SESSION, brances, reply, option)); remote = nullptr; } catch (...) { EXPECT_TRUE(false); @@ -328,20 +313,20 @@ HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_AppDone_0100, testing::ext:: } /** - * @tc.number: SUB_backup_sa_ServiceStub_GetExtFileName_0100 - * @tc.name: SUB_backup_sa_ServiceStub_GetExtFileName_0100 - * @tc.desc: Test function of GetExtFileName interface for SUCCESS. + * @tc.number: SUB_backup_sa_ServiceStub_GetFileHandle_0100 + * @tc.name: SUB_backup_sa_ServiceStub_GetFileHandle_0100 + * @tc.desc: Test function of GetFileHandle interface for SUCCESS. * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 0 * @tc.require: I6F3GV */ -HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_GetExtFileName_0100, testing::ext::TestSize.Level0) +HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_GetFileHandle_0100, testing::ext::TestSize.Level0) { - GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_GetExtFileName_0100"; + GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_GetFileHandle_0100"; try { MockService service; - EXPECT_CALL(service, GetExtFileName(_, _)).WillOnce(Return(BError(BError::Codes::OK))); + EXPECT_CALL(service, GetFileHandle(_, _)).WillOnce(Return(BError(BError::Codes::OK))); MessageParcel data; MessageParcel reply; MessageOption option; @@ -351,12 +336,111 @@ HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_GetExtFileName_0100, testing EXPECT_TRUE(data.WriteString(BUNDLE_NAME)); EXPECT_TRUE(data.WriteString(FILE_NAME)); EXPECT_EQ(BError(BError::Codes::OK), - service.OnRemoteRequest(IService::SERVICE_CMD_GET_EXT_FILE_NAME, data, reply, option)); + service.OnRemoteRequest(IService::SERVICE_CMD_GET_FILE_NAME, data, reply, option)); EXPECT_NE(BError(BError::Codes::OK), service.OnRemoteRequest(3333, data, reply, option)); } catch (...) { EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by GetExtFileName."; + GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by GetFileHandle."; + } + GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_GetFileHandle_0100"; +} + +/** + * @tc.number: SUB_backup_sa_ServiceStub_AppendBundlesRestoreSession_0100 + * @tc.name: SUB_backup_sa_ServiceStub_AppendBundlesRestoreSession_0100 + * @tc.desc: Test function of AppendBundlesRestoreSession interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_AppendBundlesRestoreSession_0100, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_AppendBundlesRestoreSession_0100"; + try { + MockService service; + EXPECT_CALL(service, AppendBundlesRestoreSession(_, _)).WillOnce(Return(BError(BError::Codes::OK))); + MessageParcel data; + MessageParcel reply; + MessageOption option; + + vector bundleNames; + bundleNames.push_back(BUNDLE_NAME); + TestManager tm("ServiceStub_GetFd_0300"); + std::string filePath = tm.GetRootDirCurTest().append(FILE_NAME); + UniqueFd fd(open(filePath.data(), O_RDONLY | O_CREAT, S_IRUSR | S_IWUSR)); + + EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); + EXPECT_TRUE(data.WriteFileDescriptor(fd)); + EXPECT_TRUE(data.WriteStringVector(bundleNames)); + EXPECT_EQ(BError(BError::Codes::OK), + service.OnRemoteRequest(IService::SERVICE_CMD_APPEND_BUNDLES_RESTORE_SESSION, data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by AppendBundlesRestoreSession."; + } + GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_AppendBundlesRestoreSession_0100"; +} + +/** + * @tc.number: SUB_backup_sa_ServiceStub_AppendBundlesBackupSession_0100 + * @tc.name: SUB_backup_sa_ServiceStub_AppendBundlesBackupSession_0100 + * @tc.desc: Test function of AppendBundlesBackupSession interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_AppendBundlesBackupSession_0100, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_AppendBundlesBackupSession_0100"; + try { + MockService service; + EXPECT_CALL(service, AppendBundlesBackupSession(_)).WillOnce(Return(BError(BError::Codes::OK))); + MessageParcel data; + MessageParcel reply; + MessageOption option; + + vector bundleNames; + bundleNames.push_back(BUNDLE_NAME); + + EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); + EXPECT_TRUE(data.WriteStringVector(bundleNames)); + EXPECT_EQ(BError(BError::Codes::OK), + service.OnRemoteRequest(IService::SERVICE_CMD_APPEND_BUNDLES_BACKUP_SESSION, data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by AppendBundlesBackupSession."; + } + GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_AppendBundlesBackupSession_0100"; +} + +/** + * @tc.number: SUB_backup_sa_ServiceStub_Finish_0100 + * @tc.name: SUB_backup_sa_ServiceStub_Finish_0100 + * @tc.desc: Test function of AppendBundlesBackupSession interface for SUCCESS. + * @tc.size: MEDIUM + * @tc.type: FUNC + * @tc.level Level 0 + * @tc.require: I6F3GV + */ +HWTEST_F(ServiceStubTest, SUB_backup_sa_ServiceStub_Finish_0100, testing::ext::TestSize.Level0) +{ + GTEST_LOG_(INFO) << "ServiceStubTest-begin SUB_backup_sa_ServiceStub_Finish_0100"; + try { + MockService service; + EXPECT_CALL(service, Finish()).WillOnce(Return(BError(BError::Codes::OK))); + MessageParcel data; + MessageParcel reply; + MessageOption option; + + EXPECT_TRUE(data.WriteInterfaceToken(IService::GetDescriptor())); + EXPECT_EQ(BError(BError::Codes::OK), + service.OnRemoteRequest(IService::SERVICE_CMD_FINISH, data, reply, option)); + } catch (...) { + EXPECT_TRUE(false); + GTEST_LOG_(INFO) << "ServiceStubTest-an exception occurred by Finish."; } - GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_GetExtFileName_0100"; + GTEST_LOG_(INFO) << "ServiceStubTest-end SUB_backup_sa_ServiceStub_Finish_0100"; } } // namespace OHOS::FileManagement::Backup \ No newline at end of file diff --git a/tests/unittests/backup_sa/module_ipc/service_test.cpp b/tests/unittests/backup_sa/module_ipc/service_test.cpp index 6e621555d..b3c4f11f6 100644 --- a/tests/unittests/backup_sa/module_ipc/service_test.cpp +++ b/tests/unittests/backup_sa/module_ipc/service_test.cpp @@ -67,11 +67,21 @@ ErrCode ServiceTest::Init(IServiceReverse::Scenario scenario) bundleNames.emplace_back(BUNDLE_NAME); ErrCode ret = 0; if (scenario == IServiceReverse::Scenario::RESTORE) { - ret = servicePtr_->InitRestoreSession(remote_, bundleNames); - } else if (scenario == IServiceReverse::Scenario::BACKUP) { UniqueFd fd = servicePtr_->GetLocalCapabilities(); EXPECT_GT(fd, BError(BError::Codes::OK)); - ret = servicePtr_->InitBackupSession(remote_, move(fd), bundleNames); + ret = servicePtr_->InitRestoreSession(remote_); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + ret = servicePtr_->AppendBundlesRestoreSession(move(fd), bundleNames); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + ret = servicePtr_->Finish(); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + } else if (scenario == IServiceReverse::Scenario::BACKUP) { + ret = servicePtr_->InitBackupSession(remote_); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + ret = servicePtr_->AppendBundlesBackupSession(bundleNames); + EXPECT_EQ(ret, BError(BError::Codes::OK)); + ret = servicePtr_->Finish(); + EXPECT_EQ(ret, BError(BError::Codes::OK)); } return ret; } @@ -162,7 +172,7 @@ HWTEST_F(ServiceTest, SUB_Service_PublishFile_0100, testing::ext::TestSize.Level GTEST_LOG_(INFO) << "ServiceTest-PublishFile Branches"; fileInfo.fileName = "test"; ret = servicePtr_->PublishFile(fileInfo); - EXPECT_EQ(ret, BError(BError::Codes::OK)); + EXPECT_NE(ret, BError(BError::Codes::OK)); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by PublishFile."; @@ -260,30 +270,30 @@ HWTEST_F(ServiceTest, SUB_Service_LaunchBackupExtension_0100, testing::ext::Test } /** - * @tc.number: SUB_Service_GetExtFileName_0100 - * @tc.name: SUB_Service_GetExtFileName_0100 - * @tc.desc: 测试 GetExtFileName 接口 + * @tc.number: SUB_Service_GetFileHandle_0100 + * @tc.name: SUB_Service_GetFileHandle_0100 + * @tc.desc: 测试 GetFileHandle 接口 * @tc.size: MEDIUM * @tc.type: FUNC * @tc.level Level 1 * @tc.require: I6F3GV */ -HWTEST_F(ServiceTest, SUB_Service_GetExtFileName_0100, testing::ext::TestSize.Level1) +HWTEST_F(ServiceTest, SUB_Service_GetFileHandle_0100, testing::ext::TestSize.Level1) { - GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_GetExtFileName_0100"; + GTEST_LOG_(INFO) << "ServiceTest-begin SUB_Service_GetFileHandle_0100"; try { ErrCode ret = Init(IServiceReverse::Scenario::RESTORE); EXPECT_EQ(ret, BError(BError::Codes::OK)); string bundleName = BUNDLE_NAME; string fileName = FILE_NAME; - ret = servicePtr_->GetExtFileName(bundleName, fileName); + ret = servicePtr_->GetFileHandle(bundleName, fileName); EXPECT_EQ(ret, BError(BError::Codes::OK)); } catch (...) { EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetExtFileName."; + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetFileHandle."; } - GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetExtFileName_0100"; + GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_GetFileHandle_0100"; } /** @@ -311,7 +321,7 @@ HWTEST_F(ServiceTest, SUB_Service_OnBackupExtensionDied_0100, testing::ext::Test servicePtr_->OnBackupExtensionDied(move(bundleName), BError(BError::Codes::OK)); } catch (...) { EXPECT_TRUE(false); - GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetExtFileName."; + GTEST_LOG_(INFO) << "ServiceTest-an exception occurred by GetFileHandle."; } GTEST_LOG_(INFO) << "ServiceTest-end SUB_Service_OnBackupExtensionDied_0100"; } 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 de055dc42..76c779487 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 @@ -72,19 +72,12 @@ void SvcSessionManagerTest::Init(IServiceReverse::Scenario scenario) vector bundleNames; map backupExtNameMap; bundleNames.emplace_back(BUNDLE_NAME); - auto setBackupExtNameMap = [](const string &bundleName) { - BackupExtInfo info {}; - info.backupExtName = BUNDLE_NAME; - info.receExtManageJson = false; - info.receExtAppDone = false; - return make_pair(bundleName, info); - }; - transform(bundleNames.begin(), bundleNames.end(), inserter(backupExtNameMap, backupExtNameMap.end()), - setBackupExtNameMap); - sessionManagerPtr_->Active({.clientToken = CLIENT_TOKEN_ID, - .scenario = scenario, - .backupExtNameMap = move(backupExtNameMap), - .clientProxy = remote_}); + sessionManagerPtr_->Active( + {.clientToken = CLIENT_TOKEN_ID, .scenario = scenario, .backupExtNameMap = {}, .clientProxy = remote_}); + sessionManagerPtr_->IsOnAllBundlesFinished(); + sessionManagerPtr_->AppendBundles(bundleNames); + sessionManagerPtr_->Finish(); + sessionManagerPtr_->IsOnAllBundlesFinished(); } /** diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_backup_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_backup_test.cpp index b0cf9d9f0..a1ebbfcdd 100644 --- a/tests/unittests/backup_tools/backup_tool/tools_op_backup_test.cpp +++ b/tests/unittests/backup_tools/backup_tool/tools_op_backup_test.cpp @@ -70,14 +70,6 @@ HWTEST_F(ToolsOpBackupTest, SUB_backup_tools_op_backup_0100, testing::ext::TestS auto ret = matchedOp->Execute(mapArgToVal); EXPECT_EQ(ret, 0); } - - GTEST_LOG_(INFO) << "GetInstance is false"; - SetMockGetInstance(false); - if (matchedOp != opeartions.end()) { - auto ret = matchedOp->Execute(mapArgToVal); - EXPECT_NE(ret, 0); - } - SetMockGetInstance(true); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ToolsOpBackupTest-an exception occurred by construction."; diff --git a/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp b/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp index 97751fe3d..0ff779c2b 100644 --- a/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp +++ b/tests/unittests/backup_tools/backup_tool/tools_op_restore_test.cpp @@ -78,16 +78,6 @@ HWTEST_F(ToolsOpRestoreTest, SUB_backup_tools_op_restore_0100, testing::ext::Tes auto ret = matchedOp->Execute(mapArgToVal); EXPECT_EQ(ret, 0); } - - GTEST_LOG_(INFO) << "GetLocalCapabilities is false"; - mapArgToVal.clear(); - mapArgToVal.insert(make_pair("pathCapFile", path)); - vector bundleVec = {"test"}; - mapArgToVal.insert(make_pair("bundles", bundleVec)); - if (matchedOp != opeartions.end()) { - auto ret = matchedOp->Execute(mapArgToVal); - EXPECT_NE(ret, 0); - } } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "ToolsOpRestoreTest-an exception occurred by construction."; diff --git a/tests/unittests/backup_utils/BUILD.gn b/tests/unittests/backup_utils/BUILD.gn index 9da04ca4c..3e7a4d4bc 100644 --- a/tests/unittests/backup_utils/BUILD.gn +++ b/tests/unittests/backup_utils/BUILD.gn @@ -79,7 +79,10 @@ ohos_unittest("b_tarball_cmdline_test") { "${path_backup}/utils/include", ] - deps = [ "${path_backup}/tests/utils:backup_test_utils" ] + deps = [ + "${path_backup}/tests/utils:backup_test_utils", + "${path_backup}/utils/:backup_utils", + ] external_deps = [ "c_utils:utils" ] use_exceptions = true diff --git a/tests/unittests/backup_utils/b_json/b_json_cached_entity_test.cpp b/tests/unittests/backup_utils/b_json/b_json_cached_entity_test.cpp index 5e8f89c8a..2718028c1 100644 --- a/tests/unittests/backup_utils/b_json/b_json_cached_entity_test.cpp +++ b/tests/unittests/backup_utils/b_json/b_json_cached_entity_test.cpp @@ -104,11 +104,17 @@ HWTEST_F(BJsonCachedEntityTest, b_json_Persist_0100, testing::ext::TestSize.Leve std::string filePath = path + ".json"; BJsonCachedEntity jce(UniqueFd(open(filePath.data(), O_RDWR | O_CREAT, 0600))); auto cache = jce.Structuralize(); - uint64_t space = 100; - cache.SetFreeDiskSpace(space); + vector bundleInfos; + bundleInfos.emplace_back(BJsonEntityCaps::BundleInfo {"com.example.app2backup", 1000000, "1.0.0", 0, true, + "BackupExtensionAbility"}); + cache.SetBundleInfos(bundleInfos); + cache.SetSystemFullName("OpenHarmony-4.0.5.3(Canary1)"); + cache.SetDeviceType("default"); jce.Persist(); - uint64_t result = cache.GetFreeDiskSpace(); - EXPECT_EQ(result, space); + auto infos = cache.GetBundleInfos(); + EXPECT_EQ(infos.size(), 1); + EXPECT_EQ(cache.GetDeviceType(), "default"); + EXPECT_EQ(cache.GetSystemFullName(), "OpenHarmony-4.0.5.3(Canary1)"); } catch (...) { EXPECT_TRUE(false); GTEST_LOG_(INFO) << "BJsonCachedEntityTest-an exception occurred."; diff --git a/tools/backup_tool/src/tools_op_backup.cpp b/tools/backup_tool/src/tools_op_backup.cpp index 72f281865..0effda0b2 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() @@ -161,6 +165,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 +211,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 +233,22 @@ static int32_t InitPathCapFile(const string &isLocal, const string &pathCapFile, FinishTrace(HITRACE_TAG_FILEMANAGEMENT); return -EPERM; } + int ret = ctx->session_->AppendBundles(bundleNames); + if (ret != 0) { + printf("backup append bundles error: %d", ret); + throw BError(BError::Codes::TOOL_INVAL_ARG, "backup append bundles error"); + } + ctx->SetBundleFinishedCount(bundleNames.size()); - int ret = ctx->session_->Start(); + ret = ctx->session_->Start(); if (ret != 0) { throw BError(BError::Codes::TOOL_INVAL_ARG, "backup start error"); } + + ret = ctx->session_->Finish(); + if (ret != 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, "backup finish error"); + } ctx->Wait(); FinishTrace(HITRACE_TAG_FILEMANAGEMENT); return 0; @@ -260,8 +260,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..fa3460c4f 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() @@ -166,13 +169,17 @@ static void OnBundleFinished(shared_ptr ctx, ErrCode err, const BundleN 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 +208,58 @@ 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(); + ret = ctx->session_->Start(); if (ret != 0) { throw BError(BError::Codes::TOOL_INVAL_ARG, "restore start error"); } + + ret = ctx->session_->Finish(); + if (ret != 0) { + throw BError(BError::Codes::TOOL_INVAL_ARG, "backup finish error"); + } ctx->Wait(); return 0; } @@ -265,7 +269,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/BUILD.gn b/utils/BUILD.gn index e05117dfb..2bc20ad1b 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -25,6 +25,10 @@ config("utils_public_config") { include_dirs = [ "include", "${path_base}/include", + "${path_filemgmt_libn}/include", + "${path_napi}/interfaces/inner_api", + "${path_napi}/interfaces/kits", + "//third_party/node/src", ] } diff --git a/utils/include/b_error/b_error.h b/utils/include/b_error/b_error.h index e12434f65..3b84ad25a 100644 --- a/utils/include/b_error/b_error.h +++ b/utils/include/b_error/b_error.h @@ -30,6 +30,8 @@ #include #include +#include "n_error.h" + #if __has_builtin(__builtin_FILE) && __has_builtin(__builtin_LINE) && __has_builtin(__builtin_FUNCTION) #define DEFINE_SOURCE_LOCATION \ int lineNo = __builtin_LINE(), const char *fileName = __builtin_FILE(), \ @@ -39,6 +41,8 @@ #endif namespace OHOS::FileManagement::Backup { +using ErrCode = int; + class BError : public std::exception { public: /** @@ -85,14 +89,7 @@ public: * * @return int 标注错误码 */ - int GetCode() const - { - if (code_ == Codes::OK) { - return 0; - } else { - return -1 * (static_cast(code_) | ErrCodeOffset(SUBSYS_FILEMANAGEMENT, codeSubsystem_)); - } - } + int GetCode() const; /** * @brief 返回原始错误码 @@ -208,8 +205,48 @@ private: {Codes::EXT_BROKEN_IPC, "Extension failed to do IPC"}, }; + static inline const std::map errCodeTable_ { + {static_cast(Codes::OK), static_cast(Codes::OK)}, + {static_cast(Codes::UTILS_INVAL_JSON_ENTITY), LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {static_cast(Codes::UTILS_INVAL_FILE_HANDLE), LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {static_cast(Codes::UTILS_INVAL_TARBALL_ARG), LibN::ErrCodeSuffixOfFileIO::E_UKERR}, + {static_cast(Codes::UTILS_INVAL_PROCESS_ARG), LibN::ErrCodeSuffixOfFileIO::E_UKERR}, + {static_cast(Codes::UTILS_INTERRUPTED_PROCESS), LibN::ErrCodeSuffixOfFileIO::E_UKERR}, + {static_cast(Codes::TOOL_INVAL_ARG), LibN::ErrCodeSuffixOfFileIO::E_UKERR}, + {static_cast(Codes::SA_INVAL_ARG), LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {static_cast(Codes::SA_BROKEN_IPC), LibN::ErrCodeSuffixOfStorageService::E_IPCSS}, + {static_cast(Codes::SA_REFUSED_ACT), LibN::ErrCodeSuffixOfFileIO::E_PERM}, + {static_cast(Codes::SA_BROKEN_ROOT_DIR), LibN::ErrCodeSuffixOfFileIO::E_UKERR}, + {static_cast(Codes::SDK_INVAL_ARG), LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {static_cast(Codes::SDK_BROKEN_IPC), LibN::ErrCodeSuffixOfStorageService::E_IPCSS}, + {static_cast(Codes::SDK_MIXED_SCENARIO), LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {static_cast(Codes::EXT_INVAL_ARG), LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {static_cast(Codes::EXT_BROKEN_FRAMEWORK), LibN::ErrCodeSuffixOfFileIO::E_UKERR}, + {static_cast(Codes::EXT_BROKEN_BACKUP_SA), LibN::ErrCodeSuffixOfStorageService::E_IPCSS}, + {static_cast(Codes::EXT_BROKEN_IPC), LibN::ErrCodeSuffixOfStorageService::E_IPCSS}, + {LibN::ErrCodeSuffixOfStorageService::E_IPCSS, LibN::ErrCodeSuffixOfStorageService::E_IPCSS}, + {LibN::ErrCodeSuffixOfFileIO::E_PERM, LibN::ErrCodeSuffixOfFileIO::E_PERM}, + {LibN::ErrCodeSuffixOfFileIO::E_INVAL, LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {LibN::ErrCodeSuffixOfFileIO::E_UKERR, LibN::ErrCodeSuffixOfFileIO::E_UKERR}, + {LibN::ErrCodeSuffixOfFileIO::E_NOMEM, LibN::ErrCodeSuffixOfFileIO::E_NOMEM}, + {LibN::ErrCodeSuffixOfFileIO::E_IO, LibN::ErrCodeSuffixOfFileIO::E_IO}, + {LibN::ErrCodeSuffixOfFileIO::E_NOSPC, LibN::ErrCodeSuffixOfFileIO::E_NOSPC}, + {ENOMEM, LibN::ErrCodeSuffixOfFileIO::E_NOMEM}, + {EIO, LibN::ErrCodeSuffixOfFileIO::E_IO}, + {ENOSPC, LibN::ErrCodeSuffixOfFileIO::E_NOSPC}, + {EBADF, LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {EEXIST, LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {EROFS, LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {ENAMETOOLONG, LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {ENOENT, LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {ENOTDIR, LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {EBADFD, LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {EISDIR, LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {EINVAL, LibN::ErrCodeSuffixOfFileIO::E_INVAL}, + {EPERM, LibN::ErrCodeSuffixOfFileIO::E_PERM}, + }; + private: - const int codeSubsystem_ {1}; Codes code_ {Codes::OK}; std::string msg_; diff --git a/utils/include/b_json/b_json_entity_caps.h b/utils/include/b_json/b_json_entity_caps.h index 7c1c7625a..226b8dcf1 100644 --- a/utils/include/b_json/b_json_entity_caps.h +++ b/utils/include/b_json/b_json_entity_caps.h @@ -22,51 +22,84 @@ namespace OHOS::FileManagement::Backup { class BJsonEntityCaps : public BJsonEntity { public: - uint64_t GetFreeDiskSpace() - { - if (!obj_ || !obj_.isMember("freeDiskSpace") || !obj_["freeDiskSpace"].isUInt64()) { - HILOGE("Failed to init field FreeDiskSpace"); - return 0; - } - - return obj_["freeDiskSpace"].asUInt64(); - } + struct BundleInfo { + std::string name; + uint32_t versionCode; + std::string versionName; + int64_t spaceOccupied; + bool allToBackup; + std::string extensionName; + }; - void SetFreeDiskSpace(uint64_t freeDiskSpace) +public: + void SetSystemFullName(std::string systemFullName) { - obj_["freeDiskSpace"] = freeDiskSpace; + obj_["systemFullName"] = systemFullName; } - void SetOSFullName(std::string osFullName) + void SetDeviceType(std::string deviceType) { - obj_["OSFullName"] = osFullName; + obj_["deviceType"] = deviceType; } - void SetDeviceType(std::string deviceType) + void SetBundleInfos(std::vector bundleInfos) { - obj_["deviceType"] = deviceType; + if (obj_.isMember("bundleInfos")) { + obj_["bundleInfos"].clear(); + } + for (const auto &item : bundleInfos) { + Json::Value arrObj; + arrObj["name"] = item.name; + arrObj["versionCode"] = item.versionCode; + arrObj["versionName"] = item.versionName; + arrObj["spaceOccupied"] = item.spaceOccupied; + arrObj["allToBackup"] = item.allToBackup; + arrObj["extensionName"] = item.extensionName; + obj_["bundleInfos"].append(arrObj); + } } - std::string GetOSFullName() + std::string GetSystemFullName() { - if (!obj_ || !obj_.isMember("OSFullName") || !obj_["OSFullName"].isString()) { - HILOGE("Failed to get field OSFullName"); + if (!obj_ || !obj_.isMember("systemFullName") || !obj_["systemFullName"].isString()) { + HILOGI("Failed to get field systemFullName"); return ""; } - return obj_["OSFullName"].asString(); + return obj_["systemFullName"].asString(); } std::string GetDeviceType() { if (!obj_ || !obj_.isMember("deviceType") || !obj_["deviceType"].isString()) { - HILOGE("Failed to get field deviceType"); + HILOGI("Failed to get field deviceType"); return ""; } return obj_["deviceType"].asString(); } + std::vector GetBundleInfos() + { + if (!obj_ || !obj_.isMember("bundleInfos") || !obj_["bundleInfos"].isArray()) { + HILOGI("Failed to get field get bundleInfos"); + return {}; + } + std::vector bundleInfos; + for (const auto &item : obj_["bundleInfos"]) { + if (!item || !item["name"].isString() || !item["versionCode"].isUInt() || !item["versionName"].isString() || + !item["spaceOccupied"].isInt64() || !item["allToBackup"].isBool() || + !item["extensionName"].isString()) { + HILOGI("Failed to get field bundleInfos, type error"); + return {}; + } + bundleInfos.emplace_back(BundleInfo {item["name"].asString(), item["versionCode"].asUInt(), + item["versionName"].asString(), item["spaceOccupied"].asInt64(), + item["allToBackup"].asBool(), item["extensionName"].asString()}); + } + return bundleInfos; + } + public: /** * @brief 构造方法,具备T(Json::Value&, std::any)能力的构造函数 @@ -76,7 +109,7 @@ public: */ explicit BJsonEntityCaps(Json::Value &obj, std::any option = std::any()) : BJsonEntity(obj, option) { - SetFreeDiskSpace(GetFreeDiskSpace()); + SetBundleInfos(GetBundleInfos()); } BJsonEntityCaps() = delete; diff --git a/utils/src/b_error/b_error.cpp b/utils/src/b_error/b_error.cpp index f9745d5d8..41b916390 100644 --- a/utils/src/b_error/b_error.cpp +++ b/utils/src/b_error/b_error.cpp @@ -64,4 +64,12 @@ ErrCode BError::ExceptionCatcherLocked(std::function callBack) return EPERM; } } + +int BError::GetCode() const +{ + if (errCodeTable_.find(abs(static_cast(GetRawCode()))) != errCodeTable_.end()) { + return errCodeTable_.at(abs(static_cast(GetRawCode()))); + } + return errCodeTable_.at(LibN::ErrCodeSuffixOfFileIO::E_UKERR); +} } // namespace OHOS::FileManagement::Backup \ No newline at end of file -- Gitee