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 HIAPPEVENT_UTIL_H_ 17 #define HIAPPEVENT_UTIL_H_ 18 #include <cstdint> 19 #include <memory> 20 #include <mutex> 21 #include <string> 22 #include <vector> 23 24 #include "hidebug_util.h" 25 26 namespace OHOS { 27 namespace HiviewDFX { 28 29 class ApiRecordReporter { 30 public: 31 virtual ~ApiRecordReporter() = default; 32 virtual void ReportRecord(const std::string& apiName, int errorCode, int64_t beginTime, int64_t endTime) = 0; 33 static void InitProcessor(); 34 protected: 35 static int64_t processId_; 36 }; 37 38 class SingleRecordReporter final : public ApiRecordReporter { 39 public: 40 static SingleRecordReporter& GetInstance(); 41 SingleRecordReporter(const SingleRecordReporter&) = delete; 42 SingleRecordReporter& operator=(const SingleRecordReporter&) = delete; 43 SingleRecordReporter(SingleRecordReporter&&) = delete; 44 SingleRecordReporter& operator=(SingleRecordReporter&&) = delete; 45 void ReportRecord(const std::string& apiName, int errorCode, int64_t beginTime, int64_t endTime) override; 46 private: 47 SingleRecordReporter() = default; 48 ~SingleRecordReporter() override = default; 49 }; 50 51 class MultipleRecordReporter final : public ApiRecordReporter { 52 public: 53 MultipleRecordReporter(uint32_t timeout, uint32_t limitValue); 54 void ReportRecord(const std::string& apiName, int errorCode, int64_t beginTime, int64_t endTime) override; 55 private: 56 void UploadRecordData(const std::string& apiName) const; 57 std::mutex mutex_; 58 const uint32_t timeout_; 59 const uint32_t limitValue_; 60 int64_t lastReportTime_{GetElapsedNanoSecondsSinceBoot()}; 61 int64_t totalCostTime_{0}; 62 int64_t maxCostTime_{std::numeric_limits<int64_t>::min()}; 63 int64_t minCostTime_{std::numeric_limits<int64_t>::max()};; 64 std::vector<int32_t> records_{}; 65 }; 66 67 class ApiInvokeRecorder { 68 public: 69 explicit ApiInvokeRecorder(std::string apiName, ApiRecordReporter& reporter = SingleRecordReporter::GetInstance()); 70 ~ApiInvokeRecorder(); 71 void SetErrorCode(int errorCode); 72 73 private: 74 std::string apiName_; 75 int errorCode_{0}; 76 int64_t beginTime_; 77 ApiRecordReporter& reporter_; 78 }; 79 } 80 } 81 #endif // HIAPPEVENT_UTIL_H_ 82