1 /*
2 * Copyright (c) 2021 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 #include <cstring>
17 #include <thread>
18 #include <vector>
19 #include <sys/time.h>
20 #include <regex>
21
22 #include <hilog_common.h>
23 #include <flow_control.h>
24 #include <log_timestamp.h>
25 #include <properties.h>
26 #include <log_utils.h>
27
28 #include "log_buffer.h"
29
30 namespace OHOS {
31 namespace HiviewDFX {
32 using namespace std;
33
34 static size_t g_maxBufferSizeByType[LOG_TYPE_MAX] = {262144, 262144, 262144, 262144, 262144};
35 static int GenerateHilogMsgInside(HilogMsg& hilogMsg, const string& msg, uint16_t logType);
36
HilogBuffer()37 HilogBuffer::HilogBuffer()
38 {
39 for (int i = 0; i < LOG_TYPE_MAX; i++) {
40 sizeByType[i] = 0;
41 }
42 InitBuffLen();
43 InitBuffHead();
44 }
45
InitBuffLen()46 void HilogBuffer::InitBuffLen()
47 {
48 size_t global_size = GetBufferSize(LOG_TYPE_MAX, false);
49 size_t persist_global_size = GetBufferSize(LOG_TYPE_MAX, true);
50 for (int i = 0; i < LOG_TYPE_MAX; i++) {
51 size_t size = GetBufferSize(i, false);
52 size_t persist_size = GetBufferSize(i, true);
53 SetBuffLen(i, global_size);
54 SetBuffLen(i, persist_global_size);
55 SetBuffLen(i, size);
56 SetBuffLen(i, persist_size);
57 }
58 }
59
InitBuffHead()60 void HilogBuffer::InitBuffHead()
61 {
62 const string msg = "========Zeroth log of type: ";
63 std::vector<char> buf(MAX_LOG_LEN, 0);
64 HilogMsg *headMsg = reinterpret_cast<HilogMsg *>(buf.data());
65
66 for (uint16_t i = 0; i < LOG_TYPE_MAX; i++) {
67 string typeStr = LogType2Str(i);
68 if (typeStr == "invalid") {
69 continue;
70 }
71 string tmpStr = msg + typeStr;
72 if (GenerateHilogMsgInside(*headMsg, tmpStr, i) == RET_SUCCESS) {
73 Insert(*headMsg);
74 }
75 }
76 }
77
~HilogBuffer()78 HilogBuffer::~HilogBuffer() {}
79
Insert(const HilogMsg & msg)80 size_t HilogBuffer::Insert(const HilogMsg& msg)
81 {
82 size_t elemSize = CONTENT_LEN((&msg)); /* include '\0' */
83
84 if (unlikely(msg.tag_len > MAX_TAG_LEN || msg.tag_len == 0 || elemSize > MAX_LOG_LEN || elemSize <= 0)) {
85 return 0;
86 }
87
88 LogMsgContainer &msgList = (msg.type == LOG_KMSG) ? hilogKlogList : hilogDataList;
89 {
90 std::lock_guard<decltype(hilogBufferMutex)> lock(hilogBufferMutex);
91
92 // Delete old entries when full
93 if (elemSize + sizeByType[msg.type] >= g_maxBufferSizeByType[msg.type]) {
94 // Drop 5% of maximum log when full
95 std::list<HilogData>::iterator it = msgList.begin();
96 static const float DROP_RATIO = 0.05;
97 while (sizeByType[msg.type] > g_maxBufferSizeByType[msg.type] * (1 - DROP_RATIO) &&
98 it != msgList.end()) {
99 if ((*it).type != msg.type) { // Only remove old logs of the same type
100 ++it;
101 continue;
102 }
103 OnDeleteItem(it, DeleteReason::BUFF_OVERFLOW);
104 size_t cLen = it->len - it->tag_len;
105 sizeByType[(*it).type] -= cLen;
106 it = msgList.erase(it);
107 }
108
109 // Re-confirm if enough elements has been removed
110 if (sizeByType[msg.type] >= g_maxBufferSizeByType[msg.type]) {
111 std::cout << "Failed to clean old logs." << std::endl;
112 }
113 }
114
115 // Append new log into HilogBuffer
116 msgList.emplace_back(msg);
117 OnPushBackedItem(msgList);
118 }
119
120 // Update current size of HilogBuffer
121 sizeByType[msg.type] += elemSize;
122
123 // Notify readers about new element added
124 OnNewItem(msgList);
125 return elemSize;
126 }
127
LogMatchFilter(const LogFilter & filter,const HilogData & logData)128 static bool LogMatchFilter(const LogFilter& filter, const HilogData& logData)
129 {
130 // types & levels match
131 if (((static_cast<uint16_t>(0b01 << logData.type)) & filter.types) == 0) {
132 return false;
133 }
134 if (((static_cast<uint16_t>(0b01 << logData.level)) & filter.levels) == 0) {
135 return false;
136 }
137
138 int i = 0;
139 // domain match
140 static constexpr uint32_t LOW_BYTE = 0xFF;
141 static constexpr uint32_t LOW_BYTE_REVERSE = ~LOW_BYTE;
142 /* 1) domain id equals exactly: (0xd012345 == 0xd012345)
143 2) last 8 bits is sub domain id, if it's 0xFF, compare high 24 bits:
144 (0xd0123ff & 0xffffff00 == 0xd012345 & 0xffffff00) */
145 bool match = false;
146 for (i = 0; i < filter.domainCount; i++) {
147 if ((logData.domain == filter.domains[i])
148 || ((static_cast<uint8_t>(filter.domains[i]) == LOW_BYTE)
149 && ((logData.domain & LOW_BYTE_REVERSE) == (filter.domains[i] & LOW_BYTE_REVERSE)))) {
150 match = true;
151 break;
152 }
153 }
154 if (filter.domainCount && match == filter.blackDomain) {
155 return false;
156 }
157 match = false;
158 // tag match
159 for (i = 0; i < filter.tagCount; i++) {
160 if (strcmp(logData.tag, filter.tags[i]) == 0) {
161 match = true;
162 break;
163 }
164 }
165 if (filter.tagCount && match == filter.blackTag) {
166 return false;
167 }
168 match = false;
169 // pid match
170 for (i = 0; i < filter.pidCount; i++) {
171 if (logData.pid == filter.pids[i]) {
172 match = true;
173 break;
174 }
175 }
176 if (filter.pidCount && match == filter.blackPid) {
177 return false;
178 }
179 // regular expression match
180 if (filter.regex[0] != 0) {
181 std::regex regExpress(filter.regex);
182 if (std::regex_search(logData.content, regExpress) == false) {
183 return false;
184 }
185 }
186 return true;
187 }
188
Query(const LogFilter & filter,const ReaderId & id,int tailCount)189 std::optional<HilogData> HilogBuffer::Query(const LogFilter& filter, const ReaderId& id, int tailCount)
190 {
191 auto reader = GetReader(id);
192 if (!reader) {
193 std::cerr << "Reader not registered!\n";
194 return std::nullopt;
195 }
196 uint16_t qTypes = filter.types;
197 LogMsgContainer &msgList = (qTypes == (0b01 << LOG_KMSG)) ? hilogKlogList : hilogDataList;
198
199 std::shared_lock<decltype(hilogBufferMutex)> lock(hilogBufferMutex);
200
201 if (reader->m_msgList != &msgList) {
202 reader->m_msgList = &msgList;
203 if (tailCount == 0) {
204 reader->m_pos = msgList.begin();
205 } else {
206 reader->m_pos = msgList.end();
207 reader->m_pos--;
208 }
209 for (int i = 0; (i < tailCount) && (reader->m_pos != msgList.begin());) {
210 if (LogMatchFilter(filter, (*reader->m_pos))) {
211 i++;
212 }
213 reader->m_pos--;
214 }
215 }
216
217 if (reader->skipped) {
218 const string msg = "========Slow reader missed log lines: ";
219 const string tmpStr = msg + to_string(reader->skipped);
220 std::vector<char> buf(MAX_LOG_LEN, 0);
221 HilogMsg *headMsg = reinterpret_cast<HilogMsg *>(buf.data());
222 if (GenerateHilogMsgInside(*headMsg, tmpStr, LOG_CORE) == RET_SUCCESS) {
223 const HilogData logData(*headMsg);
224 reader->skipped = 0;
225 return logData;
226 }
227 }
228
229 while (reader->m_pos != msgList.end()) {
230 const HilogData& logData = *reader->m_pos;
231 reader->m_pos++;
232 if (LogMatchFilter(filter, logData)) {
233 return logData;
234 }
235 }
236 return std::nullopt;
237 }
238
Delete(uint16_t logType)239 int32_t HilogBuffer::Delete(uint16_t logType)
240 {
241 std::list<HilogData> &msgList = (logType == LOG_KMSG) ? hilogKlogList : hilogDataList;
242 if (logType >= LOG_TYPE_MAX) {
243 return ERR_LOG_TYPE_INVALID;
244 }
245 size_t sum = 0;
246 std::unique_lock<decltype(hilogBufferMutex)> lock(hilogBufferMutex);
247 std::list<HilogData>::iterator it = msgList.begin();
248
249 // Delete logs corresponding to queryCondition
250 while (it != msgList.end()) {
251 // Only remove old logs of the same type
252 if ((*it).type != logType) {
253 ++it;
254 continue;
255 }
256 // Delete corresponding logs
257 OnDeleteItem(it, DeleteReason::CMD_CLEAR);
258
259 size_t cLen = it->len - it->tag_len;
260 sum += cLen;
261 sizeByType[(*it).type] -= cLen;
262 it = msgList.erase(it);
263 }
264 return sum;
265 }
266
CreateBufReader(std::function<void ()> onNewDataCallback)267 HilogBuffer::ReaderId HilogBuffer::CreateBufReader(std::function<void()> onNewDataCallback)
268 {
269 std::unique_lock<decltype(m_logReaderMtx)> lock(m_logReaderMtx);
270 auto reader = std::make_shared<BufferReader>();
271 if (reader != nullptr) {
272 reader->skipped = 0;
273 reader->m_onNewDataCallback = onNewDataCallback;
274 }
275 ReaderId id = reinterpret_cast<ReaderId>(reader.get());
276 m_logReaders.insert(std::make_pair(id, reader));
277 return id;
278 }
279
RemoveBufReader(const ReaderId & id)280 void HilogBuffer::RemoveBufReader(const ReaderId& id)
281 {
282 std::unique_lock<decltype(m_logReaderMtx)> lock(m_logReaderMtx);
283 auto it = m_logReaders.find(id);
284 if (it != m_logReaders.end()) {
285 m_logReaders.erase(it);
286 }
287 }
288
OnDeleteItem(LogMsgContainer::iterator itemPos,DeleteReason reason)289 void HilogBuffer::OnDeleteItem(LogMsgContainer::iterator itemPos, DeleteReason reason)
290 {
291 std::shared_lock<decltype(m_logReaderMtx)> lock(m_logReaderMtx);
292 for (auto& [id, readerPtr] : m_logReaders) {
293 if (readerPtr->m_pos == itemPos) {
294 readerPtr->m_pos = std::next(itemPos);
295 if (reason == DeleteReason::BUFF_OVERFLOW) {
296 readerPtr->skipped++;
297 }
298 }
299 }
300 }
301
OnPushBackedItem(LogMsgContainer & msgList)302 void HilogBuffer::OnPushBackedItem(LogMsgContainer& msgList)
303 {
304 std::shared_lock<decltype(m_logReaderMtx)> lock(m_logReaderMtx);
305 for (auto& [id, readerPtr] : m_logReaders) {
306 if (readerPtr->m_pos == msgList.end()) {
307 readerPtr->m_pos = std::prev(msgList.end());
308 }
309 }
310 }
311
OnNewItem(LogMsgContainer & msgList)312 void HilogBuffer::OnNewItem(LogMsgContainer& msgList)
313 {
314 std::shared_lock<decltype(m_logReaderMtx)> lock(m_logReaderMtx);
315 for (auto& [id, readerPtr] : m_logReaders) {
316 if (readerPtr->m_msgList == &msgList && readerPtr->m_onNewDataCallback) {
317 readerPtr->m_onNewDataCallback();
318 }
319 }
320 }
321
GetReader(const ReaderId & id)322 std::shared_ptr<HilogBuffer::BufferReader> HilogBuffer::GetReader(const ReaderId& id)
323 {
324 std::shared_lock<decltype(m_logReaderMtx)> lock(m_logReaderMtx);
325 auto it = m_logReaders.find(id);
326 if (it != m_logReaders.end()) {
327 return it->second;
328 }
329 return std::shared_ptr<HilogBuffer::BufferReader>();
330 }
331
GetBuffLen(uint16_t logType)332 int64_t HilogBuffer::GetBuffLen(uint16_t logType)
333 {
334 if (logType >= LOG_TYPE_MAX) {
335 return ERR_LOG_TYPE_INVALID;
336 }
337 uint64_t buffSize = g_maxBufferSizeByType[logType];
338 return buffSize;
339 }
340
SetBuffLen(uint16_t logType,uint64_t buffSize)341 int32_t HilogBuffer::SetBuffLen(uint16_t logType, uint64_t buffSize)
342 {
343 if (logType >= LOG_TYPE_MAX) {
344 return ERR_LOG_TYPE_INVALID;
345 }
346 if (buffSize < MIN_BUFFER_SIZE || buffSize > MAX_BUFFER_SIZE) {
347 return ERR_BUFF_SIZE_INVALID;
348 }
349 std::unique_lock<decltype(hilogBufferMutex)> lock(hilogBufferMutex);
350 g_maxBufferSizeByType[logType] = buffSize;
351 return RET_SUCCESS;
352 }
353
CountLog(const StatsInfo & info)354 void HilogBuffer::CountLog(const StatsInfo &info)
355 {
356 stats.Count(info);
357 }
358
ResetStats()359 void HilogBuffer::ResetStats()
360 {
361 stats.Reset();
362 }
363
GetStatsInfo()364 LogStats& HilogBuffer::GetStatsInfo()
365 {
366 return stats;
367 }
368
GenerateHilogMsgInside(HilogMsg & hilogMsg,const string & msg,uint16_t logType)369 static int GenerateHilogMsgInside(HilogMsg& hilogMsg, const string& msg, uint16_t logType)
370 {
371 const string tag = "HiLog";
372 size_t contentLen = tag.length() + 1 + msg.length() + 1;
373 hilogMsg.len = static_cast<uint16_t>(sizeof(HilogMsg) + contentLen);
374 hilogMsg.len = hilogMsg.len > MAX_LOG_LEN ? MAX_LOG_LEN : hilogMsg.len;
375 contentLen = hilogMsg.len - static_cast<uint16_t>(sizeof(HilogMsg));
376
377 struct timespec ts = {0};
378 (void)clock_gettime(CLOCK_REALTIME, &ts);
379 struct timespec ts_mono = {0};
380 (void)clock_gettime(CLOCK_MONOTONIC, &ts_mono);
381 hilogMsg.tv_sec = static_cast<uint32_t>(ts.tv_sec);
382 hilogMsg.tv_nsec = static_cast<uint32_t>(ts.tv_nsec);
383 hilogMsg.mono_sec = static_cast<uint32_t>(ts_mono.tv_nsec);
384 hilogMsg.type = logType;
385 hilogMsg.level = LOG_INFO;
386 hilogMsg.pid = 0;
387 hilogMsg.tid = 0;
388 hilogMsg.domain = 0;
389 hilogMsg.tag_len = tag.length() + 1;
390 if (memcpy_s(hilogMsg.tag, contentLen, tag.c_str(), hilogMsg.tag_len) != 0) {
391 return RET_FAIL;
392 }
393 if (memcpy_s(hilogMsg.tag + hilogMsg.tag_len, contentLen - hilogMsg.tag_len, msg.c_str(), msg.length() + 1) != 0) {
394 return RET_FAIL;
395 }
396
397 return RET_SUCCESS;
398 }
399 } // namespace HiviewDFX
400 } // namespace OHOS
401