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