1 /*
2 * Copyright (C) 2022-2025 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 #include "usage_event_report.h"
16
17 #include <sys/wait.h>
18
19 #include "ffrt.h"
20 #include "hiview_event_report.h"
21 #include "hiview_event_cacher.h"
22 #ifdef POWER_MANAGER_ENABLE
23 #include "hiview_shutdown_callback.h"
24 #endif
25 #include "sys_event.h"
26 #include "hiview_logger.h"
27 #include "plugin_factory.h"
28 #include "securec.h"
29 #ifdef POWER_MANAGER_ENABLE
30 #include "shutdown/shutdown_client.h"
31 #endif
32 #include "string_util.h"
33 #include "time_util.h"
34 #include "usage_event_cacher.h"
35 #include "usage_event_common.h"
36
37 namespace OHOS {
38 namespace HiviewDFX {
39 REGISTER(UsageEventReport);
40 DEFINE_LOG_TAG("HiView-UsageEventReport");
41 uint64_t UsageEventReport::lastReportTime_ = 0;
42 uint64_t UsageEventReport::lastSysReportTime_ = 0;
43 uint64_t UsageEventReport::nextReportTime_ = 0;
44 std::string UsageEventReport::workPath_ = "";
45 namespace {
46 constexpr int TRIGGER_CYCLE = 5 * 60 * 1000 * 1000; // 5 min
47 constexpr uint32_t TRIGGER_ONE_HOUR = 12; // 1h = 5min * 12
48 }
49 using namespace SysUsageDbSpace;
50 using namespace SysUsageEventSpace;
51
UsageEventReport()52 UsageEventReport::UsageEventReport() : timeOutCnt_(0), isRunning_(false)
53 {
54 #ifdef POWER_MANAGER_ENABLE
55 callback_ = nullptr;
56 #endif
57 }
58
OnLoad()59 void UsageEventReport::OnLoad()
60 {
61 HIVIEW_LOGI("start to init the env");
62 Init();
63 Start();
64 }
65
OnEvent(std::shared_ptr<Event> & event)66 bool UsageEventReport::OnEvent(std::shared_ptr<Event>& event)
67 {
68 if (event == nullptr || event->messageType_ != Event::MessageType::SYS_EVENT) {
69 HIVIEW_LOGI("event is invalid");
70 return false;
71 }
72 foldEventReport_.ProcessEvent(event);
73 return true;
74 }
75
OnUnload()76 void UsageEventReport::OnUnload()
77 {
78 HIVIEW_LOGI("start to clean up the env");
79 #ifdef POWER_MANAGER_ENABLE
80 if (callback_ != nullptr) {
81 PowerMgr::ShutdownClient::GetInstance().UnRegisterShutdownCallback(callback_);
82 callback_ = nullptr;
83 }
84 #endif
85 Stop();
86 }
87
IsRunning()88 bool UsageEventReport::IsRunning()
89 {
90 std::lock_guard lock(runningMutex_);
91 return isRunning_;
92 }
93
Init()94 void UsageEventReport::Init()
95 {
96 auto nowTime = TimeUtil::GetMilliseconds();
97 if (auto context = GetHiviewContext(); context != nullptr) {
98 workPath_ = context->GetHiViewDirectory(HiviewContext::DirectoryType::WORK_DIRECTORY);
99
100 // get plugin stats event from db if any
101 UsageEventCacher cacher(workPath_);
102 std::vector<std::shared_ptr<LoggerEvent>> pluginStatEvents;
103 cacher.GetPluginStatsEvents(pluginStatEvents);
104 HiviewEventCacher::GetInstance().AddPluginStatsEvent(pluginStatEvents);
105 HIVIEW_LOGI("get plugin stats event=%{public}zu", pluginStatEvents.size());
106
107 // get last report time from db if any
108 if (auto event = cacher.GetSysUsageEvent(LAST_SYS_USAGE_TABLE); event != nullptr) {
109 HIVIEW_LOGI("get last sys usage event=%{public}s", event->ToJsonString().c_str());
110 lastReportTime_ = event->GetValue(KEY_OF_START).GetUint64();
111 } else {
112 lastReportTime_ = nowTime;
113 }
114
115 // get last sys report time from db if any
116 if (auto event = cacher.GetSysUsageEvent(); event != nullptr) {
117 HIVIEW_LOGI("get cache sys usage event=%{public}s", event->ToJsonString().c_str());
118 lastSysReportTime_ = event->GetValue(KEY_OF_START).GetUint64();
119 } else {
120 lastSysReportTime_ = nowTime;
121 }
122 BindWorkLoop(context->GetSharedWorkLoop());
123 InitFoldEventReport(workPath_);
124 }
125 nextReportTime_ = static_cast<uint64_t>(TimeUtil::Get0ClockStampMs()) + TimeUtil::MILLISECS_PER_DAY;
126
127 // more than one day since the last report
128 if (nowTime >= (lastReportTime_ + TimeUtil::MILLISECS_PER_DAY)) {
129 HIVIEW_LOGI("lastReportTime=%{public}" PRIu64 ", need to report daily event now", lastReportTime_);
130 ReportDailyEvent();
131 }
132
133 // more than one hours since the shutdown time
134 if (nowTime >= (lastSysReportTime_ + 3600000)) { // 3600000ms: 1h
135 HIVIEW_LOGI("lastSysReportTime=%{public}" PRIu64 ", need to report sys usage event now", lastSysReportTime_);
136 ReportSysUsageEvent();
137 }
138 }
139
InitFoldEventReport(const std::string & workPath)140 void UsageEventReport::InitFoldEventReport(const std::string& workPath)
141 {
142 foldEventReport_.Init(workPath);
143 }
144
InitCallback()145 void UsageEventReport::InitCallback()
146 {
147 HIVIEW_LOGI("start to init shutdown callback");
148 #ifdef POWER_MANAGER_ENABLE
149 callback_ = new (std::nothrow) HiViewShutdownCallback();
150 PowerMgr::ShutdownClient::GetInstance().RegisterShutdownCallback(callback_,
151 PowerMgr::ShutdownPriority::HIGH);
152 #endif
153 }
154
Start()155 void UsageEventReport::Start()
156 {
157 {
158 std::lock_guard lock(runningMutex_);
159 isRunning_ = true;
160 }
161 RunTask();
162 }
163
Stop()164 void UsageEventReport::Stop()
165 {
166 std::lock_guard lock(runningMutex_);
167 isRunning_ = false;
168 }
169
RunTask()170 void UsageEventReport::RunTask()
171 {
172 auto task = bind(&UsageEventReport::TimeOut, this);
173 ffrt::submit(task, {}, {}, ffrt::task_attr().name("dft_ue_report").delay(TRIGGER_CYCLE));
174 }
175
TimeOut()176 void UsageEventReport::TimeOut()
177 {
178 if (!IsRunning()) {
179 HIVIEW_LOGI("task exit");
180 return;
181 }
182
183 HIVIEW_LOGD("start checking whether events need to be reported");
184 ReportTimeOutEvent();
185 ReportDailyEvent();
186
187 #ifdef POWER_MANAGER_ENABLE
188 // init shutdown callback if necessary
189 if (callback_ == nullptr) {
190 InitCallback();
191 }
192 #endif
193
194 RunTask();
195 }
196
ReportDailyEvent()197 void UsageEventReport::ReportDailyEvent()
198 {
199 // check whether time step occurs. If yes, update the next report time
200 auto nowTime = TimeUtil::GetMilliseconds();
201 if (nowTime > (nextReportTime_ + TimeUtil::MILLISECS_PER_DAY)
202 || nowTime < (nextReportTime_ - TimeUtil::MILLISECS_PER_DAY)) {
203 HIVIEW_LOGW("start to update the next daily report time");
204 nextReportTime_ = static_cast<uint64_t>(TimeUtil::Get0ClockStampMs()) + TimeUtil::MILLISECS_PER_DAY;
205 } else if (nowTime >= nextReportTime_) {
206 // report plugin stats event
207 HIVIEW_LOGI("start to report daily event");
208 HiviewEventReport::ReportPluginStats();
209 DeletePluginStatsEvents();
210
211 // report app usage event
212 StartServiceByOption("-A");
213 ReportFoldAppUsageEvent();
214
215 // update report time
216 lastReportTime_ = TimeUtil::GetMilliseconds();
217 nextReportTime_ += TimeUtil::MILLISECS_PER_DAY;
218 }
219 }
220
ReportTimeOutEvent()221 void UsageEventReport::ReportTimeOutEvent()
222 {
223 ++timeOutCnt_;
224 SaveSysUsageEvent();
225 if (timeOutCnt_ >= TRIGGER_ONE_HOUR) {
226 ReportSysUsageEvent();
227 timeOutCnt_ = 0;
228 }
229 }
230
ReportSysUsageEvent()231 void UsageEventReport::ReportSysUsageEvent()
232 {
233 StartServiceByOption("-S");
234 lastSysReportTime_ = TimeUtil::GetMilliseconds();
235 }
236
ReportFoldAppUsageEvent()237 void UsageEventReport::ReportFoldAppUsageEvent()
238 {
239 foldEventReport_.ReportEvent();
240 }
241
SaveEventToDb()242 void UsageEventReport::SaveEventToDb()
243 {
244 HIVIEW_LOGI("start to save the event to db");
245 SavePluginStatsEvents();
246 SaveSysUsageEvent();
247 }
248
SavePluginStatsEvents()249 void UsageEventReport::SavePluginStatsEvents()
250 {
251 std::vector<std::shared_ptr<LoggerEvent>> events;
252 HiviewEventCacher::GetInstance().GetPluginStatsEvents(events);
253 if (events.empty()) {
254 return;
255 }
256 UsageEventCacher cacher(workPath_);
257 cacher.SavePluginStatsEventsToDb(events);
258 }
259
DeletePluginStatsEvents()260 void UsageEventReport::DeletePluginStatsEvents()
261 {
262 UsageEventCacher cacher(workPath_);
263 cacher.DeletePluginStatsEventsFromDb();
264 }
265
SaveSysUsageEvent()266 void UsageEventReport::SaveSysUsageEvent()
267 {
268 StartServiceByOption("-s");
269 }
270
StartServiceByOption(const std::string & opt)271 void UsageEventReport::StartServiceByOption(const std::string& opt)
272 {
273 HIVIEW_LOGI("start service, opt=%{public}s", opt.c_str());
274 if (pid_t pid = fork(); pid < 0) {
275 HIVIEW_LOGE("failed to fork child process");
276 return;
277 } else if (pid == 0) {
278 const size_t len = 20; // 20: max_len(uint64_t) + '\0'
279 char lastRTBuf[len] = {0};
280 if (sprintf_s(lastRTBuf, len, "%" PRIu64, lastReportTime_) < 0) {
281 HIVIEW_LOGE("failed to convert lastReportTime_=%{public}" PRIu64 " to string", lastReportTime_);
282 _exit(-1);
283 }
284 char lastSRTBuf[len] = {0};
285 if (sprintf_s(lastSRTBuf, len, "%" PRIu64, lastSysReportTime_) < 0) {
286 HIVIEW_LOGE("failed to convert lastSysReportTime_=%{public}" PRIu64 " to string", lastSysReportTime_);
287 _exit(-1);
288 }
289 const std::string serviceName = "usage_report";
290 const std::string servicePath = "/system/bin/usage_report";
291 if (execl(servicePath.c_str(), serviceName.c_str(),
292 "-p", workPath_.c_str(),
293 "-t", lastRTBuf,
294 "-T", lastSRTBuf,
295 opt.c_str(), nullptr) < 0) {
296 HIVIEW_LOGE("failed to execute %{public}s", serviceName.c_str());
297 _exit(-1);
298 }
299 } else {
300 if (waitpid(pid, nullptr, 0) != pid) {
301 HIVIEW_LOGE("failed to waitpid, pid=%{public}d, err=%{public}d", pid, errno);
302 } else {
303 HIVIEW_LOGI("succ to waitpid, pid=%{public}d", pid);
304 }
305 }
306 }
307 } // namespace HiviewDFX
308 } // namespace OHOS
309