blob: 98d41c22d5406ab6cefa1e98169ea48add1edb01 [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"
tsaichristined21aacf2019-10-07 14:47:38 -070019
20#include "StatsLogProcessor.h"
Yao Chenab273e22017-09-06 12:53:50 -070021
yro947fbce2017-11-15 22:50:23 -080022#include <android-base/file.h>
23#include <dirent.h>
Chenjie Yuc7939cb2019-02-04 17:25:45 -080024#include <frameworks/base/cmds/statsd/src/active_config_list.pb.h>
tsaichristined21aacf2019-10-07 14:47:38 -070025#include <log/log_event_list.h>
26#include <utils/Errors.h>
27#include <utils/SystemClock.h>
28
yro947fbce2017-11-15 22:50:23 -080029#include "android-base/stringprintf.h"
Chenjie Yuc7939cb2019-02-04 17:25:45 -080030#include "external/StatsPullerManager.h"
Yao Chenb3561512017-11-21 18:07:17 -080031#include "guardrail/StatsdStats.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070032#include "metrics/CountMetricProducer.h"
tsaichristined21aacf2019-10-07 14:47:38 -070033#include "state/StateManager.h"
Chenjie Yuc7939cb2019-02-04 17:25:45 -080034#include "stats_log_util.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070035#include "stats_util.h"
tsaichristined21aacf2019-10-07 14:47:38 -070036#include "statslog.h"
yro947fbce2017-11-15 22:50:23 -080037#include "storage/StorageManager.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070038
Yao Chenab273e22017-09-06 12:53:50 -070039using namespace android;
yro947fbce2017-11-15 22:50:23 -080040using android::base::StringPrintf;
yrob0378b02017-11-09 20:36:25 -080041using android::util::FIELD_COUNT_REPEATED;
yro17adac92017-11-08 23:16:29 -080042using android::util::FIELD_TYPE_BOOL;
43using android::util::FIELD_TYPE_FLOAT;
44using android::util::FIELD_TYPE_INT32;
45using android::util::FIELD_TYPE_INT64;
46using android::util::FIELD_TYPE_MESSAGE;
47using android::util::FIELD_TYPE_STRING;
48using android::util::ProtoOutputStream;
Yao Chen44cf27c2017-09-14 22:32:50 -070049using std::make_unique;
50using std::unique_ptr;
51using std::vector;
Bookatz906a35c2017-09-20 15:26:44 -070052
53namespace android {
54namespace os {
55namespace statsd {
Yao Chenab273e22017-09-06 12:53:50 -070056
yro947fbce2017-11-15 22:50:23 -080057// for ConfigMetricsReportList
yro17adac92017-11-08 23:16:29 -080058const int FIELD_ID_CONFIG_KEY = 1;
yro947fbce2017-11-15 22:50:23 -080059const int FIELD_ID_REPORTS = 2;
yro17adac92017-11-08 23:16:29 -080060// for ConfigKey
61const int FIELD_ID_UID = 1;
Yangster-mac94e197c2018-01-02 16:03:03 -080062const int FIELD_ID_ID = 2;
yro947fbce2017-11-15 22:50:23 -080063// for ConfigMetricsReport
Yao Chen4c959cb2018-02-13 13:27:48 -080064// const int FIELD_ID_METRICS = 1; // written in MetricsManager.cpp
yro947fbce2017-11-15 22:50:23 -080065const int FIELD_ID_UID_MAP = 2;
Yangster-mac330af582018-02-08 15:24:38 -080066const int FIELD_ID_LAST_REPORT_ELAPSED_NANOS = 3;
67const int FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS = 4;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -080068const int FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS = 5;
69const int FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS = 6;
Chenjie Yue36018b2018-04-16 15:18:30 -070070const int FIELD_ID_DUMP_REPORT_REASON = 8;
Yangster-mac9def8e32018-04-17 13:55:51 -070071const int FIELD_ID_STRINGS = 9;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -080072
Muhammad Qureshi844694b2019-04-05 10:10:40 -070073// for ActiveConfigList
74const int FIELD_ID_ACTIVE_CONFIG_LIST_CONFIG = 1;
Chenjie Yuc7939cb2019-02-04 17:25:45 -080075
Yangster-macb142cc82018-03-30 15:22:08 -070076#define NS_PER_HOUR 3600 * NS_PER_SEC
yro947fbce2017-11-15 22:50:23 -080077
Chenjie Yuc7939cb2019-02-04 17:25:45 -080078#define STATS_ACTIVE_METRIC_DIR "/data/misc/stats-active-metric"
yro17adac92017-11-08 23:16:29 -080079
Tej Singh42f9e062018-11-09 10:01:00 -080080// Cool down period for writing data to disk to avoid overwriting files.
81#define WRITE_DATA_COOL_DOWN_SEC 5
82
yro31eb67b2017-10-24 13:33:21 -070083StatsLogProcessor::StatsLogProcessor(const sp<UidMap>& uidMap,
Chenjie Yue2219202018-06-08 10:07:51 -070084 const sp<StatsPullerManager>& pullerManager,
Yangster-mac932ecec2018-02-01 10:23:52 -080085 const sp<AlarmMonitor>& anomalyAlarmMonitor,
86 const sp<AlarmMonitor>& periodicAlarmMonitor,
Yangster-mac15f6bbc2018-04-08 11:52:26 -070087 const int64_t timeBaseNs,
Tej Singh6ede28b2019-01-29 17:06:54 -080088 const std::function<bool(const ConfigKey&)>& sendBroadcast,
89 const std::function<bool(
90 const int&, const vector<int64_t>&)>& activateBroadcast)
Chenjie Yu85ed8382017-12-14 16:48:54 -080091 : mUidMap(uidMap),
Chenjie Yue2219202018-06-08 10:07:51 -070092 mPullerManager(pullerManager),
Yangster-mac932ecec2018-02-01 10:23:52 -080093 mAnomalyAlarmMonitor(anomalyAlarmMonitor),
94 mPeriodicAlarmMonitor(periodicAlarmMonitor),
Chenjie Yu85ed8382017-12-14 16:48:54 -080095 mSendBroadcast(sendBroadcast),
Tej Singh6ede28b2019-01-29 17:06:54 -080096 mSendActivationBroadcast(activateBroadcast),
Yangster-mac15f6bbc2018-04-08 11:52:26 -070097 mTimeBaseNs(timeBaseNs),
Yao Chen163d2602018-04-10 10:39:53 -070098 mLargestTimestampSeen(0),
99 mLastTimestampSeen(0) {
Chenjie Yue2219202018-06-08 10:07:51 -0700100 mPullerManager->ForceClearPullerCache();
Yao Chenab273e22017-09-06 12:53:50 -0700101}
102
Yao Chenef99c4f2017-09-22 16:26:54 -0700103StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -0700104}
105
Yao Chen9a43b4f2019-04-10 10:43:20 -0700106static void flushProtoToBuffer(ProtoOutputStream& proto, vector<uint8_t>* outData) {
107 outData->clear();
108 outData->resize(proto.size());
109 size_t pos = 0;
110 sp<android::util::ProtoReader> reader = proto.data();
111 while (reader->readBuffer() != NULL) {
112 size_t toRead = reader->currentToRead();
113 std::memcpy(&((*outData)[pos]), reader->readBuffer(), toRead);
114 pos += toRead;
115 reader->move(toRead);
116 }
117}
118
Yangster-mace2cd6d52017-11-09 20:38:30 -0800119void StatsLogProcessor::onAnomalyAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700120 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800121 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
Yangster-macb0d06282018-01-05 15:44:07 -0800122 std::lock_guard<std::mutex> lock(mMetricsMutex);
Bookatzcc5adef22017-11-21 14:36:23 -0800123 for (const auto& itr : mMetricsManagers) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800124 itr.second->onAnomalyAlarmFired(timestampNs, alarmSet);
125 }
126}
127void StatsLogProcessor::onPeriodicAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700128 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800129 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
130
131 std::lock_guard<std::mutex> lock(mMetricsMutex);
132 for (const auto& itr : mMetricsManagers) {
133 itr.second->onPeriodicAlarmFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800134 }
135}
136
Yao Chen8a8d16c2018-02-08 14:50:40 -0800137void updateUid(Value* value, int hostUid) {
138 int uid = value->int_value;
139 if (uid != hostUid) {
140 value->setInt(hostUid);
141 }
142}
143
Yangster-macd40053e2018-01-09 16:29:22 -0800144void StatsLogProcessor::mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent* event) const {
Yao Chenc40a19d2018-03-15 16:48:25 -0700145 if (android::util::AtomsInfo::kAtomsWithAttributionChain.find(event->GetTagId()) !=
146 android::util::AtomsInfo::kAtomsWithAttributionChain.end()) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800147 for (auto& value : *(event->getMutableValues())) {
148 if (value.mField.getPosAtDepth(0) > kAttributionField) {
149 break;
150 }
151 if (isAttributionUidField(value)) {
152 const int hostUid = mUidMap->getHostUidOrSelf(value.mValue.int_value);
153 updateUid(&value.mValue, hostUid);
154 }
Yangster-macd40053e2018-01-09 16:29:22 -0800155 }
Yao Chenc40a19d2018-03-15 16:48:25 -0700156 } else {
157 auto it = android::util::AtomsInfo::kAtomsWithUidField.find(event->GetTagId());
158 if (it != android::util::AtomsInfo::kAtomsWithUidField.end()) {
159 int uidField = it->second; // uidField is the field number in proto,
160 // starting from 1
161 if (uidField > 0 && (int)event->getValues().size() >= uidField &&
162 (event->getValues())[uidField - 1].mValue.getType() == INT) {
163 Value& value = (*event->getMutableValues())[uidField - 1].mValue;
164 const int hostUid = mUidMap->getHostUidOrSelf(value.int_value);
165 updateUid(&value, hostUid);
166 } else {
167 ALOGE("Malformed log, uid not found. %s", event->ToString().c_str());
168 }
169 }
Yao Chen312e8982017-12-05 15:29:03 -0800170 }
Yangster-macd40053e2018-01-09 16:29:22 -0800171}
172
173void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
174 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
175 bool is_create = event.GetBool(3, &err);
176 auto parent_uid = int(event.GetLong(1, &err2));
177 auto isolated_uid = int(event.GetLong(2, &err3));
178 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
179 if (is_create) {
180 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
181 } else {
Bookatz3c648862018-05-25 13:32:43 -0700182 mUidMap->removeIsolatedUid(isolated_uid);
Yangster-macd40053e2018-01-09 16:29:22 -0800183 }
184 } else {
185 ALOGE("Failed to parse uid in the isolated uid change event.");
186 }
187}
188
Yangster-mac892f3d32018-05-02 14:16:48 -0700189void StatsLogProcessor::resetConfigs() {
190 std::lock_guard<std::mutex> lock(mMetricsMutex);
191 resetConfigsLocked(getElapsedRealtimeNs());
192}
193
194void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs) {
195 std::vector<ConfigKey> configKeys;
196 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
197 configKeys.push_back(it->first);
198 }
199 resetConfigsLocked(timestampNs, configKeys);
200}
201
Yao Chen3ff3a492018-08-06 16:17:37 -0700202void StatsLogProcessor::OnLogEvent(LogEvent* event) {
Tej Singh480392f2019-10-23 15:53:46 -0700203 OnLogEvent(event, getElapsedRealtimeNs());
204}
205
206void StatsLogProcessor::OnLogEvent(LogEvent* event, int64_t elapsedRealtimeNs) {
Yangster-macd40053e2018-01-09 16:29:22 -0800207 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen876889c2018-05-02 11:16:16 -0700208
209#ifdef VERY_VERBOSE_PRINTING
210 if (mPrintAllLogs) {
211 ALOGI("%s", event->ToString().c_str());
212 }
213#endif
Tej Singh480392f2019-10-23 15:53:46 -0700214 const int64_t eventElapsedTimeNs = event->GetElapsedTimestampNs();
Yangster-macb8382a12018-04-04 10:39:12 -0700215
Tej Singh480392f2019-10-23 15:53:46 -0700216 resetIfConfigTtlExpiredLocked(eventElapsedTimeNs);
Yangster-macb142cc82018-03-30 15:22:08 -0700217
Yangster-macd40053e2018-01-09 16:29:22 -0800218 StatsdStats::getInstance().noteAtomLogged(
Yangster-mac330af582018-02-08 15:24:38 -0800219 event->GetTagId(), event->GetElapsedTimestampNs() / NS_PER_SEC);
Yangster-macd40053e2018-01-09 16:29:22 -0800220
David Chen21582962017-11-01 17:32:46 -0700221 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800222 // The field numbers need to be currently updated by hand with atoms.proto
Yangster-macd40053e2018-01-09 16:29:22 -0800223 if (event->GetTagId() == android::util::ISOLATED_UID_CHANGED) {
224 onIsolatedUidChangedEventLocked(*event);
David Chencfc311d2018-01-23 17:55:54 -0800225 }
226
tsaichristined21aacf2019-10-07 14:47:38 -0700227 StateManager::getInstance().onLogEvent(*event);
228
David Chencfc311d2018-01-23 17:55:54 -0800229 if (mMetricsManagers.empty()) {
230 return;
231 }
232
Yangster-macb142cc82018-03-30 15:22:08 -0700233 int64_t curTimeSec = getElapsedRealtimeSec();
Yangster-mac330af582018-02-08 15:24:38 -0800234 if (curTimeSec - mLastPullerCacheClearTimeSec > StatsdStats::kPullerCacheClearIntervalSec) {
Chenjie Yue2219202018-06-08 10:07:51 -0700235 mPullerManager->ClearPullerCacheIfNecessary(curTimeSec * NS_PER_SEC);
Yangster-mac330af582018-02-08 15:24:38 -0800236 mLastPullerCacheClearTimeSec = curTimeSec;
Chenjie Yufa22d652018-02-05 14:37:48 -0800237 }
238
Yangster-macb142cc82018-03-30 15:22:08 -0700239
David Chencfc311d2018-01-23 17:55:54 -0800240 if (event->GetTagId() != android::util::ISOLATED_UID_CHANGED) {
Yangster-macd40053e2018-01-09 16:29:22 -0800241 // Map the isolated uid to host uid if necessary.
242 mapIsolatedUidToHostUidIfNecessaryLocked(event);
243 }
244
Tej Singh6ede28b2019-01-29 17:06:54 -0800245 std::unordered_set<int> uidsWithActiveConfigsChanged;
246 std::unordered_map<int, std::vector<int64_t>> activeConfigsPerUid;
Yangster-macd40053e2018-01-09 16:29:22 -0800247 // pass the event to metrics managers.
248 for (auto& pair : mMetricsManagers) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800249 int uid = pair.first.GetUid();
250 int64_t configId = pair.first.GetId();
251 bool isPrevActive = pair.second->isActive();
Yangster-macd40053e2018-01-09 16:29:22 -0800252 pair.second->onLogEvent(*event);
Tej Singh6ede28b2019-01-29 17:06:54 -0800253 bool isCurActive = pair.second->isActive();
254 // Map all active configs by uid.
255 if (isCurActive) {
256 auto activeConfigs = activeConfigsPerUid.find(uid);
257 if (activeConfigs != activeConfigsPerUid.end()) {
258 activeConfigs->second.push_back(configId);
259 } else {
260 vector<int64_t> newActiveConfigs;
261 newActiveConfigs.push_back(configId);
262 activeConfigsPerUid[uid] = newActiveConfigs;
263 }
264 }
265 // The activation state of this config changed.
266 if (isPrevActive != isCurActive) {
267 VLOG("Active status changed for uid %d", uid);
268 uidsWithActiveConfigsChanged.insert(uid);
269 StatsdStats::getInstance().noteActiveStatusChanged(pair.first, isCurActive);
270 }
Tej Singh480392f2019-10-23 15:53:46 -0700271 flushIfNecessaryLocked(pair.first, *(pair.second));
David Chen21582962017-11-01 17:32:46 -0700272 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800273
Tej Singh480392f2019-10-23 15:53:46 -0700274 // Don't use the event timestamp for the guardrail.
Tej Singh6ede28b2019-01-29 17:06:54 -0800275 for (int uid : uidsWithActiveConfigsChanged) {
276 // Send broadcast so that receivers can pull data.
277 auto lastBroadcastTime = mLastActivationBroadcastTimes.find(uid);
278 if (lastBroadcastTime != mLastActivationBroadcastTimes.end()) {
Tej Singh480392f2019-10-23 15:53:46 -0700279 if (elapsedRealtimeNs - lastBroadcastTime->second <
280 StatsdStats::kMinActivationBroadcastPeriodNs) {
Tej Singh16ca28f2019-06-24 11:58:23 -0700281 StatsdStats::getInstance().noteActivationBroadcastGuardrailHit(uid);
Tej Singh6ede28b2019-01-29 17:06:54 -0800282 VLOG("StatsD would've sent an activation broadcast but the rate limit stopped us.");
283 return;
284 }
285 }
286 auto activeConfigs = activeConfigsPerUid.find(uid);
287 if (activeConfigs != activeConfigsPerUid.end()) {
288 if (mSendActivationBroadcast(uid, activeConfigs->second)) {
289 VLOG("StatsD sent activation notice for uid %d", uid);
Tej Singh480392f2019-10-23 15:53:46 -0700290 mLastActivationBroadcastTimes[uid] = elapsedRealtimeNs;
Tej Singh6ede28b2019-01-29 17:06:54 -0800291 }
292 } else {
293 std::vector<int64_t> emptyActiveConfigs;
294 if (mSendActivationBroadcast(uid, emptyActiveConfigs)) {
295 VLOG("StatsD sent EMPTY activation notice for uid %d", uid);
Tej Singh480392f2019-10-23 15:53:46 -0700296 mLastActivationBroadcastTimes[uid] = elapsedRealtimeNs;
Tej Singh6ede28b2019-01-29 17:06:54 -0800297 }
298 }
299 }
300}
301
302void StatsLogProcessor::GetActiveConfigs(const int uid, vector<int64_t>& outActiveConfigs) {
303 std::lock_guard<std::mutex> lock(mMetricsMutex);
304 GetActiveConfigsLocked(uid, outActiveConfigs);
305}
306
307void StatsLogProcessor::GetActiveConfigsLocked(const int uid, vector<int64_t>& outActiveConfigs) {
308 outActiveConfigs.clear();
309 for (auto& pair : mMetricsManagers) {
310 if (pair.first.GetUid() == uid && pair.second->isActive()) {
311 outActiveConfigs.push_back(pair.first.GetId());
312 }
313 }
Yao Chenab273e22017-09-06 12:53:50 -0700314}
315
Yangster-macc04feba2018-04-02 14:37:33 -0700316void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
317 const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800318 std::lock_guard<std::mutex> lock(mMetricsMutex);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000319 WriteDataToDiskLocked(key, timestampNs, CONFIG_UPDATED, NO_TIME_CONSTRAINTS);
Yangster-macb142cc82018-03-30 15:22:08 -0700320 OnConfigUpdatedLocked(timestampNs, key, config);
321}
322
323void StatsLogProcessor::OnConfigUpdatedLocked(
324 const int64_t timestampNs, const ConfigKey& key, const StatsdConfig& config) {
Tej Singh484524a2018-02-01 15:10:05 -0800325 VLOG("Updated configuration for key %s", key.ToString().c_str());
Yangster-mac932ecec2018-02-01 10:23:52 -0800326 sp<MetricsManager> newMetricsManager =
Chenjie Yue2219202018-06-08 10:07:51 -0700327 new MetricsManager(key, config, mTimeBaseNs, timestampNs, mUidMap, mPullerManager,
328 mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
Yao Chencaf339d2017-10-06 16:01:10 -0700329 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700330 mUidMap->OnConfigUpdated(key);
Yangster-macb142cc82018-03-30 15:22:08 -0700331 newMetricsManager->refreshTtl(timestampNs);
Yao Chend10f7b12017-12-18 12:53:50 -0800332 mMetricsManagers[key] = newMetricsManager;
Yao Chenb3561512017-11-21 18:07:17 -0800333 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700334 } else {
335 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800336 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700337 }
yro00698da2017-09-15 10:06:40 -0700338}
Bookatz906a35c2017-09-20 15:26:44 -0700339
Yangster7c334a12017-11-22 14:24:24 -0800340size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800341 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700342 auto it = mMetricsManagers.find(key);
343 if (it == mMetricsManagers.end()) {
344 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800345 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700346 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800347 return it->second->byteSize();
348}
349
Yao Chena80e5c02018-09-04 13:55:29 -0700350void StatsLogProcessor::dumpStates(int out, bool verbose) {
Yao Chen884c8c12018-01-26 10:36:25 -0800351 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chena80e5c02018-09-04 13:55:29 -0700352 FILE* fout = fdopen(out, "w");
353 if (fout == NULL) {
354 return;
Yao Chen884c8c12018-01-26 10:36:25 -0800355 }
Yao Chena80e5c02018-09-04 13:55:29 -0700356 fprintf(fout, "MetricsManager count: %lu\n", (unsigned long)mMetricsManagers.size());
357 for (auto metricsManager : mMetricsManagers) {
358 metricsManager.second->dumpStates(fout, verbose);
359 }
360
361 fclose(fout);
Yao Chen884c8c12018-01-26 10:36:25 -0800362}
363
yro4beccbe2018-03-15 19:42:05 -0700364/*
Bookatz9cc7b662018-11-06 10:39:21 -0800365 * onDumpReport dumps serialized ConfigMetricsReportList into proto.
yro4beccbe2018-03-15 19:42:05 -0700366 */
Yangster-macb142cc82018-03-30 15:22:08 -0700367void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700368 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700369 const bool erase_data,
Chenjie Yue36018b2018-04-16 15:18:30 -0700370 const DumpReportReason dumpReportReason,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000371 const DumpLatency dumpLatency,
Bookatzff71cad2018-09-20 17:17:49 -0700372 ProtoOutputStream* proto) {
Yangster-macb0d06282018-01-05 15:44:07 -0800373 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800374
yro947fbce2017-11-15 22:50:23 -0800375 // Start of ConfigKey.
Bookatzff71cad2018-09-20 17:17:49 -0700376 uint64_t configKeyToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
377 proto->write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
378 proto->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
379 proto->end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800380 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800381
Yao Chen9a43b4f2019-04-10 10:43:20 -0700382 bool keepFile = false;
383 auto it = mMetricsManagers.find(key);
384 if (it != mMetricsManagers.end() && it->second->shouldPersistLocalHistory()) {
385 keepFile = true;
386 }
387
yro947fbce2017-11-15 22:50:23 -0800388 // Then, check stats-data directory to see there's any file containing
389 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
Yao Chen9a43b4f2019-04-10 10:43:20 -0700390 StorageManager::appendConfigMetricsReport(
391 key, proto, erase_data && !keepFile /* should remove file after appending it */,
392 dumpReportReason == ADB_DUMP /*if caller is adb*/);
yro947fbce2017-11-15 22:50:23 -0800393
Yangster-mace68f3a52018-04-04 00:01:43 -0700394 if (it != mMetricsManagers.end()) {
395 // This allows another broadcast to be sent within the rate-limit period if we get close to
396 // filling the buffer again soon.
397 mLastBroadcastTimes.erase(key);
398
Yao Chen9a43b4f2019-04-10 10:43:20 -0700399 vector<uint8_t> buffer;
400 onConfigMetricsReportLocked(key, dumpTimeStampNs, include_current_partial_bucket,
401 erase_data, dumpReportReason, dumpLatency,
402 false /* is this data going to be saved on disk */, &buffer);
403 proto->write(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS,
404 reinterpret_cast<char*>(buffer.data()), buffer.size());
Yangster-mace68f3a52018-04-04 00:01:43 -0700405 } else {
406 ALOGW("Config source %s does not exist", key.ToString().c_str());
407 }
Bookatzff71cad2018-09-20 17:17:49 -0700408}
409
410/*
411 * onDumpReport dumps serialized ConfigMetricsReportList into outData.
412 */
413void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
414 const bool include_current_partial_bucket,
415 const bool erase_data,
416 const DumpReportReason dumpReportReason,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000417 const DumpLatency dumpLatency,
Bookatzff71cad2018-09-20 17:17:49 -0700418 vector<uint8_t>* outData) {
419 ProtoOutputStream proto;
420 onDumpReport(key, dumpTimeStampNs, include_current_partial_bucket, erase_data,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000421 dumpReportReason, dumpLatency, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700422
David Chen1d7b0cd2017-11-15 14:20:04 -0800423 if (outData != nullptr) {
Yao Chen9a43b4f2019-04-10 10:43:20 -0700424 flushProtoToBuffer(proto, outData);
425 VLOG("output data size %zu", outData->size());
yro17adac92017-11-08 23:16:29 -0800426 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800427
Yangster-mace68f3a52018-04-04 00:01:43 -0700428 StatsdStats::getInstance().noteMetricsReportSent(key, proto.size());
Yao Chen729093d2017-10-16 10:33:26 -0700429}
430
yro4beccbe2018-03-15 19:42:05 -0700431/*
432 * onConfigMetricsReportLocked dumps serialized ConfigMetricsReport into outData.
433 */
Yao Chen9a43b4f2019-04-10 10:43:20 -0700434void StatsLogProcessor::onConfigMetricsReportLocked(
435 const ConfigKey& key, const int64_t dumpTimeStampNs,
436 const bool include_current_partial_bucket, const bool erase_data,
437 const DumpReportReason dumpReportReason, const DumpLatency dumpLatency,
438 const bool dataSavedOnDisk, vector<uint8_t>* buffer) {
yro4beccbe2018-03-15 19:42:05 -0700439 // We already checked whether key exists in mMetricsManagers in
440 // WriteDataToDisk.
441 auto it = mMetricsManagers.find(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700442 if (it == mMetricsManagers.end()) {
443 return;
444 }
yro4beccbe2018-03-15 19:42:05 -0700445 int64_t lastReportTimeNs = it->second->getLastReportTimeNs();
446 int64_t lastReportWallClockNs = it->second->getLastReportWallClockNs();
447
Yangster-mac9def8e32018-04-17 13:55:51 -0700448 std::set<string> str_set;
449
Yao Chen9a43b4f2019-04-10 10:43:20 -0700450 ProtoOutputStream tempProto;
yro4beccbe2018-03-15 19:42:05 -0700451 // First, fill in ConfigMetricsReport using current data on memory, which
452 // starts from filling in StatsLogReport's.
Yao Chen9a43b4f2019-04-10 10:43:20 -0700453 it->second->onDumpReport(dumpTimeStampNs, include_current_partial_bucket, erase_data,
454 dumpLatency, &str_set, &tempProto);
yro4beccbe2018-03-15 19:42:05 -0700455
David Chen9e6dbbd2018-05-07 17:52:29 -0700456 // Fill in UidMap if there is at least one metric to report.
457 // This skips the uid map if it's an empty config.
458 if (it->second->getNumMetrics() > 0) {
Yao Chen9a43b4f2019-04-10 10:43:20 -0700459 uint64_t uidMapToken = tempProto.start(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP);
dwchen730403e2018-10-29 11:41:56 -0700460 mUidMap->appendUidMap(
461 dumpTimeStampNs, key, it->second->hashStringInReport() ? &str_set : nullptr,
Yao Chen9a43b4f2019-04-10 10:43:20 -0700462 it->second->versionStringsInReport(), it->second->installerInReport(), &tempProto);
463 tempProto.end(uidMapToken);
David Chen9e6dbbd2018-05-07 17:52:29 -0700464 }
yro4beccbe2018-03-15 19:42:05 -0700465
466 // Fill in the timestamps.
Yao Chen9a43b4f2019-04-10 10:43:20 -0700467 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_ELAPSED_NANOS,
468 (long long)lastReportTimeNs);
469 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS,
470 (long long)dumpTimeStampNs);
471 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS,
472 (long long)lastReportWallClockNs);
473 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS,
474 (long long)getWallClockNs());
Chenjie Yue36018b2018-04-16 15:18:30 -0700475 // Dump report reason
Yao Chen9a43b4f2019-04-10 10:43:20 -0700476 tempProto.write(FIELD_TYPE_INT32 | FIELD_ID_DUMP_REPORT_REASON, dumpReportReason);
Yangster-mac9def8e32018-04-17 13:55:51 -0700477
David Chen56ae0d92018-05-11 16:00:22 -0700478 for (const auto& str : str_set) {
Yao Chen9a43b4f2019-04-10 10:43:20 -0700479 tempProto.write(FIELD_TYPE_STRING | FIELD_COUNT_REPEATED | FIELD_ID_STRINGS, str);
480 }
481
482 flushProtoToBuffer(tempProto, buffer);
483
484 // save buffer to disk if needed
485 if (erase_data && !dataSavedOnDisk && it->second->shouldPersistLocalHistory()) {
486 VLOG("save history to disk");
487 string file_name = StorageManager::getDataHistoryFileName((long)getWallClockSec(),
488 key.GetUid(), key.GetId());
489 StorageManager::writeFile(file_name.c_str(), buffer->data(), buffer->size());
Yangster-mac9def8e32018-04-17 13:55:51 -0700490 }
Yangster-macb142cc82018-03-30 15:22:08 -0700491}
yro4beccbe2018-03-15 19:42:05 -0700492
Yao Chen163d2602018-04-10 10:39:53 -0700493void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs,
494 const std::vector<ConfigKey>& configs) {
495 for (const auto& key : configs) {
Yangster-macb142cc82018-03-30 15:22:08 -0700496 StatsdConfig config;
497 if (StorageManager::readConfigFromDisk(key, &config)) {
498 OnConfigUpdatedLocked(timestampNs, key, config);
499 StatsdStats::getInstance().noteConfigReset(key);
500 } else {
501 ALOGE("Failed to read backup config from disk for : %s", key.ToString().c_str());
502 auto it = mMetricsManagers.find(key);
503 if (it != mMetricsManagers.end()) {
504 it->second->refreshTtl(timestampNs);
505 }
506 }
507 }
yro4beccbe2018-03-15 19:42:05 -0700508}
509
Yao Chen163d2602018-04-10 10:39:53 -0700510void StatsLogProcessor::resetIfConfigTtlExpiredLocked(const int64_t timestampNs) {
511 std::vector<ConfigKey> configKeysTtlExpired;
512 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
513 if (it->second != nullptr && !it->second->isInTtl(timestampNs)) {
514 configKeysTtlExpired.push_back(it->first);
515 }
516 }
517 if (configKeysTtlExpired.size() > 0) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000518 WriteDataToDiskLocked(CONFIG_RESET, NO_TIME_CONSTRAINTS);
Yao Chen163d2602018-04-10 10:39:53 -0700519 resetConfigsLocked(timestampNs, configKeysTtlExpired);
520 }
521}
522
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700523void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800524 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700525 auto it = mMetricsManagers.find(key);
526 if (it != mMetricsManagers.end()) {
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700527 WriteDataToDiskLocked(key, getElapsedRealtimeNs(), CONFIG_REMOVED,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000528 NO_TIME_CONSTRAINTS);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700529 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700530 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700531 }
Yao Chenb3561512017-11-21 18:07:17 -0800532 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800533
David Chen1d7b0cd2017-11-15 14:20:04 -0800534 mLastBroadcastTimes.erase(key);
Chenjie Yufa22d652018-02-05 14:37:48 -0800535
Tej Singh6ede28b2019-01-29 17:06:54 -0800536 int uid = key.GetUid();
537 bool lastConfigForUid = true;
538 for (auto it : mMetricsManagers) {
539 if (it.first.GetUid() == uid) {
540 lastConfigForUid = false;
541 break;
542 }
543 }
544 if (lastConfigForUid) {
545 mLastActivationBroadcastTimes.erase(uid);
546 }
547
Chenjie Yufa22d652018-02-05 14:37:48 -0800548 if (mMetricsManagers.empty()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700549 mPullerManager->ForceClearPullerCache();
Chenjie Yufa22d652018-02-05 14:37:48 -0800550 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700551}
552
Tej Singh480392f2019-10-23 15:53:46 -0700553void StatsLogProcessor::flushIfNecessaryLocked(const ConfigKey& key,
554 MetricsManager& metricsManager) {
555 int64_t elapsedRealtimeNs = getElapsedRealtimeNs();
David Chend9269e22017-12-05 13:43:51 -0800556 auto lastCheckTime = mLastByteSizeTimes.find(key);
557 if (lastCheckTime != mLastByteSizeTimes.end()) {
Tej Singh480392f2019-10-23 15:53:46 -0700558 if (elapsedRealtimeNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
David Chend9269e22017-12-05 13:43:51 -0800559 return;
560 }
561 }
562
563 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
564 size_t totalBytes = metricsManager.byteSize();
Tej Singh480392f2019-10-23 15:53:46 -0700565 mLastByteSizeTimes[key] = elapsedRealtimeNs;
David Chen48944902018-05-03 10:29:11 -0700566 bool requestDump = false;
Tej Singh480392f2019-10-23 15:53:46 -0700567 if (totalBytes > StatsdStats::kMaxMetricsBytesPerConfig) {
568 // Too late. We need to start clearing data.
569 metricsManager.dropData(elapsedRealtimeNs);
Chenjie Yuc3c30c02018-10-26 09:48:07 -0700570 StatsdStats::getInstance().noteDataDropped(key, totalBytes);
David Chen12942952017-12-04 14:28:43 -0800571 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chen48944902018-05-03 10:29:11 -0700572 } else if ((totalBytes > StatsdStats::kBytesPerConfigTriggerGetData) ||
573 (mOnDiskDataConfigs.find(key) != mOnDiskDataConfigs.end())) {
574 // Request to send a broadcast if:
575 // 1. in memory data > threshold OR
576 // 2. config has old data report on disk.
577 requestDump = true;
578 }
579
580 if (requestDump) {
David Chend9269e22017-12-05 13:43:51 -0800581 // Send broadcast so that receivers can pull data.
582 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
583 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
Tej Singh480392f2019-10-23 15:53:46 -0700584 if (elapsedRealtimeNs - lastBroadcastTime->second <
585 StatsdStats::kMinBroadcastPeriodNs) {
David Chend9269e22017-12-05 13:43:51 -0800586 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800587 return;
588 }
589 }
David Chen48944902018-05-03 10:29:11 -0700590 if (mSendBroadcast(key)) {
591 mOnDiskDataConfigs.erase(key);
592 VLOG("StatsD triggered data fetch for %s", key.ToString().c_str());
Tej Singh480392f2019-10-23 15:53:46 -0700593 mLastBroadcastTimes[key] = elapsedRealtimeNs;
David Chen48944902018-05-03 10:29:11 -0700594 StatsdStats::getInstance().noteBroadcastSent(key);
595 }
yro31eb67b2017-10-24 13:33:21 -0700596 }
597}
598
Chenjie Yue36018b2018-04-16 15:18:30 -0700599void StatsLogProcessor::WriteDataToDiskLocked(const ConfigKey& key,
Yangster-mac892f3d32018-05-02 14:16:48 -0700600 const int64_t timestampNs,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000601 const DumpReportReason dumpReportReason,
602 const DumpLatency dumpLatency) {
yro028091c2018-05-09 16:03:27 -0700603 if (mMetricsManagers.find(key) == mMetricsManagers.end() ||
604 !mMetricsManagers.find(key)->second->shouldWriteToDisk()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700605 return;
606 }
Yao Chen9a43b4f2019-04-10 10:43:20 -0700607 vector<uint8_t> buffer;
David Chen56ae0d92018-05-11 16:00:22 -0700608 onConfigMetricsReportLocked(key, timestampNs, true /* include_current_partial_bucket*/,
Yao Chen9a43b4f2019-04-10 10:43:20 -0700609 true /* erase_data */, dumpReportReason, dumpLatency, true,
610 &buffer);
611 string file_name =
612 StorageManager::getDataFileName((long)getWallClockSec(), key.GetUid(), key.GetId());
613 StorageManager::writeFile(file_name.c_str(), buffer.data(), buffer.size());
614
David Chen48944902018-05-03 10:29:11 -0700615 // We were able to write the ConfigMetricsReport to disk, so we should trigger collection ASAP.
616 mOnDiskDataConfigs.insert(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700617}
618
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700619void StatsLogProcessor::SaveActiveConfigsToDisk(int64_t currentTimeNs) {
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800620 std::lock_guard<std::mutex> lock(mMetricsMutex);
jianjin996f40d2019-03-29 13:53:48 -0700621 const int64_t timeNs = getElapsedRealtimeNs();
622 // Do not write to disk if we already have in the last few seconds.
jianjin996f40d2019-03-29 13:53:48 -0700623 if (static_cast<unsigned long long> (timeNs) <
624 mLastActiveMetricsWriteNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
625 ALOGI("Statsd skipping writing active metrics to disk. Already wrote data in last %d seconds",
626 WRITE_DATA_COOL_DOWN_SEC);
627 return;
628 }
629 mLastActiveMetricsWriteNs = timeNs;
630
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800631 ProtoOutputStream proto;
Tej Singhf53d4452019-05-09 18:17:59 -0700632 WriteActiveConfigsToProtoOutputStreamLocked(currentTimeNs, DEVICE_SHUTDOWN, &proto);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800633
634 string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
635 StorageManager::deleteFile(file_name.c_str());
636 android::base::unique_fd fd(
637 open(file_name.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
638 if (fd == -1) {
639 ALOGE("Attempt to write %s but failed", file_name.c_str());
640 return;
641 }
642 proto.flush(fd.get());
643}
644
Tej Singhf53d4452019-05-09 18:17:59 -0700645void StatsLogProcessor::WriteActiveConfigsToProtoOutputStream(
646 int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto) {
647 std::lock_guard<std::mutex> lock(mMetricsMutex);
648 WriteActiveConfigsToProtoOutputStreamLocked(currentTimeNs, reason, proto);
649}
650
651void StatsLogProcessor::WriteActiveConfigsToProtoOutputStreamLocked(
652 int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto) {
653 for (const auto& pair : mMetricsManagers) {
654 const sp<MetricsManager>& metricsManager = pair.second;
655 uint64_t configToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
656 FIELD_ID_ACTIVE_CONFIG_LIST_CONFIG);
657 metricsManager->writeActiveConfigToProtoOutputStream(currentTimeNs, reason, proto);
658 proto->end(configToken);
659 }
660}
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700661void StatsLogProcessor::LoadActiveConfigsFromDisk() {
662 std::lock_guard<std::mutex> lock(mMetricsMutex);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800663 string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
664 int fd = open(file_name.c_str(), O_RDONLY | O_CLOEXEC);
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700665 if (-1 == fd) {
666 VLOG("Attempt to read %s but failed", file_name.c_str());
667 StorageManager::deleteFile(file_name.c_str());
668 return;
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800669 }
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700670 string content;
671 if (!android::base::ReadFdToString(fd, &content)) {
672 ALOGE("Attempt to read %s but failed", file_name.c_str());
673 close(fd);
674 StorageManager::deleteFile(file_name.c_str());
675 return;
676 }
677
678 close(fd);
679
680 ActiveConfigList activeConfigList;
681 if (!activeConfigList.ParseFromString(content)) {
682 ALOGE("Attempt to read %s but failed; failed to load active configs", file_name.c_str());
683 StorageManager::deleteFile(file_name.c_str());
684 return;
685 }
Tej Singhf53d4452019-05-09 18:17:59 -0700686 // Passing in mTimeBaseNs only works as long as we only load from disk is when statsd starts.
687 SetConfigsActiveStateLocked(activeConfigList, mTimeBaseNs);
688 StorageManager::deleteFile(file_name.c_str());
689}
690
691void StatsLogProcessor::SetConfigsActiveState(const ActiveConfigList& activeConfigList,
692 int64_t currentTimeNs) {
693 std::lock_guard<std::mutex> lock(mMetricsMutex);
694 SetConfigsActiveStateLocked(activeConfigList, currentTimeNs);
695}
696
697void StatsLogProcessor::SetConfigsActiveStateLocked(const ActiveConfigList& activeConfigList,
698 int64_t currentTimeNs) {
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700699 for (int i = 0; i < activeConfigList.config_size(); i++) {
700 const auto& config = activeConfigList.config(i);
701 ConfigKey key(config.uid(), config.id());
702 auto it = mMetricsManagers.find(key);
703 if (it == mMetricsManagers.end()) {
704 ALOGE("No config found for config %s", key.ToString().c_str());
705 continue;
706 }
707 VLOG("Setting active config %s", key.ToString().c_str());
Tej Singhf53d4452019-05-09 18:17:59 -0700708 it->second->loadActiveConfig(config, currentTimeNs);
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700709 }
710 VLOG("Successfully loaded %d active configs.", activeConfigList.config_size());
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800711}
712
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000713void StatsLogProcessor::WriteDataToDiskLocked(const DumpReportReason dumpReportReason,
714 const DumpLatency dumpLatency) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700715 const int64_t timeNs = getElapsedRealtimeNs();
Tej Singh42f9e062018-11-09 10:01:00 -0800716 // Do not write to disk if we already have in the last few seconds.
717 // This is to avoid overwriting files that would have the same name if we
718 // write twice in the same second.
719 if (static_cast<unsigned long long> (timeNs) <
720 mLastWriteTimeNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
721 ALOGI("Statsd skipping writing data to disk. Already wrote data in last %d seconds",
722 WRITE_DATA_COOL_DOWN_SEC);
723 return;
724 }
725 mLastWriteTimeNs = timeNs;
Yangster-mace68f3a52018-04-04 00:01:43 -0700726 for (auto& pair : mMetricsManagers) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000727 WriteDataToDiskLocked(pair.first, timeNs, dumpReportReason, dumpLatency);
Yangster-mace68f3a52018-04-04 00:01:43 -0700728 }
729}
730
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700731void StatsLogProcessor::WriteDataToDisk(const DumpReportReason dumpReportReason,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000732 const DumpLatency dumpLatency) {
Yangster-macb0d06282018-01-05 15:44:07 -0800733 std::lock_guard<std::mutex> lock(mMetricsMutex);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000734 WriteDataToDiskLocked(dumpReportReason, dumpLatency);
yro947fbce2017-11-15 22:50:23 -0800735}
736
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700737void StatsLogProcessor::informPullAlarmFired(const int64_t timestampNs) {
Yangster6df5fcc2018-04-12 11:04:29 -0700738 std::lock_guard<std::mutex> lock(mMetricsMutex);
Chenjie Yue2219202018-06-08 10:07:51 -0700739 mPullerManager->OnAlarmFired(timestampNs);
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700740}
741
David Chend37bc232018-04-12 18:05:11 -0700742int64_t StatsLogProcessor::getLastReportTimeNs(const ConfigKey& key) {
743 auto it = mMetricsManagers.find(key);
744 if (it == mMetricsManagers.end()) {
745 return 0;
746 } else {
747 return it->second->getLastReportTimeNs();
748 }
749}
750
Tej Singh9ec159a2019-11-14 11:59:48 -0800751void StatsLogProcessor::notifyAppUpgrade(const int64_t& eventTimeNs, const string& apk,
752 const int uid, const int64_t version) {
753 std::lock_guard<std::mutex> lock(mMetricsMutex);
754 ALOGW("Received app upgrade");
755 for (auto it : mMetricsManagers) {
756 it.second->notifyAppUpgrade(eventTimeNs, apk, uid, version);
757 }
758}
759
760void StatsLogProcessor::notifyAppRemoved(const int64_t& eventTimeNs, const string& apk,
761 const int uid) {
762 std::lock_guard<std::mutex> lock(mMetricsMutex);
763 ALOGW("Received app removed");
764 for (auto it : mMetricsManagers) {
765 it.second->notifyAppRemoved(eventTimeNs, apk, uid);
766 }
767}
768
769void StatsLogProcessor::onUidMapReceived(const int64_t& eventTimeNs) {
770 std::lock_guard<std::mutex> lock(mMetricsMutex);
771 ALOGW("Received uid map");
772 for (auto it : mMetricsManagers) {
773 it.second->onUidMapReceived(eventTimeNs);
774 }
775}
776
David Chen48944902018-05-03 10:29:11 -0700777void StatsLogProcessor::noteOnDiskData(const ConfigKey& key) {
778 std::lock_guard<std::mutex> lock(mMetricsMutex);
779 mOnDiskDataConfigs.insert(key);
780}
781
Yao Chenef99c4f2017-09-22 16:26:54 -0700782} // namespace statsd
783} // namespace os
784} // namespace android