blob: c661203fc4f1be9fd1ac6c653f9cca5f95f2044f [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 }
194 if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
195 // Log traffic received to total
196 pthread_mutex_lock(&mLogElementsLock);
197 stats.add(elem);
198 stats.subtract(elem);
199 pthread_mutex_unlock(&mLogElementsLock);
200 delete elem;
201 return -EACCES;
202 }
Mark Salyzyn0175b072014-02-26 09:50:16 -0800203
204 pthread_mutex_lock(&mLogElementsLock);
205
206 // Insert elements in time sorted order if possible
207 // NB: if end is region locked, place element at end of list
208 LogBufferElementCollection::iterator it = mLogElements.end();
209 LogBufferElementCollection::iterator last = it;
Mark Salyzyneae155e2014-10-13 16:49:47 -0700210 while (last != mLogElements.begin()) {
211 --it;
Mark Salyzync03e72c2014-02-18 11:23:53 -0800212 if ((*it)->getRealTime() <= realtime) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800213 break;
214 }
215 last = it;
216 }
Mark Salyzync03e72c2014-02-18 11:23:53 -0800217
Mark Salyzyn0175b072014-02-26 09:50:16 -0800218 if (last == mLogElements.end()) {
219 mLogElements.push_back(elem);
220 } else {
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800221 uint64_t end = 1;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800222 bool end_set = false;
223 bool end_always = false;
224
225 LogTimeEntry::lock();
226
227 LastLogTimes::iterator t = mTimes.begin();
228 while(t != mTimes.end()) {
229 LogTimeEntry *entry = (*t);
230 if (entry->owned_Locked()) {
231 if (!entry->mNonBlock) {
232 end_always = true;
233 break;
234 }
235 if (!end_set || (end <= entry->mEnd)) {
236 end = entry->mEnd;
237 end_set = true;
238 }
239 }
240 t++;
241 }
242
243 if (end_always
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800244 || (end_set && (end >= (*last)->getSequence()))) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800245 mLogElements.push_back(elem);
246 } else {
247 mLogElements.insert(last,elem);
248 }
249
250 LogTimeEntry::unlock();
251 }
252
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700253 stats.add(elem);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800254 maybePrune(log_id);
255 pthread_mutex_unlock(&mLogElementsLock);
Mark Salyzyn202e1532015-02-09 08:21:05 -0800256
257 return len;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800258}
259
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700260// Prune at most 10% of the log entries or maxPrune, whichever is less.
Mark Salyzyn0175b072014-02-26 09:50:16 -0800261//
262// mLogElementsLock must be held when this function is called.
263void LogBuffer::maybePrune(log_id_t id) {
Mark Salyzyn34facab2014-02-06 14:48:50 -0800264 size_t sizes = stats.sizes(id);
Mark Salyzyn62ab0fd2015-08-10 10:23:56 -0700265 unsigned long maxSize = log_buffer_size(id);
266 if (sizes > maxSize) {
Mark Salyzynb39ed0c2015-08-19 12:20:36 -0700267 size_t sizeOver = sizes - ((maxSize * 9) / 10);
Mark Salyzyn58b8be82015-09-30 07:40:09 -0700268 size_t elements = stats.realElements(id);
269 size_t minElements = elements / 100;
270 if (minElements < minPrune) {
271 minElements = minPrune;
272 }
Mark Salyzyn62ab0fd2015-08-10 10:23:56 -0700273 unsigned long pruneRows = elements * sizeOver / sizes;
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700274 if (pruneRows < minElements) {
Mark Salyzyn62ab0fd2015-08-10 10:23:56 -0700275 pruneRows = minElements;
Mark Salyzyn740f9b42014-01-13 16:37:51 -0800276 }
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700277 if (pruneRows > maxPrune) {
278 pruneRows = maxPrune;
Mark Salyzynb39ed0c2015-08-19 12:20:36 -0700279 }
Mark Salyzyn740f9b42014-01-13 16:37:51 -0800280 prune(id, pruneRows);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800281 }
282}
283
Mark Salyzyn831aa292015-09-03 16:08:50 -0700284LogBufferElementCollection::iterator LogBuffer::erase(
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700285 LogBufferElementCollection::iterator it, bool coalesce) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700286 LogBufferElement *e = *it;
Mark Salyzync892ea32015-08-19 17:06:11 -0700287 log_id_t id = e->getLogId();
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700288
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700289 LogBufferIteratorMap::iterator f = mLastWorstUid[id].find(e->getUid());
Mark Salyzync892ea32015-08-19 17:06:11 -0700290 if ((f != mLastWorstUid[id].end()) && (it == f->second)) {
291 mLastWorstUid[id].erase(f);
292 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700293 it = mLogElements.erase(it);
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700294 if (coalesce) {
Mark Salyzyn831aa292015-09-03 16:08:50 -0700295 stats.erase(e);
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700296 } else {
297 stats.subtract(e);
Mark Salyzyn831aa292015-09-03 16:08:50 -0700298 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700299 delete e;
300
301 return it;
302}
303
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700304// Define a temporary mechanism to report the last LogBufferElement pointer
305// for the specified uid, pid and tid. Used below to help merge-sort when
306// pruning for worst UID.
307class LogBufferElementKey {
308 const union {
309 struct {
310 uint16_t uid;
311 uint16_t pid;
312 uint16_t tid;
313 uint16_t padding;
314 } __packed;
315 uint64_t value;
316 } __packed;
317
318public:
319 LogBufferElementKey(uid_t u, pid_t p, pid_t t):uid(u),pid(p),tid(t),padding(0) { }
320 LogBufferElementKey(uint64_t k):value(k) { }
321
322 uint64_t getKey() { return value; }
323};
324
Mark Salyzyn511338d2015-05-19 09:12:30 -0700325class LogBufferElementLast {
326
327 typedef std::unordered_map<uint64_t, LogBufferElement *> LogBufferElementMap;
328 LogBufferElementMap map;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700329
330public:
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700331
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700332 bool coalesce(LogBufferElement *e, unsigned short dropped) {
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700333 LogBufferElementKey key(e->getUid(), e->getPid(), e->getTid());
Mark Salyzyn511338d2015-05-19 09:12:30 -0700334 LogBufferElementMap::iterator it = map.find(key.getKey());
335 if (it != map.end()) {
336 LogBufferElement *l = it->second;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700337 unsigned short d = l->getDropped();
338 if ((dropped + d) > USHRT_MAX) {
Mark Salyzyn511338d2015-05-19 09:12:30 -0700339 map.erase(it);
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700340 } else {
341 l->setDropped(dropped + d);
342 return true;
343 }
344 }
345 return false;
346 }
347
Mark Salyzyn511338d2015-05-19 09:12:30 -0700348 void add(LogBufferElement *e) {
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700349 LogBufferElementKey key(e->getUid(), e->getPid(), e->getTid());
Mark Salyzyn511338d2015-05-19 09:12:30 -0700350 map[key.getKey()] = e;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700351 }
352
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700353 inline void clear() {
Mark Salyzyn511338d2015-05-19 09:12:30 -0700354 map.clear();
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700355 }
356
357 void clear(LogBufferElement *e) {
Mark Salyzyn047cc072015-06-04 13:35:30 -0700358 uint64_t current = e->getRealTime().nsec()
359 - (EXPIRE_RATELIMIT * NS_PER_SEC);
Mark Salyzyn511338d2015-05-19 09:12:30 -0700360 for(LogBufferElementMap::iterator it = map.begin(); it != map.end();) {
361 LogBufferElement *l = it->second;
Mark Salyzyn833a9b12015-05-15 15:58:17 -0700362 if ((l->getDropped() >= EXPIRE_THRESHOLD)
363 && (current > l->getRealTime().nsec())) {
Mark Salyzyn511338d2015-05-19 09:12:30 -0700364 it = map.erase(it);
365 } else {
366 ++it;
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700367 }
368 }
369 }
370
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700371};
372
Mark Salyzyn0175b072014-02-26 09:50:16 -0800373// prune "pruneRows" of type "id" from the buffer.
374//
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700375// This garbage collection task is used to expire log entries. It is called to
376// remove all logs (clear), all UID logs (unprivileged clear), or every
377// 256 or 10% of the total logs (whichever is less) to prune the logs.
378//
379// First there is a prep phase where we discover the reader region lock that
380// acts as a backstop to any pruning activity to stop there and go no further.
381//
382// There are three major pruning loops that follow. All expire from the oldest
383// entries. Since there are multiple log buffers, the Android logging facility
384// will appear to drop entries 'in the middle' when looking at multiple log
385// sources and buffers. This effect is slightly more prominent when we prune
386// the worst offender by logging source. Thus the logs slowly loose content
387// and value as you move back in time. This is preferred since chatty sources
388// invariably move the logs value down faster as less chatty sources would be
389// expired in the noise.
390//
391// The first loop performs blacklisting and worst offender pruning. Falling
392// through when there are no notable worst offenders and have not hit the
393// region lock preventing further worst offender pruning. This loop also looks
394// after managing the chatty log entries and merging to help provide
395// statistical basis for blame. The chatty entries are not a notification of
396// how much logs you may have, but instead represent how much logs you would
397// have had in a virtual log buffer that is extended to cover all the in-memory
398// logs without loss. They last much longer than the represented pruned logs
399// since they get multiplied by the gains in the non-chatty log sources.
400//
401// The second loop get complicated because an algorithm of watermarks and
402// history is maintained to reduce the order and keep processing time
403// down to a minimum at scale. These algorithms can be costly in the face
404// of larger log buffers, or severly limited processing time granted to a
405// background task at lowest priority.
406//
407// This second loop does straight-up expiration from the end of the logs
408// (again, remember for the specified log buffer id) but does some whitelist
409// preservation. Thus whitelist is a Hail Mary low priority, blacklists and
410// spam filtration all take priority. This second loop also checks if a region
411// lock is causing us to buffer too much in the logs to help the reader(s),
412// and will tell the slowest reader thread to skip log entries, and if
413// persistent and hits a further threshold, kill the reader thread.
414//
415// The third thread is optional, and only gets hit if there was a whitelist
416// and more needs to be pruned against the backstop of the region lock.
417//
Mark Salyzyn0175b072014-02-26 09:50:16 -0800418// mLogElementsLock must be held when this function is called.
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700419//
Mark Salyzync5dc9702015-09-16 15:34:00 -0700420bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800421 LogTimeEntry *oldest = NULL;
Mark Salyzync5dc9702015-09-16 15:34:00 -0700422 bool busy = false;
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700423 bool clearAll = pruneRows == ULONG_MAX;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800424
425 LogTimeEntry::lock();
426
427 // Region locked?
428 LastLogTimes::iterator t = mTimes.begin();
429 while(t != mTimes.end()) {
430 LogTimeEntry *entry = (*t);
TraianX Schiauda6495d2014-12-17 10:53:41 +0200431 if (entry->owned_Locked() && entry->isWatching(id)
Mark Salyzyn0175b072014-02-26 09:50:16 -0800432 && (!oldest || (oldest->mStart > entry->mStart))) {
433 oldest = entry;
434 }
435 t++;
436 }
437
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800438 LogBufferElementCollection::iterator it;
439
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700440 if (caller_uid != AID_ROOT) {
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700441 // Only here if clearAll condition (pruneRows == ULONG_MAX)
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700442 for(it = mLogElements.begin(); it != mLogElements.end();) {
443 LogBufferElement *e = *it;
444
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700445 if ((e->getLogId() != id) || (e->getUid() != caller_uid)) {
446 ++it;
447 continue;
448 }
449
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800450 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700451 oldest->triggerSkip_Locked(id, pruneRows);
452 busy = true;
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700453 break;
454 }
455
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700456 it = erase(it);
457 pruneRows--;
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700458 }
459 LogTimeEntry::unlock();
Mark Salyzync5dc9702015-09-16 15:34:00 -0700460 return busy;
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700461 }
462
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800463 // prune by worst offender by uid
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700464 bool hasBlacklist = mPrune.naughty();
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700465 while (!clearAll && (pruneRows > 0)) {
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800466 // recalculate the worst offender on every batched pass
467 uid_t worst = (uid_t) -1;
468 size_t worst_sizes = 0;
469 size_t second_worst_sizes = 0;
470
Mark Salyzynae769232015-03-17 17:17:25 -0700471 if (worstUidEnabledForLogid(id) && mPrune.worstUidEnabled()) {
Mark Salyzyn720f6d12015-03-16 08:26:05 -0700472 std::unique_ptr<const UidEntry *[]> sorted = stats.sort(2, id);
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700473
Mark Salyzyn720f6d12015-03-16 08:26:05 -0700474 if (sorted.get()) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700475 if (sorted[0] && sorted[1]) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700476 worst_sizes = sorted[0]->getSizes();
Mark Salyzynd717d802015-04-20 15:36:12 -0700477 // Calculate threshold as 12.5% of available storage
478 size_t threshold = log_buffer_size(id) / 8;
479 if (worst_sizes > threshold) {
480 worst = sorted[0]->getKey();
481 second_worst_sizes = sorted[1]->getSizes();
482 if (second_worst_sizes < threshold) {
483 second_worst_sizes = threshold;
484 }
485 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800486 }
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800487 }
488 }
489
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700490 // skip if we have neither worst nor naughty filters
491 if ((worst == (uid_t) -1) && !hasBlacklist) {
492 break;
493 }
494
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800495 bool kick = false;
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700496 bool leading = true;
Mark Salyzync892ea32015-08-19 17:06:11 -0700497 it = mLogElements.begin();
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700498 // Perform at least one mandatory garbage collection cycle in following
499 // - clear leading chatty tags
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700500 // - coalesce chatty tags
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700501 // - check age-out of preserved logs
502 bool gc = pruneRows <= 1;
503 if (!gc && (worst != (uid_t) -1)) {
Mark Salyzync892ea32015-08-19 17:06:11 -0700504 LogBufferIteratorMap::iterator f = mLastWorstUid[id].find(worst);
505 if ((f != mLastWorstUid[id].end())
506 && (f->second != mLogElements.end())) {
507 leading = false;
508 it = f->second;
509 }
510 }
Mark Salyzynccfe8442015-08-24 13:43:27 -0700511 static const timespec too_old = {
512 EXPIRE_HOUR_THRESHOLD * 60 * 60, 0
513 };
514 LogBufferElementCollection::iterator lastt;
515 lastt = mLogElements.end();
516 --lastt;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700517 LogBufferElementLast last;
Mark Salyzync892ea32015-08-19 17:06:11 -0700518 while (it != mLogElements.end()) {
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800519 LogBufferElement *e = *it;
520
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800521 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700522 busy = true;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800523 break;
524 }
525
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800526 if (e->getLogId() != id) {
527 ++it;
528 continue;
529 }
530
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700531 unsigned short dropped = e->getDropped();
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800532
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700533 // remove any leading drops
534 if (leading && dropped) {
535 it = erase(it);
536 continue;
537 }
538
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700539 if (dropped && last.coalesce(e, dropped)) {
540 it = erase(it, true);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700541 continue;
542 }
543
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700544 if (hasBlacklist && mPrune.naughty(e)) {
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700545 last.clear(e);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700546 it = erase(it);
547 if (dropped) {
548 continue;
549 }
550
551 pruneRows--;
552 if (pruneRows == 0) {
553 break;
554 }
555
556 if (e->getUid() == worst) {
557 kick = true;
558 if (worst_sizes < second_worst_sizes) {
559 break;
560 }
561 worst_sizes -= e->getMsgLen();
562 }
563 continue;
564 }
565
Mark Salyzynccfe8442015-08-24 13:43:27 -0700566 if ((e->getRealTime() < ((*lastt)->getRealTime() - too_old))
567 || (e->getRealTime() > (*lastt)->getRealTime())) {
568 break;
569 }
570
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700571 if (dropped) {
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700572 last.add(e);
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700573 if ((!gc && (e->getUid() == worst))
Mark Salyzyn49afe0d2015-08-24 13:43:27 -0700574 || (mLastWorstUid[id].find(e->getUid())
575 == mLastWorstUid[id].end())) {
576 mLastWorstUid[id][e->getUid()] = it;
577 }
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800578 ++it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700579 continue;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800580 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700581
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700582 if (e->getUid() != worst) {
Mark Salyzyn59212762015-06-01 09:41:19 -0700583 leading = false;
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700584 last.clear(e);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700585 ++it;
586 continue;
587 }
588
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700589 pruneRows--;
590 if (pruneRows == 0) {
591 break;
592 }
593
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700594 kick = true;
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700595
596 unsigned short len = e->getMsgLen();
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700597
598 // do not create any leading drops
599 if (leading) {
600 it = erase(it);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700601 } else {
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700602 stats.drop(e);
603 e->setDropped(1);
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700604 if (last.coalesce(e, 1)) {
605 it = erase(it, true);
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700606 } else {
607 last.add(e);
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700608 if (!gc || (mLastWorstUid[id].find(worst)
609 == mLastWorstUid[id].end())) {
610 mLastWorstUid[id][worst] = it;
611 }
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700612 ++it;
613 }
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700614 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700615 if (worst_sizes < second_worst_sizes) {
616 break;
617 }
618 worst_sizes -= len;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800619 }
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700620 last.clear();
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800621
Mark Salyzyn1c950472014-04-01 17:19:47 -0700622 if (!kick || !mPrune.worstUidEnabled()) {
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800623 break; // the following loop will ask bad clients to skip/drop
624 }
625 }
626
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800627 bool whitelist = false;
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700628 bool hasWhitelist = mPrune.nice() && !clearAll;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800629 it = mLogElements.begin();
Mark Salyzyn0175b072014-02-26 09:50:16 -0800630 while((pruneRows > 0) && (it != mLogElements.end())) {
631 LogBufferElement *e = *it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700632
633 if (e->getLogId() != id) {
634 it++;
635 continue;
636 }
637
638 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700639 busy = true;
640
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700641 if (whitelist) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800642 break;
643 }
Mark Salyzyn1c950472014-04-01 17:19:47 -0700644
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700645 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
646 // kick a misbehaving log reader client off the island
647 oldest->release_Locked();
648 } else {
649 oldest->triggerSkip_Locked(id, pruneRows);
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800650 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700651 break;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800652 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700653
Mark Salyzync5bf3b82015-05-21 12:50:31 -0700654 if (hasWhitelist && !e->getDropped() && mPrune.nice(e)) { // WhiteListed
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700655 whitelist = true;
656 it++;
657 continue;
658 }
659
660 it = erase(it);
661 pruneRows--;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800662 }
663
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700664 // Do not save the whitelist if we are reader range limited
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800665 if (whitelist && (pruneRows > 0)) {
666 it = mLogElements.begin();
667 while((it != mLogElements.end()) && (pruneRows > 0)) {
668 LogBufferElement *e = *it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700669
670 if (e->getLogId() != id) {
671 ++it;
672 continue;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800673 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700674
675 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700676 busy = true;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700677 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
678 // kick a misbehaving log reader client off the island
679 oldest->release_Locked();
680 } else {
681 oldest->triggerSkip_Locked(id, pruneRows);
682 }
683 break;
684 }
685
686 it = erase(it);
687 pruneRows--;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800688 }
689 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800690
Mark Salyzyn0175b072014-02-26 09:50:16 -0800691 LogTimeEntry::unlock();
Mark Salyzync5dc9702015-09-16 15:34:00 -0700692
693 return (pruneRows > 0) && busy;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800694}
695
696// clear all rows of type "id" from the buffer.
Mark Salyzync5dc9702015-09-16 15:34:00 -0700697bool LogBuffer::clear(log_id_t id, uid_t uid) {
698 bool busy = true;
699 // If it takes more than 4 tries (seconds) to clear, then kill reader(s)
700 for (int retry = 4;;) {
701 if (retry == 1) { // last pass
702 // Check if it is still busy after the sleep, we say prune
703 // one entry, not another clear run, so we are looking for
704 // the quick side effect of the return value to tell us if
705 // we have a _blocked_ reader.
706 pthread_mutex_lock(&mLogElementsLock);
707 busy = prune(id, 1, uid);
708 pthread_mutex_unlock(&mLogElementsLock);
709 // It is still busy, blocked reader(s), lets kill them all!
710 // otherwise, lets be a good citizen and preserve the slow
711 // readers and let the clear run (below) deal with determining
712 // if we are still blocked and return an error code to caller.
713 if (busy) {
714 LogTimeEntry::lock();
715 LastLogTimes::iterator times = mTimes.begin();
716 while (times != mTimes.end()) {
717 LogTimeEntry *entry = (*times);
718 // Killer punch
719 if (entry->owned_Locked() && entry->isWatching(id)) {
720 entry->release_Locked();
721 }
722 times++;
723 }
724 LogTimeEntry::unlock();
725 }
726 }
727 pthread_mutex_lock(&mLogElementsLock);
728 busy = prune(id, ULONG_MAX, uid);
729 pthread_mutex_unlock(&mLogElementsLock);
730 if (!busy || !--retry) {
731 break;
732 }
733 sleep (1); // Let reader(s) catch up after notification
734 }
735 return busy;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800736}
737
738// get the used space associated with "id".
739unsigned long LogBuffer::getSizeUsed(log_id_t id) {
740 pthread_mutex_lock(&mLogElementsLock);
Mark Salyzyn34facab2014-02-06 14:48:50 -0800741 size_t retval = stats.sizes(id);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800742 pthread_mutex_unlock(&mLogElementsLock);
743 return retval;
744}
745
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800746// set the total space allocated to "id"
747int LogBuffer::setSize(log_id_t id, unsigned long size) {
748 // Reasonable limits ...
Mark Salyzyn57a0af92014-05-09 17:44:18 -0700749 if (!valid_size(size)) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800750 return -1;
751 }
752 pthread_mutex_lock(&mLogElementsLock);
753 log_buffer_size(id) = size;
754 pthread_mutex_unlock(&mLogElementsLock);
755 return 0;
756}
757
758// get the total space allocated to "id"
759unsigned long LogBuffer::getSize(log_id_t id) {
760 pthread_mutex_lock(&mLogElementsLock);
761 size_t retval = log_buffer_size(id);
762 pthread_mutex_unlock(&mLogElementsLock);
763 return retval;
764}
765
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800766uint64_t LogBuffer::flushTo(
767 SocketClient *reader, const uint64_t start, bool privileged,
768 int (*filter)(const LogBufferElement *element, void *arg), void *arg) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800769 LogBufferElementCollection::iterator it;
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800770 uint64_t max = start;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800771 uid_t uid = reader->getUid();
772
773 pthread_mutex_lock(&mLogElementsLock);
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600774
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800775 if (start <= 1) {
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600776 // client wants to start from the beginning
777 it = mLogElements.begin();
778 } else {
779 // Client wants to start from some specified time. Chances are
780 // we are better off starting from the end of the time sorted list.
781 for (it = mLogElements.end(); it != mLogElements.begin(); /* do nothing */) {
782 --it;
783 LogBufferElement *element = *it;
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800784 if (element->getSequence() <= start) {
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600785 it++;
786 break;
787 }
788 }
789 }
790
791 for (; it != mLogElements.end(); ++it) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800792 LogBufferElement *element = *it;
793
794 if (!privileged && (element->getUid() != uid)) {
795 continue;
796 }
797
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800798 if (element->getSequence() <= start) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800799 continue;
800 }
801
802 // NB: calling out to another object with mLogElementsLock held (safe)
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800803 if (filter) {
804 int ret = (*filter)(element, arg);
805 if (ret == false) {
806 continue;
807 }
808 if (ret != true) {
809 break;
810 }
Mark Salyzyn0175b072014-02-26 09:50:16 -0800811 }
812
813 pthread_mutex_unlock(&mLogElementsLock);
814
815 // range locking in LastLogTimes looks after us
Mark Salyzyn21fb7e02015-04-20 07:26:27 -0700816 max = element->flushTo(reader, this);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800817
818 if (max == element->FLUSH_ERROR) {
819 return max;
820 }
821
822 pthread_mutex_lock(&mLogElementsLock);
823 }
824 pthread_mutex_unlock(&mLogElementsLock);
825
826 return max;
827}
Mark Salyzyn34facab2014-02-06 14:48:50 -0800828
Mark Salyzyn73160ac2015-08-20 10:01:44 -0700829std::string LogBuffer::formatStatistics(uid_t uid, unsigned int logMask) {
Mark Salyzyn34facab2014-02-06 14:48:50 -0800830 pthread_mutex_lock(&mLogElementsLock);
831
Mark Salyzyn73160ac2015-08-20 10:01:44 -0700832 std::string ret = stats.format(uid, logMask);
Mark Salyzyn34facab2014-02-06 14:48:50 -0800833
834 pthread_mutex_unlock(&mLogElementsLock);
Mark Salyzyn73160ac2015-08-20 10:01:44 -0700835
836 return ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800837}