1 /* 2 * Copyright (c) 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 #ifndef HIVIEW_THREAD_STATE_INFO_COLLECTOR_H 17 #define HIVIEW_THREAD_STATE_INFO_COLLECTOR_H 18 #include <mutex> 19 20 #include "cpu.h" 21 #include "collect_result.h" 22 #include "collect_device_client.h" 23 #include "cpu_calculator.h" 24 #include "cpu_collector.h" 25 26 namespace OHOS { 27 namespace HiviewDFX { 28 namespace UCollectUtil { 29 30 struct ThreadCpuTimeInfo { 31 uint64_t uUsageTime = 0; 32 uint64_t sUsageTime = 0; 33 uint64_t loadTime = 0; 34 uint64_t collectionTime = 0; 35 uint64_t collectionBootTime = 0; 36 }; 37 38 class ThreadStateInfoCollector : public ThreadCpuCollector { 39 public: 40 ThreadStateInfoCollector(std::shared_ptr<CollectDeviceClient> deviceClient, 41 std::shared_ptr<CpuCalculator> cpuCalculator, int collectPid); 42 explicit ThreadStateInfoCollector(int32_t collectPid); 43 virtual ~ThreadStateInfoCollector() = default; 44 45 public: 46 CollectResult<std::vector<ThreadCpuStatInfo>> CollectThreadStatInfos(bool isNeedUpdate) override; 47 int GetCollectPid() override; 48 49 private: 50 void InitLastThreadCpuTimeInfos(); 51 CalculationTimeInfo InitCalculationTimeInfo(); 52 std::shared_ptr<ThreadCpuData> FetchThreadCpuData(); 53 void UpdateLastThreadTimeInfo(const ucollection_thread_cpu_item* threadCpuItem, 54 const CalculationTimeInfo& calcTimeInfo); 55 void CalculateThreadCpuStatInfos(std::vector<ThreadCpuStatInfo>& ThreadCpuStatInfos, 56 std::shared_ptr<ThreadCpuData> ThreadCpuData, bool isNeedUpdate); 57 std::optional<ThreadCpuStatInfo> CalculateThreadCpuStatInfo( 58 const ucollection_thread_cpu_item* procCpuItem, const CalculationTimeInfo& calcTimeInfo); 59 void UpdateCollectionTime(const CalculationTimeInfo& calcTimeInfo); 60 void TryToDeleteDeadThreadInfo(); 61 void InitDeviceClient(); 62 63 private: 64 std::mutex collectMutex_; 65 uint64_t lastCollectionTime_ = 0; 66 uint64_t lastCollectionBootTime_ = 0; 67 std::shared_ptr<CollectDeviceClient> deviceClient_; 68 std::shared_ptr<CpuCalculator> cpuCalculator_; 69 std::unordered_map<int32_t, ThreadCpuTimeInfo> lastThreadCpuTimeInfos_; 70 int collectPid_ = 0; 71 }; 72 } // namespace UCollectUtil 73 } // namespace HiviewDFX 74 } // namespace OHOS 75 #endif //HIVIEW_THREAD_CPU_STATE_INFO_COLLECTOR_H 76