blob: f2443e8fb128bf8c006ca4adbc2db1a7ff704f04 [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-mac15f6bbc2018-04-08 11:52:26 -070075 const int64_t timeBaseNs,
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),
Yangster-mac15f6bbc2018-04-08 11:52:26 -070081 mTimeBaseNs(timeBaseNs),
Yao Chen163d2602018-04-10 10:39:53 -070082 mLargestTimestampSeen(0),
83 mLastTimestampSeen(0) {
Yao Chenab273e22017-09-06 12:53:50 -070084}
85
Yao Chenef99c4f2017-09-22 16:26:54 -070086StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -070087}
88
Yangster-mace2cd6d52017-11-09 20:38:30 -080089void StatsLogProcessor::onAnomalyAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -070090 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -080091 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
Yangster-macb0d06282018-01-05 15:44:07 -080092 std::lock_guard<std::mutex> lock(mMetricsMutex);
Bookatzcc5adef22017-11-21 14:36:23 -080093 for (const auto& itr : mMetricsManagers) {
Yangster-mac932ecec2018-02-01 10:23:52 -080094 itr.second->onAnomalyAlarmFired(timestampNs, alarmSet);
95 }
96}
97void StatsLogProcessor::onPeriodicAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -070098 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -080099 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
100
101 std::lock_guard<std::mutex> lock(mMetricsMutex);
102 for (const auto& itr : mMetricsManagers) {
103 itr.second->onPeriodicAlarmFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800104 }
105}
106
Yao Chen8a8d16c2018-02-08 14:50:40 -0800107void updateUid(Value* value, int hostUid) {
108 int uid = value->int_value;
109 if (uid != hostUid) {
110 value->setInt(hostUid);
111 }
112}
113
Yangster-macd40053e2018-01-09 16:29:22 -0800114void StatsLogProcessor::mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent* event) const {
Yao Chenc40a19d2018-03-15 16:48:25 -0700115 if (android::util::AtomsInfo::kAtomsWithAttributionChain.find(event->GetTagId()) !=
116 android::util::AtomsInfo::kAtomsWithAttributionChain.end()) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800117 for (auto& value : *(event->getMutableValues())) {
118 if (value.mField.getPosAtDepth(0) > kAttributionField) {
119 break;
120 }
121 if (isAttributionUidField(value)) {
122 const int hostUid = mUidMap->getHostUidOrSelf(value.mValue.int_value);
123 updateUid(&value.mValue, hostUid);
124 }
Yangster-macd40053e2018-01-09 16:29:22 -0800125 }
Yao Chenc40a19d2018-03-15 16:48:25 -0700126 } else {
127 auto it = android::util::AtomsInfo::kAtomsWithUidField.find(event->GetTagId());
128 if (it != android::util::AtomsInfo::kAtomsWithUidField.end()) {
129 int uidField = it->second; // uidField is the field number in proto,
130 // starting from 1
131 if (uidField > 0 && (int)event->getValues().size() >= uidField &&
132 (event->getValues())[uidField - 1].mValue.getType() == INT) {
133 Value& value = (*event->getMutableValues())[uidField - 1].mValue;
134 const int hostUid = mUidMap->getHostUidOrSelf(value.int_value);
135 updateUid(&value, hostUid);
136 } else {
137 ALOGE("Malformed log, uid not found. %s", event->ToString().c_str());
138 }
139 }
Yao Chen312e8982017-12-05 15:29:03 -0800140 }
Yangster-macd40053e2018-01-09 16:29:22 -0800141}
142
143void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
144 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
145 bool is_create = event.GetBool(3, &err);
146 auto parent_uid = int(event.GetLong(1, &err2));
147 auto isolated_uid = int(event.GetLong(2, &err3));
148 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
149 if (is_create) {
150 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
151 } else {
152 mUidMap->removeIsolatedUid(isolated_uid, parent_uid);
153 }
154 } else {
155 ALOGE("Failed to parse uid in the isolated uid change event.");
156 }
157}
158
Yangster-macd40053e2018-01-09 16:29:22 -0800159void StatsLogProcessor::OnLogEvent(LogEvent* event) {
Yao Chen163d2602018-04-10 10:39:53 -0700160 OnLogEvent(event, false);
161}
162
163void StatsLogProcessor::OnLogEvent(LogEvent* event, bool reconnected) {
Yangster-macd40053e2018-01-09 16:29:22 -0800164 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-macb142cc82018-03-30 15:22:08 -0700165 const int64_t currentTimestampNs = event->GetElapsedTimestampNs();
Yangster-macb8382a12018-04-04 10:39:12 -0700166
Yao Chen163d2602018-04-10 10:39:53 -0700167 if (reconnected && mLastTimestampSeen != 0) {
168 // LogReader tells us the connection has just been reset. Now we need
169 // to enter reconnection state to find the last CP.
170 mInReconnection = true;
171 }
172
173 if (mInReconnection) {
174 // We see the checkpoint
175 if (currentTimestampNs == mLastTimestampSeen) {
176 mInReconnection = false;
177 // Found the CP. ignore this event, and we will start to read from next event.
178 return;
179 }
180 if (currentTimestampNs > mLargestTimestampSeen) {
181 // We see a new log but CP has not been found yet. Give up now.
182 mLogLossCount++;
183 mInReconnection = false;
184 StatsdStats::getInstance().noteLogLost(currentTimestampNs);
185 // Persist the data before we reset. Do we want this?
186 WriteDataToDiskLocked();
187 // We see fresher event before we see the checkpoint. We might have lost data.
188 // The best we can do is to reset.
189 std::vector<ConfigKey> configKeys;
190 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
191 configKeys.push_back(it->first);
192 }
193 resetConfigsLocked(currentTimestampNs, configKeys);
194 } else {
195 // Still in search of the CP. Keep going.
196 return;
197 }
198 }
199
200 mLogCount++;
201 mLastTimestampSeen = currentTimestampNs;
202 if (mLargestTimestampSeen < currentTimestampNs) {
203 mLargestTimestampSeen = currentTimestampNs;
Yao Chen8f42ba02018-02-27 15:17:07 -0800204 }
Yangster-macb142cc82018-03-30 15:22:08 -0700205
206 resetIfConfigTtlExpiredLocked(currentTimestampNs);
207
Yangster-macd40053e2018-01-09 16:29:22 -0800208 StatsdStats::getInstance().noteAtomLogged(
Yangster-mac330af582018-02-08 15:24:38 -0800209 event->GetTagId(), event->GetElapsedTimestampNs() / NS_PER_SEC);
Yangster-macd40053e2018-01-09 16:29:22 -0800210
David Chen21582962017-11-01 17:32:46 -0700211 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800212 // The field numbers need to be currently updated by hand with atoms.proto
Yangster-macd40053e2018-01-09 16:29:22 -0800213 if (event->GetTagId() == android::util::ISOLATED_UID_CHANGED) {
214 onIsolatedUidChangedEventLocked(*event);
David Chencfc311d2018-01-23 17:55:54 -0800215 }
216
217 if (mMetricsManagers.empty()) {
218 return;
219 }
220
Yangster-macb142cc82018-03-30 15:22:08 -0700221 int64_t curTimeSec = getElapsedRealtimeSec();
Yangster-mac330af582018-02-08 15:24:38 -0800222 if (curTimeSec - mLastPullerCacheClearTimeSec > StatsdStats::kPullerCacheClearIntervalSec) {
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700223 mStatsPullerManager.ClearPullerCacheIfNecessary(curTimeSec * NS_PER_SEC);
Yangster-mac330af582018-02-08 15:24:38 -0800224 mLastPullerCacheClearTimeSec = curTimeSec;
Chenjie Yufa22d652018-02-05 14:37:48 -0800225 }
226
Yangster-macb142cc82018-03-30 15:22:08 -0700227
David Chencfc311d2018-01-23 17:55:54 -0800228 if (event->GetTagId() != android::util::ISOLATED_UID_CHANGED) {
Yangster-macd40053e2018-01-09 16:29:22 -0800229 // Map the isolated uid to host uid if necessary.
230 mapIsolatedUidToHostUidIfNecessaryLocked(event);
231 }
232
233 // pass the event to metrics managers.
234 for (auto& pair : mMetricsManagers) {
235 pair.second->onLogEvent(*event);
Yangster-mac330af582018-02-08 15:24:38 -0800236 flushIfNecessaryLocked(event->GetElapsedTimestampNs(), pair.first, *(pair.second));
David Chen21582962017-11-01 17:32:46 -0700237 }
Yao Chenab273e22017-09-06 12:53:50 -0700238}
239
Yangster-macc04feba2018-04-02 14:37:33 -0700240void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
241 const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800242 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-macb142cc82018-03-30 15:22:08 -0700243 OnConfigUpdatedLocked(timestampNs, key, config);
244}
245
246void StatsLogProcessor::OnConfigUpdatedLocked(
247 const int64_t timestampNs, const ConfigKey& key, const StatsdConfig& config) {
Tej Singh484524a2018-02-01 15:10:05 -0800248 VLOG("Updated configuration for key %s", key.ToString().c_str());
Yangster-mac932ecec2018-02-01 10:23:52 -0800249 sp<MetricsManager> newMetricsManager =
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700250 new MetricsManager(key, config, mTimeBaseNs, timestampNs, mUidMap,
Yangster-mac932ecec2018-02-01 10:23:52 -0800251 mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
Yangster-mace68f3a52018-04-04 00:01:43 -0700252 auto it = mMetricsManagers.find(key);
253 if (it != mMetricsManagers.end()) {
254 WriteDataToDiskLocked(it->first);
255 }
Yao Chencaf339d2017-10-06 16:01:10 -0700256 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700257 mUidMap->OnConfigUpdated(key);
Yao Chen147ce602017-12-22 14:35:34 -0800258 if (newMetricsManager->shouldAddUidMapListener()) {
Yao Chend10f7b12017-12-18 12:53:50 -0800259 // We have to add listener after the MetricsManager is constructed because it's
260 // not safe to create wp or sp from this pointer inside its constructor.
261 mUidMap->addListener(newMetricsManager.get());
262 }
Yangster-macb142cc82018-03-30 15:22:08 -0700263 newMetricsManager->refreshTtl(timestampNs);
Yao Chend10f7b12017-12-18 12:53:50 -0800264 mMetricsManagers[key] = newMetricsManager;
Yao Chenb3561512017-11-21 18:07:17 -0800265 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700266 } else {
267 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800268 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700269 }
yro00698da2017-09-15 10:06:40 -0700270}
Bookatz906a35c2017-09-20 15:26:44 -0700271
Yangster7c334a12017-11-22 14:24:24 -0800272size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800273 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700274 auto it = mMetricsManagers.find(key);
275 if (it == mMetricsManagers.end()) {
276 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800277 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700278 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800279 return it->second->byteSize();
280}
281
Yao Chen884c8c12018-01-26 10:36:25 -0800282void StatsLogProcessor::dumpStates(FILE* out, bool verbose) {
283 std::lock_guard<std::mutex> lock(mMetricsMutex);
284 fprintf(out, "MetricsManager count: %lu\n", (unsigned long)mMetricsManagers.size());
285 for (auto metricsManager : mMetricsManagers) {
286 metricsManager.second->dumpStates(out, verbose);
287 }
288}
289
yro4beccbe2018-03-15 19:42:05 -0700290/*
291 * onDumpReport dumps serialized ConfigMetricsReportList into outData.
292 */
Yangster-macb142cc82018-03-30 15:22:08 -0700293void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700294 const bool include_current_partial_bucket,
Yao Chen8a8d16c2018-02-08 14:50:40 -0800295 vector<uint8_t>* outData) {
Yangster-macb0d06282018-01-05 15:44:07 -0800296 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800297
yro17adac92017-11-08 23:16:29 -0800298 ProtoOutputStream proto;
299
yro947fbce2017-11-15 22:50:23 -0800300 // Start of ConfigKey.
Yi Jin5ee07872018-03-05 18:18:27 -0800301 uint64_t configKeyToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
yro17adac92017-11-08 23:16:29 -0800302 proto.write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
Yangster-mac94e197c2018-01-02 16:03:03 -0800303 proto.write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
yro17adac92017-11-08 23:16:29 -0800304 proto.end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800305 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800306
yro947fbce2017-11-15 22:50:23 -0800307 // Then, check stats-data directory to see there's any file containing
308 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
yro4beccbe2018-03-15 19:42:05 -0700309 StorageManager::appendConfigMetricsReport(key, &proto);
yro947fbce2017-11-15 22:50:23 -0800310
Yangster-mace68f3a52018-04-04 00:01:43 -0700311 auto it = mMetricsManagers.find(key);
312 if (it != mMetricsManagers.end()) {
313 // This allows another broadcast to be sent within the rate-limit period if we get close to
314 // filling the buffer again soon.
315 mLastBroadcastTimes.erase(key);
316
317 // Start of ConfigMetricsReport (reports).
318 uint64_t reportsToken =
319 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
320 onConfigMetricsReportLocked(key, dumpTimeStampNs, include_current_partial_bucket, &proto);
321 proto.end(reportsToken);
322 // End of ConfigMetricsReport (reports).
323 } else {
324 ALOGW("Config source %s does not exist", key.ToString().c_str());
325 }
326
David Chen1d7b0cd2017-11-15 14:20:04 -0800327 if (outData != nullptr) {
328 outData->clear();
329 outData->resize(proto.size());
330 size_t pos = 0;
331 auto iter = proto.data();
332 while (iter.readBuffer() != NULL) {
333 size_t toRead = iter.currentToRead();
334 std::memcpy(&((*outData)[pos]), iter.readBuffer(), toRead);
335 pos += toRead;
336 iter.rp()->move(toRead);
337 }
yro17adac92017-11-08 23:16:29 -0800338 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800339
Yangster-mace68f3a52018-04-04 00:01:43 -0700340 StatsdStats::getInstance().noteMetricsReportSent(key, proto.size());
Yao Chen729093d2017-10-16 10:33:26 -0700341}
342
yro4beccbe2018-03-15 19:42:05 -0700343/*
344 * onConfigMetricsReportLocked dumps serialized ConfigMetricsReport into outData.
345 */
346void StatsLogProcessor::onConfigMetricsReportLocked(const ConfigKey& key,
Yangster-macb142cc82018-03-30 15:22:08 -0700347 const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700348 const bool include_current_partial_bucket,
yro4beccbe2018-03-15 19:42:05 -0700349 ProtoOutputStream* proto) {
350 // We already checked whether key exists in mMetricsManagers in
351 // WriteDataToDisk.
352 auto it = mMetricsManagers.find(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700353 if (it == mMetricsManagers.end()) {
354 return;
355 }
yro4beccbe2018-03-15 19:42:05 -0700356 int64_t lastReportTimeNs = it->second->getLastReportTimeNs();
357 int64_t lastReportWallClockNs = it->second->getLastReportWallClockNs();
358
359 // First, fill in ConfigMetricsReport using current data on memory, which
360 // starts from filling in StatsLogReport's.
Yangster-mace68f3a52018-04-04 00:01:43 -0700361 it->second->onDumpReport(dumpTimeStampNs, include_current_partial_bucket, proto);
yro4beccbe2018-03-15 19:42:05 -0700362
363 // Fill in UidMap.
364 uint64_t uidMapToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP);
David Chenbd125272018-04-04 19:02:50 -0700365 mUidMap->appendUidMap(dumpTimeStampNs, key, proto);
yro4beccbe2018-03-15 19:42:05 -0700366 proto->end(uidMapToken);
367
368 // Fill in the timestamps.
369 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_ELAPSED_NANOS,
370 (long long)lastReportTimeNs);
371 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS,
372 (long long)dumpTimeStampNs);
373 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS,
374 (long long)lastReportWallClockNs);
375 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS,
376 (long long)getWallClockNs());
Yangster-macb142cc82018-03-30 15:22:08 -0700377}
yro4beccbe2018-03-15 19:42:05 -0700378
Yao Chen163d2602018-04-10 10:39:53 -0700379void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs,
380 const std::vector<ConfigKey>& configs) {
381 for (const auto& key : configs) {
Yangster-macb142cc82018-03-30 15:22:08 -0700382 StatsdConfig config;
383 if (StorageManager::readConfigFromDisk(key, &config)) {
384 OnConfigUpdatedLocked(timestampNs, key, config);
385 StatsdStats::getInstance().noteConfigReset(key);
386 } else {
387 ALOGE("Failed to read backup config from disk for : %s", key.ToString().c_str());
388 auto it = mMetricsManagers.find(key);
389 if (it != mMetricsManagers.end()) {
390 it->second->refreshTtl(timestampNs);
391 }
392 }
393 }
yro4beccbe2018-03-15 19:42:05 -0700394}
395
Yao Chen163d2602018-04-10 10:39:53 -0700396void StatsLogProcessor::resetIfConfigTtlExpiredLocked(const int64_t timestampNs) {
397 std::vector<ConfigKey> configKeysTtlExpired;
398 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
399 if (it->second != nullptr && !it->second->isInTtl(timestampNs)) {
400 configKeysTtlExpired.push_back(it->first);
401 }
402 }
403 if (configKeysTtlExpired.size() > 0) {
404 resetConfigsLocked(timestampNs, configKeysTtlExpired);
405 }
406}
407
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700408void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800409 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700410 auto it = mMetricsManagers.find(key);
411 if (it != mMetricsManagers.end()) {
Yangster-mace68f3a52018-04-04 00:01:43 -0700412 WriteDataToDiskLocked(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700413 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700414 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700415 }
Yao Chenb3561512017-11-21 18:07:17 -0800416 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800417
David Chen1d7b0cd2017-11-15 14:20:04 -0800418 mLastBroadcastTimes.erase(key);
Chenjie Yufa22d652018-02-05 14:37:48 -0800419
420 if (mMetricsManagers.empty()) {
421 mStatsPullerManager.ForceClearPullerCache();
422 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700423}
424
Yangster-macb0d06282018-01-05 15:44:07 -0800425void StatsLogProcessor::flushIfNecessaryLocked(
Yangster-macb142cc82018-03-30 15:22:08 -0700426 int64_t timestampNs, const ConfigKey& key, MetricsManager& metricsManager) {
David Chend9269e22017-12-05 13:43:51 -0800427 auto lastCheckTime = mLastByteSizeTimes.find(key);
428 if (lastCheckTime != mLastByteSizeTimes.end()) {
429 if (timestampNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
430 return;
431 }
432 }
433
434 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
435 size_t totalBytes = metricsManager.byteSize();
436 mLastByteSizeTimes[key] = timestampNs;
437 if (totalBytes >
438 StatsdStats::kMaxMetricsBytesPerConfig) { // Too late. We need to start clearing data.
Yao Chen06dba5d2018-01-26 13:38:16 -0800439 metricsManager.dropData(timestampNs);
David Chen12942952017-12-04 14:28:43 -0800440 StatsdStats::getInstance().noteDataDropped(key);
441 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chen4c6d97a2018-03-22 16:31:40 -0700442 } else if (totalBytes > StatsdStats::kBytesPerConfigTriggerGetData) {
David Chend9269e22017-12-05 13:43:51 -0800443 // Send broadcast so that receivers can pull data.
444 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
445 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
446 if (timestampNs - lastBroadcastTime->second < StatsdStats::kMinBroadcastPeriodNs) {
447 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800448 return;
449 }
450 }
451 mLastBroadcastTimes[key] = timestampNs;
Yao Chenb3561512017-11-21 18:07:17 -0800452 VLOG("StatsD requesting broadcast for %s", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800453 mSendBroadcast(key);
Yao Chenb3561512017-11-21 18:07:17 -0800454 StatsdStats::getInstance().noteBroadcastSent(key);
yro31eb67b2017-10-24 13:33:21 -0700455 }
456}
457
Yangster-mace68f3a52018-04-04 00:01:43 -0700458void StatsLogProcessor::WriteDataToDiskLocked(const ConfigKey& key) {
459 ProtoOutputStream proto;
460 onConfigMetricsReportLocked(key, getElapsedRealtimeNs(),
461 true /* include_current_partial_bucket*/, &proto);
462 string file_name = StringPrintf("%s/%ld_%d_%lld", STATS_DATA_DIR,
463 (long)getWallClockSec(), key.GetUid(), (long long)key.GetId());
464 android::base::unique_fd fd(open(file_name.c_str(),
465 O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
466 if (fd == -1) {
467 ALOGE("Attempt to write %s but failed", file_name.c_str());
468 return;
469 }
470 proto.flush(fd.get());
471}
472
473void StatsLogProcessor::WriteDataToDiskLocked() {
474 for (auto& pair : mMetricsManagers) {
475 WriteDataToDiskLocked(pair.first);
476 }
477}
478
yro947fbce2017-11-15 22:50:23 -0800479void StatsLogProcessor::WriteDataToDisk() {
Yangster-macb0d06282018-01-05 15:44:07 -0800480 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mace68f3a52018-04-04 00:01:43 -0700481 WriteDataToDiskLocked();
yro947fbce2017-11-15 22:50:23 -0800482}
483
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700484void StatsLogProcessor::informPullAlarmFired(const int64_t timestampNs) {
485 mStatsPullerManager.OnAlarmFired(timestampNs);
486}
487
Yao Chenef99c4f2017-09-22 16:26:54 -0700488} // namespace statsd
489} // namespace os
490} // namespace android