• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021 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 "KvStoreMetaManager"
16 
17 #include "kvstore_meta_manager.h"
18 
19 #include <ipc_skeleton.h>
20 #include <thread>
21 #include <unistd.h>
22 
23 #include "account_delegate.h"
24 #include "bootstrap.h"
25 #include "cloud/change_event.h"
26 #include "communication_provider.h"
27 #include "crypto_manager.h"
28 #include "device_manager_adapter.h"
29 #include "device_matrix.h"
30 #include "directory/directory_manager.h"
31 #include "eventcenter/event_center.h"
32 #include "kvstore_data_service.h"
33 #include "kv_radar_reporter.h"
34 #include "log_print.h"
35 #include "matrix_event.h"
36 #include "metadata/meta_data_manager.h"
37 #include "metadata/store_meta_data_local.h"
38 #include "metadata/version_meta_data.h"
39 #include "runtime_config.h"
40 #include "safe_block_queue.h"
41 #include "store/general_store.h"
42 #include "store/store_info.h"
43 #include "utils/anonymous.h"
44 #include "utils/block_integer.h"
45 #include "utils/corrupt_reporter.h"
46 #include "utils/crypto.h"
47 #include "utils/ref_count.h"
48 #include "utils/converter.h"
49 
50 namespace OHOS {
51 namespace DistributedKv {
52 using Commu = AppDistributedKv::CommunicationProvider;
53 using DmAdapter = DistributedData::DeviceManagerAdapter;
54 using namespace std::chrono;
55 using namespace OHOS::DistributedData;
56 using namespace DistributedDB;
57 using namespace OHOS::AppDistributedKv;
58 
59 KvStoreMetaManager::MetaDeviceChangeListenerImpl KvStoreMetaManager::listener_;
60 KvStoreMetaManager::DBInfoDeviceChangeListenerImpl KvStoreMetaManager::dbInfoListener_;
61 
KvStoreMetaManager()62 KvStoreMetaManager::KvStoreMetaManager()
63     : metaDelegate_(nullptr), metaDBDirectory_(DirectoryManager::GetInstance().GetMetaStorePath()),
64       label_(Bootstrap::GetInstance().GetProcessLabel()),
65       delegateManager_(Bootstrap::GetInstance().GetProcessLabel(), "default")
66 {
67     ZLOGI("begin.");
68 }
69 
~KvStoreMetaManager()70 KvStoreMetaManager::~KvStoreMetaManager()
71 {
72     if (delaySyncTaskId_ != ExecutorPool::INVALID_TASK_ID) {
73         executors_->Remove(delaySyncTaskId_);
74         delaySyncTaskId_ = ExecutorPool::INVALID_TASK_ID;
75     }
76 }
77 
GetInstance()78 KvStoreMetaManager &KvStoreMetaManager::GetInstance()
79 {
80     static KvStoreMetaManager instance;
81     return instance;
82 }
83 
SubscribeMeta(const std::string & keyPrefix,const ChangeObserver & observer)84 void KvStoreMetaManager::SubscribeMeta(const std::string &keyPrefix, const ChangeObserver &observer)
85 {
86     metaObserver_.handlerMap_[keyPrefix] = observer;
87 }
88 
InitMetaListener()89 void KvStoreMetaManager::InitMetaListener()
90 {
91     InitMetaData();
92     auto status = DmAdapter::GetInstance().StartWatchDeviceChange(&listener_, { "metaMgr" });
93     if (status != AppDistributedKv::Status::SUCCESS) {
94         ZLOGW("register metaMgr failed: %{public}d.", status);
95         return;
96     }
97     SubscribeMetaKvStore();
98     InitBroadcast();
99     NotifyAllAutoSyncDBInfo();
100 }
101 
InitBroadcast()102 void KvStoreMetaManager::InitBroadcast()
103 {
104     auto pipe = Bootstrap::GetInstance().GetProcessLabel() + "-" + "default";
105     auto result = Commu::GetInstance().ListenBroadcastMsg({ pipe },
106         [](const std::string &device, const AppDistributedKv::LevelInfo &levelInfo) {
107             DistributedData::DeviceMatrix::DataLevel level;
108             level.dynamic = levelInfo.dynamic;
109             level.statics = levelInfo.statics;
110             level.switches = levelInfo.switches;
111             level.switchesLen = levelInfo.switchesLen;
112             DeviceMatrix::GetInstance().OnBroadcast(device, std::move(level));
113         });
114 
115     EventCenter::GetInstance().Subscribe(DeviceMatrix::MATRIX_BROADCAST, [pipe](const Event &event) {
116         auto &matrixEvent = static_cast<const MatrixEvent &>(event);
117         auto matrixData = matrixEvent.GetMatrixData();
118         AppDistributedKv::LevelInfo level;
119         level.dynamic = matrixData.dynamic;
120         level.statics = matrixData.statics;
121         level.switches = matrixData.switches;
122         level.switchesLen = matrixData.switchesLen;
123         Commu::GetInstance().Broadcast({ pipe }, std::move(level));
124     });
125 
126     ZLOGI("observer matrix broadcast %{public}d.", result);
127 }
128 
InitMetaData()129 void KvStoreMetaManager::InitMetaData()
130 {
131     ZLOGI("start.");
132     auto metaDelegate = GetMetaKvStore();
133     if (metaDelegate == nullptr) {
134         ZLOGI("get meta failed.");
135         return;
136     }
137     auto uid = getuid();
138     auto tokenId = IPCSkeleton::GetCallingTokenID();
139     const std::string accountId = AccountDelegate::GetInstance()->GetCurrentAccountId();
140     auto userId = AccountDelegate::GetInstance()->GetUserByToken(tokenId);
141     StoreMetaData data;
142     data.appId = label_;
143     data.appType = "default";
144     data.bundleName = label_;
145     data.dataDir = metaDBDirectory_;
146     data.user = std::to_string(userId);
147     data.deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
148     data.isAutoSync = false;
149     data.isBackup = false;
150     data.isEncrypt = false;
151     data.isNeedCompress = true;
152     data.storeType = KvStoreType::SINGLE_VERSION;
153     data.dataType = DataType::TYPE_DYNAMICAL;
154     data.schema = "";
155     data.storeId = Bootstrap::GetInstance().GetMetaDBName();
156     data.account = accountId;
157     data.uid = static_cast<int32_t>(uid);
158     data.version = META_STORE_VERSION;
159     data.securityLevel = SecurityLevel::S1;
160     data.area = EL1;
161     data.tokenId = tokenId;
162     StoreMetaDataLocal localData;
163     localData.isAutoSync = false;
164     localData.isBackup = false;
165     localData.isEncrypt = false;
166     localData.dataDir = metaDBDirectory_;
167     localData.schema = "";
168     localData.isPublic = true;
169     if (!(MetaDataManager::GetInstance().SaveMeta(data.GetKey(), data) &&
170         MetaDataManager::GetInstance().SaveMeta(data.GetKey(), data, true) &&
171         MetaDataManager::GetInstance().SaveMeta(data.GetKeyLocal(), localData, true))) {
172         ZLOGE("save meta fail");
173     }
174     UpdateMetaData();
175     SetCloudSyncer();
176     ZLOGI("end.");
177 }
178 
UpdateMetaData()179 void KvStoreMetaManager::UpdateMetaData()
180 {
181     VersionMetaData versionMeta;
182     if (!MetaDataManager::GetInstance().LoadMeta(versionMeta.GetKey(), versionMeta, true)
183         || versionMeta.version < META_VERSION) {
184         std::vector<StoreMetaData> metaDataList;
185         std::string prefix = StoreMetaData::GetPrefix({ DmAdapter::GetInstance().GetLocalDevice().uuid });
186         MetaDataManager::GetInstance().LoadMeta(prefix, metaDataList);
187         for (auto metaData : metaDataList) {
188             MetaDataManager::GetInstance().SaveMeta(metaData.GetKey(), metaData, true);
189             if (CheckerManager::GetInstance().IsDistrust(Converter::ConvertToStoreInfo(metaData)) ||
190                 (metaData.storeType >= StoreMetaData::StoreType::STORE_RELATIONAL_BEGIN
191                  && metaData.storeType <= StoreMetaData::StoreType::STORE_RELATIONAL_END)) {
192                 MetaDataManager::GetInstance().DelMeta(metaData.GetKey());
193             }
194         }
195     }
196     if (versionMeta.version != VersionMetaData::CURRENT_VERSION) {
197         versionMeta.version = VersionMetaData::CURRENT_VERSION;
198         MetaDataManager::GetInstance().SaveMeta(versionMeta.GetKey(), versionMeta, true);
199     }
200 }
201 
InitMetaParameter()202 void KvStoreMetaManager::InitMetaParameter()
203 {
204     ZLOGI("start.");
205     executors_->Execute(GetTask(0));
206     DistributedDB::KvStoreConfig kvStoreConfig{ metaDBDirectory_ };
207     delegateManager_.SetKvStoreConfig(kvStoreConfig);
208 }
209 
GetTask(uint32_t retry)210 ExecutorPool::Task KvStoreMetaManager::GetTask(uint32_t retry)
211 {
212     return [this, retry] {
213         auto status = CryptoManager::GetInstance().CheckRootKey();
214         if (status == CryptoManager::ErrCode::SUCCESS) {
215             ZLOGI("root key exist.");
216             return;
217         }
218         if (status == CryptoManager::ErrCode::NOT_EXIST &&
219             CryptoManager::GetInstance().GenerateRootKey() == CryptoManager::ErrCode::SUCCESS) {
220             ZLOGI("GenerateRootKey success.");
221             return;
222         }
223         ZLOGW("GenerateRootKey failed, retry times:%{public}d.", static_cast<int>(retry));
224         if (retry + 1 > RETRY_MAX_TIMES) {
225             ZLOGE("fail to register subscriber!");
226             return;
227         }
228         executors_->Schedule(std::chrono::seconds(RETRY_INTERVAL), GetTask(retry + 1));
229     };
230 }
231 
GetMetaKvStore()232 KvStoreMetaManager::NbDelegate KvStoreMetaManager::GetMetaKvStore()
233 {
234     if (metaDelegate_ != nullptr) {
235         return metaDelegate_;
236     }
237     std::lock_guard<decltype(mutex_)> lock(mutex_);
238     if (metaDelegate_ != nullptr) {
239         return metaDelegate_;
240     }
241 
242     auto metaDbName = Bootstrap::GetInstance().GetMetaDBName();
243     if (CorruptReporter::HasCorruptedFlag(metaDBDirectory_, metaDbName)) {
244         DistributedDB::DBStatus dbStatus = delegateManager_.DeleteKvStore(metaDbName);
245         if (dbStatus != DistributedDB::DBStatus::OK) {
246             ZLOGE("delete meta store failed! dbStatus: %{public}d", dbStatus);
247         }
248         metaDelegate_ = CreateMetaKvStore(true);
249         if (metaDelegate_ != nullptr) {
250             CorruptReporter::DeleteCorruptedFlag(metaDBDirectory_, metaDbName);
251         }
252     } else {
253         metaDelegate_ = CreateMetaKvStore();
254     }
255     auto fullName = GetBackupPath();
256     auto backup = [executors = executors_, queue = std::make_shared<SafeBlockQueue<Backup>>(MAX_TASK_COUNT), fullName](
257                       const auto &store) -> int32_t {
258         auto result = queue->PushNoWait([fullName](const auto &store) -> int32_t {
259             auto dbStatus = store->CheckIntegrity();
260             if (dbStatus != DistributedDB::DBStatus::OK) {
261                 ZLOGE("meta store check integrity fail, dbStatus:%{public}d", dbStatus);
262                 return dbStatus;
263             }
264             return store->Export(fullName, {}, true);
265         });
266         if (!result) {
267             return OK;
268         }
269         executors->Schedule(std::chrono::hours(RETRY_INTERVAL), GetBackupTask(queue, executors, store));
270         return OK;
271     };
272     MetaDataManager::GetInstance().Initialize(metaDelegate_, backup, metaDbName);
273     return metaDelegate_;
274 }
275 
GetBackupTask(TaskQueue queue,std::shared_ptr<ExecutorPool> executors,const NbDelegate store)276 ExecutorPool::Task KvStoreMetaManager::GetBackupTask(
277     TaskQueue queue, std::shared_ptr<ExecutorPool> executors, const NbDelegate store)
278 {
279     return [queue, executors, store]() {
280         Backup backupTask;
281         if (!queue->PopNotWait(backupTask)) {
282             return;
283         }
284         if (backupTask(store) != OK && queue->PushNoWait(backupTask)) {
285             executors->Schedule(std::chrono::hours(RETRY_INTERVAL), GetBackupTask(queue, executors, store));
286         }
287     };
288 }
289 
CreateMetaKvStore(bool isRestore)290 KvStoreMetaManager::NbDelegate KvStoreMetaManager::CreateMetaKvStore(bool isRestore)
291 {
292     DistributedDB::DBStatus dbStatusTmp = DistributedDB::DBStatus::NOT_SUPPORT;
293     auto option = InitDBOption();
294     DistributedDB::KvStoreNbDelegate *delegate = nullptr;
295     if (!isRestore) {
296         delegateManager_.GetKvStore(Bootstrap::GetInstance().GetMetaDBName(), option,
297             [&delegate, &dbStatusTmp](DistributedDB::DBStatus dbStatus, DistributedDB::KvStoreNbDelegate *nbDelegate) {
298                 delegate = nbDelegate;
299                 dbStatusTmp = dbStatus;
300             });
301     }
302     if (dbStatusTmp == DistributedDB::DBStatus::INVALID_PASSWD_OR_CORRUPTED_DB || isRestore) {
303         ZLOGE("meta data corrupted!");
304         option.isNeedRmCorruptedDb = true;
305         auto fullName = GetBackupPath();
306         delegateManager_.GetKvStore(Bootstrap::GetInstance().GetMetaDBName(), option,
307             [&delegate, &dbStatusTmp, &fullName](DistributedDB::DBStatus dbStatus,
308                 DistributedDB::KvStoreNbDelegate *nbDelegate) {
309                 delegate = nbDelegate;
310                 dbStatusTmp = dbStatus;
311                 if (dbStatusTmp == DistributedDB::DBStatus::OK && delegate != nullptr) {
312                     ZLOGI("start import meta data");
313                     DistributedDB::CipherPassword password;
314                     delegate->Import(fullName, password, true);
315                 }
316             });
317     }
318     if (dbStatusTmp != DistributedDB::DBStatus::OK || delegate == nullptr) {
319         ZLOGE("GetKvStore return error status: %{public}d or delegate is nullptr", static_cast<int>(dbStatusTmp));
320         return nullptr;
321     }
322     delegate->SetRemotePushFinishedNotify([](const RemotePushNotifyInfo &info) {
323         DeviceMatrix::GetInstance().OnExchanged(info.deviceId, DeviceMatrix::META_STORE_MASK,
324             DeviceMatrix::LevelType::DYNAMIC, DeviceMatrix::ChangeType::CHANGE_REMOTE);
325     });
326     bool param = true;
327     auto data = static_cast<DistributedDB::PragmaData>(&param);
328     delegate->Pragma(DistributedDB::SET_SYNC_RETRY, data);
329     auto release = [this](DistributedDB::KvStoreNbDelegate *delegate) {
330         ZLOGI("release meta data kv store");
331         if (delegate == nullptr) {
332             return;
333         }
334         auto result = delegateManager_.CloseKvStore(delegate);
335         if (result != DistributedDB::DBStatus::OK) {
336             ZLOGE("CloseMetaKvStore return error status: %{public}d", static_cast<int>(result));
337         }
338     };
339     return NbDelegate(delegate, release);
340 }
341 
InitDBOption()342 DistributedDB::KvStoreNbDelegate::Option KvStoreMetaManager::InitDBOption()
343 {
344     DistributedDB::KvStoreNbDelegate::Option option;
345     option.createIfNecessary = true;
346     option.isMemoryDb = false;
347     option.createDirByStoreIdOnly = true;
348     option.isEncryptedDb = false;
349     option.isNeedIntegrityCheck = true;
350     option.isNeedRmCorruptedDb = false;
351     option.isNeedCompressOnSync = true;
352     option.compressionRate = COMPRESS_RATE;
353     option.secOption = { DistributedDB::S1, DistributedDB::ECE };
354     return option;
355 }
356 
SetCloudSyncer()357 void KvStoreMetaManager::SetCloudSyncer()
358 {
359     auto cloudSyncer = [this]() {
360         std::lock_guard<decltype(mutex_)> lock(mutex_);
361         if (delaySyncTaskId_ == Executor::INVALID_TASK_ID) {
362             delaySyncTaskId_ = executors_->Schedule(std::chrono::milliseconds(DELAY_SYNC), CloudSyncTask());
363         } else {
364             delaySyncTaskId_ = executors_->Reset(delaySyncTaskId_, std::chrono::milliseconds(DELAY_SYNC));
365         }
366     };
367     MetaDataManager::GetInstance().SetCloudSyncer(cloudSyncer);
368 }
369 
CloudSyncTask()370 std::function<void()> KvStoreMetaManager::CloudSyncTask()
371 {
372     return [this]() {
373         {
374             std::lock_guard<decltype(mutex_)> lock(mutex_);
375             delaySyncTaskId_ = ExecutorPool::INVALID_TASK_ID;
376         }
377         DeviceMatrix::GetInstance().OnChanged(DeviceMatrix::META_STORE_MASK);
378     };
379 }
380 
SubscribeMetaKvStore()381 void KvStoreMetaManager::SubscribeMetaKvStore()
382 {
383     auto metaDelegate = GetMetaKvStore();
384     if (metaDelegate == nullptr) {
385         ZLOGW("register meta observer failed.");
386         return;
387     }
388 
389     int mode = DistributedDB::OBSERVER_CHANGES_NATIVE | DistributedDB::OBSERVER_CHANGES_FOREIGN;
390     auto dbStatus = metaDelegate->RegisterObserver(DistributedDB::Key(), mode, &metaObserver_);
391     if (dbStatus != DistributedDB::DBStatus::OK) {
392         ZLOGW("register meta observer failed :%{public}d.", dbStatus);
393     }
394 }
395 
~KvStoreMetaObserver()396 KvStoreMetaManager::KvStoreMetaObserver::~KvStoreMetaObserver()
397 {
398     ZLOGW("meta observer destruct.");
399 }
400 
OnChange(const DistributedDB::KvStoreChangedData & data)401 void KvStoreMetaManager::KvStoreMetaObserver::OnChange(const DistributedDB::KvStoreChangedData &data)
402 {
403     ZLOGD("on data change.");
404     HandleChanges(CHANGE_FLAG::INSERT, data.GetEntriesInserted());
405     HandleChanges(CHANGE_FLAG::UPDATE, data.GetEntriesUpdated());
406     HandleChanges(CHANGE_FLAG::DELETE, data.GetEntriesDeleted());
407     KvStoreMetaManager::GetInstance().OnDataChange(CHANGE_FLAG::INSERT, data.GetEntriesInserted());
408     KvStoreMetaManager::GetInstance().OnDataChange(CHANGE_FLAG::UPDATE, data.GetEntriesUpdated());
409     KvStoreMetaManager::GetInstance().OnDataChange(CHANGE_FLAG::DELETE, data.GetEntriesDeleted());
410 }
411 
HandleChanges(CHANGE_FLAG flag,const std::list<DistributedDB::Entry> & entries)412 void KvStoreMetaManager::KvStoreMetaObserver::HandleChanges(CHANGE_FLAG flag,
413     const std::list<DistributedDB::Entry> &entries)
414 {
415     for (const auto &entry : entries) {
416         std::string key(entry.key.begin(), entry.key.end());
417         for (const auto &item : handlerMap_) {
418             ZLOGI("flag:%{public}d, key:%{public}s", flag, Anonymous::Change(key).c_str());
419             if (key.find(item.first) == 0) {
420                 item.second(entry.key, entry.value, flag);
421             }
422         }
423     }
424 }
425 
OnDeviceChanged(const AppDistributedKv::DeviceInfo & info,const AppDistributedKv::DeviceChangeType & type) const426 void KvStoreMetaManager::MetaDeviceChangeListenerImpl::OnDeviceChanged(const AppDistributedKv::DeviceInfo &info,
427     const AppDistributedKv::DeviceChangeType &type) const
428 {
429     if (info.uuid == DmAdapter::CLOUD_DEVICE_UUID) {
430         return;
431     }
432     switch (type) {
433         case AppDistributedKv::DeviceChangeType::DEVICE_OFFLINE:
434             DeviceMatrix::GetInstance().Offline(info.uuid);
435             break;
436         case AppDistributedKv::DeviceChangeType::DEVICE_ONLINE:
437             DeviceMatrix::GetInstance().Online(info.uuid, RefCount([deviceId = info.uuid]() {
438                 DmAdapter::GetInstance().NotifyReadyEvent(deviceId);
439             }));
440             break;
441         default:
442             ZLOGI("flag:%{public}d", type);
443             break;
444     }
445 }
446 
GetChangeLevelType() const447 AppDistributedKv::ChangeLevelType KvStoreMetaManager::MetaDeviceChangeListenerImpl::GetChangeLevelType() const
448 {
449     return AppDistributedKv::ChangeLevelType::LOW;
450 }
451 
GetBackupPath() const452 std::string KvStoreMetaManager::GetBackupPath() const
453 {
454     return (DirectoryManager::GetInstance().GetMetaBackupPath() + "/" +
455             Crypto::Sha256(label_ + "_" + Bootstrap::GetInstance().GetMetaDBName()));
456 }
457 
BindExecutor(std::shared_ptr<ExecutorPool> executors)458 void KvStoreMetaManager::BindExecutor(std::shared_ptr<ExecutorPool> executors)
459 {
460     executors_ = executors;
461 }
462 
OnDataChange(CHANGE_FLAG flag,const std::list<DistributedDB::Entry> & changedData)463 void KvStoreMetaManager::OnDataChange(CHANGE_FLAG flag, const std::list<DistributedDB::Entry>& changedData)
464 {
465     for (const auto& entry : changedData) {
466         std::string key(entry.key.begin(), entry.key.end());
467         if (key.find(StoreMetaData::GetKey({})) != 0) {
468             continue;
469         }
470         StoreMetaData metaData;
471         metaData.Unmarshall({ entry.value.begin(), entry.value.end() });
472         if (!metaData.isAutoSync) {
473             continue;
474         }
475         std::vector<DistributedDB::DBInfo> dbInfos;
476         AddDbInfo(metaData, dbInfos, flag == CHANGE_FLAG::DELETE);
477         DistributedDB::RuntimeConfig::NotifyDBInfos({ metaData.deviceId }, dbInfos);
478     }
479 }
480 
GetDbInfosByDeviceId(const std::string & deviceId,std::vector<DistributedDB::DBInfo> & dbInfos)481 void KvStoreMetaManager::GetDbInfosByDeviceId(const std::string& deviceId, std::vector<DistributedDB::DBInfo>& dbInfos)
482 {
483     std::vector<StoreMetaData> metaData;
484     if (!MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ deviceId }), metaData)) {
485         ZLOGW("load meta failed, deviceId:%{public}s", Anonymous::Change(deviceId).c_str());
486         return;
487     }
488     for (auto const& data : metaData) {
489         if (data.isAutoSync) {
490             AddDbInfo(data, dbInfos);
491         }
492     }
493 }
494 
AddDbInfo(const StoreMetaData & metaData,std::vector<DistributedDB::DBInfo> & dbInfos,bool isDeleted)495 void KvStoreMetaManager::AddDbInfo(const StoreMetaData& metaData, std::vector<DistributedDB::DBInfo>& dbInfos,
496     bool isDeleted)
497 {
498     DistributedDB::DBInfo dbInfo;
499     dbInfo.appId = metaData.deviceId;
500     dbInfo.userId = metaData.user;
501     dbInfo.storeId = metaData.storeId;
502     dbInfo.isNeedSync = !isDeleted;
503     dbInfo.syncDualTupleMode = true;
504     dbInfos.push_back(dbInfo);
505 }
506 
OnDeviceChange(const std::string & deviceId)507 void KvStoreMetaManager::OnDeviceChange(const std::string& deviceId)
508 {
509     std::vector<DistributedDB::DBInfo> dbInfos;
510     GetDbInfosByDeviceId(deviceId, dbInfos);
511     DistributedDB::RuntimeConfig::NotifyDBInfos({ deviceId }, dbInfos);
512 }
513 
NotifyAllAutoSyncDBInfo()514 void KvStoreMetaManager::NotifyAllAutoSyncDBInfo()
515 {
516     auto deviceId = DmAdapter::GetInstance().GetLocalDevice().uuid;
517     if (deviceId.empty()) {
518         ZLOGE("local deviceId empty");
519         return;
520     }
521     std::vector<StoreMetaData> metaData;
522     if (!MetaDataManager::GetInstance().LoadMeta(StoreMetaData::GetPrefix({ deviceId }), metaData)) {
523         ZLOGE("load meta failed, deviceId:%{public}s", Anonymous::Change(deviceId).c_str());
524         return;
525     }
526     std::vector<DistributedDB::DBInfo> dbInfos;
527     for (auto const& data : metaData) {
528         if (!data.isAutoSync) {
529             continue;
530         }
531         AddDbInfo(data, dbInfos);
532     }
533     if (!dbInfos.empty()) {
534         DistributedDB::RuntimeConfig::NotifyDBInfos({ deviceId }, dbInfos);
535     }
536 }
537 
OnDeviceChanged(const AppDistributedKv::DeviceInfo & info,const DeviceChangeType & type) const538 void KvStoreMetaManager::DBInfoDeviceChangeListenerImpl::OnDeviceChanged(const AppDistributedKv::DeviceInfo& info,
539     const DeviceChangeType& type) const
540 {
541     if (type != DeviceChangeType::DEVICE_ONLINE) {
542         ZLOGD("offline or onReady ignore, type:%{public}d, deviceId:%{public}s", type,
543             Anonymous::Change(info.uuid).c_str());
544         return;
545     }
546     if (info.uuid == DistributedData::DeviceManagerAdapter::CLOUD_DEVICE_UUID) {
547         ZLOGD("Network change, ignore");
548         return;
549     }
550     KvStoreMetaManager::GetInstance().OnDeviceChange(info.uuid);
551 }
552 
GetChangeLevelType() const553 AppDistributedKv::ChangeLevelType KvStoreMetaManager::DBInfoDeviceChangeListenerImpl::GetChangeLevelType() const
554 {
555     return AppDistributedKv::ChangeLevelType::MIN;
556 }
557 } // namespace DistributedKv
558 } // namespace OHOS