diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp index 9437ee8ac0aef5baf9bc0ff78cc3c48e206e0fa7..01c16a2390e7e71e399c2ca77ad720c2c12b3760 100644 --- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.cpp @@ -73,6 +73,11 @@ void RouteHeadHandlerImpl::Init() userId_ = DEFAULT_USERID; } } + if (appId_ == Bootstrap::GetInstance().GetProcessLabel() && storeId_ != Bootstrap::GetInstance().GetMetaDBName()) { + int foregroundUserId = 0; + AccountDelegate::GetInstance()->QueryForegroundUserId(foregroundUserId); + userId_ = std::to_string(foregroundUserId); + } SessionPoint localPoint { DmAdapter::GetInstance().GetLocalDevice().uuid, static_cast(atoi(userId_.c_str())), appId_, storeId_, AccountDelegate::GetInstance()->GetCurrentAccountId() }; @@ -96,7 +101,7 @@ DistributedDB::DBStatus RouteHeadHandlerImpl::GetHeadDataSize(uint32_t &headSize { ZLOGD("begin"); headSize = 0; - if (appId_ == Bootstrap::GetInstance().GetProcessLabel()) { + if (appId_ == Bootstrap::GetInstance().GetProcessLabel() && storeId_ == Bootstrap::GetInstance().GetMetaDBName()) { ZLOGI("meta data permitted"); return DistributedDB::OK; } @@ -123,6 +128,11 @@ DistributedDB::DBStatus RouteHeadHandlerImpl::GetHeadDataSize(uint32_t &headSize ZLOGI("ignore older version device"); return DistributedDB::OK; } + if (appId_ == Bootstrap::GetInstance().GetProcessLabel() && storeId_ != Bootstrap::GetInstance().GetMetaDBName() + && peerCap.version < CapMetaData::UDMF_AND_OBJECT_VERSION) { + ZLOGI("ignore older version device for udmf or object"); + return DistributedDB::OK; + } if (!session_.IsValid()) { ZLOGI("no valid session to peer device"); return DistributedDB::DB_ERROR; @@ -274,6 +284,19 @@ bool RouteHeadHandlerImpl::ParseHeadDataLen(const uint8_t *data, uint32_t totalL ZLOGI("other type device received. device:%{public}s", Anonymous::Change(device).c_str()); return true; } + + bool flag = false; + auto peerCap = UpgradeManager::GetInstance().GetCapability(device, flag); + if (!flag) { + ZLOGI("get peer cap failed"); + return false; + } + if (appId_ == Bootstrap::GetInstance().GetProcessLabel() && storeId_ != Bootstrap::GetInstance().GetMetaDBName() + && peerCap.version < CapMetaData::UDMF_AND_OBJECT_VERSION) { + ZLOGI("ignore older version device for udmf or object"); + return false; + } + RouteHead head = { 0 }; auto ret = UnPackDataHead(data, totalLen, head); headSize = ret ? sizeof(RouteHead) + head.dataLen : 0; diff --git a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h index 75331a3541f8835cc05c5b0b183b9bd4c8f74681..85611780bd5256677d1d59686296a4a67622bbbc 100644 --- a/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h +++ b/services/distributeddataservice/app/src/session_manager/route_head_handler_impl.h @@ -92,7 +92,6 @@ private: bool UnPackStoreId(uint8_t **data, uint32_t leftSize); bool UnPackAccountId(uint8_t **data, uint32_t leftSize); std::string ParseStoreId(const std::string &deviceId, const std::string &label); - std::string userId_; std::string appId_; std::string storeId_; diff --git a/services/distributeddataservice/app/test/BUILD.gn b/services/distributeddataservice/app/test/BUILD.gn index bccc0a52501adb4761e6c27811bedc2f29a826d6..61b270ec54c5efb48038d7128bac23fdcb1c44e2 100644 --- a/services/distributeddataservice/app/test/BUILD.gn +++ b/services/distributeddataservice/app/test/BUILD.gn @@ -375,6 +375,106 @@ ohos_unittest("UpgradeManagerTest") { part_name = "datamgr_service" } +ohos_unittest("RouteHeadHandlerImplTest") { + module_out_path = module_output_path + + include_dirs = [ + "${data_service_path}/adapter/include/permission", + "${data_service_path}/adapter/include/account", + "${data_service_path}/adapter/include", + "${data_service_path}/adapter/include/utils", + "${data_service_path}/framework/include", + "${data_service_path}/service/bootstrap/include", + "${data_service_path}/service/common", + "${data_service_path}/service/config/include", + "${data_service_path}/service/crypto/include", + "${data_service_path}/service/data_share/common", + "${data_service_path}/service/directory/include", + "${data_service_path}/service/permission/include", + "${data_service_path}/service/matrix/include", + "${data_service_path}/app/src", + "${data_service_path}/app/src/session_manager", + "${data_service_path}/service/kvdb", + "${data_service_path}/service/test/mock", + "../include", + "../src", + "../src/security", + "unittest", + "../src/installer", + "../../service/backup/include", + "../../../../interfaces/innerkits/distributeddata", + "../../service/dumper/include", + "${data_service_path}/adapter/include/communicator", + ] + + sources = [ + "../src/kvstore_meta_manager.cpp", + "../src/session_manager/route_head_handler_impl.cpp", + "../src/session_manager/session_manager.cpp", + "../src/session_manager/upgrade_manager.cpp", + "unittest/route_head_handler_impl_test.cpp", + ] + + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + blocklist = "${datamgr_service_path}/cfi_blocklist.txt" + } + + cflags_cc = [ "-DUT_TEST" ] + + external_deps = [ + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "c_utils:utils", + "dataclassification:data_transit_mgr", + "device_auth:deviceauth_sdk", + "device_manager:devicemanagersdk", + "file_api:securitylabel", + "googletest:gmock", + "googletest:gtest_main", + "hilog:libhilog", + "hisysevent:libhisysevent", + "ipc:ipc_core", + "cJSON:cjson", + "kv_store:distributeddata_inner", + "kv_store:distributeddata_mgr", + "kv_store:distributeddb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + if (datamgr_service_power) { + external_deps += [ + "battery_manager:batterysrv_client", + "power_manager:powermgr_client", + ] + } + + deps = [ + "${data_service_path}/adapter/utils:distributeddata_utils", + "${data_service_path}/app/src/checker:distributeddata_checker", + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", + "${data_service_path}/service/test/mock:distributeddata_mock_static", + ] + + cflags = [ + "-Werror", + "-Dprivate=public", + "-Dprotected=public", + ] + ldflags = [ "-Wl,--whole-archive" ] + defines = [ + "TEST_ON_DEVICE", + "OPENSSL_SUPPRESS_DEPRECATED", + ] + + part_name = "datamgr_service" +} + ############################################################################### group("unittest") { @@ -387,5 +487,6 @@ group("unittest") { ":KvStoreDataServiceTest", ":SessionManagerTest", ":UpgradeManagerTest", + ":RouteHeadHandlerImplTest", ] } \ No newline at end of file diff --git a/services/distributeddataservice/app/test/unittest/route_head_handler_impl_test.cpp b/services/distributeddataservice/app/test/unittest/route_head_handler_impl_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..905ce16063b3bfd425c22a2561a9984feb674818 --- /dev/null +++ b/services/distributeddataservice/app/test/unittest/route_head_handler_impl_test.cpp @@ -0,0 +1,235 @@ +/* + * Copyright (c) 2022 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 "session_manager/session_manager.h" + +#include + +#include "accesstoken_kit.h" +#include "account_delegate_mock.h" +#include "auth_delegate_mock.h" +#include "bootstrap.h" +#include "device_manager_adapter.h" +#include "device_manager_adapter_mock.h" +#include "gtest/gtest.h" +#include +#include "meta_data_manager_mock.h" +#include "metadata/meta_data_manager.h" +#include "metadata/store_meta_data.h" +#include "nativetoken_kit.h" +#include "session_manager/route_head_handler_impl.h" +#include "session_manager/upgrade_manager.h" +#include "token_setproc.h" +#include "user_delegate.h" +#include "user_delegate_mock.h" +#include "utils/endian_converter.h" + +namespace { +using namespace testing; +using namespace testing::ext; +using namespace OHOS::DistributedKv; +using namespace OHOS::DistributedData; +using namespace DistributedDB; +using namespace OHOS; +using namespace OHOS::Security::AccessToken; +using DeviceInfo = OHOS::AppDistributedKv::DeviceInfo; +using UserInfo = DistributedDB::UserInfo; +constexpr const char *PEER_DEVICE_ID = "PEER_DEVICE_ID"; +constexpr const char *PROCESSLABEL = "distributeddata"; +constexpr const char *META_DB = "service_meta"; +constexpr const char *DRAG = "drag"; +constexpr const char *OTHER_APP_ID = "test_app_id"; +constexpr const char *USER_ID = "100"; +static constexpr int32_t OH_OS_TYPE = 10; + +void GrantPermissionNative() +{ + const char **perms = new const char *[2]; + perms[0] = "ohos.permission.DISTRIBUTED_DATASYNC"; + perms[1] = "ohos.permission.ACCESS_SERVICE_DM"; + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 2, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "distributed_data_test", + .aplStr = "system_basic", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + +class RouteHeadHandlerImplTest : public testing::Test { +public: + static void SetUpTestCase() + { + GrantPermissionNative(); + deviceManagerAdapterMock = std::make_shared(); + BDeviceManagerAdapter::deviceManagerAdapter = deviceManagerAdapterMock; + metaDataManagerMock = std::make_shared(); + BMetaDataManager::metaDataManager = metaDataManagerMock; + metaDataMock = std::make_shared>(); + BMetaData::metaDataManager = metaDataMock; + userDelegateMock = std::make_shared(); + BUserDelegate::userDelegate = userDelegateMock; + } + static void TearDownTestCase() + { + deviceManagerAdapterMock = nullptr; + BDeviceManagerAdapter::deviceManagerAdapter = nullptr; + metaDataManagerMock = nullptr; + BMetaDataManager::metaDataManager = nullptr; + metaDataMock = nullptr; + BMetaData::metaDataManager = nullptr; + userDelegateMock = nullptr; + BUserDelegate::userDelegate = nullptr; + } + void SetUp(){}; + void TearDown(){}; + static inline std::shared_ptr deviceManagerAdapterMock = nullptr; + static inline std::shared_ptr metaDataManagerMock = nullptr; + static inline std::shared_ptr> metaDataMock = nullptr; + static inline std::shared_ptr userDelegateMock = nullptr; +private: + void GetEmptyHeadDataLen(const DistributedDB::ExtendInfo& info); + void ParseEmptyHeadDataLen(const DistributedDB::ExtendInfo& info); +}; + +void RouteHeadHandlerImplTest::GetEmptyHeadDataLen(const DistributedDB::ExtendInfo& info) +{ + DeviceInfo deviceInfo; + deviceInfo.osType = OH_OS_TYPE; + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(*deviceManagerAdapterMock, GetDeviceInfo(_)).WillRepeatedly(Return(deviceInfo)); + + auto sendHandler = RouteHeadHandlerImpl::Create(info); + ASSERT_NE(sendHandler, nullptr); + + CapMetaData capMetaData; + capMetaData.version = CapMetaData::UDMF_AND_OBJECT_VERSION; + EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)) + .WillRepeatedly(DoAll(SetArgReferee<1>(capMetaData), Return(true))); + uint32_t headSize = 0; + auto status = sendHandler->GetHeadDataSize(headSize); + EXPECT_EQ(status, DistributedDB::OK); + EXPECT_EQ(headSize, 0); +} + +void RouteHeadHandlerImplTest::ParseEmptyHeadDataLen(const DistributedDB::ExtendInfo& info) +{ + DeviceInfo deviceInfo; + deviceInfo.osType = OH_OS_TYPE; + EXPECT_CALL(*deviceManagerAdapterMock, IsOHOSType(_)).WillRepeatedly(Return(true)); + EXPECT_CALL(*deviceManagerAdapterMock, GetDeviceInfo(_)).WillRepeatedly(Return(deviceInfo)); + + auto recvHandler = RouteHeadHandlerImpl::Create(info); + ASSERT_NE(recvHandler, nullptr); + + CapMetaData capMetaData; + capMetaData.version = CapMetaData::UDMF_AND_OBJECT_VERSION; + EXPECT_CALL(*metaDataManagerMock, LoadMeta(_, _, _)) + .WillRepeatedly(DoAll(SetArgReferee<1>(capMetaData), Return(true))); + + uint32_t routeHeadSize = 0; + std::unique_ptr data = std::make_unique(routeHeadSize); + uint32_t parseSize = 0; + auto status = recvHandler->ParseHeadDataLen(data.get(), routeHeadSize, parseSize, PEER_DEVICE_ID); + EXPECT_EQ(status, false); + EXPECT_EQ(parseSize, routeHeadSize); +} + +/** + * @tc.name: GetEmptyHeadDataLen_Test1 + * @tc.desc: test get udmf store + * @tc.type: FUNC + */ +HWTEST_F(RouteHeadHandlerImplTest, GetEmptyHeadDataLen_Test1, TestSize.Level0) +{ + const DistributedDB::ExtendInfo info = { + .appId = PROCESSLABEL, .storeId = DRAG, .userId = USER_ID, .dstTarget = PEER_DEVICE_ID + }; + GetEmptyHeadDataLen(info); +} + +/** + * @tc.name: GetEmptyHeadDataLen_Test2 + * @tc.desc: test meta db + * @tc.type: FUNC + */ +HWTEST_F(RouteHeadHandlerImplTest, GetEmptyHeadDataLen_Test2, TestSize.Level0) +{ + const DistributedDB::ExtendInfo info = { + .appId = PROCESSLABEL, .storeId = META_DB, .userId = USER_ID, .dstTarget = PEER_DEVICE_ID + }; + GetEmptyHeadDataLen(info); +} + +/** + * @tc.name: ParseEmptyHeadDataLen_Test1 + * @tc.desc: test get udmf store + * @tc.type: FUNC + */ +HWTEST_F(RouteHeadHandlerImplTest, ParseEmptyHeadDataLen_Test1, TestSize.Level0) +{ + const DistributedDB::ExtendInfo info = { + .appId = PROCESSLABEL, .storeId = DRAG, .userId = USER_ID, .dstTarget = PEER_DEVICE_ID + }; + GetEmptyHeadDataLen(info); +} + +/** + * @tc.name: ParseEmptyHeadDataLen_Test2 + * @tc.desc: test get meta db + * @tc.type: FUNC + */ +HWTEST_F(RouteHeadHandlerImplTest, ParseEmptyHeadDataLen_Test2, TestSize.Level0) +{ + const DistributedDB::ExtendInfo info = { + .appId = PROCESSLABEL, .storeId = META_DB, .userId = USER_ID, .dstTarget = PEER_DEVICE_ID + }; + GetEmptyHeadDataLen(info); +} + +/** + * @tc.name: ParseEmptyHeadDataLen_Test3 + * @tc.desc: test OTHER_APP_ID + * @tc.type: FUNC + */ +HWTEST_F(RouteHeadHandlerImplTest, ParseEmptyHeadDataLen_Test3, TestSize.Level0) +{ + const DistributedDB::ExtendInfo info = { + .appId = OTHER_APP_ID, .storeId = DRAG, .userId = USER_ID, .dstTarget = PEER_DEVICE_ID + }; + GetEmptyHeadDataLen(info); +} + +/** + * @tc.name: ParseEmptyHeadDataLen_Test4 + * @tc.desc: test get OTHER_APP_ID and meta db + * @tc.type: FUNC + + */ +HWTEST_F(RouteHeadHandlerImplTest, ParseEmptyHeadDataLen_Test4, TestSize.Level0) +{ + const DistributedDB::ExtendInfo info = { + .appId = OTHER_APP_ID, .storeId = META_DB, .userId = USER_ID, .dstTarget = PEER_DEVICE_ID + }; + GetEmptyHeadDataLen(info); +} +} // namespace \ No newline at end of file diff --git a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp index a6452ce4d287c3a8e7d7132d49dcadf0df1ce108..b336e74fed5a9d20ad7fe7575d70f49b0f3fe74c 100644 --- a/services/distributeddataservice/app/test/unittest/session_manager_test.cpp +++ b/services/distributeddataservice/app/test/unittest/session_manager_test.cpp @@ -348,6 +348,7 @@ HWTEST_F(SessionManagerTest, GetHeadDataSize_Test1, TestSize.Level1) RouteHeadHandlerImpl routeHeadHandlerImpl(info); uint32_t headSize = 0; routeHeadHandlerImpl.appId_ = Bootstrap::GetInstance().GetProcessLabel(); + routeHeadHandlerImpl.storeId_ = Bootstrap::GetInstance().GetMetaDBName(); auto status = routeHeadHandlerImpl.GetHeadDataSize(headSize); EXPECT_EQ(status, DistributedDB::OK); EXPECT_EQ(headSize, 0); diff --git a/services/distributeddataservice/framework/directory/directory_manager.cpp b/services/distributeddataservice/framework/directory/directory_manager.cpp index 9deb434e7e53ab00574384f758f933a5a7502350..8ac7b2f03e26c19c7dce07eef656612f0d718494 100644 --- a/services/distributeddataservice/framework/directory/directory_manager.cpp +++ b/services/distributeddataservice/framework/directory/directory_manager.cpp @@ -288,6 +288,7 @@ bool DirectoryManager::CreateDirectory(const std::string &path) const if (access(subPath.c_str(), F_OK) != 0) { if (mkdir(subPath.c_str(), (S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH)) != 0) { + ZLOGE("mkdir error:%{public}d", errno); return false; } } diff --git a/services/distributeddataservice/framework/include/metadata/capability_meta_data.h b/services/distributeddataservice/framework/include/metadata/capability_meta_data.h index 28102100a140d3adca811f6f60ec9ca96a7537b9..1c49339e1e239c9e451448fbabace292e2a59706 100644 --- a/services/distributeddataservice/framework/include/metadata/capability_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/capability_meta_data.h @@ -21,9 +21,11 @@ namespace OHOS::DistributedData { class API_EXPORT CapMetaData final : public Serializable { public: // 1->2 add accountId to session - static constexpr int32_t CURRENT_VERSION = 2; + // 2->3 udmf and object add to session + static constexpr int32_t CURRENT_VERSION = 3; static constexpr int32_t INVALID_VERSION = -1; static constexpr int32_t ACCOUNT_VERSION = 2; + static constexpr int32_t UDMF_AND_OBJECT_VERSION = 3; int32_t version = INVALID_VERSION; std::string deviceId = ""; diff --git a/services/distributeddataservice/framework/include/metadata/store_meta_data.h b/services/distributeddataservice/framework/include/metadata/store_meta_data.h index 2d17763414843203eae334f12a38925ddfec2c59..40e6ca1ae6d346aa79f1b63954c94dd415e8ed1b 100644 --- a/services/distributeddataservice/framework/include/metadata/store_meta_data.h +++ b/services/distributeddataservice/framework/include/metadata/store_meta_data.h @@ -69,6 +69,8 @@ struct API_EXPORT StoreMetaData final : public Serializable { STORE_RELATIONAL_END = 19, STORE_OBJECT_BEGIN = 20, STORE_OBJECT_END = 29, + STORE_UDMF_BEGIN = 30, + STORE_UDMF_END = 39, STORE_BUTT = 255 }; diff --git a/services/distributeddataservice/service/test/BUILD.gn b/services/distributeddataservice/service/test/BUILD.gn index 35a3028a72b6acc285ebda905ea488cd888803c9..076e65832ff880dbba0cea0459accfdde02f7b18 100644 --- a/services/distributeddataservice/service/test/BUILD.gn +++ b/services/distributeddataservice/service/test/BUILD.gn @@ -867,6 +867,7 @@ ohos_unittest("UdmfRunTimeStoreTest") { "${data_service_path}/adapter/include/communicator", "${data_service_path}/app/src", "${data_service_path}/service/kvdb", + "${data_service_path}/service/matrix/include", "${data_service_path}/service/udmf", "${data_service_path}/service/udmf/store", "${data_service_path}/service/udmf/preprocess", @@ -1141,15 +1142,79 @@ ohos_unittest("UdmfServiceImplTest") { module_out_path = module_output_path sources = [ "${data_service_path}/framework/feature/feature_system.cpp", + "${data_service_path}/app/src/kvstore_meta_manager.cpp", "udmf_service_impl_test.cpp", ] include_dirs = [ + "${data_service_path}/adapter/include/account", + "${data_service_path}/adapter/include/communicator", + "${data_service_path}/app/src", + "${data_service_path}/service/kvdb", + "${data_service_path}/service/matrix/include", + "${data_service_path}/service/udmf", + "${data_service_path}/service/udmf/store", + "${data_service_path}/service/udmf/preprocess", + "${data_service_path}/service/udmf/permission", + ] + + configs = [ ":module_private_config" ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "dataclassification:data_transit_mgr", + "device_manager:devicemanagersdk", + "dsoftbus:softbus_client", + "googletest:gtest_main", + "hilog:libhilog", + "hisysevent:libhisysevent", + "image_framework:image", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "kv_store:distributeddb", + "kv_store:distributeddata_mgr", + "openssl:libcrypto_shared", + "samgr:samgr_proxy", + "safwk:system_ability_fwk", + "udmf:udmf_client", + ] + + deps = [ + "${data_service_path}/framework:distributeddatasvcfwk", + "${data_service_path}/service:distributeddatasvc", + "${data_service_path}/service/udmf:udmf_server", + ] + + defines = [ + "private=public", + "protected=public", + ] +} + +ohos_unittest("UdmfServiceImplMockTest") { + module_out_path = module_output_path + sources = [ + "${data_service_path}/framework/feature/feature_system.cpp", + "udmf_service_impl_mock_test.cpp", + ] + + include_dirs = [ + "${data_service_path}/adapter/include/account", + "${data_service_path}/adapter/include/communicator", + "${data_service_path}/framework/include", + "${data_service_path}/service/matrix/include", "${data_service_path}/service/udmf/preprocess", "${data_service_path}/service/udmf/store", "${data_service_path}/service/udmf", - "${data_service_path}/framework/include", "${data_service_path}/service/udmf/permission", + "${data_service_path}/service/test/mock", ] cflags = [ @@ -1160,23 +1225,31 @@ ohos_unittest("UdmfServiceImplTest") { deps = [ "${data_service_path}/service:distributeddatasvc", "${data_service_path}/service/udmf:udmf_server", + "mock:distributeddata_mock_static", ] external_deps = [ "ability_runtime:uri_permission_mgr", "access_token:libaccesstoken_sdk", + "access_token:libnativetoken", + "access_token:libtoken_setproc", "app_file_service:remote_file_share_native", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", + "dataclassification:data_transit_mgr", "device_manager:devicemanagersdk", + "googletest:gmock_main", "googletest:gtest_main", "hilog:libhilog", + "hisysevent:libhisysevent", "cJSON:cjson", "kv_store:distributeddata_inner", "kv_store:distributeddb", + "kv_store:distributeddata_mgr", "relational_store:native_rdb", "samgr:samgr_proxy", + "safwk:system_ability_fwk", "udmf:udmf_client", ] } @@ -1186,6 +1259,7 @@ ohos_unittest("UdmfServiceStubTest") { sources = [ "udmf_service_stub_test.cpp" ] include_dirs = [ + "${data_service_path}/service/matrix/include", "${data_service_path}/service/udmf/preprocess", "${data_service_path}/service/udmf/store", "${data_service_path}/service/udmf", @@ -1199,6 +1273,7 @@ ohos_unittest("UdmfServiceStubTest") { ] deps = [ + "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service:distributeddatasvc", "${data_service_path}/service/udmf:udmf_server", ] @@ -1231,6 +1306,7 @@ ohos_unittest("UdmfServiceStubMockTest") { "${data_service_path}/framework/feature/feature_system.cpp", "${data_service_path}/framework/metadata/appid_meta_data.cpp", "${data_service_path}/framework/metadata/auto_launch_meta_data.cpp", + "${data_service_path}/framework/metadata/capability_meta_data.cpp", "${data_service_path}/framework/metadata/capability_range.cpp", "${data_service_path}/framework/metadata/meta_data_manager.cpp", "${data_service_path}/framework/metadata/secret_key_meta_data.cpp", @@ -1259,6 +1335,7 @@ ohos_unittest("UdmfServiceStubMockTest") { ] include_dirs = [ + "${data_service_path}/service/matrix/include", "${data_service_path}/service/udmf/store", "${data_service_path}/service/udmf", "${data_service_path}/framework/include", @@ -1349,6 +1426,7 @@ ohos_unittest("UdmfPreProcessUtilsMockTest") { ] include_dirs = [ + "${data_service_path}/service/matrix/include", "${data_service_path}/service/udmf/preprocess", "${data_service_path}/service/test/mock", "${data_service_path}/service/udmf/store", @@ -1878,6 +1956,7 @@ group("unittest") { ":UdmfPreProcessUtilsMockTest", ":UdmfPreProcessUtilsTest", ":UdmfRunTimeStoreTest", + ":UdmfServiceImplMockTest", ":UdmfServiceImplTest", ":UdmfServiceStubMockTest", ":UdmfServiceStubTest", diff --git a/services/distributeddataservice/service/test/directory_manager_test.cpp b/services/distributeddataservice/service/test/directory_manager_test.cpp index c763765ab1544cf3ab8e5df7d8b395f666eb94b1..a71c6df46860fb6faa4083ac8c466700b22e7094 100644 --- a/services/distributeddataservice/service/test/directory_manager_test.cpp +++ b/services/distributeddataservice/service/test/directory_manager_test.cpp @@ -191,6 +191,33 @@ HWTEST_F(DirectoryManagerTest, GetKVDBBackupPath, TestSize.Level0) EXPECT_EQ(path, metaData.dataDir + "/backup/testStpre"); } +/** +* @tc.name: GetUdmfPath +* @tc.desc: test get udmf store path +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(DirectoryManagerTest, GetUdmfStorePath, TestSize.Level0) +{ + StoreMetaData metaData; + metaData.user = "100"; + metaData.bundleName = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); + metaData.appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel(); + metaData.storeId = "drag"; + metaData.securityLevel = SecurityLevel::S2; + metaData.tokenId = GetAccessTokenId(&tokenParam_); + metaData.area = DistributedKv::Area::EL2; + metaData.uid = static_cast(getuid()); + metaData.storeType = StoreMetaData::StoreType::STORE_UDMF_BEGIN; + metaData.dataType = DistributedKv::DataType::TYPE_DYNAMICAL; + metaData.authType = DistributedKv::AuthType::IDENTICAL_ACCOUNT; + metaData.dataDir = "/data/service/el2/100/database/distributeddata/other"; + auto path = DirectoryManager::GetInstance().GetStorePath(metaData); + EXPECT_EQ(path, metaData.dataDir); + auto res = DistributedData::DirectoryManager::GetInstance().CreateDirectory(path); + EXPECT_EQ(res, true); +} + /** * @tc.name: GetStorageMetaPath * @tc.desc: test get meta store dir diff --git a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn index a85ad62a0c5b23aaed66122a559facb08289da65..4c71160b081c3a2dd4e41b58871ea51efaf51283 100644 --- a/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn +++ b/services/distributeddataservice/service/test/fuzztest/udmfservice_fuzzer/BUILD.gn @@ -21,6 +21,7 @@ ohos_fuzztest("UdmfServiceFuzzTest") { include_dirs = [ "${data_service_path}/framework/include", + "${data_service_path}/service/matrix/include", "${data_service_path}/service/udmf/lifecycle", "${data_service_path}/service/udmf/permission", "${data_service_path}/service/udmf/preprocess", @@ -46,6 +47,7 @@ ohos_fuzztest("UdmfServiceFuzzTest") { "${data_service_path}/adapter/dfx:distributeddata_dfx", "${data_service_path}/framework:distributeddatasvcfwk", "${data_service_path}/service/bootstrap:distributeddata_bootstrap", + "${data_service_path}/service/matrix:distributeddata_matrix", "${data_service_path}/service/udmf:udmf_server", ] diff --git a/services/distributeddataservice/service/test/udmf_service_impl_mock_test.cpp b/services/distributeddataservice/service/test/udmf_service_impl_mock_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c782a4346041198003871373d5f8ec4336e65dfc --- /dev/null +++ b/services/distributeddataservice/service/test/udmf_service_impl_mock_test.cpp @@ -0,0 +1,148 @@ +/* +* Copyright (c) 2024 Huawei Device Co., Ltd. +* Licensed under the Apache License, Version 2.0 (the "License"); +* you may not use this file except in compliance with the License. +* You may obtain a copy of the License at +* +* http://www.apache.org/licenses/LICENSE-2.0 +* +* Unless required by applicable law or agreed to in writing, software +* distributed under the License is distributed on an "AS IS" BASIS, +* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +* See the License for the specific language governing permissions and +* limitations under the License. +*/ + +#define LOG_TAG "UdmfServiceImplMockTest" +#include "udmf_service_impl.h" +#include "gtest/gtest.h" +#include "error_code.h" +#include "text.h" +#include "accesstoken_kit.h" +#include "bootstrap.h" +#include "device_manager_adapter.h" +#include "executor_pool.h" +#include "ipc_skeleton.h" +#include "mock/access_token_mock.h" +#include "mock/meta_data_manager_mock.h" +#include "nativetoken_kit.h" +#include "token_setproc.h" +#include "kvstore_meta_manager.h" +using namespace OHOS::DistributedData; +using namespace OHOS::Security::AccessToken; +using namespace OHOS::UDMF; +using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; +using namespace testing::ext; +using namespace testing; + +namespace OHOS::Test { +namespace DistributedDataTest { +class UdmfServiceImplMockTest : public testing::Test { +public: + static void SetUpTestCase(void) + { + accTokenMock = std::make_shared(); + BAccessTokenKit::accessTokenkit = accTokenMock; + metaDataManagerMock = std::make_shared(); + BMetaDataManager::metaDataManager = metaDataManagerMock; + metaDataMock = std::make_shared>(); + BMetaData::metaDataManager = metaDataMock; + } + static void TearDownTestCase(void) + { + accTokenMock = nullptr; + BAccessTokenKit::accessTokenkit = nullptr; + metaDataManagerMock = nullptr; + BMetaDataManager::metaDataManager = nullptr; + metaDataMock = nullptr; + BMetaData::metaDataManager = nullptr; + } + static inline std::shared_ptr accTokenMock = nullptr; + static inline std::shared_ptr metaDataManagerMock = nullptr; + static inline std::shared_ptr> metaDataMock = nullptr; + void SetUp() {}; + void TearDown() {}; +}; + +/** +* @tc.name: IsNeedMetaSyncTest001 +* @tc.desc: IsNeedMetaSync test +* @tc.type: FUNC +*/ +HWTEST_F(UdmfServiceImplMockTest, IsNeedMetaSyncTest001, TestSize.Level0) +{ + UdmfServiceImpl udmfServiceImpl; + StoreMetaData meta = StoreMetaData("100", "distributeddata", "drag"); + std::vector devices = {"remote_device"}; + + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(false)) + .WillOnce(testing::Return(false)); + auto isNeedSync = udmfServiceImpl.IsNeedMetaSync(meta, devices); + EXPECT_EQ(isNeedSync, true); + + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(false)) + .WillOnce(testing::Return(true)); + isNeedSync = udmfServiceImpl.IsNeedMetaSync(meta, devices); + EXPECT_EQ(isNeedSync, true); + + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(true)) + .WillOnce(testing::Return(false)); + isNeedSync = udmfServiceImpl.IsNeedMetaSync(meta, devices); + EXPECT_EQ(isNeedSync, true); + + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(true)) + .WillOnce(testing::Return(true)); + isNeedSync = udmfServiceImpl.IsNeedMetaSync(meta, devices); + EXPECT_EQ(isNeedSync, false); +} + +/** +* @tc.name: SyncTest001 +* @tc.desc: IsNeedMetaSync test matrix mask +* @tc.type: FUNC +*/ +HWTEST_F(UdmfServiceImplMockTest, IsNeedMetaSyncTest002, TestSize.Level0) +{ + QueryOption query; + query.key = "test_key"; + query.tokenId = 1; + query.intention = UD_INTENTION_DRAG; + UdmfServiceImpl udmfServiceImpl; + StoreMetaData meta = StoreMetaData("100", "distributeddata", "drag"); + std::vector devices = {"remote_device"}; + + EXPECT_CALL(*metaDataManagerMock, LoadMeta(testing::_, testing::_, testing::_)) + .WillOnce(testing::Return(false)) + .WillOnce(testing::Return(false)); + auto isNeedSync = udmfServiceImpl.IsNeedMetaSync(meta, devices); + EXPECT_EQ(isNeedSync, true); + // mock mask +} + +/** + * @tc.name: ResolveAutoLaunchTest001 + * @tc.desc: ResolveAutoLaunch test. + * @tc.type: FUNC + */ +HWTEST_F(UdmfServiceImplMockTest, ResolveAutoLaunchTest001, TestSize.Level0) +{ + auto store = StoreCache::GetInstance().GetStore("drag"); + auto ret = store->Init(); + EXPECT_EQ(ret, UDMF::E_OK); + + DistributedDB::AutoLaunchParam param { + .userId = "100", + .appId = "distributeddata", + .storeId = "drag", + }; + std::string identifier = "identifier"; + std::shared_ptr udmfServiceImpl = std::make_shared(); + ret = udmfServiceImpl->ResolveAutoLaunch(identifier, param); + EXPECT_EQ(ret, UDMF::E_NOT_FOUND); +} +}; // DistributedDataTest +}; // namespace OHOS::Test \ No newline at end of file diff --git a/services/distributeddataservice/service/test/udmf_service_impl_test.cpp b/services/distributeddataservice/service/test/udmf_service_impl_test.cpp index b81e089db65857dfd94524a2ec40e48524bfa929..bcb18a86406b7702f270ea8105c8d3d591010cec 100644 --- a/services/distributeddataservice/service/test/udmf_service_impl_test.cpp +++ b/services/distributeddataservice/service/test/udmf_service_impl_test.cpp @@ -15,19 +15,76 @@ #define LOG_TAG "UdmfServiceImplTest" #include "udmf_service_impl.h" +#include "accesstoken_kit.h" +#include "bootstrap.h" +#include "device_manager_adapter.h" +#include "executor_pool.h" #include "gtest/gtest.h" -#include "error_code.h" +#include "ipc_skeleton.h" +#include "kvstore_meta_manager.h" +#include "metadata/meta_data_manager.h" +#include "nativetoken_kit.h" +#include "preprocess_utils.h" +#include "runtime_store.h" #include "text.h" +#include "token_setproc.h" -using namespace OHOS::DistributedData; -namespace OHOS::UDMF { using namespace testing::ext; +using namespace OHOS::DistributedData; +using namespace OHOS::Security::AccessToken; +using namespace OHOS::UDMF; +using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; +using Entry = DistributedDB::Entry; +using Key = DistributedDB::Key; +using Value = DistributedDB::Value; +using UnifiedData = OHOS::UDMF::UnifiedData; +using Summary = OHOS::UDMF::Summary; +namespace OHOS::Test { +namespace DistributedDataTest { + +static void GrantPermissionNative() +{ + const char **perms = new const char *[3]; + perms[0] = "ohos.permission.DISTRIBUTED_DATASYNC"; + perms[1] = "ohos.permission.ACCESS_SERVICE_DM"; + perms[2] = "ohos.permission.MONITOR_DEVICE_NETWORK_STATE"; // perms[2] is a permission parameter + TokenInfoParams infoInstance = { + .dcapsNum = 0, + .permsNum = 3, + .aclsNum = 0, + .dcaps = nullptr, + .perms = perms, + .acls = nullptr, + .processName = "distributed_data_test", + .aplStr = "system_basic", + }; + uint64_t tokenId = GetAccessTokenId(&infoInstance); + SetSelfTokenID(tokenId); + AccessTokenKit::ReloadNativeTokenInfo(); + delete[] perms; +} + class UdmfServiceImplTest : public testing::Test { public: - static void SetUpTestCase(void) {} - static void TearDownTestCase(void) {} - void SetUp() {} - void TearDown() {} + static void SetUpTestCase(void) + { + GrantPermissionNative(); + DistributedData::Bootstrap::GetInstance().LoadComponents(); + DistributedData::Bootstrap::GetInstance().LoadDirectory(); + DistributedData::Bootstrap::GetInstance().LoadCheckers(); + size_t max = 2; + size_t min = 1; + auto executors = std::make_shared(max, min); + DmAdapter::GetInstance().Init(executors); + DistributedKv::KvStoreMetaManager::GetInstance().BindExecutor(executors); + DistributedKv::KvStoreMetaManager::GetInstance().InitMetaParameter(); + DistributedKv::KvStoreMetaManager::GetInstance().InitMetaListener(); + } + static void TearDownTestCase(void){}; + void SetUp(){}; + void TearDown(){}; + + const std::string STORE_ID = "drag"; }; /** @@ -211,11 +268,70 @@ HWTEST_F(UdmfServiceImplTest, OnUserChangeTest001, TestSize.Level1) std::string account = "OH_ACCOUNT_test"; UdmfServiceImpl udmfServiceImpl; auto status = udmfServiceImpl.OnUserChange(code, user, account); - ASSERT_EQ(status, E_OK); + ASSERT_EQ(status, UDMF::E_OK); auto sizeAfter = StoreCache::GetInstance().stores_.Size(); ASSERT_EQ(sizeAfter, 0); } +/** +* @tc.name: SaveMetaData001 +* @tc.desc: Abnormal testcase of GetRuntime +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, SaveMetaData001, TestSize.Level0) +{ + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + + result = store->Init(); + EXPECT_TRUE(result); +} + +/** +* @tc.name: SaveMetaData001 +* @tc.desc: Abnormal testcase of GetRuntime +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, SyncTest001, TestSize.Level0) +{ + QueryOption query; + query.key = "udmf://drag/ohos.test.demo1/_aS6adWi7 devices = {"remote_device"}; + + auto ret = udmfServiceImpl.Sync(query, devices); + EXPECT_EQ(ret, UDMF::E_DB_ERROR); +} + +/** +* @tc.name: ResolveAutoLaunch001 +* @tc.desc: test ResolveAutoLaunch +* @tc.type: FUNC +* @tc.require: +*/ +HWTEST_F(UdmfServiceImplTest, ResolveAutoLaunch001, TestSize.Level0) +{ + auto store = std::make_shared(STORE_ID); + bool result = store->Init(); + EXPECT_TRUE(result); + + DistributedDB::AutoLaunchParam param { + .userId = "100", + .appId = "distributeddata", + .storeId = "drag", + }; + std::string identifier = "identifier"; + std::shared_ptr udmfServiceImpl = std::make_shared(); + auto ret = udmfServiceImpl->ResolveAutoLaunch(identifier, param); + EXPECT_EQ(ret, UDMF::E_OK); +} + /** * @tc.name: TransferToEntriesIfNeedTest001 * @tc.desc: TransferToEntriesIfNeed test @@ -240,7 +356,6 @@ HWTEST_F(UdmfServiceImplTest, TransferToEntriesIfNeedTest001, TestSize.Level1) int recordSize = 2; EXPECT_EQ(data.GetRecords().size(), recordSize); } - /** * @tc.name: IsValidInput001 * @tc.desc: invalid unifiedData @@ -316,5 +431,5 @@ HWTEST_F(UdmfServiceImplTest, IsValidInput004, TestSize.Level1) bool result = impl.IsValidInput(query, unifiedData, key); EXPECT_FALSE(result); } - -}; // namespace UDMF \ No newline at end of file +}; // namespace DistributedDataTest +}; // namespace OHOS::Test diff --git a/services/distributeddataservice/service/udmf/BUILD.gn b/services/distributeddataservice/service/udmf/BUILD.gn index 3d4e0ba93820ea5bbd35e39a2aed740ec825a64b..6180f01b6998dca381c6afa7f69b5783460ccb7f 100644 --- a/services/distributeddataservice/service/udmf/BUILD.gn +++ b/services/distributeddataservice/service/udmf/BUILD.gn @@ -18,6 +18,7 @@ config("module_public_config") { include_dirs = [ "${data_service_path}/adapter/include/communicator", + "${data_service_path}/service/matrix/include", "${data_service_path}/service/udmf/lifecycle", "${data_service_path}/service/udmf/permission", "${data_service_path}/service/udmf/preprocess", diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.cpp b/services/distributeddataservice/service/udmf/store/runtime_store.cpp index 60e59ff40b93700eed9fbde7e7822c52be28c3a4..03705eeca0d7a5ca40c0c123ae0993f3c043e4ba 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.cpp +++ b/services/distributeddataservice/service/udmf/store/runtime_store.cpp @@ -24,6 +24,7 @@ #include "account/account_delegate.h" #include "metadata/meta_data_manager.h" #include "metadata/appid_meta_data.h" +#include "metadata/store_meta_data.h" #include "device_manager_adapter.h" #include "bootstrap.h" #include "directory/directory_manager.h" @@ -34,6 +35,7 @@ namespace OHOS { namespace UDMF { using namespace RadarReporter; using namespace DistributedDB; +using namespace OHOS::DistributedData; using Anonymous = OHOS::DistributedData::Anonymous; using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; constexpr const char *SUMMARY_SUFIX = "#summary"; @@ -475,11 +477,11 @@ bool RuntimeStore::BuildMetaDataParam(DistributedData::StoreMetaData &metaData) metaData.account = DistributedData::AccountDelegate::GetInstance()->GetCurrentAccountId(); metaData.tokenId = token; metaData.securityLevel = DistributedKv::SecurityLevel::S1; - metaData.area = DistributedKv::Area::EL1; + metaData.area = DistributedKv::Area::EL2; metaData.uid = static_cast(getuid()); - metaData.storeType = DistributedKv::KvStoreType::SINGLE_VERSION; + metaData.storeType = StoreMetaData::StoreType::STORE_UDMF_BEGIN; metaData.dataType = DistributedKv::DataType::TYPE_DYNAMICAL; - metaData.dataDir = DistributedData::DirectoryManager::GetInstance().GetStorePath(metaData); + metaData.authType = DistributedKv::AuthType::IDENTICAL_ACCOUNT; return true; } @@ -497,21 +499,23 @@ bool RuntimeStore::SaveMetaData() ZLOGE("QueryForegroundUserId failed."); return false; } - - saveMeta.dataDir.append("/").append(std::to_string(foregroundUserId)); + saveMeta.user = std::to_string(foregroundUserId); + saveMeta.dataDir = DistributedData::DirectoryManager::GetInstance().GetStorePath(saveMeta); if (!DistributedData::DirectoryManager::GetInstance().CreateDirectory(saveMeta.dataDir)) { - ZLOGE("Create directory error"); + ZLOGE("Create directory error, dataDir: %{public}s.", Anonymous::Change(saveMeta.dataDir).c_str()); return false; } - SetDelegateManager(saveMeta.dataDir, saveMeta.appId, saveMeta.user, std::to_string(foregroundUserId)); + SetDelegateManager(saveMeta.dataDir, saveMeta.appId, saveMeta.user); DistributedData::StoreMetaData loadLocal; DistributedData::StoreMetaData syncMeta; if (DistributedData::MetaDataManager::GetInstance().LoadMeta(saveMeta.GetKey(), loadLocal, true) && DistributedData::MetaDataManager::GetInstance().LoadMeta(saveMeta.GetKey(), syncMeta, false)) { - ZLOGD("Meta data is already saved."); - return true; + if (loadLocal == saveMeta && syncMeta == saveMeta) { + ZLOGD("Meta data is already saved."); + return true; + } } auto saved = DistributedData::MetaDataManager::GetInstance().SaveMeta(saveMeta.GetKey(), saveMeta) && @@ -531,10 +535,9 @@ bool RuntimeStore::SaveMetaData() return true; } -void RuntimeStore::SetDelegateManager(const std::string &dataDir, const std::string &appId, const std::string &userId, - const std::string &subUser) +void RuntimeStore::SetDelegateManager(const std::string &dataDir, const std::string &appId, const std::string &userId) { - delegateManager_ = std::make_shared(appId, userId, subUser); + delegateManager_ = std::make_shared(appId, userId); DistributedDB::KvStoreConfig kvStoreConfig { dataDir }; auto status = delegateManager_->SetKvStoreConfig(kvStoreConfig); if (status != DBStatus::OK) { diff --git a/services/distributeddataservice/service/udmf/store/runtime_store.h b/services/distributeddataservice/service/udmf/store/runtime_store.h index 107ac11bc4991f3c7427e4c7fea0faf321920e0c..ef9c37e36c0789a10dc25fa7b7d9bb6ff698651c 100644 --- a/services/distributeddataservice/service/udmf/store/runtime_store.h +++ b/services/distributeddataservice/service/udmf/store/runtime_store.h @@ -54,8 +54,7 @@ private: std::shared_ptr delegateManager_ = nullptr; std::shared_ptr kvStore_; std::string storeId_; - void SetDelegateManager(const std::string &dataDir, const std::string &appId, const std::string &userId, - const std::string &subUser); + void SetDelegateManager(const std::string &dataDir, const std::string &appId, const std::string &userId); bool SaveMetaData(); Status GetEntries(const std::string &dataPrefix, std::vector &entries); Status PutEntries(const std::vector &entries); diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp index cd9940cb7a0559c549e51b8ce5781a2e9e283270..1ceb45cc8c31ec8eb3c3b032727484ca8aa1cecb 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.cpp +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.cpp @@ -26,9 +26,11 @@ #include "bundlemgr/bundle_mgr_proxy.h" #include "checker_manager.h" #include "device_manager_adapter.h" +#include "device_matrix.h" #include "iservice_registry.h" #include "lifecycle/lifecycle_manager.h" #include "log_print.h" +#include "metadata/capability_meta_data.h" #include "metadata/store_meta_data.h" #include "metadata/meta_data_manager.h" #include "preprocess_utils.h" @@ -45,6 +47,7 @@ namespace OHOS { namespace UDMF { using namespace Security::AccessToken; using namespace OHOS::DistributedHardware; +using namespace OHOS::DistributedData; using FeatureSystem = DistributedData::FeatureSystem; using UdmfBehaviourMsg = OHOS::DistributedDataDfx::UdmfBehaviourMsg; using Reporter = OHOS::DistributedDataDfx::Reporter; @@ -562,7 +565,6 @@ int32_t UdmfServiceImpl::AddPrivilege(const QueryOption &query, Privilege &privi int32_t UdmfServiceImpl::Sync(const QueryOption &query, const std::vector &devices) { - ZLOGD("start"); RadarReporterAdapter::ReportNormal(std::string(__FUNCTION__), BizScene::SYNC_DATA, SyncDataStage::SYNC_BEGIN, StageRes::IDLE, BizState::DFX_BEGIN); UnifiedKey key(query.key); @@ -572,15 +574,13 @@ int32_t UdmfServiceImpl::Sync(const QueryOption &query, const std::vector syncDevices; - for (auto const &device : devices) { - if (!DistributedData::DeviceManagerAdapter::GetInstance().IsSameAccount(device)) { - ZLOGW("is diff account. device:%{public}s", DistributedData::Anonymous::Change(device).c_str()); - continue; - } - syncDevices.emplace_back(device); - } RegisterAsyncProcessInfo(query.key); + return StoreSync(key, query, devices); +} + +int32_t UdmfServiceImpl::StoreSync(const UnifiedKey &key, const QueryOption &query, + const std::vector &devices) +{ auto store = StoreCache::GetInstance().GetStore(key.intention); if (store == nullptr) { RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), @@ -601,15 +601,56 @@ int32_t UdmfServiceImpl::Sync(const QueryOption &query, const std::vectorSync(syncDevices, callback) != E_OK) { - ZLOGE("Store sync failed:%{public}s", key.intention.c_str()); + int32_t id = AccountDelegate::GetInstance()->GetUserByToken(IPCSkeleton::GetCallingFullTokenID()); + StoreMetaData meta = StoreMetaData(std::to_string(id), Bootstrap::GetInstance().GetProcessLabel(), key.intention); + auto uuids = DmAdapter::GetInstance().ToUUID(devices); + if (IsNeedMetaSync(meta, uuids) && !MetaDataManager::GetInstance().Sync(uuids, + [devices, callback, store] (auto &results) { + if (store->Sync(devices, callback) != E_OK) { + ZLOGE("Store sync failed"); + RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), + BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::FAILED, E_DB_ERROR, BizState::DFX_END); + } + })) { + ZLOGW("bundleName:%{public}s, meta sync failed", key.bundleName.c_str()); + } + if (store->Sync(devices, callback) != E_OK) { + ZLOGE("Store sync failed"); RadarReporterAdapter::ReportFail(std::string(__FUNCTION__), BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::FAILED, E_DB_ERROR, BizState::DFX_END); - return E_DB_ERROR; + return UDMF::E_DB_ERROR; } return E_OK; } +bool UdmfServiceImpl::IsNeedMetaSync(const StoreMetaData &meta, const std::vector &uuids) +{ + using namespace OHOS::DistributedData; + bool isAfterMeta = false; + for (const auto &uuid : uuids) { + auto metaData = meta; + metaData.deviceId = uuid; + CapMetaData capMeta; + auto capKey = CapMetaRow::GetKeyFor(uuid); + if (!MetaDataManager::GetInstance().LoadMeta(std::string(capKey.begin(), capKey.end()), capMeta) || + !MetaDataManager::GetInstance().LoadMeta(metaData.GetKey(), metaData)) { + isAfterMeta = true; + break; + } + auto [exist, mask] = DeviceMatrix::GetInstance().GetRemoteMask(uuid); + if ((mask & DeviceMatrix::META_STORE_MASK) == DeviceMatrix::META_STORE_MASK) { + isAfterMeta = true; + break; + } + auto [existLocal, localMask] = DeviceMatrix::GetInstance().GetMask(uuid); + if ((localMask & DeviceMatrix::META_STORE_MASK) == DeviceMatrix::META_STORE_MASK) { + isAfterMeta = true; + break; + } + } + return isAfterMeta; +} + int32_t UdmfServiceImpl::IsRemoteData(const QueryOption &query, bool &result) { UnifiedKey key(query.key); @@ -825,9 +866,9 @@ int32_t UdmfServiceImpl::ResolveAutoLaunch(const std::string &identifier, DBLaun } for (const auto &storeMeta : metaData) { - if (storeMeta.storeType < StoreMetaData::StoreType::STORE_KV_BEGIN || - storeMeta.storeType > StoreMetaData::StoreType::STORE_KV_END || - storeMeta.appId != DistributedData::Bootstrap::GetInstance().GetProcessLabel()) { + if (storeMeta.storeType < StoreMetaData::StoreType::STORE_UDMF_BEGIN || + storeMeta.storeType > StoreMetaData::StoreType::STORE_UDMF_END || + storeMeta.appId != Bootstrap::GetInstance().GetProcessLabel()) { continue; } auto identifierTag = DistributedDB::KvStoreDelegateManager::GetKvStoreIdentifier("", storeMeta.appId, @@ -837,11 +878,10 @@ int32_t UdmfServiceImpl::ResolveAutoLaunch(const std::string &identifier, DBLaun } auto store = StoreCache::GetInstance().GetStore(storeMeta.storeId); if (store == nullptr) { - ZLOGE("GetStore fail, storeId:%{public}s", DistributedData::Anonymous::Change(storeMeta.storeId).c_str()); + ZLOGE("GetStore fail, storeId:%{public}s", Anonymous::Change(storeMeta.storeId).c_str()); continue; } - ZLOGI("storeId:%{public}s,appId:%{public}s,user:%{public}s", - DistributedData::Anonymous::Change(storeMeta.storeId).c_str(), + ZLOGI("storeId:%{public}s,appId:%{public}s,user:%{public}s", Anonymous::Change(storeMeta.storeId).c_str(), storeMeta.appId.c_str(), storeMeta.user.c_str()); return E_OK; } diff --git a/services/distributeddataservice/service/udmf/udmf_service_impl.h b/services/distributeddataservice/service/udmf/udmf_service_impl.h index 772ddaa2d160a37f2f21e521d9c0ff378d7e8f52..8f366463f115a91d92db2235973f50bd04c25a0c 100644 --- a/services/distributeddataservice/service/udmf/udmf_service_impl.h +++ b/services/distributeddataservice/service/udmf/udmf_service_impl.h @@ -19,6 +19,7 @@ #include "store_cache.h" #include "udmf_service_stub.h" #include "kv_store_delegate_manager.h" +#include "metadata/store_meta_data.h" #include "checker_manager.h" #include "udmf_notifier_proxy.h" namespace OHOS { @@ -55,6 +56,8 @@ public: int32_t GetDataIfAvailable(const std::string &key, const DataLoadInfo &dataLoadInfo, sptr iUdmfNotifier, std::shared_ptr unifiedData) override; private: + bool IsNeedMetaSync(const DistributedData::StoreMetaData &meta, const std::vector &uuids); + int32_t StoreSync(const UnifiedKey &key, const QueryOption &query, const std::vector &devices); int32_t SaveData(CustomOption &option, UnifiedData &unifiedData, std::string &key); int32_t RetrieveData(const QueryOption &query, UnifiedData &unifiedData); int32_t QueryDataCommon(const QueryOption &query, std::vector &dataSet, std::shared_ptr &store);