1 /*
2  * Copyright (c) 2023 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 "faultevent_listener.h"
17 
18 #include <cstring>
19 #include <iostream>
20 
21 namespace OHOS {
22 namespace HiviewDFX {
23 
SetKeyWords(const std::vector<std::string> & keyWords)24 void FaultEventListener::SetKeyWords(const std::vector<std::string>& keyWords)
25 {
26     std::cout << "Enter SetKeyWords" << std::endl;
27     this->keyWords = keyWords;
28     {
29         std::lock_guard<std::mutex> lock(setFlagMutex);
30         allFindFlag = false;
31     }
32 }
33 
OnEvent(std::shared_ptr<HiSysEventRecord> sysEvent)34 void FaultEventListener::OnEvent(std::shared_ptr<HiSysEventRecord> sysEvent)
35 {
36     if (sysEvent == nullptr) {
37         return;
38     }
39     auto str = sysEvent->AsJson();
40     std::cout << "recv event:" << str << std::endl;
41     for (const auto& keyWord : keyWords) {
42         std::cout << "match KeyWords, keyWord:" << keyWord << " , str:" << str  << std::endl;
43         if (str.find(keyWord) == std::string::npos) {
44             std::cout << "str not find keyWord"  << std::endl;
45             return;
46         }
47     }
48 
49     // find all keywords, set allFindFlag to true
50     std::cout << "OnEvent get all keyWords"  << std::endl;
51     {
52         std::lock_guard<std::mutex> lock(setFlagMutex);
53         allFindFlag = true;
54         keyWordCheckCondition.notify_all();
55     }
56 }
57 
CheckKeyWords()58 bool FaultEventListener::CheckKeyWords()
59 {
60     std::cout << "Enter CheckKeyWords"  << std::endl;
61     std::unique_lock<std::mutex> lock(setFlagMutex);
62     if (allFindFlag) {
63         std::cout << "allFindFlag is true, match ok, return true"  << std::endl;
64         return true;
65     }
66 
67     auto flagCheckFunc = [&]() {
68         return allFindFlag;
69     };
70 
71     // 8: wait allFindFlag set true for 8 seconds
72     if (keyWordCheckCondition.wait_for(lock, std::chrono::seconds(8), flagCheckFunc)) {
73         std::cout << "match ok, return true"  << std::endl;
74         return true;
75     } else {
76         std::cout << "match keywords timeout"  << std::endl;
77         return false;
78     }
79 }
80 } // namespace HiviewDFX
81 } // namespace OHOS
82