1 /* 2 * Copyright (c) 2021-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 #ifndef HIVIEW_BASE_AUDIT_H 16 #define HIVIEW_BASE_AUDIT_H 17 #include <atomic> 18 #include <fstream> 19 #include <list> 20 #include <mutex> 21 #include <string> 22 23 #include "singleton.h" 24 25 #include "unique_fd.h" 26 namespace OHOS { 27 namespace HiviewDFX { 28 class Audit : public Singleton<Audit> { 29 public: Audit()30 Audit() : init_(false), useBak_(false), enabled_(false) {}; 31 ~Audit(); 32 enum StatsEvent { 33 QUEUE_EVENT_IN = 0, 34 QUEUE_EVENT_OUT, 35 PIPELINE_EVENT_CREATE, 36 PIPELINE_EVENT_HANDLE_IN, 37 PIPELINE_EVENT_HANDLE_OUT, 38 PIPELINE_EVENT_DONE, 39 PRIVATE_AUDIT_EVENT_TYPE 40 }; 41 42 // the format of the normal event digestion should be 1.sender 2.processor 3.thread 4.detailed event info 43 static bool WriteAuditEvent(StatsEvent eventType, uint64_t eventId, const std::string& digest = ""); 44 45 // get a copy of the audit log 46 // if loadFromFile is enabled, log store in the disk will be inserted into the front of current logs 47 static bool GetAuditLog(bool loadFromFile, std::list<std::string>& ret); 48 49 static bool IsEnabled(); 50 51 // clear all logs 52 void Clear(); 53 54 // judge the version and do some initialization 55 void Init(bool isBeta); 56 57 static constexpr char DOMAIN_DELIMITER = '|'; 58 private: 59 bool IsActiveLogFileSizeReachTheashold(); 60 bool ReadLogFromFile(const std::string& path, std::list<std::string>& ret); 61 bool IsBackupFileActive(); 62 const std::string GetLogFilePath(bool active); 63 void GetAuditLogInner(bool loadFromFile, std::list<std::string>& ret); 64 void SaveToFileLocked(const std::string& content); 65 void SwitchActiveFile(); 66 void WriteEvent(const std::string& content); 67 bool init_; 68 bool useBak_; 69 bool enabled_; 70 UniqueFd writeFd_; 71 std::mutex mutex_; 72 std::once_flag initFlag_; 73 std::atomic<uint32_t> writeLogCount_; 74 static constexpr uint32_t MAX_MEMORY_LOG_COUNT = 1024; // 1024 lines 75 static constexpr uint32_t MAX_DISK_LOG_SIZE = 1024 * 512; // 512KB 76 static constexpr uint32_t MAX_AUDIT_LOG_SIZE = 1024; // 1024 byte 77 }; 78 } // namespace HiviewDFX 79 } // namespace OHOS 80 #endif // HIVIEW_BASE_AUDIT_H