From 7042c4885439c2060dbe6c8d5336cf17e2badd71 Mon Sep 17 00:00:00 2001 From: li-tiangang4 Date: Wed, 5 Jun 2024 20:10:14 +0800 Subject: [PATCH] =?UTF-8?q?=E6=95=B0=E6=8D=AE=E5=88=86=E7=BA=A7=E9=9C=80?= =?UTF-8?q?=E6=B1=82=E5=8F=8Abug=E4=BF=AE=E5=A4=8D=E5=9B=9E=E5=90=885.0bet?= =?UTF-8?q?a?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: li-tiangang4 --- bundle.json | 1 - common/utils/include/device_type.h | 6 +- .../include/idistributed_hardware_source.h | 20 +-- .../src/distributed_hardware_fwk_kit.cpp | 2 +- .../distributedhardwarefwkservice/BUILD.gn | 2 - .../include/accessmanager/access_manager.h | 7 +- .../componentmanager/component_enable.h | 4 +- .../componentmanager/component_manager.h | 9 +- .../include/distributed_hardware_manager.h | 7 +- .../include/resourcemanager/db_adapter.h | 6 +- .../resourcemanager/meta_info_manager.h | 8 ++ .../include/task/monitor_task_timer.h | 34 ----- .../include/transport/dh_comm_tool.h | 6 +- .../include/utils/dh_context.h | 11 +- .../src/accessmanager/access_manager.cpp | 4 +- .../componentmanager/component_manager.cpp | 71 ++++------ .../dh_data_sync_trigger_listener.cpp | 12 +- .../componentmanager/dh_state_listener.cpp | 8 +- .../src/distributed_hardware_manager.cpp | 28 ++-- .../distributed_hardware_manager_factory.cpp | 2 +- .../src/distributed_hardware_service.cpp | 4 + .../local_hardware_manager.cpp | 7 +- .../src/resourcemanager/capability_info.cpp | 4 + .../capability_info_manager.cpp | 2 +- .../src/resourcemanager/db_adapter.cpp | 91 ++++++++++-- .../resourcemanager/meta_capability_info.cpp | 4 + .../src/resourcemanager/meta_info_manager.cpp | 132 +++++++++++++++++- .../src/resourcemanager/version_info.cpp | 4 + .../resourcemanager/version_info_manager.cpp | 2 +- .../src/task/monitor_task_timer.cpp | 75 ---------- .../src/task/offline_task.cpp | 36 +++-- .../src/task/online_task.cpp | 69 ++++++--- .../src/transport/dh_comm_tool.cpp | 36 +++-- .../src/transport/dh_transport.cpp | 39 ++++-- .../src/transport/dh_transport_obj.cpp | 4 + .../src/utils/dh_context.cpp | 34 +++++ .../src/component_manager_test.cpp | 4 +- .../common/dbadapter/src/db_adapter_test.cpp | 8 +- utils/BUILD.gn | 1 - utils/src/anonymous_string.cpp | 3 + utils/src/dh_utils_tool.cpp | 3 +- 41 files changed, 511 insertions(+), 299 deletions(-) delete mode 100644 services/distributedhardwarefwkservice/include/task/monitor_task_timer.h delete mode 100644 services/distributedhardwarefwkservice/src/task/monitor_task_timer.cpp diff --git a/bundle.json b/bundle.json index 4f8e8db1..86b33cd7 100644 --- a/bundle.json +++ b/bundle.json @@ -55,7 +55,6 @@ "bounds_checking_function", "power_manager", "openssl", - "json", "ffmpeg", "zlib" ] diff --git a/common/utils/include/device_type.h b/common/utils/include/device_type.h index 0f383ad9..fc7d50c1 100644 --- a/common/utils/include/device_type.h +++ b/common/utils/include/device_type.h @@ -54,13 +54,15 @@ const std::unordered_map DHTypeStrMap = { }; struct DeviceInfo { + std::string networkId; std::string uuid; std::string deviceId; std::string deviceName; uint16_t deviceType; - explicit DeviceInfo(std::string uuid, std::string deviceId, std::string deviceName, uint16_t deviceType) - : uuid(uuid), deviceId(deviceId), deviceName(deviceName), deviceType(deviceType) {} + explicit DeviceInfo(std::string networkId, std::string uuid, std::string deviceId, std::string deviceName, + uint16_t deviceType) : networkId(networkId), uuid(uuid), deviceId(deviceId), deviceName(deviceName), + deviceType(deviceType) {} }; /* The key is DHType, the value is the prefix of DHId */ diff --git a/common/utils/include/idistributed_hardware_source.h b/common/utils/include/idistributed_hardware_source.h index 9c4889c9..db75a479 100644 --- a/common/utils/include/idistributed_hardware_source.h +++ b/common/utils/include/idistributed_hardware_source.h @@ -24,13 +24,13 @@ namespace DistributedHardware { const std::string COMPONENT_LOADER_GET_SOURCE_HANDLER = "GetSourceHardwareHandler"; class RegisterCallback { public: - virtual int32_t OnRegisterResult(const std::string &uuid, const std::string &dhId, int32_t status, + virtual int32_t OnRegisterResult(const std::string &networkId, const std::string &dhId, int32_t status, const std::string &data) = 0; }; class UnregisterCallback { public: - virtual int32_t OnUnregisterResult(const std::string &uuid, const std::string &dhId, int32_t status, + virtual int32_t OnUnregisterResult(const std::string &networkId, const std::string &dhId, int32_t status, const std::string &data) = 0; }; @@ -55,11 +55,11 @@ public: * @brief report the business state of local virtual driver * corresponding the remote device with the device id and dhid. * - * @param uuid the remote device uuid. + * @param networkId the remote device networkId. * @param dhId the remote device peripheral dhId. * @param state business state. */ - virtual void OnStateChanged(const std::string &uuid, const std::string &dhId, const BusinessState state) = 0; + virtual void OnStateChanged(const std::string &networkId, const std::string &dhId, const BusinessState state) = 0; }; class DataSyncTriggerListener { @@ -67,21 +67,21 @@ public: /** * @brief trigger local distributed hardware open session with remote device with uuid * - * @param uuid the remote device uuid + * @param networkId the remote device networkId */ - virtual void OnDataSyncTrigger(const std::string &uuid) = 0; + virtual void OnDataSyncTrigger(const std::string &networkId) = 0; }; class IDistributedHardwareSource { public: virtual int32_t InitSource(const std::string ¶ms) = 0; virtual int32_t ReleaseSource() = 0; - virtual int32_t RegisterDistributedHardware(const std::string &uuid, const std::string &dhId, + virtual int32_t RegisterDistributedHardware(const std::string &networkId, const std::string &dhId, const EnableParam ¶m, std::shared_ptr callback) = 0; - virtual int32_t UnregisterDistributedHardware(const std::string &uuid, const std::string &dhId, + virtual int32_t UnregisterDistributedHardware(const std::string &networkId, const std::string &dhId, std::shared_ptr callback) = 0; - virtual int32_t ConfigDistributedHardware(const std::string &uuid, const std::string &dhId, const std::string &key, - const std::string &value) = 0; + virtual int32_t ConfigDistributedHardware(const std::string &networkId, const std::string &dhId, + const std::string &key, const std::string &value) = 0; virtual void RegisterDistributedHardwareStateListener( std::shared_ptr listener) = 0; virtual void UnregisterDistributedHardwareStateListener() = 0; diff --git a/interfaces/inner_kits/src/distributed_hardware_fwk_kit.cpp b/interfaces/inner_kits/src/distributed_hardware_fwk_kit.cpp index fc3d530e..d15296f6 100644 --- a/interfaces/inner_kits/src/distributed_hardware_fwk_kit.cpp +++ b/interfaces/inner_kits/src/distributed_hardware_fwk_kit.cpp @@ -158,7 +158,7 @@ int32_t DistributedHardwareFwkKit::ReleaseAVCenter(int32_t engineId) DHLOGI("DHFWK not online or get proxy failed, can not release av control center"); return ERR_DH_FWK_POINTER_IS_NULL; } - + DHFWKSAManager::GetInstance().RemoveAVTransControlCenterCbFromCache(engineId); return DHFWKSAManager::GetInstance().GetDHFWKProxy()->ReleaseAVCenter(engineId); } diff --git a/services/distributedhardwarefwkservice/BUILD.gn b/services/distributedhardwarefwkservice/BUILD.gn index 92597676..e516c6ec 100644 --- a/services/distributedhardwarefwkservice/BUILD.gn +++ b/services/distributedhardwarefwkservice/BUILD.gn @@ -95,7 +95,6 @@ ohos_shared_library("distributedhardwarefwksvr") { "src/resourcemanager/version_info_manager.cpp", "src/task/disable_task.cpp", "src/task/enable_task.cpp", - "src/task/monitor_task_timer.cpp", "src/task/offline_task.cpp", "src/task/online_task.cpp", "src/task/task.cpp", @@ -138,7 +137,6 @@ ohos_shared_library("distributedhardwarefwksvr") { "hitrace:hitrace_meter", "init:libbegetutil", "ipc:ipc_core", - "json:nlohmann_json_static", "kv_store:distributeddata_inner", "power_manager:powermgr_client", "resource_schedule_service:ressched_client", diff --git a/services/distributedhardwarefwkservice/include/accessmanager/access_manager.h b/services/distributedhardwarefwkservice/include/accessmanager/access_manager.h index e5d2b909..2d68ce33 100644 --- a/services/distributedhardwarefwkservice/include/accessmanager/access_manager.h +++ b/services/distributedhardwarefwkservice/include/accessmanager/access_manager.h @@ -45,7 +45,8 @@ public: virtual void OnDeviceOffline(const DmDeviceInfo &deviceInfo) override; virtual void OnDeviceReady(const DmDeviceInfo &deviceInfo) override; virtual void OnDeviceChanged(const DmDeviceInfo &deviceInfo) override; - + /* Send device online event which is already online */ + void CheckTrustedDeviceOnline(); int32_t Dump(const std::vector &argsStr, std::string &result); private: @@ -54,10 +55,6 @@ private: int32_t UnRegisterDevStateCallback(); int32_t InitDeviceManager(); int32_t UnInitDeviceManager(); - - /* Send device online event which is already online */ - void SendTrustedDeviceOnline(); - std::mutex accessMutex_; }; } // namespace DistributedHardware diff --git a/services/distributedhardwarefwkservice/include/componentmanager/component_enable.h b/services/distributedhardwarefwkservice/include/componentmanager/component_enable.h index 4569ecfe..c6840749 100644 --- a/services/distributedhardwarefwkservice/include/componentmanager/component_enable.h +++ b/services/distributedhardwarefwkservice/include/componentmanager/component_enable.h @@ -27,9 +27,9 @@ class ComponentEnable : public std::enable_shared_from_this, pu public: ComponentEnable(); virtual ~ComponentEnable(); - int32_t Enable(const std::string &uuid, const std::string &dhId, const EnableParam ¶m, + int32_t Enable(const std::string &networkId, const std::string &dhId, const EnableParam ¶m, IDistributedHardwareSource *handler); - int32_t OnRegisterResult(const std::string &uuid, const std::string &dhId, int32_t status, + int32_t OnRegisterResult(const std::string &networkId, const std::string &dhId, int32_t status, const std::string &data) override; private: diff --git a/services/distributedhardwarefwkservice/include/componentmanager/component_manager.h b/services/distributedhardwarefwkservice/include/componentmanager/component_manager.h index ac570fbd..cdb9e2b9 100644 --- a/services/distributedhardwarefwkservice/include/componentmanager/component_manager.h +++ b/services/distributedhardwarefwkservice/include/componentmanager/component_manager.h @@ -34,7 +34,6 @@ #include "idistributed_hardware_source.h" #include "impl_utils.h" #include "low_latency_listener.h" -#include "monitor_task_timer.h" #include "meta_capability_info.h" #include "task_board.h" #include "task_factory.h" @@ -108,8 +107,7 @@ private: DHType dhType, EnableParam ¶m); int32_t GetVersionFromVerMgr(const std::string &uuid, const DHType dhType, std::string &version, bool isSink); int32_t GetVersionFromVerInfoMgr(const std::string &uuid, const DHType dhType, std::string &version, bool isSink); - int32_t GetVersion(const std::string &networkId, const std::string &uuid, - DHType dhType, std::string &version, bool isSink); + int32_t GetVersion(const std::string &uuid, DHType dhType, std::string &version, bool isSink); void UpdateVersionCache(const std::string &uuid, const VersionInfo &versionInfo); void DoRecover(DHType dhType); @@ -121,7 +119,6 @@ private: int32_t InitComponentHandler(); int32_t InitSAMonitor(); void StartComponent(); - void StartTaskMonitor(); void RegisterDHStateListener(); void RegisterDataSyncTriggerListener(); void InitDHCommTool(); @@ -130,7 +127,6 @@ private: void UnregisterDHStateListener(); void UnregisterDataSyncTriggerListener(); void UnInitDHCommTool(); - void StopTaskMonitor(); void StopComponent(); void StopPrivacy(); int32_t GetEnableCapParam(const std::string &networkId, const std::string &uuid, DHType dhType, EnableParam ¶m, @@ -149,7 +145,6 @@ private: std::shared_ptr cameraCompPrivacy_ = nullptr; std::shared_ptr compMonitorPtr_ = nullptr; sptr lowLatencyListener_ = nullptr; - std::shared_ptr monitorTaskTimer_ = nullptr; std::atomic isUnInitTimeOut_; // record the remote device business state, {{deviceUUID, dhId}, BusinessState}. @@ -161,7 +156,7 @@ private: std::shared_ptr eventHandler_; std::shared_ptr dhCommToolPtr_; - // save those remote dh that need refresh by full capability, {{deviceUUID, dhId}, TaskParam}. + // save those remote dh that need refresh by full capability, {{device networkId, dhId}, TaskParam}. std::map, TaskParam> needRefreshTaskParams_; std::mutex needRefreshTaskParamsMtx_; }; diff --git a/services/distributedhardwarefwkservice/include/distributed_hardware_manager.h b/services/distributedhardwarefwkservice/include/distributed_hardware_manager.h index 45f47659..97ce0f0a 100644 --- a/services/distributedhardwarefwkservice/include/distributed_hardware_manager.h +++ b/services/distributedhardwarefwkservice/include/distributed_hardware_manager.h @@ -17,8 +17,10 @@ #define OHOS_DISTRIBUTED_HARDWARE_MANAGER_H #include "idistributed_hardware_manager.h" -#include "single_instance.h" + +#include #include "device_type.h" +#include "single_instance.h" namespace OHOS { namespace DistributedHardware { @@ -34,6 +36,9 @@ public: int32_t GetComponentVersion(std::unordered_map &versionMap) override; int32_t Dump(const std::vector &argsStr, std::string &result) override; +private: + std::atomic isLocalInit{false}; + std::atomic isAllInit{false}; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/include/resourcemanager/db_adapter.h b/services/distributedhardwarefwkservice/include/resourcemanager/db_adapter.h index ddaa2746..8394a152 100644 --- a/services/distributedhardwarefwkservice/include/resourcemanager/db_adapter.h +++ b/services/distributedhardwarefwkservice/include/resourcemanager/db_adapter.h @@ -40,7 +40,7 @@ public: virtual ~DBAdapter(); // default init auto-sync kv store - int32_t Init(bool isAutoSync); + int32_t Init(bool isAutoSync, DistributedKv::DataType dataType); // init local kv store int32_t InitLocal(); void UnInit(); @@ -62,10 +62,11 @@ private: void RegisterKvStoreDeathListener(); void UnRegisterKvStoreDeathListener(); // get default kv store with auto sync - DistributedKv::Status GetKvStorePtr(bool isAutoSync); + DistributedKv::Status GetKvStorePtr(bool isAutoSync, DistributedKv::DataType dataType); // get local kv store with no sync with other devices DistributedKv::Status GetLocalKvStorePtr(); bool DBDiedOpt(int32_t ×); + void TriggerDynamicQuery(const std::string &key); private: DistributedKv::AppId appId_; @@ -75,6 +76,7 @@ private: std::shared_ptr dataChangeListener_; std::mutex dbAdapterMutex_; bool isAutoSync {false}; + DistributedKv::DataType dataType {DistributedKv::DataType::TYPE_DYNAMICAL}; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/include/resourcemanager/meta_info_manager.h b/services/distributedhardwarefwkservice/include/resourcemanager/meta_info_manager.h index d3670e34..cb569fcc 100644 --- a/services/distributedhardwarefwkservice/include/resourcemanager/meta_info_manager.h +++ b/services/distributedhardwarefwkservice/include/resourcemanager/meta_info_manager.h @@ -48,6 +48,10 @@ public: std::shared_ptr &metaCapPtr); void GetMetaCapInfosByDeviceId(const std::string &deviceId, std::vector> &metaCapInfos); + /* Database data changes callback */ + virtual void OnChange(const DistributedKv::ChangeNotification &changeNotification) override; + /* Cloud data changes callback */ + void OnChange(const DistributedKv::DataOrigin &origin, Keys &&keys) override; class MetaInfoManagerEventHandler : public AppExecFwk::EventHandler { public: @@ -63,6 +67,10 @@ public: private: MetaInfoManager(); int32_t GetMetaCapByValue(const std::string &value, std::shared_ptr &metaCapPtr); + void HandleMetaCapabilityAddChange(const std::vector &insertRecords); + void HandleMetaCapabilityUpdateChange(const std::vector &updateRecords); + void HandleMetaCapabilityDeleteChange(const std::vector &deleteRecords); + std::vector GetEntriesByKeys(const std::vector &keys); private: mutable std::mutex metaInfoMgrMutex_; std::shared_ptr dbAdapterPtr_; diff --git a/services/distributedhardwarefwkservice/include/task/monitor_task_timer.h b/services/distributedhardwarefwkservice/include/task/monitor_task_timer.h deleted file mode 100644 index 703da1b9..00000000 --- a/services/distributedhardwarefwkservice/include/task/monitor_task_timer.h +++ /dev/null @@ -1,34 +0,0 @@ -/* - * 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. - */ - -#ifndef OHOS_DISTRIBUTED_HARDWARE_MONITOR_TASK_TIMER_H -#define OHOS_DISTRIBUTED_HARDWARE_MONITOR_TASK_TIMER_H - -#include "dh_timer.h" - -namespace OHOS { -namespace DistributedHardware { -class MonitorTaskTimer : public DHTimer { -public: - MonitorTaskTimer(std::string timerId, int32_t delayTimerMs); - ~MonitorTaskTimer() override; - -private: - void ExecuteInner() override; - void HandleStopTimer() override; -}; -} // namespace DistributedHardware -} // namespace OHOS -#endif diff --git a/services/distributedhardwarefwkservice/include/transport/dh_comm_tool.h b/services/distributedhardwarefwkservice/include/transport/dh_comm_tool.h index c43248c3..ac7bace6 100644 --- a/services/distributedhardwarefwkservice/include/transport/dh_comm_tool.h +++ b/services/distributedhardwarefwkservice/include/transport/dh_comm_tool.h @@ -53,11 +53,13 @@ public: class DHCommToolEventHandler : public AppExecFwk::EventHandler { public: - DHCommToolEventHandler(const std::shared_ptr &runner); + DHCommToolEventHandler(const std::shared_ptr &runner, + std::shared_ptr dhCommToolPtr); ~DHCommToolEventHandler() override = default; void ProcessEvent(const AppExecFwk::InnerEvent::Pointer &event) override; private: - void ProcessFullCapsRsp(const FullCapsRsp &capsRsp); + void ProcessFullCapsRsp(const FullCapsRsp &capsRsp, const std::shared_ptr dhCommToolPtr); + std::weak_ptr dhCommToolWPtr_; }; std::shared_ptr GetEventHandler(); const std::shared_ptr GetDHTransportPtr(); diff --git a/services/distributedhardwarefwkservice/include/utils/dh_context.h b/services/distributedhardwarefwkservice/include/utils/dh_context.h index c7869ea0..ec368f08 100644 --- a/services/distributedhardwarefwkservice/include/utils/dh_context.h +++ b/services/distributedhardwarefwkservice/include/utils/dh_context.h @@ -45,9 +45,16 @@ public: size_t GetOnlineCount(); std::string GetNetworkIdByUUID(const std::string &uuid); std::string GetUUIDByNetworkId(const std::string &networkId); - /* DeviceId is which is hashed by sha256 */ std::string GetUUIDByDeviceId(const std::string &deviceId); + /** + * @brief Get the Network Id By Device Id object + * + * @param deviceId the device form uuid hash + * @return std::string the networkId for the deviceId + */ + std::string GetNetworkIdByDeviceId(const std::string &deviceId); + std::string GetDeviceIdByDBGetPrefix(const std::string &prefix); class CommonEventHandler : public AppExecFwk::EventHandler { public: @@ -70,7 +77,7 @@ private: void RegisterPowerStateLinstener(); private: - DeviceInfo devInfo_ { "", "", "", 0 }; + DeviceInfo devInfo_ { "", "", "", "", 0 }; std::mutex devMutex_; /* Save online device uuid and networkId */ diff --git a/services/distributedhardwarefwkservice/src/accessmanager/access_manager.cpp b/services/distributedhardwarefwkservice/src/accessmanager/access_manager.cpp index 248aa050..94c20417 100644 --- a/services/distributedhardwarefwkservice/src/accessmanager/access_manager.cpp +++ b/services/distributedhardwarefwkservice/src/accessmanager/access_manager.cpp @@ -58,12 +58,10 @@ int32_t AccessManager::Init() DHLOGE("InitDeviceManager failed"); return ERR_DH_FWK_ACCESS_INIT_DM_FAILED; } - if (RegisterDevStateCallback() != DH_FWK_SUCCESS) { DHLOGE("RegisterDevStateCallback failed"); return ERR_DH_FWK_ACCESS_REGISTER_DM_FAILED; } - SendTrustedDeviceOnline(); return DH_FWK_SUCCESS; } @@ -181,7 +179,7 @@ void AccessManager::OnDeviceChanged(const DmDeviceInfo &deviceInfo) return; } -void AccessManager::SendTrustedDeviceOnline() +void AccessManager::CheckTrustedDeviceOnline() { std::vector deviceList; DeviceManager::GetInstance().GetTrustedDeviceList(DH_FWK_PKG_NAME, "", deviceList); diff --git a/services/distributedhardwarefwkservice/src/componentmanager/component_manager.cpp b/services/distributedhardwarefwkservice/src/componentmanager/component_manager.cpp index 9ef56b41..c5b372f1 100644 --- a/services/distributedhardwarefwkservice/src/componentmanager/component_manager.cpp +++ b/services/distributedhardwarefwkservice/src/componentmanager/component_manager.cpp @@ -62,14 +62,12 @@ namespace { constexpr int32_t DISABLE_RETRY_MAX_TIMES = 3; constexpr int32_t ENABLE_PARAM_RETRY_TIME = 500 * 1000; constexpr int32_t INVALID_SA_ID = -1; - constexpr int32_t MONITOR_TASK_DELAY_MS = 5 * 1000; constexpr int32_t UNINIT_COMPONENT_TIMEOUT_SECONDS = 2; const std::string MONITOR_TASK_TIMER_ID = "monitor_task_timer_id"; } ComponentManager::ComponentManager() : compSource_({}), compSink_({}), compSrcSaId_({}), compMonitorPtr_(std::make_shared()), lowLatencyListener_(new(std::nothrow) LowLatencyListener), - monitorTaskTimer_(std::make_shared(MONITOR_TASK_TIMER_ID, MONITOR_TASK_DELAY_MS)), isUnInitTimeOut_(false), dhBizStates_({}), dhStateListener_(std::make_shared()), dataSyncTriggerListener_(std::make_shared()), dhCommToolPtr_(std::make_shared()), needRefreshTaskParams_({}) @@ -102,7 +100,6 @@ int32_t ComponentManager::Init() } StartComponent(); - StartTaskMonitor(); RegisterDHStateListener(); RegisterDataSyncTriggerListener(); InitDHCommTool(); @@ -163,13 +160,6 @@ void ComponentManager::StartComponent() } } -void ComponentManager::StartTaskMonitor() -{ - if (monitorTaskTimer_ != nullptr) { - monitorTaskTimer_->StartTimer(); - } -} - void ComponentManager::RegisterDHStateListener() { for (const auto &item : compSource_) { @@ -213,7 +203,6 @@ int32_t ComponentManager::UnInit() UnregisterDHStateListener(); UnregisterDataSyncTriggerListener(); UnInitDHCommTool(); - StopTaskMonitor(); StopPrivacy(); UnInitSAMonitor(); StopComponent(); @@ -281,14 +270,6 @@ void ComponentManager::UnInitDHCommTool() dhCommToolPtr_->UnInit(); } -void ComponentManager::StopTaskMonitor() -{ - // stop monitor task timer - if (monitorTaskTimer_ != nullptr) { - monitorTaskTimer_->StopTimer(); - } -} - void ComponentManager::StopComponent() { // stop source and sink sa @@ -536,7 +517,7 @@ int32_t ComponentManager::Enable(const std::string &networkId, const std::string std::string subtype = param.subtype; std::map resourceDesc = ComponentLoader::GetInstance().GetCompResourceDesc(); if (resourceDesc.find(subtype) == resourceDesc.end()) { - DHLOGE("GetCompResourceDesc failed."); + DHLOGE("GetCompResourceDesc failed, subtype: %{public}s", subtype.c_str()); return ERR_DH_FWK_RESOURCE_KEY_IS_EMPTY; } bool sensitiveVal = resourceDesc[subtype]; @@ -639,7 +620,6 @@ int32_t ComponentManager::GetEnableCapParam(const std::string &networkId, const DHType dhType, EnableParam ¶m, std::shared_ptr &capability) { DeviceInfo sourceDeviceInfo = GetLocalDeviceInfo(); - std::string sourceNetworkId = DHContext::GetInstance().GetNetworkIdByUUID(sourceDeviceInfo.uuid); std::vector> sourceCapInfos; std::string sourceDHId; CapabilityInfoManager::GetInstance()->GetCapabilitiesByDeviceId(sourceDeviceInfo.deviceId, sourceCapInfos); @@ -650,7 +630,7 @@ int32_t ComponentManager::GetEnableCapParam(const std::string &networkId, const } } std::string sourceVersion(""); - auto ret = GetVersion(sourceNetworkId, sourceDeviceInfo.uuid, dhType, sourceVersion, false); + auto ret = GetVersion(sourceDeviceInfo.uuid, dhType, sourceVersion, false); if (ret != DH_FWK_SUCCESS) { DHLOGE("Get source version failed."); return ERR_DH_FWK_COMPONENT_GET_SINK_VERSION_FAILED; @@ -659,7 +639,7 @@ int32_t ComponentManager::GetEnableCapParam(const std::string &networkId, const param.sinkAttrs = capability->GetDHAttrs(); std::string sinkVersion(""); - ret = GetVersion(networkId, uuid, dhType, sinkVersion, true); + ret = GetVersion(uuid, dhType, sinkVersion, true); if (ret != DH_FWK_SUCCESS) { DHLOGE("Get sink version failed."); // If Version DB not sync, try get sink version from meta info @@ -686,7 +666,6 @@ int32_t ComponentManager::GetEnableMetaParam(const std::string &networkId, const DHType dhType, EnableParam ¶m, std::shared_ptr &metaCapPtr) { DeviceInfo sourceDeviceInfo = GetLocalDeviceInfo(); - std::string sourceNetworkId = DHContext::GetInstance().GetNetworkIdByUUID(sourceDeviceInfo.uuid); std::vector> sourceMetaInfos; std::string sourceDHId; MetaInfoManager::GetInstance()->GetMetaCapInfosByDeviceId(sourceDeviceInfo.deviceId, sourceMetaInfos); @@ -697,7 +676,7 @@ int32_t ComponentManager::GetEnableMetaParam(const std::string &networkId, const } } std::string sourceVersion(""); - auto ret = GetVersion(sourceNetworkId, sourceDeviceInfo.uuid, dhType, sourceVersion, false); + auto ret = GetVersion(sourceDeviceInfo.uuid, dhType, sourceVersion, false); if (ret != DH_FWK_SUCCESS) { DHLOGE("Get source version failed."); return ERR_DH_FWK_COMPONENT_GET_SINK_VERSION_FAILED; @@ -718,17 +697,18 @@ int32_t ComponentManager::GetEnableMetaParam(const std::string &networkId, const int32_t ComponentManager::GetCapParam(const std::string &uuid, const std::string &dhId, std::shared_ptr &capability) { - auto ret = CapabilityInfoManager::GetInstance()->GetCapability(GetDeviceIdByUUID(uuid), dhId, capability); + std::string deviceId = GetDeviceIdByUUID(uuid); + auto ret = CapabilityInfoManager::GetInstance()->GetCapability(deviceId, dhId, capability); if ((ret == DH_FWK_SUCCESS) && (capability != nullptr)) { - DHLOGE("GetCapability success, uuid =%{public}s, dhId = %{public}s, errCode = %{public}d", - GetAnonyString(uuid).c_str(), GetAnonyString(dhId).c_str(), ret); + DHLOGI("GetCapability success, deviceId: %{public}s, uuid: %{public}s, dhId: %{public}s, ret: %{public}d", + GetAnonyString(deviceId).c_str(), GetAnonyString(uuid).c_str(), GetAnonyString(dhId).c_str(), ret); return ret; } - ret = LocalCapabilityInfoManager::GetInstance()->GetCapability(GetDeviceIdByUUID(uuid), dhId, capability); + ret = LocalCapabilityInfoManager::GetInstance()->GetCapability(deviceId, dhId, capability); if ((ret == DH_FWK_SUCCESS) && (capability != nullptr)) { - DHLOGE("Local GetCapability success, uuid =%{public}s, dhId = %{public}s, errCode = %{public}d", - GetAnonyString(uuid).c_str(), GetAnonyString(dhId).c_str(), ret); + DHLOGI("Local GetCaps success, deviceId: %{public}s, uuid: %{public}s, dhId: %{public}s, ret: %{public}d", + GetAnonyString(deviceId).c_str(), GetAnonyString(uuid).c_str(), GetAnonyString(dhId).c_str(), ret); return ret; } @@ -740,7 +720,7 @@ int32_t ComponentManager::GetMetaParam(const std::string &uuid, const std::strin { auto ret = MetaInfoManager::GetInstance()->GetMetaCapInfo(GetDeviceIdByUUID(uuid), dhId, metaCapPtr); if ((ret == DH_FWK_SUCCESS) && (metaCapPtr != nullptr)) { - DHLOGE("GetCapability success, uuid =%{public}s, dhId = %{public}s, errCode = %{public}d", + DHLOGI("GetCapability success, uuid =%{public}s, dhId = %{public}s, errCode = %{public}d", GetAnonyString(uuid).c_str(), GetAnonyString(dhId).c_str(), ret); return ret; } @@ -813,8 +793,7 @@ int32_t ComponentManager::GetVersionFromVerInfoMgr(const std::string &uuid, cons return DH_FWK_SUCCESS; } -int32_t ComponentManager::GetVersion(const std::string &networkId, const std::string &uuid, - DHType dhType, std::string &version, bool isSink) +int32_t ComponentManager::GetVersion(const std::string &uuid, DHType dhType, std::string &version, bool isSink) { int32_t ret = GetVersionFromVerMgr(uuid, dhType, version, isSink); if ((ret == DH_FWK_SUCCESS) && (!version.empty())) { @@ -936,22 +915,22 @@ bool ComponentManager::IsIdenticalAccount(const std::string &networkId) return false; } -void ComponentManager::UpdateBusinessState(const std::string &uuid, const std::string &dhId, BusinessState state) +void ComponentManager::UpdateBusinessState(const std::string &networkId, const std::string &dhId, BusinessState state) { - DHLOGI("UpdateBusinessState, uuid: %{public}s, dhId: %{public}s, state: %{public}" PRIu32, - GetAnonyString(uuid).c_str(), GetAnonyString(dhId).c_str(), (uint32_t)state); + DHLOGI("UpdateBusinessState, networkId: %{public}s, dhId: %{public}s, state: %{public}" PRIu32, + GetAnonyString(networkId).c_str(), GetAnonyString(dhId).c_str(), (uint32_t)state); { std::lock_guard lock(bizStateMtx_); - dhBizStates_[{uuid, dhId}] = state; + dhBizStates_[{networkId, dhId}] = state; } if (state == BusinessState::IDLE) { TaskParam taskParam; - if (!FetchNeedRefreshTask({uuid, dhId}, taskParam)) { + if (!FetchNeedRefreshTask({networkId, dhId}, taskParam)) { return; } - DHLOGI("The dh need refresh, uuid: %{public}s, dhId: %{public}s", - GetAnonyString(uuid).c_str(), GetAnonyString(dhId).c_str()); + DHLOGI("The dh need refresh, networkId: %{public}s, dhId: %{public}s", + GetAnonyString(networkId).c_str(), GetAnonyString(dhId).c_str()); auto task = TaskFactory::GetInstance().CreateTask(TaskType::ENABLE, taskParam, nullptr); TaskExecutor::GetInstance().PushTask(task); } @@ -980,7 +959,7 @@ void ComponentManager::TriggerFullCapsSync(const std::string &networkId) void ComponentManager::SaveNeedRefreshTask(const TaskParam &taskParam) { std::lock_guard lock(needRefreshTaskParamsMtx_); - needRefreshTaskParams_[{taskParam.uuid, taskParam.dhId}] = taskParam; + needRefreshTaskParams_[{taskParam.networkId, taskParam.dhId}] = taskParam; } bool ComponentManager::FetchNeedRefreshTask(const std::pair &taskKey, TaskParam &taskParam) @@ -1013,12 +992,10 @@ void ComponentManager::ComponentManagerEventHandler::ProcessEvent( DHLOGE("The data sync param invalid"); break; } - std::string uuid = *sharedObjPtr; - std::string networkId = DHContext::GetInstance().GetNetworkIdByUUID(uuid); - DHLOGI("Try receive full capabiliy info from uuid: %{public}s, networkId: %{public}s", - GetAnonyString(uuid).c_str(), GetAnonyString(networkId).c_str()); + std::string networkId = *sharedObjPtr; + DHLOGI("Try receive full capabiliy info from networkId: %{public}s", GetAnonyString(networkId).c_str()); if (networkId.empty()) { - DHLOGE("Can not get device networkid by uuid: %{public}s", GetAnonyString(uuid).c_str()); + DHLOGE("Can not get device uuid by networkId: %{public}s", GetAnonyString(networkId).c_str()); break; } ComponentManager::GetInstance().TriggerFullCapsSync(networkId); diff --git a/services/distributedhardwarefwkservice/src/componentmanager/dh_data_sync_trigger_listener.cpp b/services/distributedhardwarefwkservice/src/componentmanager/dh_data_sync_trigger_listener.cpp index 628f3445..74ebc3ed 100644 --- a/services/distributedhardwarefwkservice/src/componentmanager/dh_data_sync_trigger_listener.cpp +++ b/services/distributedhardwarefwkservice/src/componentmanager/dh_data_sync_trigger_listener.cpp @@ -37,11 +37,15 @@ DHDataSyncTriggerListener::~DHDataSyncTriggerListener() DHLOGI("Dtor DHDataSyncTriggerListener"); } -void DHDataSyncTriggerListener::OnDataSyncTrigger(const std::string &uuid) +void DHDataSyncTriggerListener::OnDataSyncTrigger(const std::string &networkId) { - DHLOGI("Receive data sync trigger, uuid: %{public}s", GetAnonyString(uuid).c_str()); - std::shared_ptr uuidPtr = std::make_shared(uuid); - AppExecFwk::InnerEvent::Pointer msgEvent = AppExecFwk::InnerEvent::Get(EVENT_DATA_SYNC_MANUAL, uuidPtr); + DHLOGI("Receive data sync trigger, networkId: %{public}s", GetAnonyString(networkId).c_str()); + if (networkId.empty()) { + DHLOGE("OnDataSyncTrigger networkId is empty"); + return; + } + std::shared_ptr networkIdPtr = std::make_shared(networkId); + AppExecFwk::InnerEvent::Pointer msgEvent = AppExecFwk::InnerEvent::Get(EVENT_DATA_SYNC_MANUAL, networkIdPtr); ComponentManager::GetInstance().GetEventHandler()->SendEvent(msgEvent, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE); } diff --git a/services/distributedhardwarefwkservice/src/componentmanager/dh_state_listener.cpp b/services/distributedhardwarefwkservice/src/componentmanager/dh_state_listener.cpp index 227b1f9e..9ce4d817 100644 --- a/services/distributedhardwarefwkservice/src/componentmanager/dh_state_listener.cpp +++ b/services/distributedhardwarefwkservice/src/componentmanager/dh_state_listener.cpp @@ -36,11 +36,11 @@ DHStateListener::~DHStateListener() DHLOGI("Dtor DHStateListener"); } -void DHStateListener::OnStateChanged(const std::string &uuid, const std::string &dhId, const BusinessState state) +void DHStateListener::OnStateChanged(const std::string &networkId, const std::string &dhId, const BusinessState state) { - DHLOGI("Receive business state change, uuid: %{public}s, dhId: %{public}s, state: %{public}" PRIu32, - GetAnonyString(uuid).c_str(), GetAnonyString(dhId).c_str(), (uint32_t)state); - ComponentManager::GetInstance().UpdateBusinessState(uuid, dhId, state); + DHLOGI("Receive business state change, networkId: %{public}s, dhId: %{public}s, state: %{public}" PRIu32, + GetAnonyString(networkId).c_str(), GetAnonyString(dhId).c_str(), (uint32_t)state); + ComponentManager::GetInstance().UpdateBusinessState(networkId, dhId, state); } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/src/distributed_hardware_manager.cpp b/services/distributedhardwarefwkservice/src/distributed_hardware_manager.cpp index d6a98a4d..ee3f702b 100644 --- a/services/distributedhardwarefwkservice/src/distributed_hardware_manager.cpp +++ b/services/distributedhardwarefwkservice/src/distributed_hardware_manager.cpp @@ -46,27 +46,33 @@ IMPLEMENT_SINGLE_INSTANCE(DistributedHardwareManager); int32_t DistributedHardwareManager::LocalInit() { DHLOGI("DHFWK Local Init begin"); + if (isLocalInit) { + DHLOGI("Local init already finish"); + return DH_FWK_SUCCESS; + } VersionInfoManager::GetInstance()->Init(); - ComponentLoader::GetInstance().Init(); - VersionManager::GetInstance().Init(); CapabilityInfoManager::GetInstance()->Init(); MetaInfoManager::GetInstance()->Init(); + LocalCapabilityInfoManager::GetInstance()->Init(); + ComponentLoader::GetInstance().Init(); + VersionManager::GetInstance().Init(); LocalHardwareManager::GetInstance().Init(); DHLOGI("DHFWK Local Init end"); + isLocalInit = true; return DH_FWK_SUCCESS; } int32_t DistributedHardwareManager::Initialize() { - DHLOGI("start"); - VersionInfoManager::GetInstance()->Init(); - CapabilityInfoManager::GetInstance()->Init(); - MetaInfoManager::GetInstance()->Init(); - LocalCapabilityInfoManager::GetInstance()->Init(); - ComponentLoader::GetInstance().Init(); - VersionManager::GetInstance().Init(); + DHLOGI("DHFWK Normal Init begin"); + if (isAllInit) { + DHLOGI("DHMgr init already finish"); + return DH_FWK_SUCCESS; + } + LocalInit(); ComponentManager::GetInstance().Init(); - LocalHardwareManager::GetInstance().Init(); + DHLOGI("DHFWK Normal Init end"); + isAllInit = true; return DH_FWK_SUCCESS; } @@ -82,6 +88,8 @@ int32_t DistributedHardwareManager::Release() CapabilityInfoManager::GetInstance()->UnInit(); MetaInfoManager::GetInstance()->UnInit(); LocalCapabilityInfoManager::GetInstance()->UnInit(); + isAllInit = false; + isLocalInit = false; return DH_FWK_SUCCESS; } diff --git a/services/distributedhardwarefwkservice/src/distributed_hardware_manager_factory.cpp b/services/distributedhardwarefwkservice/src/distributed_hardware_manager_factory.cpp index bd70d1ef..6da58efc 100644 --- a/services/distributedhardwarefwkservice/src/distributed_hardware_manager_factory.cpp +++ b/services/distributedhardwarefwkservice/src/distributed_hardware_manager_factory.cpp @@ -71,12 +71,12 @@ bool DistributedHardwareManagerFactory::InitLocalDevInfo() bool DistributedHardwareManagerFactory::Init() { DHLOGI("start"); - isInit = true; auto initResult = DistributedHardwareManager::GetInstance().Initialize(); if (initResult != DH_FWK_SUCCESS) { DHLOGE("Initialize failed, errCode = %{public}d", initResult); return false; } + isInit = true; DHLOGI("success"); return true; } diff --git a/services/distributedhardwarefwkservice/src/distributed_hardware_service.cpp b/services/distributedhardwarefwkservice/src/distributed_hardware_service.cpp index 950c5498..c8c34b43 100644 --- a/services/distributedhardwarefwkservice/src/distributed_hardware_service.cpp +++ b/services/distributedhardwarefwkservice/src/distributed_hardware_service.cpp @@ -42,6 +42,8 @@ namespace OHOS { namespace DistributedHardware { +#undef DH_LOG_TAG +#define DH_LOG_TAG "DistributedHardwareService" REGISTER_SYSTEM_ABILITY_BY_ID(DistributedHardwareService, DISTRIBUTED_HARDWARE_SA_ID, true); namespace { constexpr int32_t INIT_BUSINESS_DELAY_TIME_MS = 5 * 100; @@ -108,6 +110,7 @@ bool DistributedHardwareService::DoBusinessInit() eventHandler_->PostTask(executeInnerFunc, INIT_TASK_ID, INIT_BUSINESS_DELAY_TIME_MS); return false; } + DHLOGI("Init AccessManager"); auto ret = AccessManager::GetInstance()->Init(); if (ret != DH_FWK_SUCCESS) { @@ -116,6 +119,7 @@ bool DistributedHardwareService::DoBusinessInit() ret, "dhfwk sa AccessManager init fail."); } InitLocalDevInfo(); + AccessManager::GetInstance()->CheckTrustedDeviceOnline(); return true; } diff --git a/services/distributedhardwarefwkservice/src/localhardwaremanager/local_hardware_manager.cpp b/services/distributedhardwarefwkservice/src/localhardwaremanager/local_hardware_manager.cpp index 6c54a1bf..8a52d1b4 100644 --- a/services/distributedhardwarefwkservice/src/localhardwaremanager/local_hardware_manager.cpp +++ b/services/distributedhardwarefwkservice/src/localhardwaremanager/local_hardware_manager.cpp @@ -116,8 +116,7 @@ void LocalHardwareManager::QueryLocalHardware(const DHType dhType, IHardwareHand DHLOGE("Query hardwareHandler and obtain empty, dhType: %{public}#X", dhType); usleep(QUERY_INTERVAL_TIME); } else { - DHLOGI("Query hardwareHandler success, dhType: %{public}#X!", dhType); - + DHLOGI("Query hardwareHandler success, dhType: %{public}#X!, size: %{public}zu", dhType, dhItems.size()); /* * Failed to delete data when the device restarts or other exception situation. * So check and remove the non-exist local capabilityInfo. @@ -141,8 +140,8 @@ void LocalHardwareManager::QueryMetaHardware(const DHType dhType, IHardwareHandl DHLOGE("Query metahardwareHandler and obtain empty, dhType: %{public}#X", dhType); usleep(QUERY_INTERVAL_TIME); } else { - DHLOGI("Query metahardwareHandler success, dhType: %{public}#X!, size: %d", - dhType, static_cast(metaDhItems.size())); + DHLOGI("Query metahardwareHandler success, dhType: %{public}#X!, size: %{public}zu", + dhType, metaDhItems.size()); metaDHItemsMap_[dhType] = metaDhItems; break; } diff --git a/services/distributedhardwarefwkservice/src/resourcemanager/capability_info.cpp b/services/distributedhardwarefwkservice/src/resourcemanager/capability_info.cpp index 3d50e220..7f65f5f8 100644 --- a/services/distributedhardwarefwkservice/src/resourcemanager/capability_info.cpp +++ b/services/distributedhardwarefwkservice/src/resourcemanager/capability_info.cpp @@ -140,6 +140,10 @@ std::string CapabilityInfo::ToJsonString() } ToJson(jsonObj, *this); char *cjson = cJSON_PrintUnformatted(jsonObj); + if (cjson == nullptr) { + cJSON_Delete(jsonObj); + return ""; + } std::string jsonString(cjson); cJSON_free(cjson); cJSON_Delete(jsonObj); diff --git a/services/distributedhardwarefwkservice/src/resourcemanager/capability_info_manager.cpp b/services/distributedhardwarefwkservice/src/resourcemanager/capability_info_manager.cpp index 88536ea8..9bc21ac0 100644 --- a/services/distributedhardwarefwkservice/src/resourcemanager/capability_info_manager.cpp +++ b/services/distributedhardwarefwkservice/src/resourcemanager/capability_info_manager.cpp @@ -93,7 +93,7 @@ int32_t CapabilityInfoManager::Init() DHLOGE("dbAdapterPtr_ is null"); return ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL; } - if (dbAdapterPtr_->Init(true) != DH_FWK_SUCCESS) { + if (dbAdapterPtr_->Init(true, DistributedKv::DataType::TYPE_DYNAMICAL) != DH_FWK_SUCCESS) { DHLOGE("Init dbAdapterPtr_ failed"); return ERR_DH_FWK_RESOURCE_INIT_DB_FAILED; } diff --git a/services/distributedhardwarefwkservice/src/resourcemanager/db_adapter.cpp b/services/distributedhardwarefwkservice/src/resourcemanager/db_adapter.cpp index 43508ab8..212c8d19 100644 --- a/services/distributedhardwarefwkservice/src/resourcemanager/db_adapter.cpp +++ b/services/distributedhardwarefwkservice/src/resourcemanager/db_adapter.cpp @@ -56,7 +56,7 @@ DBAdapter::~DBAdapter() DHLOGI("DBAdapter Destruction"); } -DistributedKv::Status DBAdapter::GetKvStorePtr(bool isAutoSync) +DistributedKv::Status DBAdapter::GetKvStorePtr(bool isAutoSync, DistributedKv::DataType dataType) { DistributedKv::Options options = { .createIfMissing = true, @@ -66,12 +66,19 @@ DistributedKv::Status DBAdapter::GetKvStorePtr(bool isAutoSync) .securityLevel = DistributedKv::SecurityLevel::S1, .area = DistributedKv::EL1, .kvStoreType = DistributedKv::KvStoreType::SINGLE_VERSION, - .baseDir = DATABASE_DIR + appId_.appId - }; - DistributedKv::SyncPolicy syncPolicyOnline { - .type = DistributedKv::IMMEDIATE_SYNC_ON_ONLINE + .baseDir = DATABASE_DIR + appId_.appId, + .dataType = dataType, + .cloudConfig = { + .enableCloud = true, + .autoSync = true, + } }; - options.policies.emplace_back(syncPolicyOnline); + if (isAutoSync) { + DistributedKv::SyncPolicy syncPolicyOnline { + .type = DistributedKv::IMMEDIATE_SYNC_ON_ONLINE + }; + options.policies.emplace_back(syncPolicyOnline); + } return kvDataMgr_.GetSingleKvStore(options, appId_, storeId_, kvStoragePtr_); } @@ -89,13 +96,16 @@ DistributedKv::Status DBAdapter::GetLocalKvStorePtr() return kvDataMgr_.GetSingleKvStore(options, appId_, storeId_, kvStoragePtr_); } -int32_t DBAdapter::Init(bool isAutoSync) +int32_t DBAdapter::Init(bool isAutoSync, DistributedKv::DataType dataType) { - DHLOGI("Init DB, storeId: %{public}s", storeId_.storeId.c_str()); + this->isAutoSync = isAutoSync; + this->dataType = dataType; + DHLOGI("Init DB, storeId: %{public}s, dataType: %{public}d", + storeId_.storeId.c_str(), static_cast(dataType)); std::lock_guard lock(dbAdapterMutex_); int32_t tryTimes = MAX_INIT_RETRY_TIMES; while (tryTimes > 0) { - DistributedKv::Status status = GetKvStorePtr(isAutoSync); + DistributedKv::Status status = GetKvStorePtr(isAutoSync, dataType); if (status == DistributedKv::Status::SUCCESS && kvStoragePtr_) { DHLOGI("Init KvStorePtr Success"); RegisterChangeListener(); @@ -110,13 +120,15 @@ int32_t DBAdapter::Init(bool isAutoSync) DHLOGE("Init KvStorePtr failed"); return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL; } - this->isAutoSync = isAutoSync; return DH_FWK_SUCCESS; } int32_t DBAdapter::InitLocal() { - DHLOGI("Init local DB, storeId: %{public}s", storeId_.storeId.c_str()); + this->isAutoSync = false; + this->dataType = DistributedKv::DataType::TYPE_STATICS; + DHLOGI("Init local DB, storeId: %{public}s, dataType: %{public}d", + storeId_.storeId.c_str(), static_cast(this->dataType)); std::lock_guard lock(dbAdapterMutex_); int32_t tryTimes = MAX_INIT_RETRY_TIMES; while (tryTimes > 0) { @@ -134,7 +146,6 @@ int32_t DBAdapter::InitLocal() DHLOGE("Init KvStorePtr failed"); return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL; } - this->isAutoSync = false; return DH_FWK_SUCCESS; } @@ -162,7 +173,8 @@ int32_t DBAdapter::ReInit(bool isAutoSync) return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL; } kvStoragePtr_.reset(); - DistributedKv::Status status = this->isAutoSync ? GetKvStorePtr(isAutoSync) : GetLocalKvStorePtr(); + DistributedKv::Status status = this->isAutoSync ? + GetKvStorePtr(isAutoSync, this->dataType) : GetLocalKvStorePtr(); if (status != DistributedKv::Status::SUCCESS || !kvStoragePtr_) { DHLOGW("Get kvStoragePtr_ failed, status: %{public}d", status); return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL; @@ -171,14 +183,59 @@ int32_t DBAdapter::ReInit(bool isAutoSync) return DH_FWK_SUCCESS; } +void DBAdapter::TriggerDynamicQuery(const std::string &key) +{ + DHLOGI("Trigger DynamicQuery, key: %{public}s", GetAnonyString(key).c_str()); + std::string deviceId = DHContext::GetInstance().GetDeviceIdByDBGetPrefix(key); + if (deviceId.empty()) { + DHLOGW("Get deviceId empty, key: %{public}s", GetAnonyString(key).c_str()); + return; + } + + if (deviceId == DHContext::GetInstance().GetDeviceInfo().deviceId) { + DHLOGD("Query local db info, no need dynamic sync"); + return; + } + + std::string uuid = DHContext::GetInstance().GetUUIDByDeviceId(deviceId); + if (uuid.empty()) { + DHLOGW("Get uuid empty, deviceId: %{public}s", GetAnonyString(deviceId).c_str()); + return; + } + if (!DHContext::GetInstance().IsDeviceOnline(uuid)) { + DHLOGW("The device not online, no need dynamic sync, uuid: %{public}s, deviceId: %{public}s", + GetAnonyString(uuid).c_str(), GetAnonyString(deviceId).c_str()); + return; + } + + std::string networkId = DHContext::GetInstance().GetNetworkIdByUUID(uuid); + if (networkId.empty()) { + DHLOGW("The networkId emtpy, uuid: %{public}s", GetAnonyString(uuid).c_str()); + return; + } + + DHLOGI("Try Sync DYNAMIC data with remote dev, networkId: %{public}s", GetAnonyString(networkId).c_str()); + std::function call = + [](DistributedKv::Status status, DistributedKv::Value &&value) { + (void)status; + (void)value; + }; + DistributedKv::Key kvKey(key); + kvStoragePtr_->Get(kvKey, networkId, call); +} + int32_t DBAdapter::GetDataByKey(const std::string &key, std::string &data) { - DHLOGI("Get data by key: %{public}s", GetAnonyString(key).c_str()); + DHLOGI("Get data by key: %{public}s, storeId: %{public}s, dataType: %{public}d", + GetAnonyString(key).c_str(), storeId_.storeId.c_str(), static_cast(this->dataType)); std::lock_guard lock(dbAdapterMutex_); if (kvStoragePtr_ == nullptr) { DHLOGE("kvStoragePtr_ is null"); return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL; } + if (this->dataType == DistributedKv::DataType::TYPE_DYNAMICAL) { + TriggerDynamicQuery(key); + } DistributedKv::Key kvKey(key); DistributedKv::Value kvValue; DistributedKv::Status status = kvStoragePtr_->Get(kvKey, kvValue); @@ -192,12 +249,16 @@ int32_t DBAdapter::GetDataByKey(const std::string &key, std::string &data) int32_t DBAdapter::GetDataByKeyPrefix(const std::string &keyPrefix, std::vector &values) { - DHLOGI("Get data by key prefix: %{public}s", GetAnonyString(keyPrefix).c_str()); + DHLOGI("Get data by key prefix: %{public}s, storeId: %{public}s, dataType: %{public}d", + GetAnonyString(keyPrefix).c_str(), storeId_.storeId.c_str(), static_cast(this->dataType)); std::lock_guard lock(dbAdapterMutex_); if (kvStoragePtr_ == nullptr) { DHLOGE("kvStoragePtr_ is null"); return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL; } + if (this->dataType == DistributedKv::DataType::TYPE_DYNAMICAL) { + TriggerDynamicQuery(keyPrefix); + } // if prefix is empty, get all entries. DistributedKv::Key allEntryKeyPrefix(keyPrefix); diff --git a/services/distributedhardwarefwkservice/src/resourcemanager/meta_capability_info.cpp b/services/distributedhardwarefwkservice/src/resourcemanager/meta_capability_info.cpp index 0d59d2fa..42763419 100644 --- a/services/distributedhardwarefwkservice/src/resourcemanager/meta_capability_info.cpp +++ b/services/distributedhardwarefwkservice/src/resourcemanager/meta_capability_info.cpp @@ -63,6 +63,10 @@ std::string MetaCapabilityInfo::ToJsonString() } ToJson(jsonObj, *this); char *cjson = cJSON_PrintUnformatted(jsonObj); + if (cjson == nullptr) { + cJSON_Delete(jsonObj); + return ""; + } std::string jsonString(cjson); cJSON_free(cjson); cJSON_Delete(jsonObj); diff --git a/services/distributedhardwarefwkservice/src/resourcemanager/meta_info_manager.cpp b/services/distributedhardwarefwkservice/src/resourcemanager/meta_info_manager.cpp index 68e85f93..b328b496 100644 --- a/services/distributedhardwarefwkservice/src/resourcemanager/meta_info_manager.cpp +++ b/services/distributedhardwarefwkservice/src/resourcemanager/meta_info_manager.cpp @@ -91,7 +91,7 @@ int32_t MetaInfoManager::Init() DHLOGE("dbAdapterPtr_ is null"); return ERR_DH_FWK_RESOURCE_DB_ADAPTER_POINTER_NULL; } - if (dbAdapterPtr_->Init(true) != DH_FWK_SUCCESS) { + if (dbAdapterPtr_->Init(false, DistributedKv::DataType::TYPE_STATICS) != DH_FWK_SUCCESS) { DHLOGE("Init dbAdapterPtr_ failed"); return ERR_DH_FWK_RESOURCE_INIT_DB_FAILED; } @@ -140,7 +140,7 @@ int32_t MetaInfoManager::AddMetaCapInfos(const std::vectorGetAnonymousKey().c_str()); continue; } - DHLOGI("AddCapability, Key: %{public}s", metaCapInfo->GetAnonymousKey().c_str()); + DHLOGI("AddMetaCapability, Key: %{public}s", metaCapInfo->GetAnonymousKey().c_str()); keys.push_back(key); values.push_back(metaCapInfo->ToJsonString()); } @@ -300,5 +300,133 @@ int32_t MetaInfoManager::GetMetaCapByValue(const std::string &value, std::shared } return metaCapPtr->FromJsonString(value); } + +void MetaInfoManager::OnChange(const DistributedKv::ChangeNotification &changeNotification) +{ + DHLOGI("MetaInfoManager: DB data OnChange"); + if (!changeNotification.GetInsertEntries().empty() && + changeNotification.GetInsertEntries().size() <= MAX_DB_RECORD_SIZE) { + DHLOGI("MetaInfoManager Handle capability data add change"); + HandleMetaCapabilityAddChange(changeNotification.GetInsertEntries()); + } + if (!changeNotification.GetUpdateEntries().empty() && + changeNotification.GetUpdateEntries().size() <= MAX_DB_RECORD_SIZE) { + DHLOGI("MetaInfoManager Handle capability data update change"); + HandleMetaCapabilityUpdateChange(changeNotification.GetUpdateEntries()); + } + if (!changeNotification.GetDeleteEntries().empty() && + changeNotification.GetDeleteEntries().size() <= MAX_DB_RECORD_SIZE) { + DHLOGI("MetaInfoManager Handle capability data delete change"); + HandleMetaCapabilityDeleteChange(changeNotification.GetDeleteEntries()); + } +} + +void MetaInfoManager::OnChange(const DistributedKv::DataOrigin &origin, Keys &&keys) +{ + DHLOGI("MetaInfoManager: Cloud data OnChange."); + std::vector insertRecords = GetEntriesByKeys(keys[ChangeOp::OP_INSERT]); + if (!insertRecords.empty() && insertRecords.size() <= MAX_DB_RECORD_SIZE) { + DHLOGI("MetaInfoManager Handle capability data add change"); + HandleMetaCapabilityAddChange(insertRecords); + } + std::vector updateRecords = GetEntriesByKeys(keys[ChangeOp::OP_UPDATE]); + if (!updateRecords.empty() && updateRecords.size() <= MAX_DB_RECORD_SIZE) { + DHLOGI("MetaInfoManager Handle capability data update change"); + HandleMetaCapabilityUpdateChange(updateRecords); + } + std::vector delKeys = keys[ChangeOp::OP_DELETE]; + if (!delKeys.empty() && delKeys.size() <= MAX_DB_RECORD_SIZE) { + std::vector deleteRecords; + for (const auto &key : delKeys) { + DistributedKv::Entry entry; + DistributedKv::Key kvKey(key); + entry.key = kvKey; + deleteRecords.emplace_back(entry); + } + DHLOGI("MetaInfoManager Handle capability data delete change"); + HandleMetaCapabilityDeleteChange(deleteRecords); + } +} + +void MetaInfoManager::HandleMetaCapabilityAddChange(const std::vector &insertRecords) +{ + std::lock_guard lock(metaInfoMgrMutex_); + for (const auto &item : insertRecords) { + const std::string value = item.value.ToString(); + std::shared_ptr capPtr; + if (GetCapabilityByValue(value, capPtr) != DH_FWK_SUCCESS) { + DHLOGE("Get Meta capability by value failed"); + continue; + } + const auto keyString = capPtr->GetKey(); + DHLOGI("Add MetaCapability key: %{public}s", capPtr->GetAnonymousKey().c_str()); + globalMetaInfoMap_[keyString] = capPtr; + std::string uuid = DHContext::GetInstance().GetUUIDByDeviceId(capPtr->GetDeviceId()); + if (uuid.empty()) { + DHLOGI("Find uuid failed and never enable"); + continue; + } + std::string networkId = DHContext::GetInstance().GetNetworkIdByUUID(uuid); + if (networkId.empty()) { + DHLOGI("Find network failed and never enable, uuid: %{public}s", GetAnonyString(uuid).c_str()); + continue; + } + TaskParam taskParam = { + .networkId = networkId, + .uuid = uuid, + .dhId = capPtr->GetDHId(), + .dhType = capPtr->GetDHType() + }; + auto task = TaskFactory::GetInstance().CreateTask(TaskType::ENABLE, taskParam, nullptr); + TaskExecutor::GetInstance().PushTask(task); + } +} + +void MetaInfoManager::HandleMetaCapabilityUpdateChange(const std::vector &updateRecords) +{ + std::lock_guard lock(metaInfoMgrMutex_); + for (const auto &item : updateRecords) { + const std::string value = item.value.ToString(); + std::shared_ptr capPtr; + if (GetCapabilityByValue(value, capPtr) != DH_FWK_SUCCESS) { + DHLOGE("Get Meta capability by value failed"); + continue; + } + const auto keyString = capPtr->GetKey(); + DHLOGI("Update MetaCapability key: %{public}s", capPtr->GetAnonymousKey().c_str()); + globalMetaInfoMap_[keyString] = capPtr; + } +} + +void MetaInfoManager::HandleMetaCapabilityDeleteChange(const std::vector &deleteRecords) +{ + std::lock_guard lock(metaInfoMgrMutex_); + for (const auto &item : deleteRecords) { + const std::string value = item.value.ToString(); + std::shared_ptr capPtr; + if (GetCapabilityByValue(value, capPtr) != DH_FWK_SUCCESS) { + DHLOGE("Get Meta capability by value failed"); + continue; + } + const auto keyString = capPtr->GetKey(); + DHLOGI("Delete MetaCapability key: %{public}s", capPtr->GetAnonymousKey().c_str()); + globalMetaInfoMap_.erase(keyString); + } +} + +std::vector MetaInfoManager::GetEntriesByKeys(const std::vector &keys) +{ + DHLOGI("call"); + if (keys.empty()) { + DHLOGE("keys empty."); + return {}; + } + std::lock_guard lock(metaInfoMgrMutex_); + if (dbAdapterPtr_ == nullptr) { + DHLOGE("dbAdapterPtr_ is null"); + return {}; + } + return dbAdapterPtr_->GetEntriesByKeys(keys); +} } } \ No newline at end of file diff --git a/services/distributedhardwarefwkservice/src/resourcemanager/version_info.cpp b/services/distributedhardwarefwkservice/src/resourcemanager/version_info.cpp index 8e02c141..b279effb 100644 --- a/services/distributedhardwarefwkservice/src/resourcemanager/version_info.cpp +++ b/services/distributedhardwarefwkservice/src/resourcemanager/version_info.cpp @@ -51,6 +51,10 @@ std::string VersionInfo::ToJsonString() const } ToJson(jsonObj, *this); char *cjson = cJSON_PrintUnformatted(jsonObj); + if (cjson == nullptr) { + cJSON_Delete(jsonObj); + return ""; + } std::string result(cjson); cJSON_free(cjson); cJSON_Delete(jsonObj); diff --git a/services/distributedhardwarefwkservice/src/resourcemanager/version_info_manager.cpp b/services/distributedhardwarefwkservice/src/resourcemanager/version_info_manager.cpp index da6bbe64..cea69305 100644 --- a/services/distributedhardwarefwkservice/src/resourcemanager/version_info_manager.cpp +++ b/services/distributedhardwarefwkservice/src/resourcemanager/version_info_manager.cpp @@ -86,7 +86,7 @@ int32_t VersionInfoManager::Init() DHLOGI("VersionInfoManager instance init!"); std::lock_guard lock(verInfoMgrMutex_); dbAdapterPtr_ = std::make_shared(APP_ID, GLOBAL_VERSION_ID, shared_from_this()); - if (dbAdapterPtr_->Init(true) != DH_FWK_SUCCESS) { + if (dbAdapterPtr_->Init(true, DistributedKv::DataType::TYPE_DYNAMICAL) != DH_FWK_SUCCESS) { DHLOGE("Init dbAdapterPtr_ failed"); return ERR_DH_FWK_RESOURCE_INIT_DB_FAILED; } diff --git a/services/distributedhardwarefwkservice/src/task/monitor_task_timer.cpp b/services/distributedhardwarefwkservice/src/task/monitor_task_timer.cpp deleted file mode 100644 index d02e8a97..00000000 --- a/services/distributedhardwarefwkservice/src/task/monitor_task_timer.cpp +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Copyright (c) 2022-2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "monitor_task_timer.h" - -#include "anonymous_string.h" -#include "capability_info.h" -#include "capability_info_manager.h" -#include "distributed_hardware_errno.h" -#include "distributed_hardware_log.h" -#include "dh_timer.h" -#include "task_board.h" -#include "task_executor.h" -#include "task_factory.h" - -namespace OHOS { -namespace DistributedHardware { -#undef DH_LOG_TAG -#define DH_LOG_TAG "MonitorTaskTimer" -MonitorTaskTimer::MonitorTaskTimer(std::string timerId, int32_t delayTimeMs) : DHTimer(timerId, delayTimeMs) -{ - DHLOGI("MonitorTaskTimer ctor!"); -} - -MonitorTaskTimer::~MonitorTaskTimer() -{ - DHLOGI("MonitorTaskTimer dtor!"); -} - -void MonitorTaskTimer::ExecuteInner() -{ - DHLOGD("ExecuteInner!"); - auto enabledDevices = TaskBoard::GetInstance().GetEnabledDevice(); - std::shared_ptr capInfoPtr = nullptr; - TaskParam taskParam; - std::string capabilityKey; - for (auto item : enabledDevices) { - capabilityKey = item.first; - taskParam = item.second; - if (taskParam.dhType != DHType::INPUT) { - continue; - } - if (CapabilityInfoManager::GetInstance()->GetDataByKey(capabilityKey, capInfoPtr) != DH_FWK_SUCCESS) { - DHLOGI("CapabilityInfoManager can not find this key in DB, key: %{public}s, networkId: %{public}s, " - "uuid: %{public}s, dhId: %{public}s", GetAnonyString(capabilityKey).c_str(), - GetAnonyString(taskParam.networkId).c_str(), GetAnonyString(taskParam.uuid).c_str(), - GetAnonyString(taskParam.dhId).c_str()); - auto task = TaskFactory::GetInstance().CreateTask(TaskType::DISABLE, taskParam, nullptr); - TaskExecutor::GetInstance().PushTask(task); - } - } - - if (capInfoPtr != nullptr) { - capInfoPtr = nullptr; - } -} - -void MonitorTaskTimer::HandleStopTimer() -{ - DHLOGI("HandleStopTimer!"); -} -} // namespace DistributedHardware -} // namespace OHOS diff --git a/services/distributedhardwarefwkservice/src/task/offline_task.cpp b/services/distributedhardwarefwkservice/src/task/offline_task.cpp index 6fa6aadc..d6c51411 100644 --- a/services/distributedhardwarefwkservice/src/task/offline_task.cpp +++ b/services/distributedhardwarefwkservice/src/task/offline_task.cpp @@ -24,6 +24,7 @@ #include "dh_utils_tool.h" #include "distributed_hardware_errno.h" #include "distributed_hardware_log.h" +#include "meta_info_manager.h" #include "task_board.h" #include "task_executor.h" #include "task_factory.h" @@ -90,23 +91,34 @@ void OffLineTask::CreateDisableTask() { DHLOGI("networkId = %{public}s, uuid = %{public}s", GetAnonyString(GetNetworkId()).c_str(), GetAnonyString(GetUUID()).c_str()); + std::string deviceId = GetDeviceIdByUUID(GetUUID()); + std::vector> devDhInfos; std::vector> capabilityInfos; - CapabilityInfoManager::GetInstance()->GetCapabilitiesByDeviceId(GetDeviceIdByUUID(GetUUID()), capabilityInfos); - if (capabilityInfos.empty()) { - DHLOGE("capabilityInfos is empty, can not create disableTask, uuid = %{public}s", - GetAnonyString(GetUUID()).c_str()); - return; + CapabilityInfoManager::GetInstance()->GetCapabilitiesByDeviceId(deviceId, capabilityInfos); + std::for_each(capabilityInfos.begin(), capabilityInfos.end(), [&](std::shared_ptr cap) { + devDhInfos.push_back({cap->GetDHId(), cap->GetDHType()}); + }); + + if (devDhInfos.empty()) { + DHLOGW("Can not get cap info from CapabilityInfo, try use meta info"); + std::vector> metaCapInfos; + MetaInfoManager::GetInstance()->GetMetaCapInfosByDeviceId(deviceId, metaCapInfos); + std::for_each(metaCapInfos.begin(), metaCapInfos.end(), [&](std::shared_ptr cap) { + devDhInfos.push_back({cap->GetDHId(), cap->GetDHType()}); + }); } - for (const auto &iter : capabilityInfos) { - if (iter == nullptr) { - DHLOGE("capabilityInfo is null"); - continue; - } + + if (devDhInfos.empty()) { + DHLOGE("Can not get cap info, uuid = %{public}s, deviceId = %{public}s", GetAnonyString(GetUUID()).c_str(), + GetAnonyString(deviceId).c_str()); + } + + for (const auto &info : devDhInfos) { TaskParam taskParam = { .networkId = GetNetworkId(), .uuid = GetUUID(), - .dhId = iter->GetDHId(), - .dhType = iter->GetDHType() + .dhId = info.first, + .dhType = info.second }; auto task = TaskFactory::GetInstance().CreateTask(TaskType::DISABLE, taskParam, shared_from_this()); TaskExecutor::GetInstance().PushTask(task); diff --git a/services/distributedhardwarefwkservice/src/task/online_task.cpp b/services/distributedhardwarefwkservice/src/task/online_task.cpp index c894186e..1d9e9af7 100644 --- a/services/distributedhardwarefwkservice/src/task/online_task.cpp +++ b/services/distributedhardwarefwkservice/src/task/online_task.cpp @@ -20,6 +20,7 @@ #include "dh_utils_tool.h" #include "distributed_hardware_errno.h" #include "distributed_hardware_log.h" +#include "local_capability_info_manager.h" #include "meta_info_manager.h" #include "task_board.h" #include "task_executor.h" @@ -70,22 +71,29 @@ void OnLineTask::DoTask() void OnLineTask::DoSyncInfo() { - auto ret = CapabilityInfoManager::GetInstance()->SyncDeviceInfoFromDB(GetDeviceIdByUUID(GetUUID())); + std::string deviceId = GetDeviceIdByUUID(GetUUID()); + auto ret = CapabilityInfoManager::GetInstance()->SyncDeviceInfoFromDB(deviceId); if (ret != DH_FWK_SUCCESS) { - DHLOGE("SyncDeviceInfoFromDB failed, uuid = %{public}s, errCode = %{public}d", - GetAnonyString(GetUUID()).c_str(), ret); + DHLOGE("SyncDeviceInfoFromDB failed, deviceId = %{public}s, uuid = %{public}s, errCode = %{public}d", + GetAnonyString(deviceId).c_str(), GetAnonyString(GetUUID()).c_str(), ret); } - ret = VersionInfoManager::GetInstance()->SyncVersionInfoFromDB(GetDeviceIdByUUID(GetUUID())); + ret = VersionInfoManager::GetInstance()->SyncVersionInfoFromDB(deviceId); if (ret != DH_FWK_SUCCESS) { - DHLOGE("SyncVersionInfoFromDB failed, uuid = %{public}s, errCode = %{public}d", - GetAnonyString(GetUUID()).c_str(), ret); + DHLOGE("SyncVersionInfoFromDB failed, deviceId = %{public}s, uuid = %{public}s, errCode = %{public}d", + GetAnonyString(deviceId).c_str(), GetAnonyString(GetUUID()).c_str(), ret); } - ret = MetaInfoManager::GetInstance()->SyncMetaInfoFromDB(GetDeviceIdByUUID(GetUUID())); + ret = LocalCapabilityInfoManager::GetInstance()->SyncDeviceInfoFromDB(deviceId); if (ret != DH_FWK_SUCCESS) { - DHLOGE("SyncMetaInfoFromDB failed, uuid = %{public}s, errCode = %{public}d", - GetAnonyString(GetUUID()).c_str(), ret); + DHLOGE("SyncLocalCapabilityInfoFromDB failed, deviceId = %{public}s, uuid = %{public}s, errCode = %{public}d", + GetAnonyString(deviceId).c_str(), GetAnonyString(GetUUID()).c_str(), ret); + } + + ret = MetaInfoManager::GetInstance()->SyncMetaInfoFromDB(deviceId); + if (ret != DH_FWK_SUCCESS) { + DHLOGE("SyncMetaInfoFromDB failed, deviceId = %{public}s, uuid = %{public}s, errCode = %{public}d", + GetAnonyString(deviceId).c_str(), GetAnonyString(GetUUID()).c_str(), ret); } } @@ -93,23 +101,42 @@ void OnLineTask::CreateEnableTask() { DHLOGI("networkId = %{public}s, uuid = %{public}s", GetAnonyString(GetNetworkId()).c_str(), GetAnonyString(GetUUID()).c_str()); + std::string deviceId = GetDeviceIdByUUID(GetUUID()); + std::vector> devDhInfos; std::vector> capabilityInfos; - CapabilityInfoManager::GetInstance()->GetCapabilitiesByDeviceId(GetDeviceIdByUUID(GetUUID()), capabilityInfos); - if (capabilityInfos.empty()) { - DHLOGE("capabilityInfos is empty, can not create enableTask, uuid = %{public}s", - GetAnonyString(GetUUID()).c_str()); - return; + CapabilityInfoManager::GetInstance()->GetCapabilitiesByDeviceId(deviceId, capabilityInfos); + std::for_each(capabilityInfos.begin(), capabilityInfos.end(), [&](std::shared_ptr cap) { + devDhInfos.push_back({cap->GetDHId(), cap->GetDHType()}); + }); + + if (devDhInfos.empty()) { + DHLOGW("Can not get cap info from CapabilityInfo, try use local Capability info"); + LocalCapabilityInfoManager::GetInstance()->GetCapabilitiesByDeviceId(deviceId, capabilityInfos); + std::for_each(capabilityInfos.begin(), capabilityInfos.end(), [&](std::shared_ptr cap) { + devDhInfos.push_back({cap->GetDHId(), cap->GetDHType()}); + }); } - for (const auto &iter : capabilityInfos) { - if (iter == nullptr) { - DHLOGE("capabilityInfo is null"); - continue; - } + + if (devDhInfos.empty()) { + DHLOGW("Can not get cap info from local Capbility, try use meta info"); + std::vector> metaCapInfos; + MetaInfoManager::GetInstance()->GetMetaCapInfosByDeviceId(deviceId, metaCapInfos); + std::for_each(metaCapInfos.begin(), metaCapInfos.end(), [&](std::shared_ptr cap) { + devDhInfos.push_back({cap->GetDHId(), cap->GetDHType()}); + }); + } + + if (devDhInfos.empty()) { + DHLOGE("Can not get cap info, uuid = %{public}s, deviceId = %{public}s", GetAnonyString(GetUUID()).c_str(), + GetAnonyString(deviceId).c_str()); + } + + for (const auto &info : devDhInfos) { TaskParam taskParam = { .networkId = GetNetworkId(), .uuid = GetUUID(), - .dhId = iter->GetDHId(), - .dhType = iter->GetDHType() + .dhId = info.first, + .dhType = info.second }; auto task = TaskFactory::GetInstance().CreateTask(TaskType::ENABLE, taskParam, shared_from_this()); TaskExecutor::GetInstance().PushTask(task); diff --git a/services/distributedhardwarefwkservice/src/transport/dh_comm_tool.cpp b/services/distributedhardwarefwkservice/src/transport/dh_comm_tool.cpp index a665c197..3998af7e 100644 --- a/services/distributedhardwarefwkservice/src/transport/dh_comm_tool.cpp +++ b/services/distributedhardwarefwkservice/src/transport/dh_comm_tool.cpp @@ -43,7 +43,7 @@ void DHCommTool::Init() DHLOGI("Init DHCommTool"); dhTransportPtr_ = std::make_shared(shared_from_this()); std::shared_ptr runner = AppExecFwk::EventRunner::Create(true); - eventHandler_ = std::make_shared(runner); + eventHandler_ = std::make_shared(runner, shared_from_this()); dhTransportPtr_->Init(); } @@ -110,6 +110,10 @@ void DHCommTool::GetAndSendLocalFullCaps(const std::string &reqNetworkId) cJSON *root = cJSON_CreateObject(); ToJson(root, capsRsp); char *msg = cJSON_PrintUnformatted(root); + if (msg == nullptr) { + cJSON_Delete(root); + return; + } std::string fullCapsMsg(msg); cJSON_free(msg); cJSON_Delete(root); @@ -146,8 +150,8 @@ FullCapsRsp DHCommTool::ParseAndSaveRemoteDHCaps(const std::string &remoteCaps) return capsRsp; } -DHCommTool::DHCommToolEventHandler::DHCommToolEventHandler( - const std::shared_ptr &runner) : AppExecFwk::EventHandler(runner) +DHCommTool::DHCommToolEventHandler::DHCommToolEventHandler(const std::shared_ptr &runner, + std::shared_ptr dhCommToolPtr) : AppExecFwk::EventHandler(runner), dhCommToolWPtr_(dhCommToolPtr) { DHLOGI("Ctor DHCommToolEventHandler"); } @@ -161,17 +165,26 @@ void DHCommTool::DHCommToolEventHandler::ProcessEvent( DHLOGE("ProcessEvent commMsg is null"); return; } + if (dhCommToolWPtr_.expired()) { + DHLOGE("dhCommToolWPtr_ is expired"); + return; + } + std::shared_ptr dhCommToolPtr = dhCommToolWPtr_.lock(); + if (dhCommToolPtr == nullptr) { + DHLOGE("dhCommToolPtr is null"); + return; + } switch (eventId) { case DH_COMM_REQ_FULL_CAPS: { - DHCommTool::GetInstance()->GetAndSendLocalFullCaps(commMsg->msg); + dhCommToolPtr->GetAndSendLocalFullCaps(commMsg->msg); break; } case DH_COMM_RSP_FULL_CAPS: { // parse remote rsp full attrs and save to local db - FullCapsRsp capsRsp = DHCommTool::GetInstance()->ParseAndSaveRemoteDHCaps(commMsg->msg); + FullCapsRsp capsRsp = dhCommToolPtr->ParseAndSaveRemoteDHCaps(commMsg->msg); DHLOGI("Receive full remote capabilities, remote networkid: %{public}s, caps size: %{public}" PRIu32, GetAnonyString(capsRsp.networkId).c_str(), static_cast(capsRsp.caps.size())); - ProcessFullCapsRsp(capsRsp); + ProcessFullCapsRsp(capsRsp, dhCommToolPtr); break; } default: @@ -180,7 +193,8 @@ void DHCommTool::DHCommToolEventHandler::ProcessEvent( } } -void DHCommTool::DHCommToolEventHandler::ProcessFullCapsRsp(const FullCapsRsp &capsRsp) +void DHCommTool::DHCommToolEventHandler::ProcessFullCapsRsp(const FullCapsRsp &capsRsp, + const std::shared_ptr dhCommToolPtr) { if (capsRsp.networkId.empty() || capsRsp.caps.empty()) { DHLOGE("Receive remote caps info invalid"); @@ -189,7 +203,7 @@ void DHCommTool::DHCommToolEventHandler::ProcessFullCapsRsp(const FullCapsRsp &c // after receive rsp, close dsoftbus channel DHLOGI("we receive full remote capabilities, close channel, remote networkId: %{public}s", GetAnonyString(capsRsp.networkId).c_str()); - DHCommTool::GetInstance()->GetDHTransportPtr()->StopSocket(capsRsp.networkId); + dhCommToolPtr->GetDHTransportPtr()->StopSocket(capsRsp.networkId); // trigger register dh by full attrs std::string uuid = DHContext::GetInstance().GetUUIDByNetworkId(capsRsp.networkId); @@ -199,9 +213,9 @@ void DHCommTool::DHCommToolEventHandler::ProcessFullCapsRsp(const FullCapsRsp &c } for (auto const &cap : capsRsp.caps) { - BusinessState curState = ComponentManager::GetInstance().QueryBusinessState(uuid, cap->GetDHId()); - DHLOGI("DH state: %{public}" PRIu32 ", uuid: %{public}s, dhId: %{public}s", - (uint32_t)curState, GetAnonyString(uuid).c_str(), GetAnonyString(cap->GetDHId()).c_str()); + BusinessState curState = ComponentManager::GetInstance().QueryBusinessState(capsRsp.networkId, cap->GetDHId()); + DHLOGI("DH state: %{public}" PRIu32 ", networkId: %{public}s, dhId: %{public}s", + (uint32_t)curState, GetAnonyString(capsRsp.networkId).c_str(), GetAnonyString(cap->GetDHId()).c_str()); TaskParam taskParam = { .networkId = capsRsp.networkId, .uuid = uuid, diff --git a/services/distributedhardwarefwkservice/src/transport/dh_transport.cpp b/services/distributedhardwarefwkservice/src/transport/dh_transport.cpp index f776898a..d33b5c51 100644 --- a/services/distributedhardwarefwkservice/src/transport/dh_transport.cpp +++ b/services/distributedhardwarefwkservice/src/transport/dh_transport.cpp @@ -43,12 +43,14 @@ static QosTV g_qosInfo[] = { { .qos = QOS_TYPE_MIN_LATENCY, .value = 2000 } }; static uint32_t g_qosTvParamIndex = static_cast(sizeof(g_qosInfo) / sizeof(g_qosInfo[0])); +static std::weak_ptr g_dhCommToolWPtr_; } DHTransport::DHTransport(std::shared_ptr dhCommToolPtr) : remoteDevSocketIds_({}), localServerSocket_(-1), localSocketName_(""), isSocketSvrCreateFlag_(false), dhCommToolWPtr_(dhCommToolPtr) { DHLOGI("Ctor DHTransport"); + g_dhCommToolWPtr_ = dhCommToolPtr; } int32_t DHTransport::OnSocketOpened(int32_t socketId, const PeerSocketInfo &info) @@ -127,31 +129,50 @@ void DHTransport::HandleReceiveMessage(const std::string &payload) dhCommToolSPtr->GetEventHandler()->SendEvent(msgEvent, 0, AppExecFwk::EventQueue::Priority::IMMEDIATE); } +std::shared_ptr GetDHCommToolPtr() +{ + if (g_dhCommToolWPtr_.expired()) { + DHLOGE("DHCommTool Weak ptr expired"); + return nullptr; + } + + std::shared_ptr dhCommToolSPtr = g_dhCommToolWPtr_.lock(); + if (dhCommToolSPtr == nullptr) { + DHLOGE("Can not get DHCommTool ptr"); + return nullptr; + } + + return dhCommToolSPtr; +} + void OnBind(int32_t socket, PeerSocketInfo info) { - if (DHCommTool::GetInstance()->GetDHTransportPtr() == nullptr) { - DHLOGE("get DHTransport ptr return null"); + std::shared_ptr dhCommToolSPtr = GetDHCommToolPtr(); + if (dhCommToolSPtr == nullptr) { + DHLOGE("Can not get DHCommTool ptr"); return; } - DHCommTool::GetInstance()->GetDHTransportPtr()->OnSocketOpened(socket, info); + dhCommToolSPtr->GetDHTransportPtr()->OnSocketOpened(socket, info); } void OnShutdown(int32_t socket, ShutdownReason reason) { - if (DHCommTool::GetInstance()->GetDHTransportPtr() == nullptr) { - DHLOGE("get DHTransport ptr return null"); + std::shared_ptr dhCommToolSPtr = GetDHCommToolPtr(); + if (dhCommToolSPtr == nullptr) { + DHLOGE("Can not get DHCommTool ptr"); return; } - DHCommTool::GetInstance()->GetDHTransportPtr()->OnSocketClosed(socket, reason); + dhCommToolSPtr->GetDHTransportPtr()->OnSocketClosed(socket, reason); } void OnBytes(int32_t socket, const void *data, uint32_t dataLen) { - if (DHCommTool::GetInstance()->GetDHTransportPtr() == nullptr) { - DHLOGE("get DHTransport ptr return null"); + std::shared_ptr dhCommToolSPtr = GetDHCommToolPtr(); + if (dhCommToolSPtr == nullptr) { + DHLOGE("Can not get DHCommTool ptr"); return; } - DHCommTool::GetInstance()->GetDHTransportPtr()->OnBytesReceived(socket, data, dataLen); + dhCommToolSPtr->GetDHTransportPtr()->OnBytesReceived(socket, data, dataLen); } void OnMessage(int32_t socket, const void *data, uint32_t dataLen) diff --git a/services/distributedhardwarefwkservice/src/transport/dh_transport_obj.cpp b/services/distributedhardwarefwkservice/src/transport/dh_transport_obj.cpp index f0bf1c75..feebd097 100644 --- a/services/distributedhardwarefwkservice/src/transport/dh_transport_obj.cpp +++ b/services/distributedhardwarefwkservice/src/transport/dh_transport_obj.cpp @@ -83,6 +83,10 @@ std::string GetCommMsgString(const CommMsg &commMsg) cJSON *rootMsg = cJSON_CreateObject(); ToJson(rootMsg, commMsg); char *msg = cJSON_PrintUnformatted(rootMsg); + if (msg == nullptr) { + cJSON_Delete(rootMsg); + return ""; + } std::string msgStr = std::string(msg); cJSON_free(msg); cJSON_Delete(rootMsg); diff --git a/services/distributedhardwarefwkservice/src/utils/dh_context.cpp b/services/distributedhardwarefwkservice/src/utils/dh_context.cpp index 52af479f..68c41bed 100644 --- a/services/distributedhardwarefwkservice/src/utils/dh_context.cpp +++ b/services/distributedhardwarefwkservice/src/utils/dh_context.cpp @@ -173,5 +173,39 @@ std::string DHContext::GetUUIDByDeviceId(const std::string &deviceId) } return deviceIdUUIDMap_[deviceId]; } + +std::string DHContext::GetNetworkIdByDeviceId(const std::string &deviceId) +{ + std::string id = ""; + std::unique_lock lock(onlineDevMutex_); + if (deviceIdUUIDMap_.find(deviceId) == deviceIdUUIDMap_.end()) { + DHLOGE("Can not find uuid, deviceId: %{public}s", GetAnonyString(deviceId).c_str()); + return id; + } + + // current id is uuid + id = deviceIdUUIDMap_[deviceId]; + if (onlineDeviceMap_.find(id) == onlineDeviceMap_.end()) { + DHLOGE("Can not find networkId, uuid: %{public}s", GetAnonyString(id).c_str()); + return ""; + } + return onlineDeviceMap_[id]; +} + +std::string DHContext::GetDeviceIdByDBGetPrefix(const std::string &prefix) +{ + std::string id = ""; + if (prefix.empty()) { + return id; + } + + if (prefix.find(RESOURCE_SEPARATOR) != std::string::npos) { + id = prefix.substr(0, prefix.find_first_of(RESOURCE_SEPARATOR)); + } else { + id = prefix; + } + + return id; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/src/component_manager_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/src/component_manager_test.cpp index 8661893c..8bd9b0d4 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/src/component_manager_test.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/componentmanager/component_manager/src/component_manager_test.cpp @@ -225,7 +225,7 @@ HWTEST_F(ComponentManagerTest, init_compSink_test_001, TestSize.Level0) */ HWTEST_F(ComponentManagerTest, get_enableparam_test_001, TestSize.Level0) { - DeviceInfo devInfo { "", "", "", 0 }; + DeviceInfo devInfo { "", "", "", "", 0 }; auto info = std::make_unique(); MockGetLocalNodeDeviceInfo(DH_FWK_PKG_NAME.c_str(), info.get()); devInfo.uuid = GetUUIDBySoftBus(info->networkId); @@ -649,7 +649,7 @@ HWTEST_F(ComponentManagerTest, GetSinkVersion_001, TestSize.Level0) std::string uuid; DHType dhType = DHType::CAMERA; std::string sinkVersion; - int32_t ret = ComponentManager::GetInstance().GetVersion(networkId, uuid, dhType, sinkVersion, true); + int32_t ret = ComponentManager::GetInstance().GetVersion(uuid, dhType, sinkVersion, true); EXPECT_NE(DH_FWK_SUCCESS, ret); } diff --git a/services/distributedhardwarefwkservice/test/unittest/common/dbadapter/src/db_adapter_test.cpp b/services/distributedhardwarefwkservice/test/unittest/common/dbadapter/src/db_adapter_test.cpp index fdc1b446..cb8a6ab9 100644 --- a/services/distributedhardwarefwkservice/test/unittest/common/dbadapter/src/db_adapter_test.cpp +++ b/services/distributedhardwarefwkservice/test/unittest/common/dbadapter/src/db_adapter_test.cpp @@ -103,7 +103,7 @@ void DbAdapterTest::SetUpTestCase(void) std::shared_ptr changeListener = std::make_shared(); g_dbAdapterPtr = std::make_shared(APP_ID, GLOBAL_CAPABILITY_ID, changeListener); if (g_dbAdapterPtr != nullptr) { - g_dbAdapterPtr->Init(true); + g_dbAdapterPtr->Init(true, DistributedKv::DataType::TYPE_DYNAMICAL); } } @@ -137,7 +137,7 @@ void DbAdapterTest::TearDown() */ HWTEST_F(DbAdapterTest, db_adapter_test_000, TestSize.Level0) { - EXPECT_EQ(DH_FWK_SUCCESS, g_dbAdapterPtr->Init(true)); + EXPECT_EQ(DH_FWK_SUCCESS, g_dbAdapterPtr->Init(true, DistributedKv::DataType::TYPE_DYNAMICAL)); } /** @@ -346,7 +346,7 @@ HWTEST_F(DbAdapterTest, db_adapter_test_015, TestSize.Level0) */ HWTEST_F(DbAdapterTest, ReInit_001, TestSize.Level0) { - g_dbAdapterPtr->GetKvStorePtr(true); + g_dbAdapterPtr->GetKvStorePtr(true, DistributedKv::DataType::TYPE_DYNAMICAL); EXPECT_EQ(DH_FWK_SUCCESS, g_dbAdapterPtr->ReInit(true)); } @@ -358,7 +358,7 @@ HWTEST_F(DbAdapterTest, ReInit_001, TestSize.Level0) */ HWTEST_F(DbAdapterTest, RemoveDeviceData_001, TestSize.Level0) { - g_dbAdapterPtr->GetKvStorePtr(true); + g_dbAdapterPtr->GetKvStorePtr(true, DistributedKv::DataType::TYPE_DYNAMICAL); EXPECT_EQ(ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL, g_dbAdapterPtr->RemoveDeviceData(TEST_DEV_ID_0)); } diff --git a/utils/BUILD.gn b/utils/BUILD.gn index a8988f47..8f822fad 100644 --- a/utils/BUILD.gn +++ b/utils/BUILD.gn @@ -65,7 +65,6 @@ ohos_shared_library("distributedhardwareutils") { "hilog:libhilog", "hisysevent:libhisysevent", "hitrace:hitrace_meter", - "json:nlohmann_json_static", "openssl:libcrypto_shared", "safwk:system_ability_fwk", "zlib:shared_libz", diff --git a/utils/src/anonymous_string.cpp b/utils/src/anonymous_string.cpp index c275857a..c5491d12 100644 --- a/utils/src/anonymous_string.cpp +++ b/utils/src/anonymous_string.cpp @@ -30,6 +30,9 @@ namespace { } std::string GetAnonyString(const std::string &value) { + if (value.empty()) { + return ""; + } std::string res; std::string tmpStr("******"); size_t strLen = value.length(); diff --git a/utils/src/dh_utils_tool.cpp b/utils/src/dh_utils_tool.cpp index 1862d01c..fa48fca1 100644 --- a/utils/src/dh_utils_tool.cpp +++ b/utils/src/dh_utils_tool.cpp @@ -119,13 +119,14 @@ std::string Sha256(const std::string& in) DeviceInfo GetLocalDeviceInfo() { - DeviceInfo devInfo { "", "", "", 0 }; + DeviceInfo devInfo { "", "", "", "", 0 }; auto info = std::make_unique(); auto ret = GetLocalNodeDeviceInfo(DH_FWK_PKG_NAME.c_str(), info.get()); if (ret != DH_FWK_SUCCESS) { DHLOGE("GetLocalNodeDeviceInfo failed, errCode = %{public}d", ret); return devInfo; } + devInfo.networkId = info->networkId; devInfo.uuid = GetUUIDBySoftBus(info->networkId); devInfo.deviceId = GetDeviceIdByUUID(devInfo.uuid); devInfo.deviceName = info->deviceName; -- Gitee