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
16 #include "kv_store_delegate_manager.h"
17
18 #include <algorithm>
19 #include <cstdlib>
20 #include <cctype>
21 #include <map>
22 #include <thread>
23
24 #include "db_constant.h"
25 #include "platform_specific.h"
26 #include "log_print.h"
27 #include "db_common.h"
28 #include "db_dfx_adapter.h"
29 #include "kv_store_errno.h"
30 #include "kvdb_pragma.h"
31 #include "kvdb_properties.h"
32 #include "kvdb_manager.h"
33 #include "kv_store_nb_delegate_impl.h"
34 #include "network_adapter.h"
35 #include "runtime_context.h"
36 #include "param_check_utils.h"
37 #include "auto_launch.h"
38 #ifndef OMIT_MULTI_VER
39 #include "kv_store_delegate_impl.h"
40 #endif
41
42 namespace DistributedDB {
43 const std::string KvStoreDelegateManager::DEFAULT_PROCESS_APP_ID = "default";
44 std::mutex KvStoreDelegateManager::communicatorMutex_;
45 std::shared_ptr<IProcessCommunicator> KvStoreDelegateManager::processCommunicator_ = nullptr;
46 std::mutex KvStoreDelegateManager::multiUserMutex_;
47
48 namespace {
49 const int GET_CONNECT_RETRY = 3;
50 const int RETRY_GET_CONN_INTER = 30;
51
GetOneConnectionWithRetry(const KvDBProperties & properties,int & errCode)52 IKvDBConnection *GetOneConnectionWithRetry(const KvDBProperties &properties, int &errCode)
53 {
54 for (int i = 0; i < GET_CONNECT_RETRY; i++) {
55 auto conn = KvDBManager::GetDatabaseConnection(properties, errCode);
56 if (conn != nullptr) {
57 return conn;
58 }
59 if (errCode == -E_STALE) {
60 std::this_thread::sleep_for(std::chrono::milliseconds(RETRY_GET_CONN_INTER));
61 } else {
62 return nullptr;
63 }
64 }
65 return nullptr;
66 }
67
CheckAndGetSchema(bool isMemoryDb,const std::string & schema,SchemaObject & schemaObj)68 DBStatus CheckAndGetSchema(bool isMemoryDb, const std::string &schema, SchemaObject &schemaObj)
69 {
70 if (isMemoryDb && !schema.empty()) {
71 LOGW("[KvStoreDelegateManager] memory database doesn't support the schema.");
72 return NOT_SUPPORT;
73 }
74 if (schema.empty()) {
75 return OK;
76 }
77 schemaObj.ParseFromSchemaString(schema);
78 if (!schemaObj.IsSchemaValid()) {
79 return INVALID_SCHEMA;
80 }
81 return OK;
82 }
83
InitPropWithNbOption(KvDBProperties & properties,const std::string & storePath,const SchemaObject & schema,const KvStoreNbDelegate::Option & option)84 void InitPropWithNbOption(KvDBProperties &properties, const std::string &storePath,
85 const SchemaObject &schema, const KvStoreNbDelegate::Option &option)
86 {
87 properties.SetBoolProp(KvDBProperties::CREATE_IF_NECESSARY, option.createIfNecessary);
88 properties.SetIntProp(KvDBProperties::DATABASE_TYPE, KvDBProperties::SINGLE_VER_TYPE);
89 properties.SetBoolProp(KvDBProperties::MEMORY_MODE, option.isMemoryDb);
90 properties.SetBoolProp(KvDBProperties::ENCRYPTED_MODE, option.isEncryptedDb);
91 if (!option.isMemoryDb) { // memory db ignore store path
92 properties.SetStringProp(KvDBProperties::DATA_DIR, storePath);
93 }
94 properties.SetBoolProp(KvDBProperties::CREATE_DIR_BY_STORE_ID_ONLY, option.createDirByStoreIdOnly);
95 properties.SetSchema(schema);
96 properties.SetBoolProp(KvDBProperties::CHECK_INTEGRITY, option.isNeedIntegrityCheck);
97 properties.SetBoolProp(KvDBProperties::RM_CORRUPTED_DB, option.isNeedRmCorruptedDb);
98 if (RuntimeContext::GetInstance()->IsProcessSystemApiAdapterValid()) {
99 properties.SetIntProp(KvDBProperties::SECURITY_LABEL, option.secOption.securityLabel);
100 properties.SetIntProp(KvDBProperties::SECURITY_FLAG, option.secOption.securityFlag);
101 }
102 properties.SetIntProp(KvDBProperties::CONFLICT_RESOLVE_POLICY, option.conflictResolvePolicy);
103
104 if (option.isEncryptedDb) {
105 properties.SetPassword(option.cipher, option.passwd);
106 }
107 properties.SetBoolProp(KvDBProperties::COMPRESS_ON_SYNC, option.isNeedCompressOnSync);
108 if (option.isNeedCompressOnSync) {
109 properties.SetIntProp(KvDBProperties::COMPRESSION_RATE,
110 ParamCheckUtils::GetValidCompressionRate(option.compressionRate));
111 }
112 properties.SetBoolProp(KvDBProperties::SYNC_DUAL_TUPLE_MODE, option.syncDualTupleMode);
113 properties.SetBoolProp(KvDBProperties::LOCAL_ONLY, option.localOnly);
114 }
115
CheckObserverConflictParam(const KvStoreNbDelegate::Option & option)116 bool CheckObserverConflictParam(const KvStoreNbDelegate::Option &option)
117 {
118 if ((option.notifier && !ParamCheckUtils::CheckConflictNotifierType(option.conflictType)) ||
119 (!option.notifier && option.conflictType != 0)) {
120 LOGE("Invalid conflict type, conflict type is [%d]", option.conflictType);
121 return false;
122 }
123 if ((option.observer != nullptr && !ParamCheckUtils::CheckObserver(option.key, option.mode)) ||
124 (option.observer == nullptr && (!option.key.empty() || option.mode != 0))) {
125 LOGE("Invalid observer param, observer mode is [%u]", option.mode);
126 return false;
127 }
128 return true;
129 }
130
131 #ifndef OMIT_MULTI_VER
InitPropWithOption(KvDBProperties & properties,const std::string & storePath,const KvStoreDelegate::Option & option)132 void InitPropWithOption(KvDBProperties &properties, const std::string &storePath,
133 const KvStoreDelegate::Option &option)
134 {
135 properties.SetBoolProp(KvDBProperties::CREATE_IF_NECESSARY, option.createIfNecessary);
136 properties.SetBoolProp(KvDBProperties::CREATE_DIR_BY_STORE_ID_ONLY, option.createDirByStoreIdOnly);
137 properties.SetIntProp(KvDBProperties::DATABASE_TYPE,
138 ((option.localOnly == true) ? KvDBProperties::LOCAL_TYPE : KvDBProperties::MULTI_VER_TYPE));
139 properties.SetBoolProp(KvDBProperties::MEMORY_MODE, false);
140 properties.SetBoolProp(KvDBProperties::ENCRYPTED_MODE, option.isEncryptedDb);
141 properties.SetStringProp(KvDBProperties::DATA_DIR, storePath);
142 if (option.isEncryptedDb) {
143 properties.SetPassword(option.cipher, option.passwd);
144 }
145 }
146 #endif
147 }
148
KvStoreDelegateManager(const std::string & appId,const std::string & userId,int32_t instanceId)149 KvStoreDelegateManager::KvStoreDelegateManager(const std::string &appId, const std::string &userId, int32_t instanceId)
150 : appId_(appId),
151 userId_(userId),
152 instanceId_(instanceId)
153 {}
154
~KvStoreDelegateManager()155 KvStoreDelegateManager::~KvStoreDelegateManager() {}
156
SetKvStoreConfig(const KvStoreConfig & kvStoreConfig)157 DBStatus KvStoreDelegateManager::SetKvStoreConfig(const KvStoreConfig &kvStoreConfig)
158 {
159 std::string canonicalDir;
160 if (!IsDataDirSafe(kvStoreConfig.dataDir, canonicalDir)) {
161 return INVALID_ARGS;
162 }
163 if (!OS::CheckPathExistence(canonicalDir)) {
164 LOGE("[KvStoreMgr] Data dir doesn't exist or no perm");
165 return INVALID_ARGS;
166 }
167 {
168 std::lock_guard<std::mutex> lock(mutex_);
169 kvStoreConfig_ = kvStoreConfig;
170 kvStoreConfig_.dataDir = canonicalDir;
171 }
172 return OK;
173 }
174
175 #ifndef OMIT_MULTI_VER
GetKvStore(const std::string & storeId,const KvStoreDelegate::Option & option,const std::function<void (DBStatus,KvStoreDelegate *)> & callback)176 void KvStoreDelegateManager::GetKvStore(const std::string &storeId, const KvStoreDelegate::Option &option,
177 const std::function<void(DBStatus, KvStoreDelegate *)> &callback)
178 {
179 if (!callback) {
180 LOGE("[KvStoreMgr] Invalid callback for kv store!");
181 return;
182 }
183
184 // Multi version and local database mode not allow the creation of a memory database
185 if (!ParamCheckUtils::CheckStoreParameter(storeId, appId_, userId_) || GetKvStorePath().empty()) {
186 callback(INVALID_ARGS, nullptr);
187 return;
188 }
189
190 if (option.isEncryptedDb) {
191 if (!ParamCheckUtils::CheckEncryptedParameter(option.cipher, option.passwd)) {
192 callback(INVALID_ARGS, nullptr);
193 return;
194 }
195 }
196
197 KvDBProperties properties;
198 InitPropWithOption(properties, GetKvStorePath(), option);
199 DBCommon::SetDatabaseIds(properties, appId_, userId_, storeId);
200
201 int errCode;
202 IKvDBConnection *conn = GetOneConnectionWithRetry(properties, errCode);
203 if (errCode == -E_INVALID_PASSWD_OR_CORRUPTED_DB) {
204 DBDfxAdapter::ReportFault( { DBDfxAdapter::EVENT_OPEN_DATABASE_FAILED, userId_, appId_, storeId, errCode } );
205 }
206 if (conn == nullptr) {
207 DBStatus status = TransferDBErrno(errCode);
208 callback(status, nullptr);
209 return;
210 }
211
212 auto kvStore = new (std::nothrow) KvStoreDelegateImpl(conn, storeId);
213 if (kvStore == nullptr) {
214 LOGE("[KvStoreMgr] Failed to alloc the delegate");
215 conn->Close();
216 conn = nullptr;
217 callback(DB_ERROR, nullptr);
218 return;
219 }
220 callback(OK, kvStore);
221 }
222 #endif
223
SetObserverNotifier(KvStoreNbDelegate * kvStore,const KvStoreNbDelegate::Option & option)224 DBStatus KvStoreDelegateManager::SetObserverNotifier(KvStoreNbDelegate *kvStore,
225 const KvStoreNbDelegate::Option &option)
226 {
227 DBStatus status;
228 if (option.observer != nullptr) {
229 status = kvStore->RegisterObserver(option.key, option.mode, option.observer);
230 if (status != OK) {
231 LOGE("[KvStoreMgr] RegisterObserver failed.");
232 return status;
233 }
234 }
235 if (option.notifier != nullptr) {
236 status = kvStore->SetConflictNotifier(option.conflictType, option.notifier);
237 if (status != OK) {
238 LOGE("[KvStoreMgr] SetConflictNotifier failed.");
239 return status;
240 }
241 }
242 return OK;
243 }
244
GetKvStoreParamCheck(const std::string & storeId,const KvStoreNbDelegate::Option & option,const std::function<void (DBStatus,KvStoreNbDelegate *)> & callback) const245 bool KvStoreDelegateManager::GetKvStoreParamCheck(const std::string &storeId, const KvStoreNbDelegate::Option &option,
246 const std::function<void(DBStatus, KvStoreNbDelegate *)> &callback) const
247 {
248 if (!callback) {
249 LOGE("[KvStoreMgr] Invalid callback for kv store");
250 return false;
251 }
252 if (!ParamCheckUtils::CheckStoreParameter(storeId, appId_, userId_) ||
253 (GetKvStorePath().empty() && !option.isMemoryDb)) {
254 LOGE("[KvStoreMgr] Invalid id or path info for the store");
255 callback(INVALID_ARGS, nullptr);
256 return false;
257 }
258
259 // check if want an encrypted db
260 if (option.isEncryptedDb) {
261 if (option.isMemoryDb) {
262 LOGE("Memory db not support encrypt!");
263 callback(NOT_SUPPORT, nullptr);
264 return false;
265 }
266 if (!ParamCheckUtils::CheckEncryptedParameter(option.cipher, option.passwd)) {
267 callback(INVALID_ARGS, nullptr);
268 return false;
269 }
270 }
271 // check secOption
272 if (!option.isMemoryDb) {
273 if (!ParamCheckUtils::CheckSecOption(option.secOption)) {
274 callback(INVALID_ARGS, nullptr);
275 return false;
276 }
277 } else {
278 if (option.secOption.securityLabel != SecurityLabel::NOT_SET ||
279 option.secOption.securityFlag != 0) {
280 LOGE("Memory db has no physical files, Is not controlled by security labels, so not support set labels");
281 callback(INVALID_ARGS, nullptr);
282 return false;
283 }
284 }
285
286 if (!CheckObserverConflictParam(option)) {
287 callback(INVALID_ARGS, nullptr);
288 return false;
289 }
290 return true;
291 }
292
GetKvStore(const std::string & storeId,const KvStoreNbDelegate::Option & option,const std::function<void (DBStatus,KvStoreNbDelegate *)> & callback)293 void KvStoreDelegateManager::GetKvStore(const std::string &storeId, const KvStoreNbDelegate::Option &option,
294 const std::function<void(DBStatus, KvStoreNbDelegate *)> &callback)
295 {
296 if (!GetKvStoreParamCheck(storeId, option, callback)) {
297 return;
298 }
299 // check if schema is supported and valid
300 SchemaObject schema;
301 DBStatus retCode = CheckAndGetSchema(option.isMemoryDb, option.schema, schema);
302 if (retCode != OK) {
303 callback(retCode, nullptr);
304 return;
305 }
306 KvDBProperties properties;
307 InitPropWithNbOption(properties, GetKvStorePath(), schema, option);
308 DBCommon::SetDatabaseIds(properties, appId_, userId_, storeId, instanceId_);
309
310 int errCode;
311 IKvDBConnection *conn = GetOneConnectionWithRetry(properties, errCode);
312 if (errCode == -E_INVALID_PASSWD_OR_CORRUPTED_DB) {
313 DBDfxAdapter::ReportFault( { DBDfxAdapter::EVENT_OPEN_DATABASE_FAILED, userId_, appId_, storeId, errCode } );
314 }
315 DBStatus status = TransferDBErrno(errCode);
316 if (conn == nullptr) {
317 callback(status, nullptr);
318 return;
319 }
320
321 auto kvStore = new (std::nothrow) KvStoreNbDelegateImpl(conn, storeId);
322 if (kvStore == nullptr) {
323 conn->Close();
324 conn = nullptr;
325 callback(DB_ERROR, nullptr);
326 return;
327 }
328
329 status = SetObserverNotifier(kvStore, option);
330 if (status != OK) {
331 CloseKvStore(kvStore);
332 callback(status, nullptr);
333 return;
334 }
335
336 bool enAutoSync = false;
337 (void)conn->Pragma(PRAGMA_AUTO_SYNC, static_cast<void *>(&enAutoSync));
338
339 SecurityOption secOption = option.secOption;
340 (void)conn->Pragma(PRAGMA_TRIGGER_TO_MIGRATE_DATA, &secOption);
341
342 callback(OK, kvStore);
343 }
344
345 #ifndef OMIT_MULTI_VER
CloseKvStore(KvStoreDelegate * kvStore)346 DBStatus KvStoreDelegateManager::CloseKvStore(KvStoreDelegate *kvStore)
347 {
348 if (kvStore == nullptr) {
349 return INVALID_ARGS;
350 }
351
352 auto kvStoreImpl = static_cast<KvStoreDelegateImpl *>(kvStore);
353 DBStatus status = kvStoreImpl->Close();
354 if (status == BUSY) {
355 LOGD("DelegateImpl is busy now.");
356 return BUSY;
357 }
358
359 kvStoreImpl->SetReleaseFlag(true);
360 delete kvStore;
361 kvStore = nullptr;
362 return OK;
363 }
364 #endif
365
CloseKvStore(KvStoreNbDelegate * kvStore)366 DBStatus KvStoreDelegateManager::CloseKvStore(KvStoreNbDelegate *kvStore)
367 {
368 if (kvStore == nullptr) {
369 return INVALID_ARGS;
370 }
371
372 auto kvStoreImpl = static_cast<KvStoreNbDelegateImpl *>(kvStore);
373 DBStatus status = kvStoreImpl->Close();
374 if (status == BUSY) {
375 LOGD("NbDelegateImpl is busy now.");
376 return BUSY;
377 }
378 kvStoreImpl->SetReleaseFlag(true);
379 delete kvStore;
380 kvStore = nullptr;
381 return OK;
382 }
383
DeleteKvStore(const std::string & storeId)384 DBStatus KvStoreDelegateManager::DeleteKvStore(const std::string &storeId)
385 {
386 if (!ParamCheckUtils::IsStoreIdSafe(storeId) || GetKvStorePath().empty()) {
387 LOGE("Invalid store info for deleting");
388 return INVALID_ARGS;
389 }
390
391 KvDBProperties properties;
392 properties.SetStringProp(KvDBProperties::DATA_DIR, GetKvStorePath());
393 DBCommon::SetDatabaseIds(properties, appId_, userId_, storeId);
394 int errCode = KvDBManager::RemoveDatabase(properties);
395 if (errCode == E_OK) {
396 LOGI("Database deleted successfully!");
397 return OK;
398 }
399 LOGE("Delete the kv store error:%d", errCode);
400 return TransferDBErrno(errCode);
401 }
402
SetProcessLabel(const std::string & appId,const std::string & userId)403 DBStatus KvStoreDelegateManager::SetProcessLabel(const std::string &appId, const std::string &userId)
404 {
405 if (appId.size() > DBConstant::MAX_APP_ID_LENGTH || appId.empty() ||
406 userId.size() > DBConstant::MAX_USER_ID_LENGTH || userId.empty()) {
407 LOGE("Invalid app or user info[%zu]-[%zu]", appId.length(), userId.length());
408 return INVALID_ARGS;
409 }
410
411 int errCode = KvDBManager::SetProcessLabel(appId, userId);
412 if (errCode != E_OK) {
413 LOGE("Failed to set the process label:%d", errCode);
414 return DB_ERROR;
415 }
416 return OK;
417 }
418
SetProcessCommunicator(const std::shared_ptr<IProcessCommunicator> & inCommunicator)419 DBStatus KvStoreDelegateManager::SetProcessCommunicator(const std::shared_ptr<IProcessCommunicator> &inCommunicator)
420 {
421 std::lock_guard<std::mutex> lock(communicatorMutex_);
422 if (processCommunicator_ != nullptr) {
423 LOGE("processCommunicator_ is not null!");
424 return DB_ERROR;
425 }
426
427 std::string processLabel = RuntimeContext::GetInstance()->GetProcessLabel();
428 if (processLabel.empty()) {
429 LOGE("ProcessLabel is not set!");
430 return DB_ERROR;
431 }
432
433 NetworkAdapter *adapter = new (std::nothrow) NetworkAdapter(processLabel, inCommunicator);
434 if (adapter == nullptr) {
435 LOGE("New NetworkAdapter failed!");
436 return DB_ERROR;
437 }
438 processCommunicator_ = inCommunicator;
439 if (RuntimeContext::GetInstance()->SetCommunicatorAdapter(adapter) != E_OK) {
440 LOGE("SetProcessCommunicator not support!");
441 delete adapter;
442 return DB_ERROR;
443 }
444 KvDBManager::RestoreSyncableKvStore();
445 return OK;
446 }
447
GetKvStoreDiskSize(const std::string & storeId,uint64_t & size)448 DBStatus KvStoreDelegateManager::GetKvStoreDiskSize(const std::string &storeId, uint64_t &size)
449 {
450 std::string dataDir = GetKvStorePath();
451 if (!ParamCheckUtils::CheckStoreParameter(storeId, appId_, userId_)) {
452 LOGE("[KvStoreMgr] Invalid store info for size");
453 return INVALID_ARGS;
454 }
455 KvDBProperties properties;
456 properties.SetStringProp(KvDBProperties::DATA_DIR, dataDir);
457 DBCommon::SetDatabaseIds(properties, appId_, userId_, storeId);
458 int errCode = KvDBManager::CalculateKvStoreSize(properties, size);
459 if (errCode != E_OK) {
460 if (errCode == -E_NOT_FOUND) {
461 return NOT_FOUND;
462 }
463
464 LOGE("[KvStoreMgr] Get the file size failed[%d]", errCode);
465 return DB_ERROR;
466 }
467 return OK;
468 }
469
SetKvStoreCorruptionHandler(const KvStoreCorruptionHandler & handler)470 void KvStoreDelegateManager::SetKvStoreCorruptionHandler(const KvStoreCorruptionHandler &handler)
471 {
472 KvDBManager::SetDatabaseCorruptionHandler(handler);
473 }
474
GetDatabaseDir(const std::string & storeId,const std::string & appId,const std::string & userId,std::string & directory)475 DBStatus KvStoreDelegateManager::GetDatabaseDir(const std::string &storeId, const std::string &appId,
476 const std::string &userId, std::string &directory)
477 {
478 if (!ParamCheckUtils::CheckStoreParameter(storeId, appId, userId)) {
479 return INVALID_ARGS;
480 }
481
482 std::string identifier = DBCommon::GenerateIdentifierId(storeId, appId, userId);
483 std::string dir = DBCommon::TransferHashString(identifier);
484 if (dir.empty()) {
485 return DB_ERROR;
486 }
487 directory = DBCommon::TransferStringToHex(dir);
488 return OK;
489 }
490
GetDatabaseDir(const std::string & storeId,std::string & directory)491 DBStatus KvStoreDelegateManager::GetDatabaseDir(const std::string &storeId, std::string &directory)
492 {
493 if (!ParamCheckUtils::IsStoreIdSafe(storeId)) {
494 return INVALID_ARGS;
495 }
496
497 if (storeId.find(DBConstant::ID_CONNECTOR) != std::string::npos) {
498 return INVALID_ARGS;
499 }
500
501 std::string dir = DBCommon::TransferHashString(storeId);
502 if (dir.empty()) {
503 return DB_ERROR;
504 }
505 directory = DBCommon::TransferStringToHex(dir);
506 return OK;
507 }
508
509 // private
IsDataDirSafe(const std::string & dataDir,std::string & canonicalDir) const510 bool KvStoreDelegateManager::IsDataDirSafe(const std::string &dataDir, std::string &canonicalDir) const
511 {
512 return ParamCheckUtils::CheckDataDir(dataDir, canonicalDir);
513 }
514
GetKvStorePath() const515 const std::string &KvStoreDelegateManager::GetKvStorePath() const
516 {
517 std::lock_guard<std::mutex> lock(mutex_);
518 return kvStoreConfig_.dataDir;
519 }
520
SetPermissionCheckCallback(const PermissionCheckCallback & callback)521 DBStatus KvStoreDelegateManager::SetPermissionCheckCallback(const PermissionCheckCallback &callback)
522 {
523 int errCode = RuntimeContext::GetInstance()->SetPermissionCheckCallback(callback);
524 return TransferDBErrno(errCode);
525 }
526
SetPermissionCheckCallback(const PermissionCheckCallbackV2 & callback)527 DBStatus KvStoreDelegateManager::SetPermissionCheckCallback(const PermissionCheckCallbackV2 &callback)
528 {
529 int errCode = RuntimeContext::GetInstance()->SetPermissionCheckCallback(callback);
530 return TransferDBErrno(errCode);
531 }
532
EnableKvStoreAutoLaunch(const std::string & userId,const std::string & appId,const std::string & storeId,const AutoLaunchOption & option,const AutoLaunchNotifier & notifier)533 DBStatus KvStoreDelegateManager::EnableKvStoreAutoLaunch(const std::string &userId, const std::string &appId,
534 const std::string &storeId, const AutoLaunchOption &option, const AutoLaunchNotifier ¬ifier)
535 {
536 if (RuntimeContext::GetInstance() == nullptr) {
537 return DB_ERROR;
538 }
539 AutoLaunchParam param{ userId, appId, storeId, option, notifier, {}};
540 std::shared_ptr<DBProperties> ptr = std::make_shared<KvDBProperties>();
541 int errCode = AutoLaunch::GetAutoLaunchProperties(param, DBType::DB_KV, true, ptr);
542 if (errCode != E_OK) {
543 LOGE("[KvStoreManager] Enable auto launch failed:%d", errCode);
544 return TransferDBErrno(errCode);
545 }
546
547 std::shared_ptr<KvDBProperties> kvPtr = std::static_pointer_cast<KvDBProperties>(ptr);
548 errCode = RuntimeContext::GetInstance()->EnableKvStoreAutoLaunch(*kvPtr, notifier, option);
549 if (errCode != E_OK) {
550 LOGE("[KvStoreManager] Enable auto launch failed:%d", errCode);
551 return TransferDBErrno(errCode);
552 }
553 LOGI("[KvStoreManager] Enable auto launch");
554 return OK;
555 }
556
DisableKvStoreAutoLaunch(const std::string & userId,const std::string & appId,const std::string & storeId)557 DBStatus KvStoreDelegateManager::DisableKvStoreAutoLaunch(const std::string &userId, const std::string &appId,
558 const std::string &storeId)
559 {
560 if (RuntimeContext::GetInstance() == nullptr) {
561 return DB_ERROR;
562 }
563
564 std::string syncIdentifier = DBCommon::GenerateIdentifierId(storeId, appId, userId, 0);
565 std::string hashIdentifier = DBCommon::TransferHashString(syncIdentifier);
566 std::string dualIdentifier = DBCommon::TransferHashString(DBCommon::GenerateDualTupleIdentifierId(storeId, appId));
567 int errCode = RuntimeContext::GetInstance()->DisableKvStoreAutoLaunch(hashIdentifier, dualIdentifier, userId);
568 if (errCode != E_OK) {
569 LOGE("[KvStoreManager] Disable auto launch failed:%d", errCode);
570 return TransferDBErrno(errCode);
571 }
572 LOGI("[KvStoreManager] Disable auto launch");
573 return OK;
574 }
575
SetAutoLaunchRequestCallback(const AutoLaunchRequestCallback & callback)576 void KvStoreDelegateManager::SetAutoLaunchRequestCallback(const AutoLaunchRequestCallback &callback)
577 {
578 RuntimeContext::GetInstance()->SetAutoLaunchRequestCallback(callback, DBType::DB_KV);
579 }
580
GetKvStoreIdentifier(const std::string & userId,const std::string & appId,const std::string & storeId,bool syncDualTupleMode)581 std::string KvStoreDelegateManager::GetKvStoreIdentifier(const std::string &userId, const std::string &appId,
582 const std::string &storeId, bool syncDualTupleMode)
583 {
584 if (!ParamCheckUtils::CheckStoreParameter(storeId, appId, userId, syncDualTupleMode)) {
585 return "";
586 }
587 if (syncDualTupleMode) {
588 return DBCommon::TransferHashString(appId + "-" + storeId);
589 }
590 return DBCommon::TransferHashString(userId + "-" + appId + "-" + storeId);
591 }
592
SetProcessSystemAPIAdapter(const std::shared_ptr<IProcessSystemApiAdapter> & adapter)593 DBStatus KvStoreDelegateManager::SetProcessSystemAPIAdapter(const std::shared_ptr<IProcessSystemApiAdapter> &adapter)
594 {
595 return TransferDBErrno(RuntimeContext::GetInstance()->SetProcessSystemApiAdapter(adapter));
596 }
597
SetStoreStatusNotifier(const StoreStatusNotifier & notifier)598 void KvStoreDelegateManager::SetStoreStatusNotifier(const StoreStatusNotifier ¬ifier)
599 {
600 RuntimeContext::GetInstance()->SetStoreStatusNotifier(notifier);
601 }
602
SetSyncActivationCheckCallback(const SyncActivationCheckCallback & callback)603 DBStatus KvStoreDelegateManager::SetSyncActivationCheckCallback(const SyncActivationCheckCallback &callback)
604 {
605 std::lock_guard<std::mutex> lock(multiUserMutex_);
606 int errCode = RuntimeContext::GetInstance()->SetSyncActivationCheckCallback(callback);
607 return TransferDBErrno(errCode);
608 }
609
NotifyUserChanged()610 DBStatus KvStoreDelegateManager::NotifyUserChanged()
611 {
612 std::lock_guard<std::mutex> lock(multiUserMutex_);
613 int errCode = RuntimeContext::GetInstance()->NotifyUserChanged();
614 return TransferDBErrno(errCode);
615 }
616
IsProcessSystemApiAdapterValid()617 bool KvStoreDelegateManager::IsProcessSystemApiAdapterValid()
618 {
619 return RuntimeContext::GetInstance()->IsProcessSystemApiAdapterValid();
620 }
621 } // namespace DistributedDB
622