1 /*
2 * Copyright (c) 2023 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 "RdbSubscriberManager"
16
17 #include "rdb_subscriber_manager.h"
18
19 #include <cinttypes>
20 #include <utility>
21
22 #include "ipc_skeleton.h"
23 #include "general/load_config_data_info_strategy.h"
24 #include "log_print.h"
25 #include "scheduler_manager.h"
26 #include "template_data.h"
27 #include "uri_utils.h"
28 #include "utils/anonymous.h"
29
30 namespace OHOS::DataShare {
Get(const Key & key,int32_t userId,Template & tpl)31 bool TemplateManager::Get(const Key &key, int32_t userId, Template &tpl)
32 {
33 return TemplateData::Query(Id(TemplateData::GenId(key.uri, key.bundleName, key.subscriberId), userId), tpl) == E_OK;
34 }
35
Add(const Key & key,int32_t userId,const Template & tpl)36 int32_t TemplateManager::Add(const Key &key, int32_t userId, const Template &tpl)
37 {
38 auto status = TemplateData::Add(key.uri, userId, key.bundleName, key.subscriberId, tpl);
39 if (!status) {
40 ZLOGE("Add failed, %{public}d", status);
41 return E_ERROR;
42 }
43 return E_OK;
44 }
45
Delete(const Key & key,int32_t userId)46 int32_t TemplateManager::Delete(const Key &key, int32_t userId)
47 {
48 auto status = TemplateData::Delete(key.uri, userId, key.bundleName, key.subscriberId);
49 if (!status) {
50 ZLOGE("Delete failed, %{public}d", status);
51 return E_ERROR;
52 }
53 SchedulerManager::GetInstance().Stop(key);
54 return E_OK;
55 }
56
Key(const std::string & uri,int64_t subscriberId,const std::string & bundleName)57 Key::Key(const std::string &uri, int64_t subscriberId, const std::string &bundleName)
58 : uri(uri), subscriberId(subscriberId), bundleName(bundleName)
59 {
60 }
61
operator ==(const Key & rhs) const62 bool Key::operator==(const Key &rhs) const
63 {
64 return uri == rhs.uri && subscriberId == rhs.subscriberId && bundleName == rhs.bundleName;
65 }
66
operator !=(const Key & rhs) const67 bool Key::operator!=(const Key &rhs) const
68 {
69 return !(rhs == *this);
70 }
operator <(const Key & rhs) const71 bool Key::operator<(const Key &rhs) const
72 {
73 if (uri < rhs.uri) {
74 return true;
75 }
76 if (rhs.uri < uri) {
77 return false;
78 }
79 if (subscriberId < rhs.subscriberId) {
80 return true;
81 }
82 if (rhs.subscriberId < subscriberId) {
83 return false;
84 }
85 return bundleName < rhs.bundleName;
86 }
operator >(const Key & rhs) const87 bool Key::operator>(const Key &rhs) const
88 {
89 return rhs < *this;
90 }
operator <=(const Key & rhs) const91 bool Key::operator<=(const Key &rhs) const
92 {
93 return !(rhs < *this);
94 }
operator >=(const Key & rhs) const95 bool Key::operator>=(const Key &rhs) const
96 {
97 return !(*this < rhs);
98 }
99
TemplateManager()100 TemplateManager::TemplateManager() {}
101
GetInstance()102 TemplateManager &TemplateManager::GetInstance()
103 {
104 static TemplateManager manager;
105 return manager;
106 }
107
GetInstance()108 RdbSubscriberManager &RdbSubscriberManager::GetInstance()
109 {
110 static RdbSubscriberManager manager;
111 return manager;
112 }
113
Add(const Key & key,const sptr<IDataProxyRdbObserver> observer,std::shared_ptr<Context> context,std::shared_ptr<ExecutorPool> executorPool)114 int RdbSubscriberManager::Add(const Key &key, const sptr<IDataProxyRdbObserver> observer,
115 std::shared_ptr<Context> context, std::shared_ptr<ExecutorPool> executorPool)
116 {
117 int result = E_OK;
118 rdbCache_.Compute(key, [&observer, &context, executorPool, this](const auto &key, auto &value) {
119 ZLOGI("add subscriber, uri %{private}s tokenId 0x%{public}x", key.uri.c_str(), context->callerTokenId);
120 auto callerTokenId = IPCSkeleton::GetCallingTokenID();
121 auto callerPid = IPCSkeleton::GetCallingPid();
122 value.emplace_back(observer, context->callerTokenId, callerTokenId, callerPid);
123 std::vector<ObserverNode> node;
124 node.emplace_back(observer, context->callerTokenId, callerTokenId, callerPid);
125 ExecutorPool::Task task = [key, node, context, this]() {
126 LoadConfigDataInfoStrategy loadDataInfo;
127 if (!loadDataInfo(context)) {
128 ZLOGE("loadDataInfo failed, uri %{public}s tokenId 0x%{public}x",
129 DistributedData::Anonymous::Change(key.uri).c_str(), context->callerTokenId);
130 return;
131 }
132 DistributedData::StoreMetaData metaData = RdbSubscriberManager::GenMetaDataFromContext(context);
133 Notify(key, context->currentUserId, node, metaData);
134 if (GetEnableObserverCount(key) == 1) {
135 SchedulerManager::GetInstance().Start(key, context->currentUserId, metaData);
136 }
137 };
138 executorPool->Execute(task);
139 return true;
140 });
141 return result;
142 }
143
Delete(const Key & key,uint32_t firstCallerTokenId)144 int RdbSubscriberManager::Delete(const Key &key, uint32_t firstCallerTokenId)
145 {
146 auto result =
147 rdbCache_.ComputeIfPresent(key, [&firstCallerTokenId, this](const auto &key,
148 std::vector<ObserverNode> &value) {
149 ZLOGI("delete subscriber, uri %{public}s tokenId 0x%{public}x",
150 DistributedData::Anonymous::Change(key.uri).c_str(), firstCallerTokenId);
151 for (auto it = value.begin(); it != value.end();) {
152 if (it->firstCallerTokenId == firstCallerTokenId) {
153 ZLOGI("erase start");
154 it = value.erase(it);
155 } else {
156 it++;
157 }
158 }
159 if (value.empty()) {
160 SchedulerManager::GetInstance().Stop(key);
161 }
162 return !value.empty();
163 });
164 return result ? E_OK : E_SUBSCRIBER_NOT_EXIST;
165 }
166
Delete(uint32_t callerTokenId,uint32_t callerPid)167 void RdbSubscriberManager::Delete(uint32_t callerTokenId, uint32_t callerPid)
168 {
169 rdbCache_.EraseIf([&callerTokenId, &callerPid, this](const auto &key, std::vector<ObserverNode> &value) {
170 for (auto it = value.begin(); it != value.end();) {
171 if (it->callerTokenId == callerTokenId && it->callerPid == callerPid) {
172 it = value.erase(it);
173 } else {
174 it++;
175 }
176 }
177 if (value.empty()) {
178 ZLOGI("delete timer, subId %{public}" PRId64 ", bundleName %{public}s, tokenId %{public}x, uri %{public}s.",
179 key.subscriberId, key.bundleName.c_str(), callerTokenId,
180 DistributedData::Anonymous::Change(key.uri).c_str());
181 SchedulerManager::GetInstance().Stop(key);
182 }
183 return value.empty();
184 });
185 }
186
Disable(const Key & key,uint32_t firstCallerTokenId)187 int RdbSubscriberManager::Disable(const Key &key, uint32_t firstCallerTokenId)
188 {
189 bool isAllDisabled = true;
190 auto result =
191 rdbCache_.ComputeIfPresent(key, [&firstCallerTokenId, &isAllDisabled, this](const auto &key,
192 std::vector<ObserverNode> &value) {
193 for (auto it = value.begin(); it != value.end(); it++) {
194 if (it->firstCallerTokenId == firstCallerTokenId) {
195 it->enabled = false;
196 it->isNotifyOnEnabled = false;
197 }
198 if (it->enabled) {
199 isAllDisabled = false;
200 }
201 }
202 return true;
203 });
204 if (isAllDisabled) {
205 SchedulerManager::GetInstance().Disable(key);
206 }
207 return result ? E_OK : E_SUBSCRIBER_NOT_EXIST;
208 }
209
Enable(const Key & key,std::shared_ptr<Context> context)210 int RdbSubscriberManager::Enable(const Key &key, std::shared_ptr<Context> context)
211 {
212 bool isChanged = false;
213 DistributedData::StoreMetaData metaData;
214 auto result = rdbCache_.ComputeIfPresent(key, [&context, &metaData, &isChanged, this](const auto &key,
215 std::vector<ObserverNode> &value) {
216 for (auto it = value.begin(); it != value.end(); it++) {
217 if (it->firstCallerTokenId != context->callerTokenId) {
218 continue;
219 }
220 it->enabled = true;
221 LoadConfigDataInfoStrategy loadDataInfo;
222 if (!loadDataInfo(context)) {
223 return true;
224 }
225 isChanged = true;
226 metaData = RdbSubscriberManager::GenMetaDataFromContext(context);
227 if (it->isNotifyOnEnabled) {
228 std::vector<ObserverNode> node;
229 node.emplace_back(it->observer, context->callerTokenId);
230 Notify(key, context->currentUserId, node, metaData);
231 }
232 }
233 return true;
234 });
235 if (isChanged) {
236 SchedulerManager::GetInstance().Enable(key, context->currentUserId, metaData);
237 }
238 return result ? E_OK : E_SUBSCRIBER_NOT_EXIST;
239 }
240
Emit(const std::string & uri,std::shared_ptr<Context> context)241 void RdbSubscriberManager::Emit(const std::string &uri, std::shared_ptr<Context> context)
242 {
243 if (!URIUtils::IsDataProxyURI(uri)) {
244 return;
245 }
246 if (context->calledSourceDir.empty()) {
247 LoadConfigDataInfoStrategy loadDataInfo;
248 loadDataInfo(context);
249 }
250 DistributedData::StoreMetaData metaData = RdbSubscriberManager::GenMetaDataFromContext(context);
251 rdbCache_.ForEach([&uri, &context, &metaData, this](const Key &key, std::vector<ObserverNode> &val) {
252 if (key.uri != uri) {
253 return false;
254 }
255 Notify(key, context->currentUserId, val, metaData);
256 SetObserverNotifyOnEnabled(val);
257 return false;
258 });
259 SchedulerManager::GetInstance().Execute(
260 uri, context->currentUserId, metaData);
261 }
262
Emit(const std::string & uri,int32_t userId,DistributedData::StoreMetaData & metaData)263 void RdbSubscriberManager::Emit(const std::string &uri, int32_t userId,
264 DistributedData::StoreMetaData &metaData)
265 {
266 if (!URIUtils::IsDataProxyURI(uri)) {
267 return;
268 }
269 bool hasObserver = false;
270 rdbCache_.ForEach([&uri, &userId, &metaData, &hasObserver, this](const Key &key, std::vector<ObserverNode> &val) {
271 if (key.uri != uri) {
272 return false;
273 }
274 hasObserver = true;
275 Notify(key, userId, val, metaData);
276 SetObserverNotifyOnEnabled(val);
277 return false;
278 });
279 if (!hasObserver) {
280 return;
281 }
282 SchedulerManager::GetInstance().Execute(
283 uri, userId, metaData);
284 }
285
SetObserverNotifyOnEnabled(std::vector<ObserverNode> & nodes)286 void RdbSubscriberManager::SetObserverNotifyOnEnabled(std::vector<ObserverNode> &nodes)
287 {
288 for (auto &node : nodes) {
289 if (!node.enabled) {
290 node.isNotifyOnEnabled = true;
291 }
292 }
293 }
294
GetKeysByUri(const std::string & uri)295 std::vector<Key> RdbSubscriberManager::GetKeysByUri(const std::string &uri)
296 {
297 std::vector<Key> results;
298 rdbCache_.ForEach([&uri, &results](const Key &key, std::vector<ObserverNode> &val) {
299 if (key.uri != uri) {
300 return false;
301 }
302 results.emplace_back(key);
303 return false;
304 });
305 return results;
306 }
307
EmitByKey(const Key & key,int32_t userId,const DistributedData::StoreMetaData & metaData)308 void RdbSubscriberManager::EmitByKey(const Key &key, int32_t userId, const DistributedData::StoreMetaData &metaData)
309 {
310 if (!URIUtils::IsDataProxyURI(key.uri)) {
311 return;
312 }
313 rdbCache_.ComputeIfPresent(key, [&userId, &metaData, this](const Key &key, auto &val) {
314 Notify(key, userId, val, metaData);
315 SetObserverNotifyOnEnabled(val);
316 return true;
317 });
318 }
319
GetEnableObserverCount(const Key & key)320 int RdbSubscriberManager::GetEnableObserverCount(const Key &key)
321 {
322 auto pair = rdbCache_.Find(key);
323 if (!pair.first) {
324 return 0;
325 }
326 int count = 0;
327 for (const auto &observer : pair.second) {
328 if (observer.enabled) {
329 count++;
330 }
331 }
332 return count;
333 }
334
Notify(const Key & key,int32_t userId,const std::vector<ObserverNode> & val,const DistributedData::StoreMetaData & metaData)335 int RdbSubscriberManager::Notify(const Key &key, int32_t userId, const std::vector<ObserverNode> &val,
336 const DistributedData::StoreMetaData &metaData)
337 {
338 Template tpl;
339 if (!TemplateManager::GetInstance().Get(key, userId, tpl)) {
340 ZLOGE("template undefined, %{public}s, %{public}" PRId64 ", %{public}s",
341 DistributedData::Anonymous::Change(key.uri).c_str(), key.subscriberId, key.bundleName.c_str());
342 return E_TEMPLATE_NOT_EXIST;
343 }
344 DistributedData::StoreMetaData meta = metaData;
345 meta.bundleName = key.bundleName;
346 meta.user = std::to_string(userId);
347 auto delegate = DBDelegate::Create(meta, key.uri);
348 if (delegate == nullptr) {
349 ZLOGE("Create fail %{public}s %{public}s", DistributedData::Anonymous::Change(key.uri).c_str(),
350 key.bundleName.c_str());
351 return E_ERROR;
352 }
353 RdbChangeNode changeNode;
354 changeNode.uri_ = key.uri;
355 changeNode.templateId_.subscriberId_ = key.subscriberId;
356 changeNode.templateId_.bundleName_ = key.bundleName;
357 for (const auto &predicate : tpl.predicates_) {
358 std::string result = delegate->Query(predicate.selectSql_);
359 if (result.empty()) {
360 continue;
361 }
362 changeNode.data_.emplace_back("{\"" + predicate.key_ + "\":" + result + "}");
363 }
364 if (!tpl.update_.empty()) {
365 auto [errCode, rowCount] = delegate->UpdateSql(tpl.update_);
366 if (errCode != E_OK) {
367 ZLOGE("Update failed, err:%{public}d, %{public}s, %{public}" PRId64 ", %{public}s",
368 errCode, DistributedData::Anonymous::Change(key.uri).c_str(), key.subscriberId, key.bundleName.c_str());
369 }
370 }
371
372 ZLOGI("emit, valSize: %{public}zu, dataSize:%{public}zu, uri:%{public}s,",
373 val.size(), changeNode.data_.size(), DistributedData::Anonymous::Change(changeNode.uri_).c_str());
374 for (const auto &callback : val) {
375 if (callback.enabled && callback.observer != nullptr) {
376 callback.observer->OnChangeFromRdb(changeNode);
377 }
378 }
379 return E_OK;
380 }
381
Clear()382 void RdbSubscriberManager::Clear()
383 {
384 rdbCache_.Clear();
385 }
386
Emit(const std::string & uri,int64_t subscriberId,const std::string & bundleName,std::shared_ptr<Context> context)387 void RdbSubscriberManager::Emit(const std::string &uri, int64_t subscriberId,
388 const std::string &bundleName, std::shared_ptr<Context> context)
389 {
390 if (!URIUtils::IsDataProxyURI(uri)) {
391 return;
392 }
393 if (context->calledSourceDir.empty()) {
394 LoadConfigDataInfoStrategy loadDataInfo;
395 loadDataInfo(context);
396 }
397 DistributedData::StoreMetaData metaData = RdbSubscriberManager::GenMetaDataFromContext(context);
398 rdbCache_.ForEach([&uri, &context, &subscriberId, &metaData, this](const Key &key, std::vector<ObserverNode> &val) {
399 if (key.uri != uri || key.subscriberId != subscriberId) {
400 return false;
401 }
402 Notify(key, context->currentUserId, val, metaData);
403 SetObserverNotifyOnEnabled(val);
404 return false;
405 });
406 Key executeKey(uri, subscriberId, bundleName);
407 SchedulerManager::GetInstance().Start(executeKey, context->currentUserId, metaData);
408 }
409
GenMetaDataFromContext(const std::shared_ptr<Context> context)410 DistributedData::StoreMetaData RdbSubscriberManager::GenMetaDataFromContext(const std::shared_ptr<Context> context)
411 {
412 DistributedData::StoreMetaData metaData;
413 metaData.tokenId = context->calledTokenId;
414 metaData.dataDir = context->calledSourceDir;
415 metaData.storeId = context->calledStoreName;
416 metaData.haMode = context->haMode;
417 return metaData;
418 }
419
ObserverNode(const sptr<IDataProxyRdbObserver> & observer,uint32_t firstCallerTokenId,uint32_t callerTokenId,uint32_t callerPid)420 RdbSubscriberManager::ObserverNode::ObserverNode(const sptr<IDataProxyRdbObserver> &observer,
421 uint32_t firstCallerTokenId, uint32_t callerTokenId, uint32_t callerPid)
422 : observer(observer), firstCallerTokenId(firstCallerTokenId), callerTokenId(callerTokenId), callerPid(callerPid)
423 {
424 }
425 } // namespace OHOS::DataShare