blob: 3ce6b61e044d2c0498383d589dbec4fb9e564bbf [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;
Mark Salyzynba7a9a02015-12-01 15:57:25 -0800131 monotonic = android_log_clockid() == CLOCK_MONOTONIC;
Mark Salyzynb75cce02015-11-30 11:35:56 -0800132 if (lastMonotonic != monotonic) {
133 //
134 // Fixup all timestamps, may not be 100% accurate, but better than
135 // throwing what we have away when we get 'surprised' by a change.
136 // In-place element fixup so no need to check reader-lock. Entries
137 // should already be in timestamp order, but we could end up with a
138 // few out-of-order entries if new monotonics come in before we
139 // are notified of the reinit change in status. A Typical example would
140 // be:
141 // --------- beginning of system
142 // 10.494082 184 201 D Cryptfs : Just triggered post_fs_data
143 // --------- beginning of kernel
144 // 0.000000 0 0 I : Initializing cgroup subsys
145 // as the act of mounting /data would trigger persist.logd.timestamp to
146 // be corrected. 1/30 corner case YMMV.
147 //
148 pthread_mutex_lock(&mLogElementsLock);
149 LogBufferElementCollection::iterator it = mLogElements.begin();
150 while((it != mLogElements.end())) {
151 LogBufferElement *e = *it;
152 if (monotonic) {
153 if (!android::isMonotonic(e->mRealTime)) {
154 LogKlog::convertRealToMonotonic(e->mRealTime);
155 }
156 } else {
157 if (android::isMonotonic(e->mRealTime)) {
158 LogKlog::convertMonotonicToReal(e->mRealTime);
159 }
160 }
161 ++it;
162 }
163 pthread_mutex_unlock(&mLogElementsLock);
Mark Salyzynb6bee332015-09-08 08:56:32 -0700164 }
165
Mark Salyzynb75cce02015-11-30 11:35:56 -0800166 // We may have been triggered by a SIGHUP. Release any sleeping reader
167 // threads to dump their current content.
Mark Salyzynb6bee332015-09-08 08:56:32 -0700168 //
Mark Salyzynb75cce02015-11-30 11:35:56 -0800169 // NB: this is _not_ performed in the context of a SIGHUP, it is
170 // performed during startup, and in context of reinit administrative thread
171 LogTimeEntry::lock();
172
173 LastLogTimes::iterator times = mTimes.begin();
174 while(times != mTimes.end()) {
175 LogTimeEntry *entry = (*times);
176 if (entry->owned_Locked()) {
177 entry->triggerReader_Locked();
Mark Salyzynb6bee332015-09-08 08:56:32 -0700178 }
Mark Salyzynb75cce02015-11-30 11:35:56 -0800179 times++;
Mark Salyzynb6bee332015-09-08 08:56:32 -0700180 }
Mark Salyzynb75cce02015-11-30 11:35:56 -0800181
182 LogTimeEntry::unlock();
Mark Salyzyn0175b072014-02-26 09:50:16 -0800183}
184
Mark Salyzynb6bee332015-09-08 08:56:32 -0700185LogBuffer::LogBuffer(LastLogTimes *times):
Mark Salyzynba7a9a02015-12-01 15:57:25 -0800186 monotonic(android_log_clockid() == CLOCK_MONOTONIC),
Mark Salyzynb6bee332015-09-08 08:56:32 -0700187 mTimes(*times) {
Mark Salyzyn11e55cb2015-03-10 16:45:17 -0700188 pthread_mutex_init(&mLogElementsLock, NULL);
189
190 init();
191}
192
Mark Salyzyn202e1532015-02-09 08:21:05 -0800193int LogBuffer::log(log_id_t log_id, log_time realtime,
194 uid_t uid, pid_t pid, pid_t tid,
195 const char *msg, unsigned short len) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800196 if ((log_id >= LOG_ID_MAX) || (log_id < 0)) {
Mark Salyzyn202e1532015-02-09 08:21:05 -0800197 return -EINVAL;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800198 }
Mark Salyzyne59c4692014-10-02 13:07:05 -0700199
Mark Salyzyn0175b072014-02-26 09:50:16 -0800200 LogBufferElement *elem = new LogBufferElement(log_id, realtime,
Mark Salyzynb992d0d2014-03-20 16:09:38 -0700201 uid, pid, tid, msg, len);
Mark Salyzyn083b0372015-12-04 10:59:45 -0800202 if (log_id != LOG_ID_SECURITY) {
203 int prio = ANDROID_LOG_INFO;
204 const char *tag = NULL;
205 if (log_id == LOG_ID_EVENTS) {
206 tag = android::tagToName(elem->getTag());
207 } else {
208 prio = *msg;
209 tag = msg + 1;
210 }
211 if (!__android_log_is_loggable(prio, tag, ANDROID_LOG_VERBOSE)) {
212 // Log traffic received to total
213 pthread_mutex_lock(&mLogElementsLock);
214 stats.add(elem);
215 stats.subtract(elem);
216 pthread_mutex_unlock(&mLogElementsLock);
217 delete elem;
218 return -EACCES;
219 }
Mark Salyzyne59c4692014-10-02 13:07:05 -0700220 }
Mark Salyzyn0175b072014-02-26 09:50:16 -0800221
222 pthread_mutex_lock(&mLogElementsLock);
223
224 // Insert elements in time sorted order if possible
225 // NB: if end is region locked, place element at end of list
226 LogBufferElementCollection::iterator it = mLogElements.end();
227 LogBufferElementCollection::iterator last = it;
Mark Salyzyneae155e2014-10-13 16:49:47 -0700228 while (last != mLogElements.begin()) {
229 --it;
Mark Salyzync03e72c2014-02-18 11:23:53 -0800230 if ((*it)->getRealTime() <= realtime) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800231 break;
232 }
233 last = it;
234 }
Mark Salyzync03e72c2014-02-18 11:23:53 -0800235
Mark Salyzyn0175b072014-02-26 09:50:16 -0800236 if (last == mLogElements.end()) {
237 mLogElements.push_back(elem);
238 } else {
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800239 uint64_t end = 1;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800240 bool end_set = false;
241 bool end_always = false;
242
243 LogTimeEntry::lock();
244
245 LastLogTimes::iterator t = mTimes.begin();
246 while(t != mTimes.end()) {
247 LogTimeEntry *entry = (*t);
248 if (entry->owned_Locked()) {
249 if (!entry->mNonBlock) {
250 end_always = true;
251 break;
252 }
253 if (!end_set || (end <= entry->mEnd)) {
254 end = entry->mEnd;
255 end_set = true;
256 }
257 }
258 t++;
259 }
260
261 if (end_always
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800262 || (end_set && (end >= (*last)->getSequence()))) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800263 mLogElements.push_back(elem);
264 } else {
265 mLogElements.insert(last,elem);
266 }
267
268 LogTimeEntry::unlock();
269 }
270
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700271 stats.add(elem);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800272 maybePrune(log_id);
273 pthread_mutex_unlock(&mLogElementsLock);
Mark Salyzyn202e1532015-02-09 08:21:05 -0800274
275 return len;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800276}
277
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700278// Prune at most 10% of the log entries or maxPrune, whichever is less.
Mark Salyzyn0175b072014-02-26 09:50:16 -0800279//
280// mLogElementsLock must be held when this function is called.
281void LogBuffer::maybePrune(log_id_t id) {
Mark Salyzyn34facab2014-02-06 14:48:50 -0800282 size_t sizes = stats.sizes(id);
Mark Salyzyn62ab0fd2015-08-10 10:23:56 -0700283 unsigned long maxSize = log_buffer_size(id);
284 if (sizes > maxSize) {
Mark Salyzynb39ed0c2015-08-19 12:20:36 -0700285 size_t sizeOver = sizes - ((maxSize * 9) / 10);
Mark Salyzyn58b8be82015-09-30 07:40:09 -0700286 size_t elements = stats.realElements(id);
287 size_t minElements = elements / 100;
288 if (minElements < minPrune) {
289 minElements = minPrune;
290 }
Mark Salyzyn62ab0fd2015-08-10 10:23:56 -0700291 unsigned long pruneRows = elements * sizeOver / sizes;
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700292 if (pruneRows < minElements) {
Mark Salyzyn62ab0fd2015-08-10 10:23:56 -0700293 pruneRows = minElements;
Mark Salyzyn740f9b42014-01-13 16:37:51 -0800294 }
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700295 if (pruneRows > maxPrune) {
296 pruneRows = maxPrune;
Mark Salyzynb39ed0c2015-08-19 12:20:36 -0700297 }
Mark Salyzyn740f9b42014-01-13 16:37:51 -0800298 prune(id, pruneRows);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800299 }
300}
301
Mark Salyzyn831aa292015-09-03 16:08:50 -0700302LogBufferElementCollection::iterator LogBuffer::erase(
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700303 LogBufferElementCollection::iterator it, bool coalesce) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700304 LogBufferElement *e = *it;
Mark Salyzync892ea32015-08-19 17:06:11 -0700305 log_id_t id = e->getLogId();
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700306
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700307 LogBufferIteratorMap::iterator f = mLastWorstUid[id].find(e->getUid());
Mark Salyzync892ea32015-08-19 17:06:11 -0700308 if ((f != mLastWorstUid[id].end()) && (it == f->second)) {
309 mLastWorstUid[id].erase(f);
310 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700311 it = mLogElements.erase(it);
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700312 if (coalesce) {
Mark Salyzyn831aa292015-09-03 16:08:50 -0700313 stats.erase(e);
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700314 } else {
315 stats.subtract(e);
Mark Salyzyn831aa292015-09-03 16:08:50 -0700316 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700317 delete e;
318
319 return it;
320}
321
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700322// Define a temporary mechanism to report the last LogBufferElement pointer
323// for the specified uid, pid and tid. Used below to help merge-sort when
324// pruning for worst UID.
325class LogBufferElementKey {
326 const union {
327 struct {
328 uint16_t uid;
329 uint16_t pid;
330 uint16_t tid;
331 uint16_t padding;
332 } __packed;
333 uint64_t value;
334 } __packed;
335
336public:
337 LogBufferElementKey(uid_t u, pid_t p, pid_t t):uid(u),pid(p),tid(t),padding(0) { }
338 LogBufferElementKey(uint64_t k):value(k) { }
339
340 uint64_t getKey() { return value; }
341};
342
Mark Salyzyn511338d2015-05-19 09:12:30 -0700343class LogBufferElementLast {
344
345 typedef std::unordered_map<uint64_t, LogBufferElement *> LogBufferElementMap;
346 LogBufferElementMap map;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700347
348public:
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700349
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700350 bool coalesce(LogBufferElement *e, unsigned short dropped) {
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700351 LogBufferElementKey key(e->getUid(), e->getPid(), e->getTid());
Mark Salyzyn511338d2015-05-19 09:12:30 -0700352 LogBufferElementMap::iterator it = map.find(key.getKey());
353 if (it != map.end()) {
354 LogBufferElement *l = it->second;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700355 unsigned short d = l->getDropped();
356 if ((dropped + d) > USHRT_MAX) {
Mark Salyzyn511338d2015-05-19 09:12:30 -0700357 map.erase(it);
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700358 } else {
359 l->setDropped(dropped + d);
360 return true;
361 }
362 }
363 return false;
364 }
365
Mark Salyzyn511338d2015-05-19 09:12:30 -0700366 void add(LogBufferElement *e) {
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700367 LogBufferElementKey key(e->getUid(), e->getPid(), e->getTid());
Mark Salyzyn511338d2015-05-19 09:12:30 -0700368 map[key.getKey()] = e;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700369 }
370
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700371 inline void clear() {
Mark Salyzyn511338d2015-05-19 09:12:30 -0700372 map.clear();
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700373 }
374
375 void clear(LogBufferElement *e) {
Mark Salyzyn047cc072015-06-04 13:35:30 -0700376 uint64_t current = e->getRealTime().nsec()
377 - (EXPIRE_RATELIMIT * NS_PER_SEC);
Mark Salyzyn511338d2015-05-19 09:12:30 -0700378 for(LogBufferElementMap::iterator it = map.begin(); it != map.end();) {
379 LogBufferElement *l = it->second;
Mark Salyzyn833a9b12015-05-15 15:58:17 -0700380 if ((l->getDropped() >= EXPIRE_THRESHOLD)
381 && (current > l->getRealTime().nsec())) {
Mark Salyzyn511338d2015-05-19 09:12:30 -0700382 it = map.erase(it);
383 } else {
384 ++it;
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700385 }
386 }
387 }
388
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700389};
390
Mark Salyzyn0175b072014-02-26 09:50:16 -0800391// prune "pruneRows" of type "id" from the buffer.
392//
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700393// This garbage collection task is used to expire log entries. It is called to
394// remove all logs (clear), all UID logs (unprivileged clear), or every
395// 256 or 10% of the total logs (whichever is less) to prune the logs.
396//
397// First there is a prep phase where we discover the reader region lock that
398// acts as a backstop to any pruning activity to stop there and go no further.
399//
400// There are three major pruning loops that follow. All expire from the oldest
401// entries. Since there are multiple log buffers, the Android logging facility
402// will appear to drop entries 'in the middle' when looking at multiple log
403// sources and buffers. This effect is slightly more prominent when we prune
404// the worst offender by logging source. Thus the logs slowly loose content
405// and value as you move back in time. This is preferred since chatty sources
406// invariably move the logs value down faster as less chatty sources would be
407// expired in the noise.
408//
409// The first loop performs blacklisting and worst offender pruning. Falling
410// through when there are no notable worst offenders and have not hit the
411// region lock preventing further worst offender pruning. This loop also looks
412// after managing the chatty log entries and merging to help provide
413// statistical basis for blame. The chatty entries are not a notification of
414// how much logs you may have, but instead represent how much logs you would
415// have had in a virtual log buffer that is extended to cover all the in-memory
416// logs without loss. They last much longer than the represented pruned logs
417// since they get multiplied by the gains in the non-chatty log sources.
418//
419// The second loop get complicated because an algorithm of watermarks and
420// history is maintained to reduce the order and keep processing time
421// down to a minimum at scale. These algorithms can be costly in the face
422// of larger log buffers, or severly limited processing time granted to a
423// background task at lowest priority.
424//
425// This second loop does straight-up expiration from the end of the logs
426// (again, remember for the specified log buffer id) but does some whitelist
427// preservation. Thus whitelist is a Hail Mary low priority, blacklists and
428// spam filtration all take priority. This second loop also checks if a region
429// lock is causing us to buffer too much in the logs to help the reader(s),
430// and will tell the slowest reader thread to skip log entries, and if
431// persistent and hits a further threshold, kill the reader thread.
432//
433// The third thread is optional, and only gets hit if there was a whitelist
434// and more needs to be pruned against the backstop of the region lock.
435//
Mark Salyzyn0175b072014-02-26 09:50:16 -0800436// mLogElementsLock must be held when this function is called.
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700437//
Mark Salyzync5dc9702015-09-16 15:34:00 -0700438bool LogBuffer::prune(log_id_t id, unsigned long pruneRows, uid_t caller_uid) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800439 LogTimeEntry *oldest = NULL;
Mark Salyzync5dc9702015-09-16 15:34:00 -0700440 bool busy = false;
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700441 bool clearAll = pruneRows == ULONG_MAX;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800442
443 LogTimeEntry::lock();
444
445 // Region locked?
446 LastLogTimes::iterator t = mTimes.begin();
447 while(t != mTimes.end()) {
448 LogTimeEntry *entry = (*t);
TraianX Schiauda6495d2014-12-17 10:53:41 +0200449 if (entry->owned_Locked() && entry->isWatching(id)
Mark Salyzynb75cce02015-11-30 11:35:56 -0800450 && (!oldest ||
451 (oldest->mStart > entry->mStart) ||
452 ((oldest->mStart == entry->mStart) &&
453 (entry->mTimeout.tv_sec || entry->mTimeout.tv_nsec)))) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800454 oldest = entry;
455 }
456 t++;
457 }
458
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800459 LogBufferElementCollection::iterator it;
460
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700461 if (caller_uid != AID_ROOT) {
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700462 // Only here if clearAll condition (pruneRows == ULONG_MAX)
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700463 for(it = mLogElements.begin(); it != mLogElements.end();) {
464 LogBufferElement *e = *it;
465
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700466 if ((e->getLogId() != id) || (e->getUid() != caller_uid)) {
467 ++it;
468 continue;
469 }
470
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800471 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700472 busy = true;
Mark Salyzynb75cce02015-11-30 11:35:56 -0800473 if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
474 oldest->triggerReader_Locked();
475 } else {
476 oldest->triggerSkip_Locked(id, pruneRows);
477 }
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700478 break;
479 }
480
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700481 it = erase(it);
482 pruneRows--;
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700483 }
484 LogTimeEntry::unlock();
Mark Salyzync5dc9702015-09-16 15:34:00 -0700485 return busy;
Mark Salyzyn1a240b42014-06-12 11:16:16 -0700486 }
487
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800488 // prune by worst offender by uid
Mark Salyzyn083b0372015-12-04 10:59:45 -0800489 bool hasBlacklist = (id != LOG_ID_SECURITY) && mPrune.naughty();
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700490 while (!clearAll && (pruneRows > 0)) {
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800491 // recalculate the worst offender on every batched pass
492 uid_t worst = (uid_t) -1;
493 size_t worst_sizes = 0;
494 size_t second_worst_sizes = 0;
495
Mark Salyzynae769232015-03-17 17:17:25 -0700496 if (worstUidEnabledForLogid(id) && mPrune.worstUidEnabled()) {
Mark Salyzyn720f6d12015-03-16 08:26:05 -0700497 std::unique_ptr<const UidEntry *[]> sorted = stats.sort(2, id);
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700498
Mark Salyzyn720f6d12015-03-16 08:26:05 -0700499 if (sorted.get()) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700500 if (sorted[0] && sorted[1]) {
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700501 worst_sizes = sorted[0]->getSizes();
Mark Salyzynd717d802015-04-20 15:36:12 -0700502 // Calculate threshold as 12.5% of available storage
503 size_t threshold = log_buffer_size(id) / 8;
Mark Salyzyn50122692015-10-12 13:45:51 -0700504 if ((worst_sizes > threshold)
505 // Allow time horizon to extend roughly tenfold, assume
506 // average entry length is 100 characters.
507 && (worst_sizes > (10 * sorted[0]->getDropped()))) {
Mark Salyzynd717d802015-04-20 15:36:12 -0700508 worst = sorted[0]->getKey();
509 second_worst_sizes = sorted[1]->getSizes();
510 if (second_worst_sizes < threshold) {
511 second_worst_sizes = threshold;
512 }
513 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800514 }
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800515 }
516 }
517
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700518 // skip if we have neither worst nor naughty filters
519 if ((worst == (uid_t) -1) && !hasBlacklist) {
520 break;
521 }
522
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800523 bool kick = false;
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700524 bool leading = true;
Mark Salyzync892ea32015-08-19 17:06:11 -0700525 it = mLogElements.begin();
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700526 // Perform at least one mandatory garbage collection cycle in following
527 // - clear leading chatty tags
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700528 // - coalesce chatty tags
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700529 // - check age-out of preserved logs
530 bool gc = pruneRows <= 1;
531 if (!gc && (worst != (uid_t) -1)) {
Mark Salyzync892ea32015-08-19 17:06:11 -0700532 LogBufferIteratorMap::iterator f = mLastWorstUid[id].find(worst);
533 if ((f != mLastWorstUid[id].end())
534 && (f->second != mLogElements.end())) {
535 leading = false;
536 it = f->second;
537 }
538 }
Mark Salyzynccfe8442015-08-24 13:43:27 -0700539 static const timespec too_old = {
540 EXPIRE_HOUR_THRESHOLD * 60 * 60, 0
541 };
542 LogBufferElementCollection::iterator lastt;
543 lastt = mLogElements.end();
544 --lastt;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700545 LogBufferElementLast last;
Mark Salyzync892ea32015-08-19 17:06:11 -0700546 while (it != mLogElements.end()) {
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800547 LogBufferElement *e = *it;
548
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800549 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700550 busy = true;
Mark Salyzynb75cce02015-11-30 11:35:56 -0800551 if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
552 oldest->triggerReader_Locked();
553 }
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800554 break;
555 }
556
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800557 if (e->getLogId() != id) {
558 ++it;
559 continue;
560 }
561
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700562 unsigned short dropped = e->getDropped();
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800563
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700564 // remove any leading drops
565 if (leading && dropped) {
566 it = erase(it);
567 continue;
568 }
569
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700570 if (dropped && last.coalesce(e, dropped)) {
571 it = erase(it, true);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700572 continue;
573 }
574
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700575 if (hasBlacklist && mPrune.naughty(e)) {
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700576 last.clear(e);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700577 it = erase(it);
578 if (dropped) {
579 continue;
580 }
581
582 pruneRows--;
583 if (pruneRows == 0) {
584 break;
585 }
586
587 if (e->getUid() == worst) {
588 kick = true;
589 if (worst_sizes < second_worst_sizes) {
590 break;
591 }
592 worst_sizes -= e->getMsgLen();
593 }
594 continue;
595 }
596
Mark Salyzynccfe8442015-08-24 13:43:27 -0700597 if ((e->getRealTime() < ((*lastt)->getRealTime() - too_old))
598 || (e->getRealTime() > (*lastt)->getRealTime())) {
599 break;
600 }
601
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700602 if (dropped) {
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700603 last.add(e);
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700604 if ((!gc && (e->getUid() == worst))
Mark Salyzyn49afe0d2015-08-24 13:43:27 -0700605 || (mLastWorstUid[id].find(e->getUid())
606 == mLastWorstUid[id].end())) {
607 mLastWorstUid[id][e->getUid()] = it;
608 }
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800609 ++it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700610 continue;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800611 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700612
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700613 if (e->getUid() != worst) {
Mark Salyzyn59212762015-06-01 09:41:19 -0700614 leading = false;
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700615 last.clear(e);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700616 ++it;
617 continue;
618 }
619
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700620 pruneRows--;
621 if (pruneRows == 0) {
622 break;
623 }
624
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700625 kick = true;
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700626
627 unsigned short len = e->getMsgLen();
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700628
629 // do not create any leading drops
630 if (leading) {
631 it = erase(it);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700632 } else {
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700633 stats.drop(e);
634 e->setDropped(1);
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700635 if (last.coalesce(e, 1)) {
636 it = erase(it, true);
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700637 } else {
638 last.add(e);
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700639 if (!gc || (mLastWorstUid[id].find(worst)
640 == mLastWorstUid[id].end())) {
641 mLastWorstUid[id][worst] = it;
642 }
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700643 ++it;
644 }
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700645 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700646 if (worst_sizes < second_worst_sizes) {
647 break;
648 }
649 worst_sizes -= len;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800650 }
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700651 last.clear();
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800652
Mark Salyzyn1c950472014-04-01 17:19:47 -0700653 if (!kick || !mPrune.worstUidEnabled()) {
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800654 break; // the following loop will ask bad clients to skip/drop
655 }
656 }
657
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800658 bool whitelist = false;
Mark Salyzyn083b0372015-12-04 10:59:45 -0800659 bool hasWhitelist = (id != LOG_ID_SECURITY) && mPrune.nice() && !clearAll;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800660 it = mLogElements.begin();
Mark Salyzyn0175b072014-02-26 09:50:16 -0800661 while((pruneRows > 0) && (it != mLogElements.end())) {
662 LogBufferElement *e = *it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700663
664 if (e->getLogId() != id) {
665 it++;
666 continue;
667 }
668
669 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700670 busy = true;
671
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700672 if (whitelist) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800673 break;
674 }
Mark Salyzyn1c950472014-04-01 17:19:47 -0700675
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700676 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
677 // kick a misbehaving log reader client off the island
678 oldest->release_Locked();
Mark Salyzynb75cce02015-11-30 11:35:56 -0800679 } else if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
680 oldest->triggerReader_Locked();
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700681 } else {
682 oldest->triggerSkip_Locked(id, pruneRows);
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800683 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700684 break;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800685 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700686
Mark Salyzync5bf3b82015-05-21 12:50:31 -0700687 if (hasWhitelist && !e->getDropped() && mPrune.nice(e)) { // WhiteListed
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700688 whitelist = true;
689 it++;
690 continue;
691 }
692
693 it = erase(it);
694 pruneRows--;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800695 }
696
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700697 // Do not save the whitelist if we are reader range limited
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800698 if (whitelist && (pruneRows > 0)) {
699 it = mLogElements.begin();
700 while((it != mLogElements.end()) && (pruneRows > 0)) {
701 LogBufferElement *e = *it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700702
703 if (e->getLogId() != id) {
704 ++it;
705 continue;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800706 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700707
708 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700709 busy = true;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700710 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
711 // kick a misbehaving log reader client off the island
712 oldest->release_Locked();
Mark Salyzynb75cce02015-11-30 11:35:56 -0800713 } else if (oldest->mTimeout.tv_sec || oldest->mTimeout.tv_nsec) {
714 oldest->triggerReader_Locked();
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700715 } else {
716 oldest->triggerSkip_Locked(id, pruneRows);
717 }
718 break;
719 }
720
721 it = erase(it);
722 pruneRows--;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800723 }
724 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800725
Mark Salyzyn0175b072014-02-26 09:50:16 -0800726 LogTimeEntry::unlock();
Mark Salyzync5dc9702015-09-16 15:34:00 -0700727
728 return (pruneRows > 0) && busy;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800729}
730
731// clear all rows of type "id" from the buffer.
Mark Salyzync5dc9702015-09-16 15:34:00 -0700732bool LogBuffer::clear(log_id_t id, uid_t uid) {
733 bool busy = true;
734 // If it takes more than 4 tries (seconds) to clear, then kill reader(s)
735 for (int retry = 4;;) {
736 if (retry == 1) { // last pass
737 // Check if it is still busy after the sleep, we say prune
738 // one entry, not another clear run, so we are looking for
739 // the quick side effect of the return value to tell us if
740 // we have a _blocked_ reader.
741 pthread_mutex_lock(&mLogElementsLock);
742 busy = prune(id, 1, uid);
743 pthread_mutex_unlock(&mLogElementsLock);
744 // It is still busy, blocked reader(s), lets kill them all!
745 // otherwise, lets be a good citizen and preserve the slow
746 // readers and let the clear run (below) deal with determining
747 // if we are still blocked and return an error code to caller.
748 if (busy) {
749 LogTimeEntry::lock();
750 LastLogTimes::iterator times = mTimes.begin();
751 while (times != mTimes.end()) {
752 LogTimeEntry *entry = (*times);
753 // Killer punch
754 if (entry->owned_Locked() && entry->isWatching(id)) {
755 entry->release_Locked();
756 }
757 times++;
758 }
759 LogTimeEntry::unlock();
760 }
761 }
762 pthread_mutex_lock(&mLogElementsLock);
763 busy = prune(id, ULONG_MAX, uid);
764 pthread_mutex_unlock(&mLogElementsLock);
765 if (!busy || !--retry) {
766 break;
767 }
768 sleep (1); // Let reader(s) catch up after notification
769 }
770 return busy;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800771}
772
773// get the used space associated with "id".
774unsigned long LogBuffer::getSizeUsed(log_id_t id) {
775 pthread_mutex_lock(&mLogElementsLock);
Mark Salyzyn34facab2014-02-06 14:48:50 -0800776 size_t retval = stats.sizes(id);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800777 pthread_mutex_unlock(&mLogElementsLock);
778 return retval;
779}
780
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800781// set the total space allocated to "id"
782int LogBuffer::setSize(log_id_t id, unsigned long size) {
783 // Reasonable limits ...
Mark Salyzyn57a0af92014-05-09 17:44:18 -0700784 if (!valid_size(size)) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800785 return -1;
786 }
787 pthread_mutex_lock(&mLogElementsLock);
788 log_buffer_size(id) = size;
789 pthread_mutex_unlock(&mLogElementsLock);
790 return 0;
791}
792
793// get the total space allocated to "id"
794unsigned long LogBuffer::getSize(log_id_t id) {
795 pthread_mutex_lock(&mLogElementsLock);
796 size_t retval = log_buffer_size(id);
797 pthread_mutex_unlock(&mLogElementsLock);
798 return retval;
799}
800
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800801uint64_t LogBuffer::flushTo(
802 SocketClient *reader, const uint64_t start, bool privileged,
803 int (*filter)(const LogBufferElement *element, void *arg), void *arg) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800804 LogBufferElementCollection::iterator it;
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800805 uint64_t max = start;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800806 uid_t uid = reader->getUid();
807
808 pthread_mutex_lock(&mLogElementsLock);
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600809
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800810 if (start <= 1) {
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600811 // client wants to start from the beginning
812 it = mLogElements.begin();
813 } else {
814 // Client wants to start from some specified time. Chances are
815 // we are better off starting from the end of the time sorted list.
816 for (it = mLogElements.end(); it != mLogElements.begin(); /* do nothing */) {
817 --it;
818 LogBufferElement *element = *it;
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800819 if (element->getSequence() <= start) {
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600820 it++;
821 break;
822 }
823 }
824 }
825
826 for (; it != mLogElements.end(); ++it) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800827 LogBufferElement *element = *it;
828
829 if (!privileged && (element->getUid() != uid)) {
830 continue;
831 }
832
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800833 if (element->getSequence() <= start) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800834 continue;
835 }
836
837 // NB: calling out to another object with mLogElementsLock held (safe)
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800838 if (filter) {
839 int ret = (*filter)(element, arg);
840 if (ret == false) {
841 continue;
842 }
843 if (ret != true) {
844 break;
845 }
Mark Salyzyn0175b072014-02-26 09:50:16 -0800846 }
847
848 pthread_mutex_unlock(&mLogElementsLock);
849
850 // range locking in LastLogTimes looks after us
Mark Salyzyn21fb7e02015-04-20 07:26:27 -0700851 max = element->flushTo(reader, this);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800852
853 if (max == element->FLUSH_ERROR) {
854 return max;
855 }
856
857 pthread_mutex_lock(&mLogElementsLock);
858 }
859 pthread_mutex_unlock(&mLogElementsLock);
860
861 return max;
862}
Mark Salyzyn34facab2014-02-06 14:48:50 -0800863
Mark Salyzyn73160ac2015-08-20 10:01:44 -0700864std::string LogBuffer::formatStatistics(uid_t uid, unsigned int logMask) {
Mark Salyzyn34facab2014-02-06 14:48:50 -0800865 pthread_mutex_lock(&mLogElementsLock);
866
Mark Salyzyn73160ac2015-08-20 10:01:44 -0700867 std::string ret = stats.format(uid, logMask);
Mark Salyzyn34facab2014-02-06 14:48:50 -0800868
869 pthread_mutex_unlock(&mLogElementsLock);
Mark Salyzyn73160ac2015-08-20 10:01:44 -0700870
871 return ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800872}