diff --git a/datamgr_service/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp b/datamgr_service/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp index 80f0686ab703bde6727192afc362e58c36c6af3a..cb6142eb359daf7fb25ba67919f324745e386b19 100644 --- a/datamgr_service/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp +++ b/datamgr_service/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.cpp @@ -28,7 +28,6 @@ #include "metadata/store_meta_data.h" #include "permit_delegate.h" #include "cloud/cloud_info.h" -#include "utils/block_integer.h" namespace OHOS::DistributedKv { using namespace OHOS::AppDistributedKv; @@ -37,8 +36,13 @@ using namespace OHOS::AppExecFwk; using namespace OHOS::DistributedData; using namespace OHOS::EventFwk; -UninstallEventSubscriber::UninstallEventSubscriber(const CommonEventSubscribeInfo &info) : CommonEventSubscriber(info) +UninstallEventSubscriber::UninstallEventSubscriber(const CommonEventSubscribeInfo &info, + KvStoreDataService *kvStoreDataService) + : CommonEventSubscriber(info), kvStoreDataService_(kvStoreDataService) { + callbacks_ = { { CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED, &UninstallEventSubscriber::OnUninstall }, + { OHOS::AppExecFwk::COMMON_EVENT_SANDBOX_PACKAGE_REMOVED, &UninstallEventSubscriber::OnUninstall }, + { CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED, &UninstallEventSubscriber::OnUpdate } }; } void UninstallEventSubscriber::OnReceiveEvent(const CommonEventData &event) @@ -46,21 +50,57 @@ void UninstallEventSubscriber::OnReceiveEvent(const CommonEventData &event) ZLOGI("Intent Action Rec"); Want want = event.GetWant(); std::string action = want.GetAction(); - callbacks_.ComputeIfPresent(action, [&want](const auto& key, auto &callback) { + auto it = callbacks_.find(action); + if (it != callbacks_.end()) { std::string bundleName = want.GetElement().GetBundleName(); int32_t userId = want.GetIntParam(USER_ID, -1); int32_t appIndex = want.GetIntParam(SANDBOX_APP_INDEX, 0); ZLOGI("bundleName:%{public}s, user:%{public}d, appIndex:%{public}d", bundleName.c_str(), userId, appIndex); - callback(bundleName, userId, appIndex); - return true; - }); + (this->*(it->second))(bundleName, userId, appIndex); + } } -int32_t UninstallEventSubscriber::RegisterCallback(const std::string &action, UninstallEventCallback callback) + +void UninstallEventSubscriber::OnUninstall(const std::string &bundleName, int32_t userId, int32_t appIndex) { - callbacks_.InsertOrAssign(action, std::move(callback)); - return Status::SUCCESS; + kvStoreDataService_->OnUninstall(bundleName, userId, appIndex, IPCSkeleton::GetCallingTokenID()); + std::string prefix = StoreMetaData::GetPrefix( + { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid, std::to_string(userId), "default", bundleName }); + std::vector storeMetaData; + if (!MetaDataManager::GetInstance().LoadMeta(prefix, storeMetaData)) { + ZLOGE("load meta failed!"); + return; + } + for (auto &meta : storeMetaData) { + if (meta.instanceId == appIndex && !meta.appId.empty() && !meta.storeId.empty()) { + ZLOGI("uninstalled bundleName:%{public}s stordId:%{public}s", bundleName.c_str(), meta.storeId.c_str()); + MetaDataManager::GetInstance().DelMeta(meta.GetKey()); + MetaDataManager::GetInstance().DelMeta(meta.GetSecretKey(), true); + MetaDataManager::GetInstance().DelMeta(meta.GetStrategyKey()); + MetaDataManager::GetInstance().DelMeta(meta.appId, true); + MetaDataManager::GetInstance().DelMeta(meta.GetKeyLocal(), true); + MetaDataManager::GetInstance().DelMeta(CloudInfo::GetSchemaKey(meta), true); + PermitDelegate::GetInstance().DelCache(meta.GetKey()); + } + } } +void UninstallEventSubscriber::OnUpdate(const std::string &bundleName, int32_t userId, int32_t appIndex) +{ + kvStoreDataService_->OnUpdate(bundleName, userId, appIndex, IPCSkeleton::GetCallingTokenID()); + std::string prefix = StoreMetaData::GetPrefix( + { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid, std::to_string(userId), "default", bundleName }); + std::vector storeMetaData; + if (!MetaDataManager::GetInstance().LoadMeta(prefix, storeMetaData)) { + ZLOGE("load meta failed!"); + return; + } + for (auto &meta : storeMetaData) { + if (meta.instanceId == appIndex && !meta.appId.empty() && !meta.storeId.empty()) { + ZLOGI("updated bundleName:%{public}s, stordId:%{public}s", bundleName.c_str(), meta.storeId.c_str()); + MetaDataManager::GetInstance().DelMeta(CloudInfo::GetSchemaKey(meta), true); + } + } +} UninstallerImpl::~UninstallerImpl() { ZLOGD("destruct"); @@ -90,21 +130,7 @@ Status UninstallerImpl::Init(KvStoreDataService *kvStoreDataService, std::shared matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED); CommonEventSubscribeInfo info(matchingSkills); - auto subscriber = std::make_shared(info); - auto removedCallback = [kvStoreDataService](const std::string &bundleName, int32_t userId, int32_t appIndex) { - kvStoreDataService->OnUninstall(bundleName, userId, appIndex, IPCSkeleton::GetCallingTokenID()); - OnUninstall(bundleName, userId, appIndex); - }; - - auto updatedCallback = [kvStoreDataService](const std::string &bundleName, int32_t userId, int32_t appIndex) { - kvStoreDataService->OnUpdate(bundleName, userId, appIndex, IPCSkeleton::GetCallingTokenID()); - OnUpdate(bundleName, userId, appIndex); - }; - - subscriber->RegisterCallback(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED, removedCallback); - subscriber->RegisterCallback(OHOS::AppExecFwk::COMMON_EVENT_SANDBOX_PACKAGE_REMOVED, removedCallback); - subscriber->RegisterCallback(CommonEventSupport::COMMON_EVENT_PACKAGE_CHANGED, updatedCallback); - + auto subscriber = std::make_shared(info, kvStoreDataService); subscriber_ = subscriber; executors_ = executors; executors_->Execute(GetTask()); @@ -126,44 +152,4 @@ ExecutorPool::Task UninstallerImpl::GetTask() executors_->Schedule(std::chrono::milliseconds(RETRY_INTERVAL), GetTask()); }; } - -void UninstallerImpl::OnUninstall(const std::string &bundleName, int32_t userId, int32_t appIndex) -{ - std::string prefix = StoreMetaData::GetPrefix( - { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid, std::to_string(userId), "default", bundleName }); - std::vector storeMetaData; - if (!MetaDataManager::GetInstance().LoadMeta(prefix, storeMetaData)) { - ZLOGE("load meta failed!"); - return; - } - for (auto &meta : storeMetaData) { - if (meta.instanceId == appIndex && !meta.appId.empty() && !meta.storeId.empty()) { - ZLOGI("uninstalled bundleName:%{public}s stordId:%{public}s", bundleName.c_str(), meta.storeId.c_str()); - MetaDataManager::GetInstance().DelMeta(meta.GetKey()); - MetaDataManager::GetInstance().DelMeta(meta.GetSecretKey(), true); - MetaDataManager::GetInstance().DelMeta(meta.GetStrategyKey()); - MetaDataManager::GetInstance().DelMeta(meta.appId, true); - MetaDataManager::GetInstance().DelMeta(meta.GetKeyLocal(), true); - MetaDataManager::GetInstance().DelMeta(CloudInfo::GetSchemaKey(meta), true); - PermitDelegate::GetInstance().DelCache(meta.GetKey()); - } - } -} - -void UninstallerImpl::OnUpdate(const std::string &bundleName, int32_t userId, int32_t appIndex) -{ - std::string prefix = StoreMetaData::GetPrefix( - { DeviceManagerAdapter::GetInstance().GetLocalDevice().uuid, std::to_string(userId), "default", bundleName }); - std::vector storeMetaData; - if (!MetaDataManager::GetInstance().LoadMeta(prefix, storeMetaData)) { - ZLOGE("load meta failed!"); - return; - } - for (auto &meta : storeMetaData) { - if (meta.instanceId == appIndex && !meta.appId.empty() && !meta.storeId.empty()) { - ZLOGI("updated bundleName:%{public}s, stordId:%{public}s", bundleName.c_str(), meta.storeId.c_str()); - MetaDataManager::GetInstance().DelMeta(CloudInfo::GetSchemaKey(meta), true); - } - } -} } // namespace OHOS::DistributedKv diff --git a/datamgr_service/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.h b/datamgr_service/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.h index 4de54f49d8f5fc169f05ce1f53d83fb2301717fb..3922fbad39591462e059cd88455c6530e9488089 100644 --- a/datamgr_service/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.h +++ b/datamgr_service/services/distributeddataservice/app/src/uninstaller/uninstaller_impl.h @@ -21,12 +21,11 @@ #include "uninstaller.h" namespace OHOS::DistributedKv { -using UninstallEventCallback = std::function; - class UninstallEventSubscriber : public EventFwk::CommonEventSubscriber { public: - explicit UninstallEventSubscriber(const EventFwk::CommonEventSubscribeInfo &info); - int32_t RegisterCallback(const std::string &action, UninstallEventCallback callback); +using UninstallEventCallback = void (UninstallEventSubscriber::*) + (const std::string &bundleName, int32_t userId, int32_t appIndex); + UninstallEventSubscriber(const EventFwk::CommonEventSubscribeInfo &info, KvStoreDataService *kvStoreDataService); ~UninstallEventSubscriber() {} void OnReceiveEvent(const EventFwk::CommonEventData &event) override; @@ -34,8 +33,12 @@ public: private: static constexpr const char *USER_ID = "userId"; static constexpr const char *SANDBOX_APP_INDEX = "sandbox_app_index"; - ConcurrentMap callbacks_; + void OnUninstall(const std::string &bundleName, int32_t userId, int32_t appIndex); + void OnUpdate(const std::string &bundleName, int32_t userId, int32_t appIndex); + std::map callbacks_; + KvStoreDataService *kvStoreDataService_; }; + class UninstallerImpl : public Uninstaller { public: ~UninstallerImpl(); @@ -47,8 +50,6 @@ public: private: static constexpr int32_t RETRY_TIME = 300; static constexpr int32_t RETRY_INTERVAL = 100; - static void OnUninstall(const std::string &bundleName, int32_t userId, int32_t appIndex); - static void OnUpdate(const std::string &bundleName, int32_t userId, int32_t appIndex); int32_t retryTime_; ExecutorPool::Task GetTask(); std::shared_ptr subscriber_ {}; diff --git a/datamgr_service/services/distributeddataservice/framework/cloud/cloud_event.cpp b/datamgr_service/services/distributeddataservice/framework/cloud/cloud_event.cpp index 11f43a392842af44ce70bcd7c2643dd231e7384b..cb2604bd01b7b3593220745fe8a6767ab68b122a 100644 --- a/datamgr_service/services/distributeddataservice/framework/cloud/cloud_event.cpp +++ b/datamgr_service/services/distributeddataservice/framework/cloud/cloud_event.cpp @@ -26,7 +26,7 @@ std::string CloudEvent::GetFeatureName() const return featureName_; } -CloudEvent::StoreInfo CloudEvent::GetStoreInfo() const +const CloudEvent::StoreInfo& CloudEvent::GetStoreInfo() const { return storeInfo_; } diff --git a/datamgr_service/services/distributeddataservice/framework/cloud/cloud_info.cpp b/datamgr_service/services/distributeddataservice/framework/cloud/cloud_info.cpp index 557127498f9cfdd31043f1c928f736a4a52f0258..a50f4d69d03d060d220235e63cfed5dd50bbc043 100644 --- a/datamgr_service/services/distributeddataservice/framework/cloud/cloud_info.cpp +++ b/datamgr_service/services/distributeddataservice/framework/cloud/cloud_info.cpp @@ -98,7 +98,6 @@ bool CloudInfo::IsExist(const std::string &bundleName) const } } return false; -// return apps.find(bundleName) != apps.end(); } std::string CloudInfo::GetPrefix(const std::initializer_list &fields) diff --git a/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_event.h b/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_event.h index 5e3056e40c56ff327e9e09b7a944fde6b2cc0fb5..e1f04f41a37912b4f277c75f7b1e5c26991f9952 100644 --- a/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_event.h +++ b/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_event.h @@ -25,20 +25,22 @@ public: enum : int32_t { FEATURE_INIT = EVT_CLOUD, GET_SCHEMA, + DATA_CHANGE, CLOUD_BUTT }; struct StoreInfo { uint32_t tokenId = 0; - std::string bundleName = ""; - std::string storeName = ""; + std::string bundleName; + std::string storeName; int32_t instanceId = 0; + int32_t user = 0; }; CloudEvent(int32_t evtId, StoreInfo storeInfo, const std::string &featureName = "relational_store"); ~CloudEvent() = default; std::string GetFeatureName() const; - StoreInfo GetStoreInfo() const; + const StoreInfo& GetStoreInfo() const; private: std::string featureName_; diff --git a/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_info.h b/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_info.h index fab877050dc3a08f752ad2d4d359e5213bcc01c2..dc73202775809e0f82e98ecacabfc0f8900f43f8 100644 --- a/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_info.h +++ b/datamgr_service/services/distributeddataservice/framework/include/cloud/cloud_info.h @@ -35,7 +35,6 @@ public: uint64_t totalSpace = 0; uint64_t remainSpace = 0; bool enableCloud = false; -// std::map apps; std::vector apps; std::string GetKey() const; diff --git a/datamgr_service/services/distributeddataservice/framework/include/serializable/serializable.h b/datamgr_service/services/distributeddataservice/framework/include/serializable/serializable.h index e358decc2c249233a0d6fed08074d78ef2caf39c..f652a684b789b18826bc26e5acc59c6cf484a1c1 100644 --- a/datamgr_service/services/distributeddataservice/framework/include/serializable/serializable.h +++ b/datamgr_service/services/distributeddataservice/framework/include/serializable/serializable.h @@ -15,13 +15,13 @@ #ifndef OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_SERIALIZABLE_H #define OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_SERIALIZABLE_H -#include #include #include #include "visibility.h" #ifndef JSON_NOEXCEPTION #define JSON_NOEXCEPTION #endif +#include #include namespace OHOS { namespace DistributedData { @@ -70,6 +70,12 @@ public: API_EXPORT static bool SetValue(json &node, bool &value); API_EXPORT static bool SetValue(json &node, const std::vector &value); API_EXPORT static bool SetValue(json &node, const Serializable &value); + + template + API_EXPORT static bool SetValue(json &node, const std::variant<_Types...> &input); + + template + API_EXPORT static bool GetValue(const json &node, const std::string &name, std::variant<_Types...> &value); protected: API_EXPORT ~Serializable() = default; @@ -91,6 +97,17 @@ protected: template static bool SetValue(json &node, const T *value); + template + static bool ReadVariant(const json &node, const std::string &name, uint32_t step, uint32_t index, _OutTp &output); + + template + static bool ReadVariant(const json &node, const std::string &name, uint32_t step, uint32_t index, _OutTp &output); + + template + static bool WriteVariant(json &node, uint32_t step, const _InTp &input); + + template + static bool WriteVariant(json &node, uint32_t step, const _InTp &input); API_EXPORT static const json &GetSubNode(const json &node, const std::string &name); }; @@ -174,6 +191,67 @@ bool Serializable::SetValue(json &node, const T *value) } return SetValue(node, *value); } + +template +bool Serializable::SetValue(json &node, const std::variant<_Types...> &input) +{ + bool ret = SetValue(node[GET_NAME(type)], input.index()); + if (!ret) { + return ret; + } + return WriteVariant(node[GET_NAME(value)], 0, input); +} + +template +bool Serializable::GetValue(const json &node, const std::string &name, std::variant<_Types...> &value) +{ + auto &subNode = GetSubNode(node, name); + if (subNode.is_null()) { + return false; + } + uint32_t index; + bool ret = GetValue(subNode, GET_NAME(type), index); + if (!ret) { + return ret; + } + + return Serializable::ReadVariant(subNode, GET_NAME(value), 0, index, value); +} + +template +bool Serializable::WriteVariant(json &node, uint32_t step, const _InTp &input) +{ + return false; +} + +template +bool Serializable::ReadVariant(const json &node, const std::string &name, uint32_t step, uint32_t index, _OutTp &output) +{ + if (step == index) { + _First result; + if (!Serializable::GetValue(node, name, result)) { + return false; + } + output = result; + return true; + } + return Serializable::ReadVariant<_OutTp, _Rest...>(node, name, step + 1, index, output); +} + +template +bool Serializable::WriteVariant(json &node, uint32_t step, const _InTp &input) +{ + if (step == input.index()) { + return Serializable::SetValue(node, std::get<_First>(input)); + } + return WriteVariant<_InTp, _Rest...>(node, step + 1, input); +} + +template +bool Serializable::ReadVariant(const json &node, const std::string &name, uint32_t step, uint32_t index, _OutTp &output) +{ + return false; +} } // namespace DistributedData } // namespace OHOS #endif // OHOS_DISTRIBUTED_DATA_FRAMEWORKS_COMMON_SERIALIZABLE_H diff --git a/datamgr_service/services/distributeddataservice/framework/include/store/auto_cache.h b/datamgr_service/services/distributeddataservice/framework/include/store/auto_cache.h index b01834a53f1820c7a1e39d4b9ca3f70a83057d95..ca1a5e80045229b2b2c7fa962c5c7156c3294988 100644 --- a/datamgr_service/services/distributeddataservice/framework/include/store/auto_cache.h +++ b/datamgr_service/services/distributeddataservice/framework/include/store/auto_cache.h @@ -44,7 +44,7 @@ public: API_EXPORT void Bind(std::shared_ptr executor); - API_EXPORT Store GetStore(const StoreMetaData &meta, const Watchers &watchers, bool setWatchers = true); + API_EXPORT Store GetStore(const StoreMetaData &meta, const Watchers &watchers); API_EXPORT void CloseStore(uint32_t tokenId, const std::string &storeId); diff --git a/datamgr_service/services/distributeddataservice/framework/store/auto_cache.cpp b/datamgr_service/services/distributeddataservice/framework/store/auto_cache.cpp index 37aff132e26c327b06588afd62088a813ea282c5..db51ad5cbaf53116f7d308d6a719af71490e27ea 100644 --- a/datamgr_service/services/distributeddataservice/framework/store/auto_cache.cpp +++ b/datamgr_service/services/distributeddataservice/framework/store/auto_cache.cpp @@ -52,7 +52,7 @@ AutoCache::~AutoCache() } } -AutoCache::Store AutoCache::GetStore(const StoreMetaData &meta, const Watchers &watchers, bool setWatchers) +AutoCache::Store AutoCache::GetStore(const StoreMetaData &meta, const Watchers &watchers) { Store store; if (meta.storeType >= MAX_CREATOR_NUM || meta.storeType < 0 || !creators_[meta.storeType]) { @@ -60,10 +60,10 @@ AutoCache::Store AutoCache::GetStore(const StoreMetaData &meta, const Watchers & } stores_.Compute(meta.tokenId, - [this, &meta, &watchers, &store, setWatchers](auto &, std::map &stores) -> bool { + [this, &meta, &watchers, &store](auto &, std::map &stores) -> bool { auto it = stores.find(meta.storeId); if (it != stores.end()) { - if (setWatchers) { + if (!watchers.empty()) { it->second.SetObservers(watchers); } store = it->second; diff --git a/datamgr_service/services/distributeddataservice/service/BUILD.gn b/datamgr_service/services/distributeddataservice/service/BUILD.gn index 35707d652c5354fbbb07d7be1c4ecb67d6a67c22..e27030a974b901d651d2dc6b1559510fd40da441 100644 --- a/datamgr_service/services/distributeddataservice/service/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/service/BUILD.gn @@ -56,13 +56,13 @@ ohos_shared_library("distributeddatasvc") { "../../../../data_object/frameworks/innerkitsimpl/include", "../../../../relational_store/interfaces/inner_api/cloud_data/include", "../../../../relational_store/interfaces/inner_api/rdb/include", + "${kv_store_distributeddb_path}", ] sources = [ "backup/src/backup_manager.cpp", "bootstrap/src/bootstrap.cpp", "cloud/cloud_service_impl.cpp", "cloud/cloud_service_stub.cpp", - "cloud/cloud_syncer.cpp", "config/src/config_factory.cpp", "config/src/model/backup_config.cpp", "config/src/model/checker_config.cpp", @@ -108,7 +108,7 @@ ohos_shared_library("distributeddatasvc") { "rdb/rdb_service_stub.cpp", "rdb/rdb_store_observer_impl.cpp", "rdb/rdb_syncer.cpp", - "rdb/value_proxy.cpp", + "rdb/rdb_watcher.cpp", ] cflags = [ "-Wno-multichar" ] diff --git a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp index c2de1f609e1ec7834639657225f81a29a38c6371..f1c4186f6187411e34632b2158bccf86c111694d 100644 --- a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.cpp @@ -53,11 +53,6 @@ CloudServiceImpl::Factory::~Factory() {} CloudServiceImpl::CloudServiceImpl() { - EventCenter::GetInstance().Subscribe(CloudEvent::FEATURE_INIT, [this](const Event &event) { - FeatureInit(event); - return; - }); - EventCenter::GetInstance().Subscribe(CloudEvent::GET_SCHEMA, [this](const Event &event) { GetSchema(event); return; @@ -67,8 +62,9 @@ CloudServiceImpl::CloudServiceImpl() int32_t CloudServiceImpl::EnableCloud(const std::string &id, const std::map &switches) { CloudInfo cloudInfo; - if (GetCloudInfo(IPCSkeleton::GetCallingTokenID(), id, cloudInfo) != SUCCESS) { - return INVALID_ARGUMENT; + auto status = GetCloudInfo(IPCSkeleton::GetCallingTokenID(), id, cloudInfo); + if (status != SUCCESS) { + return status; } cloudInfo.enableCloud = true; for (const auto &item : switches) { @@ -91,8 +87,9 @@ int32_t CloudServiceImpl::EnableCloud(const std::string &id, const std::map bool { @@ -127,8 +125,10 @@ int32_t CloudServiceImpl::ChangeAppSwitch(const std::string &id, const std::stri int32_t CloudServiceImpl::Clean(const std::string &id, const std::map &actions) { CloudInfo cloudInfo; - if (GetCloudInfo(IPCSkeleton::GetCallingTokenID(), id, cloudInfo) != SUCCESS) { - return INVALID_ARGUMENT; + auto tokenId = IPCSkeleton::GetCallingTokenID(); + cloudInfo.user = DistributedKv::AccountDelegate::GetInstance()->GetUserByToken(tokenId); + if (GetCloudInfoFromMeta(cloudInfo) != SUCCESS) { + return ERROR; } auto keys = cloudInfo.GetSchemaKey(); for (const auto &action : actions) { @@ -137,6 +137,7 @@ int32_t CloudServiceImpl::Clean(const std::string &id, const std::mapGetUserByToken(tokenId); + if (GetCloudInfoFromMeta(cloudInfo) != SUCCESS) { + return ERROR; + } + if (cloudInfo.id != id) { + ZLOGE("invalid args, [input] id:%{public}s, [exist] id:%{public}s", Anonymous::Change(id).c_str(), + Anonymous::Change(cloudInfo.id).c_str()); + return INVALID_ARGUMENT; + } + if (!cloudInfo.enableCloud) { + return CLOUD_DISABLE; + } + auto it = std::find_if(cloudInfo.apps.begin(), cloudInfo.apps.end(), + [&bundleName](const CloudInfo::AppInfo &appInfo) -> bool { + return appInfo.bundleName == bundleName; + }); + if (it == cloudInfo.apps.end()) { + ZLOGE("bundleName:%{public}s", bundleName.c_str()); + return INVALID_ARGUMENT; + } + if (!it->cloudSwitch) { + return CLOUD_DISABLE_SWITCH; + } + + auto key = cloudInfo.GetSchemaKey(bundleName); + SchemaMeta schemaMeta; + if (!MetaDataManager::GetInstance().LoadMeta(key, schemaMeta, true)) { + ZLOGE("bundleName:%{public}s", bundleName.c_str()); + return INVALID_ARGUMENT; + } + for (const auto &database : schemaMeta.databases) { + EventCenter::Defer defer; + CloudEvent::StoreInfo storeInfo; + storeInfo.bundleName = it->bundleName; + storeInfo.instanceId = it->instanceId; + storeInfo.user = cloudInfo.user; + storeInfo.storeName = database.name; + auto evt = std::make_unique(CloudEvent::DATA_CHANGE, storeInfo); + EventCenter::GetInstance().PostEvent(std::move(evt)); + } + return SUCCESS; } int32_t CloudServiceImpl::OnInitialize() { + FeatureInit(); Execute(GetCloudTask(0, 0)); return E_OK; } @@ -172,10 +216,12 @@ int32_t CloudServiceImpl::OnUserChange(uint32_t code, const std::string &user, c int32_t CloudServiceImpl::GetCloudInfo(uint32_t tokenId, const std::string &id, CloudInfo &cloudInfo) { cloudInfo.user = DistributedKv::AccountDelegate::GetInstance()->GetUserByToken(tokenId); - if (!MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetKey(), cloudInfo, true) && - GetServerInfo(cloudInfo) != SUCCESS) { - ZLOGE("invalid args, user:%{public}d", cloudInfo.user); - return INVALID_ARGUMENT; + if (GetCloudInfoFromMeta(cloudInfo) != SUCCESS) { + auto status = GetCloudInfoFromServer(cloudInfo); + if (status != SUCCESS) { + ZLOGE("user:%{public}d", cloudInfo.user); + return status; + } } if (cloudInfo.id != id) { ZLOGE("invalid args, [input] id:%{public}s, [exist] id:%{public}s", Anonymous::Change(id).c_str(), @@ -185,35 +231,23 @@ int32_t CloudServiceImpl::GetCloudInfo(uint32_t tokenId, const std::string &id, return SUCCESS; } -int32_t CloudServiceImpl::GetServerInfo(CloudInfo &cloudInfo) +int32_t CloudServiceImpl::GetCloudInfoFromMeta(CloudInfo &cloudInfo) { - auto instance = CloudServer::GetInstance(); - if (instance == nullptr) { - return SERVER_UNAVAILABLE; - } - cloudInfo = instance->GetServerInfo(cloudInfo.user); - if (!cloudInfo.IsValid()) { + if (!MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetKey(), cloudInfo, true)) { + ZLOGE("no exist meta, user:%{public}d", cloudInfo.user); return ERROR; } return SUCCESS; } -std::string CloudServiceImpl::GetAppId(const std::string &bundleName) -{ - CheckerManager::StoreInfo storeInfo; - storeInfo.uid = IPCSkeleton::GetCallingUid(); - storeInfo.tokenId = IPCSkeleton::GetCallingTokenID(); - storeInfo.bundleName = bundleName; - return CheckerManager::GetInstance().GetAppId(storeInfo); -} - -bool CloudServiceImpl::CheckAccess(const std::string &bundleName) +int32_t CloudServiceImpl::GetCloudInfoFromServer(CloudInfo &cloudInfo) { - CheckerManager::StoreInfo storeInfo; - storeInfo.uid = IPCSkeleton::GetCallingUid(); - storeInfo.tokenId = IPCSkeleton::GetCallingTokenID(); - storeInfo.bundleName = bundleName; - return CheckerManager::GetInstance().IsValid(storeInfo); + auto instance = CloudServer::GetInstance(); + if (instance == nullptr) { + return NOT_SUPPORT; + } + cloudInfo = instance->GetServerInfo(cloudInfo.user); + return SUCCESS; } void CloudServiceImpl::UpdateCloudInfo(CloudInfo &cloudInfo) @@ -291,9 +325,21 @@ SchemaMeta CloudServiceImpl::GetSchemaMata(int32_t userId, const std::string &bu ZLOGE("instance is nullptr"); return schemaMeta; } - auto cloudInfo = instance->GetServerInfo(userId); - if (!cloudInfo.IsValid()) { - ZLOGE("cloudInfo is invalid"); + CloudInfo cloudInfo; + cloudInfo.user = userId; + if (!MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetKey(), cloudInfo, true)) { + cloudInfo = instance->GetServerInfo(userId); + if (!cloudInfo.IsValid()) { + ZLOGE("cloudInfo is invalid"); + return schemaMeta; + } + MetaDataManager::GetInstance().SaveMeta(cloudInfo.GetKey(), cloudInfo, true); + } + if (std::find_if(cloudInfo.apps.begin(), cloudInfo.apps.end(), + [&bundleName, &instanceId](const CloudInfo::AppInfo &appInfo) { + return appInfo.bundleName == bundleName && appInfo.instanceId == instanceId; + }) == cloudInfo.apps.end()) { + ZLOGE("bundleName:%{public}s instanceId:%{public}d", bundleName.c_str(), instanceId); return schemaMeta; } std::string schemaKey = cloudInfo.GetSchemaKey(bundleName, instanceId); @@ -317,20 +363,25 @@ StoreMetaData CloudServiceImpl::GetStoreMata(int32_t userId, const std::string & return storeMetaData; } -void CloudServiceImpl::FeatureInit(const Event &event) +void CloudServiceImpl::FeatureInit() { CloudInfo cloudInfo; std::vector users; if (!DistributedKv::AccountDelegate::GetInstance()->QueryUsers(users) || users.empty()) { return; } - cloudInfo.user = *users.begin(); - if (GetServerInfo(cloudInfo) != SUCCESS) { - ZLOGE("failed, user:%{public}d", cloudInfo.user); - return; + for (const auto &user : users) { + if (user == USER_ID) { + continue; + } + cloudInfo.user = user; + if (GetCloudInfoFromServer(cloudInfo) != SUCCESS) { + ZLOGE("failed, user:%{public}d", user); + continue; + } + UpdateCloudInfo(cloudInfo); + AddSchema(cloudInfo); } - UpdateCloudInfo(cloudInfo); - AddSchema(cloudInfo); } void CloudServiceImpl::GetSchema(const Event &event) @@ -341,33 +392,40 @@ void CloudServiceImpl::GetSchema(const Event &event) rdbEvent.GetStoreInfo().instanceId); auto userId = DistributedKv::AccountDelegate::GetInstance()->GetUserByToken(rdbEvent.GetStoreInfo().tokenId); auto schemaMeta = GetSchemaMata(userId, rdbEvent.GetStoreInfo().bundleName, rdbEvent.GetStoreInfo().instanceId); + if (schemaMeta.databases.empty()) { + return; + } auto storeMeta = GetStoreMata(userId, rdbEvent.GetStoreInfo().bundleName, rdbEvent.GetStoreInfo().storeName, rdbEvent.GetStoreInfo().instanceId); + auto instance = CloudServer::GetInstance(); + if (instance == nullptr) { + ZLOGE("instance is nullptr"); + return; + } + auto database = std::find_if(schemaMeta.databases.begin(),schemaMeta.databases.end(), + [&rdbEvent](const auto &database){ + return database.name == rdbEvent.GetStoreInfo().storeName; + }); + if (database == schemaMeta.databases.end()) { + return; + } + ZLOGD("database: %{public}s sync start", database->name.c_str()); + auto cloudDB = instance->ConnectCloudDB(rdbEvent.GetStoreInfo().tokenId, *database); + if (cloudDB == nullptr) { + ZLOGE("cloudDB is nullptr"); + return; + } AutoCache::Watchers watchers; - auto store = AutoCache::GetInstance().GetStore(storeMeta, watchers, false); + auto store = AutoCache::GetInstance().GetStore(storeMeta, watchers); if (store == nullptr) { ZLOGE("store is nullptr"); return; } store->SetSchema(schemaMeta); - auto instance = CloudServer::GetInstance(); - if (instance == nullptr) { - ZLOGE("instance is nullptr"); - return; - } - for (auto &database : schemaMeta.databases) { - if (database.name != rdbEvent.GetStoreInfo().storeName /* || don't need sync */) { - continue; - } - auto cloudDB = instance->ConnectCloudDB(rdbEvent.GetStoreInfo().tokenId, database); - if (cloudDB != nullptr) { - store->Bind(cloudDB); - } - for (auto &table : database.tables) { - ZLOGI("table: %{public}s sync start", table.name.c_str()); - } - // do sync + store->Bind(cloudDB); + for (const auto &table : database->tables) { + ZLOGD("table: %{public}s sync start", table.name.c_str()); } return; } diff --git a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h index bba447c07272ca1f378509fe8818076b6fc546d4..35121c5762f8498ff9619c4b497ace2216aa3839 100644 --- a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h +++ b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_impl.h @@ -39,6 +39,7 @@ public: int32_t OnUserChange(uint32_t code, const std::string &user, const std::string &account) override; private: + static const inline int USER_ID = 0; class Factory { public: Factory() noexcept; @@ -63,15 +64,14 @@ private: StoreMetaData GetStoreMata(int32_t userId, const std::string &bundleName, const std::string &storeName, int32_t instanceId); int32_t GetCloudInfo(uint32_t tokenId, const std::string &id, CloudInfo &cloudInfo); - int32_t GetServerInfo(CloudInfo &cloudInfo); + int32_t GetCloudInfoFromMeta(CloudInfo &cloudInfo); + int32_t GetCloudInfoFromServer(CloudInfo &cloudInfo); int32_t GetAppSchema(int32_t user, const std::string &bundleName, SchemaMeta &schemaMeta); - std::string GetAppId(const std::string &bundleName); - void FeatureInit(const Event &event); + void FeatureInit(); void GetSchema(const Event &event); ExecutorPool::Task GetCloudTask(int32_t retry, int32_t user); void Execute(ExecutorPool::Task task); bool DoSubscribe(const Subscription &sub); - bool CheckAccess(const std::string &bundleName); std::shared_ptr executor_; }; } // namespace OHOS::DistributedData diff --git a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_stub.cpp b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_stub.cpp index 61e9dc63f66d40ad14b86ec79ddef95982497ce1..b14485f4fb8b5056cd39286329f207ac6f557623 100644 --- a/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_stub.cpp +++ b/datamgr_service/services/distributeddataservice/service/cloud/cloud_service_stub.cpp @@ -48,7 +48,8 @@ int CloudServiceStub::OnRemoteRequest(uint32_t code, OHOS::MessageParcel &data, if (!TokenIdKit::IsSystemAppByFullTokenID(IPCSkeleton::GetCallingFullTokenID())) { ZLOGE("permission denied! code:%{public}u, BUTT:%{public}d", code, TRANS_BUTT); - return -1; + auto result = static_cast(PERMISSION_DENIED); + return ITypesUtil::Marshal(reply, result) ? ERR_NONE : IPC_STUB_WRITE_PARCEL_ERR; } std::string id; diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp index 16fd16ba36e3449db4030d83519fe96e85e88981..f7a9b2c79e8dee499b0221d8cb447eb2e3ce73b7 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.cpp @@ -24,11 +24,13 @@ #include "eventcenter/event_center.h" #include "ipc_skeleton.h" #include "log_print.h" +#include "metadata/appid_meta_data.h" #include "metadata/meta_data_manager.h" #include "metadata/store_meta_data.h" #include "permission/permission_validator.h" +#include "rdb_watcher.h" #include "rdb_notifier_proxy.h" -#include "store/auto_cache.h" +#include "rdb_query.h" #include "types_export.h" #include "utils/anonymous.h" #include "utils/constant.h" @@ -44,6 +46,7 @@ using namespace OHOS::DistributedData; using namespace OHOS::Security::AccessToken; using DistributedDB::RelationalStoreManager; using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter; +using system_clock = std::chrono::system_clock; constexpr uint32_t ITERATE_TIMES = 10000; namespace OHOS::DistributedRdb { @@ -91,6 +94,30 @@ RdbServiceImpl::RdbServiceImpl() : autoLaunchObserver_(this) [this](const std::string& identifier, DistributedDB::AutoLaunchParam ¶m) { return ResolveAutoLaunch(identifier, param); }); + EventCenter::GetInstance().Subscribe(CloudEvent::DATA_CHANGE, [this](const Event &event) { + auto &evt = static_cast(event); + auto storeInfo = evt.GetStoreInfo(); + StoreMetaData meta; + meta.storeId = storeInfo.storeName; + meta.bundleName = storeInfo.bundleName; + meta.user = std::to_string(storeInfo.user); + meta.instanceId = storeInfo.instanceId; + meta.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; + if (!MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), meta)) { + ZLOGE("meta empty, bundleName:%{public}s, storeId:%{public}s", + meta.bundleName.c_str(), meta.storeId.c_str()); + return; + } + auto watchers = GetWatchers(meta.tokenId, meta.storeId); + auto store = AutoCache::GetInstance().GetStore(meta, watchers); + if (store == nullptr) { + ZLOGE("store null, storeId:%{public}s", meta.storeId.c_str()); + return; + } + for (const auto &watcher : watchers) { // mock for datachange + watcher->OnChange(GeneralWatcher::Origin::ORIGIN_CLOUD, {}); + } + }); } int32_t RdbServiceImpl::ResolveAutoLaunch(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) @@ -139,6 +166,9 @@ void RdbServiceImpl::OnClientDied(pid_t pid) ZLOGI("client dead pid=%{public}d", pid); syncers_.ComputeIfPresent(pid, [this](const auto& key, StoreSyncersType& syncers) { syncerNum_ -= static_cast(syncers.size()); + for (const auto& [name, syncer] : syncers) { + executors_->Remove(syncer->GetTimerId()); + } return false; }); notifiers_.Erase(pid); @@ -259,12 +289,8 @@ std::shared_ptr RdbServiceImpl::GetRdbSyncer(const RdbSyncerParam &pa } syncers.erase(storeId); } - if (syncers.size() >= MAX_SYNCER_PER_PROCESS) { - ZLOGE("%{public}d exceed MAX_PROCESS_SYNCER_NUM", pid); - return !syncers.empty(); - } - if (syncerNum_ >= MAX_SYNCER_NUM) { - ZLOGE("no available syncer"); + if (syncers.size() >= MAX_SYNCER_PER_PROCESS || syncerNum_ >= MAX_SYNCER_NUM) { + ZLOGE("pid: %{public}d, syncers size: %{public}zu. syncerNum: %{public}d", pid, syncers.size(), syncerNum_); return !syncers.empty(); } auto rdbObserver = new (std::nothrow) RdbStoreObserverImpl(this, pid); @@ -272,7 +298,9 @@ std::shared_ptr RdbServiceImpl::GetRdbSyncer(const RdbSyncerParam &pa return !syncers.empty(); } auto syncer_ = std::make_shared(param, rdbObserver); - if (syncer_->Init(pid, uid, tokenId) != 0) { + StoreMetaData storeMetaData = GetStoreMetaData(param); + MetaDataManager::GetInstance().LoadMeta(storeMetaData.GetKey(), storeMetaData); + if (syncer_->Init(pid, uid, tokenId, storeMetaData) != 0) { return !syncers.empty(); } syncers[storeId] = syncer_; @@ -376,15 +404,74 @@ std::string RdbServiceImpl::GenIdentifier(const RdbSyncerParam ¶m) return TransferStringToHex(identifier); } -int32_t RdbServiceImpl::DoSubscribe(const RdbSyncerParam& param) +int32_t RdbServiceImpl::DoSubscribe(const RdbSyncerParam& param, const SubscribeOption &option) { pid_t pid = IPCSkeleton::GetCallingPid(); - auto identifier = GenIdentifier(param); - ZLOGI("%{public}s %{public}.6s %{public}d", param.storeName_.c_str(), identifier.c_str(), pid); - identifiers_.Insert(identifier, pid); + auto tokenId = IPCSkeleton::GetCallingTokenID(); + switch (option.mode) { + case SubscribeMode::REMOTE: { + auto identifier = GenIdentifier(param); + ZLOGI("%{public}s %{public}.6s %{public}d", param.storeName_.c_str(), identifier.c_str(), pid); + identifiers_.Insert(identifier, pid); + break; + } + case SubscribeMode::CLOUD: // fallthrough + case SubscribeMode::CLOUD_DETAIL: { + syncAgents_.Compute(tokenId, [this, pid, tokenId, ¶m, &option](auto &key, SyncAgent &value) { + if (pid != value.pid_) { + value.ReInit(pid, param.bundleName_); + } + auto storeName = RdbSyncer::RemoveSuffix(param.storeName_); + auto it = value.watchers_.find(storeName); + if (it == value.watchers_.end()) { + auto watcher = std::make_shared(this, tokenId, storeName); + value.watchers_[storeName] = { watcher }; + value.mode_[storeName] = option.mode; + } + return true; + }); + break; + } + default: + return RDB_ERROR; + } return RDB_OK; } +void RdbServiceImpl::OnChange(uint32_t tokenId, const std::string &storeName) +{ + pid_t pid = 0; + syncAgents_.ComputeIfPresent(tokenId, [&pid, &storeName](auto &key, SyncAgent &value) { + pid = value.pid_; + return true; + }); + notifiers_.ComputeIfPresent(pid, [&storeName](const auto& key, const sptr& value) { + value->OnChange(storeName, { storeName }); + return true; + }); +} + +AutoCache::Watchers RdbServiceImpl::GetWatchers(uint32_t tokenId, const std::string &storeName) +{ + AutoCache::Watchers watchers; + syncAgents_.ComputeIfPresent(tokenId, [&storeName, &watchers](auto, SyncAgent &agent) { + auto it = agent.watchers_.find(storeName); + if (it != agent.watchers_.end()) { + watchers = it->second; + } + return true; + }); + return watchers; +} + +void RdbServiceImpl::SyncAgent::ReInit(pid_t pid, const std::string &bundleName) +{ + pid_ = pid; + bundleName_ = bundleName; + watchers_.clear(); + mode_.clear(); +} + int32_t RdbServiceImpl::DoUnSubscribe(const RdbSyncerParam& param) { auto identifier = GenIdentifier(param); @@ -408,8 +495,7 @@ int32_t RdbServiceImpl::RemoteQuery(const RdbSyncerParam& param, const std::stri return syncer->RemoteQuery(device, sql, selectionArgs, resultSet); } -int32_t RdbServiceImpl::CreateRDBTable( - const RdbSyncerParam ¶m, const std::string &writePermission, const std::string &readPermission) +int32_t RdbServiceImpl::CreateRDBTable(const RdbSyncerParam ¶m) { if (!CheckAccess(param.bundleName_, param.storeName_)) { ZLOGE("permission error"); @@ -428,7 +514,9 @@ int32_t RdbServiceImpl::CreateRDBTable( } auto uid = IPCSkeleton::GetCallingUid(); auto tokenId = IPCSkeleton::GetCallingTokenID(); - if (syncer->Init(pid, uid, tokenId, writePermission, readPermission) != RDB_OK) { + StoreMetaData storeMetaData = GetStoreMetaData(param); + MetaDataManager::GetInstance().LoadMeta(storeMetaData.GetKey(), storeMetaData); + if (syncer->Init(pid, uid, tokenId, storeMetaData) != RDB_OK) { ZLOGE("Init error"); delete syncer; return RDB_ERROR; @@ -443,31 +531,12 @@ int32_t RdbServiceImpl::DestroyRDBTable(const RdbSyncerParam ¶m) ZLOGE("permission error"); return RDB_ERROR; } - pid_t pid = IPCSkeleton::GetCallingPid(); - auto rdbObserver = new (std::nothrow) RdbStoreObserverImpl(this, pid); - if (rdbObserver == nullptr) { - return RDB_ERROR; - } - auto syncer = new (std::nothrow) RdbSyncer(param, rdbObserver); - if (syncer == nullptr) { - ZLOGE("new syncer error"); - return RDB_ERROR; - } - - StoreMetaData meta; - if (syncer->DestroyMetaData(meta) != RDB_OK) { - ZLOGE("destroy meta data error"); - delete syncer; - return RDB_ERROR; - } - delete syncer; - return RDB_OK; + auto meta = GetStoreMetaData(param); + return MetaDataManager::GetInstance().DelMeta(meta.GetKey()) ? RDB_OK : RDB_ERROR; } int32_t RdbServiceImpl::OnInitialize() { - auto initEvt = std::make_unique(CloudEvent::FEATURE_INIT, CloudEvent::StoreInfo()); - EventCenter::GetInstance().PostEvent(std::move(initEvt)); return RDB_OK; } @@ -477,25 +546,12 @@ int32_t RdbServiceImpl::GetSchema(const RdbSyncerParam ¶m) ZLOGE("permission error"); return RDB_ERROR; } - auto syncer = GetRdbSyncer(param); - if (syncer == nullptr) { + StoreMetaData storeMeta; + if (CreateMetaData(param, storeMeta) != RDB_OK) { return RDB_ERROR; } -// auto storeMeta = GetStoreMetaData(param); -// StoreMetaData oldMeta; -// bool isCreated = MetaDataManager::GetInstance().LoadMeta(storeMeta.GetKey(), oldMeta); -// if (isCreated && (oldMeta.storeType != storeMeta.storeType || -// Constant::NotEqual(oldMeta.isEncrypt, storeMeta.isEncrypt) || -// oldMeta.area != storeMeta.area)) { -// ZLOGE("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " -// "area:%{public}d->%{public}d", -// storeMeta.bundleName.c_str(), storeMeta.storeId.c_str(), oldMeta.storeType, storeMeta.storeType, -// oldMeta.isEncrypt, storeMeta.isEncrypt, oldMeta.area, storeMeta.area); -// return RDB_ERROR; -// } -// if (!MetaDataManager::GetInstance().SaveMeta(storeMeta.GetKey(), storeMeta)) { -// return RDB_ERROR; -// } + + EventCenter::Defer defer; CloudEvent::StoreInfo storeInfo { IPCSkeleton::GetCallingTokenID(), param.bundleName_, RdbSyncer::RemoveSuffix(param.storeName_), RdbSyncer::GetInstIndex(IPCSkeleton::GetCallingTokenID(), param.bundleName_) }; @@ -526,6 +582,50 @@ StoreMetaData RdbServiceImpl::GetStoreMetaData(const RdbSyncerParam ¶m) return metaData; } +int32_t RdbServiceImpl::CreateMetaData(const RdbSyncerParam ¶m, StoreMetaData &old) +{ + auto meta = GetStoreMetaData(param); + bool isCreated = MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), old); + if (isCreated && (old.storeType != meta.storeType || Constant::NotEqual(old.isEncrypt, meta.isEncrypt) || + old.area != meta.area)) { + ZLOGE("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " + "area:%{public}d->%{public}d", + meta.bundleName.c_str(), meta.storeId.c_str(), old.storeType, meta.storeType, old.isEncrypt, + meta.isEncrypt, old.area, meta.area); + return RDB_ERROR; + } + + auto saved = MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta); + if (!saved) { + return RDB_ERROR; + } + AppIDMetaData appIdMeta; + appIdMeta.bundleName = meta.bundleName; + appIdMeta.appId = meta.appId; + saved = MetaDataManager::GetInstance().SaveMeta(appIdMeta.GetKey(), appIdMeta, true); + if (!saved) { + return RDB_ERROR; + } + if (!param.isEncrypt_ || param.password_.empty()) { + return RDB_OK; + } + return SetSecretKey(param, meta); +} + +bool RdbServiceImpl::SetSecretKey(const RdbSyncerParam ¶m, const StoreMetaData &meta) +{ + SecretKeyMetaData newSecretKey; + newSecretKey.storeType = meta.storeType; + newSecretKey.sKey = CryptoManager::GetInstance().Encrypt(param.password_); + if (newSecretKey.sKey.empty()) { + ZLOGE("encrypt work key error."); + return RDB_ERROR; + } + auto time = system_clock::to_time_t(system_clock::now()); + newSecretKey.time = { reinterpret_cast(&time), reinterpret_cast(&time) + sizeof(time) }; + return MetaDataManager::GetInstance().SaveMeta(meta.GetSecretKey(), newSecretKey, true) ? RDB_OK : RDB_ERROR; +} + int32_t RdbServiceImpl::OnExecutor(std::shared_ptr executors) { executors_ = std::move(executors); diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h index ca13cfba1bb14776b3f43f5d48925e3682db0a6c..c9f3eb54608f972e1020b6935594d86e4bb2073a 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_impl.h @@ -27,6 +27,7 @@ #include "rdb_notifier_proxy.h" #include "rdb_syncer.h" #include "store_observer.h" +#include "store/auto_cache.h" #include "visibility.h" namespace OHOS::DistributedRdb { class API_EXPORT RdbServiceImpl : public RdbServiceStub { @@ -49,8 +50,10 @@ public: void OnDataChange(pid_t pid, const DistributedDB::StoreChangedData& data); - int32_t CreateRDBTable( - const RdbSyncerParam ¶m, const std::string &writePermission, const std::string &readPermission) override; + void OnChange(uint32_t tokenId, const std::string &storeName); + + int32_t CreateRDBTable(const RdbSyncerParam ¶m) override; + int32_t DestroyRDBTable(const RdbSyncerParam ¶m) override; int32_t ResolveAutoLaunch(const std::string &identifier, DistributedDB::AutoLaunchParam ¶m) override; @@ -68,11 +71,22 @@ protected: int32_t DoAsync(const RdbSyncerParam& param, uint32_t seqNum, const SyncOption& option, const RdbPredicates& predicates) override; - int32_t DoSubscribe(const RdbSyncerParam& param) override; + int32_t DoSubscribe(const RdbSyncerParam& param, const SubscribeOption &option) override; int32_t DoUnSubscribe(const RdbSyncerParam& param) override; private: + using Watchers = DistributedData::AutoCache::Watchers; + struct SyncAgent { + pid_t pid_ = 0; + std::string bundleName_; + std::map mode_; + std::map watchers_; + void ReInit(pid_t pid, const std::string &bundleName); + }; + + Watchers GetWatchers(uint32_t tokenId, const std::string &storeName); + std::string GenIdentifier(const RdbSyncerParam& param); bool CheckAccess(const std::string& bundleName, const std::string& storeName); @@ -83,7 +97,9 @@ private: void OnAsyncComplete(pid_t pid, uint32_t seqNum, const SyncResult& result); - StoreMetaData GetStoreMetaData(const RdbSyncerParam& param); + int32_t CreateMetaData(const RdbSyncerParam ¶m, StoreMetaData &old); + StoreMetaData GetStoreMetaData(const RdbSyncerParam ¶m); + bool SetSecretKey(const RdbSyncerParam ¶m, const StoreMetaData &meta); class DeathRecipientImpl : public IRemoteObject::DeathRecipient { public: @@ -117,6 +133,7 @@ private: static constexpr int32_t MAX_SYNCER_PER_PROCESS = 10; static constexpr int32_t SYNCER_TIMEOUT = 60 * 1000; // ms std::shared_ptr executors_; + ConcurrentMap syncAgents_; }; } // namespace OHOS::DistributedRdb #endif diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_stub.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_stub.cpp index 39fd62d4eaacea188f684bbf7afbd7c11b03a34b..e879c52347b29b6ec6451575538010c78daab4b5 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_stub.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_service_stub.cpp @@ -60,9 +60,9 @@ int32_t RdbServiceStub::OnRemoteInitNotifier(MessageParcel &data, MessageParcel { RdbSyncerParam param; sptr notifier; - if (!ITypesUtil::Unmarshal(data, param, notifier) || param.bundleName_.empty() || notifier == nullptr) { - ZLOGE("Unmarshal bundleName:%{public}s notifier is nullptr:%{public}d", param.bundleName_.c_str(), - notifier == nullptr); + if (!ITypesUtil::Unmarshal(data, param, notifier) || notifier == nullptr) { + ZLOGE("Unmarshal bundleName:%{public}s storeName_:%{public}s notifier is nullptr:%{public}d", + param.bundleName_.c_str(), param.storeName_.c_str(), notifier == nullptr); return IPC_STUB_INVALID_DATA_ERR; } auto status = InitNotifier(param, notifier); @@ -134,13 +134,14 @@ int32_t RdbServiceStub::OnRemoteDoAsync(MessageParcel &data, MessageParcel &repl int32_t RdbServiceStub::OnRemoteDoSubscribe(MessageParcel &data, MessageParcel &reply) { RdbSyncerParam param; - if (!ITypesUtil::Unmarshal(data, param)) { + SubscribeOption option; + if (!ITypesUtil::Unmarshal(data, param, option)) { ZLOGE("Unmarshal bundleName_:%{public}s storeName_:%{public}s", param.bundleName_.c_str(), param.storeName_.c_str()); return IPC_STUB_INVALID_DATA_ERR; } - auto status = DoSubscribe(param); + auto status = DoSubscribe(param, option); if (!ITypesUtil::Marshal(reply, status)) { ZLOGE("Marshal status:0x%{public}x", status); return IPC_STUB_WRITE_PARCEL_ERR; @@ -214,17 +215,13 @@ int RdbServiceStub::OnRemoteRequest(uint32_t code, MessageParcel& data, MessageP int32_t RdbServiceStub::OnRemoteDoCreateTable(MessageParcel &data, MessageParcel &reply) { RdbSyncerParam param; - std::string writePermission; - std::string readPermission; - if (!ITypesUtil::Unmarshal(data, param, writePermission, readPermission)) { - ZLOGE("Unmarshal bundleName_:%{public}s storeName_:%{public}s writePermission:%{public}s " - "readPermission:%{public}s", param.bundleName_.c_str(), param.storeName_.c_str(), - DistributedData::Anonymous::Change(writePermission).c_str(), - DistributedData::Anonymous::Change(readPermission).c_str()); + if (!ITypesUtil::Unmarshal(data, param)) { + ZLOGE("Unmarshal bundleName_:%{public}s storeName_:%{public}s", param.bundleName_.c_str(), + param.storeName_.c_str()); return IPC_STUB_INVALID_DATA_ERR; } - int32_t status = CreateRDBTable(param, writePermission, readPermission); + int32_t status = CreateRDBTable(param); if (!ITypesUtil::Marshal(reply, status)) { ZLOGE("Marshal status:0x%{public}x", status); return IPC_STUB_WRITE_PARCEL_ERR; diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_syncer.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_syncer.cpp index 1e72273a19bd803f4687d7b798ea7091960b459b..00a31f9a11432a39ddc9c116fd268f80de3a9491 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_syncer.cpp +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_syncer.cpp @@ -102,26 +102,19 @@ std::string RdbSyncer::GetStoreId() const return RemoveSuffix(param_.storeName_); } -int32_t RdbSyncer::Init( - pid_t pid, pid_t uid, uint32_t token, const std::string &writePermission, const std::string &readPermission) +int32_t RdbSyncer::Init(pid_t pid, pid_t uid, uint32_t token, const StoreMetaData &meta) { ZLOGI("enter"); pid_ = pid; uid_ = uid; token_ = token; - StoreMetaData oldMeta; - StoreMetaData meta; - if (CreateMetaData(meta, oldMeta) != RDB_OK) { - ZLOGE("create meta data failed"); - return RDB_ERROR; - } if (InitDBDelegate(meta) != RDB_OK) { ZLOGE("delegate is nullptr"); return RDB_ERROR; } - if (oldMeta.storeType == RDB_DEVICE_COLLABORATION && oldMeta.version < StoreMetaData::UUID_CHANGED_TAG) { + if (meta.storeType == RDB_DEVICE_COLLABORATION && meta.version < StoreMetaData::UUID_CHANGED_TAG) { delegate_->RemoveDeviceData(); } @@ -129,78 +122,6 @@ int32_t RdbSyncer::Init( return RDB_OK; } -int32_t RdbSyncer::DestroyMetaData(StoreMetaData &meta) -{ - FillMetaData(meta); - auto deleted = MetaDataManager::GetInstance().DelMeta(meta.GetKey(), true); - return deleted ? RDB_OK : RDB_ERROR; -} - -void RdbSyncer::FillMetaData(StoreMetaData &meta) -{ - meta.uid = uid_; - meta.tokenId = token_; - meta.instanceId = GetInstIndex(token_, param_.bundleName_); - meta.bundleName = param_.bundleName_; - meta.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid; - meta.storeId = RemoveSuffix(param_.storeName_); - meta.user = std::to_string(AccountDelegate::GetInstance()->GetUserByToken(token_)); - meta.storeType = param_.type_; - meta.securityLevel = param_.level_; - meta.area = param_.area_; - meta.appId = CheckerManager::GetInstance().GetAppId(Converter::ConvertToStoreInfo(meta)); - meta.appType = "harmony"; - meta.hapName = param_.hapName_; - meta.dataDir = DirectoryManager::GetInstance().GetStorePath(meta) + "/" + param_.storeName_; - meta.account = AccountDelegate::GetInstance()->GetCurrentAccountId(); - meta.isEncrypt = param_.isEncrypt_; -} - -int32_t RdbSyncer::CreateMetaData(StoreMetaData &meta, StoreMetaData &old) -{ - FillMetaData(meta); - bool isCreated = MetaDataManager::GetInstance().LoadMeta(meta.GetKey(), old); - if (isCreated && (old.storeType != meta.storeType || Constant::NotEqual(old.isEncrypt, meta.isEncrypt) || - old.area != meta.area)) { - ZLOGE("meta bundle:%{public}s store:%{public}s type:%{public}d->%{public}d encrypt:%{public}d->%{public}d " - "area:%{public}d->%{public}d", - meta.bundleName.c_str(), meta.storeId.c_str(), old.storeType, meta.storeType, old.isEncrypt, - meta.isEncrypt, old.area, meta.area); - return RDB_ERROR; - } - - auto saved = MetaDataManager::GetInstance().SaveMeta(meta.GetKey(), meta); - if (!saved) { - return RDB_ERROR; - } - AppIDMetaData appIdMeta; - appIdMeta.bundleName = meta.bundleName; - appIdMeta.appId = meta.appId; - saved = MetaDataManager::GetInstance().SaveMeta(appIdMeta.GetKey(), appIdMeta, true); - if (!saved) { - return RDB_ERROR; - } - if (!param_.isEncrypt_ || param_.password_.empty()) { - return RDB_OK; - } - return SetSecretKey(meta); -} - -bool RdbSyncer::SetSecretKey(const StoreMetaData &meta) -{ - SecretKeyMetaData newSecretKey; - newSecretKey.storeType = meta.storeType; - newSecretKey.sKey = CryptoManager::GetInstance().Encrypt(param_.password_); - if (newSecretKey.sKey.empty()) { - ZLOGE("encrypt work key error."); - return RDB_ERROR; - } - param_.password_.assign(param_.password_.size(), 0); - auto time = system_clock::to_time_t(system_clock::now()); - newSecretKey.time = { reinterpret_cast(&time), reinterpret_cast(&time) + sizeof(time) }; - return MetaDataManager::GetInstance().SaveMeta(meta.GetSecretKey(), newSecretKey, true) ? RDB_OK : RDB_ERROR; -} - bool RdbSyncer::GetPassword(const StoreMetaData &metaData, DistributedDB::CipherPassword &password) { if (!metaData.isEncrypt) { diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_syncer.h b/datamgr_service/services/distributeddataservice/service/rdb/rdb_syncer.h index b103c7ad123c71147761dda0349bd2e8c749c898..68d1e44fbb4d227b10d4d8075439d3beeae02da2 100644 --- a/datamgr_service/services/distributeddataservice/service/rdb/rdb_syncer.h +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_syncer.h @@ -34,8 +34,7 @@ public: RdbSyncer(const RdbSyncerParam& param, RdbStoreObserverImpl* observer); ~RdbSyncer() noexcept; - int32_t Init(pid_t pid, pid_t uid, uint32_t token, const std::string &writePermission = "", - const std::string &readPermission = ""); + int32_t Init(pid_t pid, pid_t uid, uint32_t token, const StoreMetaData &meta); pid_t GetPid() const; @@ -56,8 +55,6 @@ public: int32_t RemoteQuery(const std::string& device, const std::string& sql, const std::vector& selectionArgs, sptr& resultSet); - int32_t DestroyMetaData(StoreMetaData &meta); - static std::string RemoveSuffix(const std::string& name); static int32_t GetInstIndex(uint32_t tokenId, const std::string &bundleName); @@ -73,10 +70,7 @@ private: std::string GetAppId() const; - int32_t CreateMetaData(StoreMetaData &meta, StoreMetaData &old); - void FillMetaData(StoreMetaData &meta); int32_t InitDBDelegate(const StoreMetaData &meta); - bool SetSecretKey(const StoreMetaData &meta); DistributedDB::RelationalStoreDelegate* GetDelegate(); @@ -95,7 +89,6 @@ private: static void HandleSyncStatus(const std::map>& SyncStatus, SyncResult& result); - static void EqualTo(const RdbPredicateOperation& operation, DistributedDB::Query& query); static void NotEqualTo(const RdbPredicateOperation& operation, DistributedDB::Query& query); static void And(const RdbPredicateOperation& operation, DistributedDB::Query& query); diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_watcher.cpp b/datamgr_service/services/distributeddataservice/service/rdb/rdb_watcher.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01572668fe1ae78a84267ee25e22145718de26da --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_watcher.cpp @@ -0,0 +1,43 @@ +/* + * 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. + */ + +#define LOG_TAG "RdbWatcher" + +#include "rdb_watcher.h" +#include "log_print.h" +#include "error/general_error.h" + +namespace OHOS::DistributedRdb { +using namespace DistributedData; +using Err = DistributedData::GeneralError; +RdbWatcher::RdbWatcher(RdbServiceImpl *rdbService, uint32_t tokenId, const std::string &storeName) + : rdbService_(rdbService), tokenId_(tokenId), storeName_(storeName) +{ +} + +int32_t RdbWatcher::OnChange(Origin origin, const std::string &id) +{ + if (rdbService_ == nullptr) { + return Err::E_ERROR; + } + rdbService_->OnChange(tokenId_, storeName_); + return Err::E_OK; +} + +int32_t RdbWatcher::OnChange(Origin origin, const std::string &id, const std::vector &values) +{ + return Err::E_NOT_SUPPORT; +} +} // namespace OHOS::DistributedRdb diff --git a/datamgr_service/services/distributeddataservice/service/rdb/rdb_watcher.h b/datamgr_service/services/distributeddataservice/service/rdb/rdb_watcher.h new file mode 100644 index 0000000000000000000000000000000000000000..65af021637c2009f343c961bb97c5365987d041e --- /dev/null +++ b/datamgr_service/services/distributeddataservice/service/rdb/rdb_watcher.h @@ -0,0 +1,37 @@ +/* + * 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_DISTRIBUTED_DATA_DATAMGR_SERVICE_RDB_GENERAL_WATCHER_H +#define OHOS_DISTRIBUTED_DATA_DATAMGR_SERVICE_RDB_GENERAL_WATCHER_H +#include "rdb_service_impl.h" +#include "store/general_value.h" +#include "store/general_watcher.h" + +namespace OHOS::DistributedRdb { +class RdbServiceImpl; +class RdbWatcher : public DistributedData::GeneralWatcher { +public: + explicit RdbWatcher(RdbServiceImpl *rdbService, uint32_t tokenId, const std::string &storeName); + int32_t OnChange(Origin origin, const std::string &id) override; + int32_t OnChange(Origin origin, const std::string &id, + const std::vector &values) override; + +private: + RdbServiceImpl* rdbService_ {}; + uint32_t tokenId_ = 0; + std::string storeName_ {}; +}; +} // namespace OHOS::DistributedRdb +#endif // OHOS_DISTRIBUTED_DATA_DATAMGR_SERVICE_RDB_GENERAL_WATCHER_H diff --git a/datamgr_service/services/distributeddataservice/service/test/BUILD.gn b/datamgr_service/services/distributeddataservice/service/test/BUILD.gn index 5a7ff143f256cf1a0563baa789cab1c99e9cbbca..97d837b7d759caed31c3009c0c00c1e264864183 100644 --- a/datamgr_service/services/distributeddataservice/service/test/BUILD.gn +++ b/datamgr_service/services/distributeddataservice/service/test/BUILD.gn @@ -43,7 +43,7 @@ ohos_unittest("CloudDataTest") { "mock/db_change_data_mock.cpp", "mock/db_store_mock.cpp", ] - + include_dirs = [ "../../../../../relational_store/interfaces/inner_api/rdb/include" ] diff --git a/datamgr_service/services/distributeddataservice/service/test/cloud_data_test.cpp b/datamgr_service/services/distributeddataservice/service/test/cloud_data_test.cpp index 031ea345fe46c08ebe7edac05a69c39af50cf45b..781ed1582970417c3ee1453713dfcbdf6b0f02ca 100644 --- a/datamgr_service/services/distributeddataservice/service/test/cloud_data_test.cpp +++ b/datamgr_service/services/distributeddataservice/service/test/cloud_data_test.cpp @@ -19,6 +19,7 @@ #include "account/account_delegate.h" #include "cloud/cloud_event.h" #include "cloud/cloud_server.h" +#include "cloud/schema_meta.h" #include "communicator/device_manager_adapter.h" #include "device_matrix.h" #include "eventcenter/event_center.h" @@ -44,11 +45,13 @@ public: void SetUp(); void TearDown(); + static SchemaMeta schemaMeta_; protected: static constexpr const char *TEST_DISTRIBUTEDDATA_BUNDLE = "test_distributeddata"; static constexpr const char *TEST_DISTRIBUTEDDATA_STORE = "test_service_meta"; void InitMetaData(); + void InitSchemaMeta(); static std::shared_ptr dbStoreMock_; StoreMetaData metaData_; }; @@ -83,29 +86,7 @@ CloudInfo CloudServerMock::GetServerInfo(int32_t userId) SchemaMeta CloudServerMock::GetAppSchema(int32_t userId, const std::string &bundleName) { - SchemaMeta::Field field1; - field1.colName = "test_cloud_field_name1"; - field1.alias = "test_cloud_field_alias1"; - SchemaMeta::Field field2; - field2.colName = "test_cloud_field_name2"; - field2.alias = "test_cloud_field_alias2"; - - SchemaMeta::Table table; - table.name = "test_cloud_table_name"; - table.alias = "test_cloud_table_alias"; - table.fields.emplace_back(field1); - table.fields.emplace_back(field2); - - SchemaMeta::Database database; - database.name = TEST_CLOUD_STORE; - database.alias = "test_cloud_database_alias"; - database.tables.emplace_back(table); - - SchemaMeta schemaMeta; - schemaMeta.version = 1; - schemaMeta.databases.emplace_back(database); - - return schemaMeta; + return CloudDataTest::schemaMeta_; } std::shared_ptr CloudDataTest::dbStoreMock_ = std::make_shared(); @@ -126,6 +107,30 @@ void CloudDataTest::InitMetaData() value.type = OHOS::DistributedKv::PolicyType::IMMEDIATE_SYNC_ON_ONLINE; } +void CloudDataTest::InitSchemaMeta() +{ + SchemaMeta::Field field1; + field1.colName = "test_cloud_field_name1"; + field1.alias = "test_cloud_field_alias1"; + SchemaMeta::Field field2; + field2.colName = "test_cloud_field_name2"; + field2.alias = "test_cloud_field_alias2"; + + SchemaMeta::Table table; + table.name = "test_cloud_table_name"; + table.alias = "test_cloud_table_alias"; + table.fields.emplace_back(field1); + table.fields.emplace_back(field2); + + SchemaMeta::Database database; + database.name = TEST_CLOUD_STORE; + database.alias = "test_cloud_database_alias"; + database.tables.emplace_back(table); + + schemaMeta_.version = 1; + schemaMeta_.databases.emplace_back(database); +} + void CloudDataTest::SetUpTestCase(void) { MetaDataManager::GetInstance().Initialize(dbStoreMock_, nullptr, [](const auto &, auto) { @@ -157,6 +162,7 @@ void CloudDataTest::SetUp() storeMetaData.user = std::to_string(DistributedKv::AccountDelegate::GetInstance()->GetUserByToken(storeMetaData.tokenId)); MetaDataManager::GetInstance().SaveMeta(storeMetaData.GetKey(), storeMetaData); + InitSchemaMeta(); } void CloudDataTest::TearDown() {} @@ -175,14 +181,15 @@ HWTEST_F(CloudDataTest, GetSchema, TestSize.Level0) auto cloudInfo = cloudServerMock->GetServerInfo( DistributedKv::AccountDelegate::GetInstance()->GetUserByToken(OHOS::IPCSkeleton::GetCallingTokenID())); ASSERT_TRUE(MetaDataManager::GetInstance().DelMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), true)); - StoreMetaData storeMetaData; + SchemaMeta schemaMeta; ASSERT_FALSE( - MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), storeMetaData, true)); + MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta, true)); CloudEvent::StoreInfo storeInfo { OHOS::IPCSkeleton::GetCallingTokenID(), TEST_CLOUD_BUNDLE, TEST_CLOUD_STORE, 0 }; auto event = std::make_unique(CloudEvent::GET_SCHEMA, std::move(storeInfo), "test_service"); EventCenter::GetInstance().PostEvent(move(event)); ASSERT_TRUE( - MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), storeMetaData, true)); + MetaDataManager::GetInstance().LoadMeta(cloudInfo.GetSchemaKey(TEST_CLOUD_BUNDLE), schemaMeta, true)); + ASSERT_EQ(to_string(schemaMeta.Marshall()), to_string(schemaMeta_.Marshall())); } } // namespace DistributedDataTest } // namespace OHOS diff --git a/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h b/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h index 6c7bc59d1e5061ea1c95f3a7ac1e622512e21730..5e28457e7055c26731630fd47fc50a727bc88d7a 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h +++ b/relational_store/frameworks/native/rdb/include/rdb_service_proxy.h @@ -49,8 +49,7 @@ public: int32_t RemoteQuery(const RdbSyncerParam& param, const std::string& device, const std::string& sql, const std::vector& selectionArgs, sptr& resultSet) override; - int32_t CreateRDBTable( - const RdbSyncerParam ¶m, const std::string &writePermission, const std::string &readPermission) override; + int32_t CreateRDBTable(const RdbSyncerParam ¶m) override; int32_t DestroyRDBTable(const RdbSyncerParam ¶m) override; ObserverMap ExportObservers(); @@ -65,7 +64,7 @@ protected: int32_t DoAsync(const RdbSyncerParam& param, uint32_t seqNum, const SyncOption& option, const RdbPredicates& predicates) override; - int32_t DoSubscribe(const RdbSyncerParam& param) override; + int32_t DoSubscribe(const RdbSyncerParam& param, const SubscribeOption &option) override; int32_t DoUnSubscribe(const RdbSyncerParam& param) override; diff --git a/relational_store/frameworks/native/rdb/include/rdb_store_impl.h b/relational_store/frameworks/native/rdb/include/rdb_store_impl.h index eb1d3df454ddbfd830fd18ed2afbc77ac1431cb6..078a04c75adc88d93465e1007d5a1153476b60a3 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_store_impl.h +++ b/relational_store/frameworks/native/rdb/include/rdb_store_impl.h @@ -119,7 +119,6 @@ private: int FreeTransaction(SqliteConnection *connection, const std::string &sql); std::pair> GetInsertParams( std::map &&values, const std::string &table); - const RdbStoreConfig rdbStoreConfig; SqliteConnectionPool *connectionPool; static const int MAX_IDLE_SESSION_SIZE = 5; diff --git a/relational_store/frameworks/native/rdb/include/rdb_types_util.h b/relational_store/frameworks/native/rdb/include/rdb_types_util.h index b2cd43928a5ab0ab7d6f47a2b0f89e9840285692..dd023b618cb64c76074c6add88d51da9d6c2319d 100644 --- a/relational_store/frameworks/native/rdb/include/rdb_types_util.h +++ b/relational_store/frameworks/native/rdb/include/rdb_types_util.h @@ -46,6 +46,10 @@ API_EXPORT bool Marshalling(const RdbOperation &input, MessageParcel &data); template<> API_EXPORT bool Unmarshalling(RdbOperation &output, MessageParcel &data); template<> +API_EXPORT bool Marshalling(const SubOption &input, MessageParcel &data); +template<> +API_EXPORT bool Unmarshalling(SubOption &output, MessageParcel &data); +template<> API_EXPORT bool Marshalling(const ValueObject &input, MessageParcel &data); template<> API_EXPORT bool Unmarshalling(ValueObject &output, MessageParcel &data); diff --git a/relational_store/frameworks/native/rdb/src/rdb_manager_impl.cpp b/relational_store/frameworks/native/rdb/src/rdb_manager_impl.cpp index d7321f9253f99b8aa73840622cb7f8a2def9171c..4023b53674217a0d5d5ec930992ddb0b6693af6d 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_manager_impl.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_manager_impl.cpp @@ -29,6 +29,7 @@ #include "rdb_errno.h" namespace OHOS::DistributedRdb { +using RdbServiceProxy = DistributedRdb::RdbServiceProxy; using namespace OHOS::NativeRdb; std::shared_ptr RdbManagerImpl::GetDistributedDataManager() { @@ -100,7 +101,19 @@ int RdbManagerImpl::GetRdbService(const RdbSyncerParam ¶m, std::shared_ptr serviceProxy = iface_cast(remote); + sptr serviceProxy = nullptr; + if (remote->IsProxyObject()) { + serviceProxy = iface_cast(remote); + } + + if (serviceProxy == nullptr) { + serviceProxy = new (std::nothrow) RdbServiceProxy(remote); + } + + if (serviceProxy == nullptr) { + return E_ERROR; + } +// sptr serviceProxy = iface_cast(remote); if (serviceProxy->InitNotifier(param) != RDB_OK) { ZLOGE("init notifier failed"); return E_ERROR; diff --git a/relational_store/frameworks/native/rdb/src/rdb_service_proxy.cpp b/relational_store/frameworks/native/rdb/src/rdb_service_proxy.cpp index fa87c474e0b2cc045f10be994dd4d1d08e47873f..bac75d407b46baf7780d22542d4fad02ee8d6e21 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_service_proxy.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_service_proxy.cpp @@ -221,11 +221,11 @@ std::string RdbServiceProxy::RemoveSuffix(const std::string& name) int32_t RdbServiceProxy::Subscribe(const RdbSyncerParam ¶m, const SubscribeOption &option, RdbStoreObserver *observer) { - if (option.mode != SubscribeMode::REMOTE) { + if (option.mode < SubscribeMode::REMOTE || option.mode >= SUBSCRIBE_MODE_MAX) { ZLOGE("subscribe mode invalid"); return RDB_ERROR; } - if (DoSubscribe(param) != RDB_OK) { + if (DoSubscribe(param, option) != RDB_OK) { ZLOGI("communicate to server failed"); return RDB_ERROR; } @@ -244,10 +244,10 @@ int32_t RdbServiceProxy::Subscribe(const RdbSyncerParam ¶m, const SubscribeO return RDB_OK; } -int32_t RdbServiceProxy::DoSubscribe(const RdbSyncerParam ¶m) +int32_t RdbServiceProxy::DoSubscribe(const RdbSyncerParam ¶m, const SubscribeOption &option) { MessageParcel reply; - int32_t status = IPC_SEND(RDB_SERVICE_CMD_SUBSCRIBE, reply, param); + int32_t status = IPC_SEND(RDB_SERVICE_CMD_SUBSCRIBE, reply, param, option); if (status != RDB_OK) { ZLOGE("status:%{public}d, bundleName:%{public}s, storeName:%{public}s", status, param.bundleName_.c_str(), param.storeName_.c_str()); @@ -317,16 +317,14 @@ void RdbServiceProxy::ImportObservers(ObserverMap &observers) return false; }); } -int32_t RdbServiceProxy::CreateRDBTable( - const RdbSyncerParam ¶m, const std::string &writePermission, const std::string &readPermission) + +int32_t RdbServiceProxy::CreateRDBTable(const RdbSyncerParam ¶m) { MessageParcel reply; - int32_t status = IPC_SEND(RDB_SERVICE_CREATE_RDB_TABLE, reply, param, writePermission, readPermission); + int32_t status = IPC_SEND(RDB_SERVICE_CREATE_RDB_TABLE, reply, param); if (status != RDB_OK) { - ZLOGE("status:%{public}d, bundleName:%{public}s, storeName:%{public}s," - "writePermission:%{public}.6s, readPermission:%{public}.6s", - status, param.bundleName_.c_str(), param.storeName_.c_str(), - writePermission.c_str(), readPermission.c_str()); + ZLOGE("status:%{public}d, bundleName:%{public}s, storeName:%{public}s", status, param.bundleName_.c_str(), + param.storeName_.c_str()); } return status; } diff --git a/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp b/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp index ec086c35f022f1f31a8c3a1c4dcd5b1e3ec732e0..2b8b7a56615b90e185050b6432e765e0cf0271a6 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_store_impl.cpp @@ -92,24 +92,15 @@ int RdbStoreImpl::InnerOpen(const RdbStoreConfig &config) syncerParam_.isEncrypt_ = config.IsEncrypt(); syncerParam_.password_ = {}; - //config.GetTokenType() == 1 - uint32_t id = IPCSkeleton::GetSelfTokenID() & 0xffffffff; - if (AccessTokenKit::GetTokenTypeFlag(id) != TOKEN_HAP) { - LOG_DEBUG("%{public}s is not a hap.", config.GetBundleName().c_str()); - return E_OK; - } std::shared_ptr service = nullptr; errCode = DistributedRdb::RdbManagerImpl::GetInstance().GetRdbService(syncerParam_, service); if (errCode != E_OK) { LOG_ERROR("GetRdbService failed, err is %{public}d.", errCode); return E_OK; } - errCode = service->GetSchema(syncerParam_); - if (errCode != E_OK) { - LOG_ERROR("GetSchema failed, err is %{public}d.", errCode); - } + service->GetSchema(syncerParam_); if (!config.GetUri().empty()) { - errCode = service->CreateRDBTable(syncerParam_, config.GetWritePermission(), config.GetReadPermission()); + errCode = service->CreateRDBTable(syncerParam_); if (errCode != E_OK) { LOG_ERROR("CreateRDBTable failed"); } else { diff --git a/relational_store/frameworks/native/rdb/src/rdb_types_util.cpp b/relational_store/frameworks/native/rdb/src/rdb_types_util.cpp index 233c13912d0d03771c299df767468ad0bff5b054..f269f84a0a187fa6a00ac3c86b1c663b1b6d5214 100644 --- a/relational_store/frameworks/native/rdb/src/rdb_types_util.cpp +++ b/relational_store/frameworks/native/rdb/src/rdb_types_util.cpp @@ -69,6 +69,20 @@ bool Unmarshalling(RdbOperation &output, MessageParcel &data) return ret; } +template<> +bool Marshalling(const SubOption &input, MessageParcel &data) +{ + return ITypesUtil::Marshal(data, static_cast(input.mode)); +} + +template<> +bool Unmarshalling(SubOption &output, MessageParcel &data) +{ + int32_t mode = static_cast(output.mode); + auto ret = ITypesUtil::Unmarshal(data, mode); + output.mode = static_cast(mode); + return ret; +} template<> bool Marshalling(const ValueObject &input, MessageParcel &data) { diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_service.h b/relational_store/interfaces/inner_api/rdb/include/rdb_service.h index fc8f6ed33cf6cf6f69a2517a2a1eeb5e739dce6e..9e82eda3105ebe10adb69646cf818406e7d15693 100644 --- a/relational_store/interfaces/inner_api/rdb/include/rdb_service.h +++ b/relational_store/interfaces/inner_api/rdb/include/rdb_service.h @@ -56,8 +56,7 @@ public: virtual int32_t RemoteQuery(const RdbSyncerParam ¶m, const std::string &device, const std::string &sql, const std::vector &selectionArgs, sptr &resultSet) = 0; - virtual int32_t CreateRDBTable(const RdbSyncerParam ¶m, const std::string &writePermission, - const std::string &readPermission) = 0; + virtual int32_t CreateRDBTable(const RdbSyncerParam ¶m) = 0; virtual int32_t DestroyRDBTable(const RdbSyncerParam ¶m) = 0; @@ -73,7 +72,7 @@ protected: virtual int32_t DoAsync(const RdbSyncerParam ¶m, uint32_t seqNum, const SyncOption &option, const RdbPredicates &predicates) = 0; - virtual int32_t DoSubscribe(const RdbSyncerParam ¶m) = 0; + virtual int32_t DoSubscribe(const RdbSyncerParam ¶m, const SubscribeOption &option) = 0; virtual int32_t DoUnSubscribe(const RdbSyncerParam ¶m) = 0; }; diff --git a/relational_store/interfaces/inner_api/rdb/include/rdb_types.h b/relational_store/interfaces/inner_api/rdb/include/rdb_types.h index ed0d372f80ffefc4b76f7981122d4220007fc16e..37111d400e8233dd16528b1ef9ec0a1d112ccde7 100644 --- a/relational_store/interfaces/inner_api/rdb/include/rdb_types.h +++ b/relational_store/interfaces/inner_api/rdb/include/rdb_types.h @@ -100,6 +100,7 @@ struct RdbPredicates { enum SubscribeMode { REMOTE, CLOUD, + CLOUD_DETAIL, SUBSCRIBE_MODE_MAX };