blob: 095dd1e9be5929df63f061f0163081226e778b1c [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>
Jonathan Nguyena0e6de12020-01-28 18:33:55 -080023#include <cutils/multiuser.h>
Chenjie Yuc7939cb2019-02-04 17:25:45 -080024#include <frameworks/base/cmds/statsd/src/active_config_list.pb.h>
Jonathan Nguyena0e6de12020-01-28 18:33:55 -080025#include <frameworks/base/cmds/statsd/src/experiment_ids.pb.h>
tsaichristined21aacf2019-10-07 14:47:38 -070026
yro947fbce2017-11-15 22:50:23 -080027#include "android-base/stringprintf.h"
Chenjie Yuc7939cb2019-02-04 17:25:45 -080028#include "external/StatsPullerManager.h"
Yao Chenb3561512017-11-21 18:07:17 -080029#include "guardrail/StatsdStats.h"
Jonathan Nguyena0e6de12020-01-28 18:33:55 -080030#include "logd/LogEvent.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070031#include "metrics/CountMetricProducer.h"
Jonathan Nguyena0e6de12020-01-28 18:33:55 -080032#include "StatsService.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"
Jeffrey Huang74fc4352020-03-06 15:18:33 -080036#include "statslog_statsd.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::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
Muhammad Qureshi844694b2019-04-05 10:10:40 -070071// for ActiveConfigList
72const int FIELD_ID_ACTIVE_CONFIG_LIST_CONFIG = 1;
Chenjie Yuc7939cb2019-02-04 17:25:45 -080073
Jonathan Nguyena0e6de12020-01-28 18:33:55 -080074// for permissions checks
75constexpr const char* kPermissionDump = "android.permission.DUMP";
76constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
77
Yangster-macb142cc82018-03-30 15:22:08 -070078#define NS_PER_HOUR 3600 * NS_PER_SEC
yro947fbce2017-11-15 22:50:23 -080079
Chenjie Yuc7939cb2019-02-04 17:25:45 -080080#define STATS_ACTIVE_METRIC_DIR "/data/misc/stats-active-metric"
Jeffrey Huangb8f54032020-03-23 13:42:42 -070081#define STATS_METADATA_DIR "/data/misc/stats-metadata"
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();
Muhammad Qureshi7ce22562020-05-12 01:08:00 -0700104 StateManager::getInstance().updateLogSources(uidMap);
Yao Chenab273e22017-09-06 12:53:50 -0700105}
106
Yao Chenef99c4f2017-09-22 16:26:54 -0700107StatsLogProcessor::~StatsLogProcessor() {
Yao Chenab273e22017-09-06 12:53:50 -0700108}
109
Yao Chen9a43b4f2019-04-10 10:43:20 -0700110static void flushProtoToBuffer(ProtoOutputStream& proto, vector<uint8_t>* outData) {
111 outData->clear();
112 outData->resize(proto.size());
113 size_t pos = 0;
114 sp<android::util::ProtoReader> reader = proto.data();
115 while (reader->readBuffer() != NULL) {
116 size_t toRead = reader->currentToRead();
117 std::memcpy(&((*outData)[pos]), reader->readBuffer(), toRead);
118 pos += toRead;
119 reader->move(toRead);
120 }
121}
122
Yangster-mace2cd6d52017-11-09 20:38:30 -0800123void StatsLogProcessor::onAnomalyAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700124 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800125 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
Yangster-macb0d06282018-01-05 15:44:07 -0800126 std::lock_guard<std::mutex> lock(mMetricsMutex);
Bookatzcc5adef22017-11-21 14:36:23 -0800127 for (const auto& itr : mMetricsManagers) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800128 itr.second->onAnomalyAlarmFired(timestampNs, alarmSet);
129 }
130}
131void StatsLogProcessor::onPeriodicAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700132 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800133 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet) {
134
135 std::lock_guard<std::mutex> lock(mMetricsMutex);
136 for (const auto& itr : mMetricsManagers) {
137 itr.second->onPeriodicAlarmFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800138 }
139}
140
Yangster-macd40053e2018-01-09 16:29:22 -0800141void StatsLogProcessor::mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent* event) const {
Muhammad Qureshi83aaa662020-04-21 12:51:36 -0700142 if (std::pair<int, int> indexRange; event->hasAttributionChain(&indexRange)) {
143 vector<FieldValue>* const fieldValues = event->getMutableValues();
144 for (int i = indexRange.first; i <= indexRange.second; i++) {
145 FieldValue& fieldValue = fieldValues->at(i);
146 if (isAttributionUidField(fieldValue)) {
147 const int hostUid = mUidMap->getHostUidOrSelf(fieldValue.mValue.int_value);
148 fieldValue.mValue.setInt(hostUid);
Yao Chen8a8d16c2018-02-08 14:50:40 -0800149 }
Yangster-macd40053e2018-01-09 16:29:22 -0800150 }
Yao Chenc40a19d2018-03-15 16:48:25 -0700151 } else {
Ruchir Rastogiffa34f052020-04-04 15:30:11 -0700152 int uidFieldIndex = event->getUidFieldIndex();
153 if (uidFieldIndex != -1) {
154 Value& value = (*event->getMutableValues())[uidFieldIndex].mValue;
155 const int hostUid = mUidMap->getHostUidOrSelf(value.int_value);
156 value.setInt(hostUid);
Yao Chenc40a19d2018-03-15 16:48:25 -0700157 }
Yao Chen312e8982017-12-05 15:29:03 -0800158 }
Yangster-macd40053e2018-01-09 16:29:22 -0800159}
160
161void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
162 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
163 bool is_create = event.GetBool(3, &err);
164 auto parent_uid = int(event.GetLong(1, &err2));
165 auto isolated_uid = int(event.GetLong(2, &err3));
166 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
167 if (is_create) {
168 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
169 } else {
Bookatz3c648862018-05-25 13:32:43 -0700170 mUidMap->removeIsolatedUid(isolated_uid);
Yangster-macd40053e2018-01-09 16:29:22 -0800171 }
172 } else {
173 ALOGE("Failed to parse uid in the isolated uid change event.");
174 }
175}
176
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800177void StatsLogProcessor::onBinaryPushStateChangedEventLocked(LogEvent* event) {
178 pid_t pid = event->GetPid();
179 uid_t uid = event->GetUid();
180 if (!checkPermissionForIds(kPermissionDump, pid, uid) ||
181 !checkPermissionForIds(kPermissionUsage, pid, uid)) {
182 return;
183 }
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800184 // The Get* functions don't modify the status on success, they only write in
185 // failure statuses, so we can use one status variable for all calls then
186 // check if it is no longer NO_ERROR.
187 status_t err = NO_ERROR;
188 InstallTrainInfo trainInfo;
189 trainInfo.trainName = string(event->GetString(1 /*train name field id*/, &err));
190 trainInfo.trainVersionCode = event->GetLong(2 /*train version field id*/, &err);
191 trainInfo.requiresStaging = event->GetBool(3 /*requires staging field id*/, &err);
192 trainInfo.rollbackEnabled = event->GetBool(4 /*rollback enabled field id*/, &err);
193 trainInfo.requiresLowLatencyMonitor =
194 event->GetBool(5 /*requires low latency monitor field id*/, &err);
195 trainInfo.status = int32_t(event->GetLong(6 /*state field id*/, &err));
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800196 std::vector<uint8_t> trainExperimentIdBytes =
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800197 event->GetStorage(7 /*experiment ids field id*/, &err);
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800198 bool is_rollback = event->GetBool(10 /*is rollback field id*/, &err);
199
200 if (err != NO_ERROR) {
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800201 ALOGE("Failed to parse fields in binary push state changed log event");
202 return;
203 }
204 ExperimentIds trainExperimentIds;
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800205 if (!trainExperimentIds.ParseFromArray(trainExperimentIdBytes.data(),
206 trainExperimentIdBytes.size())) {
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800207 ALOGE("Failed to parse experimentids in binary push state changed.");
208 return;
209 }
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800210 trainInfo.experimentIds = {trainExperimentIds.experiment_id().begin(),
211 trainExperimentIds.experiment_id().end()};
212
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800213 // Update the train info on disk and get any data the logevent is missing.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800214 getAndUpdateTrainInfoOnDisk(is_rollback, &trainInfo);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800215
216 std::vector<uint8_t> trainExperimentIdProto;
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800217 writeExperimentIdsToProto(trainInfo.experimentIds, &trainExperimentIdProto);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800218 int32_t userId = multiuser_get_user_id(uid);
219
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800220 event->updateValue(2 /*train version field id*/, trainInfo.trainVersionCode, LONG);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800221 event->updateValue(7 /*experiment ids field id*/, trainExperimentIdProto, STORAGE);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800222 event->updateValue(8 /*user id field id*/, userId, INT);
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800223
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800224 // If this event is a rollback event, then the following bits in the event
225 // are invalid and we will need to update them with the values we pulled
226 // from disk.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800227 if (is_rollback) {
228 int bit = trainInfo.requiresStaging ? 1 : 0;
229 event->updateValue(3 /*requires staging field id*/, bit, INT);
230 bit = trainInfo.rollbackEnabled ? 1 : 0;
231 event->updateValue(4 /*rollback enabled field id*/, bit, INT);
232 bit = trainInfo.requiresLowLatencyMonitor ? 1 : 0;
233 event->updateValue(5 /*requires low latency monitor field id*/, bit, INT);
234 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800235}
236
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800237void StatsLogProcessor::getAndUpdateTrainInfoOnDisk(bool is_rollback,
238 InstallTrainInfo* trainInfo) {
239 // If the train name is empty, we don't know which train to attribute the
240 // event to, so return early.
241 if (trainInfo->trainName.empty()) {
242 return;
243 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800244 bool readTrainInfoSuccess = false;
245 InstallTrainInfo trainInfoOnDisk;
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800246 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfo->trainName, trainInfoOnDisk);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800247
248 bool resetExperimentIds = false;
249 if (readTrainInfoSuccess) {
250 // Keep the old train version if we received an empty version.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800251 if (trainInfo->trainVersionCode == -1) {
252 trainInfo->trainVersionCode = trainInfoOnDisk.trainVersionCode;
253 } else if (trainInfo->trainVersionCode != trainInfoOnDisk.trainVersionCode) {
254 // Reset experiment ids if we receive a new non-empty train version.
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800255 resetExperimentIds = true;
256 }
257
258 // Reset if we received a different experiment id.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800259 if (!trainInfo->experimentIds.empty() &&
260 (trainInfoOnDisk.experimentIds.empty() ||
261 trainInfo->experimentIds.at(0) != trainInfoOnDisk.experimentIds[0])) {
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800262 resetExperimentIds = true;
263 }
264 }
265
266 // Find the right experiment IDs
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800267 if ((!resetExperimentIds || is_rollback) && readTrainInfoSuccess) {
268 trainInfo->experimentIds = trainInfoOnDisk.experimentIds;
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800269 }
270
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800271 if (!trainInfo->experimentIds.empty()) {
272 int64_t firstId = trainInfo->experimentIds.at(0);
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800273 auto& ids = trainInfo->experimentIds;
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800274 switch (trainInfo->status) {
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800275 case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALL_SUCCESS:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800276 if (find(ids.begin(), ids.end(), firstId + 1) == ids.end()) {
277 ids.push_back(firstId + 1);
278 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800279 break;
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800280 case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_INITIATED:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800281 if (find(ids.begin(), ids.end(), firstId + 2) == ids.end()) {
282 ids.push_back(firstId + 2);
283 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800284 break;
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800285 case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_SUCCESS:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800286 if (find(ids.begin(), ids.end(), firstId + 3) == ids.end()) {
287 ids.push_back(firstId + 3);
288 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800289 break;
290 }
291 }
292
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800293 // If this event is a rollback event, the following fields are invalid and
294 // need to be replaced by the fields stored to disk.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800295 if (is_rollback) {
296 trainInfo->requiresStaging = trainInfoOnDisk.requiresStaging;
297 trainInfo->rollbackEnabled = trainInfoOnDisk.rollbackEnabled;
298 trainInfo->requiresLowLatencyMonitor = trainInfoOnDisk.requiresLowLatencyMonitor;
299 }
300
301 StorageManager::writeTrainInfo(*trainInfo);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800302}
303
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800304void StatsLogProcessor::onWatchdogRollbackOccurredLocked(LogEvent* event) {
305 pid_t pid = event->GetPid();
306 uid_t uid = event->GetUid();
307 if (!checkPermissionForIds(kPermissionDump, pid, uid) ||
308 !checkPermissionForIds(kPermissionUsage, pid, uid)) {
309 return;
310 }
311 // The Get* functions don't modify the status on success, they only write in
312 // failure statuses, so we can use one status variable for all calls then
313 // check if it is no longer NO_ERROR.
314 status_t err = NO_ERROR;
315 int32_t rollbackType = int32_t(event->GetInt(1 /*rollback type field id*/, &err));
316 string packageName = string(event->GetString(2 /*package name field id*/, &err));
317
318 if (err != NO_ERROR) {
319 ALOGE("Failed to parse fields in watchdog rollback occurred log event");
320 return;
321 }
322
323 vector<int64_t> experimentIds =
324 processWatchdogRollbackOccurred(rollbackType, packageName);
325 vector<uint8_t> experimentIdProto;
326 writeExperimentIdsToProto(experimentIds, &experimentIdProto);
327
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800328 event->updateValue(6 /*experiment ids field id*/, experimentIdProto, STORAGE);
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800329}
330
331vector<int64_t> StatsLogProcessor::processWatchdogRollbackOccurred(const int32_t rollbackTypeIn,
332 const string& packageNameIn) {
333 // If the package name is empty, we can't attribute it to any train, so
334 // return early.
335 if (packageNameIn.empty()) {
336 return vector<int64_t>();
337 }
338 bool readTrainInfoSuccess = false;
339 InstallTrainInfo trainInfoOnDisk;
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800340 // We use the package name of the event as the train name.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800341 readTrainInfoSuccess = StorageManager::readTrainInfo(packageNameIn, trainInfoOnDisk);
342
343 if (!readTrainInfoSuccess) {
344 return vector<int64_t>();
345 }
346
347 if (trainInfoOnDisk.experimentIds.empty()) {
348 return vector<int64_t>();
349 }
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800350
351 int64_t firstId = trainInfoOnDisk.experimentIds[0];
352 auto& ids = trainInfoOnDisk.experimentIds;
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800353 switch (rollbackTypeIn) {
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800354 case android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800355 if (find(ids.begin(), ids.end(), firstId + 4) == ids.end()) {
356 ids.push_back(firstId + 4);
357 }
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800358 StorageManager::writeTrainInfo(trainInfoOnDisk);
359 break;
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800360 case android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800361 if (find(ids.begin(), ids.end(), firstId + 5) == ids.end()) {
362 ids.push_back(firstId + 5);
363 }
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800364 StorageManager::writeTrainInfo(trainInfoOnDisk);
365 break;
366 }
367
368 return trainInfoOnDisk.experimentIds;
369}
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800370
Yangster-mac892f3d32018-05-02 14:16:48 -0700371void StatsLogProcessor::resetConfigs() {
372 std::lock_guard<std::mutex> lock(mMetricsMutex);
373 resetConfigsLocked(getElapsedRealtimeNs());
374}
375
376void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs) {
377 std::vector<ConfigKey> configKeys;
378 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
379 configKeys.push_back(it->first);
380 }
381 resetConfigsLocked(timestampNs, configKeys);
382}
383
Yao Chen3ff3a492018-08-06 16:17:37 -0700384void StatsLogProcessor::OnLogEvent(LogEvent* event) {
Tej Singh480392f2019-10-23 15:53:46 -0700385 OnLogEvent(event, getElapsedRealtimeNs());
386}
387
388void StatsLogProcessor::OnLogEvent(LogEvent* event, int64_t elapsedRealtimeNs) {
Yangster-macd40053e2018-01-09 16:29:22 -0800389 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen876889c2018-05-02 11:16:16 -0700390
Ruchir Rastogi07f7adb2020-04-16 17:46:12 -0700391 // Tell StatsdStats about new event
392 const int64_t eventElapsedTimeNs = event->GetElapsedTimestampNs();
393 int atomId = event->GetTagId();
394 StatsdStats::getInstance().noteAtomLogged(atomId, eventElapsedTimeNs / NS_PER_SEC);
395 if (!event->isValid()) {
396 StatsdStats::getInstance().noteAtomError(atomId);
397 return;
398 }
399
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800400 // Hard-coded logic to update train info on disk and fill in any information
401 // this log event may be missing.
Ruchir Rastogi07f7adb2020-04-16 17:46:12 -0700402 if (atomId == android::os::statsd::util::BINARY_PUSH_STATE_CHANGED) {
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800403 onBinaryPushStateChangedEventLocked(event);
404 }
405
406 // Hard-coded logic to update experiment ids on disk for certain rollback
407 // types and fill the rollback atom with experiment ids
Ruchir Rastogi07f7adb2020-04-16 17:46:12 -0700408 if (atomId == android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED) {
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800409 onWatchdogRollbackOccurredLocked(event);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800410 }
411
Yao Chen876889c2018-05-02 11:16:16 -0700412#ifdef VERY_VERBOSE_PRINTING
413 if (mPrintAllLogs) {
414 ALOGI("%s", event->ToString().c_str());
415 }
416#endif
Tej Singh480392f2019-10-23 15:53:46 -0700417 resetIfConfigTtlExpiredLocked(eventElapsedTimeNs);
Yangster-macb142cc82018-03-30 15:22:08 -0700418
David Chen21582962017-11-01 17:32:46 -0700419 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800420 // The field numbers need to be currently updated by hand with atoms.proto
Ruchir Rastogi07f7adb2020-04-16 17:46:12 -0700421 if (atomId == android::os::statsd::util::ISOLATED_UID_CHANGED) {
Yangster-macd40053e2018-01-09 16:29:22 -0800422 onIsolatedUidChangedEventLocked(*event);
Muhammad Qureshi7ce22562020-05-12 01:08:00 -0700423 } else {
424 // Map the isolated uid to host uid if necessary.
425 mapIsolatedUidToHostUidIfNecessaryLocked(event);
David Chencfc311d2018-01-23 17:55:54 -0800426 }
427
tsaichristined21aacf2019-10-07 14:47:38 -0700428 StateManager::getInstance().onLogEvent(*event);
429
David Chencfc311d2018-01-23 17:55:54 -0800430 if (mMetricsManagers.empty()) {
431 return;
432 }
433
Yangster-macb142cc82018-03-30 15:22:08 -0700434 int64_t curTimeSec = getElapsedRealtimeSec();
Yangster-mac330af582018-02-08 15:24:38 -0800435 if (curTimeSec - mLastPullerCacheClearTimeSec > StatsdStats::kPullerCacheClearIntervalSec) {
Chenjie Yue2219202018-06-08 10:07:51 -0700436 mPullerManager->ClearPullerCacheIfNecessary(curTimeSec * NS_PER_SEC);
Yangster-mac330af582018-02-08 15:24:38 -0800437 mLastPullerCacheClearTimeSec = curTimeSec;
Chenjie Yufa22d652018-02-05 14:37:48 -0800438 }
439
Tej Singh6ede28b2019-01-29 17:06:54 -0800440 std::unordered_set<int> uidsWithActiveConfigsChanged;
441 std::unordered_map<int, std::vector<int64_t>> activeConfigsPerUid;
Yangster-macd40053e2018-01-09 16:29:22 -0800442 // pass the event to metrics managers.
443 for (auto& pair : mMetricsManagers) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800444 int uid = pair.first.GetUid();
445 int64_t configId = pair.first.GetId();
446 bool isPrevActive = pair.second->isActive();
Yangster-macd40053e2018-01-09 16:29:22 -0800447 pair.second->onLogEvent(*event);
Tej Singh6ede28b2019-01-29 17:06:54 -0800448 bool isCurActive = pair.second->isActive();
449 // Map all active configs by uid.
450 if (isCurActive) {
451 auto activeConfigs = activeConfigsPerUid.find(uid);
452 if (activeConfigs != activeConfigsPerUid.end()) {
453 activeConfigs->second.push_back(configId);
454 } else {
455 vector<int64_t> newActiveConfigs;
456 newActiveConfigs.push_back(configId);
457 activeConfigsPerUid[uid] = newActiveConfigs;
458 }
459 }
460 // The activation state of this config changed.
461 if (isPrevActive != isCurActive) {
462 VLOG("Active status changed for uid %d", uid);
463 uidsWithActiveConfigsChanged.insert(uid);
464 StatsdStats::getInstance().noteActiveStatusChanged(pair.first, isCurActive);
465 }
Tej Singh480392f2019-10-23 15:53:46 -0700466 flushIfNecessaryLocked(pair.first, *(pair.second));
David Chen21582962017-11-01 17:32:46 -0700467 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800468
Tej Singh480392f2019-10-23 15:53:46 -0700469 // Don't use the event timestamp for the guardrail.
Tej Singh6ede28b2019-01-29 17:06:54 -0800470 for (int uid : uidsWithActiveConfigsChanged) {
471 // Send broadcast so that receivers can pull data.
472 auto lastBroadcastTime = mLastActivationBroadcastTimes.find(uid);
473 if (lastBroadcastTime != mLastActivationBroadcastTimes.end()) {
Tej Singh480392f2019-10-23 15:53:46 -0700474 if (elapsedRealtimeNs - lastBroadcastTime->second <
475 StatsdStats::kMinActivationBroadcastPeriodNs) {
Tej Singh16ca28f2019-06-24 11:58:23 -0700476 StatsdStats::getInstance().noteActivationBroadcastGuardrailHit(uid);
Tej Singh6ede28b2019-01-29 17:06:54 -0800477 VLOG("StatsD would've sent an activation broadcast but the rate limit stopped us.");
478 return;
479 }
480 }
481 auto activeConfigs = activeConfigsPerUid.find(uid);
482 if (activeConfigs != activeConfigsPerUid.end()) {
483 if (mSendActivationBroadcast(uid, activeConfigs->second)) {
484 VLOG("StatsD sent activation notice for uid %d", uid);
Tej Singh480392f2019-10-23 15:53:46 -0700485 mLastActivationBroadcastTimes[uid] = elapsedRealtimeNs;
Tej Singh6ede28b2019-01-29 17:06:54 -0800486 }
487 } else {
488 std::vector<int64_t> emptyActiveConfigs;
489 if (mSendActivationBroadcast(uid, emptyActiveConfigs)) {
490 VLOG("StatsD sent EMPTY activation notice for uid %d", uid);
Tej Singh480392f2019-10-23 15:53:46 -0700491 mLastActivationBroadcastTimes[uid] = elapsedRealtimeNs;
Tej Singh6ede28b2019-01-29 17:06:54 -0800492 }
493 }
494 }
495}
496
497void StatsLogProcessor::GetActiveConfigs(const int uid, vector<int64_t>& outActiveConfigs) {
498 std::lock_guard<std::mutex> lock(mMetricsMutex);
499 GetActiveConfigsLocked(uid, outActiveConfigs);
500}
501
502void StatsLogProcessor::GetActiveConfigsLocked(const int uid, vector<int64_t>& outActiveConfigs) {
503 outActiveConfigs.clear();
504 for (auto& pair : mMetricsManagers) {
505 if (pair.first.GetUid() == uid && pair.second->isActive()) {
506 outActiveConfigs.push_back(pair.first.GetId());
507 }
508 }
Yao Chenab273e22017-09-06 12:53:50 -0700509}
510
Yangster-macc04feba2018-04-02 14:37:33 -0700511void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
512 const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800513 std::lock_guard<std::mutex> lock(mMetricsMutex);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000514 WriteDataToDiskLocked(key, timestampNs, CONFIG_UPDATED, NO_TIME_CONSTRAINTS);
Yangster-macb142cc82018-03-30 15:22:08 -0700515 OnConfigUpdatedLocked(timestampNs, key, config);
516}
517
518void StatsLogProcessor::OnConfigUpdatedLocked(
519 const int64_t timestampNs, const ConfigKey& key, const StatsdConfig& config) {
Tej Singh484524a2018-02-01 15:10:05 -0800520 VLOG("Updated configuration for key %s", key.ToString().c_str());
Yangster-mac932ecec2018-02-01 10:23:52 -0800521 sp<MetricsManager> newMetricsManager =
Chenjie Yue2219202018-06-08 10:07:51 -0700522 new MetricsManager(key, config, mTimeBaseNs, timestampNs, mUidMap, mPullerManager,
523 mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
Yao Chencaf339d2017-10-06 16:01:10 -0700524 if (newMetricsManager->isConfigValid()) {
Tej Singh3be093b2020-03-04 20:08:38 -0800525 newMetricsManager->init();
David Chend6896892017-10-25 11:49:03 -0700526 mUidMap->OnConfigUpdated(key);
Yangster-macb142cc82018-03-30 15:22:08 -0700527 newMetricsManager->refreshTtl(timestampNs);
Yao Chend10f7b12017-12-18 12:53:50 -0800528 mMetricsManagers[key] = newMetricsManager;
Yao Chenb3561512017-11-21 18:07:17 -0800529 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700530 } else {
531 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800532 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700533 }
yro00698da2017-09-15 10:06:40 -0700534}
Bookatz906a35c2017-09-20 15:26:44 -0700535
Yangster7c334a12017-11-22 14:24:24 -0800536size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800537 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700538 auto it = mMetricsManagers.find(key);
539 if (it == mMetricsManagers.end()) {
540 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800541 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700542 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800543 return it->second->byteSize();
544}
545
Yao Chena80e5c02018-09-04 13:55:29 -0700546void StatsLogProcessor::dumpStates(int out, bool verbose) {
Yao Chen884c8c12018-01-26 10:36:25 -0800547 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chena80e5c02018-09-04 13:55:29 -0700548 FILE* fout = fdopen(out, "w");
549 if (fout == NULL) {
550 return;
Yao Chen884c8c12018-01-26 10:36:25 -0800551 }
Yao Chena80e5c02018-09-04 13:55:29 -0700552 fprintf(fout, "MetricsManager count: %lu\n", (unsigned long)mMetricsManagers.size());
553 for (auto metricsManager : mMetricsManagers) {
554 metricsManager.second->dumpStates(fout, verbose);
555 }
556
557 fclose(fout);
Yao Chen884c8c12018-01-26 10:36:25 -0800558}
559
yro4beccbe2018-03-15 19:42:05 -0700560/*
Bookatz9cc7b662018-11-06 10:39:21 -0800561 * onDumpReport dumps serialized ConfigMetricsReportList into proto.
yro4beccbe2018-03-15 19:42:05 -0700562 */
Yangster-macb142cc82018-03-30 15:22:08 -0700563void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700564 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700565 const bool erase_data,
Chenjie Yue36018b2018-04-16 15:18:30 -0700566 const DumpReportReason dumpReportReason,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000567 const DumpLatency dumpLatency,
Bookatzff71cad2018-09-20 17:17:49 -0700568 ProtoOutputStream* proto) {
Yangster-macb0d06282018-01-05 15:44:07 -0800569 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800570
yro947fbce2017-11-15 22:50:23 -0800571 // Start of ConfigKey.
Bookatzff71cad2018-09-20 17:17:49 -0700572 uint64_t configKeyToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
573 proto->write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
574 proto->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
575 proto->end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800576 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800577
Yao Chen9a43b4f2019-04-10 10:43:20 -0700578 bool keepFile = false;
579 auto it = mMetricsManagers.find(key);
580 if (it != mMetricsManagers.end() && it->second->shouldPersistLocalHistory()) {
581 keepFile = true;
582 }
583
yro947fbce2017-11-15 22:50:23 -0800584 // Then, check stats-data directory to see there's any file containing
585 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
Yao Chen9a43b4f2019-04-10 10:43:20 -0700586 StorageManager::appendConfigMetricsReport(
587 key, proto, erase_data && !keepFile /* should remove file after appending it */,
588 dumpReportReason == ADB_DUMP /*if caller is adb*/);
yro947fbce2017-11-15 22:50:23 -0800589
Yangster-mace68f3a52018-04-04 00:01:43 -0700590 if (it != mMetricsManagers.end()) {
591 // This allows another broadcast to be sent within the rate-limit period if we get close to
592 // filling the buffer again soon.
593 mLastBroadcastTimes.erase(key);
594
Yao Chen9a43b4f2019-04-10 10:43:20 -0700595 vector<uint8_t> buffer;
596 onConfigMetricsReportLocked(key, dumpTimeStampNs, include_current_partial_bucket,
597 erase_data, dumpReportReason, dumpLatency,
598 false /* is this data going to be saved on disk */, &buffer);
599 proto->write(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS,
600 reinterpret_cast<char*>(buffer.data()), buffer.size());
Yangster-mace68f3a52018-04-04 00:01:43 -0700601 } else {
602 ALOGW("Config source %s does not exist", key.ToString().c_str());
603 }
Bookatzff71cad2018-09-20 17:17:49 -0700604}
605
606/*
607 * onDumpReport dumps serialized ConfigMetricsReportList into outData.
608 */
609void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
610 const bool include_current_partial_bucket,
611 const bool erase_data,
612 const DumpReportReason dumpReportReason,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000613 const DumpLatency dumpLatency,
Bookatzff71cad2018-09-20 17:17:49 -0700614 vector<uint8_t>* outData) {
615 ProtoOutputStream proto;
616 onDumpReport(key, dumpTimeStampNs, include_current_partial_bucket, erase_data,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000617 dumpReportReason, dumpLatency, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700618
David Chen1d7b0cd2017-11-15 14:20:04 -0800619 if (outData != nullptr) {
Yao Chen9a43b4f2019-04-10 10:43:20 -0700620 flushProtoToBuffer(proto, outData);
621 VLOG("output data size %zu", outData->size());
yro17adac92017-11-08 23:16:29 -0800622 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800623
Yangster-mace68f3a52018-04-04 00:01:43 -0700624 StatsdStats::getInstance().noteMetricsReportSent(key, proto.size());
Yao Chen729093d2017-10-16 10:33:26 -0700625}
626
yro4beccbe2018-03-15 19:42:05 -0700627/*
628 * onConfigMetricsReportLocked dumps serialized ConfigMetricsReport into outData.
629 */
Yao Chen9a43b4f2019-04-10 10:43:20 -0700630void StatsLogProcessor::onConfigMetricsReportLocked(
631 const ConfigKey& key, const int64_t dumpTimeStampNs,
632 const bool include_current_partial_bucket, const bool erase_data,
633 const DumpReportReason dumpReportReason, const DumpLatency dumpLatency,
634 const bool dataSavedOnDisk, vector<uint8_t>* buffer) {
yro4beccbe2018-03-15 19:42:05 -0700635 // We already checked whether key exists in mMetricsManagers in
636 // WriteDataToDisk.
637 auto it = mMetricsManagers.find(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700638 if (it == mMetricsManagers.end()) {
639 return;
640 }
yro4beccbe2018-03-15 19:42:05 -0700641 int64_t lastReportTimeNs = it->second->getLastReportTimeNs();
642 int64_t lastReportWallClockNs = it->second->getLastReportWallClockNs();
643
Yangster-mac9def8e32018-04-17 13:55:51 -0700644 std::set<string> str_set;
645
Yao Chen9a43b4f2019-04-10 10:43:20 -0700646 ProtoOutputStream tempProto;
yro4beccbe2018-03-15 19:42:05 -0700647 // First, fill in ConfigMetricsReport using current data on memory, which
648 // starts from filling in StatsLogReport's.
Yao Chen9a43b4f2019-04-10 10:43:20 -0700649 it->second->onDumpReport(dumpTimeStampNs, include_current_partial_bucket, erase_data,
650 dumpLatency, &str_set, &tempProto);
yro4beccbe2018-03-15 19:42:05 -0700651
David Chen9e6dbbd2018-05-07 17:52:29 -0700652 // Fill in UidMap if there is at least one metric to report.
653 // This skips the uid map if it's an empty config.
654 if (it->second->getNumMetrics() > 0) {
Yao Chen9a43b4f2019-04-10 10:43:20 -0700655 uint64_t uidMapToken = tempProto.start(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP);
dwchen730403e2018-10-29 11:41:56 -0700656 mUidMap->appendUidMap(
657 dumpTimeStampNs, key, it->second->hashStringInReport() ? &str_set : nullptr,
Yao Chen9a43b4f2019-04-10 10:43:20 -0700658 it->second->versionStringsInReport(), it->second->installerInReport(), &tempProto);
659 tempProto.end(uidMapToken);
David Chen9e6dbbd2018-05-07 17:52:29 -0700660 }
yro4beccbe2018-03-15 19:42:05 -0700661
662 // Fill in the timestamps.
Yao Chen9a43b4f2019-04-10 10:43:20 -0700663 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_ELAPSED_NANOS,
664 (long long)lastReportTimeNs);
665 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS,
666 (long long)dumpTimeStampNs);
667 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS,
668 (long long)lastReportWallClockNs);
669 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS,
670 (long long)getWallClockNs());
Chenjie Yue36018b2018-04-16 15:18:30 -0700671 // Dump report reason
Yao Chen9a43b4f2019-04-10 10:43:20 -0700672 tempProto.write(FIELD_TYPE_INT32 | FIELD_ID_DUMP_REPORT_REASON, dumpReportReason);
Yangster-mac9def8e32018-04-17 13:55:51 -0700673
David Chen56ae0d92018-05-11 16:00:22 -0700674 for (const auto& str : str_set) {
Yao Chen9a43b4f2019-04-10 10:43:20 -0700675 tempProto.write(FIELD_TYPE_STRING | FIELD_COUNT_REPEATED | FIELD_ID_STRINGS, str);
676 }
677
678 flushProtoToBuffer(tempProto, buffer);
679
680 // save buffer to disk if needed
681 if (erase_data && !dataSavedOnDisk && it->second->shouldPersistLocalHistory()) {
682 VLOG("save history to disk");
683 string file_name = StorageManager::getDataHistoryFileName((long)getWallClockSec(),
684 key.GetUid(), key.GetId());
685 StorageManager::writeFile(file_name.c_str(), buffer->data(), buffer->size());
Yangster-mac9def8e32018-04-17 13:55:51 -0700686 }
Yangster-macb142cc82018-03-30 15:22:08 -0700687}
yro4beccbe2018-03-15 19:42:05 -0700688
Yao Chen163d2602018-04-10 10:39:53 -0700689void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs,
690 const std::vector<ConfigKey>& configs) {
691 for (const auto& key : configs) {
Yangster-macb142cc82018-03-30 15:22:08 -0700692 StatsdConfig config;
693 if (StorageManager::readConfigFromDisk(key, &config)) {
694 OnConfigUpdatedLocked(timestampNs, key, config);
695 StatsdStats::getInstance().noteConfigReset(key);
696 } else {
697 ALOGE("Failed to read backup config from disk for : %s", key.ToString().c_str());
698 auto it = mMetricsManagers.find(key);
699 if (it != mMetricsManagers.end()) {
700 it->second->refreshTtl(timestampNs);
701 }
702 }
703 }
yro4beccbe2018-03-15 19:42:05 -0700704}
705
Yao Chen163d2602018-04-10 10:39:53 -0700706void StatsLogProcessor::resetIfConfigTtlExpiredLocked(const int64_t timestampNs) {
707 std::vector<ConfigKey> configKeysTtlExpired;
708 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
709 if (it->second != nullptr && !it->second->isInTtl(timestampNs)) {
710 configKeysTtlExpired.push_back(it->first);
711 }
712 }
713 if (configKeysTtlExpired.size() > 0) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000714 WriteDataToDiskLocked(CONFIG_RESET, NO_TIME_CONSTRAINTS);
Yao Chen163d2602018-04-10 10:39:53 -0700715 resetConfigsLocked(timestampNs, configKeysTtlExpired);
716 }
717}
718
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700719void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800720 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700721 auto it = mMetricsManagers.find(key);
722 if (it != mMetricsManagers.end()) {
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700723 WriteDataToDiskLocked(key, getElapsedRealtimeNs(), CONFIG_REMOVED,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000724 NO_TIME_CONSTRAINTS);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700725 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700726 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700727 }
Yao Chenb3561512017-11-21 18:07:17 -0800728 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800729
David Chen1d7b0cd2017-11-15 14:20:04 -0800730 mLastBroadcastTimes.erase(key);
Chenjie Yufa22d652018-02-05 14:37:48 -0800731
Tej Singh6ede28b2019-01-29 17:06:54 -0800732 int uid = key.GetUid();
733 bool lastConfigForUid = true;
734 for (auto it : mMetricsManagers) {
735 if (it.first.GetUid() == uid) {
736 lastConfigForUid = false;
737 break;
738 }
739 }
740 if (lastConfigForUid) {
741 mLastActivationBroadcastTimes.erase(uid);
742 }
743
Chenjie Yufa22d652018-02-05 14:37:48 -0800744 if (mMetricsManagers.empty()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700745 mPullerManager->ForceClearPullerCache();
Chenjie Yufa22d652018-02-05 14:37:48 -0800746 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700747}
748
Tej Singh480392f2019-10-23 15:53:46 -0700749void StatsLogProcessor::flushIfNecessaryLocked(const ConfigKey& key,
750 MetricsManager& metricsManager) {
751 int64_t elapsedRealtimeNs = getElapsedRealtimeNs();
David Chend9269e22017-12-05 13:43:51 -0800752 auto lastCheckTime = mLastByteSizeTimes.find(key);
753 if (lastCheckTime != mLastByteSizeTimes.end()) {
Tej Singh480392f2019-10-23 15:53:46 -0700754 if (elapsedRealtimeNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
David Chend9269e22017-12-05 13:43:51 -0800755 return;
756 }
757 }
758
759 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
760 size_t totalBytes = metricsManager.byteSize();
Tej Singh480392f2019-10-23 15:53:46 -0700761 mLastByteSizeTimes[key] = elapsedRealtimeNs;
David Chen48944902018-05-03 10:29:11 -0700762 bool requestDump = false;
Tej Singh480392f2019-10-23 15:53:46 -0700763 if (totalBytes > StatsdStats::kMaxMetricsBytesPerConfig) {
764 // Too late. We need to start clearing data.
765 metricsManager.dropData(elapsedRealtimeNs);
Chenjie Yuc3c30c02018-10-26 09:48:07 -0700766 StatsdStats::getInstance().noteDataDropped(key, totalBytes);
David Chen12942952017-12-04 14:28:43 -0800767 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chen48944902018-05-03 10:29:11 -0700768 } else if ((totalBytes > StatsdStats::kBytesPerConfigTriggerGetData) ||
769 (mOnDiskDataConfigs.find(key) != mOnDiskDataConfigs.end())) {
770 // Request to send a broadcast if:
771 // 1. in memory data > threshold OR
772 // 2. config has old data report on disk.
773 requestDump = true;
774 }
775
776 if (requestDump) {
David Chend9269e22017-12-05 13:43:51 -0800777 // Send broadcast so that receivers can pull data.
778 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
779 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
Tej Singh480392f2019-10-23 15:53:46 -0700780 if (elapsedRealtimeNs - lastBroadcastTime->second <
781 StatsdStats::kMinBroadcastPeriodNs) {
David Chend9269e22017-12-05 13:43:51 -0800782 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800783 return;
784 }
785 }
David Chen48944902018-05-03 10:29:11 -0700786 if (mSendBroadcast(key)) {
787 mOnDiskDataConfigs.erase(key);
788 VLOG("StatsD triggered data fetch for %s", key.ToString().c_str());
Tej Singh480392f2019-10-23 15:53:46 -0700789 mLastBroadcastTimes[key] = elapsedRealtimeNs;
David Chen48944902018-05-03 10:29:11 -0700790 StatsdStats::getInstance().noteBroadcastSent(key);
791 }
yro31eb67b2017-10-24 13:33:21 -0700792 }
793}
794
Chenjie Yue36018b2018-04-16 15:18:30 -0700795void StatsLogProcessor::WriteDataToDiskLocked(const ConfigKey& key,
Yangster-mac892f3d32018-05-02 14:16:48 -0700796 const int64_t timestampNs,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000797 const DumpReportReason dumpReportReason,
798 const DumpLatency dumpLatency) {
yro028091c2018-05-09 16:03:27 -0700799 if (mMetricsManagers.find(key) == mMetricsManagers.end() ||
800 !mMetricsManagers.find(key)->second->shouldWriteToDisk()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700801 return;
802 }
Yao Chen9a43b4f2019-04-10 10:43:20 -0700803 vector<uint8_t> buffer;
David Chen56ae0d92018-05-11 16:00:22 -0700804 onConfigMetricsReportLocked(key, timestampNs, true /* include_current_partial_bucket*/,
Yao Chen9a43b4f2019-04-10 10:43:20 -0700805 true /* erase_data */, dumpReportReason, dumpLatency, true,
806 &buffer);
807 string file_name =
808 StorageManager::getDataFileName((long)getWallClockSec(), key.GetUid(), key.GetId());
809 StorageManager::writeFile(file_name.c_str(), buffer.data(), buffer.size());
810
David Chen48944902018-05-03 10:29:11 -0700811 // We were able to write the ConfigMetricsReport to disk, so we should trigger collection ASAP.
812 mOnDiskDataConfigs.insert(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700813}
814
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700815void StatsLogProcessor::SaveActiveConfigsToDisk(int64_t currentTimeNs) {
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800816 std::lock_guard<std::mutex> lock(mMetricsMutex);
jianjin996f40d2019-03-29 13:53:48 -0700817 const int64_t timeNs = getElapsedRealtimeNs();
818 // Do not write to disk if we already have in the last few seconds.
jianjin996f40d2019-03-29 13:53:48 -0700819 if (static_cast<unsigned long long> (timeNs) <
820 mLastActiveMetricsWriteNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
821 ALOGI("Statsd skipping writing active metrics to disk. Already wrote data in last %d seconds",
822 WRITE_DATA_COOL_DOWN_SEC);
823 return;
824 }
825 mLastActiveMetricsWriteNs = timeNs;
826
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800827 ProtoOutputStream proto;
Tej Singhf53d4452019-05-09 18:17:59 -0700828 WriteActiveConfigsToProtoOutputStreamLocked(currentTimeNs, DEVICE_SHUTDOWN, &proto);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800829
830 string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
831 StorageManager::deleteFile(file_name.c_str());
832 android::base::unique_fd fd(
833 open(file_name.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
834 if (fd == -1) {
835 ALOGE("Attempt to write %s but failed", file_name.c_str());
836 return;
837 }
838 proto.flush(fd.get());
839}
840
Jeffrey Huangb8f54032020-03-23 13:42:42 -0700841void StatsLogProcessor::SaveMetadataToDisk(int64_t currentWallClockTimeNs,
842 int64_t systemElapsedTimeNs) {
843 std::lock_guard<std::mutex> lock(mMetricsMutex);
844 // Do not write to disk if we already have in the last few seconds.
845 if (static_cast<unsigned long long> (systemElapsedTimeNs) <
846 mLastMetadataWriteNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
847 ALOGI("Statsd skipping writing metadata to disk. Already wrote data in last %d seconds",
848 WRITE_DATA_COOL_DOWN_SEC);
849 return;
850 }
851 mLastMetadataWriteNs = systemElapsedTimeNs;
852
853 metadata::StatsMetadataList metadataList;
854 WriteMetadataToProtoLocked(
855 currentWallClockTimeNs, systemElapsedTimeNs, &metadataList);
856
857 string file_name = StringPrintf("%s/metadata", STATS_METADATA_DIR);
858 StorageManager::deleteFile(file_name.c_str());
859
860 if (metadataList.stats_metadata_size() == 0) {
861 // Skip the write if we have nothing to write.
862 return;
863 }
864
865 std::string data;
866 metadataList.SerializeToString(&data);
867 StorageManager::writeFile(file_name.c_str(), data.c_str(), data.size());
868}
869
870void StatsLogProcessor::WriteMetadataToProto(int64_t currentWallClockTimeNs,
871 int64_t systemElapsedTimeNs,
872 metadata::StatsMetadataList* metadataList) {
873 std::lock_guard<std::mutex> lock(mMetricsMutex);
874 WriteMetadataToProtoLocked(currentWallClockTimeNs, systemElapsedTimeNs, metadataList);
875}
876
877void StatsLogProcessor::WriteMetadataToProtoLocked(int64_t currentWallClockTimeNs,
878 int64_t systemElapsedTimeNs,
879 metadata::StatsMetadataList* metadataList) {
880 for (const auto& pair : mMetricsManagers) {
881 const sp<MetricsManager>& metricsManager = pair.second;
882 metadata::StatsMetadata* statsMetadata = metadataList->add_stats_metadata();
883 bool metadataWritten = metricsManager->writeMetadataToProto(currentWallClockTimeNs,
884 systemElapsedTimeNs, statsMetadata);
885 if (!metadataWritten) {
886 metadataList->mutable_stats_metadata()->RemoveLast();
887 }
888 }
889}
890
Jeffrey Huang475677e2020-03-30 19:52:07 -0700891void StatsLogProcessor::LoadMetadataFromDisk(int64_t currentWallClockTimeNs,
892 int64_t systemElapsedTimeNs) {
893 std::lock_guard<std::mutex> lock(mMetricsMutex);
894 string file_name = StringPrintf("%s/metadata", STATS_METADATA_DIR);
895 int fd = open(file_name.c_str(), O_RDONLY | O_CLOEXEC);
896 if (-1 == fd) {
897 VLOG("Attempt to read %s but failed", file_name.c_str());
898 StorageManager::deleteFile(file_name.c_str());
899 return;
900 }
901 string content;
902 if (!android::base::ReadFdToString(fd, &content)) {
903 ALOGE("Attempt to read %s but failed", file_name.c_str());
904 close(fd);
905 StorageManager::deleteFile(file_name.c_str());
906 return;
907 }
908
909 close(fd);
910
911 metadata::StatsMetadataList statsMetadataList;
912 if (!statsMetadataList.ParseFromString(content)) {
913 ALOGE("Attempt to read %s but failed; failed to metadata", file_name.c_str());
914 StorageManager::deleteFile(file_name.c_str());
915 return;
916 }
917 SetMetadataStateLocked(statsMetadataList, currentWallClockTimeNs, systemElapsedTimeNs);
918 StorageManager::deleteFile(file_name.c_str());
919}
920
921void StatsLogProcessor::SetMetadataState(const metadata::StatsMetadataList& statsMetadataList,
922 int64_t currentWallClockTimeNs,
923 int64_t systemElapsedTimeNs) {
924 std::lock_guard<std::mutex> lock(mMetricsMutex);
925 SetMetadataStateLocked(statsMetadataList, currentWallClockTimeNs, systemElapsedTimeNs);
926}
927
928void StatsLogProcessor::SetMetadataStateLocked(
929 const metadata::StatsMetadataList& statsMetadataList,
930 int64_t currentWallClockTimeNs,
931 int64_t systemElapsedTimeNs) {
932 for (const metadata::StatsMetadata& metadata : statsMetadataList.stats_metadata()) {
933 ConfigKey key(metadata.config_key().uid(), metadata.config_key().config_id());
934 auto it = mMetricsManagers.find(key);
935 if (it == mMetricsManagers.end()) {
936 ALOGE("No config found for configKey %s", key.ToString().c_str());
937 continue;
938 }
939 VLOG("Setting metadata %s", key.ToString().c_str());
940 it->second->loadMetadata(metadata, currentWallClockTimeNs, systemElapsedTimeNs);
941 }
942 VLOG("Successfully loaded %d metadata.", statsMetadataList.stats_metadata_size());
943}
944
Tej Singhf53d4452019-05-09 18:17:59 -0700945void StatsLogProcessor::WriteActiveConfigsToProtoOutputStream(
946 int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto) {
947 std::lock_guard<std::mutex> lock(mMetricsMutex);
948 WriteActiveConfigsToProtoOutputStreamLocked(currentTimeNs, reason, proto);
949}
950
951void StatsLogProcessor::WriteActiveConfigsToProtoOutputStreamLocked(
952 int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto) {
953 for (const auto& pair : mMetricsManagers) {
954 const sp<MetricsManager>& metricsManager = pair.second;
955 uint64_t configToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
956 FIELD_ID_ACTIVE_CONFIG_LIST_CONFIG);
957 metricsManager->writeActiveConfigToProtoOutputStream(currentTimeNs, reason, proto);
958 proto->end(configToken);
959 }
960}
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700961void StatsLogProcessor::LoadActiveConfigsFromDisk() {
962 std::lock_guard<std::mutex> lock(mMetricsMutex);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800963 string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
964 int fd = open(file_name.c_str(), O_RDONLY | O_CLOEXEC);
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700965 if (-1 == fd) {
966 VLOG("Attempt to read %s but failed", file_name.c_str());
967 StorageManager::deleteFile(file_name.c_str());
968 return;
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800969 }
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700970 string content;
971 if (!android::base::ReadFdToString(fd, &content)) {
972 ALOGE("Attempt to read %s but failed", file_name.c_str());
973 close(fd);
974 StorageManager::deleteFile(file_name.c_str());
975 return;
976 }
977
978 close(fd);
979
980 ActiveConfigList activeConfigList;
981 if (!activeConfigList.ParseFromString(content)) {
982 ALOGE("Attempt to read %s but failed; failed to load active configs", file_name.c_str());
983 StorageManager::deleteFile(file_name.c_str());
984 return;
985 }
Tej Singhf53d4452019-05-09 18:17:59 -0700986 // Passing in mTimeBaseNs only works as long as we only load from disk is when statsd starts.
987 SetConfigsActiveStateLocked(activeConfigList, mTimeBaseNs);
988 StorageManager::deleteFile(file_name.c_str());
989}
990
991void StatsLogProcessor::SetConfigsActiveState(const ActiveConfigList& activeConfigList,
992 int64_t currentTimeNs) {
993 std::lock_guard<std::mutex> lock(mMetricsMutex);
994 SetConfigsActiveStateLocked(activeConfigList, currentTimeNs);
995}
996
997void StatsLogProcessor::SetConfigsActiveStateLocked(const ActiveConfigList& activeConfigList,
998 int64_t currentTimeNs) {
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700999 for (int i = 0; i < activeConfigList.config_size(); i++) {
1000 const auto& config = activeConfigList.config(i);
1001 ConfigKey key(config.uid(), config.id());
1002 auto it = mMetricsManagers.find(key);
1003 if (it == mMetricsManagers.end()) {
1004 ALOGE("No config found for config %s", key.ToString().c_str());
1005 continue;
1006 }
1007 VLOG("Setting active config %s", key.ToString().c_str());
Tej Singhf53d4452019-05-09 18:17:59 -07001008 it->second->loadActiveConfig(config, currentTimeNs);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001009 }
1010 VLOG("Successfully loaded %d active configs.", activeConfigList.config_size());
Chenjie Yuc7939cb2019-02-04 17:25:45 -08001011}
1012
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001013void StatsLogProcessor::WriteDataToDiskLocked(const DumpReportReason dumpReportReason,
1014 const DumpLatency dumpLatency) {
Yangster-mac892f3d32018-05-02 14:16:48 -07001015 const int64_t timeNs = getElapsedRealtimeNs();
Tej Singh42f9e062018-11-09 10:01:00 -08001016 // Do not write to disk if we already have in the last few seconds.
1017 // This is to avoid overwriting files that would have the same name if we
1018 // write twice in the same second.
1019 if (static_cast<unsigned long long> (timeNs) <
1020 mLastWriteTimeNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
1021 ALOGI("Statsd skipping writing data to disk. Already wrote data in last %d seconds",
1022 WRITE_DATA_COOL_DOWN_SEC);
1023 return;
1024 }
1025 mLastWriteTimeNs = timeNs;
Yangster-mace68f3a52018-04-04 00:01:43 -07001026 for (auto& pair : mMetricsManagers) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001027 WriteDataToDiskLocked(pair.first, timeNs, dumpReportReason, dumpLatency);
Yangster-mace68f3a52018-04-04 00:01:43 -07001028 }
1029}
1030
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001031void StatsLogProcessor::WriteDataToDisk(const DumpReportReason dumpReportReason,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001032 const DumpLatency dumpLatency) {
Yangster-macb0d06282018-01-05 15:44:07 -08001033 std::lock_guard<std::mutex> lock(mMetricsMutex);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001034 WriteDataToDiskLocked(dumpReportReason, dumpLatency);
yro947fbce2017-11-15 22:50:23 -08001035}
1036
Yangster-mac15f6bbc2018-04-08 11:52:26 -07001037void StatsLogProcessor::informPullAlarmFired(const int64_t timestampNs) {
Yangster6df5fcc2018-04-12 11:04:29 -07001038 std::lock_guard<std::mutex> lock(mMetricsMutex);
Chenjie Yue2219202018-06-08 10:07:51 -07001039 mPullerManager->OnAlarmFired(timestampNs);
Yangster-mac15f6bbc2018-04-08 11:52:26 -07001040}
1041
David Chend37bc232018-04-12 18:05:11 -07001042int64_t StatsLogProcessor::getLastReportTimeNs(const ConfigKey& key) {
1043 auto it = mMetricsManagers.find(key);
1044 if (it == mMetricsManagers.end()) {
1045 return 0;
1046 } else {
1047 return it->second->getLastReportTimeNs();
1048 }
1049}
1050
Tej Singh9ec159a2019-11-14 11:59:48 -08001051void StatsLogProcessor::notifyAppUpgrade(const int64_t& eventTimeNs, const string& apk,
1052 const int uid, const int64_t version) {
1053 std::lock_guard<std::mutex> lock(mMetricsMutex);
Tej Singhe678cb72020-04-14 16:23:30 -07001054 VLOG("Received app upgrade");
Muhammad Qureshi7ce22562020-05-12 01:08:00 -07001055 StateManager::getInstance().notifyAppChanged(apk, mUidMap);
Tej Singhe678cb72020-04-14 16:23:30 -07001056 for (const auto& it : mMetricsManagers) {
Tej Singh9ec159a2019-11-14 11:59:48 -08001057 it.second->notifyAppUpgrade(eventTimeNs, apk, uid, version);
1058 }
1059}
1060
1061void StatsLogProcessor::notifyAppRemoved(const int64_t& eventTimeNs, const string& apk,
1062 const int uid) {
1063 std::lock_guard<std::mutex> lock(mMetricsMutex);
Tej Singhe678cb72020-04-14 16:23:30 -07001064 VLOG("Received app removed");
Muhammad Qureshi7ce22562020-05-12 01:08:00 -07001065 StateManager::getInstance().notifyAppChanged(apk, mUidMap);
Tej Singhe678cb72020-04-14 16:23:30 -07001066 for (const auto& it : mMetricsManagers) {
Tej Singh9ec159a2019-11-14 11:59:48 -08001067 it.second->notifyAppRemoved(eventTimeNs, apk, uid);
1068 }
1069}
1070
1071void StatsLogProcessor::onUidMapReceived(const int64_t& eventTimeNs) {
1072 std::lock_guard<std::mutex> lock(mMetricsMutex);
Tej Singhe678cb72020-04-14 16:23:30 -07001073 VLOG("Received uid map");
Muhammad Qureshi7ce22562020-05-12 01:08:00 -07001074 StateManager::getInstance().updateLogSources(mUidMap);
Tej Singhe678cb72020-04-14 16:23:30 -07001075 for (const auto& it : mMetricsManagers) {
Tej Singh9ec159a2019-11-14 11:59:48 -08001076 it.second->onUidMapReceived(eventTimeNs);
1077 }
1078}
1079
Tej Singhe678cb72020-04-14 16:23:30 -07001080void StatsLogProcessor::onStatsdInitCompleted(const int64_t& elapsedTimeNs) {
1081 std::lock_guard<std::mutex> lock(mMetricsMutex);
1082 VLOG("Received boot completed signal");
1083 for (const auto& it : mMetricsManagers) {
1084 it.second->onStatsdInitCompleted(elapsedTimeNs);
1085 }
1086}
1087
David Chen48944902018-05-03 10:29:11 -07001088void StatsLogProcessor::noteOnDiskData(const ConfigKey& key) {
1089 std::lock_guard<std::mutex> lock(mMetricsMutex);
1090 mOnDiskDataConfigs.insert(key);
1091}
1092
Yao Chenef99c4f2017-09-22 16:26:54 -07001093} // namespace statsd
1094} // namespace os
1095} // namespace android