blob: fd5c066ac681c0b826680a9a6e9f18561b00c206 [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;
Mark Salyzyn50122692015-10-12 13:45:51 -0700479 if ((worst_sizes > threshold)
480 // Allow time horizon to extend roughly tenfold, assume
481 // average entry length is 100 characters.
482 && (worst_sizes > (10 * sorted[0]->getDropped()))) {
Mark Salyzynd717d802015-04-20 15:36:12 -0700483 worst = sorted[0]->getKey();
484 second_worst_sizes = sorted[1]->getSizes();
485 if (second_worst_sizes < threshold) {
486 second_worst_sizes = threshold;
487 }
488 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800489 }
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800490 }
491 }
492
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700493 // skip if we have neither worst nor naughty filters
494 if ((worst == (uid_t) -1) && !hasBlacklist) {
495 break;
496 }
497
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800498 bool kick = false;
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700499 bool leading = true;
Mark Salyzync892ea32015-08-19 17:06:11 -0700500 it = mLogElements.begin();
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700501 // Perform at least one mandatory garbage collection cycle in following
502 // - clear leading chatty tags
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700503 // - coalesce chatty tags
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700504 // - check age-out of preserved logs
505 bool gc = pruneRows <= 1;
506 if (!gc && (worst != (uid_t) -1)) {
Mark Salyzync892ea32015-08-19 17:06:11 -0700507 LogBufferIteratorMap::iterator f = mLastWorstUid[id].find(worst);
508 if ((f != mLastWorstUid[id].end())
509 && (f->second != mLogElements.end())) {
510 leading = false;
511 it = f->second;
512 }
513 }
Mark Salyzynccfe8442015-08-24 13:43:27 -0700514 static const timespec too_old = {
515 EXPIRE_HOUR_THRESHOLD * 60 * 60, 0
516 };
517 LogBufferElementCollection::iterator lastt;
518 lastt = mLogElements.end();
519 --lastt;
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700520 LogBufferElementLast last;
Mark Salyzync892ea32015-08-19 17:06:11 -0700521 while (it != mLogElements.end()) {
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800522 LogBufferElement *e = *it;
523
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800524 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700525 busy = true;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800526 break;
527 }
528
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800529 if (e->getLogId() != id) {
530 ++it;
531 continue;
532 }
533
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700534 unsigned short dropped = e->getDropped();
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800535
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700536 // remove any leading drops
537 if (leading && dropped) {
538 it = erase(it);
539 continue;
540 }
541
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700542 if (dropped && last.coalesce(e, dropped)) {
543 it = erase(it, true);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700544 continue;
545 }
546
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700547 if (hasBlacklist && mPrune.naughty(e)) {
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700548 last.clear(e);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700549 it = erase(it);
550 if (dropped) {
551 continue;
552 }
553
554 pruneRows--;
555 if (pruneRows == 0) {
556 break;
557 }
558
559 if (e->getUid() == worst) {
560 kick = true;
561 if (worst_sizes < second_worst_sizes) {
562 break;
563 }
564 worst_sizes -= e->getMsgLen();
565 }
566 continue;
567 }
568
Mark Salyzynccfe8442015-08-24 13:43:27 -0700569 if ((e->getRealTime() < ((*lastt)->getRealTime() - too_old))
570 || (e->getRealTime() > (*lastt)->getRealTime())) {
571 break;
572 }
573
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700574 if (dropped) {
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700575 last.add(e);
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700576 if ((!gc && (e->getUid() == worst))
Mark Salyzyn49afe0d2015-08-24 13:43:27 -0700577 || (mLastWorstUid[id].find(e->getUid())
578 == mLastWorstUid[id].end())) {
579 mLastWorstUid[id][e->getUid()] = it;
580 }
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800581 ++it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700582 continue;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800583 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700584
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700585 if (e->getUid() != worst) {
Mark Salyzyn59212762015-06-01 09:41:19 -0700586 leading = false;
Mark Salyzyne06a6e02015-04-20 14:08:56 -0700587 last.clear(e);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700588 ++it;
589 continue;
590 }
591
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700592 pruneRows--;
593 if (pruneRows == 0) {
594 break;
595 }
596
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700597 kick = true;
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700598
599 unsigned short len = e->getMsgLen();
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700600
601 // do not create any leading drops
602 if (leading) {
603 it = erase(it);
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700604 } else {
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700605 stats.drop(e);
606 e->setDropped(1);
Mark Salyzynaaad42f2015-09-30 07:40:09 -0700607 if (last.coalesce(e, 1)) {
608 it = erase(it, true);
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700609 } else {
610 last.add(e);
Mark Salyzyn5bb29722015-09-08 09:12:51 -0700611 if (!gc || (mLastWorstUid[id].find(worst)
612 == mLastWorstUid[id].end())) {
613 mLastWorstUid[id][worst] = it;
614 }
Mark Salyzyn5392aac2015-05-22 10:03:31 -0700615 ++it;
616 }
Mark Salyzynab0dcf62015-03-16 12:04:09 -0700617 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700618 if (worst_sizes < second_worst_sizes) {
619 break;
620 }
621 worst_sizes -= len;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800622 }
Mark Salyzyn2c9d9092015-04-17 15:38:04 -0700623 last.clear();
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800624
Mark Salyzyn1c950472014-04-01 17:19:47 -0700625 if (!kick || !mPrune.worstUidEnabled()) {
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800626 break; // the following loop will ask bad clients to skip/drop
627 }
628 }
629
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800630 bool whitelist = false;
Mark Salyzyn2b25c662015-09-16 15:34:00 -0700631 bool hasWhitelist = mPrune.nice() && !clearAll;
Mark Salyzyn64d6fe92014-02-06 18:11:13 -0800632 it = mLogElements.begin();
Mark Salyzyn0175b072014-02-26 09:50:16 -0800633 while((pruneRows > 0) && (it != mLogElements.end())) {
634 LogBufferElement *e = *it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700635
636 if (e->getLogId() != id) {
637 it++;
638 continue;
639 }
640
641 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700642 busy = true;
643
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700644 if (whitelist) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800645 break;
646 }
Mark Salyzyn1c950472014-04-01 17:19:47 -0700647
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700648 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
649 // kick a misbehaving log reader client off the island
650 oldest->release_Locked();
651 } else {
652 oldest->triggerSkip_Locked(id, pruneRows);
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800653 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700654 break;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800655 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700656
Mark Salyzync5bf3b82015-05-21 12:50:31 -0700657 if (hasWhitelist && !e->getDropped() && mPrune.nice(e)) { // WhiteListed
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700658 whitelist = true;
659 it++;
660 continue;
661 }
662
663 it = erase(it);
664 pruneRows--;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800665 }
666
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700667 // Do not save the whitelist if we are reader range limited
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800668 if (whitelist && (pruneRows > 0)) {
669 it = mLogElements.begin();
670 while((it != mLogElements.end()) && (pruneRows > 0)) {
671 LogBufferElement *e = *it;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700672
673 if (e->getLogId() != id) {
674 ++it;
675 continue;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800676 }
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700677
678 if (oldest && (oldest->mStart <= e->getSequence())) {
Mark Salyzync5dc9702015-09-16 15:34:00 -0700679 busy = true;
Mark Salyzyn97c1c2b2015-03-10 13:51:35 -0700680 if (stats.sizes(id) > (2 * log_buffer_size(id))) {
681 // kick a misbehaving log reader client off the island
682 oldest->release_Locked();
683 } else {
684 oldest->triggerSkip_Locked(id, pruneRows);
685 }
686 break;
687 }
688
689 it = erase(it);
690 pruneRows--;
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800691 }
692 }
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800693
Mark Salyzyn0175b072014-02-26 09:50:16 -0800694 LogTimeEntry::unlock();
Mark Salyzync5dc9702015-09-16 15:34:00 -0700695
696 return (pruneRows > 0) && busy;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800697}
698
699// clear all rows of type "id" from the buffer.
Mark Salyzync5dc9702015-09-16 15:34:00 -0700700bool LogBuffer::clear(log_id_t id, uid_t uid) {
701 bool busy = true;
702 // If it takes more than 4 tries (seconds) to clear, then kill reader(s)
703 for (int retry = 4;;) {
704 if (retry == 1) { // last pass
705 // Check if it is still busy after the sleep, we say prune
706 // one entry, not another clear run, so we are looking for
707 // the quick side effect of the return value to tell us if
708 // we have a _blocked_ reader.
709 pthread_mutex_lock(&mLogElementsLock);
710 busy = prune(id, 1, uid);
711 pthread_mutex_unlock(&mLogElementsLock);
712 // It is still busy, blocked reader(s), lets kill them all!
713 // otherwise, lets be a good citizen and preserve the slow
714 // readers and let the clear run (below) deal with determining
715 // if we are still blocked and return an error code to caller.
716 if (busy) {
717 LogTimeEntry::lock();
718 LastLogTimes::iterator times = mTimes.begin();
719 while (times != mTimes.end()) {
720 LogTimeEntry *entry = (*times);
721 // Killer punch
722 if (entry->owned_Locked() && entry->isWatching(id)) {
723 entry->release_Locked();
724 }
725 times++;
726 }
727 LogTimeEntry::unlock();
728 }
729 }
730 pthread_mutex_lock(&mLogElementsLock);
731 busy = prune(id, ULONG_MAX, uid);
732 pthread_mutex_unlock(&mLogElementsLock);
733 if (!busy || !--retry) {
734 break;
735 }
736 sleep (1); // Let reader(s) catch up after notification
737 }
738 return busy;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800739}
740
741// get the used space associated with "id".
742unsigned long LogBuffer::getSizeUsed(log_id_t id) {
743 pthread_mutex_lock(&mLogElementsLock);
Mark Salyzyn34facab2014-02-06 14:48:50 -0800744 size_t retval = stats.sizes(id);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800745 pthread_mutex_unlock(&mLogElementsLock);
746 return retval;
747}
748
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800749// set the total space allocated to "id"
750int LogBuffer::setSize(log_id_t id, unsigned long size) {
751 // Reasonable limits ...
Mark Salyzyn57a0af92014-05-09 17:44:18 -0700752 if (!valid_size(size)) {
Mark Salyzyndfa7a072014-02-11 12:29:31 -0800753 return -1;
754 }
755 pthread_mutex_lock(&mLogElementsLock);
756 log_buffer_size(id) = size;
757 pthread_mutex_unlock(&mLogElementsLock);
758 return 0;
759}
760
761// get the total space allocated to "id"
762unsigned long LogBuffer::getSize(log_id_t id) {
763 pthread_mutex_lock(&mLogElementsLock);
764 size_t retval = log_buffer_size(id);
765 pthread_mutex_unlock(&mLogElementsLock);
766 return retval;
767}
768
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800769uint64_t LogBuffer::flushTo(
770 SocketClient *reader, const uint64_t start, bool privileged,
771 int (*filter)(const LogBufferElement *element, void *arg), void *arg) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800772 LogBufferElementCollection::iterator it;
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800773 uint64_t max = start;
Mark Salyzyn0175b072014-02-26 09:50:16 -0800774 uid_t uid = reader->getUid();
775
776 pthread_mutex_lock(&mLogElementsLock);
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600777
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800778 if (start <= 1) {
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600779 // client wants to start from the beginning
780 it = mLogElements.begin();
781 } else {
782 // Client wants to start from some specified time. Chances are
783 // we are better off starting from the end of the time sorted list.
784 for (it = mLogElements.end(); it != mLogElements.begin(); /* do nothing */) {
785 --it;
786 LogBufferElement *element = *it;
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800787 if (element->getSequence() <= start) {
Dragoslav Mitrinovic8e8e8db2015-01-15 09:29:43 -0600788 it++;
789 break;
790 }
791 }
792 }
793
794 for (; it != mLogElements.end(); ++it) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800795 LogBufferElement *element = *it;
796
797 if (!privileged && (element->getUid() != uid)) {
798 continue;
799 }
800
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800801 if (element->getSequence() <= start) {
Mark Salyzyn0175b072014-02-26 09:50:16 -0800802 continue;
803 }
804
805 // NB: calling out to another object with mLogElementsLock held (safe)
Mark Salyzynf7c0f752015-03-03 13:39:37 -0800806 if (filter) {
807 int ret = (*filter)(element, arg);
808 if (ret == false) {
809 continue;
810 }
811 if (ret != true) {
812 break;
813 }
Mark Salyzyn0175b072014-02-26 09:50:16 -0800814 }
815
816 pthread_mutex_unlock(&mLogElementsLock);
817
818 // range locking in LastLogTimes looks after us
Mark Salyzyn21fb7e02015-04-20 07:26:27 -0700819 max = element->flushTo(reader, this);
Mark Salyzyn0175b072014-02-26 09:50:16 -0800820
821 if (max == element->FLUSH_ERROR) {
822 return max;
823 }
824
825 pthread_mutex_lock(&mLogElementsLock);
826 }
827 pthread_mutex_unlock(&mLogElementsLock);
828
829 return max;
830}
Mark Salyzyn34facab2014-02-06 14:48:50 -0800831
Mark Salyzyn73160ac2015-08-20 10:01:44 -0700832std::string LogBuffer::formatStatistics(uid_t uid, unsigned int logMask) {
Mark Salyzyn34facab2014-02-06 14:48:50 -0800833 pthread_mutex_lock(&mLogElementsLock);
834
Mark Salyzyn73160ac2015-08-20 10:01:44 -0700835 std::string ret = stats.format(uid, logMask);
Mark Salyzyn34facab2014-02-06 14:48:50 -0800836
837 pthread_mutex_unlock(&mLogElementsLock);
Mark Salyzyn73160ac2015-08-20 10:01:44 -0700838
839 return ret;
Mark Salyzyn34facab2014-02-06 14:48:50 -0800840}