blob: 653ef2ec986957ccd104d5d4474db9a8641a7797 [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
Chenjie Yuc7939cb2019-02-04 17:25:45 -080017#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>
Chenjie Yuc7939cb2019-02-04 17:25:45 -080023#include <frameworks/base/cmds/statsd/src/active_config_list.pb.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070024#include "StatsLogProcessor.h"
yro947fbce2017-11-15 22:50:23 -080025#include "android-base/stringprintf.h"
Chenjie Yuc7939cb2019-02-04 17:25:45 -080026#include "external/StatsPullerManager.h"
Yao Chenb3561512017-11-21 18:07:17 -080027#include "guardrail/StatsdStats.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070028#include "metrics/CountMetricProducer.h"
Chenjie Yuc7939cb2019-02-04 17:25:45 -080029#include "stats_log_util.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070030#include "stats_util.h"
yro947fbce2017-11-15 22:50:23 -080031#include "storage/StorageManager.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070032
yro00698da2017-09-15 10:06:40 -070033#include <log/log_event_list.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070034#include <utils/Errors.h>
David Chen16049572018-02-01 18:27:51 -080035#include <utils/SystemClock.h>
Yao Chenab273e22017-09-06 12:53:50 -070036
37using namespace android;
yro947fbce2017-11-15 22:50:23 -080038using android::base::StringPrintf;
yrob0378b02017-11-09 20:36:25 -080039using android::util::FIELD_COUNT_REPEATED;
yro17adac92017-11-08 23:16:29 -080040using android::util::FIELD_TYPE_BOOL;
41using android::util::FIELD_TYPE_FLOAT;
42using android::util::FIELD_TYPE_INT32;
43using android::util::FIELD_TYPE_INT64;
44using android::util::FIELD_TYPE_MESSAGE;
45using android::util::FIELD_TYPE_STRING;
46using android::util::ProtoOutputStream;
Yao Chen44cf27c2017-09-14 22:32:50 -070047using std::make_unique;
48using std::unique_ptr;
49using std::vector;
Bookatz906a35c2017-09-20 15:26:44 -070050
51namespace android {
52namespace os {
53namespace statsd {
Yao Chenab273e22017-09-06 12:53:50 -070054
yro947fbce2017-11-15 22:50:23 -080055// for ConfigMetricsReportList
yro17adac92017-11-08 23:16:29 -080056const int FIELD_ID_CONFIG_KEY = 1;
yro947fbce2017-11-15 22:50:23 -080057const int FIELD_ID_REPORTS = 2;
yro17adac92017-11-08 23:16:29 -080058// for ConfigKey
59const int FIELD_ID_UID = 1;
Yangster-mac94e197c2018-01-02 16:03:03 -080060const int FIELD_ID_ID = 2;
yro947fbce2017-11-15 22:50:23 -080061// for ConfigMetricsReport
Yao Chen4c959cb2018-02-13 13:27:48 -080062// const int FIELD_ID_METRICS = 1; // written in MetricsManager.cpp
yro947fbce2017-11-15 22:50:23 -080063const int FIELD_ID_UID_MAP = 2;
Yangster-mac330af582018-02-08 15:24:38 -080064const int FIELD_ID_LAST_REPORT_ELAPSED_NANOS = 3;
65const int FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS = 4;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -080066const int FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS = 5;
67const int FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS = 6;
Chenjie Yue36018b2018-04-16 15:18:30 -070068const int FIELD_ID_DUMP_REPORT_REASON = 8;
Yangster-mac9def8e32018-04-17 13:55:51 -070069const int FIELD_ID_STRINGS = 9;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -080070
Chenjie Yuc7939cb2019-02-04 17:25:45 -080071const int FIELD_ID_ACTIVE_CONFIG_LIST = 1;
72const int FIELD_ID_CONFIG_ID = 1;
73const int FIELD_ID_CONFIG_UID = 2;
74const int FIELD_ID_ACTIVE_METRIC = 3;
75const int FIELD_ID_METRIC_ID = 1;
76const int FIELD_ID_TIME_TO_LIVE_NANOS = 2;
77
Yangster-macb142cc82018-03-30 15:22:08 -070078#define NS_PER_HOUR 3600 * NS_PER_SEC
yro947fbce2017-11-15 22:50:23 -080079
yro03faf092017-12-12 00:17:50 -080080#define STATS_DATA_DIR "/data/misc/stats-data"
Chenjie Yuc7939cb2019-02-04 17:25:45 -080081#define STATS_ACTIVE_METRIC_DIR "/data/misc/stats-active-metric"
yro17adac92017-11-08 23:16:29 -080082
Tej Singh42f9e062018-11-09 10:01:00 -080083// Cool down period for writing data to disk to avoid overwriting files.
84#define WRITE_DATA_COOL_DOWN_SEC 5
85
yro31eb67b2017-10-24 13:33:21 -070086StatsLogProcessor::StatsLogProcessor(const sp<UidMap>& uidMap,
Chenjie Yue2219202018-06-08 10:07:51 -070087 const sp<StatsPullerManager>& pullerManager,
Yangster-mac932ecec2018-02-01 10:23:52 -080088 const sp<AlarmMonitor>& anomalyAlarmMonitor,
89 const sp<AlarmMonitor>& periodicAlarmMonitor,
Yangster-mac15f6bbc2018-04-08 11:52:26 -070090 const int64_t timeBaseNs,
Tej Singh6ede28b2019-01-29 17:06:54 -080091 const std::function<bool(const ConfigKey&)>& sendBroadcast,
92 const std::function<bool(
93 const int&, const vector<int64_t>&)>& activateBroadcast)
Chenjie Yu85ed8382017-12-14 16:48:54 -080094 : mUidMap(uidMap),
Chenjie Yue2219202018-06-08 10:07:51 -070095 mPullerManager(pullerManager),
Yangster-mac932ecec2018-02-01 10:23:52 -080096 mAnomalyAlarmMonitor(anomalyAlarmMonitor),
97 mPeriodicAlarmMonitor(periodicAlarmMonitor),
Chenjie Yu85ed8382017-12-14 16:48:54 -080098 mSendBroadcast(sendBroadcast),
Tej Singh6ede28b2019-01-29 17:06:54 -080099 mSendActivationBroadcast(activateBroadcast),
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700100 mTimeBaseNs(timeBaseNs),
Yao Chen163d2602018-04-10 10:39:53 -0700101 mLargestTimestampSeen(0),
102 mLastTimestampSeen(0) {
Chenjie Yue2219202018-06-08 10:07:51 -0700103 mPullerManager->ForceClearPullerCache();
Yao Chenab273e22017-09-06 12:53:50 -0700104}
105
Yao Chenef99c4f2017-09-22 16:26:54 -0700106StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -0700107}
108
Yangster-mace2cd6d52017-11-09 20:38:30 -0800109void StatsLogProcessor::onAnomalyAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700110 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800111 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
Yangster-macb0d06282018-01-05 15:44:07 -0800112 std::lock_guard<std::mutex> lock(mMetricsMutex);
Bookatzcc5adef22017-11-21 14:36:23 -0800113 for (const auto& itr : mMetricsManagers) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800114 itr.second->onAnomalyAlarmFired(timestampNs, alarmSet);
115 }
116}
117void StatsLogProcessor::onPeriodicAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700118 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800119 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
120
121 std::lock_guard<std::mutex> lock(mMetricsMutex);
122 for (const auto& itr : mMetricsManagers) {
123 itr.second->onPeriodicAlarmFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800124 }
125}
126
Yao Chen8a8d16c2018-02-08 14:50:40 -0800127void updateUid(Value* value, int hostUid) {
128 int uid = value->int_value;
129 if (uid != hostUid) {
130 value->setInt(hostUid);
131 }
132}
133
Yangster-macd40053e2018-01-09 16:29:22 -0800134void StatsLogProcessor::mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent* event) const {
Yao Chenc40a19d2018-03-15 16:48:25 -0700135 if (android::util::AtomsInfo::kAtomsWithAttributionChain.find(event->GetTagId()) !=
136 android::util::AtomsInfo::kAtomsWithAttributionChain.end()) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800137 for (auto& value : *(event->getMutableValues())) {
138 if (value.mField.getPosAtDepth(0) > kAttributionField) {
139 break;
140 }
141 if (isAttributionUidField(value)) {
142 const int hostUid = mUidMap->getHostUidOrSelf(value.mValue.int_value);
143 updateUid(&value.mValue, hostUid);
144 }
Yangster-macd40053e2018-01-09 16:29:22 -0800145 }
Yao Chenc40a19d2018-03-15 16:48:25 -0700146 } else {
147 auto it = android::util::AtomsInfo::kAtomsWithUidField.find(event->GetTagId());
148 if (it != android::util::AtomsInfo::kAtomsWithUidField.end()) {
149 int uidField = it->second; // uidField is the field number in proto,
150 // starting from 1
151 if (uidField > 0 && (int)event->getValues().size() >= uidField &&
152 (event->getValues())[uidField - 1].mValue.getType() == INT) {
153 Value& value = (*event->getMutableValues())[uidField - 1].mValue;
154 const int hostUid = mUidMap->getHostUidOrSelf(value.int_value);
155 updateUid(&value, hostUid);
156 } else {
157 ALOGE("Malformed log, uid not found. %s", event->ToString().c_str());
158 }
159 }
Yao Chen312e8982017-12-05 15:29:03 -0800160 }
Yangster-macd40053e2018-01-09 16:29:22 -0800161}
162
163void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
164 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
165 bool is_create = event.GetBool(3, &err);
166 auto parent_uid = int(event.GetLong(1, &err2));
167 auto isolated_uid = int(event.GetLong(2, &err3));
168 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
169 if (is_create) {
170 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
171 } else {
Bookatz3c648862018-05-25 13:32:43 -0700172 mUidMap->removeIsolatedUid(isolated_uid);
Yangster-macd40053e2018-01-09 16:29:22 -0800173 }
174 } else {
175 ALOGE("Failed to parse uid in the isolated uid change event.");
176 }
177}
178
Yangster-mac892f3d32018-05-02 14:16:48 -0700179void StatsLogProcessor::resetConfigs() {
180 std::lock_guard<std::mutex> lock(mMetricsMutex);
181 resetConfigsLocked(getElapsedRealtimeNs());
182}
183
184void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs) {
185 std::vector<ConfigKey> configKeys;
186 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
187 configKeys.push_back(it->first);
188 }
189 resetConfigsLocked(timestampNs, configKeys);
190}
191
Yao Chen3ff3a492018-08-06 16:17:37 -0700192void StatsLogProcessor::OnLogEvent(LogEvent* event) {
Yangster-macd40053e2018-01-09 16:29:22 -0800193 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen876889c2018-05-02 11:16:16 -0700194
195#ifdef VERY_VERBOSE_PRINTING
196 if (mPrintAllLogs) {
197 ALOGI("%s", event->ToString().c_str());
198 }
199#endif
Yangster-macb142cc82018-03-30 15:22:08 -0700200 const int64_t currentTimestampNs = event->GetElapsedTimestampNs();
Yangster-macb8382a12018-04-04 10:39:12 -0700201
Yangster-macb142cc82018-03-30 15:22:08 -0700202 resetIfConfigTtlExpiredLocked(currentTimestampNs);
203
Yangster-macd40053e2018-01-09 16:29:22 -0800204 StatsdStats::getInstance().noteAtomLogged(
Yangster-mac330af582018-02-08 15:24:38 -0800205 event->GetTagId(), event->GetElapsedTimestampNs() / NS_PER_SEC);
Yangster-macd40053e2018-01-09 16:29:22 -0800206
David Chen21582962017-11-01 17:32:46 -0700207 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800208 // The field numbers need to be currently updated by hand with atoms.proto
Yangster-macd40053e2018-01-09 16:29:22 -0800209 if (event->GetTagId() == android::util::ISOLATED_UID_CHANGED) {
210 onIsolatedUidChangedEventLocked(*event);
David Chencfc311d2018-01-23 17:55:54 -0800211 }
212
213 if (mMetricsManagers.empty()) {
214 return;
215 }
216
Yangster-macb142cc82018-03-30 15:22:08 -0700217 int64_t curTimeSec = getElapsedRealtimeSec();
Yangster-mac330af582018-02-08 15:24:38 -0800218 if (curTimeSec - mLastPullerCacheClearTimeSec > StatsdStats::kPullerCacheClearIntervalSec) {
Chenjie Yue2219202018-06-08 10:07:51 -0700219 mPullerManager->ClearPullerCacheIfNecessary(curTimeSec * NS_PER_SEC);
Yangster-mac330af582018-02-08 15:24:38 -0800220 mLastPullerCacheClearTimeSec = curTimeSec;
Chenjie Yufa22d652018-02-05 14:37:48 -0800221 }
222
Yangster-macb142cc82018-03-30 15:22:08 -0700223
David Chencfc311d2018-01-23 17:55:54 -0800224 if (event->GetTagId() != android::util::ISOLATED_UID_CHANGED) {
Yangster-macd40053e2018-01-09 16:29:22 -0800225 // Map the isolated uid to host uid if necessary.
226 mapIsolatedUidToHostUidIfNecessaryLocked(event);
227 }
228
Tej Singh6ede28b2019-01-29 17:06:54 -0800229 std::unordered_set<int> uidsWithActiveConfigsChanged;
230 std::unordered_map<int, std::vector<int64_t>> activeConfigsPerUid;
Yangster-macd40053e2018-01-09 16:29:22 -0800231 // pass the event to metrics managers.
232 for (auto& pair : mMetricsManagers) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800233 int uid = pair.first.GetUid();
234 int64_t configId = pair.first.GetId();
235 bool isPrevActive = pair.second->isActive();
Yangster-macd40053e2018-01-09 16:29:22 -0800236 pair.second->onLogEvent(*event);
Tej Singh6ede28b2019-01-29 17:06:54 -0800237 bool isCurActive = pair.second->isActive();
238 // Map all active configs by uid.
239 if (isCurActive) {
240 auto activeConfigs = activeConfigsPerUid.find(uid);
241 if (activeConfigs != activeConfigsPerUid.end()) {
242 activeConfigs->second.push_back(configId);
243 } else {
244 vector<int64_t> newActiveConfigs;
245 newActiveConfigs.push_back(configId);
246 activeConfigsPerUid[uid] = newActiveConfigs;
247 }
248 }
249 // The activation state of this config changed.
250 if (isPrevActive != isCurActive) {
251 VLOG("Active status changed for uid %d", uid);
252 uidsWithActiveConfigsChanged.insert(uid);
253 StatsdStats::getInstance().noteActiveStatusChanged(pair.first, isCurActive);
254 }
Yangster-mac330af582018-02-08 15:24:38 -0800255 flushIfNecessaryLocked(event->GetElapsedTimestampNs(), pair.first, *(pair.second));
David Chen21582962017-11-01 17:32:46 -0700256 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800257
258 for (int uid : uidsWithActiveConfigsChanged) {
259 // Send broadcast so that receivers can pull data.
260 auto lastBroadcastTime = mLastActivationBroadcastTimes.find(uid);
261 if (lastBroadcastTime != mLastActivationBroadcastTimes.end()) {
262 if (currentTimestampNs - lastBroadcastTime->second <
263 StatsdStats::kMinActivationBroadcastPeriodNs) {
264 VLOG("StatsD would've sent an activation broadcast but the rate limit stopped us.");
265 return;
266 }
267 }
268 auto activeConfigs = activeConfigsPerUid.find(uid);
269 if (activeConfigs != activeConfigsPerUid.end()) {
270 if (mSendActivationBroadcast(uid, activeConfigs->second)) {
271 VLOG("StatsD sent activation notice for uid %d", uid);
272 mLastActivationBroadcastTimes[uid] = currentTimestampNs;
273 }
274 } else {
275 std::vector<int64_t> emptyActiveConfigs;
276 if (mSendActivationBroadcast(uid, emptyActiveConfigs)) {
277 VLOG("StatsD sent EMPTY activation notice for uid %d", uid);
278 mLastActivationBroadcastTimes[uid] = currentTimestampNs;
279 }
280 }
281 }
282}
283
284void StatsLogProcessor::GetActiveConfigs(const int uid, vector<int64_t>& outActiveConfigs) {
285 std::lock_guard<std::mutex> lock(mMetricsMutex);
286 GetActiveConfigsLocked(uid, outActiveConfigs);
287}
288
289void StatsLogProcessor::GetActiveConfigsLocked(const int uid, vector<int64_t>& outActiveConfigs) {
290 outActiveConfigs.clear();
291 for (auto& pair : mMetricsManagers) {
292 if (pair.first.GetUid() == uid && pair.second->isActive()) {
293 outActiveConfigs.push_back(pair.first.GetId());
294 }
295 }
Yao Chenab273e22017-09-06 12:53:50 -0700296}
297
Yangster-macc04feba2018-04-02 14:37:33 -0700298void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
299 const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800300 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac892f3d32018-05-02 14:16:48 -0700301 WriteDataToDiskLocked(key, timestampNs, CONFIG_UPDATED);
Yangster-macb142cc82018-03-30 15:22:08 -0700302 OnConfigUpdatedLocked(timestampNs, key, config);
303}
304
305void StatsLogProcessor::OnConfigUpdatedLocked(
306 const int64_t timestampNs, const ConfigKey& key, const StatsdConfig& config) {
Tej Singh484524a2018-02-01 15:10:05 -0800307 VLOG("Updated configuration for key %s", key.ToString().c_str());
Yangster-mac932ecec2018-02-01 10:23:52 -0800308 sp<MetricsManager> newMetricsManager =
Chenjie Yue2219202018-06-08 10:07:51 -0700309 new MetricsManager(key, config, mTimeBaseNs, timestampNs, mUidMap, mPullerManager,
310 mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
Yao Chencaf339d2017-10-06 16:01:10 -0700311 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700312 mUidMap->OnConfigUpdated(key);
Yao Chen147ce602017-12-22 14:35:34 -0800313 if (newMetricsManager->shouldAddUidMapListener()) {
Yao Chend10f7b12017-12-18 12:53:50 -0800314 // We have to add listener after the MetricsManager is constructed because it's
315 // not safe to create wp or sp from this pointer inside its constructor.
316 mUidMap->addListener(newMetricsManager.get());
317 }
Yangster-macb142cc82018-03-30 15:22:08 -0700318 newMetricsManager->refreshTtl(timestampNs);
Yao Chend10f7b12017-12-18 12:53:50 -0800319 mMetricsManagers[key] = newMetricsManager;
Yao Chenb3561512017-11-21 18:07:17 -0800320 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700321 } else {
322 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800323 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700324 }
yro00698da2017-09-15 10:06:40 -0700325}
Bookatz906a35c2017-09-20 15:26:44 -0700326
Yangster7c334a12017-11-22 14:24:24 -0800327size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800328 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700329 auto it = mMetricsManagers.find(key);
330 if (it == mMetricsManagers.end()) {
331 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800332 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700333 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800334 return it->second->byteSize();
335}
336
Yao Chena80e5c02018-09-04 13:55:29 -0700337void StatsLogProcessor::dumpStates(int out, bool verbose) {
Yao Chen884c8c12018-01-26 10:36:25 -0800338 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chena80e5c02018-09-04 13:55:29 -0700339 FILE* fout = fdopen(out, "w");
340 if (fout == NULL) {
341 return;
Yao Chen884c8c12018-01-26 10:36:25 -0800342 }
Yao Chena80e5c02018-09-04 13:55:29 -0700343 fprintf(fout, "MetricsManager count: %lu\n", (unsigned long)mMetricsManagers.size());
344 for (auto metricsManager : mMetricsManagers) {
345 metricsManager.second->dumpStates(fout, verbose);
346 }
347
348 fclose(fout);
Yao Chen884c8c12018-01-26 10:36:25 -0800349}
350
yro4beccbe2018-03-15 19:42:05 -0700351/*
Bookatz9cc7b662018-11-06 10:39:21 -0800352 * onDumpReport dumps serialized ConfigMetricsReportList into proto.
yro4beccbe2018-03-15 19:42:05 -0700353 */
Yangster-macb142cc82018-03-30 15:22:08 -0700354void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700355 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700356 const bool erase_data,
Chenjie Yue36018b2018-04-16 15:18:30 -0700357 const DumpReportReason dumpReportReason,
Bookatzff71cad2018-09-20 17:17:49 -0700358 ProtoOutputStream* proto) {
Yangster-macb0d06282018-01-05 15:44:07 -0800359 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800360
yro947fbce2017-11-15 22:50:23 -0800361 // Start of ConfigKey.
Bookatzff71cad2018-09-20 17:17:49 -0700362 uint64_t configKeyToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
363 proto->write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
364 proto->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
365 proto->end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800366 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800367
yro947fbce2017-11-15 22:50:23 -0800368 // Then, check stats-data directory to see there's any file containing
369 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
Bookatzc71d9012018-12-19 12:28:38 -0800370 StorageManager::appendConfigMetricsReport(key, proto, erase_data);
yro947fbce2017-11-15 22:50:23 -0800371
Yangster-mace68f3a52018-04-04 00:01:43 -0700372 auto it = mMetricsManagers.find(key);
373 if (it != mMetricsManagers.end()) {
374 // This allows another broadcast to be sent within the rate-limit period if we get close to
375 // filling the buffer again soon.
376 mLastBroadcastTimes.erase(key);
377
378 // Start of ConfigMetricsReport (reports).
379 uint64_t reportsToken =
Bookatzff71cad2018-09-20 17:17:49 -0700380 proto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS);
Chenjie Yue36018b2018-04-16 15:18:30 -0700381 onConfigMetricsReportLocked(key, dumpTimeStampNs, include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700382 erase_data, dumpReportReason, proto);
383 proto->end(reportsToken);
Yangster-mace68f3a52018-04-04 00:01:43 -0700384 // End of ConfigMetricsReport (reports).
385 } else {
386 ALOGW("Config source %s does not exist", key.ToString().c_str());
387 }
Bookatzff71cad2018-09-20 17:17:49 -0700388}
389
390/*
391 * onDumpReport dumps serialized ConfigMetricsReportList into outData.
392 */
393void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
394 const bool include_current_partial_bucket,
395 const bool erase_data,
396 const DumpReportReason dumpReportReason,
397 vector<uint8_t>* outData) {
398 ProtoOutputStream proto;
399 onDumpReport(key, dumpTimeStampNs, include_current_partial_bucket, erase_data,
400 dumpReportReason, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700401
David Chen1d7b0cd2017-11-15 14:20:04 -0800402 if (outData != nullptr) {
403 outData->clear();
404 outData->resize(proto.size());
405 size_t pos = 0;
406 auto iter = proto.data();
407 while (iter.readBuffer() != NULL) {
408 size_t toRead = iter.currentToRead();
409 std::memcpy(&((*outData)[pos]), iter.readBuffer(), toRead);
410 pos += toRead;
411 iter.rp()->move(toRead);
412 }
yro17adac92017-11-08 23:16:29 -0800413 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800414
Yangster-mace68f3a52018-04-04 00:01:43 -0700415 StatsdStats::getInstance().noteMetricsReportSent(key, proto.size());
Yao Chen729093d2017-10-16 10:33:26 -0700416}
417
yro4beccbe2018-03-15 19:42:05 -0700418/*
419 * onConfigMetricsReportLocked dumps serialized ConfigMetricsReport into outData.
420 */
421void StatsLogProcessor::onConfigMetricsReportLocked(const ConfigKey& key,
Yangster-macb142cc82018-03-30 15:22:08 -0700422 const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700423 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700424 const bool erase_data,
Chenjie Yue36018b2018-04-16 15:18:30 -0700425 const DumpReportReason dumpReportReason,
yro4beccbe2018-03-15 19:42:05 -0700426 ProtoOutputStream* proto) {
427 // We already checked whether key exists in mMetricsManagers in
428 // WriteDataToDisk.
429 auto it = mMetricsManagers.find(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700430 if (it == mMetricsManagers.end()) {
431 return;
432 }
yro4beccbe2018-03-15 19:42:05 -0700433 int64_t lastReportTimeNs = it->second->getLastReportTimeNs();
434 int64_t lastReportWallClockNs = it->second->getLastReportWallClockNs();
435
Yangster-mac9def8e32018-04-17 13:55:51 -0700436 std::set<string> str_set;
437
yro4beccbe2018-03-15 19:42:05 -0700438 // First, fill in ConfigMetricsReport using current data on memory, which
439 // starts from filling in StatsLogReport's.
Yangster-mac9def8e32018-04-17 13:55:51 -0700440 it->second->onDumpReport(dumpTimeStampNs, include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700441 erase_data, &str_set, proto);
yro4beccbe2018-03-15 19:42:05 -0700442
David Chen9e6dbbd2018-05-07 17:52:29 -0700443 // Fill in UidMap if there is at least one metric to report.
444 // This skips the uid map if it's an empty config.
445 if (it->second->getNumMetrics() > 0) {
446 uint64_t uidMapToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP);
dwchen730403e2018-10-29 11:41:56 -0700447 mUidMap->appendUidMap(
448 dumpTimeStampNs, key, it->second->hashStringInReport() ? &str_set : nullptr,
449 it->second->versionStringsInReport(), it->second->installerInReport(), proto);
David Chen9e6dbbd2018-05-07 17:52:29 -0700450 proto->end(uidMapToken);
451 }
yro4beccbe2018-03-15 19:42:05 -0700452
453 // Fill in the timestamps.
454 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_ELAPSED_NANOS,
455 (long long)lastReportTimeNs);
456 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS,
457 (long long)dumpTimeStampNs);
458 proto->write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS,
459 (long long)lastReportWallClockNs);
460 proto->write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS,
461 (long long)getWallClockNs());
Chenjie Yue36018b2018-04-16 15:18:30 -0700462 // Dump report reason
463 proto->write(FIELD_TYPE_INT32 | FIELD_ID_DUMP_REPORT_REASON, dumpReportReason);
Yangster-mac9def8e32018-04-17 13:55:51 -0700464
David Chen56ae0d92018-05-11 16:00:22 -0700465 for (const auto& str : str_set) {
466 proto->write(FIELD_TYPE_STRING | FIELD_COUNT_REPEATED | FIELD_ID_STRINGS, str);
Yangster-mac9def8e32018-04-17 13:55:51 -0700467 }
Yangster-macb142cc82018-03-30 15:22:08 -0700468}
yro4beccbe2018-03-15 19:42:05 -0700469
Yao Chen163d2602018-04-10 10:39:53 -0700470void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs,
471 const std::vector<ConfigKey>& configs) {
472 for (const auto& key : configs) {
Yangster-macb142cc82018-03-30 15:22:08 -0700473 StatsdConfig config;
474 if (StorageManager::readConfigFromDisk(key, &config)) {
475 OnConfigUpdatedLocked(timestampNs, key, config);
476 StatsdStats::getInstance().noteConfigReset(key);
477 } else {
478 ALOGE("Failed to read backup config from disk for : %s", key.ToString().c_str());
479 auto it = mMetricsManagers.find(key);
480 if (it != mMetricsManagers.end()) {
481 it->second->refreshTtl(timestampNs);
482 }
483 }
484 }
yro4beccbe2018-03-15 19:42:05 -0700485}
486
Yao Chen163d2602018-04-10 10:39:53 -0700487void StatsLogProcessor::resetIfConfigTtlExpiredLocked(const int64_t timestampNs) {
488 std::vector<ConfigKey> configKeysTtlExpired;
489 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
490 if (it->second != nullptr && !it->second->isInTtl(timestampNs)) {
491 configKeysTtlExpired.push_back(it->first);
492 }
493 }
494 if (configKeysTtlExpired.size() > 0) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700495 WriteDataToDiskLocked(CONFIG_RESET);
Yao Chen163d2602018-04-10 10:39:53 -0700496 resetConfigsLocked(timestampNs, configKeysTtlExpired);
497 }
498}
499
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700500void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800501 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700502 auto it = mMetricsManagers.find(key);
503 if (it != mMetricsManagers.end()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700504 WriteDataToDiskLocked(key, getElapsedRealtimeNs(), CONFIG_REMOVED);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700505 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700506 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700507 }
Yao Chenb3561512017-11-21 18:07:17 -0800508 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800509
David Chen1d7b0cd2017-11-15 14:20:04 -0800510 mLastBroadcastTimes.erase(key);
Chenjie Yufa22d652018-02-05 14:37:48 -0800511
Tej Singh6ede28b2019-01-29 17:06:54 -0800512 int uid = key.GetUid();
513 bool lastConfigForUid = true;
514 for (auto it : mMetricsManagers) {
515 if (it.first.GetUid() == uid) {
516 lastConfigForUid = false;
517 break;
518 }
519 }
520 if (lastConfigForUid) {
521 mLastActivationBroadcastTimes.erase(uid);
522 }
523
Chenjie Yufa22d652018-02-05 14:37:48 -0800524 if (mMetricsManagers.empty()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700525 mPullerManager->ForceClearPullerCache();
Chenjie Yufa22d652018-02-05 14:37:48 -0800526 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700527}
528
Yangster-macb0d06282018-01-05 15:44:07 -0800529void StatsLogProcessor::flushIfNecessaryLocked(
Yangster-macb142cc82018-03-30 15:22:08 -0700530 int64_t timestampNs, const ConfigKey& key, MetricsManager& metricsManager) {
David Chend9269e22017-12-05 13:43:51 -0800531 auto lastCheckTime = mLastByteSizeTimes.find(key);
532 if (lastCheckTime != mLastByteSizeTimes.end()) {
533 if (timestampNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
534 return;
535 }
536 }
537
538 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
539 size_t totalBytes = metricsManager.byteSize();
540 mLastByteSizeTimes[key] = timestampNs;
David Chen48944902018-05-03 10:29:11 -0700541 bool requestDump = false;
David Chend9269e22017-12-05 13:43:51 -0800542 if (totalBytes >
543 StatsdStats::kMaxMetricsBytesPerConfig) { // Too late. We need to start clearing data.
Yao Chen06dba5d2018-01-26 13:38:16 -0800544 metricsManager.dropData(timestampNs);
Chenjie Yuc3c30c02018-10-26 09:48:07 -0700545 StatsdStats::getInstance().noteDataDropped(key, totalBytes);
David Chen12942952017-12-04 14:28:43 -0800546 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chen48944902018-05-03 10:29:11 -0700547 } else if ((totalBytes > StatsdStats::kBytesPerConfigTriggerGetData) ||
548 (mOnDiskDataConfigs.find(key) != mOnDiskDataConfigs.end())) {
549 // Request to send a broadcast if:
550 // 1. in memory data > threshold OR
551 // 2. config has old data report on disk.
552 requestDump = true;
553 }
554
555 if (requestDump) {
David Chend9269e22017-12-05 13:43:51 -0800556 // Send broadcast so that receivers can pull data.
557 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
558 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
559 if (timestampNs - lastBroadcastTime->second < StatsdStats::kMinBroadcastPeriodNs) {
560 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800561 return;
562 }
563 }
David Chen48944902018-05-03 10:29:11 -0700564 if (mSendBroadcast(key)) {
565 mOnDiskDataConfigs.erase(key);
566 VLOG("StatsD triggered data fetch for %s", key.ToString().c_str());
567 mLastBroadcastTimes[key] = timestampNs;
568 StatsdStats::getInstance().noteBroadcastSent(key);
569 }
yro31eb67b2017-10-24 13:33:21 -0700570 }
571}
572
Chenjie Yue36018b2018-04-16 15:18:30 -0700573void StatsLogProcessor::WriteDataToDiskLocked(const ConfigKey& key,
Yangster-mac892f3d32018-05-02 14:16:48 -0700574 const int64_t timestampNs,
Chenjie Yue36018b2018-04-16 15:18:30 -0700575 const DumpReportReason dumpReportReason) {
yro028091c2018-05-09 16:03:27 -0700576 if (mMetricsManagers.find(key) == mMetricsManagers.end() ||
577 !mMetricsManagers.find(key)->second->shouldWriteToDisk()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700578 return;
579 }
Yangster-mace68f3a52018-04-04 00:01:43 -0700580 ProtoOutputStream proto;
David Chen56ae0d92018-05-11 16:00:22 -0700581 onConfigMetricsReportLocked(key, timestampNs, true /* include_current_partial_bucket*/,
Bookatzff71cad2018-09-20 17:17:49 -0700582 true /* erase_data */, dumpReportReason, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700583 string file_name = StringPrintf("%s/%ld_%d_%lld", STATS_DATA_DIR,
584 (long)getWallClockSec(), key.GetUid(), (long long)key.GetId());
585 android::base::unique_fd fd(open(file_name.c_str(),
586 O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
587 if (fd == -1) {
588 ALOGE("Attempt to write %s but failed", file_name.c_str());
589 return;
590 }
591 proto.flush(fd.get());
David Chen48944902018-05-03 10:29:11 -0700592 // We were able to write the ConfigMetricsReport to disk, so we should trigger collection ASAP.
593 mOnDiskDataConfigs.insert(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700594}
595
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800596void StatsLogProcessor::WriteMetricsActivationToDisk(int64_t currentTimeNs) {
597 std::lock_guard<std::mutex> lock(mMetricsMutex);
598 ProtoOutputStream proto;
599
600 for (const auto& pair : mMetricsManagers) {
601 uint64_t activeConfigListToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
602 FIELD_ID_ACTIVE_CONFIG_LIST);
603 proto.write(FIELD_TYPE_INT64 | FIELD_ID_CONFIG_ID, (long long)pair.first.GetId());
604 proto.write(FIELD_TYPE_INT32 | FIELD_ID_CONFIG_UID, pair.first.GetUid());
605
Chenjie Yua9a310e2019-02-06 13:40:10 -0800606 vector<MetricProducer*> activeMetrics;
607 pair.second->prepForShutDown(currentTimeNs);
608 pair.second->getActiveMetrics(activeMetrics);
609 for (MetricProducer* metric : activeMetrics) {
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800610 if (metric->isActive()) {
611 uint64_t metricToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
612 FIELD_ID_ACTIVE_METRIC);
613 proto.write(FIELD_TYPE_INT64 | FIELD_ID_METRIC_ID,
614 (long long)metric->getMetricId());
615 proto.write(FIELD_TYPE_INT64 | FIELD_ID_TIME_TO_LIVE_NANOS,
616 (long long)metric->getRemainingTtlNs(currentTimeNs));
617 proto.end(metricToken);
618 }
619 }
620 proto.end(activeConfigListToken);
621 }
622
623 string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
624 StorageManager::deleteFile(file_name.c_str());
625 android::base::unique_fd fd(
626 open(file_name.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
627 if (fd == -1) {
628 ALOGE("Attempt to write %s but failed", file_name.c_str());
629 return;
630 }
631 proto.flush(fd.get());
632}
633
634void StatsLogProcessor::LoadMetricsActivationFromDisk() {
635 string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
636 int fd = open(file_name.c_str(), O_RDONLY | O_CLOEXEC);
637 if (fd != -1) {
638 string content;
639 if (android::base::ReadFdToString(fd, &content)) {
640 ActiveConfigList activeConfigList;
641 if (activeConfigList.ParseFromString(content)) {
642 for (int i = 0; i < activeConfigList.active_config_size(); i++) {
643 const auto& config = activeConfigList.active_config(i);
644 ConfigKey key(config.uid(), config.config_id());
645 auto it = mMetricsManagers.find(key);
646 if (it == mMetricsManagers.end()) {
647 ALOGE("No config found for config %s", key.ToString().c_str());
648 continue;
649 }
650 VLOG("Setting active config %s", key.ToString().c_str());
651 it->second->setActiveMetrics(config, mTimeBaseNs);
652 }
653 }
654 VLOG("Successfully loaded %d active configs.", activeConfigList.active_config_size());
655 }
656 close(fd);
657 }
658 StorageManager::deleteFile(file_name.c_str());
659}
660
Chenjie Yue36018b2018-04-16 15:18:30 -0700661void StatsLogProcessor::WriteDataToDiskLocked(const DumpReportReason dumpReportReason) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700662 const int64_t timeNs = getElapsedRealtimeNs();
Tej Singh42f9e062018-11-09 10:01:00 -0800663 // Do not write to disk if we already have in the last few seconds.
664 // This is to avoid overwriting files that would have the same name if we
665 // write twice in the same second.
666 if (static_cast<unsigned long long> (timeNs) <
667 mLastWriteTimeNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
668 ALOGI("Statsd skipping writing data to disk. Already wrote data in last %d seconds",
669 WRITE_DATA_COOL_DOWN_SEC);
670 return;
671 }
672 mLastWriteTimeNs = timeNs;
Yangster-mace68f3a52018-04-04 00:01:43 -0700673 for (auto& pair : mMetricsManagers) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700674 WriteDataToDiskLocked(pair.first, timeNs, dumpReportReason);
Yangster-mace68f3a52018-04-04 00:01:43 -0700675 }
676}
677
Yangster-mac892f3d32018-05-02 14:16:48 -0700678void StatsLogProcessor::WriteDataToDisk(const DumpReportReason dumpReportReason) {
Yangster-macb0d06282018-01-05 15:44:07 -0800679 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac892f3d32018-05-02 14:16:48 -0700680 WriteDataToDiskLocked(dumpReportReason);
yro947fbce2017-11-15 22:50:23 -0800681}
682
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700683void StatsLogProcessor::informPullAlarmFired(const int64_t timestampNs) {
Yangster6df5fcc2018-04-12 11:04:29 -0700684 std::lock_guard<std::mutex> lock(mMetricsMutex);
Chenjie Yue2219202018-06-08 10:07:51 -0700685 mPullerManager->OnAlarmFired(timestampNs);
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700686}
687
David Chend37bc232018-04-12 18:05:11 -0700688int64_t StatsLogProcessor::getLastReportTimeNs(const ConfigKey& key) {
689 auto it = mMetricsManagers.find(key);
690 if (it == mMetricsManagers.end()) {
691 return 0;
692 } else {
693 return it->second->getLastReportTimeNs();
694 }
695}
696
David Chen48944902018-05-03 10:29:11 -0700697void StatsLogProcessor::noteOnDiskData(const ConfigKey& key) {
698 std::lock_guard<std::mutex> lock(mMetricsMutex);
699 mOnDiskDataConfigs.insert(key);
700}
701
Yao Chenef99c4f2017-09-22 16:26:54 -0700702} // namespace statsd
703} // namespace os
704} // namespace android