• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 }
89 
HandlerEvent(std::shared_ptr<EventRaw::RawData> rawData)90 void SysEventReceiver::HandlerEvent(std::shared_ptr<EventRaw::RawData> rawData)
91 {
92     if (rawData == nullptr || rawData->GetData() == nullptr) {
93         HIVIEW_LOGW("raw data of sys event is null");
94         return;
95     }
96     std::shared_ptr<PipelineEvent> event = std::make_shared<SysEvent>("SysEventSource",
97         static_cast<PipelineEventProducer*>(&eventSource), rawData);
98     if (eventSource.CheckEvent(event)) {
99         eventSource.PublishPipelineEvent(event);
100     }
101 }
102 
OnLoad()103 void SysEventSource::OnLoad()
104 {
105     HIVIEW_LOGI("SysEventSource load ");
106     std::shared_ptr<EventLoop> looper = GetHiviewContext()->GetSharedWorkLoop();
107     platformMonitor_.StartMonitor(looper);
108 
109     sysEventStat_ = std::make_unique<SysEventStat>();
110     InitController();
111 
112     // start sys event service
113     auto notifyFunc = [&] (std::shared_ptr<Event> event) -> void {
114         this->GetHiviewContext()->PostUnorderedEvent(shared_from_this(), event);
115     };
116     SysEventServiceAdapter::StartService(this, notifyFunc);
117     SysEventServiceAdapter::SetWorkLoop(looper);
118 
119     auto defFilePath = HiViewConfigUtil::GetConfigFilePath(DEF_ZIP_NAME, DEF_CFG_DIR, DEF_FILE_NAME);
120     HIVIEW_LOGI("init json parser with %{public}s", defFilePath.c_str());
121     sysEventParser_ = std::make_shared<EventJsonParser>(defFilePath);
122 
123     SysEventServiceAdapter::BindGetTagFunc(
124         [this] (const std::string& domain, const std::string& name) {
125             return this->sysEventParser_->GetTagByDomainAndName(domain, name);
126         });
127     SysEventServiceAdapter::BindGetTypeFunc(
128         [this] (const std::string& domain, const std::string& name) {
129             return this->sysEventParser_->GetTypeByDomainAndName(domain, name);
130         });
131 
132     // watch parameter
133     if (WatchParameter(TEST_TYPE_PARAM_KEY, ParameterWatchCallback, this) != 0) {
134         HIVIEW_LOGW("failed to watch the change of parameter %{public}s", TEST_TYPE_PARAM_KEY);
135     }
136 }
137 
InitController()138 void SysEventSource::InitController()
139 {
140     auto context = GetHiviewContext();
141     if (context == nullptr) {
142         HIVIEW_LOGW("context is null");
143         return;
144     }
145 
146     std::string workPath = context->GetHiViewDirectory(HiviewContext::DirectoryType::WORK_DIRECTORY);
147     std::string configPath = context->GetHiViewDirectory(HiviewContext::DirectoryType::CONFIG_DIRECTORY);
148     const std::string configFileName = "event_threshold.json";
149     controller_ = std::make_unique<DailyController>(workPath, configPath.append(configFileName));
150 }
151 
OnUnload()152 void SysEventSource::OnUnload()
153 {
154     eventServer_.Stop();
155     HIVIEW_LOGI("SysEventSource unload");
156 }
157 
StartEventSource()158 void SysEventSource::StartEventSource()
159 {
160     HIVIEW_LOGI("SysEventSource start");
161     std::shared_ptr<EventReceiver> sysEventReceiver = std::make_shared<SysEventReceiver>(*this);
162     eventServer_.AddReceiver(sysEventReceiver);
163     eventServer_.Start();
164 }
165 
Recycle(PipelineEvent * event)166 void SysEventSource::Recycle(PipelineEvent *event)
167 {
168     platformMonitor_.CollectCostTime(event);
169 }
170 
PauseDispatch(std::weak_ptr<Plugin> plugin)171 void SysEventSource::PauseDispatch(std::weak_ptr<Plugin> plugin)
172 {
173     auto requester = plugin.lock();
174     if (requester != nullptr) {
175         HIVIEW_LOGI("process pause dispatch event from plugin:%s.\n", requester->GetName().c_str());
176     }
177 }
178 
PublishPipelineEvent(std::shared_ptr<PipelineEvent> event)179 bool SysEventSource::PublishPipelineEvent(std::shared_ptr<PipelineEvent> event)
180 {
181     platformMonitor_.CollectEvent(event);
182     platformMonitor_.Breaking();
183     auto context = GetHiviewContext();
184     HiviewPlatform* hiviewPlatform = static_cast<HiviewPlatform*>(context);
185     if (hiviewPlatform == nullptr) {
186         HIVIEW_LOGW("hiviewPlatform is null");
187         return false;
188     }
189     auto const &pipelineRules = hiviewPlatform->GetPipelineConfigMap();
190     auto const &pipelineMap = hiviewPlatform->GetPipelineMap();
191     for (auto it = pipelineRules.begin(); it != pipelineRules.end(); it++) {
192         std::string pipelineName = it->first;
193         auto dispathRule = it->second;
194         if (dispathRule->FindEvent(event->domain_, event->eventName_)) {
195             pipelineMap.at(pipelineName)->ProcessEvent(event);
196             return true;
197         }
198     }
199     pipelineMap.at("SysEventPipeline")->ProcessEvent(event);
200     return true;
201 }
202 
CheckEvent(std::shared_ptr<Event> event)203 bool SysEventSource::CheckEvent(std::shared_ptr<Event> event)
204 {
205     if (isConfigUpdated_) {
206         auto defFilePath = HiViewConfigUtil::GetConfigFilePath(DEF_ZIP_NAME, DEF_CFG_DIR, DEF_FILE_NAME);
207         HIVIEW_LOGI("update json parser with %{public}s", defFilePath.c_str());
208         sysEventParser_->ReadDefFile(defFilePath);
209         isConfigUpdated_.store(false);
210     }
211     std::shared_ptr<SysEvent> sysEvent = Convert2SysEvent(event);
212     if (sysEvent == nullptr) {
213         HIVIEW_LOGE("event or event parser is null.");
214         sysEventStat_->AccumulateEvent(false);
215         return false;
216     }
217     if (controller_ != nullptr && !controller_->CheckThreshold(sysEvent)) {
218         sysEventStat_->AccumulateEvent(false);
219         return false;
220     }
221     EventStore::SysEventDao::CheckRepeat(sysEvent);
222     if (!IsValidSysEvent(sysEvent)) {
223         sysEventStat_->AccumulateEvent(sysEvent->domain_, sysEvent->eventName_, false);
224         return false;
225     }
226     if (FocusedEventUtil::IsFocusedEvent(sysEvent->domain_, sysEvent->eventName_)) {
227         HIVIEW_LOGI("event[%{public}s|%{public}s|%{public}" PRIu64 "] is valid.",
228             sysEvent->domain_.c_str(), sysEvent->eventName_.c_str(), event->happenTime_);
229     } else {
230         HIVIEW_LOGD("event[%{public}s|%{public}s|%{public}" PRIu64 "] is valid.",
231             sysEvent->domain_.c_str(), sysEvent->eventName_.c_str(), event->happenTime_);
232     }
233     sysEventStat_->AccumulateEvent();
234     return true;
235 }
236 
Convert2SysEvent(std::shared_ptr<Event> & event)237 std::shared_ptr<SysEvent> SysEventSource::Convert2SysEvent(std::shared_ptr<Event>& event)
238 {
239     if (event == nullptr) {
240         HIVIEW_LOGE("event is null");
241         return nullptr;
242     }
243     if (event->messageType_ != Event::MessageType::SYS_EVENT) {
244         HIVIEW_LOGE("receive out of sys event type");
245         return nullptr;
246     }
247     return Event::DownCastTo<SysEvent>(event);
248 }
249 
ShowUsage(int fd,const std::vector<std::string> & cmds)250 static void ShowUsage(int fd, const std::vector<std::string>& cmds)
251 {
252     dprintf(fd, "invalid cmd:");
253     for (auto it = cmds.begin(); it != cmds.end(); it++) {
254         dprintf(fd, "%s ", it->c_str());
255     }
256     dprintf(fd, "\n");
257     dprintf(fd, "usage: SysEventService [sum|detail|invalid|clear]\n");
258 }
259 
Dump(int fd,const std::vector<std::string> & cmds)260 void SysEventSource::Dump(int fd, const std::vector<std::string>& cmds)
261 {
262     if (cmds.size() >= 2) { // 2: args from the second item
263         std::string arg1 = cmds[1];
264         if (arg1 == "sum") {
265             sysEventStat_->StatSummary(fd);
266         } else if (arg1 == "detail") {
267             sysEventStat_->StatDetail(fd);
268         } else if (arg1 == "invalid") {
269             sysEventStat_->StatInvalidDetail(fd);
270         } else if (arg1 == "clear") {
271             sysEventStat_->Clear(fd);
272         } else {
273             ShowUsage(fd, cmds);
274         }
275     } else {
276         sysEventStat_->StatSummary(fd);
277     }
278 }
279 
OnConfigUpdate(const std::string & localCfgPath,const std::string & cloudCfgPath)280 void SysEventSource::OnConfigUpdate(const std::string& localCfgPath, const std::string& cloudCfgPath)
281 {
282     this->isConfigUpdated_.store(true);
283 }
284 
IsValidSysEvent(const std::shared_ptr<SysEvent> event)285 bool SysEventSource::IsValidSysEvent(const std::shared_ptr<SysEvent> event)
286 {
287     if (event->domain_.empty() || event->eventName_.empty()) {
288         HIVIEW_LOGW("domain=%{public}s or name=%{public}s is empty.",
289             event->domain_.c_str(), event->eventName_.c_str());
290         return false;
291     }
292     auto baseInfo = sysEventParser_->GetDefinedBaseInfoByDomainName(event->domain_, event->eventName_);
293     if (baseInfo.type == INVALID_EVENT_TYPE) {
294         HIVIEW_LOGW("type defined for event[%{public}s|%{public}s|%{public}" PRIu64 "] is invalid.",
295             event->domain_.c_str(), event->eventName_.c_str(), event->happenTime_);
296         return false;
297     }
298     if (event->GetEventType() != baseInfo.type) {
299         HIVIEW_LOGW("type=%{public}d of event[%{public}s|%{public}s|%{public}" PRIu64 "] is invalid.",
300             event->GetEventType(), event->domain_.c_str(), event->eventName_.c_str(), event->happenTime_);
301         return false;
302     }
303     // append id
304     auto eventId = GenerateHash(event);
305     if (IsDuplicateEvent(eventId)) {
306         HIVIEW_LOGW("ignore duplicate event[%{public}s|%{public}s|%{public}" PRIu64 "].",
307             event->domain_.c_str(), event->eventName_.c_str(), eventId);
308         return false;
309     }
310     DecorateSysEvent(event, baseInfo, eventId);
311     return true;
312 }
313 
UpdateTestType(const std::string & testType)314 void SysEventSource::UpdateTestType(const std::string& testType)
315 {
316     testType_ = testType;
317 }
318 
DecorateSysEvent(const std::shared_ptr<SysEvent> event,const BaseInfo & baseInfo,uint64_t id)319 void SysEventSource::DecorateSysEvent(const std::shared_ptr<SysEvent> event, const BaseInfo& baseInfo, uint64_t id)
320 {
321     if (!baseInfo.level.empty()) {
322         event->SetLevel(baseInfo.level);
323     }
324     if (!baseInfo.tag.empty()) {
325         event->SetTag(baseInfo.tag);
326     }
327     event->SetPrivacy(baseInfo.privacy);
328     if (!testType_.empty()) {
329         event->SetEventValue(TEST_TYPE_KEY, testType_);
330     }
331     event->preserve_ = baseInfo.preserve;
332     // add hashcode id
333     event->SetId(id);
334 }
335 
IsDuplicateEvent(const uint64_t eventId)336 bool SysEventSource::IsDuplicateEvent(const uint64_t eventId)
337 {
338     for (auto iter = eventIdList_.begin(); iter != eventIdList_.end(); iter++) {
339         if (*iter == eventId) {
340             return true;
341         }
342     }
343     std::list<std::string>::size_type maxSize { 5 }; // size of queue limit to 5
344     if (eventIdList_.size() >= maxSize) {
345         eventIdList_.pop_front();
346     }
347     eventIdList_.emplace_back(eventId);
348     return false;
349 }
350 } // namespace HiviewDFX
351 } // namespace OHOS
352