1 /*
2  * Copyright (c) Huawei Technologies Co., Ltd. 2022. All rights reserved.
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 BPF_LOG_READER_H
17 #define BPF_LOG_READER_H
18 
19 #include <string>
20 #include <thread>
21 #include <memory>
22 
23 #include "bpf_log.h"
24 
25 class BPFLogReader {
26 public:
27     ~BPFLogReader();
28     static std::unique_ptr<BPFLogReader> MakeUnique(const std::string& logFile = "/data/local/tmp/bpf_log.txt");
Start()29     inline int Start()
30     {
31 #if defined(BPF_LOGGER_DEBUG) || defined(BPF_LOGGER_INFO) || defined(BPF_LOGGER_WARN) ||  \
32     defined(BPF_LOGGER_ERROR) || defined(BPF_LOGGER_FATAL)
33         worker_ = std::thread([this] { this->MoveBPFLog(); });
34 #endif
35         return 0;
36     }
Stop()37     inline int Stop()
38     {
39         stop_ = true;
40         return 0;
41     }
42 
43 private:
44     BPFLogReader() = default;
45     int OpenTracePipe();
46     int EnableTracePipe() const;
47     std::string GetLogFileName() const;
48     int OpenLogFile(const std::string& logFile);
49     int MoveBPFLog();
50 
51     const std::string confPath_ {"/sys/kernel/debug/tracing/tracing_on"};
52     const std::string pipePath_ {"/sys/kernel/debug/tracing/trace_pipe"};
53 
54     bool stop_ {false};
55     int ifd_ {-1};
56     int ofd_ {-1};
57     std::thread worker_;
58 };
59 #endif  // BPF_LOG_READER_H