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 "SchedulerManager"
16
17 #include "scheduler_manager.h"
18
19 #include <cinttypes>
20
21 #include "log_print.h"
22 #include "uri_utils.h"
23 #include "utils/anonymous.h"
24
25 namespace OHOS::DataShare {
26 static constexpr int64_t MAX_MILLISECONDS = 31536000000; // 365 days
GetInstance()27 SchedulerManager &SchedulerManager::GetInstance()
28 {
29 static SchedulerManager instance;
30 return instance;
31 }
32
Execute(const std::string & uri,const int32_t userId,const std::string & rdbDir,int version)33 void SchedulerManager::Execute(const std::string &uri, const int32_t userId, const std::string &rdbDir, int version)
34 {
35 if (!URIUtils::IsDataProxyURI(uri)) {
36 return;
37 }
38 auto delegate = DBDelegate::Create(rdbDir, version, true);
39 if (delegate == nullptr) {
40 ZLOGE("malloc fail %{public}s", DistributedData::Anonymous::Change(uri).c_str());
41 return;
42 }
43 std::vector<Key> keys = RdbSubscriberManager::GetInstance().GetKeysByUri(uri);
44 for (auto const &key : keys) {
45 ExecuteSchedulerSQL(rdbDir, userId, version, key, delegate);
46 }
47 }
48
Execute(const Key & key,const int32_t userId,const std::string & rdbDir,int version)49 void SchedulerManager::Execute(const Key &key, const int32_t userId, const std::string &rdbDir, int version)
50 {
51 auto delegate = DBDelegate::Create(rdbDir, version, true);
52 if (delegate == nullptr) {
53 ZLOGE("malloc fail %{public}s", DistributedData::Anonymous::Change(key.uri).c_str());
54 return;
55 }
56 ExecuteSchedulerSQL(rdbDir, userId, version, key, delegate);
57 }
58
SetTimer(const std::string & dbPath,const int32_t userId,int version,const Key & key,int64_t reminderTime)59 void SchedulerManager::SetTimer(
60 const std::string &dbPath, const int32_t userId, int version, const Key &key, int64_t reminderTime)
61 {
62 std::lock_guard<std::mutex> lock(mutex_);
63 if (executor_ == nullptr) {
64 ZLOGE("executor_ is nullptr");
65 return;
66 }
67 int64_t now = std::chrono::duration_cast<std::chrono::milliseconds>(
68 std::chrono::system_clock::now().time_since_epoch()).count();
69 // reminder time must is in future
70 if (reminderTime <= now || reminderTime - now >= MAX_MILLISECONDS) {
71 ZLOGE("invalid args, %{public}" PRId64 ", %{public}" PRId64 ", subId=%{public}" PRId64
72 ", bundleName=%{public}s.", reminderTime, now, key.subscriberId, key.bundleName.c_str());
73 return;
74 }
75 auto duration = std::chrono::milliseconds(reminderTime - now);
76 ZLOGI("the task will notify in %{public}" PRId64 " ms, %{public}" PRId64 ", %{public}s.",
77 reminderTime - now, key.subscriberId, key.bundleName.c_str());
78 auto it = timerCache_.find(key);
79 if (it != timerCache_.end()) {
80 // has current timer, reset time
81 ZLOGD("has current taskId, uri is %{private}s, subscriberId is %{public}" PRId64 ", bundleName is %{public}s",
82 key.uri.c_str(), key.subscriberId, key.bundleName.c_str());
83 auto taskId = executor_->Reset(it->second, duration);
84 if (taskId == ExecutorPool::INVALID_TASK_ID) {
85 ZLOGE("the task %{public}" PRIu64 " already invalid, %{public}" PRId64 ", %{public}s.", it->second,
86 key.subscriberId, key.bundleName.c_str());
87 }
88 return;
89 }
90 // not find task in map, create new timer
91 auto taskId = executor_->Schedule(duration, [key, dbPath, version, userId, this]() {
92 ZLOGI("schedule notify start, uri is %{private}s, subscriberId is %{public}" PRId64 ", bundleName is "
93 "%{public}s", key.uri.c_str(), key.subscriberId, key.bundleName.c_str());
94 {
95 std::lock_guard<std::mutex> lock(mutex_);
96 timerCache_.erase(key);
97 }
98 // 1. execute schedulerSQL in next time
99 Execute(key, userId, dbPath, version);
100 // 2. notify
101 RdbSubscriberManager::GetInstance().EmitByKey(key, userId, dbPath, version);
102 });
103 if (taskId == ExecutorPool::INVALID_TASK_ID) {
104 ZLOGE("create timer failed, over the max capacity");
105 return;
106 }
107 ZLOGI("create new task success, uri is %{public}s, subscriberId is %{public}" PRId64 ", bundleName is %{public}s",
108 DistributedData::Anonymous::Change(key.uri).c_str(), key.subscriberId, key.bundleName.c_str());
109 timerCache_.emplace(key, taskId);
110 }
111
ExecuteSchedulerSQL(const std::string & rdbDir,const int32_t userId,int version,const Key & key,std::shared_ptr<DBDelegate> delegate)112 void SchedulerManager::ExecuteSchedulerSQL(const std::string &rdbDir, const int32_t userId, int version, const Key &key,
113 std::shared_ptr<DBDelegate> delegate)
114 {
115 Template tpl;
116 if (!TemplateManager::GetInstance().Get(key, userId, tpl)) {
117 ZLOGE("template undefined, %{public}s, %{public}" PRId64 ", %{public}s",
118 DistributedData::Anonymous::Change(key.uri).c_str(), key.subscriberId, key.bundleName.c_str());
119 return;
120 }
121 if (tpl.scheduler_.empty()) {
122 ZLOGW("template scheduler_ empty, %{public}s, %{public}" PRId64 ", %{public}s",
123 DistributedData::Anonymous::Change(key.uri).c_str(), key.subscriberId, key.bundleName.c_str());
124 return;
125 }
126 GenRemindTimerFuncParams(rdbDir, userId, version, key, tpl.scheduler_);
127 auto resultSet = delegate->QuerySql(tpl.scheduler_);
128 if (resultSet == nullptr) {
129 ZLOGE("resultSet is nullptr, %{public}s, %{public}" PRId64 ", %{public}s",
130 DistributedData::Anonymous::Change(key.uri).c_str(), key.subscriberId, key.bundleName.c_str());
131 return;
132 }
133 int count;
134 int errCode = resultSet->GetRowCount(count);
135 if (errCode != E_OK || count == 0) {
136 ZLOGE("GetRowCount error, %{public}s, %{public}" PRId64 ", %{public}s, errorCode is %{public}d, count is "
137 "%{public}d",
138 DistributedData::Anonymous::Change(key.uri).c_str(), key.subscriberId, key.bundleName.c_str(), errCode,
139 count);
140 return;
141 }
142 errCode = resultSet->GoToFirstRow();
143 if (errCode != E_OK) {
144 ZLOGE("GoToFirstRow error, %{public}s, %{public}" PRId64 ", %{public}s, errCode is %{public}d",
145 DistributedData::Anonymous::Change(key.uri).c_str(), key.subscriberId, key.bundleName.c_str(), errCode);
146 }
147 }
148
GenRemindTimerFuncParams(const std::string & rdbDir,const int32_t userId,int version,const Key & key,std::string & schedulerSQL)149 void SchedulerManager::GenRemindTimerFuncParams(
150 const std::string &rdbDir, const int32_t userId, int version, const Key &key, std::string &schedulerSQL)
151 {
152 auto index = schedulerSQL.find(REMIND_TIMER_FUNC);
153 if (index == std::string::npos) {
154 ZLOGW("not find remindTimer, sql is %{public}s", schedulerSQL.c_str());
155 return;
156 }
157 index += REMIND_TIMER_FUNC_LEN;
158 std::string keyStr = "'" + rdbDir + "', " + std::to_string(version) + ", '" + key.uri + "', " +
159 std::to_string(key.subscriberId) + ", '" + key.bundleName + "', " + std::to_string(userId) +
160 ", ";
161 schedulerSQL.insert(index, keyStr);
162 return;
163 }
164
RemoveTimer(const Key & key)165 void SchedulerManager::RemoveTimer(const Key &key)
166 {
167 std::lock_guard<std::mutex> lock(mutex_);
168 if (executor_ == nullptr) {
169 ZLOGE("executor_ is nullptr");
170 return;
171 }
172 auto it = timerCache_.find(key);
173 if (it != timerCache_.end()) {
174 ZLOGW("RemoveTimer %{public}s %{public}s %{public}" PRId64,
175 DistributedData::Anonymous::Change(key.uri).c_str(), key.bundleName.c_str(), key.subscriberId);
176 executor_->Remove(it->second);
177 timerCache_.erase(key);
178 }
179 }
180
ClearTimer()181 void SchedulerManager::ClearTimer()
182 {
183 ZLOGI("Clear all timer");
184 std::lock_guard<std::mutex> lock(mutex_);
185 if (executor_ == nullptr) {
186 ZLOGE("executor_ is nullptr");
187 return;
188 }
189 auto it = timerCache_.begin();
190 while (it != timerCache_.end()) {
191 executor_->Remove(it->second);
192 it = timerCache_.erase(it);
193 }
194 }
195
SetExecutorPool(std::shared_ptr<ExecutorPool> executor)196 void SchedulerManager::SetExecutorPool(std::shared_ptr<ExecutorPool> executor)
197 {
198 executor_ = executor;
199 }
200
ReExecuteAll()201 void SchedulerManager::ReExecuteAll()
202 {
203 std::lock_guard<std::mutex> lock(mutex_);
204 for (auto &item : timerCache_) {
205 // restart in 200ms
206 executor_->Reset(item.second, std::chrono::milliseconds(200));
207 }
208 }
209 } // namespace OHOS::DataShare
210
211