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 "active_key_event.h"
17
18 #include <vector>
19
20 #include "event_log_task.h"
21 #include "file_util.h"
22 #include "hiview_logger.h"
23 #include "sys_event.h"
24 #include "time_util.h"
25 #include "trace_collector.h"
26 #include "parameter_ex.h"
27 namespace OHOS {
28 namespace HiviewDFX {
29 namespace {
30 static constexpr int REPORT_LIMIT = 3;
31 }
32 DEFINE_LOG_LABEL(0xD002D01, "EventLogger-ActiveKeyEvent");
ActiveKeyEvent()33 ActiveKeyEvent::ActiveKeyEvent()
34 {
35 triggeringTime_ = 0;
36 logStore_ = nullptr;
37 }
38
~ActiveKeyEvent()39 ActiveKeyEvent::~ActiveKeyEvent()
40 {
41 std::unique_lock<ffrt::mutex> uniqueLock(mutex_);
42 for (auto it = subscribeIds_.begin(); it != subscribeIds_.end(); it = subscribeIds_.erase(it)) {
43 if (*it >= 0) {
44 MMI::InputManager::GetInstance()->UnsubscribeKeyEvent(*it);
45 HIVIEW_LOGI("~ActiveKeyEvent subscribeId_: %{public}d", *it);
46 }
47 }
48 }
49
SystemTimeMillisecond()50 int64_t ActiveKeyEvent::SystemTimeMillisecond()
51 {
52 struct timespec t;
53 t.tv_sec = 0;
54 t.tv_nsec = 0;
55 clock_gettime(CLOCK_MONOTONIC, &t);
56 return (int64_t)((t.tv_sec) * TimeUtil::SEC_TO_NANOSEC + t.tv_nsec) / TimeUtil::SEC_TO_MICROSEC;
57 }
58
InitSubscribe(std::set<int32_t> preKeys,int32_t finalKey,int32_t count,int32_t holdTime)59 void ActiveKeyEvent::InitSubscribe(std::set<int32_t> preKeys, int32_t finalKey, int32_t count, int32_t holdTime)
60 {
61 const int32_t maxCount = 5;
62 if (++count > maxCount) {
63 return;
64 }
65 std::shared_ptr<MMI::KeyOption> keyOption = std::make_shared<MMI::KeyOption>();
66 if (keyOption == nullptr) {
67 HIVIEW_LOGE("Invalid key option");
68 return;
69 }
70
71 keyOption->SetPreKeys(preKeys);
72 keyOption->SetFinalKey(finalKey);
73 keyOption->SetFinalKeyDown(true);
74 keyOption->SetFinalKeyDownDuration(holdTime);
75 auto keyEventCallBack = [this] (std::shared_ptr<MMI::KeyEvent> keyEvent) {
76 this->CombinationKeyCallback(keyEvent);
77 };
78 int32_t subscribeId = MMI::InputManager::GetInstance()->SubscribeKeyEvent(keyOption, keyEventCallBack);
79 if (subscribeId < 0) {
80 HIVIEW_LOGE("SubscribeKeyEvent failed, finalKey: %{public}d,"
81 "subscribeId: %{public}d option failed.", finalKey, subscribeId);
82 auto task = [this, preKeys, finalKey, count, holdTime] {
83 this->InitSubscribe(preKeys, finalKey, count, holdTime);
84 taskOutDeps++;
85 };
86 std::string taskName("InitSubscribe" + std::to_string(finalKey) + "_" + std::to_string(count));
87 ffrt::submit(task, {}, {&taskOutDeps}, ffrt::task_attr().name(taskName.c_str()));
88 }
89 std::unique_lock<ffrt::mutex> uniqueLock(mutex_);
90 subscribeIds_.emplace_back(subscribeId);
91 HIVIEW_LOGI("CombinationKeyInit finalKey: %{public}d subscribeId_: %{public}d",
92 finalKey, subscribeId);
93 }
94
Init(std::shared_ptr<LogStoreEx> logStore)95 void ActiveKeyEvent::Init(std::shared_ptr<LogStoreEx> logStore)
96 {
97 HIVIEW_LOGI("CombinationKeyInit");
98 logStore_ = logStore;
99
100 std::set<int32_t> prePowerKeys;
101 prePowerKeys.insert(MMI::KeyEvent::KEYCODE_VOLUME_DOWN);
102 auto initSubscribePower = [this, prePowerKeys] {
103 this->InitSubscribe(prePowerKeys, MMI::KeyEvent::KEYCODE_POWER, 0, 500);
104 };
105 std::set<int32_t> preOnlyPowerKeys;
106 auto initSubscribeOnlyPower = [this, preOnlyPowerKeys] {
107 this->InitSubscribe(preOnlyPowerKeys, MMI::KeyEvent::KEYCODE_POWER, 0, 3000);
108 };
109 ffrt::submit(initSubscribePower, {}, {}, ffrt::task_attr().name("initSubscribePower").qos(ffrt::qos_default));
110 ffrt::submit(initSubscribeOnlyPower, {}, {},
111 ffrt::task_attr().name("initSubscribeOnlyPower").qos(ffrt::qos_default));
112 }
113
HitraceCapture()114 void ActiveKeyEvent::HitraceCapture()
115 {
116 std::shared_ptr<UCollectUtil::TraceCollector> collector = UCollectUtil::TraceCollector::Create();
117 UCollect::TraceCaller caller = UCollect::TraceCaller::BETACLUB;
118 auto result = collector->DumpTrace(caller);
119 if (result.retCode != 0) {
120 HIVIEW_LOGE("get hitrace fail! error code: %{public}d", result.retCode);
121 return;
122 }
123 }
124
SysMemCapture(int fd)125 void ActiveKeyEvent::SysMemCapture(int fd)
126 {
127 FileUtil::SaveStringToFd(fd, "\n\ncatcher cmd : /proc/meminfo\n");
128 std::string content;
129 FileUtil::LoadStringFromFile("/proc/meminfo", content);
130 FileUtil::SaveStringToFd(fd, content);
131 }
132
DumpCapture(int fd)133 void ActiveKeyEvent::DumpCapture(int fd)
134 {
135 SysEventCreator sysEventCreator("HIVIEWDFX", "ACTIVE_KEY", SysEventCreator::FAULT);
136 std::shared_ptr<SysEvent> sysEvent = std::make_shared<SysEvent>("ActiveKeyEvent", nullptr, sysEventCreator);
137 int noNeedJsonFd = -1;
138 std::unique_ptr<EventLogTask> logTask = std::make_unique<EventLogTask>(fd, noNeedJsonFd, sysEvent);
139 for (const std::string& cmd : CMD_LIST) {
140 logTask->AddLog(cmd);
141 }
142
143 auto ret = logTask->StartCompose();
144 if (ret != EventLogTask::TASK_SUCCESS) {
145 HIVIEW_LOGE("capture fail %{public}d", ret);
146 }
147 SysMemCapture(fd);
148 }
149
CombinationKeyHandle(std::shared_ptr<MMI::KeyEvent> keyEvent)150 void ActiveKeyEvent::CombinationKeyHandle(std::shared_ptr<MMI::KeyEvent> keyEvent)
151 {
152 HIVIEW_LOGI("Receive CombinationKeyHandle.");
153 if (logStore_ == nullptr || !Parameter::IsBetaVersion() || reportLimit_ > REPORT_LIMIT) {
154 HIVIEW_LOGI("Don't report ACTIVE_KEY_EVENT");
155 return;
156 }
157
158 std::string logFile = "ACTIVE_KEY_EVENT-0-" +
159 TimeUtil::TimestampFormatToDate(TimeUtil::GetMilliseconds() / TimeUtil::SEC_TO_MILLISEC,
160 "%Y%m%d%H%M%S") + ".log";
161 if (FileUtil::FileExists("/data/log/eventlog/" + logFile)) {
162 HIVIEW_LOGW("filename: %{public}s is existed, direct use.", logFile.c_str());
163 return;
164 }
165 int fd = logStore_->CreateLogFile(logFile);
166
167 auto sysStart = ActiveKeyEvent::SystemTimeMillisecond();
168 const uint32_t placeholder = 3;
169 auto start = TimeUtil::GetMilliseconds();
170 uint64_t startTime = start / TimeUtil::SEC_TO_MILLISEC;
171 std::ostringstream startTimeStr;
172 startTimeStr << "start time: " << TimeUtil::TimestampFormatToDate(startTime, "%Y/%m/%d-%H:%M:%S");
173 startTimeStr << ":" << std::setw(placeholder) << std::setfill('0') <<
174 std::to_string(start % TimeUtil::SEC_TO_MILLISEC) << std::endl;
175 std::vector<int32_t> keys = keyEvent->GetPressedKeys();
176 for (auto& i : keys) {
177 startTimeStr << "CombinationKeyCallback key : ";
178 startTimeStr << MMI::KeyEvent::KeyCodeToString(i) << std::endl;
179 }
180 FileUtil::SaveStringToFd(fd, startTimeStr.str());
181
182 auto hitraceCapture = [this] { this->HitraceCapture(); };
183 ffrt::submit(hitraceCapture, {}, {}, ffrt::task_attr().name("HitraceCapture").qos(ffrt::qos_user_initiated));
184
185 DumpCapture(fd);
186 auto end = ActiveKeyEvent::SystemTimeMillisecond();
187 std::string totalTime = "\n\nCatcher log total time is " + std::to_string(end - sysStart) + "ms\n";
188 FileUtil::SaveStringToFd(fd, totalTime);
189 close(fd);
190 reportLimit_++;
191 }
192
CombinationKeyCallback(std::shared_ptr<MMI::KeyEvent> keyEvent)193 void ActiveKeyEvent::CombinationKeyCallback(std::shared_ptr<MMI::KeyEvent> keyEvent)
194 {
195 HIVIEW_LOGI("Receive CombinationKeyCallback key id: %{public}d.", keyEvent->GetId());
196 uint64_t now = (uint64_t)ActiveKeyEvent::SystemTimeMillisecond();
197 const uint64_t interval = 10000;
198 if (now - triggeringTime_ < interval) {
199 return;
200 }
201 triggeringTime_ = now;
202 auto combinationKeyHandle = [this, keyEvent] { this->CombinationKeyHandle(keyEvent); };
203 ffrt::submit(combinationKeyHandle, {}, {},
204 ffrt::task_attr().name("ActiveKeyEvent").qos(ffrt::qos_user_initiated));
205 }
206 } // namespace HiviewDFX
207 } // namespace OHOS