• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2025 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 "db_adapter.h"
17 
18 #include <vector>
19 
20 #include "anonymous_string.h"
21 #include "capability_info.h"
22 #include "capability_info_manager.h"
23 #include "capability_utils.h"
24 #include "constants.h"
25 #include "dh_context.h"
26 #include "dh_utils_tool.h"
27 #include "distributed_hardware_errno.h"
28 #include "distributed_hardware_log.h"
29 #include "event_handler.h"
30 #include "meta_info_manager.h"
31 #include "version_info_manager.h"
32 
33 namespace OHOS {
34 namespace DistributedHardware {
35 #undef DH_LOG_TAG
36 #define DH_LOG_TAG "DBAdapter"
37 
38 namespace {
39     constexpr int32_t MAX_INIT_RETRY_TIMES = 20;
40     constexpr int32_t INIT_RETRY_SLEEP_INTERVAL = 200 * 1000; // 200ms
41     constexpr int32_t DIED_CHECK_MAX_TIMES = 300;
42     constexpr int32_t DIED_CHECK_INTERVAL = 100 * 1000; // 100ms
43     const std::string DATABASE_DIR = "/data/service/el1/public/database/";
44     constexpr const char *GLOBAL_META_INFO_KEY = "global_meta_info";
45     constexpr const char *GLOBAL_VERSION_INFO_KEY = "global_version_info";
46     constexpr const char *GLOBAL_CAPABILITY_INFO_KEY = "global_capability_info";
47 }
48 
DBAdapter(const char * appId,const char * storeId,const std::shared_ptr<DistributedKv::KvStoreObserver> changeListener)49 DBAdapter::DBAdapter(const char *appId, const char *storeId,
50     const std::shared_ptr<DistributedKv::KvStoreObserver> changeListener)
51 {
52     this->appId_.appId = std::string(appId);
53     this->storeId_.storeId = std::string(storeId);
54     this->dataChangeListener_ = changeListener;
55     DHLOGI("DBAdapter Constructor Success, appId: %{public}s, storeId: %{public}s", appId, storeId);
56 }
57 
~DBAdapter()58 DBAdapter::~DBAdapter()
59 {
60     DHLOGI("DBAdapter Destruction");
61 }
62 
GetKvStorePtr(bool isAutoSync,DistributedKv::DataType dataType)63 DistributedKv::Status DBAdapter::GetKvStorePtr(bool isAutoSync, DistributedKv::DataType dataType)
64 {
65     DistributedKv::Options options = {
66         .createIfMissing = true,
67         .encrypt = false,
68         .autoSync = isAutoSync,
69         .isPublic = true,
70         .securityLevel = DistributedKv::SecurityLevel::S1,
71         .area = DistributedKv::EL1,
72         .kvStoreType = DistributedKv::KvStoreType::SINGLE_VERSION,
73         .baseDir = DATABASE_DIR + appId_.appId,
74         .dataType = dataType,
75         .cloudConfig = {
76             .enableCloud = true,
77             .autoSync  = true,
78         }
79     };
80     if (dataType == DistributedKv::DataType::TYPE_DYNAMICAL) {
81         DHLOGI("Dynamic not go to cloud.");
82         options.cloudConfig.enableCloud = false;
83         options.cloudConfig.autoSync = false;
84     }
85     return kvDataMgr_.GetSingleKvStore(options, appId_, storeId_, kvStoragePtr_);
86 }
87 
GetLocalKvStorePtr()88 DistributedKv::Status DBAdapter::GetLocalKvStorePtr()
89 {
90     DistributedKv::Options options = {
91         .createIfMissing = true,
92         .encrypt = false,
93         .autoSync = false,
94         .securityLevel = DistributedKv::SecurityLevel::S1,
95         .area = DistributedKv::EL1,
96         .kvStoreType = DistributedKv::KvStoreType::SINGLE_VERSION,
97         .baseDir = DATABASE_DIR + appId_.appId
98     };
99     return kvDataMgr_.GetSingleKvStore(options, appId_, storeId_, kvStoragePtr_);
100 }
101 
Init(bool isAutoSync,DistributedKv::DataType dataType)102 int32_t DBAdapter::Init(bool isAutoSync, DistributedKv::DataType dataType)
103 {
104     this->isAutoSync_ = isAutoSync;
105     this->dataType_ = dataType;
106     DHLOGI("Init DB, storeId: %{public}s, dataType: %{public}d",
107         storeId_.storeId.c_str(), static_cast<int32_t>(dataType));
108     std::lock_guard<std::mutex> lock(dbAdapterMutex_);
109     int32_t tryTimes = MAX_INIT_RETRY_TIMES;
110     while (tryTimes > 0) {
111         DistributedKv::Status status = GetKvStorePtr(isAutoSync, dataType);
112         if (status == DistributedKv::Status::SUCCESS && kvStoragePtr_) {
113             DHLOGI("Init KvStorePtr Success");
114             RegisterChangeListener();
115             RegisterKvStoreDeathListener();
116             return DH_FWK_SUCCESS;
117         }
118 
119         if (status == DistributedKv::Status::STORE_META_CHANGED) {
120             DHLOGW("This db meta changed, remove and rebuild it");
121             kvDataMgr_.DeleteKvStore(appId_, storeId_, DATABASE_DIR + appId_.appId);
122         }
123 
124         DHLOGD("CheckKvStore, left times: %{public}d", tryTimes);
125         usleep(INIT_RETRY_SLEEP_INTERVAL);
126         tryTimes--;
127     }
128     if (kvStoragePtr_ == nullptr) {
129         DHLOGE("Init KvStorePtr failed");
130         return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
131     }
132     return DH_FWK_SUCCESS;
133 }
134 
InitLocal()135 int32_t DBAdapter::InitLocal()
136 {
137     this->isAutoSync_ = false;
138     this->dataType_ = DistributedKv::DataType::TYPE_STATICS;
139     DHLOGI("Init local DB, storeId: %{public}s, dataType: %{public}d",
140         storeId_.storeId.c_str(), static_cast<int32_t>(this->dataType_));
141     std::lock_guard<std::mutex> lock(dbAdapterMutex_);
142     int32_t tryTimes = MAX_INIT_RETRY_TIMES;
143     while (tryTimes > 0) {
144         DistributedKv::Status status = GetLocalKvStorePtr();
145         if (status == DistributedKv::Status::SUCCESS && kvStoragePtr_) {
146             DHLOGI("Init KvStorePtr Success");
147             RegisterKvStoreDeathListener();
148             return DH_FWK_SUCCESS;
149         }
150         DHLOGD("CheckKvStore, left times: %{public}d", tryTimes);
151         usleep(INIT_RETRY_SLEEP_INTERVAL);
152         tryTimes--;
153     }
154     if (kvStoragePtr_ == nullptr) {
155         DHLOGE("Init KvStorePtr failed");
156         return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
157     }
158     return DH_FWK_SUCCESS;
159 }
160 
UnInit()161 void DBAdapter::UnInit()
162 {
163     DHLOGI("DBAdapter UnInit");
164     std::lock_guard<std::mutex> lock(dbAdapterMutex_);
165     if (kvStoragePtr_ == nullptr) {
166         DHLOGE("kvStoragePtr_ is null");
167         return;
168     }
169     UnRegisterKvStoreDeathListener();
170     if (this->isAutoSync_) {
171         UnRegisterChangeListener();
172     }
173     kvStoragePtr_.reset();
174 }
175 
ReInit(bool isAutoSync)176 int32_t DBAdapter::ReInit(bool isAutoSync)
177 {
178     DHLOGI("ReInit DB, storeId: %{public}s", storeId_.storeId.c_str());
179     std::lock_guard<std::mutex> lock(dbAdapterMutex_);
180     if (kvStoragePtr_ == nullptr) {
181         DHLOGE("kvStoragePtr_ is null");
182         return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
183     }
184     kvStoragePtr_.reset();
185     DistributedKv::Status status = this->isAutoSync_ ?
186         GetKvStorePtr(isAutoSync, this->dataType_) : GetLocalKvStorePtr();
187     if (status != DistributedKv::Status::SUCCESS || !kvStoragePtr_) {
188         DHLOGW("Get kvStoragePtr_ failed, status: %{public}d", status);
189         return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
190     }
191     RegisterKvStoreDeathListener();
192     return DH_FWK_SUCCESS;
193 }
194 
GetNetworkIdByKey(const std::string & key)195 std::string DBAdapter::GetNetworkIdByKey(const std::string &key)
196 {
197     if (!IsIdLengthValid(key)) {
198         return "";
199     }
200     DHLOGI("Get networkId by key: %{public}s", GetAnonyString(key).c_str());
201     std::string deviceId = DHContext::GetInstance().GetDeviceIdByDBGetPrefix(key);
202     if (deviceId.empty()) {
203         DHLOGW("Get deviceId empty, key: %{public}s", GetAnonyString(key).c_str());
204         return "";
205     }
206 
207     if (deviceId == DHContext::GetInstance().GetDeviceInfo().deviceId) {
208         DHLOGW("Query local db info, no need sync");
209         return "";
210     }
211 
212     std::string uuid = DHContext::GetInstance().GetUUIDByDeviceId(deviceId);
213     if (uuid.empty()) {
214         DHLOGW("Get uuid empty, deviceId: %{public}s", GetAnonyString(deviceId).c_str());
215         return "";
216     }
217     if (!DHContext::GetInstance().IsDeviceOnline(uuid)) {
218         DHLOGW("The device not online, no need sync, uuid: %{public}s, deviceId: %{public}s",
219             GetAnonyString(uuid).c_str(), GetAnonyString(deviceId).c_str());
220         return "";
221     }
222     return DHContext::GetInstance().GetNetworkIdByUUID(uuid);
223 }
224 
SyncByNotFound(const std::string & key)225 void DBAdapter::SyncByNotFound(const std::string &key)
226 {
227     if (!IsIdLengthValid(key)) {
228         return;
229     }
230     std::string networkId = GetNetworkIdByKey(key);
231     if (networkId.empty()) {
232         DHLOGW("The networkId emtpy.");
233         return;
234     }
235     DHLOGI("Try sync data by key: %{public}s, storeId: %{public}s", GetAnonyString(key).c_str(),
236         storeId_.storeId.c_str());
237     std::vector<std::string> networkIdVec;
238     networkIdVec.push_back(networkId);
239     kvStoragePtr_->Sync(networkIdVec, DistributedKv::SyncMode::PUSH_PULL);
240     return;
241 }
242 
GetDataByKey(const std::string & key,std::string & data)243 int32_t DBAdapter::GetDataByKey(const std::string &key, std::string &data)
244 {
245     if (!IsIdLengthValid(key)) {
246         return ERR_DH_FWK_PARA_INVALID;
247     }
248     DHLOGI("Get data by key: %{public}s, storeId: %{public}s, dataType: %{public}d",
249         GetAnonyString(key).c_str(), storeId_.storeId.c_str(), static_cast<int32_t>(this->dataType_));
250     std::lock_guard<std::mutex> lock(dbAdapterMutex_);
251     if (kvStoragePtr_ == nullptr) {
252         DHLOGE("kvStoragePtr_ is null");
253         return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
254     }
255     DistributedKv::Key kvKey(key);
256     DistributedKv::Value kvValue;
257     DistributedKv::Status status = kvStoragePtr_->Get(kvKey, kvValue);
258     if (status == DistributedKv::Status::NOT_FOUND) {
259         if (this->dataType_ == DistributedKv::DataType::TYPE_DYNAMICAL) {
260             SyncByNotFound(key);
261         }
262 #ifdef DHARDWARE_OPEN_SOURCE
263         if (this->dataType_ == DistributedKv::DataType::TYPE_STATICS &&
264             this->storeId_.storeId == std::string(GLOBAL_META_INFO_KEY)) {
265             SyncByNotFound(key);
266         }
267 #endif
268     }
269     if (status != DistributedKv::Status::SUCCESS) {
270         DHLOGE("Query from db failed, key: %{public}s", GetAnonyString(key).c_str());
271         return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
272     }
273     data = kvValue.ToString();
274     return DH_FWK_SUCCESS;
275 }
276 
GetDataByKeyPrefix(const std::string & keyPrefix,std::vector<std::string> & values)277 int32_t DBAdapter::GetDataByKeyPrefix(const std::string &keyPrefix, std::vector<std::string> &values)
278 {
279     DHLOGI("Get data by key prefix: %{public}s, storeId: %{public}s, dataType: %{public}d",
280         GetAnonyString(keyPrefix).c_str(), storeId_.storeId.c_str(), static_cast<int32_t>(this->dataType_));
281     std::lock_guard<std::mutex> lock(dbAdapterMutex_);
282     if (kvStoragePtr_ == nullptr) {
283         DHLOGE("kvStoragePtr_ is null");
284         return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
285     }
286     // if prefix is empty, get all entries.
287     DistributedKv::Key allEntryKeyPrefix(keyPrefix);
288     std::vector<DistributedKv::Entry> allEntries;
289     DistributedKv::Status status = kvStoragePtr_->GetEntries(allEntryKeyPrefix, allEntries);
290     if (status == DistributedKv::Status::SUCCESS && allEntries.size() == 0) {
291         if (this->dataType_ == DistributedKv::DataType::TYPE_DYNAMICAL) {
292             SyncByNotFound(keyPrefix);
293         }
294 #ifdef DHARDWARE_OPEN_SOURCE
295         if (this->dataType_ == DistributedKv::DataType::TYPE_STATICS &&
296             this->storeId_.storeId == std::string(GLOBAL_META_INFO_KEY)) {
297             SyncByNotFound(keyPrefix);
298         }
299 #endif
300     }
301     if (status != DistributedKv::Status::SUCCESS) {
302         DHLOGE("Query data by keyPrefix failed, prefix: %{public}s", GetAnonyString(keyPrefix).c_str());
303         return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
304     }
305     if (allEntries.empty() || allEntries.size() > MAX_DB_RECORD_SIZE) {
306         DHLOGE("AllEntries size: %{public}zu is invalid, maybe empty or too large.", allEntries.size());
307         return ERR_DH_FWK_RESOURCE_RES_DB_DATA_INVALID;
308     }
309     for (const auto& item : allEntries) {
310         values.push_back(item.value.ToString());
311     }
312     return DH_FWK_SUCCESS;
313 }
314 
PutData(const std::string & key,const std::string & value)315 int32_t DBAdapter::PutData(const std::string &key, const std::string &value)
316 {
317     if (!IsIdLengthValid(key) || !IsMessageLengthValid(value)) {
318         return ERR_DH_FWK_PARA_INVALID;
319     }
320     std::lock_guard<std::mutex> lock(dbAdapterMutex_);
321     if (kvStoragePtr_ == nullptr) {
322         DHLOGE("kvStoragePtr_ is null");
323         return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
324     }
325     DistributedKv::Key kvKey(key);
326     DistributedKv::Value kvValue(value);
327     DistributedKv::Status status = kvStoragePtr_->Put(kvKey, kvValue);
328     if (status == DistributedKv::Status::IPC_ERROR) {
329         DHLOGE("Put kv to db failed, ret: %{public}d", status);
330         return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
331     }
332     return DH_FWK_SUCCESS;
333 }
334 
PutDataBatch(const std::vector<std::string> & keys,const std::vector<std::string> & values)335 int32_t DBAdapter::PutDataBatch(const std::vector<std::string> &keys, const std::vector<std::string> &values)
336 {
337     if (!IsArrayLengthValid(keys) || !IsArrayLengthValid(values)) {
338         return ERR_DH_FWK_PARA_INVALID;
339     }
340     std::lock_guard<std::mutex> lock(dbAdapterMutex_);
341     if (kvStoragePtr_ == nullptr) {
342         DHLOGE("kvStoragePtr_ is null");
343         return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
344     }
345     if (keys.size() != values.size() || keys.empty() || values.empty()) {
346         DHLOGE("Param is invalid!");
347         return ERR_DH_FWK_PARA_INVALID;
348     }
349     std::vector<DistributedKv::Entry> entries;
350     for (unsigned long i = 0; i < keys.size(); i++) {
351         DistributedKv::Entry entry;
352         entry.key = keys[i];
353         entry.value = values[i];
354         entries.push_back(entry);
355     }
356     DistributedKv::Status status = kvStoragePtr_->PutBatch(entries);
357     if (status != DistributedKv::Status::SUCCESS) {
358         DHLOGE("Put kv batch to db failed, ret: %{public}d", status);
359         return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
360     }
361     DHLOGI("Put kv batch to db success");
362     return DH_FWK_SUCCESS;
363 }
364 
SyncDBForRecover()365 void DBAdapter::SyncDBForRecover()
366 {
367     DHLOGI("Sync store id: %{public}s after db recover", storeId_.storeId.c_str());
368     if (storeId_.storeId == std::string(GLOBAL_CAPABILITY_INFO_KEY)) {
369         AppExecFwk::InnerEvent::Pointer msgEvent = AppExecFwk::InnerEvent::Get(EVENT_CAPABILITY_INFO_DB_RECOVER);
370         CapabilityInfoManager::GetInstance()->GetEventHandler()->SendEvent(msgEvent,
371             0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
372     }
373 
374     if (storeId_.storeId == std::string(GLOBAL_VERSION_INFO_KEY)) {
375         AppExecFwk::InnerEvent::Pointer msgEvent = AppExecFwk::InnerEvent::Get(EVENT_VERSION_INFO_DB_RECOVER);
376         VersionInfoManager::GetInstance()->GetEventHandler()->SendEvent(msgEvent,
377             0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
378     }
379 
380     if (storeId_.storeId == std::string(GLOBAL_META_INFO_KEY)) {
381         AppExecFwk::InnerEvent::Pointer msgEvent = AppExecFwk::InnerEvent::Get(EVENT_META_INFO_DB_RECOVER);
382         MetaInfoManager::GetInstance()->GetEventHandler()->SendEvent(msgEvent,
383             0, AppExecFwk::EventQueue::Priority::IMMEDIATE);
384     }
385 }
386 
RegisterChangeListener()387 int32_t DBAdapter::RegisterChangeListener()
388 {
389     DHLOGI("Register db data change listener");
390     if (kvStoragePtr_ == nullptr) {
391         DHLOGE("kvStoragePtr_ is null");
392         return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
393     }
394     DistributedKv::Status status = kvStoragePtr_->SubscribeKvStore(DistributedKv::SubscribeType::SUBSCRIBE_TYPE_REMOTE,
395         dataChangeListener_);
396     if (status == DistributedKv::Status::IPC_ERROR) {
397         DHLOGE("Register db data change listener failed, ret: %{public}d", status);
398         return ERR_DH_FWK_RESOURCE_REGISTER_DB_FAILED;
399     }
400     status = kvStoragePtr_->SubscribeKvStore(DistributedKv::SubscribeType::SUBSCRIBE_TYPE_CLOUD,
401         dataChangeListener_);
402     if (status == DistributedKv::Status::IPC_ERROR) {
403         DHLOGE("Register db cloud data change listener failed, ret: %{public}d", status);
404         return ERR_DH_FWK_RESOURCE_REGISTER_DB_FAILED;
405     }
406     return DH_FWK_SUCCESS;
407 }
408 
UnRegisterChangeListener()409 int32_t DBAdapter::UnRegisterChangeListener()
410 {
411     DHLOGI("UnRegister db data change listener");
412     if (kvStoragePtr_ == nullptr) {
413         DHLOGE("kvStoragePtr_ is null");
414         return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
415     }
416     DistributedKv::Status status = kvStoragePtr_->UnSubscribeKvStore(
417         DistributedKv::SubscribeType::SUBSCRIBE_TYPE_REMOTE, dataChangeListener_);
418     if (status == DistributedKv::Status::IPC_ERROR) {
419         DHLOGE("UnRegister db data change listener failed, ret: %{public}d", status);
420         return ERR_DH_FWK_RESOURCE_UNREGISTER_DB_FAILED;
421     }
422     status = kvStoragePtr_->UnSubscribeKvStore(
423         DistributedKv::SubscribeType::SUBSCRIBE_TYPE_CLOUD, dataChangeListener_);
424     if (status == DistributedKv::Status::IPC_ERROR) {
425         DHLOGE("UnRegister db cloud data change listener failed, ret: %{public}d", status);
426         return ERR_DH_FWK_RESOURCE_UNREGISTER_DB_FAILED;
427     }
428     return DH_FWK_SUCCESS;
429 }
430 
RegisterKvStoreDeathListener()431 void DBAdapter::RegisterKvStoreDeathListener()
432 {
433     DHLOGI("Register kvStore death listener");
434     kvDataMgr_.RegisterKvStoreServiceDeathRecipient(shared_from_this());
435 }
436 
UnRegisterKvStoreDeathListener()437 void DBAdapter::UnRegisterKvStoreDeathListener()
438 {
439     DHLOGI("UnRegister kvStore death listener");
440     kvDataMgr_.UnRegisterKvStoreServiceDeathRecipient(shared_from_this());
441 }
442 
OnRemoteDied()443 void DBAdapter::OnRemoteDied()
444 {
445     DHLOGI("OnRemoteDied, recover db begin");
446     auto reInitTask = [this] {
447         int32_t times = 0;
448         while (times < DIED_CHECK_MAX_TIMES) {
449             if (DBDiedOpt(times)) {
450                 DHLOGI("ReInit DB success");
451                 break;
452             }
453         }
454     };
455     DHContext::GetInstance().GetEventHandler()->PostTask(reInitTask, "reInitTask", 0);
456     DHLOGI("OnRemoteDied, recover db end");
457 }
458 
DBDiedOpt(int32_t & times)459 bool DBAdapter::DBDiedOpt(int32_t &times)
460 {
461     // init kvStore.
462     if (this->ReInit(this->isAutoSync_) == DH_FWK_SUCCESS) {
463         // register data change listener again.
464         if (this->isAutoSync_) {
465             this->RegisterChangeListener();
466         }
467         this->SyncDBForRecover();
468         DHLOGE("Current times is %{public}d", times);
469         return true;
470     }
471     times++;
472     usleep(DIED_CHECK_INTERVAL);
473     return false;
474 }
475 
DeleteKvStore()476 void DBAdapter::DeleteKvStore()
477 {
478     std::lock_guard<std::mutex> lock(dbAdapterMutex_);
479     DistributedKv::Status status = kvDataMgr_.DeleteKvStore(appId_, storeId_);
480     if (status != DistributedKv::Status::SUCCESS) {
481         DHLOGE("DeleteKvStore error, appId: %{public}s, storeId: %{public}s, status: %{public}d",
482             appId_.appId.c_str(), storeId_.storeId.c_str(), status);
483         return;
484     }
485     DHLOGI("DeleteKvStore success appId: %{public}s", appId_.appId.c_str());
486 }
487 
RemoveDeviceData(const std::string & deviceId)488 int32_t DBAdapter::RemoveDeviceData(const std::string &deviceId)
489 {
490     if (!IsIdLengthValid(deviceId)) {
491         return ERR_DH_FWK_PARA_INVALID;
492     }
493     std::lock_guard<std::mutex> lock(dbAdapterMutex_);
494     if (kvStoragePtr_ == nullptr) {
495         DHLOGE("kvStoragePtr_ is null");
496         return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
497     }
498     DistributedKv::Status status = kvStoragePtr_->RemoveDeviceData(deviceId);
499     if (status != DistributedKv::Status::SUCCESS) {
500         DHLOGE("Remove device data failed, deviceId: %{public}s", GetAnonyString(deviceId).c_str());
501         return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
502     }
503     DHLOGD("Remove device data success, deviceId: %{public}s", GetAnonyString(deviceId).c_str());
504     return DH_FWK_SUCCESS;
505 }
506 
RemoveDataByKey(const std::string & key)507 int32_t DBAdapter::RemoveDataByKey(const std::string &key)
508 {
509     if (!IsIdLengthValid(key)) {
510         return ERR_DH_FWK_PARA_INVALID;
511     }
512     std::lock_guard<std::mutex> lock(dbAdapterMutex_);
513     if (kvStoragePtr_ == nullptr) {
514         DHLOGE("kvStoragePtr_ is null");
515         return ERR_DH_FWK_RESOURCE_KV_STORAGE_POINTER_NULL;
516     }
517     DistributedKv::Key kvKey(key);
518     DistributedKv::Status status = kvStoragePtr_->Delete(kvKey);
519     if (status != DistributedKv::Status::SUCCESS) {
520         DHLOGE("Remove data by key failed");
521         return ERR_DH_FWK_RESOURCE_KV_STORAGE_OPERATION_FAIL;
522     }
523     DHLOGD("Remove data by key success");
524     return DH_FWK_SUCCESS;
525 }
526 
GetEntriesByKeys(const std::vector<std::string> & keys)527 std::vector<DistributedKv::Entry> DBAdapter::GetEntriesByKeys(const std::vector<std::string> &keys)
528 {
529     if (!IsArrayLengthValid(keys)) {
530         return {};
531     }
532     DHLOGI("call");
533     std::vector<DistributedKv::Entry> entries;
534     {
535         std::lock_guard<std::mutex> lock(dbAdapterMutex_);
536         if (kvStoragePtr_ == nullptr) {
537             DHLOGE("kvStoragePtr_ is nullptr!");
538             return entries;
539         }
540         for (const auto &key : keys) {
541             DistributedKv::Key kvKey(key);
542             DistributedKv::Value kvValue;
543             if (kvStoragePtr_->Get(kvKey, kvValue) != DistributedKv::Status::SUCCESS) {
544                 continue;
545             }
546             DistributedKv::Entry entry;
547             entry.key = kvKey;
548             entry.value = kvValue;
549             entries.emplace_back(entry);
550         }
551     }
552     return entries;
553 }
554 
SyncDataByNetworkId(const std::string & networkId)555 bool DBAdapter::SyncDataByNetworkId(const std::string &networkId)
556 {
557     DHLOGI("Try initiative sync data by networId: %{public}s", GetAnonyString(networkId).c_str());
558     std::lock_guard<std::mutex> lock(dbAdapterMutex_);
559     if (kvStoragePtr_ == nullptr) {
560         DHLOGE("kvStoragePtr_ is nullptr!");
561         return false;
562     }
563     std::vector<std::string> networkIdVec;
564     networkIdVec.push_back(networkId);
565     DistributedKv::Status status = kvStoragePtr_->Sync(networkIdVec, DistributedKv::SyncMode::PUSH_PULL);
566     if (status != DistributedKv::Status::SUCCESS) {
567         DHLOGE("initiative sync data failed");
568         return false;
569     }
570     return true;
571 }
572 
ClearDataByPrefix(const std::string & prefix)573 bool DBAdapter::ClearDataByPrefix(const std::string &prefix)
574 {
575     DHLOGI("Clear data by prefix: %{public}s.", GetAnonyString(prefix).c_str());
576     std::lock_guard<std::mutex> lock(dbAdapterMutex_);
577     if (kvStoragePtr_ == nullptr) {
578         DHLOGE("kvStoragePtr_ is nullptr!");
579         return false;
580     }
581     std::string keyPrefix = Sha256(prefix);
582     DistributedKv::Key allEntryKeyPrefix(keyPrefix);
583     std::vector<DistributedKv::Entry> peerEntries;
584     DistributedKv::Status status = kvStoragePtr_->GetEntries(allEntryKeyPrefix, peerEntries);
585     if (status != DistributedKv::Status::SUCCESS || peerEntries.size() == 0) {
586         DHLOGE("GetEntries error: %{public}d, or peerEntries is empty", status);
587         return false;
588     }
589     std::vector<DistributedKv::Key> peerkeys;
590     for (const auto &entry : peerEntries) {
591         peerkeys.push_back(entry.key);
592     }
593 
594     if (kvStoragePtr_->DeleteBatch(peerkeys) != DistributedKv::Status::SUCCESS) {
595         DHLOGE("DeleteBatch failed, error: %{public}d", status);
596         return false;
597     }
598     return true;
599 }
600 } // namespace DistributedHardware
601 } // namespace OHOS
602