blob: c2f71d1495208f0772e77c1770047bb91e3da4f1 [file] [log] [blame]
Mark Salyzyn0175b072014-02-26 09:50:16 -08001/*
2 * Copyright (C) 2012-2014 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
Mark Salyzyn671e3432014-05-06 07:34:59 -070017#include <ctype.h>
Mark Salyzyn202e1532015-02-09 08:21:05 -080018#include <errno.h>
Mark Salyzyn0175b072014-02-26 09:50:16 -080019#include <stdio.h>
20#include <string.h>
Mark Salyzyn57a0af92014-05-09 17:44:18 -070021#include <sys/user.h>
Mark Salyzyn0175b072014-02-26 09:50:16 -080022#include <time.h>
23#include <unistd.h>
24
Mark Salyzyn511338d2015-05-19 09:12:30 -070025#include <unordered_map>
26
Mark Salyzyn671e3432014-05-06 07:34:59 -070027#include <cutils/properties.h>
Mark Salyzyn0175b072014-02-26 09:50:16 -080028#include <log/logger.h>
29
30#include "LogBuffer.h"
Mark Salyzynb6bee332015-09-08 08:56:32 -070031#include "LogKlog.h"
Mark Salyzyn671e3432014-05-06 07:34:59 -070032#include "LogReader.h"
Mark Salyzyn0175b072014-02-26 09:50:16 -080033
Mark Salyzyndfa7a072014-02-11 12:29:31 -080034// Default
Mark Salyzyn0175b072014-02-26 09:50:16 -080035#define LOG_BUFFER_SIZE (256 * 1024) // Tuned on a per-platform basis here?
Mark Salyzyndfa7a072014-02-11 12:29:31 -080036#define log_buffer_size(id) mMaxSize[id]
Mark Salyzyn57a0af92014-05-09 17:44:18 -070037#define LOG_BUFFER_MIN_SIZE (64 * 1024UL)
38#define LOG_BUFFER_MAX_SIZE (256 * 1024 * 1024UL)
39
40static bool valid_size(unsigned long value) {
41 if ((value < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < value)) {
42 return false;
43 }
44
45 long pages = sysconf(_SC_PHYS_PAGES);
46 if (pages < 1) {
47 return true;
48 }
49
50 long pagesize = sysconf(_SC_PAGESIZE);
51 if (pagesize <= 1) {
52 pagesize = PAGE_SIZE;
53 }
54
55 // maximum memory impact a somewhat arbitrary ~3%
56 pages = (pages + 31) / 32;
57 unsigned long maximum = pages * pagesize;
58
59 if ((maximum < LOG_BUFFER_MIN_SIZE) || (LOG_BUFFER_MAX_SIZE < maximum)) {
60 return true;
61 }
62
63 return value <= maximum;
64}
Mark Salyzyn0175b072014-02-26 09:50:16 -080065
Mark Salyzyn671e3432014-05-06 07:34:59 -070066static unsigned long property_get_size(const char *key) {
67 char property[PROPERTY_VALUE_MAX];
68 property_get(key, property, "");
69
70 char *cp;
71 unsigned long value = strtoul(property, &cp, 10);
72
73 switch(*cp) {
74 case 'm':
75 case 'M':
76 value *= 1024;
77 /* FALLTHRU */
78 case 'k':
79 case 'K':
80 value *= 1024;
81 /* FALLTHRU */
82 case '\0':
83 break;
84
85 default:
86 value = 0;
87 }
88
Mark Salyzyn57a0af92014-05-09 17:44:18 -070089 if (!valid_size(value)) {
90 value = 0;
91 }
92
Mark Salyzyn671e3432014-05-06 07:34:59 -070093 return value;
94}
95
Mark Salyzyn11e55cb2015-03-10 16:45:17 -070096void LogBuffer::init() {
Mark Salyzyn57a0af92014-05-09 17:44:18 -070097 static const char global_tuneable[] = "persist.logd.size"; // Settings App
98 static const char global_default[] = "ro.logd.size"; // BoardConfig.mk
99
100 unsigned long default_size = property_get_size(global_tuneable);
101 if (!default_size) {
102 default_size = property_get_size(global_default);
103 }
Mark Salyzyn671e3432014-05-06 07:34:59 -0700104
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800105 log_id_for_each(i) {
Mark Salyzyn671e3432014-05-06 07:34:59 -0700106 char key[PROP_NAME_MAX];
Mark Salyzyn671e3432014-05-06 07:34:59 -0700107
Mark Salyzyn57a0af92014-05-09 17:44:18 -0700108 snprintf(key, sizeof(key), "%s.%s",
109 global_tuneable, android_log_id_to_name(i));
110 unsigned long property_size = property_get_size(key);
111
112 if (!property_size) {
113 snprintf(key, sizeof(key), "%s.%s",
114 global_default, android_log_id_to_name(i));
115 property_size = property_get_size(key);
116 }
117
118 if (!property_size) {
119 property_size = default_size;
120 }
121
122 if (!property_size) {
123 property_size = LOG_BUFFER_SIZE;
124 }
125
126 if (setSize(i, property_size)) {
127 setSize(i, LOG_BUFFER_MIN_SIZE);
128 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800129 }
Mark Salyzynb6bee332015-09-08 08:56:32 -0700130 bool lastMonotonic = monotonic;
131 monotonic = android_log_timestamp() == 'm';
132 if (lastMonotonic == monotonic) {
133 return;
134 }
135
136 //
137 // Fixup all timestamps, may not be 100% accurate, but better than
138 // throwing what we have away when we get 'surprised' by a change.
139 // In-place element fixup so no need to check reader-lock. Entries
140 // should already be in timestamp order, but we could end up with a
141 // few out-of-order entries if new monotonics come in before we
142 // are notified of the reinit change in status. A Typical example would
143 // be:
144 // --------- beginning of system
145 // 10.494082 184 201 D Cryptfs : Just triggered post_fs_data
146 // --------- beginning of kernel
147 // 0.000000 0 0 I : Initializing cgroup subsys cpuacct
148 // as the act of mounting /data would trigger persist.logd.timestamp to
149 // be corrected. 1/30 corner case YMMV.
150 //
151 pthread_mutex_lock(&mLogElementsLock);
152 LogBufferElementCollection::iterator it = mLogElements.begin();
153 while((it != mLogElements.end())) {
154 LogBufferElement *e = *it;
155 if (monotonic) {
156 if (!android::isMonotonic(e->mRealTime)) {
157 LogKlog::convertRealToMonotonic(e->mRealTime);
158 }
159 } else {
160 if (android::isMonotonic(e->mRealTime)) {
161 LogKlog::convertMonotonicToReal(e->mRealTime);
162 }
163 }
164 ++it;
165 }
166 pthread_mutex_unlock(&mLogElementsLock);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800167}
168
Mark Salyzynb6bee332015-09-08 08:56:32 -0700169LogBuffer::LogBuffer(LastLogTimes *times):
170 monotonic(android_log_timestamp() == 'm'),
171 mTimes(*times) {
Mark Salyzyn11e55cb2015-03-10 16:45:17 -0700172 pthread_mutex_init(&mLogElementsLock, NULL);
173
174 init();
175}
176
Mark Salyzyn202e1532015-02-09 08:21:05 -0800177int LogBuffer::log(log_id_t log_id, log_time realtime,
178 uid_t uid, pid_t pid, pid_t tid,
179 const char *msg, unsigned short len) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800180 if ((log_id >= LOG_ID_MAX) || (log_id < 0)) {
Mark Salyzyn202e1532015-02-09 08:21:05 -0800181 return -EINVAL;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800182 }
Mark Salyzyne59c4692014-10-02 13:07:05 -0700183
Mark Salyzyn0175b072014-02-26 09:50:16 -0800184 LogBufferElement *elem = new LogBufferElement(log_id, realtime,
Mark Salyzynb992d0d2014-03-20 16:09:38 -0700185 uid, pid, tid, msg, len);
Mark Salyzyne59c4692014-10-02 13:07:05 -0700186 int prio = ANDROID_LOG_INFO;
187 const char *tag = NULL;
188 if (log_id == LOG_ID_EVENTS) {
189 tag = android::tagToName(elem->getTag());
190 } else {
191 prio = *msg;
192 tag = msg + 1;
193 }
Mark Salyzyn7a2a3072015-11-06 12:26:52 -0800194 if (!__android_log_is_loggable(prio, tag,
195 ANDROID_LOG_VERBOSE |
196 ANDROID_LOGGABLE_FLAG_NOT_WITHIN_SIGNAL)) {
Mark Salyzyne59c4692014-10-02 13:07:05 -0700197 // Log traffic received to total
198 pthread_mutex_lock(&mLogElementsLock);
199 stats.add(elem);
200 stats.subtract(elem);
201 pthread_mutex_unlock(&mLogElementsLock);
202 delete elem;
203 return -EACCES;
204 }
Mark Salyzyn0175b072014-02-26 09:50:16 -0800205
206 pthread_mutex_lock(&mLogElementsLock);
207
208 // Insert elements in time sorted order if possible
209 // NB: if end is region locked, place element at end of list
210 LogBufferElementCollection::iterator it = mLogElements.end();
211 LogBufferElementCollection::iterator last = it;
Mark Salyzyneae155e2014-10-13 16:49:47 -0700212 while (last != mLogElements.begin()) {
213 --it;
Mark Salyzync03e72c2014-02-18 11:23:53 -0800214 if ((*it)->getRealTime() <= realtime) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800215 break;
216 }
217 last = it;
218 }
Mark Salyzync03e72c2014-02-18 11:23:53 -0800219
Mark Salyzyn0175b072014-02-26 09:50:16 -0800220 if (last == mLogElements.end()) {
221 mLogElements.push_back(elem);
222 } else {
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800223 uint64_t end = 1;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800224 bool end_set = false;
225 bool end_always = false;
226
227 LogTimeEntry::lock();
228
229 LastLogTimes::iterator t = mTimes.begin();
230 while(t != mTimes.end()) {
231 LogTimeEntry *entry = (*t);
232 if (entry->owned_Locked()) {
233 if (!entry->mNonBlock) {
234 end_always = true;
235 break;
236 }
237 if (!end_set || (end <= entry->mEnd)) {
238 end = entry->mEnd;
239 end_set = true;
240 }
241 }
242 t++;
243 }
244
245 if (end_always
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800246 || (end_set && (end >= (*last)->getSequence()))) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800247 mLogElements.push_back(elem);
248 } else {
249 mLogElements.insert(last,elem);
250 }
251
252 LogTimeEntry::unlock();
253 }
254
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700255 stats.add(elem);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800256 maybePrune(log_id);
257 pthread_mutex_unlock(&mLogElementsLock);
Mark Salyzyn202e1532015-02-09 08:21:05 -0800258
259 return len;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800260}
261
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700262// Prune at most 10% of the log entries or maxPrune, whichever is less.
Mark Salyzyn0175b072014-02-26 09:50:16 -0800263//
264// mLogElementsLock must be held when this function is called.
265void LogBuffer::maybePrune(log_id_t id) {
Mark Salyzyn34facab2014-02-06 14:48:50 -0800266 size_t sizes = stats.sizes(id);
Mark Salyzyn62ab0fd2015-08-10 10:23:56 -0700267 unsigned long maxSize = log_buffer_size(id);
268 if (sizes > maxSize) {
Mark Salyzynb39ed0c2015-08-19 12:20:36 -0700269 size_t sizeOver = sizes - ((maxSize * 9) / 10);
Mark Salyzyn58b8be82015-09-30 07:40:09 -0700270 size_t elements = stats.realElements(id);
271 size_t minElements = elements / 100;
272 if (minElements < minPrune) {
273 minElements = minPrune;
274 }
Mark Salyzyn62ab0fd2015-08-10 10:23:56 -0700275 unsigned long pruneRows = elements * sizeOver / sizes;
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700276 if (pruneRows < minElements) {
Mark Salyzyn62ab0fd2015-08-10 10:23:56 -0700277 pruneRows = minElements;
Mark Salyzyn740f9b42014-01-13 16:37:51 -0800278 }
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700279 if (pruneRows > maxPrune) {
280 pruneRows = maxPrune;
Mark Salyzynb39ed0c2015-08-19 12:20:36 -0700281 }
Mark Salyzyn740f9b42014-01-13 16:37:51 -0800282 prune(id, pruneRows);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800283 }
284}
285
Mark Salyzyn831aa292015-09-03 16:08:50 -0700286LogBufferElementCollection::iterator LogBuffer::erase(
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700287 LogBufferElementCollection::iterator it, bool coalesce) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700288 LogBufferElement *e = *it;
Mark Salyzync892ea32015-08-19 17:06:11 -0700289 log_id_t id = e->getLogId();
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700290
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700291 LogBufferIteratorMap::iterator f = mLastWorstUid[id].find(e->getUid());
Mark Salyzync892ea32015-08-19 17:06:11 -0700292 if ((f != mLastWorstUid[id].end()) && (it == f->second)) {
293 mLastWorstUid[id].erase(f);
294 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700295 it = mLogElements.erase(it);
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700296 if (coalesce) {
Mark Salyzyn831aa292015-09-03 16:08:50 -0700297 stats.erase(e);
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700298 } else {
299 stats.subtract(e);
Mark Salyzyn831aa292015-09-03 16:08:50 -0700300 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700301 delete e;
302
303 return it;
304}
305
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700306// Define a temporary mechanism to report the last LogBufferElement pointer
307// for the specified uid, pid and tid. Used below to help merge-sort when
308// pruning for worst UID.
309class LogBufferElementKey {
310 const union {
311 struct {
312 uint16_t uid;
313 uint16_t pid;
314 uint16_t tid;
315 uint16_t padding;
316 } __packed;
317 uint64_t value;
318 } __packed;
319
320public:
321 LogBufferElementKey(uid_t u, pid_t p, pid_t t):uid(u),pid(p),tid(t),padding(0) { }
322 LogBufferElementKey(uint64_t k):value(k) { }
323
324 uint64_t getKey() { return value; }
325};
326
Mark Salyzyn511338d2015-05-19 09:12:30 -0700327class LogBufferElementLast {
328
329 typedef std::unordered_map<uint64_t, LogBufferElement *> LogBufferElementMap;
330 LogBufferElementMap map;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700331
332public:
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700333
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700334 bool coalesce(LogBufferElement *e, unsigned short dropped) {
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700335 LogBufferElementKey key(e->getUid(), e->getPid(), e->getTid());
Mark Salyzyn511338d2015-05-19 09:12:30 -0700336 LogBufferElementMap::iterator it = map.find(key.getKey());
337 if (it != map.end()) {
338 LogBufferElement *l = it->second;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700339 unsigned short d = l->getDropped();
340 if ((dropped + d) > USHRT_MAX) {
Mark Salyzyn511338d2015-05-19 09:12:30 -0700341 map.erase(it);
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700342 } else {
343 l->setDropped(dropped + d);
344 return true;
345 }
346 }
347 return false;
348 }
349
Mark Salyzyn511338d2015-05-19 09:12:30 -0700350 void add(LogBufferElement *e) {
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700351 LogBufferElementKey key(e->getUid(), e->getPid(), e->getTid());
Mark Salyzyn511338d2015-05-19 09:12:30 -0700352 map[key.getKey()] = e;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700353 }
354
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700355 inline void clear() {
Mark Salyzyn511338d2015-05-19 09:12:30 -0700356 map.clear();
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700357 }
358
359 void clear(LogBufferElement *e) {
Mark Salyzyn047cc072015-06-04 13:35:30 -0700360 uint64_t current = e->getRealTime().nsec()
361 - (EXPIRE_RATELIMIT * NS_PER_SEC);
Mark Salyzyn511338d2015-05-19 09:12:30 -0700362 for(LogBufferElementMap::iterator it = map.begin(); it != map.end();) {
363 LogBufferElement *l = it->second;
Mark Salyzyn833a9b12015-05-15 15:58:17 -0700364 if ((l->getDropped() >= EXPIRE_THRESHOLD)
365 && (current > l->getRealTime().nsec())) {
Mark Salyzyn511338d2015-05-19 09:12:30 -0700366 it = map.erase(it);
367 } else {
368 ++it;
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700369 }
370 }
371 }
372
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700373};
374
Mark Salyzyn0175b072014-02-26 09:50:16 -0800375// prune "pruneRows" of type "id" from the buffer.
376//
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700377// This garbage collection task is used to expire log entries. It is called to
378// remove all logs (clear), all UID logs (unprivileged clear), or every
379// 256 or 10% of the total logs (whichever is less) to prune the logs.
380//
381// First there is a prep phase where we discover the reader region lock that
382// acts as a backstop to any pruning activity to stop there and go no further.
383//
384// There are three major pruning loops that follow. All expire from the oldest
385// entries. Since there are multiple log buffers, the Android logging facility
386// will appear to drop entries 'in the middle' when looking at multiple log
387// sources and buffers. This effect is slightly more prominent when we prune
388// the worst offender by logging source. Thus the logs slowly loose content
389// and value as you move back in time. This is preferred since chatty sources
390// invariably move the logs value down faster as less chatty sources would be
391// expired in the noise.
392//
393// The first loop performs blacklisting and worst offender pruning. Falling
394// through when there are no notable worst offenders and have not hit the
395// region lock preventing further worst offender pruning. This loop also looks
396// after managing the chatty log entries and merging to help provide
397// statistical basis for blame. The chatty entries are not a notification of
398// how much logs you may have, but instead represent how much logs you would
399// have had in a virtual log buffer that is extended to cover all the in-memory
400// logs without loss. They last much longer than the represented pruned logs
401// since they get multiplied by the gains in the non-chatty log sources.
402//
403// The second loop get complicated because an algorithm of watermarks and
404// history is maintained to reduce the order and keep processing time
405// down to a minimum at scale. These algorithms can be costly in the face
406// of larger log buffers, or severly limited processing time granted to a
407// background task at lowest priority.
408//
409// This second loop does straight-up expiration from the end of the logs
410// (again, remember for the specified log buffer id) but does some whitelist
411// preservation. Thus whitelist is a Hail Mary low priority, blacklists and
412// spam filtration all take priority. This second loop also checks if a region
413// lock is causing us to buffer too much in the logs to help the reader(s),
414// and will tell the slowest reader thread to skip log entries, and if
415// persistent and hits a further threshold, kill the reader thread.
416//
417// The third thread is optional, and only gets hit if there was a whitelist
418// and more needs to be pruned against the backstop of the region lock.
419//
Mark Salyzyn0175b072014-02-26 09:50:16 -0800420// mLogElementsLock must be held when this function is called.
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700421//
Mark Salyzync5dc9702015-09-16 15:34:00 -0700422bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800423 LogTimeEntry *oldest = NULL;
Mark Salyzync5dc9702015-09-16 15:34:00 -0700424 bool busy = false;
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700425 bool clearAll = pruneRows == ULONG_MAX;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800426
427 LogTimeEntry::lock();
428
429 // Region locked?
430 LastLogTimes::iterator t = mTimes.begin();
431 while(t != mTimes.end()) {
432 LogTimeEntry *entry = (*t);
TraianX Schiauda6495d2014-12-17 10:53:41 +0200433 if (entry->owned_Locked() && entry->isWatching(id)
Mark Salyzyn0175b072014-02-26 09:50:16 -0800434 && (!oldest || (oldest->mStart > entry->mStart))) {
435 oldest = entry;
436 }
437 t++;
438 }
439
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800440 LogBufferElementCollection::iterator it;
441
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700442 if (caller_uid != AID_ROOT) {
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700443 // Only here if clearAll condition (pruneRows == ULONG_MAX)
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700444 for(it = mLogElements.begin(); it != mLogElements.end();) {
445 LogBufferElement *e = *it;
446
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700447 if ((e->getLogId() != id) || (e->getUid() != caller_uid)) {
448 ++it;
449 continue;
450 }
451
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800452 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700453 oldest->triggerSkip_Locked(id, pruneRows);
454 busy = true;
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700455 break;
456 }
457
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700458 it = erase(it);
459 pruneRows--;
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700460 }
461 LogTimeEntry::unlock();
Mark Salyzync5dc9702015-09-16 15:34:00 -0700462 return busy;
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700463 }
464
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800465 // prune by worst offender by uid
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700466 bool hasBlacklist = mPrune.naughty();
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700467 while (!clearAll && (pruneRows > 0)) {
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800468 // recalculate the worst offender on every batched pass
469 uid_t worst = (uid_t) -1;
470 size_t worst_sizes = 0;
471 size_t second_worst_sizes = 0;
472
Mark Salyzynae769232015-03-17 17:17:25 -0700473 if (worstUidEnabledForLogid(id) && mPrune.worstUidEnabled()) {
Mark Salyzyn720f6d12015-03-16 08:26:05 -0700474 std::unique_ptr<const UidEntry *[]> sorted = stats.sort(2, id);
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700475
Mark Salyzyn720f6d12015-03-16 08:26:05 -0700476 if (sorted.get()) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700477 if (sorted[0] && sorted[1]) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700478 worst_sizes = sorted[0]->getSizes();
Mark Salyzynd717d802015-04-20 15:36:12 -0700479 // Calculate threshold as 12.5% of available storage
480 size_t threshold = log_buffer_size(id) / 8;
Mark Salyzyn50122692015-10-12 13:45:51 -0700481 if ((worst_sizes > threshold)
482 // Allow time horizon to extend roughly tenfold, assume
483 // average entry length is 100 characters.
484 && (worst_sizes > (10 * sorted[0]->getDropped()))) {
Mark Salyzynd717d802015-04-20 15:36:12 -0700485 worst = sorted[0]->getKey();
486 second_worst_sizes = sorted[1]->getSizes();
487 if (second_worst_sizes < threshold) {
488 second_worst_sizes = threshold;
489 }
490 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800491 }
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800492 }
493 }
494
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700495 // skip if we have neither worst nor naughty filters
496 if ((worst == (uid_t) -1) && !hasBlacklist) {
497 break;
498 }
499
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800500 bool kick = false;
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700501 bool leading = true;
Mark Salyzync892ea32015-08-19 17:06:11 -0700502 it = mLogElements.begin();
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700503 // Perform at least one mandatory garbage collection cycle in following
504 // - clear leading chatty tags
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700505 // - coalesce chatty tags
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700506 // - check age-out of preserved logs
507 bool gc = pruneRows <= 1;
508 if (!gc && (worst != (uid_t) -1)) {
Mark Salyzync892ea32015-08-19 17:06:11 -0700509 LogBufferIteratorMap::iterator f = mLastWorstUid[id].find(worst);
510 if ((f != mLastWorstUid[id].end())
511 && (f->second != mLogElements.end())) {
512 leading = false;
513 it = f->second;
514 }
515 }
Mark Salyzynccfe8442015-08-24 13:43:27 -0700516 static const timespec too_old = {
517 EXPIRE_HOUR_THRESHOLD * 60 * 60, 0
518 };
519 LogBufferElementCollection::iterator lastt;
520 lastt = mLogElements.end();
521 --lastt;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700522 LogBufferElementLast last;
Mark Salyzync892ea32015-08-19 17:06:11 -0700523 while (it != mLogElements.end()) {
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800524 LogBufferElement *e = *it;
525
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800526 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700527 busy = true;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800528 break;
529 }
530
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800531 if (e->getLogId() != id) {
532 ++it;
533 continue;
534 }
535
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700536 unsigned short dropped = e->getDropped();
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800537
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700538 // remove any leading drops
539 if (leading && dropped) {
540 it = erase(it);
541 continue;
542 }
543
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700544 if (dropped && last.coalesce(e, dropped)) {
545 it = erase(it, true);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700546 continue;
547 }
548
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700549 if (hasBlacklist && mPrune.naughty(e)) {
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700550 last.clear(e);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700551 it = erase(it);
552 if (dropped) {
553 continue;
554 }
555
556 pruneRows--;
557 if (pruneRows == 0) {
558 break;
559 }
560
561 if (e->getUid() == worst) {
562 kick = true;
563 if (worst_sizes < second_worst_sizes) {
564 break;
565 }
566 worst_sizes -= e->getMsgLen();
567 }
568 continue;
569 }
570
Mark Salyzynccfe8442015-08-24 13:43:27 -0700571 if ((e->getRealTime() < ((*lastt)->getRealTime() - too_old))
572 || (e->getRealTime() > (*lastt)->getRealTime())) {
573 break;
574 }
575
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700576 if (dropped) {
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700577 last.add(e);
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700578 if ((!gc && (e->getUid() == worst))
Mark Salyzyn49afe0d2015-08-24 13:43:27 -0700579 || (mLastWorstUid[id].find(e->getUid())
580 == mLastWorstUid[id].end())) {
581 mLastWorstUid[id][e->getUid()] = it;
582 }
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800583 ++it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700584 continue;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800585 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700586
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700587 if (e->getUid() != worst) {
Mark Salyzyn59212762015-06-01 09:41:19 -0700588 leading = false;
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700589 last.clear(e);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700590 ++it;
591 continue;
592 }
593
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700594 pruneRows--;
595 if (pruneRows == 0) {
596 break;
597 }
598
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700599 kick = true;
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700600
601 unsigned short len = e->getMsgLen();
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700602
603 // do not create any leading drops
604 if (leading) {
605 it = erase(it);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700606 } else {
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700607 stats.drop(e);
608 e->setDropped(1);
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700609 if (last.coalesce(e, 1)) {
610 it = erase(it, true);
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700611 } else {
612 last.add(e);
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700613 if (!gc || (mLastWorstUid[id].find(worst)
614 == mLastWorstUid[id].end())) {
615 mLastWorstUid[id][worst] = it;
616 }
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700617 ++it;
618 }
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700619 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700620 if (worst_sizes < second_worst_sizes) {
621 break;
622 }
623 worst_sizes -= len;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800624 }
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700625 last.clear();
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800626
Mark Salyzyn1c950472014-04-01 17:19:47 -0700627 if (!kick || !mPrune.worstUidEnabled()) {
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800628 break; // the following loop will ask bad clients to skip/drop
629 }
630 }
631
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800632 bool whitelist = false;
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700633 bool hasWhitelist = mPrune.nice() && !clearAll;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800634 it = mLogElements.begin();
Mark Salyzyn0175b072014-02-26 09:50:16 -0800635 while((pruneRows > 0) && (it != mLogElements.end())) {
636 LogBufferElement *e = *it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700637
638 if (e->getLogId() != id) {
639 it++;
640 continue;
641 }
642
643 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700644 busy = true;
645
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700646 if (whitelist) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800647 break;
648 }
Mark Salyzyn1c950472014-04-01 17:19:47 -0700649
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700650 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
651 // kick a misbehaving log reader client off the island
652 oldest->release_Locked();
653 } else {
654 oldest->triggerSkip_Locked(id, pruneRows);
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800655 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700656 break;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800657 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700658
Mark Salyzync5bf3b82015-05-21 12:50:31 -0700659 if (hasWhitelist && !e->getDropped() && mPrune.nice(e)) { // WhiteListed
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700660 whitelist = true;
661 it++;
662 continue;
663 }
664
665 it = erase(it);
666 pruneRows--;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800667 }
668
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700669 // Do not save the whitelist if we are reader range limited
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800670 if (whitelist && (pruneRows > 0)) {
671 it = mLogElements.begin();
672 while((it != mLogElements.end()) && (pruneRows > 0)) {
673 LogBufferElement *e = *it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700674
675 if (e->getLogId() != id) {
676 ++it;
677 continue;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800678 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700679
680 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700681 busy = true;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700682 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
683 // kick a misbehaving log reader client off the island
684 oldest->release_Locked();
685 } else {
686 oldest->triggerSkip_Locked(id, pruneRows);
687 }
688 break;
689 }
690
691 it = erase(it);
692 pruneRows--;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800693 }
694 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800695
Mark Salyzyn0175b072014-02-26 09:50:16 -0800696 LogTimeEntry::unlock();
Mark Salyzync5dc9702015-09-16 15:34:00 -0700697
698 return (pruneRows > 0) && busy;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800699}
700
701// clear all rows of type "id" from the buffer.
Mark Salyzync5dc9702015-09-16 15:34:00 -0700702bool LogBuffer::clear(log_id_t id, uid_t uid) {
703 bool busy = true;
704 // If it takes more than 4 tries (seconds) to clear, then kill reader(s)
705 for (int retry = 4;;) {
706 if (retry == 1) { // last pass
707 // Check if it is still busy after the sleep, we say prune
708 // one entry, not another clear run, so we are looking for
709 // the quick side effect of the return value to tell us if
710 // we have a _blocked_ reader.
711 pthread_mutex_lock(&mLogElementsLock);
712 busy = prune(id, 1, uid);
713 pthread_mutex_unlock(&mLogElementsLock);
714 // It is still busy, blocked reader(s), lets kill them all!
715 // otherwise, lets be a good citizen and preserve the slow
716 // readers and let the clear run (below) deal with determining
717 // if we are still blocked and return an error code to caller.
718 if (busy) {
719 LogTimeEntry::lock();
720 LastLogTimes::iterator times = mTimes.begin();
721 while (times != mTimes.end()) {
722 LogTimeEntry *entry = (*times);
723 // Killer punch
724 if (entry->owned_Locked() && entry->isWatching(id)) {
725 entry->release_Locked();
726 }
727 times++;
728 }
729 LogTimeEntry::unlock();
730 }
731 }
732 pthread_mutex_lock(&mLogElementsLock);
733 busy = prune(id, ULONG_MAX, uid);
734 pthread_mutex_unlock(&mLogElementsLock);
735 if (!busy || !--retry) {
736 break;
737 }
738 sleep (1); // Let reader(s) catch up after notification
739 }
740 return busy;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800741}
742
743// get the used space associated with "id".
744unsigned long LogBuffer::getSizeUsed(log_id_t id) {
745 pthread_mutex_lock(&mLogElementsLock);
Mark Salyzyn34facab2014-02-06 14:48:50 -0800746 size_t retval = stats.sizes(id);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800747 pthread_mutex_unlock(&mLogElementsLock);
748 return retval;
749}
750
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800751// set the total space allocated to "id"
752int LogBuffer::setSize(log_id_t id, unsigned long size) {
753 // Reasonable limits ...
Mark Salyzyn57a0af92014-05-09 17:44:18 -0700754 if (!valid_size(size)) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800755 return -1;
756 }
757 pthread_mutex_lock(&mLogElementsLock);
758 log_buffer_size(id) = size;
759 pthread_mutex_unlock(&mLogElementsLock);
760 return 0;
761}
762
763// get the total space allocated to "id"
764unsigned long LogBuffer::getSize(log_id_t id) {
765 pthread_mutex_lock(&mLogElementsLock);
766 size_t retval = log_buffer_size(id);
767 pthread_mutex_unlock(&mLogElementsLock);
768 return retval;
769}
770
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800771uint64_t LogBuffer::flushTo(
772 SocketClient *reader, const uint64_t start, bool privileged,
773 int (*filter)(const LogBufferElement *element, void *arg), void *arg) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800774 LogBufferElementCollection::iterator it;
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800775 uint64_t max = start;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800776 uid_t uid = reader->getUid();
777
778 pthread_mutex_lock(&mLogElementsLock);
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600779
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800780 if (start <= 1) {
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600781 // client wants to start from the beginning
782 it = mLogElements.begin();
783 } else {
784 // Client wants to start from some specified time. Chances are
785 // we are better off starting from the end of the time sorted list.
786 for (it = mLogElements.end(); it != mLogElements.begin(); /* do nothing */) {
787 --it;
788 LogBufferElement *element = *it;
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800789 if (element->getSequence() <= start) {
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600790 it++;
791 break;
792 }
793 }
794 }
795
796 for (; it != mLogElements.end(); ++it) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800797 LogBufferElement *element = *it;
798
799 if (!privileged && (element->getUid() != uid)) {
800 continue;
801 }
802
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800803 if (element->getSequence() <= start) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800804 continue;
805 }
806
807 // NB: calling out to another object with mLogElementsLock held (safe)
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800808 if (filter) {
809 int ret = (*filter)(element, arg);
810 if (ret == false) {
811 continue;
812 }
813 if (ret != true) {
814 break;
815 }
Mark Salyzyn0175b072014-02-26 09:50:16 -0800816 }
817
818 pthread_mutex_unlock(&mLogElementsLock);
819
820 // range locking in LastLogTimes looks after us
Mark Salyzyn21fb7e02015-04-20 07:26:27 -0700821 max = element->flushTo(reader, this);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800822
823 if (max == element->FLUSH_ERROR) {
824 return max;
825 }
826
827 pthread_mutex_lock(&mLogElementsLock);
828 }
829 pthread_mutex_unlock(&mLogElementsLock);
830
831 return max;
832}
Mark Salyzyn34facab2014-02-06 14:48:50 -0800833
Mark Salyzyn73160ac2015-08-20 10:01:44 -0700834std::string LogBuffer::formatStatistics(uid_t uid, unsigned int logMask) {
Mark Salyzyn34facab2014-02-06 14:48:50 -0800835 pthread_mutex_lock(&mLogElementsLock);
836
Mark Salyzyn73160ac2015-08-20 10:01:44 -0700837 std::string ret = stats.format(uid, logMask);
Mark Salyzyn34facab2014-02-06 14:48:50 -0800838
839 pthread_mutex_unlock(&mLogElementsLock);
Mark Salyzyn73160ac2015-08-20 10:01:44 -0700840
841 return ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800842}