blob: de4ab639419ad10c0c1c7fed475967f23134ad7b [file] [log] [blame]
Yao Chenab273e22017-09-06 12:53:50 -07001/*
2 * Copyright (C) 2017 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
Yao Chen8a8d16c2018-02-08 14:50:40 -080017#define DEBUG true // STOPSHIP if true
Joe Onorato9fc9edf2017-10-15 20:08:52 -070018#include "Log.h"
David Chen21582962017-11-01 17:32:46 -070019#include "statslog.h"
Yao Chenab273e22017-09-06 12:53:50 -070020
yro947fbce2017-11-15 22:50:23 -080021#include <android-base/file.h>
22#include <dirent.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070023#include "StatsLogProcessor.h"
Yangster-mac330af582018-02-08 15:24:38 -080024#include "stats_log_util.h"
yro947fbce2017-11-15 22:50:23 -080025#include "android-base/stringprintf.h"
Yao Chenb3561512017-11-21 18:07:17 -080026#include "guardrail/StatsdStats.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070027#include "metrics/CountMetricProducer.h"
Chenjie Yu85ed8382017-12-14 16:48:54 -080028#include "external/StatsPullerManager.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070029#include "stats_util.h"
yro947fbce2017-11-15 22:50:23 -080030#include "storage/StorageManager.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070031
yro00698da2017-09-15 10:06:40 -070032#include <log/log_event_list.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070033#include <utils/Errors.h>
David Chen16049572018-02-01 18:27:51 -080034#include <utils/SystemClock.h>
Yao Chenab273e22017-09-06 12:53:50 -070035
36using namespace android;
yro947fbce2017-11-15 22:50:23 -080037using android::base::StringPrintf;
yrob0378b02017-11-09 20:36:25 -080038using android::util::FIELD_COUNT_REPEATED;
yro17adac92017-11-08 23:16:29 -080039using android::util::FIELD_TYPE_BOOL;
40using android::util::FIELD_TYPE_FLOAT;
41using android::util::FIELD_TYPE_INT32;
42using android::util::FIELD_TYPE_INT64;
43using android::util::FIELD_TYPE_MESSAGE;
44using android::util::FIELD_TYPE_STRING;
45using android::util::ProtoOutputStream;
Yao Chen44cf27c2017-09-14 22:32:50 -070046using std::make_unique;
47using std::unique_ptr;
48using std::vector;
Bookatz906a35c2017-09-20 15:26:44 -070049
50namespace android {
51namespace os {
52namespace statsd {
Yao Chenab273e22017-09-06 12:53:50 -070053
yro947fbce2017-11-15 22:50:23 -080054// for ConfigMetricsReportList
yro17adac92017-11-08 23:16:29 -080055const int FIELD_ID_CONFIG_KEY = 1;
yro947fbce2017-11-15 22:50:23 -080056const int FIELD_ID_REPORTS = 2;
yro17adac92017-11-08 23:16:29 -080057// for ConfigKey
58const int FIELD_ID_UID = 1;
Yangster-mac94e197c2018-01-02 16:03:03 -080059const int FIELD_ID_ID = 2;
yro947fbce2017-11-15 22:50:23 -080060// for ConfigMetricsReport
Yao Chen4c959cb2018-02-13 13:27:48 -080061// const int FIELD_ID_METRICS = 1; // written in MetricsManager.cpp
yro947fbce2017-11-15 22:50:23 -080062const int FIELD_ID_UID_MAP = 2;
Yangster-mac330af582018-02-08 15:24:38 -080063const int FIELD_ID_LAST_REPORT_ELAPSED_NANOS = 3;
64const int FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS = 4;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -080065const int FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS = 5;
66const int FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS = 6;
67
Yangster-macb142cc82018-03-30 15:22:08 -070068#define NS_PER_HOUR 3600 * NS_PER_SEC
yro947fbce2017-11-15 22:50:23 -080069
yro03faf092017-12-12 00:17:50 -080070#define STATS_DATA_DIR "/data/misc/stats-data"
yro17adac92017-11-08 23:16:29 -080071
yro31eb67b2017-10-24 13:33:21 -070072StatsLogProcessor::StatsLogProcessor(const sp<UidMap>& uidMap,
Yangster-mac932ecec2018-02-01 10:23:52 -080073 const sp<AlarmMonitor>& anomalyAlarmMonitor,
74 const sp<AlarmMonitor>& periodicAlarmMonitor,
Yangster-mac20877162017-12-22 17:19:39 -080075 const long timeBaseSec,
David Chen1d7b0cd2017-11-15 14:20:04 -080076 const std::function<void(const ConfigKey&)>& sendBroadcast)
Chenjie Yu85ed8382017-12-14 16:48:54 -080077 : mUidMap(uidMap),
Yangster-mac932ecec2018-02-01 10:23:52 -080078 mAnomalyAlarmMonitor(anomalyAlarmMonitor),
79 mPeriodicAlarmMonitor(periodicAlarmMonitor),
Chenjie Yu85ed8382017-12-14 16:48:54 -080080 mSendBroadcast(sendBroadcast),
Yao Chen8f42ba02018-02-27 15:17:07 -080081 mTimeBaseSec(timeBaseSec),
82 mLastLogTimestamp(0) {
Yao Chenab273e22017-09-06 12:53:50 -070083}
84
Yao Chenef99c4f2017-09-22 16:26:54 -070085StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -070086}
87
Yangster-mace2cd6d52017-11-09 20:38:30 -080088void StatsLogProcessor::onAnomalyAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -070089 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -080090 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
Yangster-macb0d06282018-01-05 15:44:07 -080091 std::lock_guard<std::mutex> lock(mMetricsMutex);
Bookatzcc5adef22017-11-21 14:36:23 -080092 for (const auto& itr : mMetricsManagers) {
Yangster-mac932ecec2018-02-01 10:23:52 -080093 itr.second->onAnomalyAlarmFired(timestampNs, alarmSet);
94 }
95}
96void StatsLogProcessor::onPeriodicAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -070097 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -080098 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
99
100 std::lock_guard<std::mutex> lock(mMetricsMutex);
101 for (const auto& itr : mMetricsManagers) {
102 itr.second->onPeriodicAlarmFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800103 }
104}
105
Yao Chen8a8d16c2018-02-08 14:50:40 -0800106void updateUid(Value* value, int hostUid) {
107 int uid = value->int_value;
108 if (uid != hostUid) {
109 value->setInt(hostUid);
110 }
111}
112
Yangster-macd40053e2018-01-09 16:29:22 -0800113void StatsLogProcessor::mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent* event) const {
Yao Chenc40a19d2018-03-15 16:48:25 -0700114 if (android::util::AtomsInfo::kAtomsWithAttributionChain.find(event->GetTagId()) !=
115 android::util::AtomsInfo::kAtomsWithAttributionChain.end()) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800116 for (auto& value : *(event->getMutableValues())) {
117 if (value.mField.getPosAtDepth(0) > kAttributionField) {
118 break;
119 }
120 if (isAttributionUidField(value)) {
121 const int hostUid = mUidMap->getHostUidOrSelf(value.mValue.int_value);
122 updateUid(&value.mValue, hostUid);
123 }
Yangster-macd40053e2018-01-09 16:29:22 -0800124 }
Yao Chenc40a19d2018-03-15 16:48:25 -0700125 } else {
126 auto it = android::util::AtomsInfo::kAtomsWithUidField.find(event->GetTagId());
127 if (it != android::util::AtomsInfo::kAtomsWithUidField.end()) {
128 int uidField = it->second; // uidField is the field number in proto,
129 // starting from 1
130 if (uidField > 0 && (int)event->getValues().size() >= uidField &&
131 (event->getValues())[uidField - 1].mValue.getType() == INT) {
132 Value& value = (*event->getMutableValues())[uidField - 1].mValue;
133 const int hostUid = mUidMap->getHostUidOrSelf(value.int_value);
134 updateUid(&value, hostUid);
135 } else {
136 ALOGE("Malformed log, uid not found. %s", event->ToString().c_str());
137 }
138 }
Yao Chen312e8982017-12-05 15:29:03 -0800139 }
Yangster-macd40053e2018-01-09 16:29:22 -0800140}
141
142void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
143 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
144 bool is_create = event.GetBool(3, &err);
145 auto parent_uid = int(event.GetLong(1, &err2));
146 auto isolated_uid = int(event.GetLong(2, &err3));
147 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
148 if (is_create) {
149 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
150 } else {
151 mUidMap->removeIsolatedUid(isolated_uid, parent_uid);
152 }
153 } else {
154 ALOGE("Failed to parse uid in the isolated uid change event.");
155 }
156}
157
Yangster-macd40053e2018-01-09 16:29:22 -0800158void StatsLogProcessor::OnLogEvent(LogEvent* event) {
159 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-macb142cc82018-03-30 15:22:08 -0700160 const int64_t currentTimestampNs = event->GetElapsedTimestampNs();
Yangster-macb8382a12018-04-04 10:39:12 -0700161
Yangster-macb142cc82018-03-30 15:22:08 -0700162 if (currentTimestampNs < mLastLogTimestamp) {
Yangster-macb8382a12018-04-04 10:39:12 -0700163 StatsdStats::getInstance().noteLogEventSkipped(
164 event->GetTagId(), event->GetElapsedTimestampNs());
Yao Chen8f42ba02018-02-27 15:17:07 -0800165 return;
166 }
Yangster-macb142cc82018-03-30 15:22:08 -0700167
168 resetIfConfigTtlExpiredLocked(currentTimestampNs);
169
170 mLastLogTimestamp = currentTimestampNs;
Yangster-macd40053e2018-01-09 16:29:22 -0800171 StatsdStats::getInstance().noteAtomLogged(
Yangster-mac330af582018-02-08 15:24:38 -0800172 event->GetTagId(), event->GetElapsedTimestampNs() / NS_PER_SEC);
Yangster-macd40053e2018-01-09 16:29:22 -0800173
David Chen21582962017-11-01 17:32:46 -0700174 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800175 // The field numbers need to be currently updated by hand with atoms.proto
Yangster-macd40053e2018-01-09 16:29:22 -0800176 if (event->GetTagId() == android::util::ISOLATED_UID_CHANGED) {
177 onIsolatedUidChangedEventLocked(*event);
David Chencfc311d2018-01-23 17:55:54 -0800178 }
179
180 if (mMetricsManagers.empty()) {
181 return;
182 }
183
Yangster-macb142cc82018-03-30 15:22:08 -0700184 int64_t curTimeSec = getElapsedRealtimeSec();
Yangster-mac330af582018-02-08 15:24:38 -0800185 if (curTimeSec - mLastPullerCacheClearTimeSec > StatsdStats::kPullerCacheClearIntervalSec) {
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700186 mStatsPullerManager.ClearPullerCacheIfNecessary(curTimeSec * NS_PER_SEC);
Yangster-mac330af582018-02-08 15:24:38 -0800187 mLastPullerCacheClearTimeSec = curTimeSec;
Chenjie Yufa22d652018-02-05 14:37:48 -0800188 }
189
Yangster-macb142cc82018-03-30 15:22:08 -0700190
David Chencfc311d2018-01-23 17:55:54 -0800191 if (event->GetTagId() != android::util::ISOLATED_UID_CHANGED) {
Yangster-macd40053e2018-01-09 16:29:22 -0800192 // Map the isolated uid to host uid if necessary.
193 mapIsolatedUidToHostUidIfNecessaryLocked(event);
194 }
195
196 // pass the event to metrics managers.
197 for (auto& pair : mMetricsManagers) {
198 pair.second->onLogEvent(*event);
Yangster-mac330af582018-02-08 15:24:38 -0800199 flushIfNecessaryLocked(event->GetElapsedTimestampNs(), pair.first, *(pair.second));
David Chen21582962017-11-01 17:32:46 -0700200 }
Yao Chenab273e22017-09-06 12:53:50 -0700201}
202
Yangster-macc04feba2018-04-02 14:37:33 -0700203void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
204 const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800205 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-macb142cc82018-03-30 15:22:08 -0700206 OnConfigUpdatedLocked(timestampNs, key, config);
207}
208
209void StatsLogProcessor::OnConfigUpdatedLocked(
210 const int64_t timestampNs, const ConfigKey& key, const StatsdConfig& config) {
Tej Singh484524a2018-02-01 15:10:05 -0800211 VLOG("Updated configuration for key %s", key.ToString().c_str());
Yangster-mac932ecec2018-02-01 10:23:52 -0800212 sp<MetricsManager> newMetricsManager =
Yangster-macc04feba2018-04-02 14:37:33 -0700213 new MetricsManager(key, config, mTimeBaseSec, (timestampNs - 1) / NS_PER_SEC + 1, mUidMap,
Yangster-mac932ecec2018-02-01 10:23:52 -0800214 mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
Yao Chen44cf27c2017-09-14 22:32:50 -0700215
Yao Chencaf339d2017-10-06 16:01:10 -0700216 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700217 mUidMap->OnConfigUpdated(key);
Yao Chen147ce602017-12-22 14:35:34 -0800218 if (newMetricsManager->shouldAddUidMapListener()) {
Yao Chend10f7b12017-12-18 12:53:50 -0800219 // We have to add listener after the MetricsManager is constructed because it's
220 // not safe to create wp or sp from this pointer inside its constructor.
221 mUidMap->addListener(newMetricsManager.get());
222 }
Yangster-macb142cc82018-03-30 15:22:08 -0700223 newMetricsManager->refreshTtl(timestampNs);
Yao Chend10f7b12017-12-18 12:53:50 -0800224 mMetricsManagers[key] = newMetricsManager;
Yao Chenb3561512017-11-21 18:07:17 -0800225 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700226 } else {
227 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800228 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700229 }
yro00698da2017-09-15 10:06:40 -0700230}
Bookatz906a35c2017-09-20 15:26:44 -0700231
Yangster7c334a12017-11-22 14:24:24 -0800232size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800233 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700234 auto it = mMetricsManagers.find(key);
235 if (it == mMetricsManagers.end()) {
236 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800237 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700238 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800239 return it->second->byteSize();
240}
241
Yao Chen884c8c12018-01-26 10:36:25 -0800242void StatsLogProcessor::dumpStates(FILE* out, bool verbose) {
243 std::lock_guard<std::mutex> lock(mMetricsMutex);
244 fprintf(out, "MetricsManager count: %lu\n", (unsigned long)mMetricsManagers.size());
245 for (auto metricsManager : mMetricsManagers) {
246 metricsManager.second->dumpStates(out, verbose);
247 }
248}
249
yro4beccbe2018-03-15 19:42:05 -0700250/*
251 * onDumpReport dumps serialized ConfigMetricsReportList into outData.
252 */
Yangster-macb142cc82018-03-30 15:22:08 -0700253void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
Yao Chen8a8d16c2018-02-08 14:50:40 -0800254 vector<uint8_t>* outData) {
Yangster-macb0d06282018-01-05 15:44:07 -0800255 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800256
David Chen1d7b0cd2017-11-15 14:20:04 -0800257 auto it = mMetricsManagers.find(key);
258 if (it == mMetricsManagers.end()) {
259 ALOGW("Config source %s does not exist", key.ToString().c_str());
260 return;
261 }
262
263 // This allows another broadcast to be sent within the rate-limit period if we get close to
264 // filling the buffer again soon.
David Chen1d7b0cd2017-11-15 14:20:04 -0800265 mLastBroadcastTimes.erase(key);
Yao Chen729093d2017-10-16 10:33:26 -0700266
yro17adac92017-11-08 23:16:29 -0800267 ProtoOutputStream proto;
268
yro947fbce2017-11-15 22:50:23 -0800269 // Start of ConfigKey.
Yi Jin5ee07872018-03-05 18:18:27 -0800270 uint64_t configKeyToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
yro17adac92017-11-08 23:16:29 -0800271 proto.write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
Yangster-mac94e197c2018-01-02 16:03:03 -0800272 proto.write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
yro17adac92017-11-08 23:16:29 -0800273 proto.end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800274 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800275
yro947fbce2017-11-15 22:50:23 -0800276 // Start of ConfigMetricsReport (reports).
Yi Jin5ee07872018-03-05 18:18:27 -0800277 uint64_t reportsToken =
yro947fbce2017-11-15 22:50:23 -0800278 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
yro4beccbe2018-03-15 19:42:05 -0700279 onConfigMetricsReportLocked(key, dumpTimeStampNs, &proto);
yro947fbce2017-11-15 22:50:23 -0800280 proto.end(reportsToken);
yro4beccbe2018-03-15 19:42:05 -0700281 // End of ConfigMetricsReport (reports).
282
yro947fbce2017-11-15 22:50:23 -0800283
284 // Then, check stats-data directory to see there's any file containing
285 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
yro4beccbe2018-03-15 19:42:05 -0700286 StorageManager::appendConfigMetricsReport(key, &proto);
yro947fbce2017-11-15 22:50:23 -0800287
David Chen1d7b0cd2017-11-15 14:20:04 -0800288 if (outData != nullptr) {
289 outData->clear();
290 outData->resize(proto.size());
291 size_t pos = 0;
292 auto iter = proto.data();
293 while (iter.readBuffer() != NULL) {
294 size_t toRead = iter.currentToRead();
295 std::memcpy(&((*outData)[pos]), iter.readBuffer(), toRead);
296 pos += toRead;
297 iter.rp()->move(toRead);
298 }
yro17adac92017-11-08 23:16:29 -0800299 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800300
Yao Chen69f1baf2017-11-27 17:25:36 -0800301 StatsdStats::getInstance().noteMetricsReportSent(key);
Yao Chen729093d2017-10-16 10:33:26 -0700302}
303
yro4beccbe2018-03-15 19:42:05 -0700304/*
305 * onConfigMetricsReportLocked dumps serialized ConfigMetricsReport into outData.
306 */
307void StatsLogProcessor::onConfigMetricsReportLocked(const ConfigKey& key,
Yangster-macb142cc82018-03-30 15:22:08 -0700308 const int64_t dumpTimeStampNs,
yro4beccbe2018-03-15 19:42:05 -0700309 ProtoOutputStream* proto) {
310 // We already checked whether key exists in mMetricsManagers in
311 // WriteDataToDisk.
312 auto it = mMetricsManagers.find(key);
313 int64_t lastReportTimeNs = it->second->getLastReportTimeNs();
314 int64_t lastReportWallClockNs = it->second->getLastReportWallClockNs();
315
316 // First, fill in ConfigMetricsReport using current data on memory, which
317 // starts from filling in StatsLogReport's.
318 it->second->onDumpReport(dumpTimeStampNs, proto);
319
320 // Fill in UidMap.
321 uint64_t uidMapToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP);
322 mUidMap->appendUidMap(key, proto);
323 proto->end(uidMapToken);
324
325 // Fill in the timestamps.
326 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_ELAPSED_NANOS,
327 (long long)lastReportTimeNs);
328 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS,
329 (long long)dumpTimeStampNs);
330 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS,
331 (long long)lastReportWallClockNs);
332 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS,
333 (long long)getWallClockNs());
334
Yangster-macb142cc82018-03-30 15:22:08 -0700335}
yro4beccbe2018-03-15 19:42:05 -0700336
Yangster-macb142cc82018-03-30 15:22:08 -0700337void StatsLogProcessor::resetIfConfigTtlExpiredLocked(const int64_t timestampNs) {
338 std::vector<ConfigKey> configKeysTtlExpired;
339 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
340 if (it->second != nullptr && !it->second->isInTtl(timestampNs)) {
341 configKeysTtlExpired.push_back(it->first);
342 }
343 }
344
345 for (const auto& key : configKeysTtlExpired) {
346 StatsdConfig config;
347 if (StorageManager::readConfigFromDisk(key, &config)) {
348 OnConfigUpdatedLocked(timestampNs, key, config);
349 StatsdStats::getInstance().noteConfigReset(key);
350 } else {
351 ALOGE("Failed to read backup config from disk for : %s", key.ToString().c_str());
352 auto it = mMetricsManagers.find(key);
353 if (it != mMetricsManagers.end()) {
354 it->second->refreshTtl(timestampNs);
355 }
356 }
357 }
yro4beccbe2018-03-15 19:42:05 -0700358}
359
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700360void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800361 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700362 auto it = mMetricsManagers.find(key);
363 if (it != mMetricsManagers.end()) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700364 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700365 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700366 }
Yao Chenb3561512017-11-21 18:07:17 -0800367 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800368
David Chen1d7b0cd2017-11-15 14:20:04 -0800369 mLastBroadcastTimes.erase(key);
Chenjie Yufa22d652018-02-05 14:37:48 -0800370
371 if (mMetricsManagers.empty()) {
372 mStatsPullerManager.ForceClearPullerCache();
373 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700374}
375
Yangster-macb0d06282018-01-05 15:44:07 -0800376void StatsLogProcessor::flushIfNecessaryLocked(
Yangster-macb142cc82018-03-30 15:22:08 -0700377 int64_t timestampNs, const ConfigKey& key, MetricsManager& metricsManager) {
David Chend9269e22017-12-05 13:43:51 -0800378 auto lastCheckTime = mLastByteSizeTimes.find(key);
379 if (lastCheckTime != mLastByteSizeTimes.end()) {
380 if (timestampNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
381 return;
382 }
383 }
384
385 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
386 size_t totalBytes = metricsManager.byteSize();
387 mLastByteSizeTimes[key] = timestampNs;
388 if (totalBytes >
389 StatsdStats::kMaxMetricsBytesPerConfig) { // Too late. We need to start clearing data.
Yao Chen06dba5d2018-01-26 13:38:16 -0800390 metricsManager.dropData(timestampNs);
David Chen12942952017-12-04 14:28:43 -0800391 StatsdStats::getInstance().noteDataDropped(key);
392 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chen4c6d97a2018-03-22 16:31:40 -0700393 } else if (totalBytes > StatsdStats::kBytesPerConfigTriggerGetData) {
David Chend9269e22017-12-05 13:43:51 -0800394 // Send broadcast so that receivers can pull data.
395 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
396 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
397 if (timestampNs - lastBroadcastTime->second < StatsdStats::kMinBroadcastPeriodNs) {
398 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800399 return;
400 }
401 }
402 mLastBroadcastTimes[key] = timestampNs;
Yao Chenb3561512017-11-21 18:07:17 -0800403 VLOG("StatsD requesting broadcast for %s", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800404 mSendBroadcast(key);
Yao Chenb3561512017-11-21 18:07:17 -0800405 StatsdStats::getInstance().noteBroadcastSent(key);
yro31eb67b2017-10-24 13:33:21 -0700406 }
407}
408
yro947fbce2017-11-15 22:50:23 -0800409void StatsLogProcessor::WriteDataToDisk() {
Yangster-macb0d06282018-01-05 15:44:07 -0800410 std::lock_guard<std::mutex> lock(mMetricsMutex);
yro947fbce2017-11-15 22:50:23 -0800411 for (auto& pair : mMetricsManagers) {
412 const ConfigKey& key = pair.first;
yro4beccbe2018-03-15 19:42:05 -0700413 ProtoOutputStream proto;
414 onConfigMetricsReportLocked(key, getElapsedRealtimeNs(), &proto);
Yangster-mac330af582018-02-08 15:24:38 -0800415 string file_name = StringPrintf("%s/%ld_%d_%lld", STATS_DATA_DIR,
416 (long)getWallClockSec(), key.GetUid(), (long long)key.GetId());
yro4beccbe2018-03-15 19:42:05 -0700417 android::base::unique_fd fd(open(file_name.c_str(),
418 O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
419 if (fd == -1) {
420 VLOG("Attempt to write %s but failed", file_name.c_str());
421 return;
422 }
423 proto.flush(fd.get());
yro947fbce2017-11-15 22:50:23 -0800424 }
425}
426
Yao Chenef99c4f2017-09-22 16:26:54 -0700427} // namespace statsd
428} // namespace os
429} // namespace android