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