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 "sysevent_source.h"
17
18 #include <functional>
19 #include <memory>
20
21 #include "daily_controller.h"
22 #include "decoded/decoded_event.h"
23 #include "defines.h"
24 #include "raw_data_base_def.h"
25 #include "file_util.h"
26 #include "focused_event_util.h"
27 #include "hiview_config_util.h"
28 #include "hiview_logger.h"
29 #include "plugin_factory.h"
30 #include "time_util.h"
31 #include "sys_event.h"
32 #include "hiview_platform.h"
33 #include "param_const_common.h"
34 #include "parameter.h"
35 #include "sys_event_dao.h"
36 #include "sys_event_service_adapter.h"
37
38 namespace OHOS {
39 namespace HiviewDFX {
40 REGISTER(SysEventSource);
41 namespace {
42 DEFINE_LOG_TAG("HiView-SysEventSource");
43 constexpr char DEF_FILE_NAME[] = "hisysevent.def";
44 constexpr char DEF_ZIP_NAME[] = "hisysevent.zip";
45 constexpr char DEF_CFG_DIR[] = "sys_event_def";
46 constexpr char TEST_TYPE_PARAM_KEY[] = "hiviewdfx.hiview.testtype";
47 constexpr char TEST_TYPE_KEY[] = "test_type_";
48
GenerateHash(std::shared_ptr<SysEvent> event)49 uint64_t GenerateHash(std::shared_ptr<SysEvent> event)
50 {
51 if (event == nullptr) {
52 return 0;
53 }
54 constexpr size_t infoLenLimit = 256;
55 size_t infoLen = event->rawData_->GetDataLength();
56 size_t hashLen = (infoLen < infoLenLimit) ? infoLen : infoLenLimit;
57 const uint8_t* p = event->rawData_->GetData();
58 uint64_t ret { 0xCBF29CE484222325ULL }; // basis value
59 size_t i = 0;
60 while (i < hashLen) {
61 ret ^= *(p + i);
62 ret *= 0x100000001B3ULL; // prime value
63 i++;
64 }
65 return ret;
66 }
67
ParameterWatchCallback(const char* key, const char* value, void* context)68 void ParameterWatchCallback(const char* key, const char* value, void* context)
69 {
70 if (context == nullptr) {
71 HIVIEW_LOGE("context is null");
72 return;
73 }
74 auto eventSourcePlugin = reinterpret_cast<SysEventSource*>(context);
75 if (eventSourcePlugin == nullptr) {
76 HIVIEW_LOGE("eventsource plugin is null");
77 return;
78 }
79 size_t testTypeStrMaxLen = 256;
80 std::string testTypeStr(value);
81 if (testTypeStr.size() > testTypeStrMaxLen) {
82 HIVIEW_LOGE("length of the test type string set exceeds the limit");
83 return;
84 }
85 HIVIEW_LOGI("test_type is set to be \"%{public}s\"", testTypeStr.c_str());
86 eventSourcePlugin->UpdateTestType(testTypeStr);
87 }
88
CheckIfEventDelayed(std::shared_ptr<SysEvent> event)89 void CheckIfEventDelayed(std::shared_ptr<SysEvent> event)
90 {
91 // only delay detection is performed on fault events
92 if (event->GetEventType() != SysEventCreator::EventType::FAULT) {
93 return;
94 }
95
96 uint64_t happenTime = event->happenTime_;
97 uint64_t createTime = event->createTime_ / 1000; // 1000: us->ms
98 if (createTime < happenTime) { // for the time jump scene
99 return;
100 }
101 constexpr uint64_t delayDetectLimit = 5 * 1000; // 5s
102 if (uint64_t delayTime = createTime - happenTime; delayTime > delayDetectLimit) {
103 HIVIEW_LOGI("event[%{public}s|%{public}s|%{public}" PRIu64 "] delayed by %{public}" PRIu64 "ms",
104 event->domain_.c_str(), event->eventName_.c_str(), happenTime, delayTime);
105 }
106 }
107 }
108
HandlerEvent(std::shared_ptr<EventRaw::RawData> rawData)109 void SysEventReceiver::HandlerEvent(std::shared_ptr<EventRaw::RawData> rawData)
110 {
111 if (rawData == nullptr || rawData->GetData() == nullptr) {
112 HIVIEW_LOGW("raw data of sys event is null");
113 return;
114 }
115 std::shared_ptr<PipelineEvent> event = std::make_shared<SysEvent>("SysEventSource",
116 static_cast<PipelineEventProducer*>(&eventSource), rawData);
117 if (eventSource.CheckEvent(event)) {
118 eventSource.PublishPipelineEvent(event);
119 }
120 }
121
OnLoad()122 void SysEventSource::OnLoad()
123 {
124 HIVIEW_LOGI("SysEventSource load ");
125 std::shared_ptr<EventLoop> looper = GetHiviewContext()->GetSharedWorkLoop();
126 platformMonitor_.StartMonitor(looper);
127
128 sysEventStat_ = std::make_unique<SysEventStat>();
129 InitController();
130
131 // start sys event service
132 auto notifyFunc = [&] (std::shared_ptr<Event> event) -> void {
133 this->GetHiviewContext()->PostUnorderedEvent(shared_from_this(), event);
134 };
135 SysEventServiceAdapter::StartService(this, notifyFunc);
136 SysEventServiceAdapter::SetWorkLoop(looper);
137
138 auto defFilePath = HiViewConfigUtil::GetConfigFilePath(DEF_ZIP_NAME, DEF_CFG_DIR, DEF_FILE_NAME);
139 HIVIEW_LOGI("init json parser with %{public}s", defFilePath.c_str());
140 sysEventParser_ = std::make_shared<EventJsonParser>(defFilePath);
141
142 SysEventServiceAdapter::BindGetTagFunc(
143 [this] (const std::string& domain, const std::string& name) {
144 return this->sysEventParser_->GetTagByDomainAndName(domain, name);
145 });
146 SysEventServiceAdapter::BindGetTypeFunc(
147 [this] (const std::string& domain, const std::string& name) {
148 return this->sysEventParser_->GetTypeByDomainAndName(domain, name);
149 });
150
151 // watch parameter
152 if (WatchParameter(TEST_TYPE_PARAM_KEY, ParameterWatchCallback, this) != 0) {
153 HIVIEW_LOGW("failed to watch the change of parameter %{public}s", TEST_TYPE_PARAM_KEY);
154 }
155 }
156
InitController()157 void SysEventSource::InitController()
158 {
159 auto context = GetHiviewContext();
160 if (context == nullptr) {
161 HIVIEW_LOGW("context is null");
162 return;
163 }
164
165 std::string workPath = context->GetHiViewDirectory(HiviewContext::DirectoryType::WORK_DIRECTORY);
166 std::string configPath = context->GetHiViewDirectory(HiviewContext::DirectoryType::CONFIG_DIRECTORY);
167 const std::string configFileName = "event_threshold.json";
168 controller_ = std::make_unique<DailyController>(workPath, configPath.append(configFileName));
169 }
170
OnUnload()171 void SysEventSource::OnUnload()
172 {
173 eventServer_.Stop();
174 HIVIEW_LOGI("SysEventSource unload");
175 }
176
StartEventSource()177 void SysEventSource::StartEventSource()
178 {
179 HIVIEW_LOGI("SysEventSource start");
180 std::shared_ptr<EventReceiver> sysEventReceiver = std::make_shared<SysEventReceiver>(*this);
181 eventServer_.AddReceiver(sysEventReceiver);
182 eventServer_.Start();
183 }
184
Recycle(PipelineEvent *event)185 void SysEventSource::Recycle(PipelineEvent *event)
186 {
187 platformMonitor_.CollectCostTime(event);
188 }
189
PauseDispatch(std::weak_ptr<Plugin> plugin)190 void SysEventSource::PauseDispatch(std::weak_ptr<Plugin> plugin)
191 {
192 auto requester = plugin.lock();
193 if (requester != nullptr) {
194 HIVIEW_LOGI("process pause dispatch event from plugin:%s.\n", requester->GetName().c_str());
195 }
196 }
197
PublishPipelineEvent(std::shared_ptr<PipelineEvent> event)198 bool SysEventSource::PublishPipelineEvent(std::shared_ptr<PipelineEvent> event)
199 {
200 platformMonitor_.CollectEvent(event);
201 platformMonitor_.Breaking();
202 auto context = GetHiviewContext();
203 HiviewPlatform* hiviewPlatform = static_cast<HiviewPlatform*>(context);
204 if (hiviewPlatform == nullptr) {
205 HIVIEW_LOGW("hiviewPlatform is null");
206 return false;
207 }
208 auto const &pipelineRules = hiviewPlatform->GetPipelineConfigMap();
209 auto const &pipelineMap = hiviewPlatform->GetPipelineMap();
210 for (auto it = pipelineRules.begin(); it != pipelineRules.end(); it++) {
211 std::string pipelineName = it->first;
212 auto dispathRule = it->second;
213 if (dispathRule->FindEvent(event->domain_, event->eventName_)) {
214 pipelineMap.at(pipelineName)->ProcessEvent(event);
215 return true;
216 }
217 }
218 pipelineMap.at("SysEventPipeline")->ProcessEvent(event);
219 return true;
220 }
221
CheckEvent(std::shared_ptr<Event> event)222 bool SysEventSource::CheckEvent(std::shared_ptr<Event> event)
223 {
224 if (isConfigUpdated_) {
225 auto defFilePath = HiViewConfigUtil::GetConfigFilePath(DEF_ZIP_NAME, DEF_CFG_DIR, DEF_FILE_NAME);
226 HIVIEW_LOGI("update json parser with %{public}s", defFilePath.c_str());
227 sysEventParser_->ReadDefFile(defFilePath);
228 isConfigUpdated_.store(false);
229 }
230 std::shared_ptr<SysEvent> sysEvent = Convert2SysEvent(event);
231 if (sysEvent == nullptr) {
232 HIVIEW_LOGE("event or event parser is null.");
233 sysEventStat_->AccumulateEvent(false);
234 return false;
235 }
236 CheckIfEventDelayed(sysEvent);
237 if (controller_ != nullptr && !controller_->CheckThreshold(sysEvent)) {
238 sysEventStat_->AccumulateEvent(false);
239 return false;
240 }
241 EventStore::SysEventDao::CheckRepeat(sysEvent);
242 if (!IsValidSysEvent(sysEvent)) {
243 sysEventStat_->AccumulateEvent(sysEvent->domain_, sysEvent->eventName_, false);
244 return false;
245 }
246 if (FocusedEventUtil::IsFocusedEvent(sysEvent->domain_, sysEvent->eventName_)) {
247 HIVIEW_LOGI("event[%{public}s|%{public}s|%{public}" PRIu64 "] is valid.",
248 sysEvent->domain_.c_str(), sysEvent->eventName_.c_str(), event->happenTime_);
249 } else {
250 HIVIEW_LOGD("event[%{public}s|%{public}s|%{public}" PRIu64 "] is valid.",
251 sysEvent->domain_.c_str(), sysEvent->eventName_.c_str(), event->happenTime_);
252 }
253 sysEventStat_->AccumulateEvent();
254 return true;
255 }
256
Convert2SysEvent(std::shared_ptr<Event>& event)257 std::shared_ptr<SysEvent> SysEventSource::Convert2SysEvent(std::shared_ptr<Event>& event)
258 {
259 if (event == nullptr) {
260 HIVIEW_LOGE("event is null");
261 return nullptr;
262 }
263 if (event->messageType_ != Event::MessageType::SYS_EVENT) {
264 HIVIEW_LOGE("receive out of sys event type");
265 return nullptr;
266 }
267 return Event::DownCastTo<SysEvent>(event);
268 }
269
ShowUsage(int fd, const std::vector<std::string>& cmds)270 static void ShowUsage(int fd, const std::vector<std::string>& cmds)
271 {
272 dprintf(fd, "invalid cmd:");
273 for (auto it = cmds.begin(); it != cmds.end(); it++) {
274 dprintf(fd, "%s ", it->c_str());
275 }
276 dprintf(fd, "\n");
277 dprintf(fd, "usage: SysEventService [sum|detail|invalid|clear]\n");
278 }
279
Dump(int fd, const std::vector<std::string>& cmds)280 void SysEventSource::Dump(int fd, const std::vector<std::string>& cmds)
281 {
282 if (cmds.size() >= 2) { // 2: args from the second item
283 std::string arg1 = cmds[1];
284 if (arg1 == "sum") {
285 sysEventStat_->StatSummary(fd);
286 } else if (arg1 == "detail") {
287 sysEventStat_->StatDetail(fd);
288 } else if (arg1 == "invalid") {
289 sysEventStat_->StatInvalidDetail(fd);
290 } else if (arg1 == "clear") {
291 sysEventStat_->Clear(fd);
292 } else {
293 ShowUsage(fd, cmds);
294 }
295 } else {
296 sysEventStat_->StatSummary(fd);
297 }
298 }
299
OnConfigUpdate(const std::string& localCfgPath, const std::string& cloudCfgPath)300 void SysEventSource::OnConfigUpdate(const std::string& localCfgPath, const std::string& cloudCfgPath)
301 {
302 this->isConfigUpdated_.store(true);
303 }
304
IsValidSysEvent(const std::shared_ptr<SysEvent> event)305 bool SysEventSource::IsValidSysEvent(const std::shared_ptr<SysEvent> event)
306 {
307 if (event->domain_.empty() || event->eventName_.empty()) {
308 HIVIEW_LOGW("domain=%{public}s or name=%{public}s is empty.",
309 event->domain_.c_str(), event->eventName_.c_str());
310 return false;
311 }
312 auto baseInfo = sysEventParser_->GetDefinedBaseInfoByDomainName(event->domain_, event->eventName_);
313 if (baseInfo.type == INVALID_EVENT_TYPE) {
314 HIVIEW_LOGW("type defined for event[%{public}s|%{public}s|%{public}" PRIu64 "] is invalid.",
315 event->domain_.c_str(), event->eventName_.c_str(), event->happenTime_);
316 return false;
317 }
318 if (event->GetEventType() != baseInfo.type) {
319 HIVIEW_LOGW("type=%{public}d of event[%{public}s|%{public}s|%{public}" PRIu64 "] is invalid.",
320 event->GetEventType(), event->domain_.c_str(), event->eventName_.c_str(), event->happenTime_);
321 return false;
322 }
323 // append id
324 auto eventId = GenerateHash(event);
325 if (IsDuplicateEvent(eventId)) {
326 HIVIEW_LOGW("ignore duplicate event[%{public}s|%{public}s|%{public}" PRIu64 "].",
327 event->domain_.c_str(), event->eventName_.c_str(), eventId);
328 return false;
329 }
330 DecorateSysEvent(event, baseInfo, eventId);
331 return true;
332 }
333
UpdateTestType(const std::string& testType)334 void SysEventSource::UpdateTestType(const std::string& testType)
335 {
336 testType_ = testType;
337 }
338
DecorateSysEvent(const std::shared_ptr<SysEvent> event, const BaseInfo& baseInfo, uint64_t id)339 void SysEventSource::DecorateSysEvent(const std::shared_ptr<SysEvent> event, const BaseInfo& baseInfo, uint64_t id)
340 {
341 if (!baseInfo.level.empty()) {
342 event->SetLevel(baseInfo.level);
343 }
344 if (!baseInfo.tag.empty()) {
345 event->SetTag(baseInfo.tag);
346 }
347 event->SetPrivacy(baseInfo.privacy);
348 if (!testType_.empty()) {
349 event->SetEventValue(TEST_TYPE_KEY, testType_);
350 }
351 event->preserve_ = baseInfo.preserve;
352 // add hashcode id
353 event->SetId(id);
354 }
355
IsDuplicateEvent(const uint64_t eventId)356 bool SysEventSource::IsDuplicateEvent(const uint64_t eventId)
357 {
358 for (auto iter = eventIdList_.begin(); iter != eventIdList_.end(); iter++) {
359 if (*iter == eventId) {
360 return true;
361 }
362 }
363 std::list<std::string>::size_type maxSize { 5 }; // size of queue limit to 5
364 if (eventIdList_.size() >= maxSize) {
365 eventIdList_.pop_front();
366 }
367 eventIdList_.emplace_back(eventId);
368 return false;
369 }
370 } // namespace HiviewDFX
371 } // namespace OHOS
372