1 /*
2 * Copyright (c) 2021-2022 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 #include "util/dump_cpu_info_util.h"
16 #include <dirent.h>
17 #include <unistd.h>
18 #include "file_ex.h"
19 #include "string_ex.h"
20 #include "hilog_wrapper.h"
21 namespace OHOS {
22 namespace HiviewDFX {
23 const std::string DumpCpuInfoUtil::LOAD_AVG_FILE_PATH = "/proc/loadavg";
24 const std::string DumpCpuInfoUtil::PROC_STAT_FILE_PATH = "/proc/stat";
25 const std::string DumpCpuInfoUtil::SPACE = " ";
DumpCpuInfoUtil()26 DumpCpuInfoUtil::DumpCpuInfoUtil()
27 {
28 DUMPER_HILOGD(MODULE_COMMON, "create debug|");
29 curCPUInfo_ = std::make_shared<CPUInfo>();
30 oldCPUInfo_ = std::make_shared<CPUInfo>();
31 }
32
~DumpCpuInfoUtil()33 DumpCpuInfoUtil::~DumpCpuInfoUtil()
34 {
35 DUMPER_HILOGD(MODULE_COMMON, "release debug|");
36 curCPUInfo_.reset();
37 oldCPUInfo_.reset();
38 curProcs_.clear();
39 oldProcs_.clear();
40 }
41
UpdateCpuInfo()42 void DumpCpuInfoUtil::UpdateCpuInfo()
43 {
44 DUMPER_HILOGD(MODULE_COMMON, "UpdateCpuInfo debug|");
45 std::unique_lock<std::mutex> lock(mutex_);
46 CopyCpuInfo(oldCPUInfo_, curCPUInfo_);
47 GetCurCPUInfo(curCPUInfo_);
48 oldProcs_.assign(curProcs_.begin(), curProcs_.end());
49 GetCurProcInfo(curProcs_);
50 }
51
GetCurCPUInfo(std::shared_ptr<CPUInfo> & cpuInfo)52 bool DumpCpuInfoUtil::GetCurCPUInfo(std::shared_ptr<CPUInfo> &cpuInfo)
53 {
54 if (cpuInfo == nullptr) {
55 return false;
56 }
57 std::string statRawData;
58 if (!LoadStringFromFile(PROC_STAT_FILE_PATH, statRawData)) {
59 return false;
60 }
61 size_t pos = statRawData.find_first_of("\n");
62 if (pos == std::string::npos) {
63 return false;
64 }
65
66 statRawData = statRawData.substr(0, pos);
67 std::vector<std::string> cpuStates;
68 SplitStr(statRawData, SPACE, cpuStates);
69 if (cpuStates.size() <= static_cast<size_t>(CPU_STAT_SIRQ_TIME_INDEX)) {
70 return false;
71 }
72
73 SetCPUInfo(cpuInfo->uTime, cpuStates[CPU_STAT_USER_TIME_INDEX]);
74 SetCPUInfo(cpuInfo->nTime, cpuStates[CPU_STAT_NICE_TIME_INDEX]);
75 SetCPUInfo(cpuInfo->sTime, cpuStates[CPU_STAT_SYS_TIME_INDEX]);
76 SetCPUInfo(cpuInfo->iTime, cpuStates[CPU_STAT_IDLE_TIME_INDEX]);
77 SetCPUInfo(cpuInfo->iowTime, cpuStates[CPU_STAT_IOW_TIME_INDEX]);
78 SetCPUInfo(cpuInfo->irqTime, cpuStates[CPU_STAT_IRQ_TIME_INDEX]);
79 SetCPUInfo(cpuInfo->sirqTime, cpuStates[CPU_STAT_SIRQ_TIME_INDEX]);
80 return true;
81 }
82
SetCPUInfo(long unsigned & info,const std::string & strInfo)83 void DumpCpuInfoUtil::SetCPUInfo(long unsigned &info, const std::string &strInfo)
84 {
85 if (IsNumericStr(strInfo)) {
86 const int base = CONSTANT_NUM_10;
87 info = strtoul(strInfo.c_str(), nullptr, base);
88 } else {
89 info = 0;
90 }
91 }
92
GetCurProcInfo(std::vector<std::shared_ptr<ProcInfo>> & procInfos)93 bool DumpCpuInfoUtil::GetCurProcInfo(std::vector<std::shared_ptr<ProcInfo>> &procInfos)
94 {
95 std::vector<std::string> procFiles;
96 GetProcessDirFiles("/proc", "stat", procFiles);
97 if (procFiles.size() < 1) {
98 return false;
99 }
100 // Set procInfos size 0
101 procInfos.clear();
102 for (size_t i = 0; i < procFiles.size(); i++) {
103 std::string rawData;
104 if (!LoadStringFromFile(procFiles[i], rawData)) {
105 continue;
106 }
107
108 // Get comm name, (xxx) in stat file.
109 std::vector<std::string> comms;
110 GetSubStrBetween(rawData, "(", ")", comms);
111 if (comms.empty()) {
112 continue;
113 }
114
115 /**
116 * @brief (xxx xxx xx) contain ' ' will effect function SplitStr,
117 * there will be wrong string for infos, so replace '()' instead of (xxx xxx xx)
118 */
119 rawData = ReplaceStr(rawData, comms[0], "()");
120 std::vector<std::string> procInfosStr;
121 SplitStr(rawData, SPACE, procInfosStr);
122 if (procInfosStr.size() <= static_cast<size_t>(PROC_INFO_SYS_TIME_INDEX)) {
123 continue;
124 }
125
126 std::shared_ptr<ProcInfo> ptrProcInfo = std::make_shared<ProcInfo>();
127 ptrProcInfo->comm = comms[0];
128 ptrProcInfo->pid = procInfosStr[0];
129 SetCPUInfo(ptrProcInfo->uTime, procInfosStr[PROC_INFO_USER_TIME_INDEX]);
130 SetCPUInfo(ptrProcInfo->sTime, procInfosStr[PROC_INFO_SYS_TIME_INDEX]);
131 ptrProcInfo->minflt = procInfosStr[PROC_INFO_MINOR_FAULT_INDEX];
132 ptrProcInfo->majflt = procInfosStr[PROC_INFO_MAJOR_FAULT_INDEX];
133 procInfos.push_back(ptrProcInfo);
134 }
135 return true;
136 }
137
GetProcessDirFiles(const std::string & path,const std::string & file,std::vector<std::string> & files)138 void DumpCpuInfoUtil::GetProcessDirFiles(const std::string &path, const std::string &file,
139 std::vector<std::string> &files)
140 {
141 DIR *dir = opendir(path.c_str());
142 if (dir == nullptr) {
143 return;
144 }
145
146 while (true) {
147 struct dirent *pidDir = readdir(dir);
148 if (pidDir == nullptr) {
149 break;
150 }
151
152 if (!IsNumericStr(std::string(pidDir->d_name))) {
153 continue;
154 }
155
156 std::string filePath(path + "/" + std::string(pidDir->d_name) + "/" + file);
157 files.push_back(std::move(filePath));
158 }
159 closedir(dir);
160 }
161
GetCurSpecProcInfo(int pid,std::shared_ptr<ProcInfo> & specProc)162 bool DumpCpuInfoUtil::GetCurSpecProcInfo(int pid, std::shared_ptr<ProcInfo> &specProc)
163 {
164 if (specProc == nullptr) {
165 return false;
166 }
167
168 std::string filePath = "/proc/" + std::to_string(pid) + "/stat";
169 std::string rawData;
170 if (!LoadStringFromFile(filePath, rawData)) {
171 return false;
172 }
173
174 // Get comm name, (xxx) in stat file.
175 std::vector<std::string> comms;
176 GetSubStrBetween(rawData, "(", ")", comms);
177 if (comms.empty()) {
178 return false;
179 }
180
181 /**
182 * @brief (xxx xxx xx) contain ' ' will effect function SplitStr,
183 * there will be wrong string for infos, so replace '()' instead of (xxx xxx xx)
184 */
185 rawData = ReplaceStr(rawData, comms[0], "()");
186 std::vector<std::string> procInfosStr;
187 SplitStr(rawData, SPACE, procInfosStr);
188 if (procInfosStr.size() <= static_cast<size_t>(PROC_INFO_SYS_TIME_INDEX)) {
189 return false;
190 }
191
192 specProc->comm = comms[0];
193 specProc->pid = procInfosStr[0];
194 SetCPUInfo(specProc->uTime, procInfosStr[PROC_INFO_USER_TIME_INDEX]);
195 SetCPUInfo(specProc->sTime, procInfosStr[PROC_INFO_SYS_TIME_INDEX]);
196 specProc->minflt = procInfosStr[PROC_INFO_MINOR_FAULT_INDEX];
197 specProc->majflt = procInfosStr[PROC_INFO_MAJOR_FAULT_INDEX];
198 return true;
199 }
200
GetOldCPUInfo(std::shared_ptr<CPUInfo> & cpuInfo)201 bool DumpCpuInfoUtil::GetOldCPUInfo(std::shared_ptr<CPUInfo> &cpuInfo)
202 {
203 if (!CheckFrequentDumpping()) {
204 CopyCpuInfo(cpuInfo, curCPUInfo_);
205 } else {
206 CopyCpuInfo(cpuInfo, oldCPUInfo_);
207 }
208 return true;
209 }
210
GetOldProcInfo(std::vector<std::shared_ptr<ProcInfo>> & procInfos)211 bool DumpCpuInfoUtil::GetOldProcInfo(std::vector<std::shared_ptr<ProcInfo>> &procInfos)
212 {
213 if (!CheckFrequentDumpping()) {
214 procInfos.assign(curProcs_.begin(), curProcs_.end());
215 } else {
216 procInfos.assign(oldProcs_.begin(), oldProcs_.end());
217 }
218 return true;
219 }
220
GetOldSpecProcInfo(int pid,std::shared_ptr<ProcInfo> & specProc)221 bool DumpCpuInfoUtil::GetOldSpecProcInfo(int pid, std::shared_ptr<ProcInfo> &specProc)
222 {
223 if (!CheckFrequentDumpping()) {
224 for (size_t i = 0; i < curProcs_.size(); i++) {
225 if (curProcs_[i] == nullptr) {
226 continue;
227 }
228 if (!IsNumericStr(curProcs_[i]->pid)) {
229 return false;
230 }
231 int specPid = 0;
232 if (!StrToInt(curProcs_[i]->pid, specPid)) {
233 return false;
234 }
235 if (pid == specPid) {
236 CopyProcInfo(specProc, curProcs_[i]);
237 return true;
238 }
239 }
240 } else {
241 for (size_t i = 0; i < oldProcs_.size(); i++) {
242 if (oldProcs_[i] == nullptr) {
243 continue;
244 }
245 if (!IsNumericStr(oldProcs_[i]->pid)) {
246 return false;
247 }
248 int specPid = 0;
249 if (!StrToInt(oldProcs_[i]->pid, specPid)) {
250 return false;
251 }
252 if (pid == specPid) {
253 CopyProcInfo(specProc, oldProcs_[i]);
254 return true;
255 }
256 }
257 }
258 return false;
259 }
260
CopyCpuInfo(std::shared_ptr<CPUInfo> & tar,const std::shared_ptr<CPUInfo> & source)261 void DumpCpuInfoUtil::CopyCpuInfo(std::shared_ptr<CPUInfo> &tar, const std::shared_ptr<CPUInfo> &source)
262 {
263 if ((tar == nullptr) || (source == nullptr)) {
264 return;
265 }
266
267 tar->uTime = source->uTime;
268 tar->nTime = source->nTime;
269 tar->sTime = source->sTime;
270 tar->iTime = source->iTime;
271 tar->iowTime = source->iowTime;
272 tar->irqTime = source->irqTime;
273 tar->sirqTime = source->sirqTime;
274 }
275
CopyProcInfo(std::shared_ptr<ProcInfo> & tar,const std::shared_ptr<ProcInfo> & source)276 void DumpCpuInfoUtil::CopyProcInfo(std::shared_ptr<ProcInfo> &tar, const std::shared_ptr<ProcInfo> &source)
277 {
278 if ((tar == nullptr) || (source == nullptr)) {
279 return;
280 }
281
282 tar->pid = source->pid;
283 tar->comm = source->comm;
284 tar->uTime = source->uTime;
285 tar->sTime = source->sTime;
286 tar->minflt = source->minflt;
287 tar->majflt = source->majflt;
288 }
289
CheckFrequentDumpping()290 bool DumpCpuInfoUtil::CheckFrequentDumpping()
291 {
292 time_t curTime;
293 struct tm ptrCurtime = {0};
294 (void)time(&curTime);
295 gmtime_r(&curTime, &ptrCurtime);
296 int interval = ptrCurtime.tm_sec - dumpTimeSec_;
297 if (interval > 0 && interval < DUMP_TIME_INTERVAL) {
298 return true;
299 }
300 dumpTimeSec_ = ptrCurtime.tm_sec;
301 return false;
302 }
303
GetCpuUsage(const int pid)304 float DumpCpuInfoUtil::GetCpuUsage(const int pid)
305 {
306 std::shared_ptr<CPUInfo> oldCPUInfo = std::make_shared<CPUInfo>();
307 if (!GetCurCPUInfo(oldCPUInfo)) {
308 return false;
309 }
310 std::shared_ptr<ProcInfo> oldSpecProc = std::make_shared<ProcInfo>();
311 if (!GetCurSpecProcInfo(pid, oldSpecProc)) {
312 return false;
313 }
314
315 sleep(1);
316
317 std::shared_ptr<CPUInfo> curCPUInfo = std::make_shared<CPUInfo>();
318 if (!GetCurCPUInfo(curCPUInfo)) {
319 return false;
320 }
321 std::shared_ptr<ProcInfo> curSpecProc = std::make_shared<ProcInfo>();
322 if (!GetCurSpecProcInfo(pid, curSpecProc)) {
323 return false;
324 }
325
326 long unsigned totalDeltaTime = (curCPUInfo->uTime + curCPUInfo->nTime + curCPUInfo->sTime + curCPUInfo->iTime
327 + curCPUInfo->iowTime + curCPUInfo->irqTime + curCPUInfo->sirqTime)
328 - (oldCPUInfo->uTime + oldCPUInfo->nTime + oldCPUInfo->sTime + oldCPUInfo->iTime
329 + oldCPUInfo->iowTime + oldCPUInfo->irqTime + oldCPUInfo->sirqTime);
330
331 if (totalDeltaTime != 0) {
332 float cpuUsage = static_cast<float>((curSpecProc->uTime - oldSpecProc->uTime)
333 + (curSpecProc->sTime - oldSpecProc->sTime)) / static_cast<float>(totalDeltaTime);
334 return cpuUsage;
335 } else {
336 return 0;
337 }
338 }
339 } // namespace HiviewDFX
340 } // namespace OHOS
341