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