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