1 /*
2 * Copyright (c) 2023 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 #define LOG_TAG "RuntimeStore"
16
17 #include "runtime_store.h"
18
19 #include "data_handler.h"
20 #include "log_print.h"
21 #include "ipc_skeleton.h"
22 #include "unified_data_helper.h"
23 #include "udmf_radar_reporter.h"
24 #include "account/account_delegate.h"
25 #include "metadata/meta_data_manager.h"
26 #include "metadata/appid_meta_data.h"
27 #include "metadata/store_meta_data.h"
28 #include "device_manager_adapter.h"
29 #include "bootstrap.h"
30 #include "directory/directory_manager.h"
31 #include "utils/anonymous.h"
32 #include "preprocess_utils.h"
33
34 namespace OHOS {
35 namespace UDMF {
36 using namespace RadarReporter;
37 using namespace DistributedDB;
38 using namespace OHOS::DistributedData;
39 using Anonymous = OHOS::DistributedData::Anonymous;
40 using DmAdapter = OHOS::DistributedData::DeviceManagerAdapter;
41 constexpr const char *SUMMARY_SUFIX = "#summary";
42
RuntimeStore(const std::string & storeId)43 RuntimeStore::RuntimeStore(const std::string &storeId) : storeId_(storeId)
44 {
45 UpdateTime();
46 ZLOGD("Construct runtimeStore: %{public}s.", Anonymous::Change(storeId_).c_str());
47 }
48
~RuntimeStore()49 RuntimeStore::~RuntimeStore()
50 {
51 ZLOGD("Destruct runtimeStore: %{public}s.", Anonymous::Change(storeId_).c_str());
52 }
53
PutLocal(const std::string & key,const std::string & value)54 Status RuntimeStore::PutLocal(const std::string &key, const std::string &value)
55 {
56 UpdateTime();
57 std::vector<uint8_t> keyBytes = {key.begin(), key.end()};
58 std::vector<uint8_t> valueBytes = {value.begin(), value.end()};
59
60 auto status = kvStore_->PutLocal(keyBytes, valueBytes);
61 if (status != DBStatus::OK) {
62 ZLOGE("KvStore PutLocal failed, status: %{public}d.", status);
63 return MarkWhenCorrupted(status);
64 }
65 return E_OK;
66 }
67
GetLocal(const std::string & key,std::string & value)68 Status RuntimeStore::GetLocal(const std::string &key, std::string &value)
69 {
70 UpdateTime();
71 std::vector<uint8_t> valueBytes;
72 std::vector<uint8_t> keyBytes = {key.begin(), key.end()};
73 DBStatus status = kvStore_->GetLocal(keyBytes, valueBytes);
74 if (status != DBStatus::OK && status != DBStatus::NOT_FOUND) {
75 ZLOGE("GetLocal entry failed, key: %{public}s.", key.c_str());
76 return MarkWhenCorrupted(status);
77 }
78 if (valueBytes.empty()) {
79 ZLOGW("GetLocal entry is empty, key: %{public}s", key.c_str());
80 return E_NOT_FOUND;
81 }
82 value = {valueBytes.begin(), valueBytes.end()};
83 return E_OK;
84 }
85
DeleteLocal(const std::string & key)86 Status RuntimeStore::DeleteLocal(const std::string &key)
87 {
88 UpdateTime();
89 std::vector<uint8_t> valueBytes;
90 std::vector<uint8_t> keyBytes = {key.begin(), key.end()};
91 DBStatus status = kvStore_->DeleteLocal(keyBytes);
92 if (status != DBStatus::OK && status != DBStatus::NOT_FOUND) {
93 ZLOGE("DeleteLocal failed, key: %{public}s.", key.c_str());
94 return MarkWhenCorrupted(status);
95 }
96 return E_OK;
97 }
98
Put(const UnifiedData & unifiedData)99 Status RuntimeStore::Put(const UnifiedData &unifiedData)
100 {
101 UpdateTime();
102 std::vector<Entry> entries;
103 std::string intention = unifiedData.GetRuntime()->key.intention;
104 if (intention == UD_INTENTION_MAP.at(UD_INTENTION_DRAG)) {
105 PutSummary(unifiedData, entries);
106 }
107 auto status = DataHandler::MarshalToEntries(unifiedData, entries);
108 if (status != E_OK) {
109 return status;
110 }
111 return PutEntries(entries);
112 }
113
Get(const std::string & key,UnifiedData & unifiedData)114 Status RuntimeStore::Get(const std::string &key, UnifiedData &unifiedData)
115 {
116 UpdateTime();
117 std::vector<Entry> entries;
118 auto status = GetEntries(UnifiedKey(key).GetKeyCommonPrefix(), entries);
119 if (status != E_OK) {
120 ZLOGE("GetEntries failed, dataPrefix: %{public}s.", key.c_str());
121 return status;
122 }
123 if (entries.empty()) {
124 ZLOGW("entries is empty, dataPrefix: %{public}s", key.c_str());
125 return E_NOT_FOUND;
126 }
127 return DataHandler::UnmarshalEntries(key, entries, unifiedData);
128 }
129
PutSummary(const UnifiedData & data,std::vector<Entry> & entries)130 Status RuntimeStore::PutSummary(const UnifiedData &data, std::vector<Entry> &entries)
131 {
132 UpdateTime();
133 UDDetails details {};
134 Summary summary;
135 if (PreProcessUtils::GetDetailsFromUData(data, details)) {
136 PreProcessUtils::GetSummaryFromDetails(details, summary);
137 } else {
138 UnifiedDataHelper::GetSummary(data, summary);
139 }
140
141 auto propertyKey = data.GetRuntime()->key.GetKeyCommonPrefix();
142 Value value;
143 auto status = DataHandler::MarshalToEntries(summary, value, TAG::TAG_SUMMARY);
144 if (status != E_OK) {
145 ZLOGE("Marshal summary failed, key: %{public}s, status:%{public}d", propertyKey.c_str(), status);
146 return status;
147 }
148 auto summaryKey = propertyKey + SUMMARY_SUFIX;
149 entries.push_back({{summaryKey.begin(), summaryKey.end()}, value});
150 return E_OK;
151 }
152
PutSummary(UnifiedKey & key,const Summary & summary)153 Status RuntimeStore::PutSummary(UnifiedKey &key, const Summary &summary)
154 {
155 auto propertyKey = key.GetKeyCommonPrefix();
156 Value value;
157 auto status = DataHandler::MarshalToEntries(summary, value, TAG::TAG_SUMMARY);
158 if (status != E_OK) {
159 ZLOGE("Marshal summary failed, key: %{public}s, status:%{public}d", propertyKey.c_str(), status);
160 return status;
161 }
162 auto summaryKey = propertyKey + SUMMARY_SUFIX;
163 std::vector<Entry> entries{{{summaryKey.begin(), summaryKey.end()}, value}};
164 return PutEntries(std::move(entries));
165 }
166
GetSummary(UnifiedKey & key,Summary & summary)167 Status RuntimeStore::GetSummary(UnifiedKey &key, Summary &summary)
168 {
169 UpdateTime();
170 Value value;
171 auto summaryKey = key.GetKeyCommonPrefix() + SUMMARY_SUFIX;
172 auto res = kvStore_->Get({summaryKey.begin(), summaryKey.end()}, value);
173 if (res != OK || value.empty()) {
174 ZLOGW("Get stored summary failed, key: %{public}s, status:%{public}d", summaryKey.c_str(), res);
175 UnifiedData unifiedData;
176 auto udKey = key.GetUnifiedKey();
177 auto status = Get(udKey, unifiedData);
178 if (status != E_OK) {
179 ZLOGE("Get unified data failed, key: %{public}s", udKey.c_str());
180 return status;
181 }
182 UDDetails details {};
183 if (PreProcessUtils::GetDetailsFromUData(unifiedData, details)) {
184 return PreProcessUtils::GetSummaryFromDetails(details, summary);
185 }
186 UnifiedDataHelper::GetSummary(unifiedData, summary);
187 return E_OK;
188 }
189 auto status = DataHandler::UnmarshalEntries(value, summary, TAG::TAG_SUMMARY);
190 if (status != E_OK) {
191 ZLOGE("Unmarshal summary failed, key: %{public}s, status:%{public}d", summaryKey.c_str(), status);
192 return status;
193 }
194 return E_OK;
195 }
196
PutRuntime(const std::string & key,const Runtime & runtime)197 Status RuntimeStore::PutRuntime(const std::string &key, const Runtime &runtime)
198 {
199 UpdateTime();
200 Value value;
201 auto status = DataHandler::MarshalToEntries(runtime, value, TAG::TAG_RUNTIME);
202 if (status != E_OK) {
203 ZLOGE("Marshal runtime failed, key: %{public}s, status:%{public}d", key.c_str(), status);
204 return status;
205 }
206 auto res = kvStore_->Put({key.begin(), key.end()}, value);
207 if (res != OK) {
208 ZLOGE("Put failed, key:%{public}s, status:%{public}d", key.c_str(), res);
209 return MarkWhenCorrupted(res);
210 }
211 return E_OK;
212 }
213
GetRuntime(const std::string & key,Runtime & runtime)214 Status RuntimeStore::GetRuntime(const std::string &key, Runtime &runtime)
215 {
216 UpdateTime();
217 Value value;
218 auto res = kvStore_->Get({key.begin(), key.end()}, value);
219 if (res == NOT_FOUND) {
220 ZLOGW("Runtime not found, key: %{public}s", key.c_str());
221 return E_NOT_FOUND;
222 }
223 if (res != OK || value.empty()) {
224 ZLOGE("Get failed, key: %{public}s, status:%{public}d", key.c_str(), res);
225 return MarkWhenCorrupted(res);
226 }
227 auto status = DataHandler::UnmarshalEntries(value, runtime, TAG::TAG_RUNTIME);
228 if (status != E_OK) {
229 ZLOGE("Unmarshal runtime failed, key: %{public}s, status:%{public}d", key.c_str(), status);
230 return status;
231 }
232 return E_OK;
233 }
234
Update(const UnifiedData & unifiedData)235 Status RuntimeStore::Update(const UnifiedData &unifiedData)
236 {
237 std::string key = unifiedData.GetRuntime()->key.key;
238 auto status = Delete(UnifiedKey(key).GetKeyCommonPrefix());
239 if (status != E_OK) {
240 UpdateTime();
241 ZLOGE("Delete unified data failed, dataPrefix: %{public}s.", key.c_str());
242 return status;
243 }
244 status = Put(unifiedData);
245 if (status != E_OK) {
246 ZLOGE("Update unified data failed, dataPrefix: %{public}s.", key.c_str());
247 return status;
248 }
249 return E_OK;
250 }
251
Delete(const std::string & key)252 Status RuntimeStore::Delete(const std::string &key)
253 {
254 std::vector<Entry> entries;
255 auto status = GetEntries(key, entries);
256 if (status != E_OK) {
257 ZLOGE("GetEntries failed, dataPrefix: %{public}s.", key.c_str());
258 return status;
259 }
260 if (entries.empty()) {
261 ZLOGD("entries is empty.");
262 return E_OK;
263 }
264 std::vector<Key> keys;
265 for (const auto &entry : entries) {
266 keys.push_back(entry.key);
267 }
268 return DeleteEntries(keys);
269 }
270
DeleteBatch(const std::vector<std::string> & unifiedKeys)271 Status RuntimeStore::DeleteBatch(const std::vector<std::string> &unifiedKeys)
272 {
273 UpdateTime();
274 ZLOGD("called!");
275 if (unifiedKeys.empty()) {
276 ZLOGD("No need to delete!");
277 return E_OK;
278 }
279 for (const std::string &unifiedKey : unifiedKeys) {
280 if (Delete(unifiedKey) != E_OK) {
281 ZLOGE("Delete failed, key: %{public}s.", unifiedKey.c_str());
282 return E_DB_ERROR;
283 }
284 }
285 return E_OK;
286 }
287
Sync(const std::vector<std::string> & devices)288 Status RuntimeStore::Sync(const std::vector<std::string> &devices)
289 {
290 UpdateTime();
291 if (devices.empty()) {
292 ZLOGE("devices empty, no need sync.");
293 return E_INVALID_PARAMETERS;
294 }
295 std::vector<std::string> syncDevices = DmAdapter::ToUUID(devices);
296 auto onComplete = [this](const std::map<std::string, DBStatus> &devsSyncStatus) {
297 DBStatus dbStatus = DBStatus::OK;
298 for (const auto &[originDeviceId, status] : devsSyncStatus) { // only one device.
299 if (status != DBStatus::OK) {
300 dbStatus = status;
301 break;
302 }
303 }
304 if (dbStatus != DBStatus::OK) {
305 RadarReporterAdapter::ReportFail(std::string(__FUNCTION__),
306 BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::FAILED, dbStatus, BizState::DFX_END);
307 } else {
308 RadarReporterAdapter::ReportNormal(std::string(__FUNCTION__),
309 BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::SUCCESS, BizState::DFX_END);
310 }
311
312 ZLOGI("sync complete, %{public}s, status:%{public}d.", Anonymous::Change(storeId_).c_str(), dbStatus);
313 };
314 DBStatus status = kvStore_->Sync(syncDevices, SyncMode::SYNC_MODE_PULL_ONLY, onComplete);
315 if (status != DBStatus::OK) {
316 ZLOGE("Sync kvStore failed, status: %{public}d.", status);
317 return E_DB_ERROR;
318 }
319 return E_OK;
320 }
321
Sync(const std::vector<std::string> & devices,ProcessCallback callback)322 Status RuntimeStore::Sync(const std::vector<std::string> &devices, ProcessCallback callback)
323 {
324 UpdateTime();
325 if (devices.empty()) {
326 ZLOGE("devices empty, no need sync.");
327 return E_INVALID_PARAMETERS;
328 }
329 std::vector<std::string> syncDevices = DmAdapter::ToUUID(devices);
330 DevNameMap deviceNameMap;
331 for (const auto &device : devices) {
332 std::string deviceUuid = DmAdapter::GetInstance().ToUUID(device);
333 std::string deviceName = DmAdapter::GetInstance().GetDeviceInfo(device).deviceName;
334 deviceNameMap.emplace(deviceUuid, deviceName);
335 }
336 auto progressCallback = [this, callback, deviceNameMap](const DevSyncProcessMap &processMap) {
337 this->NotifySyncProcss(processMap, callback, deviceNameMap);
338 };
339
340 DistributedDB::DeviceSyncOption option;
341 option.devices = syncDevices;
342 option.isWait = false;
343 DBStatus status = kvStore_->Sync(option, progressCallback);
344 if (status != DBStatus::OK) {
345 ZLOGE("Sync kvStore failed, status: %{public}d.", status);
346 return E_DB_ERROR;
347 }
348 return E_OK;
349 }
350
NotifySyncProcss(const DevSyncProcessMap & processMap,ProcessCallback callback,const DevNameMap & deviceNameMap)351 void RuntimeStore::NotifySyncProcss(const DevSyncProcessMap &processMap, ProcessCallback callback,
352 const DevNameMap &deviceNameMap)
353 {
354 AsyncProcessInfo processInfo;
355 for (const auto &[originDeviceId, syncProcess] : processMap) { // only one device
356 processInfo.srcDevName = deviceNameMap.at(originDeviceId);
357 processInfo.syncId = syncProcess.syncId;
358 processInfo.syncFinished = syncProcess.pullInfo.finishedCount;
359 processInfo.syncTotal = syncProcess.pullInfo.total;
360 if (syncProcess.process != DistributedDB::ProcessStatus::FINISHED) {
361 processInfo.syncStatus = ASYNC_RUNNING;
362 continue;
363 }
364 if (syncProcess.errCode == DBStatus::OK) {
365 processInfo.syncStatus = ASYNC_SUCCESS;
366 RadarReporterAdapter::ReportNormal(std::string(__FUNCTION__),
367 BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::SUCCESS, BizState::DFX_END);
368 } else {
369 processInfo.syncStatus = ASYNC_FAILURE;
370 RadarReporterAdapter::ReportFail(std::string(__FUNCTION__),
371 BizScene::SYNC_DATA, SyncDataStage::SYNC_END, StageRes::FAILED, syncProcess.errCode, BizState::DFX_END);
372 }
373 }
374 callback(processInfo);
375 }
376
Clear()377 Status RuntimeStore::Clear()
378 {
379 UpdateTime();
380 return Delete(DATA_PREFIX);
381 }
382
GetBatchData(const std::string & dataPrefix,std::vector<UnifiedData> & unifiedDataSet)383 Status RuntimeStore::GetBatchData(const std::string &dataPrefix, std::vector<UnifiedData> &unifiedDataSet)
384 {
385 UpdateTime();
386 std::vector<Entry> entries;
387 auto status = GetEntries(dataPrefix, entries);
388 if (status != E_OK) {
389 ZLOGE("GetEntries failed, dataPrefix: %{public}s.", dataPrefix.c_str());
390 return status;
391 }
392 if (entries.empty()) {
393 ZLOGD("entries is empty.");
394 return E_OK;
395 }
396 std::vector<std::string> keySet;
397 for (const auto &entry : entries) {
398 std::string keyStr = {entry.key.begin(), entry.key.end()};
399 if (std::count(keyStr.begin(), keyStr.end(), '/') == SLASH_COUNT_IN_KEY &&
400 std::count(keyStr.begin(), keyStr.end(), '#') == 0) {
401 keySet.emplace_back(keyStr);
402 }
403 }
404
405 for (const std::string &key : keySet) {
406 UnifiedData data;
407 if (DataHandler::UnmarshalEntries(key, entries, data) != E_OK) {
408 return E_READ_PARCEL_ERROR;
409 }
410 unifiedDataSet.emplace_back(data);
411 }
412 return E_OK;
413 }
414
Init()415 bool RuntimeStore::Init()
416 {
417 if (!SaveMetaData()) { // get keyinfo about create db fail.
418 ZLOGW("Save meta data fail.");
419 return false;
420 }
421 DistributedDB::KvStoreNbDelegate::Option option;
422 option.createIfNecessary = true;
423 option.isMemoryDb = false;
424 option.createDirByStoreIdOnly = true;
425 option.isEncryptedDb = false;
426 option.isNeedRmCorruptedDb = true;
427 option.syncDualTupleMode = true;
428 option.secOption = {DistributedKv::SecurityLevel::S1, DistributedDB::ECE};
429 DistributedDB::KvStoreNbDelegate *delegate = nullptr;
430 DBStatus status = DBStatus::NOT_SUPPORT;
431 delegateManager_->GetKvStore(storeId_, option,
432 [&delegate, &status](DBStatus dbStatus, KvStoreNbDelegate *nbDelegate) {
433 delegate = nbDelegate;
434 status = dbStatus;
435 });
436 if (status != DBStatus::OK) {
437 ZLOGE("GetKvStore fail, status: %{public}d.", static_cast<int>(status));
438 if (status == INVALID_PASSWD_OR_CORRUPTED_DB) {
439 status = delegateManager_->DeleteKvStore(storeId_);
440 if (status != DBStatus::OK) {
441 ZLOGE("DeleteKvStore fail, status: %{public}d.", static_cast<int>(status));
442 }
443 }
444 return false;
445 }
446 auto release = [this](KvStoreNbDelegate *delegate) {
447 ZLOGI("Release runtime kvStore, db is corrupted: %{public}d.", isCorrupted_);
448 ReleaseStore(delegate);
449 };
450 kvStore_ = std::shared_ptr<KvStoreNbDelegate>(delegate, release);
451 uint32_t pragmData = 16 * 1024 * 1024;
452 PragmaData input = static_cast<PragmaData>(&pragmData);
453 kvStore_->Pragma(SET_MAX_VALUE_SIZE, input);
454 return true;
455 }
456
BuildMetaDataParam(DistributedData::StoreMetaData & metaData)457 bool RuntimeStore::BuildMetaDataParam(DistributedData::StoreMetaData &metaData)
458 {
459 auto localDeviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
460 if (localDeviceId.empty()) {
461 ZLOGE("failed to get local device id");
462 return false;
463 }
464
465 uint32_t token = IPCSkeleton::GetSelfTokenID();
466 const std::string userId = std::to_string(DistributedData::AccountDelegate::GetInstance()->GetUserByToken(token));
467 metaData.appType = "harmony";
468 metaData.deviceId = localDeviceId;
469 metaData.storeId = storeId_;
470 metaData.isAutoSync = false;
471 metaData.isBackup = false;
472 metaData.isEncrypt = false;
473 metaData.bundleName = DistributedData::Bootstrap::GetInstance().GetProcessLabel();
474 metaData.appId = DistributedData::Bootstrap::GetInstance().GetProcessLabel();
475 metaData.user = userId;
476 metaData.account = DistributedData::AccountDelegate::GetInstance()->GetCurrentAccountId();
477 metaData.tokenId = token;
478 metaData.securityLevel = DistributedKv::SecurityLevel::S1;
479 metaData.area = DistributedKv::Area::EL2;
480 metaData.uid = static_cast<int32_t>(getuid());
481 metaData.storeType = DistributedKv::KvStoreType::SINGLE_VERSION;
482 metaData.dataType = DistributedKv::DataType::TYPE_DYNAMICAL;
483 metaData.authType = DistributedKv::AuthType::IDENTICAL_ACCOUNT;
484
485 return true;
486 }
487
SaveMetaData()488 bool RuntimeStore::SaveMetaData()
489 {
490 DistributedData::StoreMetaData saveMeta;
491 if (!BuildMetaDataParam(saveMeta)) {
492 return false;
493 }
494
495 int foregroundUserId = 0;
496 bool ret = DistributedData::AccountDelegate::GetInstance()->QueryForegroundUserId(foregroundUserId);
497 if (!ret) {
498 ZLOGE("QueryForegroundUserId failed.");
499 return false;
500 }
501 saveMeta.user = std::to_string(foregroundUserId);
502 saveMeta.dataDir = DistributedData::DirectoryManager::GetInstance().GetStorePath(saveMeta);
503 if (!DistributedData::DirectoryManager::GetInstance().CreateDirectory(saveMeta.dataDir)) {
504 ZLOGE("Create directory error, dataDir: %{public}s.", Anonymous::Change(saveMeta.dataDir).c_str());
505 return false;
506 }
507
508 SetDelegateManager(saveMeta.dataDir, saveMeta.appId, saveMeta.user);
509
510 DistributedData::StoreMetaData loadLocal;
511 DistributedData::StoreMetaData syncMeta;
512 if (DistributedData::MetaDataManager::GetInstance().LoadMeta(saveMeta.GetKey(), loadLocal, true) &&
513 DistributedData::MetaDataManager::GetInstance().LoadMeta(saveMeta.GetKeyLocalWithoutPath(), syncMeta, false)) {
514 if (loadLocal == saveMeta && syncMeta == saveMeta) {
515 ZLOGD("Meta data is already saved.");
516 return true;
517 }
518 }
519
520 auto saved = DistributedData::MetaDataManager::GetInstance().SaveMeta(saveMeta.GetKeyWithoutPath(), saveMeta) &&
521 DistributedData::MetaDataManager::GetInstance().SaveMeta(saveMeta.GetKey(), saveMeta, true);
522 if (!saved) {
523 ZLOGE("SaveMeta failed, saveMeta.key:%{public}s", saveMeta.GetKey().c_str());
524 return false;
525 }
526 DistributedData::AppIDMetaData appIdMeta;
527 appIdMeta.bundleName = saveMeta.bundleName;
528 appIdMeta.appId = saveMeta.appId;
529 saved = DistributedData::MetaDataManager::GetInstance().SaveMeta(appIdMeta.GetKey(), appIdMeta, true);
530 if (!saved) {
531 ZLOGE("Save appIdMeta failed, appIdMeta.key:%{public}s", appIdMeta.GetKey().c_str());
532 return false;
533 }
534 return true;
535 }
536
ReleaseStore(DistributedDB::KvStoreNbDelegate * delegate)537 void RuntimeStore::ReleaseStore(DistributedDB::KvStoreNbDelegate *delegate)
538 {
539 if (delegate == nullptr) {
540 return;
541 }
542 auto retStatus = delegateManager_->CloseKvStore(delegate);
543 if (retStatus != DBStatus::OK) {
544 ZLOGE("CloseKvStore fail, status: %{public}d.", static_cast<int>(retStatus));
545 return;
546 }
547 if (isCorrupted_) {
548 retStatus = delegateManager_->DeleteKvStore(storeId_);
549 if (retStatus != DBStatus::OK) {
550 ZLOGE("DeleteKvStore fail, status: %{public}d.", static_cast<int>(retStatus));
551 }
552 }
553 }
554
SetDelegateManager(const std::string & dataDir,const std::string & appId,const std::string & userId)555 void RuntimeStore::SetDelegateManager(const std::string &dataDir, const std::string &appId, const std::string &userId)
556 {
557 delegateManager_ = std::make_shared<DistributedDB::KvStoreDelegateManager>(appId, userId);
558 DistributedDB::KvStoreConfig kvStoreConfig { dataDir };
559 auto status = delegateManager_->SetKvStoreConfig(kvStoreConfig);
560 if (status != DBStatus::OK) {
561 ZLOGE("SetKvStoreConfig failed, status: %{public}d.", status);
562 }
563 }
564
GetEntries(const std::string & dataPrefix,std::vector<Entry> & entries)565 Status RuntimeStore::GetEntries(const std::string &dataPrefix, std::vector<Entry> &entries)
566 {
567 Query dbQuery = Query::Select();
568 std::vector<uint8_t> prefix = {dataPrefix.begin(), dataPrefix.end()};
569 dbQuery.PrefixKey(prefix);
570 dbQuery.OrderByWriteTime(true);
571 DBStatus status = kvStore_->GetEntries(dbQuery, entries);
572 if (status != DBStatus::OK && status != DBStatus::NOT_FOUND) {
573 ZLOGE("KvStore getEntries failed, status: %{public}d.", static_cast<int>(status));
574 return MarkWhenCorrupted(status);
575 }
576 return E_OK;
577 }
578
PutEntries(const std::vector<Entry> & entries)579 Status RuntimeStore::PutEntries(const std::vector<Entry> &entries)
580 {
581 DBStatus status = kvStore_->PutBatch(entries);
582 if (status != DBStatus::OK) {
583 ZLOGE("putBatch failed, status: %{public}d.", status);
584 return MarkWhenCorrupted(status);
585 }
586 return E_OK;
587 }
588
DeleteEntries(const std::vector<Key> & keys)589 Status RuntimeStore::DeleteEntries(const std::vector<Key> &keys)
590 {
591 DBStatus status = kvStore_->DeleteBatch(keys);
592 if (status != DBStatus::OK) {
593 ZLOGE("deleteBatch failed, status: %{public}d.", status);
594 return MarkWhenCorrupted(status);
595 }
596 return E_OK;
597 }
598
MarkWhenCorrupted(DistributedDB::DBStatus status)599 Status RuntimeStore::MarkWhenCorrupted(DistributedDB::DBStatus status)
600 {
601 if (status == INVALID_PASSWD_OR_CORRUPTED_DB) {
602 ZLOGE("Kv database corrupted");
603 isCorrupted_ = true;
604 return E_DB_CORRUPTED;
605 }
606 return E_DB_ERROR;
607 }
608 } // namespace UDMF
609 } // namespace OHOS