1 /* 2 * Copyright (c) 2025 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 "dump_trace_controller.h" 17 18 #include "common_utils.h" 19 #include "cpu_collector.h" 20 #include "hiview_logger.h" 21 #include "time_util.h" 22 #include "trace_collector.h" 23 24 namespace OHOS { 25 namespace HiviewDFX { 26 DEFINE_LOG_TAG("DumpTraceController"); 27 CheckAndDumpTrace()28void DumpTraceController::CheckAndDumpTrace() 29 { 30 for (auto& cpuThresholdItem : cpuThresholdItems_) { 31 if (!IsTimeOver(cpuThresholdItem)) { 32 continue; 33 } 34 if (!IsCpuLoadBackToNormal(cpuThresholdItem)) { 35 continue; 36 } 37 DumpTrace(cpuThresholdItem); 38 } 39 } 40 IsTimeOver(const CpuThresholdItem & item)41bool DumpTraceController::IsTimeOver(const CpuThresholdItem& item) 42 { 43 uint64_t currentTime = TimeUtil::GetBootTimeMs() / static_cast<uint64_t>(TimeUtil::SEC_TO_MILLISEC); 44 return (currentTime - item.lastDumpTraceTime) > item.dumpTraceInterval; 45 } 46 47 // only when cpu load restore form high to normal, meet the condition for capturing trace IsCpuLoadBackToNormal(CpuThresholdItem & item)48bool DumpTraceController::IsCpuLoadBackToNormal(CpuThresholdItem& item) 49 { 50 int32_t pid = CommonUtils::GetPidByName(item.processName); 51 if (pid <= 0) { 52 HIVIEW_LOGW("get pid failed, process:%{public}s", item.processName.c_str()); 53 return false; 54 } 55 auto cpuCollector = UCollectUtil::CpuCollector::Create(); 56 auto processCpuStatInfo = cpuCollector->CollectProcessCpuStatInfo(pid); 57 double cpuLoad = processCpuStatInfo.data.cpuLoad; 58 if (cpuLoad >= item.cpuLoadThreshold) { 59 item.hasOverThreshold = true; 60 return false; 61 } 62 if (item.hasOverThreshold && cpuLoad < item.cpuLoadThreshold) { 63 return true; 64 } 65 return false; 66 } 67 DumpTrace(CpuThresholdItem & item)68void DumpTraceController::DumpTrace(CpuThresholdItem& item) 69 { 70 auto traceCollector = UCollectUtil::TraceCollector::Create(); 71 traceCollector->DumpTrace(item.caller); 72 item.hasOverThreshold = false; 73 item.lastDumpTraceTime = TimeUtil::GetBootTimeMs() / static_cast<uint64_t>(TimeUtil::SEC_TO_MILLISEC); 74 } 75 } // namespace HiviewDFX 76 } // namespace OHOS 77