blob: d5579139ed1a540b8487d9cf4a9d214b07d2a386 [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;
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,
Yangster-mac932ecec2018-02-01 10:23:52 -080075 const sp<AlarmMonitor>& anomalyAlarmMonitor,
76 const sp<AlarmMonitor>& periodicAlarmMonitor,
Yangster-mac15f6bbc2018-04-08 11:52:26 -070077 const int64_t timeBaseNs,
David Chen1d7b0cd2017-11-15 14:20:04 -080078 const std::function<void(const ConfigKey&)>& sendBroadcast)
Chenjie Yu85ed8382017-12-14 16:48:54 -080079 : mUidMap(uidMap),
Yangster-mac932ecec2018-02-01 10:23:52 -080080 mAnomalyAlarmMonitor(anomalyAlarmMonitor),
81 mPeriodicAlarmMonitor(periodicAlarmMonitor),
Chenjie Yu85ed8382017-12-14 16:48:54 -080082 mSendBroadcast(sendBroadcast),
Yangster-mac15f6bbc2018-04-08 11:52:26 -070083 mTimeBaseNs(timeBaseNs),
Yao Chen163d2602018-04-10 10:39:53 -070084 mLargestTimestampSeen(0),
85 mLastTimestampSeen(0) {
Yao Chenab273e22017-09-06 12:53:50 -070086}
87
Yao Chenef99c4f2017-09-22 16:26:54 -070088StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -070089}
90
Yangster-mace2cd6d52017-11-09 20:38:30 -080091void StatsLogProcessor::onAnomalyAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -070092 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -080093 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
Yangster-macb0d06282018-01-05 15:44:07 -080094 std::lock_guard<std::mutex> lock(mMetricsMutex);
Bookatzcc5adef22017-11-21 14:36:23 -080095 for (const auto& itr : mMetricsManagers) {
Yangster-mac932ecec2018-02-01 10:23:52 -080096 itr.second->onAnomalyAlarmFired(timestampNs, alarmSet);
97 }
98}
99void StatsLogProcessor::onPeriodicAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700100 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800101 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
102
103 std::lock_guard<std::mutex> lock(mMetricsMutex);
104 for (const auto& itr : mMetricsManagers) {
105 itr.second->onPeriodicAlarmFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800106 }
107}
108
Yao Chen8a8d16c2018-02-08 14:50:40 -0800109void updateUid(Value* value, int hostUid) {
110 int uid = value->int_value;
111 if (uid != hostUid) {
112 value->setInt(hostUid);
113 }
114}
115
Yangster-macd40053e2018-01-09 16:29:22 -0800116void StatsLogProcessor::mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent* event) const {
Yao Chenc40a19d2018-03-15 16:48:25 -0700117 if (android::util::AtomsInfo::kAtomsWithAttributionChain.find(event->GetTagId()) !=
118 android::util::AtomsInfo::kAtomsWithAttributionChain.end()) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800119 for (auto& value : *(event->getMutableValues())) {
120 if (value.mField.getPosAtDepth(0) > kAttributionField) {
121 break;
122 }
123 if (isAttributionUidField(value)) {
124 const int hostUid = mUidMap->getHostUidOrSelf(value.mValue.int_value);
125 updateUid(&value.mValue, hostUid);
126 }
Yangster-macd40053e2018-01-09 16:29:22 -0800127 }
Yao Chenc40a19d2018-03-15 16:48:25 -0700128 } else {
129 auto it = android::util::AtomsInfo::kAtomsWithUidField.find(event->GetTagId());
130 if (it != android::util::AtomsInfo::kAtomsWithUidField.end()) {
131 int uidField = it->second; // uidField is the field number in proto,
132 // starting from 1
133 if (uidField > 0 && (int)event->getValues().size() >= uidField &&
134 (event->getValues())[uidField - 1].mValue.getType() == INT) {
135 Value& value = (*event->getMutableValues())[uidField - 1].mValue;
136 const int hostUid = mUidMap->getHostUidOrSelf(value.int_value);
137 updateUid(&value, hostUid);
138 } else {
139 ALOGE("Malformed log, uid not found. %s", event->ToString().c_str());
140 }
141 }
Yao Chen312e8982017-12-05 15:29:03 -0800142 }
Yangster-macd40053e2018-01-09 16:29:22 -0800143}
144
145void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
146 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
147 bool is_create = event.GetBool(3, &err);
148 auto parent_uid = int(event.GetLong(1, &err2));
149 auto isolated_uid = int(event.GetLong(2, &err3));
150 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
151 if (is_create) {
152 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
153 } else {
154 mUidMap->removeIsolatedUid(isolated_uid, parent_uid);
155 }
156 } else {
157 ALOGE("Failed to parse uid in the isolated uid change event.");
158 }
159}
160
Yangster-macd40053e2018-01-09 16:29:22 -0800161void StatsLogProcessor::OnLogEvent(LogEvent* event) {
Yao Chen163d2602018-04-10 10:39:53 -0700162 OnLogEvent(event, false);
163}
164
Yangster-mac892f3d32018-05-02 14:16:48 -0700165void StatsLogProcessor::resetConfigs() {
166 std::lock_guard<std::mutex> lock(mMetricsMutex);
167 resetConfigsLocked(getElapsedRealtimeNs());
168}
169
170void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs) {
171 std::vector<ConfigKey> configKeys;
172 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
173 configKeys.push_back(it->first);
174 }
175 resetConfigsLocked(timestampNs, configKeys);
176}
177
Yao Chen163d2602018-04-10 10:39:53 -0700178void StatsLogProcessor::OnLogEvent(LogEvent* event, bool reconnected) {
Yangster-macd40053e2018-01-09 16:29:22 -0800179 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-macb142cc82018-03-30 15:22:08 -0700180 const int64_t currentTimestampNs = event->GetElapsedTimestampNs();
Yangster-macb8382a12018-04-04 10:39:12 -0700181
Yao Chen163d2602018-04-10 10:39:53 -0700182 if (reconnected && mLastTimestampSeen != 0) {
183 // LogReader tells us the connection has just been reset. Now we need
184 // to enter reconnection state to find the last CP.
185 mInReconnection = true;
186 }
187
188 if (mInReconnection) {
189 // We see the checkpoint
190 if (currentTimestampNs == mLastTimestampSeen) {
191 mInReconnection = false;
192 // Found the CP. ignore this event, and we will start to read from next event.
193 return;
194 }
195 if (currentTimestampNs > mLargestTimestampSeen) {
196 // We see a new log but CP has not been found yet. Give up now.
197 mLogLossCount++;
198 mInReconnection = false;
199 StatsdStats::getInstance().noteLogLost(currentTimestampNs);
200 // Persist the data before we reset. Do we want this?
Chenjie Yue36018b2018-04-16 15:18:30 -0700201 WriteDataToDiskLocked(CONFIG_RESET);
Yao Chen163d2602018-04-10 10:39:53 -0700202 // We see fresher event before we see the checkpoint. We might have lost data.
203 // The best we can do is to reset.
Yangster-mac892f3d32018-05-02 14:16:48 -0700204 resetConfigsLocked(currentTimestampNs);
Yao Chen163d2602018-04-10 10:39:53 -0700205 } else {
206 // Still in search of the CP. Keep going.
207 return;
208 }
209 }
210
211 mLogCount++;
212 mLastTimestampSeen = currentTimestampNs;
213 if (mLargestTimestampSeen < currentTimestampNs) {
214 mLargestTimestampSeen = currentTimestampNs;
Yao Chen8f42ba02018-02-27 15:17:07 -0800215 }
Yangster-macb142cc82018-03-30 15:22:08 -0700216
217 resetIfConfigTtlExpiredLocked(currentTimestampNs);
218
Yangster-macd40053e2018-01-09 16:29:22 -0800219 StatsdStats::getInstance().noteAtomLogged(
Yangster-mac330af582018-02-08 15:24:38 -0800220 event->GetTagId(), event->GetElapsedTimestampNs() / NS_PER_SEC);
Yangster-macd40053e2018-01-09 16:29:22 -0800221
David Chen21582962017-11-01 17:32:46 -0700222 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800223 // The field numbers need to be currently updated by hand with atoms.proto
Yangster-macd40053e2018-01-09 16:29:22 -0800224 if (event->GetTagId() == android::util::ISOLATED_UID_CHANGED) {
225 onIsolatedUidChangedEventLocked(*event);
David Chencfc311d2018-01-23 17:55:54 -0800226 }
227
228 if (mMetricsManagers.empty()) {
229 return;
230 }
231
Yangster-macb142cc82018-03-30 15:22:08 -0700232 int64_t curTimeSec = getElapsedRealtimeSec();
Yangster-mac330af582018-02-08 15:24:38 -0800233 if (curTimeSec - mLastPullerCacheClearTimeSec > StatsdStats::kPullerCacheClearIntervalSec) {
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700234 mStatsPullerManager.ClearPullerCacheIfNecessary(curTimeSec * NS_PER_SEC);
Yangster-mac330af582018-02-08 15:24:38 -0800235 mLastPullerCacheClearTimeSec = curTimeSec;
Chenjie Yufa22d652018-02-05 14:37:48 -0800236 }
237
Yangster-macb142cc82018-03-30 15:22:08 -0700238
David Chencfc311d2018-01-23 17:55:54 -0800239 if (event->GetTagId() != android::util::ISOLATED_UID_CHANGED) {
Yangster-macd40053e2018-01-09 16:29:22 -0800240 // Map the isolated uid to host uid if necessary.
241 mapIsolatedUidToHostUidIfNecessaryLocked(event);
242 }
243
244 // pass the event to metrics managers.
245 for (auto& pair : mMetricsManagers) {
246 pair.second->onLogEvent(*event);
Yangster-mac330af582018-02-08 15:24:38 -0800247 flushIfNecessaryLocked(event->GetElapsedTimestampNs(), pair.first, *(pair.second));
David Chen21582962017-11-01 17:32:46 -0700248 }
Yao Chenab273e22017-09-06 12:53:50 -0700249}
250
Yangster-macc04feba2018-04-02 14:37:33 -0700251void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
252 const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800253 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac892f3d32018-05-02 14:16:48 -0700254 WriteDataToDiskLocked(key, timestampNs, CONFIG_UPDATED);
Yangster-macb142cc82018-03-30 15:22:08 -0700255 OnConfigUpdatedLocked(timestampNs, key, config);
256}
257
258void StatsLogProcessor::OnConfigUpdatedLocked(
259 const int64_t timestampNs, const ConfigKey& key, const StatsdConfig& config) {
Tej Singh484524a2018-02-01 15:10:05 -0800260 VLOG("Updated configuration for key %s", key.ToString().c_str());
Yangster-mac932ecec2018-02-01 10:23:52 -0800261 sp<MetricsManager> newMetricsManager =
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700262 new MetricsManager(key, config, mTimeBaseNs, timestampNs, mUidMap,
Yangster-mac932ecec2018-02-01 10:23:52 -0800263 mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
Yao Chencaf339d2017-10-06 16:01:10 -0700264 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700265 mUidMap->OnConfigUpdated(key);
Yao Chen147ce602017-12-22 14:35:34 -0800266 if (newMetricsManager->shouldAddUidMapListener()) {
Yao Chend10f7b12017-12-18 12:53:50 -0800267 // We have to add listener after the MetricsManager is constructed because it's
268 // not safe to create wp or sp from this pointer inside its constructor.
269 mUidMap->addListener(newMetricsManager.get());
270 }
Yangster-macb142cc82018-03-30 15:22:08 -0700271 newMetricsManager->refreshTtl(timestampNs);
Yao Chend10f7b12017-12-18 12:53:50 -0800272 mMetricsManagers[key] = newMetricsManager;
Yao Chenb3561512017-11-21 18:07:17 -0800273 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700274 } else {
275 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800276 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700277 }
yro00698da2017-09-15 10:06:40 -0700278}
Bookatz906a35c2017-09-20 15:26:44 -0700279
Yangster7c334a12017-11-22 14:24:24 -0800280size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800281 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700282 auto it = mMetricsManagers.find(key);
283 if (it == mMetricsManagers.end()) {
284 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800285 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700286 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800287 return it->second->byteSize();
288}
289
Yao Chen884c8c12018-01-26 10:36:25 -0800290void StatsLogProcessor::dumpStates(FILE* out, bool verbose) {
291 std::lock_guard<std::mutex> lock(mMetricsMutex);
292 fprintf(out, "MetricsManager count: %lu\n", (unsigned long)mMetricsManagers.size());
293 for (auto metricsManager : mMetricsManagers) {
294 metricsManager.second->dumpStates(out, verbose);
295 }
296}
297
yro4beccbe2018-03-15 19:42:05 -0700298/*
299 * onDumpReport dumps serialized ConfigMetricsReportList into outData.
300 */
Yangster-macb142cc82018-03-30 15:22:08 -0700301void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700302 const bool include_current_partial_bucket,
Yangster-mac9def8e32018-04-17 13:55:51 -0700303 const bool include_string,
Chenjie Yue36018b2018-04-16 15:18:30 -0700304 const DumpReportReason dumpReportReason,
Yao Chen8a8d16c2018-02-08 14:50:40 -0800305 vector<uint8_t>* outData) {
Yangster-macb0d06282018-01-05 15:44:07 -0800306 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800307
yro17adac92017-11-08 23:16:29 -0800308 ProtoOutputStream proto;
309
yro947fbce2017-11-15 22:50:23 -0800310 // Start of ConfigKey.
Yi Jin5ee07872018-03-05 18:18:27 -0800311 uint64_t configKeyToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
yro17adac92017-11-08 23:16:29 -0800312 proto.write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
Yangster-mac94e197c2018-01-02 16:03:03 -0800313 proto.write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
yro17adac92017-11-08 23:16:29 -0800314 proto.end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800315 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800316
yro947fbce2017-11-15 22:50:23 -0800317 // Then, check stats-data directory to see there's any file containing
318 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
yro4beccbe2018-03-15 19:42:05 -0700319 StorageManager::appendConfigMetricsReport(key, &proto);
yro947fbce2017-11-15 22:50:23 -0800320
Yangster-mace68f3a52018-04-04 00:01:43 -0700321 auto it = mMetricsManagers.find(key);
322 if (it != mMetricsManagers.end()) {
323 // This allows another broadcast to be sent within the rate-limit period if we get close to
324 // filling the buffer again soon.
325 mLastBroadcastTimes.erase(key);
326
327 // Start of ConfigMetricsReport (reports).
328 uint64_t reportsToken =
329 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
Chenjie Yue36018b2018-04-16 15:18:30 -0700330 onConfigMetricsReportLocked(key, dumpTimeStampNs, include_current_partial_bucket,
Yangster-mac9def8e32018-04-17 13:55:51 -0700331 include_string, dumpReportReason, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700332 proto.end(reportsToken);
333 // End of ConfigMetricsReport (reports).
334 } else {
335 ALOGW("Config source %s does not exist", key.ToString().c_str());
336 }
337
David Chen1d7b0cd2017-11-15 14:20:04 -0800338 if (outData != nullptr) {
339 outData->clear();
340 outData->resize(proto.size());
341 size_t pos = 0;
342 auto iter = proto.data();
343 while (iter.readBuffer() != NULL) {
344 size_t toRead = iter.currentToRead();
345 std::memcpy(&((*outData)[pos]), iter.readBuffer(), toRead);
346 pos += toRead;
347 iter.rp()->move(toRead);
348 }
yro17adac92017-11-08 23:16:29 -0800349 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800350
Yangster-mace68f3a52018-04-04 00:01:43 -0700351 StatsdStats::getInstance().noteMetricsReportSent(key, proto.size());
Yao Chen729093d2017-10-16 10:33:26 -0700352}
353
yro4beccbe2018-03-15 19:42:05 -0700354/*
355 * onConfigMetricsReportLocked dumps serialized ConfigMetricsReport into outData.
356 */
357void StatsLogProcessor::onConfigMetricsReportLocked(const ConfigKey& key,
Yangster-macb142cc82018-03-30 15:22:08 -0700358 const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700359 const bool include_current_partial_bucket,
Yangster-mac9def8e32018-04-17 13:55:51 -0700360 const bool include_string,
Chenjie Yue36018b2018-04-16 15:18:30 -0700361 const DumpReportReason dumpReportReason,
yro4beccbe2018-03-15 19:42:05 -0700362 ProtoOutputStream* proto) {
363 // We already checked whether key exists in mMetricsManagers in
364 // WriteDataToDisk.
365 auto it = mMetricsManagers.find(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700366 if (it == mMetricsManagers.end()) {
367 return;
368 }
yro4beccbe2018-03-15 19:42:05 -0700369 int64_t lastReportTimeNs = it->second->getLastReportTimeNs();
370 int64_t lastReportWallClockNs = it->second->getLastReportWallClockNs();
371
Yangster-mac9def8e32018-04-17 13:55:51 -0700372 std::set<string> str_set;
373
yro4beccbe2018-03-15 19:42:05 -0700374 // First, fill in ConfigMetricsReport using current data on memory, which
375 // starts from filling in StatsLogReport's.
Yangster-mac9def8e32018-04-17 13:55:51 -0700376 it->second->onDumpReport(dumpTimeStampNs, include_current_partial_bucket,
377 &str_set, proto);
yro4beccbe2018-03-15 19:42:05 -0700378
379 // Fill in UidMap.
380 uint64_t uidMapToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP);
Yangster-mac9def8e32018-04-17 13:55:51 -0700381 mUidMap->appendUidMap(dumpTimeStampNs, key, &str_set, proto);
yro4beccbe2018-03-15 19:42:05 -0700382 proto->end(uidMapToken);
383
384 // Fill in the timestamps.
385 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_ELAPSED_NANOS,
386 (long long)lastReportTimeNs);
387 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS,
388 (long long)dumpTimeStampNs);
389 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS,
390 (long long)lastReportWallClockNs);
391 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS,
392 (long long)getWallClockNs());
Chenjie Yue36018b2018-04-16 15:18:30 -0700393 // Dump report reason
394 proto->write(FIELD_TYPE_INT32 | FIELD_ID_DUMP_REPORT_REASON, dumpReportReason);
Yangster-mac9def8e32018-04-17 13:55:51 -0700395
396 if (include_string) {
397 for (const auto& str : str_set) {
398 proto->write(FIELD_TYPE_STRING | FIELD_COUNT_REPEATED | FIELD_ID_STRINGS, str);
399 }
400 }
Yangster-macb142cc82018-03-30 15:22:08 -0700401}
yro4beccbe2018-03-15 19:42:05 -0700402
Yao Chen163d2602018-04-10 10:39:53 -0700403void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs,
404 const std::vector<ConfigKey>& configs) {
405 for (const auto& key : configs) {
Yangster-macb142cc82018-03-30 15:22:08 -0700406 StatsdConfig config;
407 if (StorageManager::readConfigFromDisk(key, &config)) {
408 OnConfigUpdatedLocked(timestampNs, key, config);
409 StatsdStats::getInstance().noteConfigReset(key);
410 } else {
411 ALOGE("Failed to read backup config from disk for : %s", key.ToString().c_str());
412 auto it = mMetricsManagers.find(key);
413 if (it != mMetricsManagers.end()) {
414 it->second->refreshTtl(timestampNs);
415 }
416 }
417 }
yro4beccbe2018-03-15 19:42:05 -0700418}
419
Yao Chen163d2602018-04-10 10:39:53 -0700420void StatsLogProcessor::resetIfConfigTtlExpiredLocked(const int64_t timestampNs) {
421 std::vector<ConfigKey> configKeysTtlExpired;
422 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
423 if (it->second != nullptr && !it->second->isInTtl(timestampNs)) {
424 configKeysTtlExpired.push_back(it->first);
425 }
426 }
427 if (configKeysTtlExpired.size() > 0) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700428 WriteDataToDiskLocked(CONFIG_RESET);
Yao Chen163d2602018-04-10 10:39:53 -0700429 resetConfigsLocked(timestampNs, configKeysTtlExpired);
430 }
431}
432
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700433void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800434 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700435 auto it = mMetricsManagers.find(key);
436 if (it != mMetricsManagers.end()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700437 WriteDataToDiskLocked(key, getElapsedRealtimeNs(), CONFIG_REMOVED);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700438 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700439 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700440 }
Yao Chenb3561512017-11-21 18:07:17 -0800441 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800442
David Chen1d7b0cd2017-11-15 14:20:04 -0800443 mLastBroadcastTimes.erase(key);
Chenjie Yufa22d652018-02-05 14:37:48 -0800444
445 if (mMetricsManagers.empty()) {
446 mStatsPullerManager.ForceClearPullerCache();
447 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700448}
449
Yangster-macb0d06282018-01-05 15:44:07 -0800450void StatsLogProcessor::flushIfNecessaryLocked(
Yangster-macb142cc82018-03-30 15:22:08 -0700451 int64_t timestampNs, const ConfigKey& key, MetricsManager& metricsManager) {
David Chend9269e22017-12-05 13:43:51 -0800452 auto lastCheckTime = mLastByteSizeTimes.find(key);
453 if (lastCheckTime != mLastByteSizeTimes.end()) {
454 if (timestampNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
455 return;
456 }
457 }
458
459 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
460 size_t totalBytes = metricsManager.byteSize();
461 mLastByteSizeTimes[key] = timestampNs;
462 if (totalBytes >
463 StatsdStats::kMaxMetricsBytesPerConfig) { // Too late. We need to start clearing data.
Yao Chen06dba5d2018-01-26 13:38:16 -0800464 metricsManager.dropData(timestampNs);
David Chen12942952017-12-04 14:28:43 -0800465 StatsdStats::getInstance().noteDataDropped(key);
466 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chen4c6d97a2018-03-22 16:31:40 -0700467 } else if (totalBytes > StatsdStats::kBytesPerConfigTriggerGetData) {
David Chend9269e22017-12-05 13:43:51 -0800468 // Send broadcast so that receivers can pull data.
469 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
470 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
471 if (timestampNs - lastBroadcastTime->second < StatsdStats::kMinBroadcastPeriodNs) {
472 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800473 return;
474 }
475 }
476 mLastBroadcastTimes[key] = timestampNs;
Yao Chenb3561512017-11-21 18:07:17 -0800477 VLOG("StatsD requesting broadcast for %s", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800478 mSendBroadcast(key);
Yao Chenb3561512017-11-21 18:07:17 -0800479 StatsdStats::getInstance().noteBroadcastSent(key);
yro31eb67b2017-10-24 13:33:21 -0700480 }
481}
482
Chenjie Yue36018b2018-04-16 15:18:30 -0700483void StatsLogProcessor::WriteDataToDiskLocked(const ConfigKey& key,
Yangster-mac892f3d32018-05-02 14:16:48 -0700484 const int64_t timestampNs,
Chenjie Yue36018b2018-04-16 15:18:30 -0700485 const DumpReportReason dumpReportReason) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700486 if (mMetricsManagers.find(key) == mMetricsManagers.end()) {
487 return;
488 }
Yangster-mace68f3a52018-04-04 00:01:43 -0700489 ProtoOutputStream proto;
Yangster-mac892f3d32018-05-02 14:16:48 -0700490 onConfigMetricsReportLocked(key, timestampNs,
Yangster-mac9def8e32018-04-17 13:55:51 -0700491 true /* include_current_partial_bucket*/,
492 false /* include strings */, dumpReportReason, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700493 string file_name = StringPrintf("%s/%ld_%d_%lld", STATS_DATA_DIR,
494 (long)getWallClockSec(), key.GetUid(), (long long)key.GetId());
495 android::base::unique_fd fd(open(file_name.c_str(),
496 O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
497 if (fd == -1) {
498 ALOGE("Attempt to write %s but failed", file_name.c_str());
499 return;
500 }
501 proto.flush(fd.get());
502}
503
Chenjie Yue36018b2018-04-16 15:18:30 -0700504void StatsLogProcessor::WriteDataToDiskLocked(const DumpReportReason dumpReportReason) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700505 const int64_t timeNs = getElapsedRealtimeNs();
Yangster-mace68f3a52018-04-04 00:01:43 -0700506 for (auto& pair : mMetricsManagers) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700507 WriteDataToDiskLocked(pair.first, timeNs, dumpReportReason);
Yangster-mace68f3a52018-04-04 00:01:43 -0700508 }
509}
510
Yangster-mac892f3d32018-05-02 14:16:48 -0700511void StatsLogProcessor::WriteDataToDisk(const DumpReportReason dumpReportReason) {
Yangster-macb0d06282018-01-05 15:44:07 -0800512 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac892f3d32018-05-02 14:16:48 -0700513 WriteDataToDiskLocked(dumpReportReason);
yro947fbce2017-11-15 22:50:23 -0800514}
515
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700516void StatsLogProcessor::informPullAlarmFired(const int64_t timestampNs) {
Yangster6df5fcc2018-04-12 11:04:29 -0700517 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700518 mStatsPullerManager.OnAlarmFired(timestampNs);
519}
520
David Chend37bc232018-04-12 18:05:11 -0700521int64_t StatsLogProcessor::getLastReportTimeNs(const ConfigKey& key) {
522 auto it = mMetricsManagers.find(key);
523 if (it == mMetricsManagers.end()) {
524 return 0;
525 } else {
526 return it->second->getLastReportTimeNs();
527 }
528}
529
Yao Chenef99c4f2017-09-22 16:26:54 -0700530} // namespace statsd
531} // namespace os
532} // namespace android