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     if (!IsValidSysEvent(sysEvent)) {
222         sysEventStat_->AccumulateEvent(sysEvent->domain_, sysEvent->eventName_, false);
223         return false;
224     }
225     if (FocusedEventUtil::IsFocusedEvent(sysEvent->domain_, sysEvent->eventName_)) {
226         HIVIEW_LOGI("event[%{public}s|%{public}s|%{public}" PRIu64 "] is valid.",
227             sysEvent->domain_.c_str(), sysEvent->eventName_.c_str(), event->happenTime_);
228     } else {
229         HIVIEW_LOGD("event[%{public}s|%{public}s|%{public}" PRIu64 "] is valid.",
230             sysEvent->domain_.c_str(), sysEvent->eventName_.c_str(), event->happenTime_);
231     }
232     sysEventStat_->AccumulateEvent();
233     return true;
234 }
235 
Convert2SysEvent(std::shared_ptr<Event> & event)236 std::shared_ptr<SysEvent> SysEventSource::Convert2SysEvent(std::shared_ptr<Event>& event)
237 {
238     if (event == nullptr) {
239         HIVIEW_LOGE("event is null");
240         return nullptr;
241     }
242     if (event->messageType_ != Event::MessageType::SYS_EVENT) {
243         HIVIEW_LOGE("receive out of sys event type");
244         return nullptr;
245     }
246     return Event::DownCastTo<SysEvent>(event);
247 }
248 
ShowUsage(int fd,const std::vector<std::string> & cmds)249 static void ShowUsage(int fd, const std::vector<std::string>& cmds)
250 {
251     dprintf(fd, "invalid cmd:");
252     for (auto it = cmds.begin(); it != cmds.end(); it++) {
253         dprintf(fd, "%s ", it->c_str());
254     }
255     dprintf(fd, "\n");
256     dprintf(fd, "usage: SysEventService [sum|detail|invalid|clear]\n");
257 }
258 
Dump(int fd,const std::vector<std::string> & cmds)259 void SysEventSource::Dump(int fd, const std::vector<std::string>& cmds)
260 {
261     if (cmds.size() >= 2) { // 2: args from the second item
262         std::string arg1 = cmds[1];
263         if (arg1 == "sum") {
264             sysEventStat_->StatSummary(fd);
265         } else if (arg1 == "detail") {
266             sysEventStat_->StatDetail(fd);
267         } else if (arg1 == "invalid") {
268             sysEventStat_->StatInvalidDetail(fd);
269         } else if (arg1 == "clear") {
270             sysEventStat_->Clear(fd);
271         } else {
272             ShowUsage(fd, cmds);
273         }
274     } else {
275         sysEventStat_->StatSummary(fd);
276     }
277 }
278 
OnConfigUpdate(const std::string & localCfgPath,const std::string & cloudCfgPath)279 void SysEventSource::OnConfigUpdate(const std::string& localCfgPath, const std::string& cloudCfgPath)
280 {
281     this->isConfigUpdated_.store(true);
282 }
283 
IsValidSysEvent(const std::shared_ptr<SysEvent> event)284 bool SysEventSource::IsValidSysEvent(const std::shared_ptr<SysEvent> event)
285 {
286     if (event->domain_.empty() || event->eventName_.empty()) {
287         HIVIEW_LOGW("domain=%{public}s or name=%{public}s is empty.",
288             event->domain_.c_str(), event->eventName_.c_str());
289         return false;
290     }
291     auto baseInfo = sysEventParser_->GetDefinedBaseInfoByDomainName(event->domain_, event->eventName_);
292     if (baseInfo.type == INVALID_EVENT_TYPE) {
293         HIVIEW_LOGW("type defined for event[%{public}s|%{public}s|%{public}" PRIu64 "] is invalid.",
294             event->domain_.c_str(), event->eventName_.c_str(), event->happenTime_);
295         return false;
296     }
297     if (event->GetEventType() != baseInfo.type) {
298         HIVIEW_LOGW("type=%{public}d of event[%{public}s|%{public}s|%{public}" PRIu64 "] is invalid.",
299             event->GetEventType(), event->domain_.c_str(), event->eventName_.c_str(), event->happenTime_);
300         return false;
301     }
302     // append id
303     auto eventId = GenerateHash(event);
304     if (IsDuplicateEvent(eventId)) {
305         HIVIEW_LOGW("ignore duplicate event[%{public}s|%{public}s|%{public}" PRIu64 "].",
306             event->domain_.c_str(), event->eventName_.c_str(), eventId);
307         return false;
308     }
309     DecorateSysEvent(event, baseInfo, eventId);
310     return true;
311 }
312 
UpdateTestType(const std::string & testType)313 void SysEventSource::UpdateTestType(const std::string& testType)
314 {
315     testType_ = testType;
316 }
317 
DecorateSysEvent(const std::shared_ptr<SysEvent> event,const BaseInfo & baseInfo,uint64_t id)318 void SysEventSource::DecorateSysEvent(const std::shared_ptr<SysEvent> event, const BaseInfo& baseInfo, uint64_t id)
319 {
320     if (!baseInfo.level.empty()) {
321         event->SetLevel(baseInfo.level);
322     }
323     if (!baseInfo.tag.empty()) {
324         event->SetTag(baseInfo.tag);
325     }
326     event->SetPrivacy(baseInfo.privacy);
327     if (!testType_.empty()) {
328         event->SetEventValue(TEST_TYPE_KEY, testType_);
329     }
330     event->preserve_ = baseInfo.preserve;
331     // add hashcode id
332     event->SetId(id);
333 }
334 
IsDuplicateEvent(const uint64_t eventId)335 bool SysEventSource::IsDuplicateEvent(const uint64_t eventId)
336 {
337     for (auto iter = eventIdList_.begin(); iter != eventIdList_.end(); iter++) {
338         if (*iter == eventId) {
339             return true;
340         }
341     }
342     std::list<std::string>::size_type maxSize { 5 }; // size of queue limit to 5
343     if (eventIdList_.size() >= maxSize) {
344         eventIdList_.pop_front();
345     }
346     eventIdList_.emplace_back(eventId);
347     return false;
348 }
349 } // namespace HiviewDFX
350 } // namespace OHOS
351