blob: a31904715d5f189775d86893f52a830248e4eb8c [file] [log] [blame]
Mike Yu939e3692019-10-29 17:28:34 +08001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 *
16 */
17
18#pragma once
19
20#include <deque>
21#include <string>
22#include <vector>
23
24#include <android-base/thread_annotations.h>
25#include <netdutils/DumpWriter.h>
26
27namespace android::net {
28
29// A circular buffer based class used for query logging. It's thread-safe for concurrent access.
30class DnsQueryLog {
31 public:
32 static constexpr std::string_view DUMP_KEYWORD = "querylog";
33
34 struct Record {
35 Record(uint32_t netId, uid_t uid, pid_t pid, const std::string& hostname,
36 const std::vector<std::string>& addrs, int timeTaken)
37 : netId(netId),
38 uid(uid),
39 pid(pid),
40 hostname(hostname),
41 addrs(addrs),
42 timeTaken(timeTaken) {}
43 const uint32_t netId;
44 const uid_t uid;
45 const pid_t pid;
46 const std::chrono::system_clock::time_point timestamp = std::chrono::system_clock::now();
47 const std::string hostname;
48 const std::vector<std::string> addrs;
49 const int timeTaken;
50 };
51
52 void push(Record&& record) EXCLUDES(mLock);
53 void dump(netdutils::DumpWriter& dw) const EXCLUDES(mLock);
54
55 private:
56 mutable std::mutex mLock;
57 std::deque<Record> mQueue GUARDED_BY(mLock);
58
59 // The capacity of the circular buffer.
60 static constexpr size_t kLogSize = 200;
61
62 // Limit to dump the queries within last |kValidityMinutes| minutes.
63 static constexpr std::chrono::minutes kValidityMinutes{60};
64};
65
66} // namespace android::net