blob: e7adba4d194af39ae67234d6592aeb2c3db9852c [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
Yangster-mac754e29e2018-05-02 12:23:17 -070017#define DEBUG false // 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;
Chenjie Yue36018b2018-04-16 15:18:30 -070067const int FIELD_ID_DUMP_REPORT_REASON = 8;
Yangster-mac9def8e32018-04-17 13:55:51 -070068const int FIELD_ID_STRINGS = 9;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -080069
Yangster-macb142cc82018-03-30 15:22:08 -070070#define NS_PER_HOUR 3600 * NS_PER_SEC
yro947fbce2017-11-15 22:50:23 -080071
yro03faf092017-12-12 00:17:50 -080072#define STATS_DATA_DIR "/data/misc/stats-data"
yro17adac92017-11-08 23:16:29 -080073
Tej Singh42f9e062018-11-09 10:01:00 -080074// Cool down period for writing data to disk to avoid overwriting files.
75#define WRITE_DATA_COOL_DOWN_SEC 5
76
yro31eb67b2017-10-24 13:33:21 -070077StatsLogProcessor::StatsLogProcessor(const sp<UidMap>& uidMap,
Yangster-mac932ecec2018-02-01 10:23:52 -080078 const sp<AlarmMonitor>& anomalyAlarmMonitor,
79 const sp<AlarmMonitor>& periodicAlarmMonitor,
Yangster-mac15f6bbc2018-04-08 11:52:26 -070080 const int64_t timeBaseNs,
David Chen48944902018-05-03 10:29:11 -070081 const std::function<bool(const ConfigKey&)>& sendBroadcast)
Chenjie Yu85ed8382017-12-14 16:48:54 -080082 : mUidMap(uidMap),
Yangster-mac932ecec2018-02-01 10:23:52 -080083 mAnomalyAlarmMonitor(anomalyAlarmMonitor),
84 mPeriodicAlarmMonitor(periodicAlarmMonitor),
Chenjie Yu85ed8382017-12-14 16:48:54 -080085 mSendBroadcast(sendBroadcast),
Yangster-mac15f6bbc2018-04-08 11:52:26 -070086 mTimeBaseNs(timeBaseNs),
Yao Chen163d2602018-04-10 10:39:53 -070087 mLargestTimestampSeen(0),
88 mLastTimestampSeen(0) {
Chenjie Yu021e2532018-05-16 12:23:07 -070089 mStatsPullerManager.ForceClearPullerCache();
Yao Chenab273e22017-09-06 12:53:50 -070090}
91
Yao Chenef99c4f2017-09-22 16:26:54 -070092StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -070093}
94
Yangster-mace2cd6d52017-11-09 20:38:30 -080095void StatsLogProcessor::onAnomalyAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -070096 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -080097 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
Yangster-macb0d06282018-01-05 15:44:07 -080098 std::lock_guard<std::mutex> lock(mMetricsMutex);
Bookatzcc5adef2017-11-21 14:36:23 -080099 for (const auto& itr : mMetricsManagers) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800100 itr.second->onAnomalyAlarmFired(timestampNs, alarmSet);
101 }
102}
103void StatsLogProcessor::onPeriodicAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700104 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800105 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
106
107 std::lock_guard<std::mutex> lock(mMetricsMutex);
108 for (const auto& itr : mMetricsManagers) {
109 itr.second->onPeriodicAlarmFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800110 }
111}
112
Yao Chen8a8d16c2018-02-08 14:50:40 -0800113void updateUid(Value* value, int hostUid) {
114 int uid = value->int_value;
115 if (uid != hostUid) {
116 value->setInt(hostUid);
117 }
118}
119
Yangster-macd40053e2018-01-09 16:29:22 -0800120void StatsLogProcessor::mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent* event) const {
Yao Chenc40a19d2018-03-15 16:48:25 -0700121 if (android::util::AtomsInfo::kAtomsWithAttributionChain.find(event->GetTagId()) !=
122 android::util::AtomsInfo::kAtomsWithAttributionChain.end()) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800123 for (auto& value : *(event->getMutableValues())) {
124 if (value.mField.getPosAtDepth(0) > kAttributionField) {
125 break;
126 }
127 if (isAttributionUidField(value)) {
128 const int hostUid = mUidMap->getHostUidOrSelf(value.mValue.int_value);
129 updateUid(&value.mValue, hostUid);
130 }
Yangster-macd40053e2018-01-09 16:29:22 -0800131 }
Yao Chenc40a19d2018-03-15 16:48:25 -0700132 } else {
133 auto it = android::util::AtomsInfo::kAtomsWithUidField.find(event->GetTagId());
134 if (it != android::util::AtomsInfo::kAtomsWithUidField.end()) {
135 int uidField = it->second; // uidField is the field number in proto,
136 // starting from 1
137 if (uidField > 0 && (int)event->getValues().size() >= uidField &&
138 (event->getValues())[uidField - 1].mValue.getType() == INT) {
139 Value& value = (*event->getMutableValues())[uidField - 1].mValue;
140 const int hostUid = mUidMap->getHostUidOrSelf(value.int_value);
141 updateUid(&value, hostUid);
142 } else {
143 ALOGE("Malformed log, uid not found. %s", event->ToString().c_str());
144 }
145 }
Yao Chen312e8982017-12-05 15:29:03 -0800146 }
Yangster-macd40053e2018-01-09 16:29:22 -0800147}
148
149void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
150 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
151 bool is_create = event.GetBool(3, &err);
152 auto parent_uid = int(event.GetLong(1, &err2));
153 auto isolated_uid = int(event.GetLong(2, &err3));
154 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
155 if (is_create) {
156 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
157 } else {
158 mUidMap->removeIsolatedUid(isolated_uid, parent_uid);
159 }
160 } else {
161 ALOGE("Failed to parse uid in the isolated uid change event.");
162 }
163}
164
Yangster-macd40053e2018-01-09 16:29:22 -0800165void StatsLogProcessor::OnLogEvent(LogEvent* event) {
Yao Chen163d2602018-04-10 10:39:53 -0700166 OnLogEvent(event, false);
167}
168
Yangster-mac892f3d32018-05-02 14:16:48 -0700169void StatsLogProcessor::resetConfigs() {
170 std::lock_guard<std::mutex> lock(mMetricsMutex);
171 resetConfigsLocked(getElapsedRealtimeNs());
172}
173
174void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs) {
175 std::vector<ConfigKey> configKeys;
176 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
177 configKeys.push_back(it->first);
178 }
179 resetConfigsLocked(timestampNs, configKeys);
180}
181
Yao Chen163d2602018-04-10 10:39:53 -0700182void StatsLogProcessor::OnLogEvent(LogEvent* event, bool reconnected) {
Yangster-macd40053e2018-01-09 16:29:22 -0800183 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen876889c2018-05-02 11:16:16 -0700184
185#ifdef VERY_VERBOSE_PRINTING
186 if (mPrintAllLogs) {
187 ALOGI("%s", event->ToString().c_str());
188 }
189#endif
Yangster-macb142cc82018-03-30 15:22:08 -0700190 const int64_t currentTimestampNs = event->GetElapsedTimestampNs();
Yangster-macb8382a12018-04-04 10:39:12 -0700191
Yao Chen163d2602018-04-10 10:39:53 -0700192 if (reconnected && mLastTimestampSeen != 0) {
193 // LogReader tells us the connection has just been reset. Now we need
194 // to enter reconnection state to find the last CP.
195 mInReconnection = true;
196 }
197
198 if (mInReconnection) {
199 // We see the checkpoint
200 if (currentTimestampNs == mLastTimestampSeen) {
201 mInReconnection = false;
202 // Found the CP. ignore this event, and we will start to read from next event.
203 return;
204 }
205 if (currentTimestampNs > mLargestTimestampSeen) {
206 // We see a new log but CP has not been found yet. Give up now.
207 mLogLossCount++;
208 mInReconnection = false;
209 StatsdStats::getInstance().noteLogLost(currentTimestampNs);
210 // Persist the data before we reset. Do we want this?
Chenjie Yue36018b2018-04-16 15:18:30 -0700211 WriteDataToDiskLocked(CONFIG_RESET);
Yao Chen163d2602018-04-10 10:39:53 -0700212 // We see fresher event before we see the checkpoint. We might have lost data.
213 // The best we can do is to reset.
Yangster-mac892f3d32018-05-02 14:16:48 -0700214 resetConfigsLocked(currentTimestampNs);
Yao Chen163d2602018-04-10 10:39:53 -0700215 } else {
216 // Still in search of the CP. Keep going.
217 return;
218 }
219 }
220
221 mLogCount++;
222 mLastTimestampSeen = currentTimestampNs;
223 if (mLargestTimestampSeen < currentTimestampNs) {
224 mLargestTimestampSeen = currentTimestampNs;
Yao Chen8f42ba02018-02-27 15:17:07 -0800225 }
Yangster-macb142cc82018-03-30 15:22:08 -0700226
227 resetIfConfigTtlExpiredLocked(currentTimestampNs);
228
Yangster-macd40053e2018-01-09 16:29:22 -0800229 StatsdStats::getInstance().noteAtomLogged(
Yangster-mac330af582018-02-08 15:24:38 -0800230 event->GetTagId(), event->GetElapsedTimestampNs() / NS_PER_SEC);
Yangster-macd40053e2018-01-09 16:29:22 -0800231
David Chen21582962017-11-01 17:32:46 -0700232 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800233 // The field numbers need to be currently updated by hand with atoms.proto
Yangster-macd40053e2018-01-09 16:29:22 -0800234 if (event->GetTagId() == android::util::ISOLATED_UID_CHANGED) {
235 onIsolatedUidChangedEventLocked(*event);
David Chencfc311d2018-01-23 17:55:54 -0800236 }
237
238 if (mMetricsManagers.empty()) {
239 return;
240 }
241
Yangster-macb142cc82018-03-30 15:22:08 -0700242 int64_t curTimeSec = getElapsedRealtimeSec();
Yangster-mac330af582018-02-08 15:24:38 -0800243 if (curTimeSec - mLastPullerCacheClearTimeSec > StatsdStats::kPullerCacheClearIntervalSec) {
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700244 mStatsPullerManager.ClearPullerCacheIfNecessary(curTimeSec * NS_PER_SEC);
Yangster-mac330af582018-02-08 15:24:38 -0800245 mLastPullerCacheClearTimeSec = curTimeSec;
Chenjie Yufa22d652018-02-05 14:37:48 -0800246 }
247
Yangster-macb142cc82018-03-30 15:22:08 -0700248
David Chencfc311d2018-01-23 17:55:54 -0800249 if (event->GetTagId() != android::util::ISOLATED_UID_CHANGED) {
Yangster-macd40053e2018-01-09 16:29:22 -0800250 // Map the isolated uid to host uid if necessary.
251 mapIsolatedUidToHostUidIfNecessaryLocked(event);
252 }
253
254 // pass the event to metrics managers.
255 for (auto& pair : mMetricsManagers) {
256 pair.second->onLogEvent(*event);
Yangster-mac330af582018-02-08 15:24:38 -0800257 flushIfNecessaryLocked(event->GetElapsedTimestampNs(), pair.first, *(pair.second));
David Chen21582962017-11-01 17:32:46 -0700258 }
Yao Chenab273e22017-09-06 12:53:50 -0700259}
260
Yangster-macc04feba2018-04-02 14:37:33 -0700261void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
262 const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800263 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac892f3d32018-05-02 14:16:48 -0700264 WriteDataToDiskLocked(key, timestampNs, CONFIG_UPDATED);
Yangster-macb142cc82018-03-30 15:22:08 -0700265 OnConfigUpdatedLocked(timestampNs, key, config);
266}
267
268void StatsLogProcessor::OnConfigUpdatedLocked(
269 const int64_t timestampNs, const ConfigKey& key, const StatsdConfig& config) {
Tej Singh484524a2018-02-01 15:10:05 -0800270 VLOG("Updated configuration for key %s", key.ToString().c_str());
Yangster-mac932ecec2018-02-01 10:23:52 -0800271 sp<MetricsManager> newMetricsManager =
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700272 new MetricsManager(key, config, mTimeBaseNs, timestampNs, mUidMap,
Yangster-mac932ecec2018-02-01 10:23:52 -0800273 mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
Yao Chencaf339d2017-10-06 16:01:10 -0700274 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700275 mUidMap->OnConfigUpdated(key);
Yao Chen147ce602017-12-22 14:35:34 -0800276 if (newMetricsManager->shouldAddUidMapListener()) {
Yao Chend10f7b12017-12-18 12:53:50 -0800277 // We have to add listener after the MetricsManager is constructed because it's
278 // not safe to create wp or sp from this pointer inside its constructor.
279 mUidMap->addListener(newMetricsManager.get());
280 }
Yangster-macb142cc82018-03-30 15:22:08 -0700281 newMetricsManager->refreshTtl(timestampNs);
Yao Chend10f7b12017-12-18 12:53:50 -0800282 mMetricsManagers[key] = newMetricsManager;
Yao Chenb3561512017-11-21 18:07:17 -0800283 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700284 } else {
285 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800286 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700287 }
yro00698da2017-09-15 10:06:40 -0700288}
Bookatz906a35c2017-09-20 15:26:44 -0700289
Yangster7c334a12017-11-22 14:24:24 -0800290size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800291 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700292 auto it = mMetricsManagers.find(key);
293 if (it == mMetricsManagers.end()) {
294 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800295 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700296 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800297 return it->second->byteSize();
298}
299
Yao Chen884c8c12018-01-26 10:36:25 -0800300void StatsLogProcessor::dumpStates(FILE* out, bool verbose) {
301 std::lock_guard<std::mutex> lock(mMetricsMutex);
302 fprintf(out, "MetricsManager count: %lu\n", (unsigned long)mMetricsManagers.size());
303 for (auto metricsManager : mMetricsManagers) {
304 metricsManager.second->dumpStates(out, verbose);
305 }
306}
307
yro4beccbe2018-03-15 19:42:05 -0700308/*
309 * onDumpReport dumps serialized ConfigMetricsReportList into outData.
310 */
Yangster-macb142cc82018-03-30 15:22:08 -0700311void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700312 const bool include_current_partial_bucket,
Chenjie Yue36018b2018-04-16 15:18:30 -0700313 const DumpReportReason dumpReportReason,
Yao Chen8a8d16c2018-02-08 14:50:40 -0800314 vector<uint8_t>* outData) {
Yangster-macb0d06282018-01-05 15:44:07 -0800315 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800316
yro17adac92017-11-08 23:16:29 -0800317 ProtoOutputStream proto;
318
yro947fbce2017-11-15 22:50:23 -0800319 // Start of ConfigKey.
Yi Jin5ee07872018-03-05 18:18:27 -0800320 uint64_t configKeyToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
yro17adac92017-11-08 23:16:29 -0800321 proto.write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
Yangster-mac94e197c2018-01-02 16:03:03 -0800322 proto.write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
yro17adac92017-11-08 23:16:29 -0800323 proto.end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800324 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800325
yro947fbce2017-11-15 22:50:23 -0800326 // Then, check stats-data directory to see there's any file containing
327 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
yro4beccbe2018-03-15 19:42:05 -0700328 StorageManager::appendConfigMetricsReport(key, &proto);
yro947fbce2017-11-15 22:50:23 -0800329
Yangster-mace68f3a52018-04-04 00:01:43 -0700330 auto it = mMetricsManagers.find(key);
331 if (it != mMetricsManagers.end()) {
332 // This allows another broadcast to be sent within the rate-limit period if we get close to
333 // filling the buffer again soon.
334 mLastBroadcastTimes.erase(key);
335
336 // Start of ConfigMetricsReport (reports).
337 uint64_t reportsToken =
338 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
Chenjie Yue36018b2018-04-16 15:18:30 -0700339 onConfigMetricsReportLocked(key, dumpTimeStampNs, include_current_partial_bucket,
David Chen56ae0d92018-05-11 16:00:22 -0700340 dumpReportReason, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700341 proto.end(reportsToken);
342 // End of ConfigMetricsReport (reports).
343 } else {
344 ALOGW("Config source %s does not exist", key.ToString().c_str());
345 }
346
David Chen1d7b0cd2017-11-15 14:20:04 -0800347 if (outData != nullptr) {
348 outData->clear();
349 outData->resize(proto.size());
350 size_t pos = 0;
351 auto iter = proto.data();
352 while (iter.readBuffer() != NULL) {
353 size_t toRead = iter.currentToRead();
354 std::memcpy(&((*outData)[pos]), iter.readBuffer(), toRead);
355 pos += toRead;
356 iter.rp()->move(toRead);
357 }
yro17adac92017-11-08 23:16:29 -0800358 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800359
Yangster-mace68f3a52018-04-04 00:01:43 -0700360 StatsdStats::getInstance().noteMetricsReportSent(key, proto.size());
Yao Chen729093d2017-10-16 10:33:26 -0700361}
362
yro4beccbe2018-03-15 19:42:05 -0700363/*
364 * onConfigMetricsReportLocked dumps serialized ConfigMetricsReport into outData.
365 */
366void StatsLogProcessor::onConfigMetricsReportLocked(const ConfigKey& key,
Yangster-macb142cc82018-03-30 15:22:08 -0700367 const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700368 const bool include_current_partial_bucket,
Chenjie Yue36018b2018-04-16 15:18:30 -0700369 const DumpReportReason dumpReportReason,
yro4beccbe2018-03-15 19:42:05 -0700370 ProtoOutputStream* proto) {
371 // We already checked whether key exists in mMetricsManagers in
372 // WriteDataToDisk.
373 auto it = mMetricsManagers.find(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700374 if (it == mMetricsManagers.end()) {
375 return;
376 }
yro4beccbe2018-03-15 19:42:05 -0700377 int64_t lastReportTimeNs = it->second->getLastReportTimeNs();
378 int64_t lastReportWallClockNs = it->second->getLastReportWallClockNs();
379
Yangster-mac9def8e32018-04-17 13:55:51 -0700380 std::set<string> str_set;
381
yro4beccbe2018-03-15 19:42:05 -0700382 // First, fill in ConfigMetricsReport using current data on memory, which
383 // starts from filling in StatsLogReport's.
Yangster-mac9def8e32018-04-17 13:55:51 -0700384 it->second->onDumpReport(dumpTimeStampNs, include_current_partial_bucket,
385 &str_set, proto);
yro4beccbe2018-03-15 19:42:05 -0700386
David Chen9e6dbbd2018-05-07 17:52:29 -0700387 // Fill in UidMap if there is at least one metric to report.
388 // This skips the uid map if it's an empty config.
389 if (it->second->getNumMetrics() > 0) {
390 uint64_t uidMapToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP);
Yangster-mac1c58f042018-05-17 15:52:51 -0700391 if (it->second->hashStringInReport()) {
392 mUidMap->appendUidMap(dumpTimeStampNs, key, &str_set, proto);
393 } else {
394 mUidMap->appendUidMap(dumpTimeStampNs, key, nullptr, proto);
395 }
David Chen9e6dbbd2018-05-07 17:52:29 -0700396 proto->end(uidMapToken);
397 }
yro4beccbe2018-03-15 19:42:05 -0700398
399 // Fill in the timestamps.
400 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_ELAPSED_NANOS,
401 (long long)lastReportTimeNs);
402 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS,
403 (long long)dumpTimeStampNs);
404 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS,
405 (long long)lastReportWallClockNs);
406 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS,
407 (long long)getWallClockNs());
Chenjie Yue36018b2018-04-16 15:18:30 -0700408 // Dump report reason
409 proto->write(FIELD_TYPE_INT32 | FIELD_ID_DUMP_REPORT_REASON, dumpReportReason);
Yangster-mac9def8e32018-04-17 13:55:51 -0700410
David Chen56ae0d92018-05-11 16:00:22 -0700411 for (const auto& str : str_set) {
412 proto->write(FIELD_TYPE_STRING | FIELD_COUNT_REPEATED | FIELD_ID_STRINGS, str);
Yangster-mac9def8e32018-04-17 13:55:51 -0700413 }
Yangster-macb142cc82018-03-30 15:22:08 -0700414}
yro4beccbe2018-03-15 19:42:05 -0700415
Yao Chen163d2602018-04-10 10:39:53 -0700416void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs,
417 const std::vector<ConfigKey>& configs) {
418 for (const auto& key : configs) {
Yangster-macb142cc82018-03-30 15:22:08 -0700419 StatsdConfig config;
420 if (StorageManager::readConfigFromDisk(key, &config)) {
421 OnConfigUpdatedLocked(timestampNs, key, config);
422 StatsdStats::getInstance().noteConfigReset(key);
423 } else {
424 ALOGE("Failed to read backup config from disk for : %s", key.ToString().c_str());
425 auto it = mMetricsManagers.find(key);
426 if (it != mMetricsManagers.end()) {
427 it->second->refreshTtl(timestampNs);
428 }
429 }
430 }
yro4beccbe2018-03-15 19:42:05 -0700431}
432
Yao Chen163d2602018-04-10 10:39:53 -0700433void StatsLogProcessor::resetIfConfigTtlExpiredLocked(const int64_t timestampNs) {
434 std::vector<ConfigKey> configKeysTtlExpired;
435 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
436 if (it->second != nullptr && !it->second->isInTtl(timestampNs)) {
437 configKeysTtlExpired.push_back(it->first);
438 }
439 }
440 if (configKeysTtlExpired.size() > 0) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700441 WriteDataToDiskLocked(CONFIG_RESET);
Yao Chen163d2602018-04-10 10:39:53 -0700442 resetConfigsLocked(timestampNs, configKeysTtlExpired);
443 }
444}
445
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700446void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800447 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700448 auto it = mMetricsManagers.find(key);
449 if (it != mMetricsManagers.end()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700450 WriteDataToDiskLocked(key, getElapsedRealtimeNs(), CONFIG_REMOVED);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700451 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700452 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700453 }
Yao Chenb3561512017-11-21 18:07:17 -0800454 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800455
David Chen1d7b0cd2017-11-15 14:20:04 -0800456 mLastBroadcastTimes.erase(key);
Chenjie Yufa22d652018-02-05 14:37:48 -0800457
458 if (mMetricsManagers.empty()) {
459 mStatsPullerManager.ForceClearPullerCache();
460 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700461}
462
Yangster-macb0d06282018-01-05 15:44:07 -0800463void StatsLogProcessor::flushIfNecessaryLocked(
Yangster-macb142cc82018-03-30 15:22:08 -0700464 int64_t timestampNs, const ConfigKey& key, MetricsManager& metricsManager) {
David Chend9269e22017-12-05 13:43:51 -0800465 auto lastCheckTime = mLastByteSizeTimes.find(key);
466 if (lastCheckTime != mLastByteSizeTimes.end()) {
467 if (timestampNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
468 return;
469 }
470 }
471
472 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
473 size_t totalBytes = metricsManager.byteSize();
474 mLastByteSizeTimes[key] = timestampNs;
David Chen48944902018-05-03 10:29:11 -0700475 bool requestDump = false;
David Chend9269e22017-12-05 13:43:51 -0800476 if (totalBytes >
477 StatsdStats::kMaxMetricsBytesPerConfig) { // Too late. We need to start clearing data.
Yao Chen06dba5d2018-01-26 13:38:16 -0800478 metricsManager.dropData(timestampNs);
David Chen12942952017-12-04 14:28:43 -0800479 StatsdStats::getInstance().noteDataDropped(key);
480 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chen48944902018-05-03 10:29:11 -0700481 } else if ((totalBytes > StatsdStats::kBytesPerConfigTriggerGetData) ||
482 (mOnDiskDataConfigs.find(key) != mOnDiskDataConfigs.end())) {
483 // Request to send a broadcast if:
484 // 1. in memory data > threshold OR
485 // 2. config has old data report on disk.
486 requestDump = true;
487 }
488
489 if (requestDump) {
David Chend9269e22017-12-05 13:43:51 -0800490 // Send broadcast so that receivers can pull data.
491 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
492 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
493 if (timestampNs - lastBroadcastTime->second < StatsdStats::kMinBroadcastPeriodNs) {
494 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800495 return;
496 }
497 }
David Chen48944902018-05-03 10:29:11 -0700498 if (mSendBroadcast(key)) {
499 mOnDiskDataConfigs.erase(key);
500 VLOG("StatsD triggered data fetch for %s", key.ToString().c_str());
501 mLastBroadcastTimes[key] = timestampNs;
502 StatsdStats::getInstance().noteBroadcastSent(key);
503 }
yro31eb67b2017-10-24 13:33:21 -0700504 }
505}
506
Chenjie Yue36018b2018-04-16 15:18:30 -0700507void StatsLogProcessor::WriteDataToDiskLocked(const ConfigKey& key,
Yangster-mac892f3d32018-05-02 14:16:48 -0700508 const int64_t timestampNs,
Chenjie Yue36018b2018-04-16 15:18:30 -0700509 const DumpReportReason dumpReportReason) {
yro028091c2018-05-09 16:03:27 -0700510 if (mMetricsManagers.find(key) == mMetricsManagers.end() ||
511 !mMetricsManagers.find(key)->second->shouldWriteToDisk()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700512 return;
513 }
Yangster-mace68f3a52018-04-04 00:01:43 -0700514 ProtoOutputStream proto;
David Chen56ae0d92018-05-11 16:00:22 -0700515 onConfigMetricsReportLocked(key, timestampNs, true /* include_current_partial_bucket*/,
516 dumpReportReason, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700517 string file_name = StringPrintf("%s/%ld_%d_%lld", STATS_DATA_DIR,
518 (long)getWallClockSec(), key.GetUid(), (long long)key.GetId());
519 android::base::unique_fd fd(open(file_name.c_str(),
520 O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
521 if (fd == -1) {
522 ALOGE("Attempt to write %s but failed", file_name.c_str());
523 return;
524 }
525 proto.flush(fd.get());
David Chen48944902018-05-03 10:29:11 -0700526 // We were able to write the ConfigMetricsReport to disk, so we should trigger collection ASAP.
527 mOnDiskDataConfigs.insert(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700528}
529
Chenjie Yue36018b2018-04-16 15:18:30 -0700530void StatsLogProcessor::WriteDataToDiskLocked(const DumpReportReason dumpReportReason) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700531 const int64_t timeNs = getElapsedRealtimeNs();
Tej Singh42f9e062018-11-09 10:01:00 -0800532 // Do not write to disk if we already have in the last few seconds.
533 // This is to avoid overwriting files that would have the same name if we
534 // write twice in the same second.
535 if (static_cast<unsigned long long> (timeNs) <
536 mLastWriteTimeNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
537 ALOGI("Statsd skipping writing data to disk. Already wrote data in last %d seconds",
538 WRITE_DATA_COOL_DOWN_SEC);
539 return;
540 }
541 mLastWriteTimeNs = timeNs;
Yangster-mace68f3a52018-04-04 00:01:43 -0700542 for (auto& pair : mMetricsManagers) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700543 WriteDataToDiskLocked(pair.first, timeNs, dumpReportReason);
Yangster-mace68f3a52018-04-04 00:01:43 -0700544 }
545}
546
Yangster-mac892f3d32018-05-02 14:16:48 -0700547void StatsLogProcessor::WriteDataToDisk(const DumpReportReason dumpReportReason) {
Yangster-macb0d06282018-01-05 15:44:07 -0800548 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac892f3d32018-05-02 14:16:48 -0700549 WriteDataToDiskLocked(dumpReportReason);
yro947fbce2017-11-15 22:50:23 -0800550}
551
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700552void StatsLogProcessor::informPullAlarmFired(const int64_t timestampNs) {
Yangster6df5fcc2018-04-12 11:04:29 -0700553 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700554 mStatsPullerManager.OnAlarmFired(timestampNs);
555}
556
David Chend37bc232018-04-12 18:05:11 -0700557int64_t StatsLogProcessor::getLastReportTimeNs(const ConfigKey& key) {
558 auto it = mMetricsManagers.find(key);
559 if (it == mMetricsManagers.end()) {
560 return 0;
561 } else {
562 return it->second->getLastReportTimeNs();
563 }
564}
565
David Chen48944902018-05-03 10:29:11 -0700566void StatsLogProcessor::noteOnDiskData(const ConfigKey& key) {
567 std::lock_guard<std::mutex> lock(mMetricsMutex);
568 mOnDiskDataConfigs.insert(key);
569}
570
Yao Chenef99c4f2017-09-22 16:26:54 -0700571} // namespace statsd
572} // namespace os
573} // namespace android