1 /*
2  * Copyright (c) 2021-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 
16 #include "online_sync_table.h"
17 
18 #include "device_profile_errors.h"
19 #include "device_profile_log.h"
20 #include "device_profile_utils.h"
21 #include "dp_device_manager.h"
22 #include "sync_coordinator.h"
23 
24 namespace OHOS {
25 namespace DeviceProfile {
26 using namespace OHOS::DistributedKv;
27 
28 namespace {
29 const std::string TAG = "OnlineSyncTable";
30 
31 const std::string APP_ID = "distributed_device_profile_service";
32 const std::string STORE_ID = "online_sync_storage";
33 constexpr int32_t MAX_RETRY_SYNC_TIMES = 30;
34 constexpr int32_t INTERVAL_RETRY_SYNC_MS = 100;
35 }
36 
OnlineSyncTable()37 OnlineSyncTable::OnlineSyncTable() : DeviceProfileStorage(APP_ID, STORE_ID)
38 {
39 }
40 
Init()41 void OnlineSyncTable::Init()
42 {
43     HILOGD("called");
44     Options options = {
45         .createIfMissing = true,
46         .encrypt = true,
47         .autoSync = true,
48         .securityLevel = DistributedKv::SecurityLevel::S1,
49         .area = 1,
50         .kvStoreType = KvStoreType::SINGLE_VERSION,
51         .baseDir = "/data/service/el1/public/database/distributed_device_profile_service"
52     };
53     // clean the IMMEDIATE_SYNC_ON_CHANGE
54     SyncPolicy syncPolicyOnline {
55         .type = PolicyType::IMMEDIATE_SYNC_ON_ONLINE
56     };
57     options.policies.emplace_back(syncPolicyOnline);
58     SetOptions(options);
59     DeviceProfileStorage::Init();
60     int32_t errCode = DeviceProfileStorage::RegisterSyncCallback(shared_from_this());
61     if (errCode != ERR_OK) {
62         HILOGE("register sync callback failed, errCode = %{public}d", errCode);
63     }
64 }
65 
RegisterSyncCallback(const std::shared_ptr<KvStoreSyncCallback> & syncCb)66 int32_t OnlineSyncTable::RegisterSyncCallback(const std::shared_ptr<KvStoreSyncCallback>& syncCb)
67 {
68     HILOGI("called");
69     if (syncCb == nullptr) {
70         HILOGE("syncCb is nullptr!");
71         return ERR_DP_INVALID_PARAMS;
72     }
73     std::lock_guard<std::mutex> autoLock(tableLock_);
74     syncCallback_ = syncCb;
75     HILOGI("RegisterSyncCallback success!");
76     return ERR_OK;
77 }
78 
UnRegisterSyncCallback()79 int32_t OnlineSyncTable::UnRegisterSyncCallback()
80 {
81     HILOGI("called");
82     std::lock_guard<std::mutex> autoLock(tableLock_);
83     syncCallback_ = nullptr;
84     return ERR_OK;
85 }
86 
SyncDeviceProfile(const std::vector<std::string> & deviceIds,SyncMode syncMode)87 int32_t OnlineSyncTable::SyncDeviceProfile(const std::vector<std::string>& deviceIds,
88     SyncMode syncMode)
89 {
90     HILOGI("called");
91     auto syncTask = [this, deviceIds = std::move(deviceIds), syncMode]() {
92         HILOGI("start sync task");
93         retrySyncTimes_ = 0;
94         int32_t errCode = DeviceProfileStorage::SyncDeviceProfile(deviceIds, syncMode);
95         if (errCode != ERR_OK) {
96             SyncCoordinator::GetInstance().ReleaseSync();
97             HILOGE("sync errCode = %{public}d", errCode);
98         }
99     };
100     if (!SyncCoordinator::GetInstance().DispatchSyncTask(syncTask)) {
101         HILOGE("post online sync task failed");
102         return ERR_DP_POST_TASK_FAILED;
103     }
104     return ERR_OK;
105 }
106 
SyncCompleted(const std::map<std::string,Status> & results)107 void OnlineSyncTable::SyncCompleted(const std::map<std::string, Status>& results)
108 {
109     if (!SyncCoordinator::GetInstance().IsOnlineSync()) {
110         HILOGI("manual sync callback");
111         NotifySyncCompleted(results);
112         return;
113     }
114 
115     HILOGI("online sync callback");
116     std::vector<std::string> failedDeviceIds;
117     for (const auto& [deviceId, result] : results) {
118         HILOGI("deviceId = %{public}s, result = %{public}d",
119             DeviceProfileUtils::AnonymizeDeviceId(deviceId).c_str(), result);
120         if (result != Status::SUCCESS) {
121             std::string networkId;
122             if (!DpDeviceManager::GetInstance().TransformDeviceId(deviceId, networkId,
123                 DeviceIdType::NETWORKID)) {
124                 HILOGE("transform to networkid failed");
125                 continue;
126             }
127             failedDeviceIds.emplace_back(std::move(networkId));
128         }
129     }
130 
131     HILOGI("retry times = %{public}d", retrySyncTimes_.load());
132     if ((retrySyncTimes_++ < MAX_RETRY_SYNC_TIMES) && !failedDeviceIds.empty()) {
133         auto retrySyncTask = [this, deviceIds = std::move(failedDeviceIds)]() {
134             HILOGI("retrying sync...");
135             DeviceProfileStorage::SyncDeviceProfile(deviceIds, SyncMode::PUSH);
136         };
137         if (SyncCoordinator::GetInstance().DispatchSyncTask(retrySyncTask,
138             INTERVAL_RETRY_SYNC_MS)) {
139             return;
140         } else {
141             HILOGE("post online sync retry task failed");
142         }
143     }
144     // notify and release when there is no retry
145     NotifySyncCompleted(results);
146     SyncCoordinator::GetInstance().ReleaseSync();
147 }
148 
NotifySyncCompleted(const std::map<std::string,Status> & results)149 void OnlineSyncTable::NotifySyncCompleted(const std::map<std::string, Status>& results)
150 {
151     HILOGI("called, syncResult size %{public}zu!", results.size());
152     for (const auto& item : results) {
153         HILOGI("SyncResult networkId %{public}s result %{public}d",
154             DeviceProfileUtils::AnonymizeDeviceId(item.first).c_str(), static_cast<int32_t>(item.second));
155     }
156     std::lock_guard<std::mutex> autoLock(tableLock_);
157     if (syncCallback_ != nullptr) {
158         HILOGI("notify sync callback");
159         syncCallback_->SyncCompleted(results);
160     }
161     HILOGI("NotifySyncCompleted end!");
162 }
163 } // namespace DeviceProfile
164 } // namespace OHOS
165