blob: ab0aa25103e923fff64fef031f03bae7e64166b5 [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
yro31eb67b2017-10-24 13:33:21 -070074StatsLogProcessor::StatsLogProcessor(const sp<UidMap>& uidMap,
Chenjie Yue2219202018-06-08 10:07:51 -070075 const sp<StatsPullerManager>& pullerManager,
Yangster-mac932ecec2018-02-01 10:23:52 -080076 const sp<AlarmMonitor>& anomalyAlarmMonitor,
77 const sp<AlarmMonitor>& periodicAlarmMonitor,
Yangster-mac15f6bbc2018-04-08 11:52:26 -070078 const int64_t timeBaseNs,
David Chen48944902018-05-03 10:29:11 -070079 const std::function<bool(const ConfigKey&)>& sendBroadcast)
Chenjie Yu85ed8382017-12-14 16:48:54 -080080 : mUidMap(uidMap),
Chenjie Yue2219202018-06-08 10:07:51 -070081 mPullerManager(pullerManager),
Yangster-mac932ecec2018-02-01 10:23:52 -080082 mAnomalyAlarmMonitor(anomalyAlarmMonitor),
83 mPeriodicAlarmMonitor(periodicAlarmMonitor),
Chenjie Yu85ed8382017-12-14 16:48:54 -080084 mSendBroadcast(sendBroadcast),
Yangster-mac15f6bbc2018-04-08 11:52:26 -070085 mTimeBaseNs(timeBaseNs),
Yao Chen163d2602018-04-10 10:39:53 -070086 mLargestTimestampSeen(0),
87 mLastTimestampSeen(0) {
Chenjie Yue2219202018-06-08 10:07:51 -070088 mPullerManager->ForceClearPullerCache();
Yao Chenab273e22017-09-06 12:53:50 -070089}
90
Yao Chenef99c4f2017-09-22 16:26:54 -070091StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -070092}
93
Yangster-mace2cd6d52017-11-09 20:38:30 -080094void StatsLogProcessor::onAnomalyAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -070095 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -080096 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
Yangster-macb0d06282018-01-05 15:44:07 -080097 std::lock_guard<std::mutex> lock(mMetricsMutex);
Bookatzcc5adef22017-11-21 14:36:23 -080098 for (const auto& itr : mMetricsManagers) {
Yangster-mac932ecec2018-02-01 10:23:52 -080099 itr.second->onAnomalyAlarmFired(timestampNs, alarmSet);
100 }
101}
102void StatsLogProcessor::onPeriodicAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700103 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800104 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
105
106 std::lock_guard<std::mutex> lock(mMetricsMutex);
107 for (const auto& itr : mMetricsManagers) {
108 itr.second->onPeriodicAlarmFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800109 }
110}
111
Yao Chen8a8d16c2018-02-08 14:50:40 -0800112void updateUid(Value* value, int hostUid) {
113 int uid = value->int_value;
114 if (uid != hostUid) {
115 value->setInt(hostUid);
116 }
117}
118
Yangster-macd40053e2018-01-09 16:29:22 -0800119void StatsLogProcessor::mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent* event) const {
Yao Chenc40a19d2018-03-15 16:48:25 -0700120 if (android::util::AtomsInfo::kAtomsWithAttributionChain.find(event->GetTagId()) !=
121 android::util::AtomsInfo::kAtomsWithAttributionChain.end()) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800122 for (auto& value : *(event->getMutableValues())) {
123 if (value.mField.getPosAtDepth(0) > kAttributionField) {
124 break;
125 }
126 if (isAttributionUidField(value)) {
127 const int hostUid = mUidMap->getHostUidOrSelf(value.mValue.int_value);
128 updateUid(&value.mValue, hostUid);
129 }
Yangster-macd40053e2018-01-09 16:29:22 -0800130 }
Yao Chenc40a19d2018-03-15 16:48:25 -0700131 } else {
132 auto it = android::util::AtomsInfo::kAtomsWithUidField.find(event->GetTagId());
133 if (it != android::util::AtomsInfo::kAtomsWithUidField.end()) {
134 int uidField = it->second; // uidField is the field number in proto,
135 // starting from 1
136 if (uidField > 0 && (int)event->getValues().size() >= uidField &&
137 (event->getValues())[uidField - 1].mValue.getType() == INT) {
138 Value& value = (*event->getMutableValues())[uidField - 1].mValue;
139 const int hostUid = mUidMap->getHostUidOrSelf(value.int_value);
140 updateUid(&value, hostUid);
141 } else {
142 ALOGE("Malformed log, uid not found. %s", event->ToString().c_str());
143 }
144 }
Yao Chen312e8982017-12-05 15:29:03 -0800145 }
Yangster-macd40053e2018-01-09 16:29:22 -0800146}
147
148void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
149 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
150 bool is_create = event.GetBool(3, &err);
151 auto parent_uid = int(event.GetLong(1, &err2));
152 auto isolated_uid = int(event.GetLong(2, &err3));
153 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
154 if (is_create) {
155 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
156 } else {
Bookatz3c648862018-05-25 13:32:43 -0700157 mUidMap->removeIsolatedUid(isolated_uid);
Yangster-macd40053e2018-01-09 16:29:22 -0800158 }
159 } else {
160 ALOGE("Failed to parse uid in the isolated uid change event.");
161 }
162}
163
Yangster-macd40053e2018-01-09 16:29:22 -0800164void StatsLogProcessor::OnLogEvent(LogEvent* event) {
Yao Chen163d2602018-04-10 10:39:53 -0700165 OnLogEvent(event, false);
166}
167
Yangster-mac892f3d32018-05-02 14:16:48 -0700168void StatsLogProcessor::resetConfigs() {
169 std::lock_guard<std::mutex> lock(mMetricsMutex);
170 resetConfigsLocked(getElapsedRealtimeNs());
171}
172
173void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs) {
174 std::vector<ConfigKey> configKeys;
175 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
176 configKeys.push_back(it->first);
177 }
178 resetConfigsLocked(timestampNs, configKeys);
179}
180
Yao Chen163d2602018-04-10 10:39:53 -0700181void StatsLogProcessor::OnLogEvent(LogEvent* event, bool reconnected) {
Yangster-macd40053e2018-01-09 16:29:22 -0800182 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen876889c2018-05-02 11:16:16 -0700183
184#ifdef VERY_VERBOSE_PRINTING
185 if (mPrintAllLogs) {
186 ALOGI("%s", event->ToString().c_str());
187 }
188#endif
Yangster-macb142cc82018-03-30 15:22:08 -0700189 const int64_t currentTimestampNs = event->GetElapsedTimestampNs();
Yangster-macb8382a12018-04-04 10:39:12 -0700190
Yao Chen163d2602018-04-10 10:39:53 -0700191 if (reconnected && mLastTimestampSeen != 0) {
192 // LogReader tells us the connection has just been reset. Now we need
193 // to enter reconnection state to find the last CP.
194 mInReconnection = true;
195 }
196
197 if (mInReconnection) {
198 // We see the checkpoint
199 if (currentTimestampNs == mLastTimestampSeen) {
200 mInReconnection = false;
201 // Found the CP. ignore this event, and we will start to read from next event.
202 return;
203 }
204 if (currentTimestampNs > mLargestTimestampSeen) {
205 // We see a new log but CP has not been found yet. Give up now.
206 mLogLossCount++;
207 mInReconnection = false;
208 StatsdStats::getInstance().noteLogLost(currentTimestampNs);
209 // Persist the data before we reset. Do we want this?
Chenjie Yue36018b2018-04-16 15:18:30 -0700210 WriteDataToDiskLocked(CONFIG_RESET);
Yao Chen163d2602018-04-10 10:39:53 -0700211 // We see fresher event before we see the checkpoint. We might have lost data.
212 // The best we can do is to reset.
Yangster-mac892f3d32018-05-02 14:16:48 -0700213 resetConfigsLocked(currentTimestampNs);
Yao Chen163d2602018-04-10 10:39:53 -0700214 } else {
215 // Still in search of the CP. Keep going.
216 return;
217 }
218 }
219
220 mLogCount++;
221 mLastTimestampSeen = currentTimestampNs;
222 if (mLargestTimestampSeen < currentTimestampNs) {
223 mLargestTimestampSeen = currentTimestampNs;
Yao Chen8f42ba02018-02-27 15:17:07 -0800224 }
Yangster-macb142cc82018-03-30 15:22:08 -0700225
226 resetIfConfigTtlExpiredLocked(currentTimestampNs);
227
Yangster-macd40053e2018-01-09 16:29:22 -0800228 StatsdStats::getInstance().noteAtomLogged(
Yangster-mac330af582018-02-08 15:24:38 -0800229 event->GetTagId(), event->GetElapsedTimestampNs() / NS_PER_SEC);
Yangster-macd40053e2018-01-09 16:29:22 -0800230
David Chen21582962017-11-01 17:32:46 -0700231 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800232 // The field numbers need to be currently updated by hand with atoms.proto
Yangster-macd40053e2018-01-09 16:29:22 -0800233 if (event->GetTagId() == android::util::ISOLATED_UID_CHANGED) {
234 onIsolatedUidChangedEventLocked(*event);
David Chencfc311d2018-01-23 17:55:54 -0800235 }
236
237 if (mMetricsManagers.empty()) {
238 return;
239 }
240
Yangster-macb142cc82018-03-30 15:22:08 -0700241 int64_t curTimeSec = getElapsedRealtimeSec();
Yangster-mac330af582018-02-08 15:24:38 -0800242 if (curTimeSec - mLastPullerCacheClearTimeSec > StatsdStats::kPullerCacheClearIntervalSec) {
Chenjie Yue2219202018-06-08 10:07:51 -0700243 mPullerManager->ClearPullerCacheIfNecessary(curTimeSec * NS_PER_SEC);
Yangster-mac330af582018-02-08 15:24:38 -0800244 mLastPullerCacheClearTimeSec = curTimeSec;
Chenjie Yufa22d652018-02-05 14:37:48 -0800245 }
246
Yangster-macb142cc82018-03-30 15:22:08 -0700247
David Chencfc311d2018-01-23 17:55:54 -0800248 if (event->GetTagId() != android::util::ISOLATED_UID_CHANGED) {
Yangster-macd40053e2018-01-09 16:29:22 -0800249 // Map the isolated uid to host uid if necessary.
250 mapIsolatedUidToHostUidIfNecessaryLocked(event);
251 }
252
253 // pass the event to metrics managers.
254 for (auto& pair : mMetricsManagers) {
255 pair.second->onLogEvent(*event);
Yangster-mac330af582018-02-08 15:24:38 -0800256 flushIfNecessaryLocked(event->GetElapsedTimestampNs(), pair.first, *(pair.second));
David Chen21582962017-11-01 17:32:46 -0700257 }
Yao Chenab273e22017-09-06 12:53:50 -0700258}
259
Yangster-macc04feba2018-04-02 14:37:33 -0700260void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
261 const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800262 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac892f3d32018-05-02 14:16:48 -0700263 WriteDataToDiskLocked(key, timestampNs, CONFIG_UPDATED);
Yangster-macb142cc82018-03-30 15:22:08 -0700264 OnConfigUpdatedLocked(timestampNs, key, config);
265}
266
267void StatsLogProcessor::OnConfigUpdatedLocked(
268 const int64_t timestampNs, const ConfigKey& key, const StatsdConfig& config) {
Tej Singh484524a2018-02-01 15:10:05 -0800269 VLOG("Updated configuration for key %s", key.ToString().c_str());
Yangster-mac932ecec2018-02-01 10:23:52 -0800270 sp<MetricsManager> newMetricsManager =
Chenjie Yue2219202018-06-08 10:07:51 -0700271 new MetricsManager(key, config, mTimeBaseNs, timestampNs, mUidMap, mPullerManager,
272 mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
Yao Chencaf339d2017-10-06 16:01:10 -0700273 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700274 mUidMap->OnConfigUpdated(key);
Yao Chen147ce602017-12-22 14:35:34 -0800275 if (newMetricsManager->shouldAddUidMapListener()) {
Yao Chend10f7b12017-12-18 12:53:50 -0800276 // We have to add listener after the MetricsManager is constructed because it's
277 // not safe to create wp or sp from this pointer inside its constructor.
278 mUidMap->addListener(newMetricsManager.get());
279 }
Yangster-macb142cc82018-03-30 15:22:08 -0700280 newMetricsManager->refreshTtl(timestampNs);
Yao Chend10f7b12017-12-18 12:53:50 -0800281 mMetricsManagers[key] = newMetricsManager;
Yao Chenb3561512017-11-21 18:07:17 -0800282 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700283 } else {
284 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800285 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700286 }
yro00698da2017-09-15 10:06:40 -0700287}
Bookatz906a35c2017-09-20 15:26:44 -0700288
Yangster7c334a12017-11-22 14:24:24 -0800289size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800290 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700291 auto it = mMetricsManagers.find(key);
292 if (it == mMetricsManagers.end()) {
293 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800294 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700295 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800296 return it->second->byteSize();
297}
298
Yao Chen884c8c12018-01-26 10:36:25 -0800299void StatsLogProcessor::dumpStates(FILE* out, bool verbose) {
300 std::lock_guard<std::mutex> lock(mMetricsMutex);
301 fprintf(out, "MetricsManager count: %lu\n", (unsigned long)mMetricsManagers.size());
302 for (auto metricsManager : mMetricsManagers) {
303 metricsManager.second->dumpStates(out, verbose);
304 }
305}
306
yro4beccbe2018-03-15 19:42:05 -0700307/*
308 * onDumpReport dumps serialized ConfigMetricsReportList into outData.
309 */
Yangster-macb142cc82018-03-30 15:22:08 -0700310void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700311 const bool include_current_partial_bucket,
Chenjie Yue36018b2018-04-16 15:18:30 -0700312 const DumpReportReason dumpReportReason,
Yao Chen8a8d16c2018-02-08 14:50:40 -0800313 vector<uint8_t>* outData) {
Yangster-macb0d06282018-01-05 15:44:07 -0800314 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800315
yro17adac92017-11-08 23:16:29 -0800316 ProtoOutputStream proto;
317
yro947fbce2017-11-15 22:50:23 -0800318 // Start of ConfigKey.
Yi Jin5ee07872018-03-05 18:18:27 -0800319 uint64_t configKeyToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
yro17adac92017-11-08 23:16:29 -0800320 proto.write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
Yangster-mac94e197c2018-01-02 16:03:03 -0800321 proto.write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
yro17adac92017-11-08 23:16:29 -0800322 proto.end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800323 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800324
yro947fbce2017-11-15 22:50:23 -0800325 // Then, check stats-data directory to see there's any file containing
326 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
yro4beccbe2018-03-15 19:42:05 -0700327 StorageManager::appendConfigMetricsReport(key, &proto);
yro947fbce2017-11-15 22:50:23 -0800328
Yangster-mace68f3a52018-04-04 00:01:43 -0700329 auto it = mMetricsManagers.find(key);
330 if (it != mMetricsManagers.end()) {
331 // This allows another broadcast to be sent within the rate-limit period if we get close to
332 // filling the buffer again soon.
333 mLastBroadcastTimes.erase(key);
334
335 // Start of ConfigMetricsReport (reports).
336 uint64_t reportsToken =
337 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
Chenjie Yue36018b2018-04-16 15:18:30 -0700338 onConfigMetricsReportLocked(key, dumpTimeStampNs, include_current_partial_bucket,
David Chen56ae0d92018-05-11 16:00:22 -0700339 dumpReportReason, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700340 proto.end(reportsToken);
341 // End of ConfigMetricsReport (reports).
342 } else {
343 ALOGW("Config source %s does not exist", key.ToString().c_str());
344 }
345
David Chen1d7b0cd2017-11-15 14:20:04 -0800346 if (outData != nullptr) {
347 outData->clear();
348 outData->resize(proto.size());
349 size_t pos = 0;
350 auto iter = proto.data();
351 while (iter.readBuffer() != NULL) {
352 size_t toRead = iter.currentToRead();
353 std::memcpy(&((*outData)[pos]), iter.readBuffer(), toRead);
354 pos += toRead;
355 iter.rp()->move(toRead);
356 }
yro17adac92017-11-08 23:16:29 -0800357 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800358
Yangster-mace68f3a52018-04-04 00:01:43 -0700359 StatsdStats::getInstance().noteMetricsReportSent(key, proto.size());
Yao Chen729093d2017-10-16 10:33:26 -0700360}
361
yro4beccbe2018-03-15 19:42:05 -0700362/*
363 * onConfigMetricsReportLocked dumps serialized ConfigMetricsReport into outData.
364 */
365void StatsLogProcessor::onConfigMetricsReportLocked(const ConfigKey& key,
Yangster-macb142cc82018-03-30 15:22:08 -0700366 const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700367 const bool include_current_partial_bucket,
Chenjie Yue36018b2018-04-16 15:18:30 -0700368 const DumpReportReason dumpReportReason,
yro4beccbe2018-03-15 19:42:05 -0700369 ProtoOutputStream* proto) {
370 // We already checked whether key exists in mMetricsManagers in
371 // WriteDataToDisk.
372 auto it = mMetricsManagers.find(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700373 if (it == mMetricsManagers.end()) {
374 return;
375 }
yro4beccbe2018-03-15 19:42:05 -0700376 int64_t lastReportTimeNs = it->second->getLastReportTimeNs();
377 int64_t lastReportWallClockNs = it->second->getLastReportWallClockNs();
378
Yangster-mac9def8e32018-04-17 13:55:51 -0700379 std::set<string> str_set;
380
yro4beccbe2018-03-15 19:42:05 -0700381 // First, fill in ConfigMetricsReport using current data on memory, which
382 // starts from filling in StatsLogReport's.
Yangster-mac9def8e32018-04-17 13:55:51 -0700383 it->second->onDumpReport(dumpTimeStampNs, include_current_partial_bucket,
384 &str_set, proto);
yro4beccbe2018-03-15 19:42:05 -0700385
David Chen9e6dbbd2018-05-07 17:52:29 -0700386 // Fill in UidMap if there is at least one metric to report.
387 // This skips the uid map if it's an empty config.
388 if (it->second->getNumMetrics() > 0) {
389 uint64_t uidMapToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP);
Yangster-mac1c58f042018-05-17 15:52:51 -0700390 if (it->second->hashStringInReport()) {
391 mUidMap->appendUidMap(dumpTimeStampNs, key, &str_set, proto);
392 } else {
393 mUidMap->appendUidMap(dumpTimeStampNs, key, nullptr, proto);
394 }
David Chen9e6dbbd2018-05-07 17:52:29 -0700395 proto->end(uidMapToken);
396 }
yro4beccbe2018-03-15 19:42:05 -0700397
398 // Fill in the timestamps.
399 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_ELAPSED_NANOS,
400 (long long)lastReportTimeNs);
401 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS,
402 (long long)dumpTimeStampNs);
403 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS,
404 (long long)lastReportWallClockNs);
405 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS,
406 (long long)getWallClockNs());
Chenjie Yue36018b2018-04-16 15:18:30 -0700407 // Dump report reason
408 proto->write(FIELD_TYPE_INT32 | FIELD_ID_DUMP_REPORT_REASON, dumpReportReason);
Yangster-mac9def8e32018-04-17 13:55:51 -0700409
David Chen56ae0d92018-05-11 16:00:22 -0700410 for (const auto& str : str_set) {
411 proto->write(FIELD_TYPE_STRING | FIELD_COUNT_REPEATED | FIELD_ID_STRINGS, str);
Yangster-mac9def8e32018-04-17 13:55:51 -0700412 }
Yangster-macb142cc82018-03-30 15:22:08 -0700413}
yro4beccbe2018-03-15 19:42:05 -0700414
Yao Chen163d2602018-04-10 10:39:53 -0700415void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs,
416 const std::vector<ConfigKey>& configs) {
417 for (const auto& key : configs) {
Yangster-macb142cc82018-03-30 15:22:08 -0700418 StatsdConfig config;
419 if (StorageManager::readConfigFromDisk(key, &config)) {
420 OnConfigUpdatedLocked(timestampNs, key, config);
421 StatsdStats::getInstance().noteConfigReset(key);
422 } else {
423 ALOGE("Failed to read backup config from disk for : %s", key.ToString().c_str());
424 auto it = mMetricsManagers.find(key);
425 if (it != mMetricsManagers.end()) {
426 it->second->refreshTtl(timestampNs);
427 }
428 }
429 }
yro4beccbe2018-03-15 19:42:05 -0700430}
431
Yao Chen163d2602018-04-10 10:39:53 -0700432void StatsLogProcessor::resetIfConfigTtlExpiredLocked(const int64_t timestampNs) {
433 std::vector<ConfigKey> configKeysTtlExpired;
434 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
435 if (it->second != nullptr && !it->second->isInTtl(timestampNs)) {
436 configKeysTtlExpired.push_back(it->first);
437 }
438 }
439 if (configKeysTtlExpired.size() > 0) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700440 WriteDataToDiskLocked(CONFIG_RESET);
Yao Chen163d2602018-04-10 10:39:53 -0700441 resetConfigsLocked(timestampNs, configKeysTtlExpired);
442 }
443}
444
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700445void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800446 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700447 auto it = mMetricsManagers.find(key);
448 if (it != mMetricsManagers.end()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700449 WriteDataToDiskLocked(key, getElapsedRealtimeNs(), CONFIG_REMOVED);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700450 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700451 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700452 }
Yao Chenb3561512017-11-21 18:07:17 -0800453 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800454
David Chen1d7b0cd2017-11-15 14:20:04 -0800455 mLastBroadcastTimes.erase(key);
Chenjie Yufa22d652018-02-05 14:37:48 -0800456
457 if (mMetricsManagers.empty()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700458 mPullerManager->ForceClearPullerCache();
Chenjie Yufa22d652018-02-05 14:37:48 -0800459 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700460}
461
Yangster-macb0d06282018-01-05 15:44:07 -0800462void StatsLogProcessor::flushIfNecessaryLocked(
Yangster-macb142cc82018-03-30 15:22:08 -0700463 int64_t timestampNs, const ConfigKey& key, MetricsManager& metricsManager) {
David Chend9269e22017-12-05 13:43:51 -0800464 auto lastCheckTime = mLastByteSizeTimes.find(key);
465 if (lastCheckTime != mLastByteSizeTimes.end()) {
466 if (timestampNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
467 return;
468 }
469 }
470
471 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
472 size_t totalBytes = metricsManager.byteSize();
473 mLastByteSizeTimes[key] = timestampNs;
David Chen48944902018-05-03 10:29:11 -0700474 bool requestDump = false;
David Chend9269e22017-12-05 13:43:51 -0800475 if (totalBytes >
476 StatsdStats::kMaxMetricsBytesPerConfig) { // Too late. We need to start clearing data.
Yao Chen06dba5d2018-01-26 13:38:16 -0800477 metricsManager.dropData(timestampNs);
David Chen12942952017-12-04 14:28:43 -0800478 StatsdStats::getInstance().noteDataDropped(key);
479 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chen48944902018-05-03 10:29:11 -0700480 } else if ((totalBytes > StatsdStats::kBytesPerConfigTriggerGetData) ||
481 (mOnDiskDataConfigs.find(key) != mOnDiskDataConfigs.end())) {
482 // Request to send a broadcast if:
483 // 1. in memory data > threshold OR
484 // 2. config has old data report on disk.
485 requestDump = true;
486 }
487
488 if (requestDump) {
David Chend9269e22017-12-05 13:43:51 -0800489 // Send broadcast so that receivers can pull data.
490 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
491 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
492 if (timestampNs - lastBroadcastTime->second < StatsdStats::kMinBroadcastPeriodNs) {
493 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800494 return;
495 }
496 }
David Chen48944902018-05-03 10:29:11 -0700497 if (mSendBroadcast(key)) {
498 mOnDiskDataConfigs.erase(key);
499 VLOG("StatsD triggered data fetch for %s", key.ToString().c_str());
500 mLastBroadcastTimes[key] = timestampNs;
501 StatsdStats::getInstance().noteBroadcastSent(key);
502 }
yro31eb67b2017-10-24 13:33:21 -0700503 }
504}
505
Chenjie Yue36018b2018-04-16 15:18:30 -0700506void StatsLogProcessor::WriteDataToDiskLocked(const ConfigKey& key,
Yangster-mac892f3d32018-05-02 14:16:48 -0700507 const int64_t timestampNs,
Chenjie Yue36018b2018-04-16 15:18:30 -0700508 const DumpReportReason dumpReportReason) {
yro028091c2018-05-09 16:03:27 -0700509 if (mMetricsManagers.find(key) == mMetricsManagers.end() ||
510 !mMetricsManagers.find(key)->second->shouldWriteToDisk()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700511 return;
512 }
Yangster-mace68f3a52018-04-04 00:01:43 -0700513 ProtoOutputStream proto;
David Chen56ae0d92018-05-11 16:00:22 -0700514 onConfigMetricsReportLocked(key, timestampNs, true /* include_current_partial_bucket*/,
515 dumpReportReason, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700516 string file_name = StringPrintf("%s/%ld_%d_%lld", STATS_DATA_DIR,
517 (long)getWallClockSec(), key.GetUid(), (long long)key.GetId());
518 android::base::unique_fd fd(open(file_name.c_str(),
519 O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
520 if (fd == -1) {
521 ALOGE("Attempt to write %s but failed", file_name.c_str());
522 return;
523 }
524 proto.flush(fd.get());
David Chen48944902018-05-03 10:29:11 -0700525 // We were able to write the ConfigMetricsReport to disk, so we should trigger collection ASAP.
526 mOnDiskDataConfigs.insert(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700527}
528
Chenjie Yue36018b2018-04-16 15:18:30 -0700529void StatsLogProcessor::WriteDataToDiskLocked(const DumpReportReason dumpReportReason) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700530 const int64_t timeNs = getElapsedRealtimeNs();
Yangster-mace68f3a52018-04-04 00:01:43 -0700531 for (auto& pair : mMetricsManagers) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700532 WriteDataToDiskLocked(pair.first, timeNs, dumpReportReason);
Yangster-mace68f3a52018-04-04 00:01:43 -0700533 }
534}
535
Yangster-mac892f3d32018-05-02 14:16:48 -0700536void StatsLogProcessor::WriteDataToDisk(const DumpReportReason dumpReportReason) {
Yangster-macb0d06282018-01-05 15:44:07 -0800537 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac892f3d32018-05-02 14:16:48 -0700538 WriteDataToDiskLocked(dumpReportReason);
yro947fbce2017-11-15 22:50:23 -0800539}
540
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700541void StatsLogProcessor::informPullAlarmFired(const int64_t timestampNs) {
Yangster6df5fcc2018-04-12 11:04:29 -0700542 std::lock_guard<std::mutex> lock(mMetricsMutex);
Chenjie Yue2219202018-06-08 10:07:51 -0700543 mPullerManager->OnAlarmFired(timestampNs);
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700544}
545
David Chend37bc232018-04-12 18:05:11 -0700546int64_t StatsLogProcessor::getLastReportTimeNs(const ConfigKey& key) {
547 auto it = mMetricsManagers.find(key);
548 if (it == mMetricsManagers.end()) {
549 return 0;
550 } else {
551 return it->second->getLastReportTimeNs();
552 }
553}
554
David Chen48944902018-05-03 10:29:11 -0700555void StatsLogProcessor::noteOnDiskData(const ConfigKey& key) {
556 std::lock_guard<std::mutex> lock(mMetricsMutex);
557 mOnDiskDataConfigs.insert(key);
558}
559
Yao Chenef99c4f2017-09-22 16:26:54 -0700560} // namespace statsd
561} // namespace os
562} // namespace android