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