1 /*
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "component_manager.h"
17 
18 #include <cinttypes>
19 #include <future>
20 #include <pthread.h>
21 #include <string>
22 #include <thread>
23 
24 #include "ffrt.h"
25 #include "ipc_object_stub.h"
26 #include "iservice_registry.h"
27 #include "system_ability_definition.h"
28 
29 #include "anonymous_string.h"
30 #include "capability_info_manager.h"
31 #include "component_disable.h"
32 #include "component_enable.h"
33 #include "component_loader.h"
34 #include "constants.h"
35 #include "device_manager.h"
36 #include "dh_context.h"
37 #include "dh_data_sync_trigger_listener.h"
38 #include "dh_state_listener.h"
39 #include "dh_utils_hitrace.h"
40 #include "dh_utils_hisysevent.h"
41 #include "dh_utils_tool.h"
42 #include "distributed_hardware_errno.h"
43 #include "distributed_hardware_log.h"
44 #include "enabled_comps_dump.h"
45 #include "local_capability_info_manager.h"
46 #include "low_latency.h"
47 #include "meta_info_manager.h"
48 #include "publisher.h"
49 #include "task_executor.h"
50 #include "task_factory.h"
51 #include "version_info_manager.h"
52 #include "version_manager.h"
53 
54 namespace OHOS {
55 namespace DistributedHardware {
56 #undef DH_LOG_TAG
57 #define DH_LOG_TAG "ComponentManager"
58 
59 IMPLEMENT_SINGLE_INSTANCE(ComponentManager);
60 
61 namespace {
62     constexpr int32_t ENABLE_RETRY_MAX_TIMES = 3;
63     constexpr int32_t DISABLE_RETRY_MAX_TIMES = 3;
64     constexpr int32_t ENABLE_PARAM_RETRY_TIME = 500 * 1000;
65     constexpr int32_t INVALID_SA_ID = -1;
66     constexpr int32_t UNINIT_COMPONENT_TIMEOUT_SECONDS = 2;
67     const std::string MONITOR_TASK_TIMER_ID = "monitor_task_timer_id";
68 }
69 
ComponentManager()70 ComponentManager::ComponentManager() : compSource_({}), compSink_({}), compSrcSaId_({}),
71     compMonitorPtr_(std::make_shared<ComponentMonitor>()),
72     lowLatencyListener_(sptr<LowLatencyListener>(new(std::nothrow) LowLatencyListener())),
73     isUnInitTimeOut_(false), dhBizStates_({}), dhStateListener_(std::make_shared<DHStateListener>()),
74     dataSyncTriggerListener_(std::make_shared<DHDataSyncTriggerListener>()),
75     dhCommToolPtr_(std::make_shared<DHCommTool>()), needRefreshTaskParams_({})
76 {
77     DHLOGI("Ctor ComponentManager");
78 }
79 
~ComponentManager()80 ComponentManager::~ComponentManager()
81 {
82     DHLOGD("Dtor ComponentManager");
83     compMonitorPtr_.reset();
84     compMonitorPtr_ = nullptr;
85     lowLatencyListener_ = nullptr;
86 }
87 
Init()88 int32_t ComponentManager::Init()
89 {
90     DHLOGI("start.");
91     DHTraceStart(COMPONENT_INIT_START);
92     InitComponentHandler();
93 
94     int32_t ret = InitSAMonitor();
95     if (ret != DH_FWK_SUCCESS) {
96         DHLOGE("Init SA monitor failed, ret: %{public}d", ret);
97         return ret;
98     }
99 
100     StartComponent();
101     RegisterDHStateListener();
102     RegisterDataSyncTriggerListener();
103     InitDHCommTool();
104 #ifdef DHARDWARE_LOW_LATENCY
105     Publisher::GetInstance().RegisterListener(DHTopic::TOPIC_LOW_LATENCY, lowLatencyListener_);
106 #endif
107     DHLOGI("Init component success");
108     DHTraceEnd();
109     return DH_FWK_SUCCESS;
110 }
111 
InitComponentHandler()112 void ComponentManager::InitComponentHandler()
113 {
114     DHLOGI("start.");
115     if (!InitCompSource()) {
116         DHLOGE("InitCompSource failed.");
117         DHTraceEnd();
118     }
119     if (!InitCompSink()) {
120         DHLOGE("InitCompSink failed.");
121         DHTraceEnd();
122     }
123 }
124 
InitSAMonitor()125 int32_t ComponentManager::InitSAMonitor()
126 {
127     if (compMonitorPtr_ == nullptr) {
128         DHLOGE("compMonitorPtr_ is null.");
129         return ERR_DH_FWK_COMPONENT_MONITOR_NULL;
130     }
131     for (const auto &comp : compSource_) {
132         if (compSrcSaId_.find(comp.first) == compSrcSaId_.end()) {
133             continue;
134         }
135         compMonitorPtr_->AddSAMonitor(compSrcSaId_.at(comp.first));
136     }
137     return DH_FWK_SUCCESS;
138 }
139 
StartComponent()140 void ComponentManager::StartComponent()
141 {
142     auto sourceResult = StartSource();
143     auto sinkResult = StartSink();
144 
145     if (!WaitForResult(Action::START_SOURCE, sourceResult)) {
146         DHLOGE("StartSource failed, some virtual components maybe cannot work, but want to continue");
147         HiSysEventWriteMsg(DHFWK_INIT_FAIL, OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
148             "dhfwk start source failed.");
149     }
150     if (!WaitForResult(Action::START_SINK, sinkResult)) {
151         DHLOGE("StartSink failed, some virtual components maybe cannot work, but want to continue");
152         HiSysEventWriteMsg(DHFWK_INIT_FAIL, OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
153             "dhfwk start sink failed.");
154     }
155 }
156 
RegisterDHStateListener()157 void ComponentManager::RegisterDHStateListener()
158 {
159     for (const auto &item : compSource_) {
160         DHLOGI("Register DH State listener, dhType: %{public}" PRIu32, (uint32_t)item.first);
161         if (item.second == nullptr) {
162             DHLOGE("comp source ptr is null");
163             continue;
164         }
165         item.second->RegisterDistributedHardwareStateListener(dhStateListener_);
166     }
167 }
168 
RegisterDataSyncTriggerListener()169 void ComponentManager::RegisterDataSyncTriggerListener()
170 {
171     std::shared_ptr<AppExecFwk::EventRunner> runner = AppExecFwk::EventRunner::Create(true);
172     eventHandler_ = std::make_shared<ComponentManager::ComponentManagerEventHandler>(runner);
173 
174     for (const auto &item : compSource_) {
175         DHLOGI("Register Data Sync Trigger listener, dhType: %{public}" PRIu32, (uint32_t)item.first);
176         if (item.second == nullptr) {
177             DHLOGE("comp source ptr is null");
178             continue;
179         }
180         item.second->RegisterDataSyncTriggerListener(dataSyncTriggerListener_);
181     }
182 }
183 
InitDHCommTool()184 void ComponentManager::InitDHCommTool()
185 {
186     if (dhCommToolPtr_ == nullptr) {
187         DHLOGE("DH communication tool ptr is null");
188         return;
189     }
190     DHLOGI("Init DH communication tool");
191     dhCommToolPtr_->Init();
192 }
193 
UnInit()194 int32_t ComponentManager::UnInit()
195 {
196     DHLOGI("start.");
197     UnregisterDHStateListener();
198     UnregisterDataSyncTriggerListener();
199     UnInitDHCommTool();
200     StopPrivacy();
201     UnInitSAMonitor();
202     StopComponent();
203 
204 #ifdef DHARDWARE_LOW_LATENCY
205     Publisher::GetInstance().UnregisterListener(DHTopic::TOPIC_LOW_LATENCY, lowLatencyListener_);
206     LowLatency::GetInstance().CloseLowLatency();
207 #endif
208     DHLOGI("Release component success");
209 
210     if (isUnInitTimeOut_.load()) {
211         DHLOGE("Some component stop timeout, FORCE exit!");
212         _Exit(0);
213     }
214 
215     return DH_FWK_SUCCESS;
216 }
217 
UnInitSAMonitor()218 void ComponentManager::UnInitSAMonitor()
219 {
220     // clear SA monitor
221     if (compMonitorPtr_ == nullptr) {
222         DHLOGE("compMonitorPtr_ is null.");
223         return;
224     }
225     for (const auto &comp : compSource_) {
226         if (compSrcSaId_.find(comp.first) == compSrcSaId_.end()) {
227             continue;
228         }
229         compMonitorPtr_->RemoveSAMonitor(compSrcSaId_.at(comp.first));
230     }
231 }
232 
UnregisterDHStateListener()233 void ComponentManager::UnregisterDHStateListener()
234 {
235     for (const auto &item : compSource_) {
236         DHLOGI("Unregister DH State listener, dhType: %{public}" PRIu32, (uint32_t)item.first);
237         if (item.second == nullptr) {
238             DHLOGE("comp source ptr is null");
239             continue;
240         }
241         item.second->UnregisterDistributedHardwareStateListener();
242     }
243 }
244 
UnregisterDataSyncTriggerListener()245 void ComponentManager::UnregisterDataSyncTriggerListener()
246 {
247     for (const auto &item : compSource_) {
248         DHLOGI("Unregister Data Sync Trigger listener, dhType: %{public}" PRIu32, (uint32_t)item.first);
249         if (item.second == nullptr) {
250             DHLOGE("comp source ptr is null");
251             continue;
252         }
253         item.second->UnregisterDataSyncTriggerListener();
254     }
255 }
256 
UnInitDHCommTool()257 void ComponentManager::UnInitDHCommTool()
258 {
259     if (dhCommToolPtr_ == nullptr) {
260         DHLOGE("DH communication tool ptr is null");
261         return;
262     }
263     DHLOGI("UnInit DH communication tool");
264     dhCommToolPtr_->UnInit();
265 }
266 
StopComponent()267 void ComponentManager::StopComponent()
268 {
269     // stop source and sink sa
270     auto sourceResult = StopSource();
271     auto sinkResult = StopSink();
272 
273     if (!WaitForResult(Action::STOP_SOURCE, sourceResult)) {
274         DHLOGE("StopSource failed, but want to continue");
275     }
276     if (!WaitForResult(Action::STOP_SINK, sinkResult)) {
277         DHLOGE("StopSource failed, but want to continue");
278     }
279 
280     compSource_.clear();
281     compSink_.clear();
282 }
283 
StopPrivacy()284 void ComponentManager::StopPrivacy()
285 {
286     // stop privacy
287     if (cameraCompPrivacy_ != nullptr && cameraCompPrivacy_->GetPageFlag()) {
288         cameraCompPrivacy_->StopPrivacePage("camera");
289         cameraCompPrivacy_->SetPageFlagFalse();
290     }
291 
292     if (audioCompPrivacy_ != nullptr  && audioCompPrivacy_->GetPageFlag()) {
293         audioCompPrivacy_->StopPrivacePage("mic");
294         audioCompPrivacy_->SetPageFlagFalse();
295     }
296 }
297 
StartSource()298 ActionResult ComponentManager::StartSource()
299 {
300     DHLOGI("start.");
301     std::unordered_map<DHType, std::shared_future<int32_t>> futures;
302     std::string uuid = DHContext::GetInstance().GetDeviceInfo().uuid;
303     for (const auto &item : compSource_) {
304         if (item.second == nullptr) {
305             DHLOGE("comp source ptr is null");
306             continue;
307         }
308         CompVersion compversion;
309         VersionManager::GetInstance().GetCompVersion(uuid, item.first, compversion);
310         auto params = compversion.sourceVersion;
311         std::promise<int32_t> p;
312         std::future<int32_t> f = p.get_future();
313         std::thread([p = std::move(p), item, params] () mutable {
314             p.set_value(item.second->InitSource(params));
315         }).detach();
316         futures.emplace(item.first, f.share());
317     }
318     return futures;
319 }
320 
StartSource(DHType dhType)321 ActionResult ComponentManager::StartSource(DHType dhType)
322 {
323     DHLOGI("Start Source, dhType: %{public}" PRIu32, (uint32_t)dhType);
324     std::unordered_map<DHType, std::shared_future<int32_t>> futures;
325     if (compSource_.find(dhType) == compSource_.end()) {
326         DHLOGE("Component for DHType: %{public}" PRIu32 " not init source handler", (uint32_t)dhType);
327         return futures;
328     }
329     if (compSource_[dhType] == nullptr) {
330         DHLOGE("comp source ptr is null");
331         return futures;
332     }
333     std::string uuid = DHContext::GetInstance().GetDeviceInfo().uuid;
334     CompVersion compVersion;
335     VersionManager::GetInstance().GetCompVersion(uuid, dhType, compVersion);
336     auto params = compVersion.sourceVersion;
337     std::promise<int32_t> p;
338     std::future<int32_t> f = p.get_future();
339     std::thread([p = std::move(p), this, dhType, params] () mutable {
340         p.set_value(compSource_[dhType]->InitSource(params));
341     }).detach();
342     futures.emplace(dhType, f.share());
343 
344     return futures;
345 }
346 
StartSink()347 ActionResult ComponentManager::StartSink()
348 {
349     DHLOGI("start.");
350     std::unordered_map<DHType, std::shared_future<int32_t>> futures;
351     std::string uuid = DHContext::GetInstance().GetDeviceInfo().uuid;
352     for (const auto &item : compSink_) {
353         if (item.second == nullptr) {
354             DHLOGE("comp sink ptr is null");
355             continue;
356         }
357         CompVersion compversion;
358         VersionManager::GetInstance().GetCompVersion(uuid, item.first, compversion);
359         auto params = compversion.sinkVersion;
360         std::promise<int32_t> p;
361         std::future<int32_t> f = p.get_future();
362         std::thread([p = std::move(p), item, params] () mutable {
363             p.set_value(item.second->InitSink(params));
364         }).detach();
365         futures.emplace(item.first, f.share());
366         if (cameraCompPrivacy_ == nullptr && item.first == DHType::CAMERA) {
367             cameraCompPrivacy_ = std::make_shared<ComponentPrivacy>();
368             item.second->RegisterPrivacyResources(cameraCompPrivacy_);
369         }
370         if (audioCompPrivacy_ == nullptr && item.first == DHType::AUDIO) {
371             audioCompPrivacy_ = std::make_shared<ComponentPrivacy>();
372             item.second->RegisterPrivacyResources(audioCompPrivacy_);
373         }
374     }
375     return futures;
376 }
377 
StartSink(DHType dhType)378 ActionResult ComponentManager::StartSink(DHType dhType)
379 {
380     DHLOGI("Start Sink, dhType: %{public}" PRIu32, (uint32_t)dhType);
381     std::unordered_map<DHType, std::shared_future<int32_t>> futures;
382     if (compSink_.find(dhType) == compSink_.end()) {
383         DHLOGE("Component for DHType: %{public}" PRIu32 " not init sink handler", (uint32_t)dhType);
384         return futures;
385     }
386     if (compSink_[dhType] == nullptr) {
387         DHLOGE("comp sink ptr is null");
388         return futures;
389     }
390     std::string uuid = DHContext::GetInstance().GetDeviceInfo().uuid;
391     CompVersion compVersion;
392     VersionManager::GetInstance().GetCompVersion(uuid, dhType, compVersion);
393     auto params = compVersion.sinkVersion;
394     std::promise<int32_t> p;
395     std::future<int32_t> f = p.get_future();
396     std::thread([p = std::move(p), this, dhType, params] () mutable {
397         p.set_value(compSink_[dhType]->InitSink(params));
398     }).detach();
399     futures.emplace(dhType, f.share());
400     if (cameraCompPrivacy_ == nullptr && dhType == DHType::CAMERA) {
401         cameraCompPrivacy_ = std::make_shared<ComponentPrivacy>();
402         compSink_[dhType]->RegisterPrivacyResources(cameraCompPrivacy_);
403     }
404     if (audioCompPrivacy_ == nullptr && dhType == DHType::AUDIO) {
405         audioCompPrivacy_ = std::make_shared<ComponentPrivacy>();
406         compSink_[dhType]->RegisterPrivacyResources(audioCompPrivacy_);
407     }
408 
409     return futures;
410 }
411 
StopSource()412 ActionResult ComponentManager::StopSource()
413 {
414     DHLOGI("start.");
415     std::unordered_map<DHType, std::shared_future<int32_t>> futures;
416     for (const auto &item : compSource_) {
417         if (item.second == nullptr) {
418             DHLOGE("comp source ptr is null");
419             continue;
420         }
421         std::promise<int32_t> p;
422         std::future<int32_t> f = p.get_future();
423         std::thread([p = std::move(p), item] () mutable {
424             p.set_value(item.second->ReleaseSource());
425         }).detach();
426         futures.emplace(item.first, f.share());
427     }
428     return futures;
429 }
430 
StopSink()431 ActionResult ComponentManager::StopSink()
432 {
433     DHLOGI("start.");
434     std::unordered_map<DHType, std::shared_future<int32_t>> futures;
435     for (const auto &item : compSink_) {
436         if (item.second == nullptr) {
437             DHLOGE("comp sink ptr is null");
438             continue;
439         }
440         std::promise<int32_t> p;
441         std::future<int32_t> f = p.get_future();
442         std::thread([p = std::move(p), item] () mutable {
443             p.set_value(item.second->ReleaseSink());
444             IHardwareHandler *hardwareHandler = nullptr;
445             int32_t status = ComponentLoader::GetInstance().GetHardwareHandler(item.first, hardwareHandler);
446             if (status != DH_FWK_SUCCESS || hardwareHandler == nullptr) {
447                 DHLOGE("GetHardwareHandler %{public}#X failed", item.first);
448                 return status;
449             }
450             hardwareHandler->UnRegisterPluginListener();
451             return status;
452         }).detach();
453         futures.emplace(item.first, f.share());
454     }
455     return futures;
456 }
457 
WaitForResult(const Action & action,ActionResult actionsResult)458 bool ComponentManager::WaitForResult(const Action &action, ActionResult actionsResult)
459 {
460     DHLOGD("start.");
461     auto ret = true;
462     for (auto &iter : actionsResult) {
463         std::future_status status = iter.second.wait_for(std::chrono::seconds(UNINIT_COMPONENT_TIMEOUT_SECONDS));
464         if (status == std::future_status::ready) {
465             auto result = iter.second.get();
466             DHLOGI("action = %{public}d, compType = %{public}#X, READY, ret = %{public}d.",
467                 static_cast<int32_t>(action), iter.first, result);
468             if (result != DH_FWK_SUCCESS) {
469                 ret = false;
470                 DHLOGE("there is error, but want to continue.");
471             }
472         }
473 
474         if (status == std::future_status::timeout) {
475             DHLOGI("action = %{public}d, compType = %{public}#X, TIMEOUT", static_cast<int32_t>(action), iter.first);
476             if (action == Action::STOP_SOURCE || action == Action::STOP_SINK) {
477                 isUnInitTimeOut_ = true;
478             }
479         }
480 
481         if (status == std::future_status::deferred) {
482             DHLOGI("action = %{public}d, compType = %{public}#X, DEFERRED", static_cast<int32_t>(action), iter.first);
483         }
484     }
485     DHLOGD("end.");
486     return ret;
487 }
488 
InitCompSource()489 bool ComponentManager::InitCompSource()
490 {
491     auto compTypes = ComponentLoader::GetInstance().GetAllCompTypes();
492     for (const auto &type : compTypes) {
493         IDistributedHardwareSource *sourcePtr = nullptr;
494         auto ret = ComponentLoader::GetInstance().GetSource(type, sourcePtr);
495         if (ret != DH_FWK_SUCCESS) {
496             DHLOGW("GetSource failed, compType = %{public}#X, ret = %{public}d.", type, ret);
497             continue;
498         }
499         if (sourcePtr == nullptr) {
500             DHLOGW("sourcePtr is null, compType = %{public}#X.", type);
501             continue;
502         }
503         compSource_.insert(std::make_pair(type, sourcePtr));
504 
505         int32_t saId = ComponentLoader::GetInstance().GetSourceSaId(type);
506         if (saId != INVALID_SA_ID) {
507             compSrcSaId_.insert(std::make_pair(type, saId));
508         }
509     }
510     return !compSource_.empty();
511 }
512 
InitCompSink()513 bool ComponentManager::InitCompSink()
514 {
515     auto compTypes = ComponentLoader::GetInstance().GetAllCompTypes();
516     for (const auto &type : compTypes) {
517         IDistributedHardwareSink *sinkPtr = nullptr;
518         auto ret = ComponentLoader::GetInstance().GetSink(type, sinkPtr);
519         if (ret != DH_FWK_SUCCESS) {
520             DHLOGW("GetSink failed, compType = %{public}#X, ret = %{public}d.", type, ret);
521             continue;
522         }
523         if (sinkPtr == nullptr) {
524             DHLOGW("sinkPtr is null, compType = %{public}#X.", type);
525             continue;
526         }
527         compSink_.insert(std::make_pair(type, sinkPtr));
528     }
529     return !compSink_.empty();
530 }
531 
Enable(const std::string & networkId,const std::string & uuid,const std::string & dhId,const DHType dhType)532 int32_t ComponentManager::Enable(const std::string &networkId, const std::string &uuid, const std::string &dhId,
533     const DHType dhType)
534 {
535     if (!IsIdLengthValid(networkId) || !IsIdLengthValid(uuid) || !IsIdLengthValid(dhId)) {
536         return ERR_DH_FWK_PARA_INVALID;
537     }
538     DHLOGI("start.");
539     if (compSource_.find(dhType) == compSource_.end()) {
540         DHLOGE("can not find handler for dhId = %{public}s.", GetAnonyString(dhId).c_str());
541         return ERR_DH_FWK_PARA_INVALID;
542     }
543     EnableParam param;
544     auto ret = GetEnableParam(networkId, uuid, dhId, dhType, param);
545     if (ret != DH_FWK_SUCCESS) {
546         DHLOGE("GetEnableParam failed, uuid = %{public}s, dhId = %{public}s, errCode = %{public}d",
547             GetAnonyString(uuid).c_str(), GetAnonyString(dhId).c_str(), ret);
548         if (RetryGetEnableParam(networkId, uuid, dhId, dhType, param) != DH_FWK_SUCCESS) {
549             return ret;
550         }
551     }
552     std::string subtype = param.subtype;
553     std::map<std::string, bool> resourceDesc = ComponentLoader::GetInstance().GetCompResourceDesc();
554     if (resourceDesc.find(subtype) == resourceDesc.end()) {
555         DHLOGE("GetCompResourceDesc failed, subtype: %{public}s", subtype.c_str());
556         return ERR_DH_FWK_RESOURCE_KEY_IS_EMPTY;
557     }
558     if (resourceDesc[subtype] && !IsIdenticalAccount(networkId)) {
559         DHLOGE("Privacy resources must be logged in with the same account.");
560         return ERR_DH_FWK_COMPONENT_ENABLE_FAILED;
561     }
562 
563     auto compEnable = std::make_shared<ComponentEnable>();
564     auto result = compEnable->Enable(networkId, dhId, param, (compSource_.find(dhType))->second);
565     if (result != DH_FWK_SUCCESS) {
566         for (int32_t retryCount = 0; retryCount < ENABLE_RETRY_MAX_TIMES; retryCount++) {
567             if (!DHContext::GetInstance().IsDeviceOnline(uuid)) {
568                 DHLOGE("device is already offline, no need try enable, uuid= %{public}s", GetAnonyString(uuid).c_str());
569                 return result;
570             }
571             if (compEnable->Enable(networkId, dhId, param, (compSource_.find(dhType))->second) == DH_FWK_SUCCESS) {
572                 DHLOGE("enable success, retryCount = %{public}d", retryCount);
573                 EnabledCompsDump::GetInstance().DumpEnabledComp(networkId, dhType, dhId);
574                 return DH_FWK_SUCCESS;
575             }
576             DHLOGE("enable failed, retryCount = %{public}d", retryCount);
577         }
578         return result;
579     }
580     DHLOGI("enable result is %{public}d, uuid = %{public}s, dhId = %{public}s", result, GetAnonyString(uuid).c_str(),
581         GetAnonyString(dhId).c_str());
582     EnabledCompsDump::GetInstance().DumpEnabledComp(networkId, dhType, dhId);
583 
584     return result;
585 }
586 
RetryGetEnableParam(const std::string & networkId,const std::string & uuid,const std::string & dhId,const DHType dhType,EnableParam & param)587 int32_t ComponentManager::RetryGetEnableParam(const std::string &networkId, const std::string &uuid,
588     const std::string &dhId, const DHType dhType, EnableParam &param)
589 {
590     if (!IsIdLengthValid(networkId) || !IsIdLengthValid(uuid) || !IsIdLengthValid(dhId)) {
591         return ERR_DH_FWK_PARA_INVALID;
592     }
593     for (int32_t retryCount = 0; retryCount < ENABLE_RETRY_MAX_TIMES; retryCount++) {
594         if (!DHContext::GetInstance().IsDeviceOnline(uuid)) {
595             DHLOGE("device is already offline, no need try GetEnableParam, uuid = %{public}s",
596                 GetAnonyString(uuid).c_str());
597             return ERR_DH_FWK_COMPONENT_ENABLE_FAILED;
598         }
599         if (GetEnableParam(networkId, uuid, dhId, dhType, param) == DH_FWK_SUCCESS) {
600             DHLOGE("GetEnableParam success, retryCount = %{public}d", retryCount);
601             break;
602         }
603         DHLOGE("GetEnableParam failed, retryCount = %{public}d", retryCount);
604         usleep(ENABLE_PARAM_RETRY_TIME);
605     }
606     return DH_FWK_SUCCESS;
607 }
608 
Disable(const std::string & networkId,const std::string & uuid,const std::string & dhId,const DHType dhType)609 int32_t ComponentManager::Disable(const std::string &networkId, const std::string &uuid, const std::string &dhId,
610     const DHType dhType)
611 {
612     if (!IsIdLengthValid(networkId) || !IsIdLengthValid(uuid) || !IsIdLengthValid(dhId)) {
613         return ERR_DH_FWK_PARA_INVALID;
614     }
615     auto find = compSource_.find(dhType);
616     if (find == compSource_.end()) {
617         DHLOGE("can not find handler for dhId = %{public}s.", GetAnonyString(dhId).c_str());
618         return ERR_DH_FWK_PARA_INVALID;
619     }
620 
621     auto compDisable = std::make_shared<ComponentDisable>();
622     auto result = compDisable->Disable(networkId, dhId, find->second);
623     if (result != DH_FWK_SUCCESS) {
624         for (int32_t retryCount = 0; retryCount < DISABLE_RETRY_MAX_TIMES; retryCount++) {
625             if (DHContext::GetInstance().IsDeviceOnline(uuid)) {
626                 DHLOGE("device is already online, no need try disable, uuid = %{public}s",
627                     GetAnonyString(uuid).c_str());
628                 return result;
629             }
630             if (compDisable->Disable(networkId, dhId, find->second) == DH_FWK_SUCCESS) {
631                 DHLOGE("disable success, retryCount = %{public}d", retryCount);
632                 EnabledCompsDump::GetInstance().DumpDisabledComp(networkId, dhType, dhId);
633                 return DH_FWK_SUCCESS;
634             }
635             DHLOGE("disable failed, retryCount = %{public}d", retryCount);
636         }
637         return result;
638     }
639     DHLOGI("disable result is %{public}d, uuid = %{public}s, dhId = %{public}s", result, GetAnonyString(uuid).c_str(),
640         GetAnonyString(dhId).c_str());
641     EnabledCompsDump::GetInstance().DumpDisabledComp(networkId, dhType, dhId);
642 
643     return result;
644 }
645 
GetDHType(const std::string & uuid,const std::string & dhId) const646 DHType ComponentManager::GetDHType(const std::string &uuid, const std::string &dhId) const
647 {
648     std::shared_ptr<CapabilityInfo> capability = nullptr;
649     auto ret = CapabilityInfoManager::GetInstance()->GetCapability(GetDeviceIdByUUID(uuid), dhId, capability);
650     if ((ret == DH_FWK_SUCCESS) && (capability != nullptr)) {
651         return capability->GetDHType();
652     }
653     DHLOGE("get dhType failed, uuid = %{public}s, dhId = %{public}s", GetAnonyString(uuid).c_str(),
654         GetAnonyString(dhId).c_str());
655     return DHType::UNKNOWN;
656 }
657 
GetEnableCapParam(const std::string & networkId,const std::string & uuid,DHType dhType,EnableParam & param,std::shared_ptr<CapabilityInfo> capability)658 int32_t ComponentManager::GetEnableCapParam(const std::string &networkId, const std::string &uuid,
659     DHType dhType, EnableParam &param, std::shared_ptr<CapabilityInfo> capability)
660 {
661     if (!IsIdLengthValid(networkId) || !IsIdLengthValid(uuid)) {
662         return ERR_DH_FWK_PARA_INVALID;
663     }
664     DeviceInfo sourceDeviceInfo = GetLocalDeviceInfo();
665     std::vector<std::shared_ptr<CapabilityInfo>> sourceCapInfos;
666     std::string sourceDHId;
667     CapabilityInfoManager::GetInstance()->GetCapabilitiesByDeviceId(sourceDeviceInfo.deviceId, sourceCapInfos);
668     for (const auto &capInfo : sourceCapInfos) {
669         if (dhType == capInfo->GetDHType()) {
670             param.sourceAttrs = capInfo->GetDHAttrs();
671             sourceDHId = capInfo->GetDHId();
672         }
673     }
674     std::string sourceVersion("");
675     auto ret = GetVersion(sourceDeviceInfo.uuid, dhType, sourceVersion, false);
676     if (ret != DH_FWK_SUCCESS) {
677         DHLOGE("Get source version failed.");
678         return ERR_DH_FWK_COMPONENT_GET_SINK_VERSION_FAILED;
679     }
680     param.sourceVersion = sourceVersion;
681 
682     param.sinkAttrs = capability->GetDHAttrs();
683     std::string sinkVersion("");
684     ret = GetVersion(uuid, dhType, sinkVersion, true);
685     if (ret != DH_FWK_SUCCESS) {
686         DHLOGE("Get sink version failed.");
687         // If Version DB not sync, try get sink version from meta info
688         std::shared_ptr<MetaCapabilityInfo> metaCapPtr = nullptr;
689         ret = MetaInfoManager::GetInstance()->GetMetaCapInfo(DHContext::GetInstance().GetUdidHashIdByUUID(uuid),
690             capability->GetDHId(), metaCapPtr);
691         if ((ret == DH_FWK_SUCCESS) && (metaCapPtr != nullptr)) {
692             sinkVersion = metaCapPtr->GetSinkVersion();
693         } else {
694             return ERR_DH_FWK_COMPONENT_GET_SINK_VERSION_FAILED;
695         }
696     }
697     param.sinkVersion = sinkVersion;
698     param.subtype = capability->GetDHSubtype();
699     DHLOGI("GetEnableCapParam success. dhType = %{public}#X, sink uuid =%{public}s,"
700         "sinVersion = %{public}s, source uuid =%{public}s, source dhId = %{public}s, sourceVersion = %{public}s,"
701         "subtype = %{public}s", dhType, GetAnonyString(uuid).c_str(),
702         param.sinkVersion.c_str(), GetAnonyString(sourceDeviceInfo.uuid).c_str(), GetAnonyString(sourceDHId).c_str(),
703         param.sourceVersion.c_str(), param.subtype.c_str());
704     return DH_FWK_SUCCESS;
705 }
706 
GetEnableMetaParam(const std::string & networkId,const std::string & uuid,DHType dhType,EnableParam & param,std::shared_ptr<MetaCapabilityInfo> metaCapPtr)707 int32_t ComponentManager::GetEnableMetaParam(const std::string &networkId, const std::string &uuid,
708     DHType dhType, EnableParam &param, std::shared_ptr<MetaCapabilityInfo> metaCapPtr)
709 {
710     if (!IsIdLengthValid(networkId) || !IsIdLengthValid(uuid)) {
711         return ERR_DH_FWK_PARA_INVALID;
712     }
713     DeviceInfo sourceDeviceInfo = GetLocalDeviceInfo();
714     std::vector<std::shared_ptr<MetaCapabilityInfo>> sourceMetaInfos;
715     std::string sourceDHId;
716     MetaInfoManager::GetInstance()->GetMetaCapInfosByUdidHash(sourceDeviceInfo.udidHash, sourceMetaInfos);
717     for (const auto &metaInfo : sourceMetaInfos) {
718         if (dhType == metaInfo->GetDHType()) {
719             param.sourceAttrs = metaInfo->GetDHAttrs();
720             sourceDHId = metaInfo->GetDHId();
721         }
722     }
723     std::string sourceVersion("");
724     auto ret = GetVersion(sourceDeviceInfo.uuid, dhType, sourceVersion, false);
725     if (ret != DH_FWK_SUCCESS) {
726         DHLOGE("Get source version failed.");
727         return ERR_DH_FWK_COMPONENT_GET_SINK_VERSION_FAILED;
728     }
729     param.sourceVersion = sourceVersion;
730 
731     param.sinkAttrs = metaCapPtr->GetDHAttrs();
732     param.sinkVersion = metaCapPtr->GetSinkVersion();
733     param.subtype = metaCapPtr->GetDHSubtype();
734     DHLOGI("GetEnableCapParam success. dhType = %{public}#X, sink uuid =%{public}s,"
735         "sinVersion = %{public}s, source uuid =%{public}s, source dhId = %{public}s, sourceVersion = %{public}s,"
736         "subtype = %{public}s", dhType, GetAnonyString(uuid).c_str(),
737         param.sinkVersion.c_str(), GetAnonyString(sourceDeviceInfo.uuid).c_str(), GetAnonyString(sourceDHId).c_str(),
738         param.sourceVersion.c_str(), param.subtype.c_str());
739     return DH_FWK_SUCCESS;
740 }
741 
GetCapParam(const std::string & uuid,const std::string & dhId,std::shared_ptr<CapabilityInfo> & capability)742 int32_t ComponentManager::GetCapParam(const std::string &uuid, const std::string &dhId,
743     std::shared_ptr<CapabilityInfo> &capability)
744 {
745     if (!IsIdLengthValid(uuid) || !IsIdLengthValid(dhId)) {
746         return ERR_DH_FWK_PARA_INVALID;
747     }
748     std::string deviceId = GetDeviceIdByUUID(uuid);
749     auto ret = CapabilityInfoManager::GetInstance()->GetCapability(deviceId, dhId, capability);
750     if ((ret == DH_FWK_SUCCESS) && (capability != nullptr)) {
751         DHLOGI("GetCapability success, deviceId: %{public}s, uuid: %{public}s, dhId: %{public}s, ret: %{public}d",
752             GetAnonyString(deviceId).c_str(), GetAnonyString(uuid).c_str(), GetAnonyString(dhId).c_str(), ret);
753         return ret;
754     }
755 
756     ret = LocalCapabilityInfoManager::GetInstance()->GetCapability(deviceId, dhId, capability);
757     if ((ret == DH_FWK_SUCCESS) && (capability != nullptr)) {
758         DHLOGI("Local GetCaps success, deviceId: %{public}s, uuid: %{public}s, dhId: %{public}s, ret: %{public}d",
759             GetAnonyString(deviceId).c_str(), GetAnonyString(uuid).c_str(), GetAnonyString(dhId).c_str(), ret);
760         return ret;
761     }
762 
763     return ret;
764 }
765 
GetMetaParam(const std::string & uuid,const std::string & dhId,std::shared_ptr<MetaCapabilityInfo> & metaCapPtr)766 int32_t ComponentManager::GetMetaParam(const std::string &uuid, const std::string &dhId,
767     std::shared_ptr<MetaCapabilityInfo> &metaCapPtr)
768 {
769     if (!IsIdLengthValid(uuid) || !IsIdLengthValid(dhId)) {
770         return ERR_DH_FWK_PARA_INVALID;
771     }
772     auto ret = MetaInfoManager::GetInstance()->GetMetaCapInfo(DHContext::GetInstance().GetUdidHashIdByUUID(uuid),
773         dhId, metaCapPtr);
774     if ((ret == DH_FWK_SUCCESS) && (metaCapPtr != nullptr)) {
775         DHLOGI("GetCapability success, uuid =%{public}s, dhId = %{public}s, errCode = %{public}d",
776             GetAnonyString(uuid).c_str(), GetAnonyString(dhId).c_str(), ret);
777         return ret;
778     }
779     return ret;
780 }
781 
GetEnableParam(const std::string & networkId,const std::string & uuid,const std::string & dhId,DHType dhType,EnableParam & param)782 int32_t ComponentManager::GetEnableParam(const std::string &networkId, const std::string &uuid,
783     const std::string &dhId, DHType dhType, EnableParam &param)
784 {
785     if (!IsIdLengthValid(networkId) || !IsIdLengthValid(uuid) || !IsIdLengthValid(dhId)) {
786         return ERR_DH_FWK_COMPONENT_GET_ENABLE_PARAM_FAILED;
787     }
788     DHLOGI("GetEnableParam start, networkId= %{public}s, uuid = %{public}s, dhId = %{public}s, dhType = %{public}#X,",
789         GetAnonyString(networkId).c_str(), GetAnonyString(uuid).c_str(), GetAnonyString(dhId).c_str(), dhType);
790     std::shared_ptr<CapabilityInfo> capability = nullptr;
791     if (GetCapParam(uuid, dhId, capability) == DH_FWK_SUCCESS) {
792         auto ret = GetEnableCapParam(networkId, uuid, dhType, param, capability);
793         if (ret == DH_FWK_SUCCESS) {
794             return ret;
795         }
796         DHLOGE("GetEnableCapParam failed.");
797     }
798 
799     std::shared_ptr<MetaCapabilityInfo> metaCapPtr = nullptr;
800     if (GetMetaParam(uuid, dhId, metaCapPtr) == DH_FWK_SUCCESS) {
801         auto ret = GetEnableMetaParam(networkId, uuid, dhType, param, metaCapPtr);
802         if (ret == DH_FWK_SUCCESS) {
803             return ret;
804         }
805         DHLOGE("GetEnableMetaParam failed.");
806     }
807     DHLOGE("GetEnableParam is failed.");
808     return ERR_DH_FWK_COMPONENT_GET_ENABLE_PARAM_FAILED;
809 }
810 
GetVersionFromVerMgr(const std::string & uuid,const DHType dhType,std::string & version,bool isSink)811 int32_t ComponentManager::GetVersionFromVerMgr(const std::string &uuid, const DHType dhType,
812     std::string &version, bool isSink)
813 {
814     if (!IsIdLengthValid(uuid)) {
815         return ERR_DH_FWK_PARA_INVALID;
816     }
817     CompVersion compversion;
818     int32_t ret = VersionManager::GetInstance().GetCompVersion(uuid, dhType, compversion);
819     if (ret != DH_FWK_SUCCESS) {
820         DHLOGE("Get version Manager failed, uuid =%{public}s, dhType = %{public}#X, errCode = %{public}d",
821             GetAnonyString(uuid).c_str(), dhType, ret);
822         return ret;
823     }
824     DHLOGI("Get version mgr success, sinkVersion = %{public}s, sourceVersion = %{public}s,uuid = %{public}s, "
825         "dhType = %{public}#X", compversion.sinkVersion.c_str(), compversion.sourceVersion.c_str(),
826         GetAnonyString(uuid).c_str(), dhType);
827     version = isSink ? compversion.sinkVersion : compversion.sourceVersion;
828     return DH_FWK_SUCCESS;
829 }
830 
GetVersionFromVerInfoMgr(const std::string & uuid,const DHType dhType,std::string & version,bool isSink)831 int32_t ComponentManager::GetVersionFromVerInfoMgr(const std::string &uuid, const DHType dhType,
832     std::string &version, bool isSink)
833 {
834     if (!IsIdLengthValid(uuid)) {
835         return ERR_DH_FWK_PARA_INVALID;
836     }
837     VersionInfo versionInfo;
838     int32_t ret =  VersionInfoManager::GetInstance()->GetVersionInfoByDeviceId(GetDeviceIdByUUID(uuid), versionInfo);
839     if (ret != DH_FWK_SUCCESS) {
840         DHLOGE("Get Version info Manager failed, uuid =%{public}s, dhType = %{public}#X, errCode = %{public}d",
841             GetAnonyString(uuid).c_str(), dhType, ret);
842         return ret;
843     }
844     auto iter = versionInfo.compVersions.find(dhType);
845     if (iter == versionInfo.compVersions.end()) {
846         DHLOGE("can not find component version for dhType = %{public}d", dhType);
847         return ERR_DH_FWK_COMPONENT_DHTYPE_NOT_FOUND;
848     }
849     DHLOGI("Get version info mgr success, sinkVersion = %{public}s, sourceVersion = %{public}s, uuid = %{public}s, "
850         "dhType = %{public}#X", iter->second.sinkVersion.c_str(), iter->second.sourceVersion.c_str(),
851         GetAnonyString(uuid).c_str(), dhType);
852     UpdateVersionCache(uuid, versionInfo);
853     version = isSink ? iter->second.sinkVersion : iter->second.sourceVersion;
854     return DH_FWK_SUCCESS;
855 }
856 
GetVersion(const std::string & uuid,DHType dhType,std::string & version,bool isSink)857 int32_t ComponentManager::GetVersion(const std::string &uuid, DHType dhType, std::string &version, bool isSink)
858 {
859     if (!IsIdLengthValid(uuid)) {
860         return ERR_DH_FWK_PARA_INVALID;
861     }
862     int32_t ret = GetVersionFromVerMgr(uuid, dhType, version, isSink);
863     if ((ret == DH_FWK_SUCCESS) && (!version.empty())) {
864         return DH_FWK_SUCCESS;
865     }
866 
867     ret = GetVersionFromVerInfoMgr(uuid, dhType, version, isSink);
868     if ((ret == DH_FWK_SUCCESS) && (!version.empty())) {
869         return DH_FWK_SUCCESS;
870     }
871 
872     return ret;
873 }
874 
UpdateVersionCache(const std::string & uuid,const VersionInfo & versionInfo)875 void ComponentManager::UpdateVersionCache(const std::string &uuid, const VersionInfo &versionInfo)
876 {
877     if (!IsIdLengthValid(uuid)) {
878         return;
879     }
880     DHVersion dhVersion;
881     dhVersion.uuid = uuid;
882     dhVersion.dhVersion = versionInfo.dhVersion;
883     dhVersion.compVersions = versionInfo.compVersions;
884     VersionManager::GetInstance().AddDHVersion(uuid, dhVersion);
885 }
886 
DumpLoadedComps(std::set<DHType> & compSourceType,std::set<DHType> & compSinkType)887 void ComponentManager::DumpLoadedComps(std::set<DHType> &compSourceType, std::set<DHType> &compSinkType)
888 {
889     for (auto compSource : compSource_) {
890         compSourceType.emplace(compSource.first);
891     }
892     for (auto compSink : compSink_) {
893         compSinkType.emplace(compSink.first);
894     }
895 }
896 
Recover(DHType dhType)897 void ComponentManager::Recover(DHType dhType)
898 {
899     ffrt::submit([this, dhType]() { this->DoRecover(dhType); });
900 }
901 
DoRecover(DHType dhType)902 void ComponentManager::DoRecover(DHType dhType)
903 {
904     int32_t ret = pthread_setname_np(pthread_self(), DO_RECOVER);
905     if (ret != DH_FWK_SUCCESS) {
906         DHLOGE("DoRecover setname failed.");
907     }
908     // step1: restart sa process
909     ReStartSA(dhType);
910     // step2: recover distributed hardware virtual driver
911     RecoverDistributedHardware(dhType);
912 }
913 
ReStartSA(DHType dhType)914 void ComponentManager::ReStartSA(DHType dhType)
915 {
916     DHLOGI("Restart SA for DHType %{public}" PRIu32, (uint32_t)dhType);
917     auto sourceResult = StartSource(dhType);
918     auto sinkResult = StartSink(dhType);
919 
920     if (!WaitForResult(Action::START_SOURCE, sourceResult)) {
921         DHLOGE("ReStartSource failed, DHType: %{public}" PRIu32, (uint32_t)dhType);
922     }
923 
924     if (!WaitForResult(Action::START_SINK, sinkResult)) {
925         DHLOGE("ReStartSink failed, DHType: %{public}" PRIu32, (uint32_t)dhType);
926     }
927     DHLOGI("Finish Restart");
928 }
929 
RecoverDistributedHardware(DHType dhType)930 void ComponentManager::RecoverDistributedHardware(DHType dhType)
931 {
932     MetaCapInfoMap metaInfoMap;
933     MetaInfoManager::GetInstance()->GetMetaDataByDHType(dhType, metaInfoMap);
934     for (const auto &metaInfo : metaInfoMap) {
935         std::string uuid = DHContext::GetInstance().GetUUIDByDeviceId(metaInfo.second->GetDeviceId());
936         if (uuid.empty()) {
937             DHLOGE("Can not find uuid by capability deviceId: %{public}s",
938                 GetAnonyString(metaInfo.second->GetDeviceId()).c_str());
939             continue;
940         }
941 
942         std::string networkId = DHContext::GetInstance().GetNetworkIdByUUID(uuid);
943         if (networkId.empty()) {
944             DHLOGI("Can not find network id by uuid: %{public}s", GetAnonyString(uuid).c_str());
945             continue;
946         }
947 
948         TaskParam taskParam = {
949             .networkId = networkId,
950             .uuid = uuid,
951             .dhId = metaInfo.second->GetDHId(),
952             .dhType = metaInfo.second->GetDHType()
953         };
954         auto task = TaskFactory::GetInstance().CreateTask(TaskType::ENABLE, taskParam, nullptr);
955         TaskExecutor::GetInstance().PushTask(task);
956     }
957 }
958 
GetDHSinkInstance()959 std::map<DHType, IDistributedHardwareSink*> ComponentManager::GetDHSinkInstance()
960 {
961     return compSink_;
962 }
963 
IsIdenticalAccount(const std::string & networkId)964 bool ComponentManager::IsIdenticalAccount(const std::string &networkId)
965 {
966     if (!IsIdLengthValid(networkId)) {
967         return false;
968     }
969     DmAuthForm authForm = DmAuthForm::INVALID_TYPE;
970     std::vector<DmDeviceInfo> deviceList;
971     DeviceManager::GetInstance().GetTrustedDeviceList(DH_FWK_PKG_NAME, "", deviceList);
972     if (deviceList.size() == 0 || deviceList.size() > MAX_ONLINE_DEVICE_SIZE) {
973         DHLOGE("DeviceList size is invalid!");
974         return false;
975     }
976     for (const auto &deviceInfo : deviceList) {
977         if (std::string(deviceInfo.networkId) == networkId) {
978             authForm = deviceInfo.authForm;
979             break;
980         }
981     }
982     if (authForm == DmAuthForm::IDENTICAL_ACCOUNT) {
983         return true;
984     }
985     return false;
986 }
987 
UpdateBusinessState(const std::string & networkId,const std::string & dhId,BusinessState state)988 void ComponentManager::UpdateBusinessState(const std::string &networkId, const std::string &dhId, BusinessState state)
989 {
990     if (!IsIdLengthValid(networkId) || !IsIdLengthValid(dhId)) {
991         return;
992     }
993     DHLOGI("UpdateBusinessState, networkId: %{public}s, dhId: %{public}s, state: %{public}" PRIu32,
994         GetAnonyString(networkId).c_str(), GetAnonyString(dhId).c_str(), (uint32_t)state);
995     {
996         std::lock_guard<std::mutex> lock(bizStateMtx_);
997         dhBizStates_[{networkId, dhId}] = state;
998     }
999 
1000     if (state == BusinessState::IDLE) {
1001         TaskParam taskParam;
1002         if (!FetchNeedRefreshTask({networkId, dhId}, taskParam)) {
1003             return;
1004         }
1005         DHLOGI("The dh need refresh, networkId: %{public}s, dhId: %{public}s",
1006             GetAnonyString(networkId).c_str(), GetAnonyString(dhId).c_str());
1007         auto task = TaskFactory::GetInstance().CreateTask(TaskType::ENABLE, taskParam, nullptr);
1008         TaskExecutor::GetInstance().PushTask(task);
1009     }
1010 }
1011 
GetDHSourceInstance(DHType dhType)1012 IDistributedHardwareSource* ComponentManager::GetDHSourceInstance(DHType dhType)
1013 {
1014     if (compSource_.find(dhType) == compSource_.end()) {
1015         DHLOGE("can not find handler for dhType = %{public}d.", dhType);
1016         return nullptr;
1017     }
1018     return compSource_[dhType];
1019 }
1020 
QueryBusinessState(const std::string & uuid,const std::string & dhId)1021 BusinessState ComponentManager::QueryBusinessState(const std::string &uuid, const std::string &dhId)
1022 {
1023     if (!IsIdLengthValid(uuid) || !IsIdLengthValid(dhId)) {
1024         return BusinessState::UNKNOWN;
1025     }
1026     std::lock_guard<std::mutex> lock(bizStateMtx_);
1027     std::pair<std::string, std::string> key = {uuid, dhId};
1028     if (dhBizStates_.find(key) == dhBizStates_.end()) {
1029         return BusinessState::UNKNOWN;
1030     }
1031 
1032     return dhBizStates_.at(key);
1033 }
1034 
TriggerFullCapsSync(const std::string & networkId)1035 void ComponentManager::TriggerFullCapsSync(const std::string &networkId)
1036 {
1037     if (!IsIdLengthValid(networkId)) {
1038         return;
1039     }
1040     if (dhCommToolPtr_ == nullptr) {
1041         DHLOGE("DH communication tool ptr is null");
1042         return;
1043     }
1044     dhCommToolPtr_->TriggerReqFullDHCaps(networkId);
1045 }
1046 
SaveNeedRefreshTask(const TaskParam & taskParam)1047 void ComponentManager::SaveNeedRefreshTask(const TaskParam &taskParam)
1048 {
1049     std::lock_guard<std::mutex> lock(needRefreshTaskParamsMtx_);
1050     needRefreshTaskParams_[{taskParam.networkId, taskParam.dhId}] = taskParam;
1051 }
1052 
FetchNeedRefreshTask(const std::pair<std::string,std::string> & taskKey,TaskParam & taskParam)1053 bool ComponentManager::FetchNeedRefreshTask(const std::pair<std::string, std::string> &taskKey, TaskParam &taskParam)
1054 {
1055     std::lock_guard<std::mutex> lock(needRefreshTaskParamsMtx_);
1056     if (needRefreshTaskParams_.find(taskKey) == needRefreshTaskParams_.end()) {
1057         return false;
1058     }
1059 
1060     taskParam = needRefreshTaskParams_.at(taskKey);
1061     needRefreshTaskParams_.erase(taskKey);
1062     return true;
1063 }
1064 
ComponentManagerEventHandler(const std::shared_ptr<AppExecFwk::EventRunner> runner)1065 ComponentManager::ComponentManagerEventHandler::ComponentManagerEventHandler(
1066     const std::shared_ptr<AppExecFwk::EventRunner> runner) : AppExecFwk::EventHandler(runner)
1067 {
1068     DHLOGI("Ctor ComponentManagerEventHandler");
1069 }
1070 
ProcessEvent(const AppExecFwk::InnerEvent::Pointer & event)1071 void ComponentManager::ComponentManagerEventHandler::ProcessEvent(
1072     const AppExecFwk::InnerEvent::Pointer &event)
1073 {
1074     if (event == nullptr) {
1075         DHLOGE("event is nullptr");
1076         return;
1077     }
1078     uint32_t eventId = event->GetInnerEventId();
1079     switch (eventId) {
1080         case EVENT_DATA_SYNC_MANUAL: {
1081             // do muanul sync with remote
1082             auto sharedObjPtr = event->GetSharedObject<std::string>();
1083             if (sharedObjPtr == nullptr) {
1084                 DHLOGE("The data sync param invalid!");
1085                 break;
1086             }
1087             std::string networkId = *sharedObjPtr;
1088             DHLOGI("Try receive full capabiliy info from networkId: %{public}s", GetAnonyString(networkId).c_str());
1089             if (networkId.empty()) {
1090                 DHLOGE("Can not get device uuid by networkId: %{public}s", GetAnonyString(networkId).c_str());
1091                 break;
1092             }
1093             ComponentManager::GetInstance().TriggerFullCapsSync(networkId);
1094             break;
1095         }
1096         default:
1097             DHLOGE("event is undefined, id is %{public}d", eventId);
1098             break;
1099     }
1100 }
1101 
GetEventHandler()1102 std::shared_ptr<ComponentManager::ComponentManagerEventHandler> ComponentManager::GetEventHandler()
1103 {
1104     return this->eventHandler_;
1105 }
1106 
1107 } // namespace DistributedHardware
1108 } // namespace OHOS
1109