blob: fc7b9504f5901390459813259b6b53f4563b1df4 [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"
Muhammad Qureshic8e22662019-11-20 17:18:03 -080028#include "atoms_info.h"
Chenjie Yuc7939cb2019-02-04 17:25:45 -080029#include "external/StatsPullerManager.h"
Yao Chenb3561512017-11-21 18:07:17 -080030#include "guardrail/StatsdStats.h"
Jonathan Nguyena0e6de12020-01-28 18:33:55 -080031#include "logd/LogEvent.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070032#include "metrics/CountMetricProducer.h"
Jonathan Nguyena0e6de12020-01-28 18:33:55 -080033#include "StatsService.h"
tsaichristined21aacf2019-10-07 14:47:38 -070034#include "state/StateManager.h"
Chenjie Yuc7939cb2019-02-04 17:25:45 -080035#include "stats_log_util.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070036#include "stats_util.h"
Jeffrey Huang74fc4352020-03-06 15:18:33 -080037#include "statslog_statsd.h"
yro947fbce2017-11-15 22:50:23 -080038#include "storage/StorageManager.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070039
Yao Chenab273e22017-09-06 12:53:50 -070040using namespace android;
yro947fbce2017-11-15 22:50:23 -080041using android::base::StringPrintf;
yrob0378b02017-11-09 20:36:25 -080042using android::util::FIELD_COUNT_REPEATED;
yro17adac92017-11-08 23:16:29 -080043using android::util::FIELD_TYPE_BOOL;
44using android::util::FIELD_TYPE_FLOAT;
45using android::util::FIELD_TYPE_INT32;
46using android::util::FIELD_TYPE_INT64;
47using android::util::FIELD_TYPE_MESSAGE;
48using android::util::FIELD_TYPE_STRING;
49using android::util::ProtoOutputStream;
Yao Chen44cf27c2017-09-14 22:32:50 -070050using std::vector;
Bookatz906a35c2017-09-20 15:26:44 -070051
52namespace android {
53namespace os {
54namespace statsd {
Yao Chenab273e22017-09-06 12:53:50 -070055
yro947fbce2017-11-15 22:50:23 -080056// for ConfigMetricsReportList
yro17adac92017-11-08 23:16:29 -080057const int FIELD_ID_CONFIG_KEY = 1;
yro947fbce2017-11-15 22:50:23 -080058const int FIELD_ID_REPORTS = 2;
yro17adac92017-11-08 23:16:29 -080059// for ConfigKey
60const int FIELD_ID_UID = 1;
Yangster-mac94e197c2018-01-02 16:03:03 -080061const int FIELD_ID_ID = 2;
yro947fbce2017-11-15 22:50:23 -080062// for ConfigMetricsReport
Yao Chen4c959cb2018-02-13 13:27:48 -080063// const int FIELD_ID_METRICS = 1; // written in MetricsManager.cpp
yro947fbce2017-11-15 22:50:23 -080064const int FIELD_ID_UID_MAP = 2;
Yangster-mac330af582018-02-08 15:24:38 -080065const int FIELD_ID_LAST_REPORT_ELAPSED_NANOS = 3;
66const int FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS = 4;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -080067const int FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS = 5;
68const int FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS = 6;
Chenjie Yue36018b2018-04-16 15:18:30 -070069const int FIELD_ID_DUMP_REPORT_REASON = 8;
Yangster-mac9def8e32018-04-17 13:55:51 -070070const int FIELD_ID_STRINGS = 9;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -080071
Muhammad Qureshi844694b2019-04-05 10:10:40 -070072// for ActiveConfigList
73const int FIELD_ID_ACTIVE_CONFIG_LIST_CONFIG = 1;
Chenjie Yuc7939cb2019-02-04 17:25:45 -080074
Jonathan Nguyena0e6de12020-01-28 18:33:55 -080075// for permissions checks
76constexpr const char* kPermissionDump = "android.permission.DUMP";
77constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
78
Yangster-macb142cc82018-03-30 15:22:08 -070079#define NS_PER_HOUR 3600 * NS_PER_SEC
yro947fbce2017-11-15 22:50:23 -080080
Chenjie Yuc7939cb2019-02-04 17:25:45 -080081#define STATS_ACTIVE_METRIC_DIR "/data/misc/stats-active-metric"
Jeffrey Huangb8f54032020-03-23 13:42:42 -070082#define STATS_METADATA_DIR "/data/misc/stats-metadata"
yro17adac92017-11-08 23:16:29 -080083
Tej Singh42f9e062018-11-09 10:01:00 -080084// Cool down period for writing data to disk to avoid overwriting files.
85#define WRITE_DATA_COOL_DOWN_SEC 5
86
yro31eb67b2017-10-24 13:33:21 -070087StatsLogProcessor::StatsLogProcessor(const sp<UidMap>& uidMap,
Chenjie Yue2219202018-06-08 10:07:51 -070088 const sp<StatsPullerManager>& pullerManager,
Yangster-mac932ecec2018-02-01 10:23:52 -080089 const sp<AlarmMonitor>& anomalyAlarmMonitor,
90 const sp<AlarmMonitor>& periodicAlarmMonitor,
Yangster-mac15f6bbc2018-04-08 11:52:26 -070091 const int64_t timeBaseNs,
Tej Singh6ede28b2019-01-29 17:06:54 -080092 const std::function<bool(const ConfigKey&)>& sendBroadcast,
93 const std::function<bool(
94 const int&, const vector<int64_t>&)>& activateBroadcast)
Chenjie Yu85ed8382017-12-14 16:48:54 -080095 : mUidMap(uidMap),
Chenjie Yue2219202018-06-08 10:07:51 -070096 mPullerManager(pullerManager),
Yangster-mac932ecec2018-02-01 10:23:52 -080097 mAnomalyAlarmMonitor(anomalyAlarmMonitor),
98 mPeriodicAlarmMonitor(periodicAlarmMonitor),
Chenjie Yu85ed8382017-12-14 16:48:54 -080099 mSendBroadcast(sendBroadcast),
Tej Singh6ede28b2019-01-29 17:06:54 -0800100 mSendActivationBroadcast(activateBroadcast),
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700101 mTimeBaseNs(timeBaseNs),
Yao Chen163d2602018-04-10 10:39:53 -0700102 mLargestTimestampSeen(0),
103 mLastTimestampSeen(0) {
Chenjie Yue2219202018-06-08 10:07:51 -0700104 mPullerManager->ForceClearPullerCache();
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 {
Yao Chenc40a19d2018-03-15 16:48:25 -0700142 if (android::util::AtomsInfo::kAtomsWithAttributionChain.find(event->GetTagId()) !=
143 android::util::AtomsInfo::kAtomsWithAttributionChain.end()) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800144 for (auto& value : *(event->getMutableValues())) {
145 if (value.mField.getPosAtDepth(0) > kAttributionField) {
146 break;
147 }
148 if (isAttributionUidField(value)) {
149 const int hostUid = mUidMap->getHostUidOrSelf(value.mValue.int_value);
Ruchir Rastogiffa34f052020-04-04 15:30:11 -0700150 value.mValue.setInt(hostUid);
Yao Chen8a8d16c2018-02-08 14:50:40 -0800151 }
Yangster-macd40053e2018-01-09 16:29:22 -0800152 }
Yao Chenc40a19d2018-03-15 16:48:25 -0700153 } else {
Ruchir Rastogiffa34f052020-04-04 15:30:11 -0700154 int uidFieldIndex = event->getUidFieldIndex();
155 if (uidFieldIndex != -1) {
156 Value& value = (*event->getMutableValues())[uidFieldIndex].mValue;
157 const int hostUid = mUidMap->getHostUidOrSelf(value.int_value);
158 value.setInt(hostUid);
Yao Chenc40a19d2018-03-15 16:48:25 -0700159 }
Yao Chen312e8982017-12-05 15:29:03 -0800160 }
Yangster-macd40053e2018-01-09 16:29:22 -0800161}
162
163void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
164 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
165 bool is_create = event.GetBool(3, &err);
166 auto parent_uid = int(event.GetLong(1, &err2));
167 auto isolated_uid = int(event.GetLong(2, &err3));
168 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
169 if (is_create) {
170 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
171 } else {
Bookatz3c648862018-05-25 13:32:43 -0700172 mUidMap->removeIsolatedUid(isolated_uid);
Yangster-macd40053e2018-01-09 16:29:22 -0800173 }
174 } else {
175 ALOGE("Failed to parse uid in the isolated uid change event.");
176 }
177}
178
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800179void StatsLogProcessor::onBinaryPushStateChangedEventLocked(LogEvent* event) {
180 pid_t pid = event->GetPid();
181 uid_t uid = event->GetUid();
182 if (!checkPermissionForIds(kPermissionDump, pid, uid) ||
183 !checkPermissionForIds(kPermissionUsage, pid, uid)) {
184 return;
185 }
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800186 // The Get* functions don't modify the status on success, they only write in
187 // failure statuses, so we can use one status variable for all calls then
188 // check if it is no longer NO_ERROR.
189 status_t err = NO_ERROR;
190 InstallTrainInfo trainInfo;
191 trainInfo.trainName = string(event->GetString(1 /*train name field id*/, &err));
192 trainInfo.trainVersionCode = event->GetLong(2 /*train version field id*/, &err);
193 trainInfo.requiresStaging = event->GetBool(3 /*requires staging field id*/, &err);
194 trainInfo.rollbackEnabled = event->GetBool(4 /*rollback enabled field id*/, &err);
195 trainInfo.requiresLowLatencyMonitor =
196 event->GetBool(5 /*requires low latency monitor field id*/, &err);
197 trainInfo.status = int32_t(event->GetLong(6 /*state field id*/, &err));
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800198 std::vector<uint8_t> trainExperimentIdBytes =
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800199 event->GetStorage(7 /*experiment ids field id*/, &err);
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800200 bool is_rollback = event->GetBool(10 /*is rollback field id*/, &err);
201
202 if (err != NO_ERROR) {
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800203 ALOGE("Failed to parse fields in binary push state changed log event");
204 return;
205 }
206 ExperimentIds trainExperimentIds;
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800207 if (!trainExperimentIds.ParseFromArray(trainExperimentIdBytes.data(),
208 trainExperimentIdBytes.size())) {
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800209 ALOGE("Failed to parse experimentids in binary push state changed.");
210 return;
211 }
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800212 trainInfo.experimentIds = {trainExperimentIds.experiment_id().begin(),
213 trainExperimentIds.experiment_id().end()};
214
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800215 // Update the train info on disk and get any data the logevent is missing.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800216 getAndUpdateTrainInfoOnDisk(is_rollback, &trainInfo);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800217
218 std::vector<uint8_t> trainExperimentIdProto;
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800219 writeExperimentIdsToProto(trainInfo.experimentIds, &trainExperimentIdProto);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800220 int32_t userId = multiuser_get_user_id(uid);
221
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800222 event->updateValue(2 /*train version field id*/, trainInfo.trainVersionCode, LONG);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800223 event->updateValue(7 /*experiment ids field id*/, trainExperimentIdProto, STORAGE);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800224 event->updateValue(8 /*user id field id*/, userId, INT);
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800225
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800226 // If this event is a rollback event, then the following bits in the event
227 // are invalid and we will need to update them with the values we pulled
228 // from disk.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800229 if (is_rollback) {
230 int bit = trainInfo.requiresStaging ? 1 : 0;
231 event->updateValue(3 /*requires staging field id*/, bit, INT);
232 bit = trainInfo.rollbackEnabled ? 1 : 0;
233 event->updateValue(4 /*rollback enabled field id*/, bit, INT);
234 bit = trainInfo.requiresLowLatencyMonitor ? 1 : 0;
235 event->updateValue(5 /*requires low latency monitor field id*/, bit, INT);
236 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800237}
238
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800239void StatsLogProcessor::getAndUpdateTrainInfoOnDisk(bool is_rollback,
240 InstallTrainInfo* trainInfo) {
241 // If the train name is empty, we don't know which train to attribute the
242 // event to, so return early.
243 if (trainInfo->trainName.empty()) {
244 return;
245 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800246 bool readTrainInfoSuccess = false;
247 InstallTrainInfo trainInfoOnDisk;
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800248 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfo->trainName, trainInfoOnDisk);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800249
250 bool resetExperimentIds = false;
251 if (readTrainInfoSuccess) {
252 // Keep the old train version if we received an empty version.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800253 if (trainInfo->trainVersionCode == -1) {
254 trainInfo->trainVersionCode = trainInfoOnDisk.trainVersionCode;
255 } else if (trainInfo->trainVersionCode != trainInfoOnDisk.trainVersionCode) {
256 // Reset experiment ids if we receive a new non-empty train version.
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800257 resetExperimentIds = true;
258 }
259
260 // Reset if we received a different experiment id.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800261 if (!trainInfo->experimentIds.empty() &&
262 (trainInfoOnDisk.experimentIds.empty() ||
263 trainInfo->experimentIds.at(0) != trainInfoOnDisk.experimentIds[0])) {
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800264 resetExperimentIds = true;
265 }
266 }
267
268 // Find the right experiment IDs
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800269 if ((!resetExperimentIds || is_rollback) && readTrainInfoSuccess) {
270 trainInfo->experimentIds = trainInfoOnDisk.experimentIds;
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800271 }
272
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800273 if (!trainInfo->experimentIds.empty()) {
274 int64_t firstId = trainInfo->experimentIds.at(0);
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800275 auto& ids = trainInfo->experimentIds;
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800276 switch (trainInfo->status) {
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800277 case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALL_SUCCESS:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800278 if (find(ids.begin(), ids.end(), firstId + 1) == ids.end()) {
279 ids.push_back(firstId + 1);
280 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800281 break;
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800282 case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_INITIATED:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800283 if (find(ids.begin(), ids.end(), firstId + 2) == ids.end()) {
284 ids.push_back(firstId + 2);
285 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800286 break;
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800287 case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_SUCCESS:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800288 if (find(ids.begin(), ids.end(), firstId + 3) == ids.end()) {
289 ids.push_back(firstId + 3);
290 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800291 break;
292 }
293 }
294
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800295 // If this event is a rollback event, the following fields are invalid and
296 // need to be replaced by the fields stored to disk.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800297 if (is_rollback) {
298 trainInfo->requiresStaging = trainInfoOnDisk.requiresStaging;
299 trainInfo->rollbackEnabled = trainInfoOnDisk.rollbackEnabled;
300 trainInfo->requiresLowLatencyMonitor = trainInfoOnDisk.requiresLowLatencyMonitor;
301 }
302
303 StorageManager::writeTrainInfo(*trainInfo);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800304}
305
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800306void StatsLogProcessor::onWatchdogRollbackOccurredLocked(LogEvent* event) {
307 pid_t pid = event->GetPid();
308 uid_t uid = event->GetUid();
309 if (!checkPermissionForIds(kPermissionDump, pid, uid) ||
310 !checkPermissionForIds(kPermissionUsage, pid, uid)) {
311 return;
312 }
313 // The Get* functions don't modify the status on success, they only write in
314 // failure statuses, so we can use one status variable for all calls then
315 // check if it is no longer NO_ERROR.
316 status_t err = NO_ERROR;
317 int32_t rollbackType = int32_t(event->GetInt(1 /*rollback type field id*/, &err));
318 string packageName = string(event->GetString(2 /*package name field id*/, &err));
319
320 if (err != NO_ERROR) {
321 ALOGE("Failed to parse fields in watchdog rollback occurred log event");
322 return;
323 }
324
325 vector<int64_t> experimentIds =
326 processWatchdogRollbackOccurred(rollbackType, packageName);
327 vector<uint8_t> experimentIdProto;
328 writeExperimentIdsToProto(experimentIds, &experimentIdProto);
329
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800330 event->updateValue(6 /*experiment ids field id*/, experimentIdProto, STORAGE);
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800331}
332
333vector<int64_t> StatsLogProcessor::processWatchdogRollbackOccurred(const int32_t rollbackTypeIn,
334 const string& packageNameIn) {
335 // If the package name is empty, we can't attribute it to any train, so
336 // return early.
337 if (packageNameIn.empty()) {
338 return vector<int64_t>();
339 }
340 bool readTrainInfoSuccess = false;
341 InstallTrainInfo trainInfoOnDisk;
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800342 // We use the package name of the event as the train name.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800343 readTrainInfoSuccess = StorageManager::readTrainInfo(packageNameIn, trainInfoOnDisk);
344
345 if (!readTrainInfoSuccess) {
346 return vector<int64_t>();
347 }
348
349 if (trainInfoOnDisk.experimentIds.empty()) {
350 return vector<int64_t>();
351 }
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800352
353 int64_t firstId = trainInfoOnDisk.experimentIds[0];
354 auto& ids = trainInfoOnDisk.experimentIds;
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800355 switch (rollbackTypeIn) {
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800356 case android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800357 if (find(ids.begin(), ids.end(), firstId + 4) == ids.end()) {
358 ids.push_back(firstId + 4);
359 }
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800360 StorageManager::writeTrainInfo(trainInfoOnDisk);
361 break;
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800362 case android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800363 if (find(ids.begin(), ids.end(), firstId + 5) == ids.end()) {
364 ids.push_back(firstId + 5);
365 }
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800366 StorageManager::writeTrainInfo(trainInfoOnDisk);
367 break;
368 }
369
370 return trainInfoOnDisk.experimentIds;
371}
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800372
Yangster-mac892f3d32018-05-02 14:16:48 -0700373void StatsLogProcessor::resetConfigs() {
374 std::lock_guard<std::mutex> lock(mMetricsMutex);
375 resetConfigsLocked(getElapsedRealtimeNs());
376}
377
378void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs) {
379 std::vector<ConfigKey> configKeys;
380 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
381 configKeys.push_back(it->first);
382 }
383 resetConfigsLocked(timestampNs, configKeys);
384}
385
Yao Chen3ff3a492018-08-06 16:17:37 -0700386void StatsLogProcessor::OnLogEvent(LogEvent* event) {
Tej Singh480392f2019-10-23 15:53:46 -0700387 OnLogEvent(event, getElapsedRealtimeNs());
388}
389
390void StatsLogProcessor::OnLogEvent(LogEvent* event, int64_t elapsedRealtimeNs) {
Yangster-macd40053e2018-01-09 16:29:22 -0800391 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen876889c2018-05-02 11:16:16 -0700392
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800393 // Hard-coded logic to update train info on disk and fill in any information
394 // this log event may be missing.
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800395 if (event->GetTagId() == android::os::statsd::util::BINARY_PUSH_STATE_CHANGED) {
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800396 onBinaryPushStateChangedEventLocked(event);
397 }
398
399 // Hard-coded logic to update experiment ids on disk for certain rollback
400 // types and fill the rollback atom with experiment ids
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800401 if (event->GetTagId() == android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED) {
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800402 onWatchdogRollbackOccurredLocked(event);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800403 }
404
Yao Chen876889c2018-05-02 11:16:16 -0700405#ifdef VERY_VERBOSE_PRINTING
406 if (mPrintAllLogs) {
407 ALOGI("%s", event->ToString().c_str());
408 }
409#endif
Tej Singh480392f2019-10-23 15:53:46 -0700410 const int64_t eventElapsedTimeNs = event->GetElapsedTimestampNs();
Yangster-macb8382a12018-04-04 10:39:12 -0700411
Tej Singh480392f2019-10-23 15:53:46 -0700412 resetIfConfigTtlExpiredLocked(eventElapsedTimeNs);
Yangster-macb142cc82018-03-30 15:22:08 -0700413
Yangster-macd40053e2018-01-09 16:29:22 -0800414 StatsdStats::getInstance().noteAtomLogged(
Yangster-mac330af582018-02-08 15:24:38 -0800415 event->GetTagId(), event->GetElapsedTimestampNs() / NS_PER_SEC);
Yangster-macd40053e2018-01-09 16:29:22 -0800416
David Chen21582962017-11-01 17:32:46 -0700417 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800418 // The field numbers need to be currently updated by hand with atoms.proto
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800419 if (event->GetTagId() == android::os::statsd::util::ISOLATED_UID_CHANGED) {
Yangster-macd40053e2018-01-09 16:29:22 -0800420 onIsolatedUidChangedEventLocked(*event);
David Chencfc311d2018-01-23 17:55:54 -0800421 }
422
tsaichristined21aacf2019-10-07 14:47:38 -0700423 StateManager::getInstance().onLogEvent(*event);
424
David Chencfc311d2018-01-23 17:55:54 -0800425 if (mMetricsManagers.empty()) {
426 return;
427 }
428
Yangster-macb142cc82018-03-30 15:22:08 -0700429 int64_t curTimeSec = getElapsedRealtimeSec();
Yangster-mac330af582018-02-08 15:24:38 -0800430 if (curTimeSec - mLastPullerCacheClearTimeSec > StatsdStats::kPullerCacheClearIntervalSec) {
Chenjie Yue2219202018-06-08 10:07:51 -0700431 mPullerManager->ClearPullerCacheIfNecessary(curTimeSec * NS_PER_SEC);
Yangster-mac330af582018-02-08 15:24:38 -0800432 mLastPullerCacheClearTimeSec = curTimeSec;
Chenjie Yufa22d652018-02-05 14:37:48 -0800433 }
434
Yangster-macb142cc82018-03-30 15:22:08 -0700435
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800436 if (event->GetTagId() != android::os::statsd::util::ISOLATED_UID_CHANGED) {
Yangster-macd40053e2018-01-09 16:29:22 -0800437 // Map the isolated uid to host uid if necessary.
438 mapIsolatedUidToHostUidIfNecessaryLocked(event);
439 }
440
Tej Singh6ede28b2019-01-29 17:06:54 -0800441 std::unordered_set<int> uidsWithActiveConfigsChanged;
442 std::unordered_map<int, std::vector<int64_t>> activeConfigsPerUid;
Yangster-macd40053e2018-01-09 16:29:22 -0800443 // pass the event to metrics managers.
444 for (auto& pair : mMetricsManagers) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800445 int uid = pair.first.GetUid();
446 int64_t configId = pair.first.GetId();
447 bool isPrevActive = pair.second->isActive();
Yangster-macd40053e2018-01-09 16:29:22 -0800448 pair.second->onLogEvent(*event);
Tej Singh6ede28b2019-01-29 17:06:54 -0800449 bool isCurActive = pair.second->isActive();
450 // Map all active configs by uid.
451 if (isCurActive) {
452 auto activeConfigs = activeConfigsPerUid.find(uid);
453 if (activeConfigs != activeConfigsPerUid.end()) {
454 activeConfigs->second.push_back(configId);
455 } else {
456 vector<int64_t> newActiveConfigs;
457 newActiveConfigs.push_back(configId);
458 activeConfigsPerUid[uid] = newActiveConfigs;
459 }
460 }
461 // The activation state of this config changed.
462 if (isPrevActive != isCurActive) {
463 VLOG("Active status changed for uid %d", uid);
464 uidsWithActiveConfigsChanged.insert(uid);
465 StatsdStats::getInstance().noteActiveStatusChanged(pair.first, isCurActive);
466 }
Tej Singh480392f2019-10-23 15:53:46 -0700467 flushIfNecessaryLocked(pair.first, *(pair.second));
David Chen21582962017-11-01 17:32:46 -0700468 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800469
Tej Singh480392f2019-10-23 15:53:46 -0700470 // Don't use the event timestamp for the guardrail.
Tej Singh6ede28b2019-01-29 17:06:54 -0800471 for (int uid : uidsWithActiveConfigsChanged) {
472 // Send broadcast so that receivers can pull data.
473 auto lastBroadcastTime = mLastActivationBroadcastTimes.find(uid);
474 if (lastBroadcastTime != mLastActivationBroadcastTimes.end()) {
Tej Singh480392f2019-10-23 15:53:46 -0700475 if (elapsedRealtimeNs - lastBroadcastTime->second <
476 StatsdStats::kMinActivationBroadcastPeriodNs) {
Tej Singh16ca28f2019-06-24 11:58:23 -0700477 StatsdStats::getInstance().noteActivationBroadcastGuardrailHit(uid);
Tej Singh6ede28b2019-01-29 17:06:54 -0800478 VLOG("StatsD would've sent an activation broadcast but the rate limit stopped us.");
479 return;
480 }
481 }
482 auto activeConfigs = activeConfigsPerUid.find(uid);
483 if (activeConfigs != activeConfigsPerUid.end()) {
484 if (mSendActivationBroadcast(uid, activeConfigs->second)) {
485 VLOG("StatsD sent activation notice for uid %d", uid);
Tej Singh480392f2019-10-23 15:53:46 -0700486 mLastActivationBroadcastTimes[uid] = elapsedRealtimeNs;
Tej Singh6ede28b2019-01-29 17:06:54 -0800487 }
488 } else {
489 std::vector<int64_t> emptyActiveConfigs;
490 if (mSendActivationBroadcast(uid, emptyActiveConfigs)) {
491 VLOG("StatsD sent EMPTY activation notice for uid %d", uid);
Tej Singh480392f2019-10-23 15:53:46 -0700492 mLastActivationBroadcastTimes[uid] = elapsedRealtimeNs;
Tej Singh6ede28b2019-01-29 17:06:54 -0800493 }
494 }
495 }
496}
497
498void StatsLogProcessor::GetActiveConfigs(const int uid, vector<int64_t>& outActiveConfigs) {
499 std::lock_guard<std::mutex> lock(mMetricsMutex);
500 GetActiveConfigsLocked(uid, outActiveConfigs);
501}
502
503void StatsLogProcessor::GetActiveConfigsLocked(const int uid, vector<int64_t>& outActiveConfigs) {
504 outActiveConfigs.clear();
505 for (auto& pair : mMetricsManagers) {
506 if (pair.first.GetUid() == uid && pair.second->isActive()) {
507 outActiveConfigs.push_back(pair.first.GetId());
508 }
509 }
Yao Chenab273e22017-09-06 12:53:50 -0700510}
511
Yangster-macc04feba2018-04-02 14:37:33 -0700512void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
513 const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800514 std::lock_guard<std::mutex> lock(mMetricsMutex);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000515 WriteDataToDiskLocked(key, timestampNs, CONFIG_UPDATED, NO_TIME_CONSTRAINTS);
Yangster-macb142cc82018-03-30 15:22:08 -0700516 OnConfigUpdatedLocked(timestampNs, key, config);
517}
518
519void StatsLogProcessor::OnConfigUpdatedLocked(
520 const int64_t timestampNs, const ConfigKey& key, const StatsdConfig& config) {
Tej Singh484524a2018-02-01 15:10:05 -0800521 VLOG("Updated configuration for key %s", key.ToString().c_str());
Yangster-mac932ecec2018-02-01 10:23:52 -0800522 sp<MetricsManager> newMetricsManager =
Chenjie Yue2219202018-06-08 10:07:51 -0700523 new MetricsManager(key, config, mTimeBaseNs, timestampNs, mUidMap, mPullerManager,
524 mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
Yao Chencaf339d2017-10-06 16:01:10 -0700525 if (newMetricsManager->isConfigValid()) {
Tej Singh3be093b2020-03-04 20:08:38 -0800526 newMetricsManager->init();
David Chend6896892017-10-25 11:49:03 -0700527 mUidMap->OnConfigUpdated(key);
Yangster-macb142cc82018-03-30 15:22:08 -0700528 newMetricsManager->refreshTtl(timestampNs);
Yao Chend10f7b12017-12-18 12:53:50 -0800529 mMetricsManagers[key] = newMetricsManager;
Yao Chenb3561512017-11-21 18:07:17 -0800530 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700531 } else {
532 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800533 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700534 }
yro00698da2017-09-15 10:06:40 -0700535}
Bookatz906a35c2017-09-20 15:26:44 -0700536
Yangster7c334a12017-11-22 14:24:24 -0800537size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800538 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700539 auto it = mMetricsManagers.find(key);
540 if (it == mMetricsManagers.end()) {
541 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800542 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700543 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800544 return it->second->byteSize();
545}
546
Yao Chena80e5c02018-09-04 13:55:29 -0700547void StatsLogProcessor::dumpStates(int out, bool verbose) {
Yao Chen884c8c12018-01-26 10:36:25 -0800548 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chena80e5c02018-09-04 13:55:29 -0700549 FILE* fout = fdopen(out, "w");
550 if (fout == NULL) {
551 return;
Yao Chen884c8c12018-01-26 10:36:25 -0800552 }
Yao Chena80e5c02018-09-04 13:55:29 -0700553 fprintf(fout, "MetricsManager count: %lu\n", (unsigned long)mMetricsManagers.size());
554 for (auto metricsManager : mMetricsManagers) {
555 metricsManager.second->dumpStates(fout, verbose);
556 }
557
558 fclose(fout);
Yao Chen884c8c12018-01-26 10:36:25 -0800559}
560
yro4beccbe2018-03-15 19:42:05 -0700561/*
Bookatz9cc7b662018-11-06 10:39:21 -0800562 * onDumpReport dumps serialized ConfigMetricsReportList into proto.
yro4beccbe2018-03-15 19:42:05 -0700563 */
Yangster-macb142cc82018-03-30 15:22:08 -0700564void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700565 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700566 const bool erase_data,
Chenjie Yue36018b2018-04-16 15:18:30 -0700567 const DumpReportReason dumpReportReason,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000568 const DumpLatency dumpLatency,
Bookatzff71cad2018-09-20 17:17:49 -0700569 ProtoOutputStream* proto) {
Yangster-macb0d06282018-01-05 15:44:07 -0800570 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800571
yro947fbce2017-11-15 22:50:23 -0800572 // Start of ConfigKey.
Bookatzff71cad2018-09-20 17:17:49 -0700573 uint64_t configKeyToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
574 proto->write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
575 proto->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
576 proto->end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800577 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800578
Yao Chen9a43b4f2019-04-10 10:43:20 -0700579 bool keepFile = false;
580 auto it = mMetricsManagers.find(key);
581 if (it != mMetricsManagers.end() && it->second->shouldPersistLocalHistory()) {
582 keepFile = true;
583 }
584
yro947fbce2017-11-15 22:50:23 -0800585 // Then, check stats-data directory to see there's any file containing
586 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
Yao Chen9a43b4f2019-04-10 10:43:20 -0700587 StorageManager::appendConfigMetricsReport(
588 key, proto, erase_data && !keepFile /* should remove file after appending it */,
589 dumpReportReason == ADB_DUMP /*if caller is adb*/);
yro947fbce2017-11-15 22:50:23 -0800590
Yangster-mace68f3a52018-04-04 00:01:43 -0700591 if (it != mMetricsManagers.end()) {
592 // This allows another broadcast to be sent within the rate-limit period if we get close to
593 // filling the buffer again soon.
594 mLastBroadcastTimes.erase(key);
595
Yao Chen9a43b4f2019-04-10 10:43:20 -0700596 vector<uint8_t> buffer;
597 onConfigMetricsReportLocked(key, dumpTimeStampNs, include_current_partial_bucket,
598 erase_data, dumpReportReason, dumpLatency,
599 false /* is this data going to be saved on disk */, &buffer);
600 proto->write(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS,
601 reinterpret_cast<char*>(buffer.data()), buffer.size());
Yangster-mace68f3a52018-04-04 00:01:43 -0700602 } else {
603 ALOGW("Config source %s does not exist", key.ToString().c_str());
604 }
Bookatzff71cad2018-09-20 17:17:49 -0700605}
606
607/*
608 * onDumpReport dumps serialized ConfigMetricsReportList into outData.
609 */
610void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
611 const bool include_current_partial_bucket,
612 const bool erase_data,
613 const DumpReportReason dumpReportReason,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000614 const DumpLatency dumpLatency,
Bookatzff71cad2018-09-20 17:17:49 -0700615 vector<uint8_t>* outData) {
616 ProtoOutputStream proto;
617 onDumpReport(key, dumpTimeStampNs, include_current_partial_bucket, erase_data,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000618 dumpReportReason, dumpLatency, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700619
David Chen1d7b0cd2017-11-15 14:20:04 -0800620 if (outData != nullptr) {
Yao Chen9a43b4f2019-04-10 10:43:20 -0700621 flushProtoToBuffer(proto, outData);
622 VLOG("output data size %zu", outData->size());
yro17adac92017-11-08 23:16:29 -0800623 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800624
Yangster-mace68f3a52018-04-04 00:01:43 -0700625 StatsdStats::getInstance().noteMetricsReportSent(key, proto.size());
Yao Chen729093d2017-10-16 10:33:26 -0700626}
627
yro4beccbe2018-03-15 19:42:05 -0700628/*
629 * onConfigMetricsReportLocked dumps serialized ConfigMetricsReport into outData.
630 */
Yao Chen9a43b4f2019-04-10 10:43:20 -0700631void StatsLogProcessor::onConfigMetricsReportLocked(
632 const ConfigKey& key, const int64_t dumpTimeStampNs,
633 const bool include_current_partial_bucket, const bool erase_data,
634 const DumpReportReason dumpReportReason, const DumpLatency dumpLatency,
635 const bool dataSavedOnDisk, vector<uint8_t>* buffer) {
yro4beccbe2018-03-15 19:42:05 -0700636 // We already checked whether key exists in mMetricsManagers in
637 // WriteDataToDisk.
638 auto it = mMetricsManagers.find(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700639 if (it == mMetricsManagers.end()) {
640 return;
641 }
yro4beccbe2018-03-15 19:42:05 -0700642 int64_t lastReportTimeNs = it->second->getLastReportTimeNs();
643 int64_t lastReportWallClockNs = it->second->getLastReportWallClockNs();
644
Yangster-mac9def8e32018-04-17 13:55:51 -0700645 std::set<string> str_set;
646
Yao Chen9a43b4f2019-04-10 10:43:20 -0700647 ProtoOutputStream tempProto;
yro4beccbe2018-03-15 19:42:05 -0700648 // First, fill in ConfigMetricsReport using current data on memory, which
649 // starts from filling in StatsLogReport's.
Yao Chen9a43b4f2019-04-10 10:43:20 -0700650 it->second->onDumpReport(dumpTimeStampNs, include_current_partial_bucket, erase_data,
651 dumpLatency, &str_set, &tempProto);
yro4beccbe2018-03-15 19:42:05 -0700652
David Chen9e6dbbd2018-05-07 17:52:29 -0700653 // Fill in UidMap if there is at least one metric to report.
654 // This skips the uid map if it's an empty config.
655 if (it->second->getNumMetrics() > 0) {
Yao Chen9a43b4f2019-04-10 10:43:20 -0700656 uint64_t uidMapToken = tempProto.start(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP);
dwchen730403e2018-10-29 11:41:56 -0700657 mUidMap->appendUidMap(
658 dumpTimeStampNs, key, it->second->hashStringInReport() ? &str_set : nullptr,
Yao Chen9a43b4f2019-04-10 10:43:20 -0700659 it->second->versionStringsInReport(), it->second->installerInReport(), &tempProto);
660 tempProto.end(uidMapToken);
David Chen9e6dbbd2018-05-07 17:52:29 -0700661 }
yro4beccbe2018-03-15 19:42:05 -0700662
663 // Fill in the timestamps.
Yao Chen9a43b4f2019-04-10 10:43:20 -0700664 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_ELAPSED_NANOS,
665 (long long)lastReportTimeNs);
666 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS,
667 (long long)dumpTimeStampNs);
668 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS,
669 (long long)lastReportWallClockNs);
670 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS,
671 (long long)getWallClockNs());
Chenjie Yue36018b2018-04-16 15:18:30 -0700672 // Dump report reason
Yao Chen9a43b4f2019-04-10 10:43:20 -0700673 tempProto.write(FIELD_TYPE_INT32 | FIELD_ID_DUMP_REPORT_REASON, dumpReportReason);
Yangster-mac9def8e32018-04-17 13:55:51 -0700674
David Chen56ae0d92018-05-11 16:00:22 -0700675 for (const auto& str : str_set) {
Yao Chen9a43b4f2019-04-10 10:43:20 -0700676 tempProto.write(FIELD_TYPE_STRING | FIELD_COUNT_REPEATED | FIELD_ID_STRINGS, str);
677 }
678
679 flushProtoToBuffer(tempProto, buffer);
680
681 // save buffer to disk if needed
682 if (erase_data && !dataSavedOnDisk && it->second->shouldPersistLocalHistory()) {
683 VLOG("save history to disk");
684 string file_name = StorageManager::getDataHistoryFileName((long)getWallClockSec(),
685 key.GetUid(), key.GetId());
686 StorageManager::writeFile(file_name.c_str(), buffer->data(), buffer->size());
Yangster-mac9def8e32018-04-17 13:55:51 -0700687 }
Yangster-macb142cc82018-03-30 15:22:08 -0700688}
yro4beccbe2018-03-15 19:42:05 -0700689
Yao Chen163d2602018-04-10 10:39:53 -0700690void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs,
691 const std::vector<ConfigKey>& configs) {
692 for (const auto& key : configs) {
Yangster-macb142cc82018-03-30 15:22:08 -0700693 StatsdConfig config;
694 if (StorageManager::readConfigFromDisk(key, &config)) {
695 OnConfigUpdatedLocked(timestampNs, key, config);
696 StatsdStats::getInstance().noteConfigReset(key);
697 } else {
698 ALOGE("Failed to read backup config from disk for : %s", key.ToString().c_str());
699 auto it = mMetricsManagers.find(key);
700 if (it != mMetricsManagers.end()) {
701 it->second->refreshTtl(timestampNs);
702 }
703 }
704 }
yro4beccbe2018-03-15 19:42:05 -0700705}
706
Yao Chen163d2602018-04-10 10:39:53 -0700707void StatsLogProcessor::resetIfConfigTtlExpiredLocked(const int64_t timestampNs) {
708 std::vector<ConfigKey> configKeysTtlExpired;
709 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
710 if (it->second != nullptr && !it->second->isInTtl(timestampNs)) {
711 configKeysTtlExpired.push_back(it->first);
712 }
713 }
714 if (configKeysTtlExpired.size() > 0) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000715 WriteDataToDiskLocked(CONFIG_RESET, NO_TIME_CONSTRAINTS);
Yao Chen163d2602018-04-10 10:39:53 -0700716 resetConfigsLocked(timestampNs, configKeysTtlExpired);
717 }
718}
719
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700720void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800721 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700722 auto it = mMetricsManagers.find(key);
723 if (it != mMetricsManagers.end()) {
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700724 WriteDataToDiskLocked(key, getElapsedRealtimeNs(), CONFIG_REMOVED,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000725 NO_TIME_CONSTRAINTS);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700726 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700727 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700728 }
Yao Chenb3561512017-11-21 18:07:17 -0800729 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800730
David Chen1d7b0cd2017-11-15 14:20:04 -0800731 mLastBroadcastTimes.erase(key);
Chenjie Yufa22d652018-02-05 14:37:48 -0800732
Tej Singh6ede28b2019-01-29 17:06:54 -0800733 int uid = key.GetUid();
734 bool lastConfigForUid = true;
735 for (auto it : mMetricsManagers) {
736 if (it.first.GetUid() == uid) {
737 lastConfigForUid = false;
738 break;
739 }
740 }
741 if (lastConfigForUid) {
742 mLastActivationBroadcastTimes.erase(uid);
743 }
744
Chenjie Yufa22d652018-02-05 14:37:48 -0800745 if (mMetricsManagers.empty()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700746 mPullerManager->ForceClearPullerCache();
Chenjie Yufa22d652018-02-05 14:37:48 -0800747 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700748}
749
Tej Singh480392f2019-10-23 15:53:46 -0700750void StatsLogProcessor::flushIfNecessaryLocked(const ConfigKey& key,
751 MetricsManager& metricsManager) {
752 int64_t elapsedRealtimeNs = getElapsedRealtimeNs();
David Chend9269e22017-12-05 13:43:51 -0800753 auto lastCheckTime = mLastByteSizeTimes.find(key);
754 if (lastCheckTime != mLastByteSizeTimes.end()) {
Tej Singh480392f2019-10-23 15:53:46 -0700755 if (elapsedRealtimeNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
David Chend9269e22017-12-05 13:43:51 -0800756 return;
757 }
758 }
759
760 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
761 size_t totalBytes = metricsManager.byteSize();
Tej Singh480392f2019-10-23 15:53:46 -0700762 mLastByteSizeTimes[key] = elapsedRealtimeNs;
David Chen48944902018-05-03 10:29:11 -0700763 bool requestDump = false;
Tej Singh480392f2019-10-23 15:53:46 -0700764 if (totalBytes > StatsdStats::kMaxMetricsBytesPerConfig) {
765 // Too late. We need to start clearing data.
766 metricsManager.dropData(elapsedRealtimeNs);
Chenjie Yuc3c30c02018-10-26 09:48:07 -0700767 StatsdStats::getInstance().noteDataDropped(key, totalBytes);
David Chen12942952017-12-04 14:28:43 -0800768 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chen48944902018-05-03 10:29:11 -0700769 } else if ((totalBytes > StatsdStats::kBytesPerConfigTriggerGetData) ||
770 (mOnDiskDataConfigs.find(key) != mOnDiskDataConfigs.end())) {
771 // Request to send a broadcast if:
772 // 1. in memory data > threshold OR
773 // 2. config has old data report on disk.
774 requestDump = true;
775 }
776
777 if (requestDump) {
David Chend9269e22017-12-05 13:43:51 -0800778 // Send broadcast so that receivers can pull data.
779 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
780 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
Tej Singh480392f2019-10-23 15:53:46 -0700781 if (elapsedRealtimeNs - lastBroadcastTime->second <
782 StatsdStats::kMinBroadcastPeriodNs) {
David Chend9269e22017-12-05 13:43:51 -0800783 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800784 return;
785 }
786 }
David Chen48944902018-05-03 10:29:11 -0700787 if (mSendBroadcast(key)) {
788 mOnDiskDataConfigs.erase(key);
789 VLOG("StatsD triggered data fetch for %s", key.ToString().c_str());
Tej Singh480392f2019-10-23 15:53:46 -0700790 mLastBroadcastTimes[key] = elapsedRealtimeNs;
David Chen48944902018-05-03 10:29:11 -0700791 StatsdStats::getInstance().noteBroadcastSent(key);
792 }
yro31eb67b2017-10-24 13:33:21 -0700793 }
794}
795
Chenjie Yue36018b2018-04-16 15:18:30 -0700796void StatsLogProcessor::WriteDataToDiskLocked(const ConfigKey& key,
Yangster-mac892f3d32018-05-02 14:16:48 -0700797 const int64_t timestampNs,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000798 const DumpReportReason dumpReportReason,
799 const DumpLatency dumpLatency) {
yro028091c2018-05-09 16:03:27 -0700800 if (mMetricsManagers.find(key) == mMetricsManagers.end() ||
801 !mMetricsManagers.find(key)->second->shouldWriteToDisk()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700802 return;
803 }
Yao Chen9a43b4f2019-04-10 10:43:20 -0700804 vector<uint8_t> buffer;
David Chen56ae0d92018-05-11 16:00:22 -0700805 onConfigMetricsReportLocked(key, timestampNs, true /* include_current_partial_bucket*/,
Yao Chen9a43b4f2019-04-10 10:43:20 -0700806 true /* erase_data */, dumpReportReason, dumpLatency, true,
807 &buffer);
808 string file_name =
809 StorageManager::getDataFileName((long)getWallClockSec(), key.GetUid(), key.GetId());
810 StorageManager::writeFile(file_name.c_str(), buffer.data(), buffer.size());
811
David Chen48944902018-05-03 10:29:11 -0700812 // We were able to write the ConfigMetricsReport to disk, so we should trigger collection ASAP.
813 mOnDiskDataConfigs.insert(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700814}
815
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700816void StatsLogProcessor::SaveActiveConfigsToDisk(int64_t currentTimeNs) {
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800817 std::lock_guard<std::mutex> lock(mMetricsMutex);
jianjin996f40d2019-03-29 13:53:48 -0700818 const int64_t timeNs = getElapsedRealtimeNs();
819 // Do not write to disk if we already have in the last few seconds.
jianjin996f40d2019-03-29 13:53:48 -0700820 if (static_cast<unsigned long long> (timeNs) <
821 mLastActiveMetricsWriteNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
822 ALOGI("Statsd skipping writing active metrics to disk. Already wrote data in last %d seconds",
823 WRITE_DATA_COOL_DOWN_SEC);
824 return;
825 }
826 mLastActiveMetricsWriteNs = timeNs;
827
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800828 ProtoOutputStream proto;
Tej Singhf53d4452019-05-09 18:17:59 -0700829 WriteActiveConfigsToProtoOutputStreamLocked(currentTimeNs, DEVICE_SHUTDOWN, &proto);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800830
831 string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
832 StorageManager::deleteFile(file_name.c_str());
833 android::base::unique_fd fd(
834 open(file_name.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
835 if (fd == -1) {
836 ALOGE("Attempt to write %s but failed", file_name.c_str());
837 return;
838 }
839 proto.flush(fd.get());
840}
841
Jeffrey Huangb8f54032020-03-23 13:42:42 -0700842void StatsLogProcessor::SaveMetadataToDisk(int64_t currentWallClockTimeNs,
843 int64_t systemElapsedTimeNs) {
844 std::lock_guard<std::mutex> lock(mMetricsMutex);
845 // Do not write to disk if we already have in the last few seconds.
846 if (static_cast<unsigned long long> (systemElapsedTimeNs) <
847 mLastMetadataWriteNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
848 ALOGI("Statsd skipping writing metadata to disk. Already wrote data in last %d seconds",
849 WRITE_DATA_COOL_DOWN_SEC);
850 return;
851 }
852 mLastMetadataWriteNs = systemElapsedTimeNs;
853
854 metadata::StatsMetadataList metadataList;
855 WriteMetadataToProtoLocked(
856 currentWallClockTimeNs, systemElapsedTimeNs, &metadataList);
857
858 string file_name = StringPrintf("%s/metadata", STATS_METADATA_DIR);
859 StorageManager::deleteFile(file_name.c_str());
860
861 if (metadataList.stats_metadata_size() == 0) {
862 // Skip the write if we have nothing to write.
863 return;
864 }
865
866 std::string data;
867 metadataList.SerializeToString(&data);
868 StorageManager::writeFile(file_name.c_str(), data.c_str(), data.size());
869}
870
871void StatsLogProcessor::WriteMetadataToProto(int64_t currentWallClockTimeNs,
872 int64_t systemElapsedTimeNs,
873 metadata::StatsMetadataList* metadataList) {
874 std::lock_guard<std::mutex> lock(mMetricsMutex);
875 WriteMetadataToProtoLocked(currentWallClockTimeNs, systemElapsedTimeNs, metadataList);
876}
877
878void StatsLogProcessor::WriteMetadataToProtoLocked(int64_t currentWallClockTimeNs,
879 int64_t systemElapsedTimeNs,
880 metadata::StatsMetadataList* metadataList) {
881 for (const auto& pair : mMetricsManagers) {
882 const sp<MetricsManager>& metricsManager = pair.second;
883 metadata::StatsMetadata* statsMetadata = metadataList->add_stats_metadata();
884 bool metadataWritten = metricsManager->writeMetadataToProto(currentWallClockTimeNs,
885 systemElapsedTimeNs, statsMetadata);
886 if (!metadataWritten) {
887 metadataList->mutable_stats_metadata()->RemoveLast();
888 }
889 }
890}
891
Jeffrey Huang475677e2020-03-30 19:52:07 -0700892void StatsLogProcessor::LoadMetadataFromDisk(int64_t currentWallClockTimeNs,
893 int64_t systemElapsedTimeNs) {
894 std::lock_guard<std::mutex> lock(mMetricsMutex);
895 string file_name = StringPrintf("%s/metadata", STATS_METADATA_DIR);
896 int fd = open(file_name.c_str(), O_RDONLY | O_CLOEXEC);
897 if (-1 == fd) {
898 VLOG("Attempt to read %s but failed", file_name.c_str());
899 StorageManager::deleteFile(file_name.c_str());
900 return;
901 }
902 string content;
903 if (!android::base::ReadFdToString(fd, &content)) {
904 ALOGE("Attempt to read %s but failed", file_name.c_str());
905 close(fd);
906 StorageManager::deleteFile(file_name.c_str());
907 return;
908 }
909
910 close(fd);
911
912 metadata::StatsMetadataList statsMetadataList;
913 if (!statsMetadataList.ParseFromString(content)) {
914 ALOGE("Attempt to read %s but failed; failed to metadata", file_name.c_str());
915 StorageManager::deleteFile(file_name.c_str());
916 return;
917 }
918 SetMetadataStateLocked(statsMetadataList, currentWallClockTimeNs, systemElapsedTimeNs);
919 StorageManager::deleteFile(file_name.c_str());
920}
921
922void StatsLogProcessor::SetMetadataState(const metadata::StatsMetadataList& statsMetadataList,
923 int64_t currentWallClockTimeNs,
924 int64_t systemElapsedTimeNs) {
925 std::lock_guard<std::mutex> lock(mMetricsMutex);
926 SetMetadataStateLocked(statsMetadataList, currentWallClockTimeNs, systemElapsedTimeNs);
927}
928
929void StatsLogProcessor::SetMetadataStateLocked(
930 const metadata::StatsMetadataList& statsMetadataList,
931 int64_t currentWallClockTimeNs,
932 int64_t systemElapsedTimeNs) {
933 for (const metadata::StatsMetadata& metadata : statsMetadataList.stats_metadata()) {
934 ConfigKey key(metadata.config_key().uid(), metadata.config_key().config_id());
935 auto it = mMetricsManagers.find(key);
936 if (it == mMetricsManagers.end()) {
937 ALOGE("No config found for configKey %s", key.ToString().c_str());
938 continue;
939 }
940 VLOG("Setting metadata %s", key.ToString().c_str());
941 it->second->loadMetadata(metadata, currentWallClockTimeNs, systemElapsedTimeNs);
942 }
943 VLOG("Successfully loaded %d metadata.", statsMetadataList.stats_metadata_size());
944}
945
Tej Singhf53d4452019-05-09 18:17:59 -0700946void StatsLogProcessor::WriteActiveConfigsToProtoOutputStream(
947 int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto) {
948 std::lock_guard<std::mutex> lock(mMetricsMutex);
949 WriteActiveConfigsToProtoOutputStreamLocked(currentTimeNs, reason, proto);
950}
951
952void StatsLogProcessor::WriteActiveConfigsToProtoOutputStreamLocked(
953 int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto) {
954 for (const auto& pair : mMetricsManagers) {
955 const sp<MetricsManager>& metricsManager = pair.second;
956 uint64_t configToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
957 FIELD_ID_ACTIVE_CONFIG_LIST_CONFIG);
958 metricsManager->writeActiveConfigToProtoOutputStream(currentTimeNs, reason, proto);
959 proto->end(configToken);
960 }
961}
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700962void StatsLogProcessor::LoadActiveConfigsFromDisk() {
963 std::lock_guard<std::mutex> lock(mMetricsMutex);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800964 string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
965 int fd = open(file_name.c_str(), O_RDONLY | O_CLOEXEC);
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700966 if (-1 == fd) {
967 VLOG("Attempt to read %s but failed", file_name.c_str());
968 StorageManager::deleteFile(file_name.c_str());
969 return;
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800970 }
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700971 string content;
972 if (!android::base::ReadFdToString(fd, &content)) {
973 ALOGE("Attempt to read %s but failed", file_name.c_str());
974 close(fd);
975 StorageManager::deleteFile(file_name.c_str());
976 return;
977 }
978
979 close(fd);
980
981 ActiveConfigList activeConfigList;
982 if (!activeConfigList.ParseFromString(content)) {
983 ALOGE("Attempt to read %s but failed; failed to load active configs", file_name.c_str());
984 StorageManager::deleteFile(file_name.c_str());
985 return;
986 }
Tej Singhf53d4452019-05-09 18:17:59 -0700987 // Passing in mTimeBaseNs only works as long as we only load from disk is when statsd starts.
988 SetConfigsActiveStateLocked(activeConfigList, mTimeBaseNs);
989 StorageManager::deleteFile(file_name.c_str());
990}
991
992void StatsLogProcessor::SetConfigsActiveState(const ActiveConfigList& activeConfigList,
993 int64_t currentTimeNs) {
994 std::lock_guard<std::mutex> lock(mMetricsMutex);
995 SetConfigsActiveStateLocked(activeConfigList, currentTimeNs);
996}
997
998void StatsLogProcessor::SetConfigsActiveStateLocked(const ActiveConfigList& activeConfigList,
999 int64_t currentTimeNs) {
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001000 for (int i = 0; i < activeConfigList.config_size(); i++) {
1001 const auto& config = activeConfigList.config(i);
1002 ConfigKey key(config.uid(), config.id());
1003 auto it = mMetricsManagers.find(key);
1004 if (it == mMetricsManagers.end()) {
1005 ALOGE("No config found for config %s", key.ToString().c_str());
1006 continue;
1007 }
1008 VLOG("Setting active config %s", key.ToString().c_str());
Tej Singhf53d4452019-05-09 18:17:59 -07001009 it->second->loadActiveConfig(config, currentTimeNs);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001010 }
1011 VLOG("Successfully loaded %d active configs.", activeConfigList.config_size());
Chenjie Yuc7939cb2019-02-04 17:25:45 -08001012}
1013
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001014void StatsLogProcessor::WriteDataToDiskLocked(const DumpReportReason dumpReportReason,
1015 const DumpLatency dumpLatency) {
Yangster-mac892f3d32018-05-02 14:16:48 -07001016 const int64_t timeNs = getElapsedRealtimeNs();
Tej Singh42f9e062018-11-09 10:01:00 -08001017 // Do not write to disk if we already have in the last few seconds.
1018 // This is to avoid overwriting files that would have the same name if we
1019 // write twice in the same second.
1020 if (static_cast<unsigned long long> (timeNs) <
1021 mLastWriteTimeNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
1022 ALOGI("Statsd skipping writing data to disk. Already wrote data in last %d seconds",
1023 WRITE_DATA_COOL_DOWN_SEC);
1024 return;
1025 }
1026 mLastWriteTimeNs = timeNs;
Yangster-mace68f3a52018-04-04 00:01:43 -07001027 for (auto& pair : mMetricsManagers) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001028 WriteDataToDiskLocked(pair.first, timeNs, dumpReportReason, dumpLatency);
Yangster-mace68f3a52018-04-04 00:01:43 -07001029 }
1030}
1031
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001032void StatsLogProcessor::WriteDataToDisk(const DumpReportReason dumpReportReason,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001033 const DumpLatency dumpLatency) {
Yangster-macb0d06282018-01-05 15:44:07 -08001034 std::lock_guard<std::mutex> lock(mMetricsMutex);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001035 WriteDataToDiskLocked(dumpReportReason, dumpLatency);
yro947fbce2017-11-15 22:50:23 -08001036}
1037
Yangster-mac15f6bbc2018-04-08 11:52:26 -07001038void StatsLogProcessor::informPullAlarmFired(const int64_t timestampNs) {
Yangster6df5fcc2018-04-12 11:04:29 -07001039 std::lock_guard<std::mutex> lock(mMetricsMutex);
Chenjie Yue2219202018-06-08 10:07:51 -07001040 mPullerManager->OnAlarmFired(timestampNs);
Yangster-mac15f6bbc2018-04-08 11:52:26 -07001041}
1042
David Chend37bc232018-04-12 18:05:11 -07001043int64_t StatsLogProcessor::getLastReportTimeNs(const ConfigKey& key) {
1044 auto it = mMetricsManagers.find(key);
1045 if (it == mMetricsManagers.end()) {
1046 return 0;
1047 } else {
1048 return it->second->getLastReportTimeNs();
1049 }
1050}
1051
Tej Singh9ec159a2019-11-14 11:59:48 -08001052void StatsLogProcessor::notifyAppUpgrade(const int64_t& eventTimeNs, const string& apk,
1053 const int uid, const int64_t version) {
1054 std::lock_guard<std::mutex> lock(mMetricsMutex);
Tej Singhe678cb72020-04-14 16:23:30 -07001055 VLOG("Received app upgrade");
1056 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");
1065 for (const auto& it : mMetricsManagers) {
Tej Singh9ec159a2019-11-14 11:59:48 -08001066 it.second->notifyAppRemoved(eventTimeNs, apk, uid);
1067 }
1068}
1069
1070void StatsLogProcessor::onUidMapReceived(const int64_t& eventTimeNs) {
1071 std::lock_guard<std::mutex> lock(mMetricsMutex);
Tej Singhe678cb72020-04-14 16:23:30 -07001072 VLOG("Received uid map");
1073 for (const auto& it : mMetricsManagers) {
Tej Singh9ec159a2019-11-14 11:59:48 -08001074 it.second->onUidMapReceived(eventTimeNs);
1075 }
1076}
1077
Tej Singhe678cb72020-04-14 16:23:30 -07001078void StatsLogProcessor::onStatsdInitCompleted(const int64_t& elapsedTimeNs) {
1079 std::lock_guard<std::mutex> lock(mMetricsMutex);
1080 VLOG("Received boot completed signal");
1081 for (const auto& it : mMetricsManagers) {
1082 it.second->onStatsdInitCompleted(elapsedTimeNs);
1083 }
1084}
1085
David Chen48944902018-05-03 10:29:11 -07001086void StatsLogProcessor::noteOnDiskData(const ConfigKey& key) {
1087 std::lock_guard<std::mutex> lock(mMetricsMutex);
1088 mOnDiskDataConfigs.insert(key);
1089}
1090
Yao Chenef99c4f2017-09-22 16:26:54 -07001091} // namespace statsd
1092} // namespace os
1093} // namespace android