1 /*
2 * Copyright (c) 2022-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 *     http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15 #define LOG_TAG "KVDBExporter"
16 #include "kvdb_exporter.h"
17 
18 #include "backup_manager.h"
19 #include "directory/directory_manager.h"
20 #include "kvdb_general_store.h"
21 #include "log_print.h"
22 #include "reporter.h"
23 namespace OHOS::DistributedKv {
24 using namespace OHOS::DistributedData;
25 using namespace OHOS::DistributedDataDfx;
26 __attribute__((used)) KVDBExporter KVDBExporter::instance_;
27 
Exporter(const StoreMetaData & meta,const std::string & backupPath,bool & result)28 void KVDBExporter::Exporter(const StoreMetaData &meta, const std::string &backupPath, bool &result)
29 {
30     DBManager manager(meta.appId, meta.user);
31     auto path = DirectoryManager::GetInstance().GetStorePath(meta);
32     manager.SetKvStoreConfig({ path });
33     auto dbPassword = KVDBGeneralStore::GetDBPassword(meta);
34     auto dbOption = KVDBGeneralStore::GetDBOption(meta, dbPassword);
35 
36     manager.GetKvStore(meta.storeId, dbOption, [&manager, &backupPath, &dbPassword, &result]
37         (DistributedDB::DBStatus dbstatus, DistributedDB::KvStoreNbDelegate *delegate) {
38         if (delegate == nullptr) {
39             ZLOGE("Auto backup delegate is null");
40             result = false;
41             return;
42         }
43         dbstatus = delegate->Export(backupPath, dbPassword);
44         result = (dbstatus == DistributedDB::DBStatus::OK) ? true : false;
45         manager.CloseKvStore(delegate);
46     });
47     std::string message;
48     message.append(" backup name [")
49         .append(backupPath)
50         .append("], isEncrypt [")
51         .append(std::to_string(meta.isEncrypt))
52         .append("]")
53         .append("], backup result  [")
54         .append(std::to_string(result))
55         .append("]");
56     Reporter::GetInstance()->BehaviourReporter()->Report(
57         { meta.account, meta.appId, meta.storeId, BehaviourType::DATABASE_BACKUP, message });
58 }
59 
KVDBExporter()60 KVDBExporter::KVDBExporter() noexcept
61 {
62     BackupManager::GetInstance().RegisterExporter(KvStoreType::SINGLE_VERSION, Exporter);
63     BackupManager::GetInstance().RegisterExporter(KvStoreType::DEVICE_COLLABORATION, Exporter);
64 }
65 } // namespace OHOS::DistributedKv
66