blob: 45cb07b93eb994eb0bcc3185b3ddb9ba626df871 [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
Yao Chen8a8d16c2018-02-08 14:50:40 -0800141void updateUid(Value* value, int hostUid) {
142 int uid = value->int_value;
143 if (uid != hostUid) {
144 value->setInt(hostUid);
145 }
146}
147
Yangster-macd40053e2018-01-09 16:29:22 -0800148void StatsLogProcessor::mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent* event) const {
Yao Chenc40a19d2018-03-15 16:48:25 -0700149 if (android::util::AtomsInfo::kAtomsWithAttributionChain.find(event->GetTagId()) !=
150 android::util::AtomsInfo::kAtomsWithAttributionChain.end()) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800151 for (auto& value : *(event->getMutableValues())) {
152 if (value.mField.getPosAtDepth(0) > kAttributionField) {
153 break;
154 }
155 if (isAttributionUidField(value)) {
156 const int hostUid = mUidMap->getHostUidOrSelf(value.mValue.int_value);
157 updateUid(&value.mValue, hostUid);
158 }
Yangster-macd40053e2018-01-09 16:29:22 -0800159 }
Yao Chenc40a19d2018-03-15 16:48:25 -0700160 } else {
161 auto it = android::util::AtomsInfo::kAtomsWithUidField.find(event->GetTagId());
162 if (it != android::util::AtomsInfo::kAtomsWithUidField.end()) {
163 int uidField = it->second; // uidField is the field number in proto,
164 // starting from 1
165 if (uidField > 0 && (int)event->getValues().size() >= uidField &&
166 (event->getValues())[uidField - 1].mValue.getType() == INT) {
167 Value& value = (*event->getMutableValues())[uidField - 1].mValue;
168 const int hostUid = mUidMap->getHostUidOrSelf(value.int_value);
169 updateUid(&value, hostUid);
170 } else {
171 ALOGE("Malformed log, uid not found. %s", event->ToString().c_str());
172 }
173 }
Yao Chen312e8982017-12-05 15:29:03 -0800174 }
Yangster-macd40053e2018-01-09 16:29:22 -0800175}
176
177void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
178 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
179 bool is_create = event.GetBool(3, &err);
180 auto parent_uid = int(event.GetLong(1, &err2));
181 auto isolated_uid = int(event.GetLong(2, &err3));
182 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
183 if (is_create) {
184 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
185 } else {
Bookatz3c648862018-05-25 13:32:43 -0700186 mUidMap->removeIsolatedUid(isolated_uid);
Yangster-macd40053e2018-01-09 16:29:22 -0800187 }
188 } else {
189 ALOGE("Failed to parse uid in the isolated uid change event.");
190 }
191}
192
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800193void StatsLogProcessor::onBinaryPushStateChangedEventLocked(LogEvent* event) {
194 pid_t pid = event->GetPid();
195 uid_t uid = event->GetUid();
196 if (!checkPermissionForIds(kPermissionDump, pid, uid) ||
197 !checkPermissionForIds(kPermissionUsage, pid, uid)) {
198 return;
199 }
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800200 // The Get* functions don't modify the status on success, they only write in
201 // failure statuses, so we can use one status variable for all calls then
202 // check if it is no longer NO_ERROR.
203 status_t err = NO_ERROR;
204 InstallTrainInfo trainInfo;
205 trainInfo.trainName = string(event->GetString(1 /*train name field id*/, &err));
206 trainInfo.trainVersionCode = event->GetLong(2 /*train version field id*/, &err);
207 trainInfo.requiresStaging = event->GetBool(3 /*requires staging field id*/, &err);
208 trainInfo.rollbackEnabled = event->GetBool(4 /*rollback enabled field id*/, &err);
209 trainInfo.requiresLowLatencyMonitor =
210 event->GetBool(5 /*requires low latency monitor field id*/, &err);
211 trainInfo.status = int32_t(event->GetLong(6 /*state field id*/, &err));
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800212 std::vector<uint8_t> trainExperimentIdBytes =
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800213 event->GetStorage(7 /*experiment ids field id*/, &err);
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800214 bool is_rollback = event->GetBool(10 /*is rollback field id*/, &err);
215
216 if (err != NO_ERROR) {
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800217 ALOGE("Failed to parse fields in binary push state changed log event");
218 return;
219 }
220 ExperimentIds trainExperimentIds;
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800221 if (!trainExperimentIds.ParseFromArray(trainExperimentIdBytes.data(),
222 trainExperimentIdBytes.size())) {
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800223 ALOGE("Failed to parse experimentids in binary push state changed.");
224 return;
225 }
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800226 trainInfo.experimentIds = {trainExperimentIds.experiment_id().begin(),
227 trainExperimentIds.experiment_id().end()};
228
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800229 // Update the train info on disk and get any data the logevent is missing.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800230 getAndUpdateTrainInfoOnDisk(is_rollback, &trainInfo);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800231
232 std::vector<uint8_t> trainExperimentIdProto;
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800233 writeExperimentIdsToProto(trainInfo.experimentIds, &trainExperimentIdProto);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800234 int32_t userId = multiuser_get_user_id(uid);
235
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800236 event->updateValue(2 /*train version field id*/, trainInfo.trainVersionCode, LONG);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800237 event->updateValue(7 /*experiment ids field id*/, trainExperimentIdProto, STORAGE);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800238 event->updateValue(8 /*user id field id*/, userId, INT);
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800239
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800240 // If this event is a rollback event, then the following bits in the event
241 // are invalid and we will need to update them with the values we pulled
242 // from disk.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800243 if (is_rollback) {
244 int bit = trainInfo.requiresStaging ? 1 : 0;
245 event->updateValue(3 /*requires staging field id*/, bit, INT);
246 bit = trainInfo.rollbackEnabled ? 1 : 0;
247 event->updateValue(4 /*rollback enabled field id*/, bit, INT);
248 bit = trainInfo.requiresLowLatencyMonitor ? 1 : 0;
249 event->updateValue(5 /*requires low latency monitor field id*/, bit, INT);
250 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800251}
252
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800253void StatsLogProcessor::getAndUpdateTrainInfoOnDisk(bool is_rollback,
254 InstallTrainInfo* trainInfo) {
255 // If the train name is empty, we don't know which train to attribute the
256 // event to, so return early.
257 if (trainInfo->trainName.empty()) {
258 return;
259 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800260 bool readTrainInfoSuccess = false;
261 InstallTrainInfo trainInfoOnDisk;
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800262 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfo->trainName, trainInfoOnDisk);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800263
264 bool resetExperimentIds = false;
265 if (readTrainInfoSuccess) {
266 // Keep the old train version if we received an empty version.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800267 if (trainInfo->trainVersionCode == -1) {
268 trainInfo->trainVersionCode = trainInfoOnDisk.trainVersionCode;
269 } else if (trainInfo->trainVersionCode != trainInfoOnDisk.trainVersionCode) {
270 // Reset experiment ids if we receive a new non-empty train version.
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800271 resetExperimentIds = true;
272 }
273
274 // Reset if we received a different experiment id.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800275 if (!trainInfo->experimentIds.empty() &&
276 (trainInfoOnDisk.experimentIds.empty() ||
277 trainInfo->experimentIds.at(0) != trainInfoOnDisk.experimentIds[0])) {
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800278 resetExperimentIds = true;
279 }
280 }
281
282 // Find the right experiment IDs
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800283 if ((!resetExperimentIds || is_rollback) && readTrainInfoSuccess) {
284 trainInfo->experimentIds = trainInfoOnDisk.experimentIds;
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800285 }
286
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800287 if (!trainInfo->experimentIds.empty()) {
288 int64_t firstId = trainInfo->experimentIds.at(0);
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800289 auto& ids = trainInfo->experimentIds;
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800290 switch (trainInfo->status) {
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800291 case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALL_SUCCESS:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800292 if (find(ids.begin(), ids.end(), firstId + 1) == ids.end()) {
293 ids.push_back(firstId + 1);
294 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800295 break;
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800296 case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_INITIATED:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800297 if (find(ids.begin(), ids.end(), firstId + 2) == ids.end()) {
298 ids.push_back(firstId + 2);
299 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800300 break;
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800301 case android::os::statsd::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_SUCCESS:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800302 if (find(ids.begin(), ids.end(), firstId + 3) == ids.end()) {
303 ids.push_back(firstId + 3);
304 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800305 break;
306 }
307 }
308
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800309 // If this event is a rollback event, the following fields are invalid and
310 // need to be replaced by the fields stored to disk.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800311 if (is_rollback) {
312 trainInfo->requiresStaging = trainInfoOnDisk.requiresStaging;
313 trainInfo->rollbackEnabled = trainInfoOnDisk.rollbackEnabled;
314 trainInfo->requiresLowLatencyMonitor = trainInfoOnDisk.requiresLowLatencyMonitor;
315 }
316
317 StorageManager::writeTrainInfo(*trainInfo);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800318}
319
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800320void StatsLogProcessor::onWatchdogRollbackOccurredLocked(LogEvent* event) {
321 pid_t pid = event->GetPid();
322 uid_t uid = event->GetUid();
323 if (!checkPermissionForIds(kPermissionDump, pid, uid) ||
324 !checkPermissionForIds(kPermissionUsage, pid, uid)) {
325 return;
326 }
327 // The Get* functions don't modify the status on success, they only write in
328 // failure statuses, so we can use one status variable for all calls then
329 // check if it is no longer NO_ERROR.
330 status_t err = NO_ERROR;
331 int32_t rollbackType = int32_t(event->GetInt(1 /*rollback type field id*/, &err));
332 string packageName = string(event->GetString(2 /*package name field id*/, &err));
333
334 if (err != NO_ERROR) {
335 ALOGE("Failed to parse fields in watchdog rollback occurred log event");
336 return;
337 }
338
339 vector<int64_t> experimentIds =
340 processWatchdogRollbackOccurred(rollbackType, packageName);
341 vector<uint8_t> experimentIdProto;
342 writeExperimentIdsToProto(experimentIds, &experimentIdProto);
343
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800344 event->updateValue(6 /*experiment ids field id*/, experimentIdProto, STORAGE);
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800345}
346
347vector<int64_t> StatsLogProcessor::processWatchdogRollbackOccurred(const int32_t rollbackTypeIn,
348 const string& packageNameIn) {
349 // If the package name is empty, we can't attribute it to any train, so
350 // return early.
351 if (packageNameIn.empty()) {
352 return vector<int64_t>();
353 }
354 bool readTrainInfoSuccess = false;
355 InstallTrainInfo trainInfoOnDisk;
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800356 // We use the package name of the event as the train name.
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800357 readTrainInfoSuccess = StorageManager::readTrainInfo(packageNameIn, trainInfoOnDisk);
358
359 if (!readTrainInfoSuccess) {
360 return vector<int64_t>();
361 }
362
363 if (trainInfoOnDisk.experimentIds.empty()) {
364 return vector<int64_t>();
365 }
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800366
367 int64_t firstId = trainInfoOnDisk.experimentIds[0];
368 auto& ids = trainInfoOnDisk.experimentIds;
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800369 switch (rollbackTypeIn) {
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800370 case android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800371 if (find(ids.begin(), ids.end(), firstId + 4) == ids.end()) {
372 ids.push_back(firstId + 4);
373 }
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800374 StorageManager::writeTrainInfo(trainInfoOnDisk);
375 break;
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800376 case android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS:
Jonathan Nguyen727a9642020-02-12 17:24:32 -0800377 if (find(ids.begin(), ids.end(), firstId + 5) == ids.end()) {
378 ids.push_back(firstId + 5);
379 }
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800380 StorageManager::writeTrainInfo(trainInfoOnDisk);
381 break;
382 }
383
384 return trainInfoOnDisk.experimentIds;
385}
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800386
Yangster-mac892f3d32018-05-02 14:16:48 -0700387void StatsLogProcessor::resetConfigs() {
388 std::lock_guard<std::mutex> lock(mMetricsMutex);
389 resetConfigsLocked(getElapsedRealtimeNs());
390}
391
392void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs) {
393 std::vector<ConfigKey> configKeys;
394 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
395 configKeys.push_back(it->first);
396 }
397 resetConfigsLocked(timestampNs, configKeys);
398}
399
Yao Chen3ff3a492018-08-06 16:17:37 -0700400void StatsLogProcessor::OnLogEvent(LogEvent* event) {
Tej Singh480392f2019-10-23 15:53:46 -0700401 OnLogEvent(event, getElapsedRealtimeNs());
402}
403
404void StatsLogProcessor::OnLogEvent(LogEvent* event, int64_t elapsedRealtimeNs) {
Yangster-macd40053e2018-01-09 16:29:22 -0800405 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen876889c2018-05-02 11:16:16 -0700406
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800407 // Hard-coded logic to update train info on disk and fill in any information
408 // this log event may be missing.
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800409 if (event->GetTagId() == android::os::statsd::util::BINARY_PUSH_STATE_CHANGED) {
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800410 onBinaryPushStateChangedEventLocked(event);
411 }
412
413 // Hard-coded logic to update experiment ids on disk for certain rollback
414 // types and fill the rollback atom with experiment ids
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800415 if (event->GetTagId() == android::os::statsd::util::WATCHDOG_ROLLBACK_OCCURRED) {
Jonathan Nguyen703c42f2020-02-04 15:54:26 -0800416 onWatchdogRollbackOccurredLocked(event);
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800417 }
418
Yao Chen876889c2018-05-02 11:16:16 -0700419#ifdef VERY_VERBOSE_PRINTING
420 if (mPrintAllLogs) {
421 ALOGI("%s", event->ToString().c_str());
422 }
423#endif
Tej Singh480392f2019-10-23 15:53:46 -0700424 const int64_t eventElapsedTimeNs = event->GetElapsedTimestampNs();
Yangster-macb8382a12018-04-04 10:39:12 -0700425
Tej Singh480392f2019-10-23 15:53:46 -0700426 resetIfConfigTtlExpiredLocked(eventElapsedTimeNs);
Yangster-macb142cc82018-03-30 15:22:08 -0700427
Yangster-macd40053e2018-01-09 16:29:22 -0800428 StatsdStats::getInstance().noteAtomLogged(
Yangster-mac330af582018-02-08 15:24:38 -0800429 event->GetTagId(), event->GetElapsedTimestampNs() / NS_PER_SEC);
Yangster-macd40053e2018-01-09 16:29:22 -0800430
David Chen21582962017-11-01 17:32:46 -0700431 // Hard-coded logic to update the isolated uid's in the uid-map.
Stefan Lafonae2df012017-11-14 09:17:21 -0800432 // The field numbers need to be currently updated by hand with atoms.proto
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800433 if (event->GetTagId() == android::os::statsd::util::ISOLATED_UID_CHANGED) {
Yangster-macd40053e2018-01-09 16:29:22 -0800434 onIsolatedUidChangedEventLocked(*event);
David Chencfc311d2018-01-23 17:55:54 -0800435 }
436
tsaichristined21aacf2019-10-07 14:47:38 -0700437 StateManager::getInstance().onLogEvent(*event);
438
David Chencfc311d2018-01-23 17:55:54 -0800439 if (mMetricsManagers.empty()) {
440 return;
441 }
442
Yangster-macb142cc82018-03-30 15:22:08 -0700443 int64_t curTimeSec = getElapsedRealtimeSec();
Yangster-mac330af582018-02-08 15:24:38 -0800444 if (curTimeSec - mLastPullerCacheClearTimeSec > StatsdStats::kPullerCacheClearIntervalSec) {
Chenjie Yue2219202018-06-08 10:07:51 -0700445 mPullerManager->ClearPullerCacheIfNecessary(curTimeSec * NS_PER_SEC);
Yangster-mac330af582018-02-08 15:24:38 -0800446 mLastPullerCacheClearTimeSec = curTimeSec;
Chenjie Yufa22d652018-02-05 14:37:48 -0800447 }
448
Yangster-macb142cc82018-03-30 15:22:08 -0700449
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800450 if (event->GetTagId() != android::os::statsd::util::ISOLATED_UID_CHANGED) {
Yangster-macd40053e2018-01-09 16:29:22 -0800451 // Map the isolated uid to host uid if necessary.
452 mapIsolatedUidToHostUidIfNecessaryLocked(event);
453 }
454
Tej Singh6ede28b2019-01-29 17:06:54 -0800455 std::unordered_set<int> uidsWithActiveConfigsChanged;
456 std::unordered_map<int, std::vector<int64_t>> activeConfigsPerUid;
Yangster-macd40053e2018-01-09 16:29:22 -0800457 // pass the event to metrics managers.
458 for (auto& pair : mMetricsManagers) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800459 int uid = pair.first.GetUid();
460 int64_t configId = pair.first.GetId();
461 bool isPrevActive = pair.second->isActive();
Yangster-macd40053e2018-01-09 16:29:22 -0800462 pair.second->onLogEvent(*event);
Tej Singh6ede28b2019-01-29 17:06:54 -0800463 bool isCurActive = pair.second->isActive();
464 // Map all active configs by uid.
465 if (isCurActive) {
466 auto activeConfigs = activeConfigsPerUid.find(uid);
467 if (activeConfigs != activeConfigsPerUid.end()) {
468 activeConfigs->second.push_back(configId);
469 } else {
470 vector<int64_t> newActiveConfigs;
471 newActiveConfigs.push_back(configId);
472 activeConfigsPerUid[uid] = newActiveConfigs;
473 }
474 }
475 // The activation state of this config changed.
476 if (isPrevActive != isCurActive) {
477 VLOG("Active status changed for uid %d", uid);
478 uidsWithActiveConfigsChanged.insert(uid);
479 StatsdStats::getInstance().noteActiveStatusChanged(pair.first, isCurActive);
480 }
Tej Singh480392f2019-10-23 15:53:46 -0700481 flushIfNecessaryLocked(pair.first, *(pair.second));
David Chen21582962017-11-01 17:32:46 -0700482 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800483
Tej Singh480392f2019-10-23 15:53:46 -0700484 // Don't use the event timestamp for the guardrail.
Tej Singh6ede28b2019-01-29 17:06:54 -0800485 for (int uid : uidsWithActiveConfigsChanged) {
486 // Send broadcast so that receivers can pull data.
487 auto lastBroadcastTime = mLastActivationBroadcastTimes.find(uid);
488 if (lastBroadcastTime != mLastActivationBroadcastTimes.end()) {
Tej Singh480392f2019-10-23 15:53:46 -0700489 if (elapsedRealtimeNs - lastBroadcastTime->second <
490 StatsdStats::kMinActivationBroadcastPeriodNs) {
Tej Singh16ca28f2019-06-24 11:58:23 -0700491 StatsdStats::getInstance().noteActivationBroadcastGuardrailHit(uid);
Tej Singh6ede28b2019-01-29 17:06:54 -0800492 VLOG("StatsD would've sent an activation broadcast but the rate limit stopped us.");
493 return;
494 }
495 }
496 auto activeConfigs = activeConfigsPerUid.find(uid);
497 if (activeConfigs != activeConfigsPerUid.end()) {
498 if (mSendActivationBroadcast(uid, activeConfigs->second)) {
499 VLOG("StatsD sent activation notice for uid %d", uid);
Tej Singh480392f2019-10-23 15:53:46 -0700500 mLastActivationBroadcastTimes[uid] = elapsedRealtimeNs;
Tej Singh6ede28b2019-01-29 17:06:54 -0800501 }
502 } else {
503 std::vector<int64_t> emptyActiveConfigs;
504 if (mSendActivationBroadcast(uid, emptyActiveConfigs)) {
505 VLOG("StatsD sent EMPTY activation notice for uid %d", uid);
Tej Singh480392f2019-10-23 15:53:46 -0700506 mLastActivationBroadcastTimes[uid] = elapsedRealtimeNs;
Tej Singh6ede28b2019-01-29 17:06:54 -0800507 }
508 }
509 }
510}
511
512void StatsLogProcessor::GetActiveConfigs(const int uid, vector<int64_t>& outActiveConfigs) {
513 std::lock_guard<std::mutex> lock(mMetricsMutex);
514 GetActiveConfigsLocked(uid, outActiveConfigs);
515}
516
517void StatsLogProcessor::GetActiveConfigsLocked(const int uid, vector<int64_t>& outActiveConfigs) {
518 outActiveConfigs.clear();
519 for (auto& pair : mMetricsManagers) {
520 if (pair.first.GetUid() == uid && pair.second->isActive()) {
521 outActiveConfigs.push_back(pair.first.GetId());
522 }
523 }
Yao Chenab273e22017-09-06 12:53:50 -0700524}
525
Yangster-macc04feba2018-04-02 14:37:33 -0700526void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
527 const StatsdConfig& config) {
Yangster-macb0d06282018-01-05 15:44:07 -0800528 std::lock_guard<std::mutex> lock(mMetricsMutex);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000529 WriteDataToDiskLocked(key, timestampNs, CONFIG_UPDATED, NO_TIME_CONSTRAINTS);
Yangster-macb142cc82018-03-30 15:22:08 -0700530 OnConfigUpdatedLocked(timestampNs, key, config);
531}
532
533void StatsLogProcessor::OnConfigUpdatedLocked(
534 const int64_t timestampNs, const ConfigKey& key, const StatsdConfig& config) {
Tej Singh484524a2018-02-01 15:10:05 -0800535 VLOG("Updated configuration for key %s", key.ToString().c_str());
Yangster-mac932ecec2018-02-01 10:23:52 -0800536 sp<MetricsManager> newMetricsManager =
Chenjie Yue2219202018-06-08 10:07:51 -0700537 new MetricsManager(key, config, mTimeBaseNs, timestampNs, mUidMap, mPullerManager,
538 mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
Yao Chencaf339d2017-10-06 16:01:10 -0700539 if (newMetricsManager->isConfigValid()) {
David Chend6896892017-10-25 11:49:03 -0700540 mUidMap->OnConfigUpdated(key);
Yangster-macb142cc82018-03-30 15:22:08 -0700541 newMetricsManager->refreshTtl(timestampNs);
Yao Chend10f7b12017-12-18 12:53:50 -0800542 mMetricsManagers[key] = newMetricsManager;
Yao Chenb3561512017-11-21 18:07:17 -0800543 VLOG("StatsdConfig valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700544 } else {
545 // If there is any error in the config, don't use it.
Yao Chenb3561512017-11-21 18:07:17 -0800546 ALOGE("StatsdConfig NOT valid");
Yao Chencaf339d2017-10-06 16:01:10 -0700547 }
yro00698da2017-09-15 10:06:40 -0700548}
Bookatz906a35c2017-09-20 15:26:44 -0700549
Yangster7c334a12017-11-22 14:24:24 -0800550size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
Yangster-macb0d06282018-01-05 15:44:07 -0800551 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chen729093d2017-10-16 10:33:26 -0700552 auto it = mMetricsManagers.find(key);
553 if (it == mMetricsManagers.end()) {
554 ALOGW("Config source %s does not exist", key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -0800555 return 0;
Yao Chen729093d2017-10-16 10:33:26 -0700556 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800557 return it->second->byteSize();
558}
559
Yao Chena80e5c02018-09-04 13:55:29 -0700560void StatsLogProcessor::dumpStates(int out, bool verbose) {
Yao Chen884c8c12018-01-26 10:36:25 -0800561 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yao Chena80e5c02018-09-04 13:55:29 -0700562 FILE* fout = fdopen(out, "w");
563 if (fout == NULL) {
564 return;
Yao Chen884c8c12018-01-26 10:36:25 -0800565 }
Yao Chena80e5c02018-09-04 13:55:29 -0700566 fprintf(fout, "MetricsManager count: %lu\n", (unsigned long)mMetricsManagers.size());
567 for (auto metricsManager : mMetricsManagers) {
568 metricsManager.second->dumpStates(fout, verbose);
569 }
570
571 fclose(fout);
Yao Chen884c8c12018-01-26 10:36:25 -0800572}
573
yro4beccbe2018-03-15 19:42:05 -0700574/*
Bookatz9cc7b662018-11-06 10:39:21 -0800575 * onDumpReport dumps serialized ConfigMetricsReportList into proto.
yro4beccbe2018-03-15 19:42:05 -0700576 */
Yangster-macb142cc82018-03-30 15:22:08 -0700577void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700578 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700579 const bool erase_data,
Chenjie Yue36018b2018-04-16 15:18:30 -0700580 const DumpReportReason dumpReportReason,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000581 const DumpLatency dumpLatency,
Bookatzff71cad2018-09-20 17:17:49 -0700582 ProtoOutputStream* proto) {
Yangster-macb0d06282018-01-05 15:44:07 -0800583 std::lock_guard<std::mutex> lock(mMetricsMutex);
Yangster-mac20877162017-12-22 17:19:39 -0800584
yro947fbce2017-11-15 22:50:23 -0800585 // Start of ConfigKey.
Bookatzff71cad2018-09-20 17:17:49 -0700586 uint64_t configKeyToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
587 proto->write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
588 proto->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
589 proto->end(configKeyToken);
yro947fbce2017-11-15 22:50:23 -0800590 // End of ConfigKey.
yro17adac92017-11-08 23:16:29 -0800591
Yao Chen9a43b4f2019-04-10 10:43:20 -0700592 bool keepFile = false;
593 auto it = mMetricsManagers.find(key);
594 if (it != mMetricsManagers.end() && it->second->shouldPersistLocalHistory()) {
595 keepFile = true;
596 }
597
yro947fbce2017-11-15 22:50:23 -0800598 // Then, check stats-data directory to see there's any file containing
599 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
Yao Chen9a43b4f2019-04-10 10:43:20 -0700600 StorageManager::appendConfigMetricsReport(
601 key, proto, erase_data && !keepFile /* should remove file after appending it */,
602 dumpReportReason == ADB_DUMP /*if caller is adb*/);
yro947fbce2017-11-15 22:50:23 -0800603
Yangster-mace68f3a52018-04-04 00:01:43 -0700604 if (it != mMetricsManagers.end()) {
605 // This allows another broadcast to be sent within the rate-limit period if we get close to
606 // filling the buffer again soon.
607 mLastBroadcastTimes.erase(key);
608
Yao Chen9a43b4f2019-04-10 10:43:20 -0700609 vector<uint8_t> buffer;
610 onConfigMetricsReportLocked(key, dumpTimeStampNs, include_current_partial_bucket,
611 erase_data, dumpReportReason, dumpLatency,
612 false /* is this data going to be saved on disk */, &buffer);
613 proto->write(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS,
614 reinterpret_cast<char*>(buffer.data()), buffer.size());
Yangster-mace68f3a52018-04-04 00:01:43 -0700615 } else {
616 ALOGW("Config source %s does not exist", key.ToString().c_str());
617 }
Bookatzff71cad2018-09-20 17:17:49 -0700618}
619
620/*
621 * onDumpReport dumps serialized ConfigMetricsReportList into outData.
622 */
623void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
624 const bool include_current_partial_bucket,
625 const bool erase_data,
626 const DumpReportReason dumpReportReason,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000627 const DumpLatency dumpLatency,
Bookatzff71cad2018-09-20 17:17:49 -0700628 vector<uint8_t>* outData) {
629 ProtoOutputStream proto;
630 onDumpReport(key, dumpTimeStampNs, include_current_partial_bucket, erase_data,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000631 dumpReportReason, dumpLatency, &proto);
Yangster-mace68f3a52018-04-04 00:01:43 -0700632
David Chen1d7b0cd2017-11-15 14:20:04 -0800633 if (outData != nullptr) {
Yao Chen9a43b4f2019-04-10 10:43:20 -0700634 flushProtoToBuffer(proto, outData);
635 VLOG("output data size %zu", outData->size());
yro17adac92017-11-08 23:16:29 -0800636 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800637
Yangster-mace68f3a52018-04-04 00:01:43 -0700638 StatsdStats::getInstance().noteMetricsReportSent(key, proto.size());
Yao Chen729093d2017-10-16 10:33:26 -0700639}
640
yro4beccbe2018-03-15 19:42:05 -0700641/*
642 * onConfigMetricsReportLocked dumps serialized ConfigMetricsReport into outData.
643 */
Yao Chen9a43b4f2019-04-10 10:43:20 -0700644void StatsLogProcessor::onConfigMetricsReportLocked(
645 const ConfigKey& key, const int64_t dumpTimeStampNs,
646 const bool include_current_partial_bucket, const bool erase_data,
647 const DumpReportReason dumpReportReason, const DumpLatency dumpLatency,
648 const bool dataSavedOnDisk, vector<uint8_t>* buffer) {
yro4beccbe2018-03-15 19:42:05 -0700649 // We already checked whether key exists in mMetricsManagers in
650 // WriteDataToDisk.
651 auto it = mMetricsManagers.find(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700652 if (it == mMetricsManagers.end()) {
653 return;
654 }
yro4beccbe2018-03-15 19:42:05 -0700655 int64_t lastReportTimeNs = it->second->getLastReportTimeNs();
656 int64_t lastReportWallClockNs = it->second->getLastReportWallClockNs();
657
Yangster-mac9def8e32018-04-17 13:55:51 -0700658 std::set<string> str_set;
659
Yao Chen9a43b4f2019-04-10 10:43:20 -0700660 ProtoOutputStream tempProto;
yro4beccbe2018-03-15 19:42:05 -0700661 // First, fill in ConfigMetricsReport using current data on memory, which
662 // starts from filling in StatsLogReport's.
Yao Chen9a43b4f2019-04-10 10:43:20 -0700663 it->second->onDumpReport(dumpTimeStampNs, include_current_partial_bucket, erase_data,
664 dumpLatency, &str_set, &tempProto);
yro4beccbe2018-03-15 19:42:05 -0700665
David Chen9e6dbbd2018-05-07 17:52:29 -0700666 // Fill in UidMap if there is at least one metric to report.
667 // This skips the uid map if it's an empty config.
668 if (it->second->getNumMetrics() > 0) {
Yao Chen9a43b4f2019-04-10 10:43:20 -0700669 uint64_t uidMapToken = tempProto.start(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP);
dwchen730403e2018-10-29 11:41:56 -0700670 mUidMap->appendUidMap(
671 dumpTimeStampNs, key, it->second->hashStringInReport() ? &str_set : nullptr,
Yao Chen9a43b4f2019-04-10 10:43:20 -0700672 it->second->versionStringsInReport(), it->second->installerInReport(), &tempProto);
673 tempProto.end(uidMapToken);
David Chen9e6dbbd2018-05-07 17:52:29 -0700674 }
yro4beccbe2018-03-15 19:42:05 -0700675
676 // Fill in the timestamps.
Yao Chen9a43b4f2019-04-10 10:43:20 -0700677 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_ELAPSED_NANOS,
678 (long long)lastReportTimeNs);
679 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS,
680 (long long)dumpTimeStampNs);
681 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS,
682 (long long)lastReportWallClockNs);
683 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS,
684 (long long)getWallClockNs());
Chenjie Yue36018b2018-04-16 15:18:30 -0700685 // Dump report reason
Yao Chen9a43b4f2019-04-10 10:43:20 -0700686 tempProto.write(FIELD_TYPE_INT32 | FIELD_ID_DUMP_REPORT_REASON, dumpReportReason);
Yangster-mac9def8e32018-04-17 13:55:51 -0700687
David Chen56ae0d92018-05-11 16:00:22 -0700688 for (const auto& str : str_set) {
Yao Chen9a43b4f2019-04-10 10:43:20 -0700689 tempProto.write(FIELD_TYPE_STRING | FIELD_COUNT_REPEATED | FIELD_ID_STRINGS, str);
690 }
691
692 flushProtoToBuffer(tempProto, buffer);
693
694 // save buffer to disk if needed
695 if (erase_data && !dataSavedOnDisk && it->second->shouldPersistLocalHistory()) {
696 VLOG("save history to disk");
697 string file_name = StorageManager::getDataHistoryFileName((long)getWallClockSec(),
698 key.GetUid(), key.GetId());
699 StorageManager::writeFile(file_name.c_str(), buffer->data(), buffer->size());
Yangster-mac9def8e32018-04-17 13:55:51 -0700700 }
Yangster-macb142cc82018-03-30 15:22:08 -0700701}
yro4beccbe2018-03-15 19:42:05 -0700702
Yao Chen163d2602018-04-10 10:39:53 -0700703void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs,
704 const std::vector<ConfigKey>& configs) {
705 for (const auto& key : configs) {
Yangster-macb142cc82018-03-30 15:22:08 -0700706 StatsdConfig config;
707 if (StorageManager::readConfigFromDisk(key, &config)) {
708 OnConfigUpdatedLocked(timestampNs, key, config);
709 StatsdStats::getInstance().noteConfigReset(key);
710 } else {
711 ALOGE("Failed to read backup config from disk for : %s", key.ToString().c_str());
712 auto it = mMetricsManagers.find(key);
713 if (it != mMetricsManagers.end()) {
714 it->second->refreshTtl(timestampNs);
715 }
716 }
717 }
yro4beccbe2018-03-15 19:42:05 -0700718}
719
Yao Chen163d2602018-04-10 10:39:53 -0700720void StatsLogProcessor::resetIfConfigTtlExpiredLocked(const int64_t timestampNs) {
721 std::vector<ConfigKey> configKeysTtlExpired;
722 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
723 if (it->second != nullptr && !it->second->isInTtl(timestampNs)) {
724 configKeysTtlExpired.push_back(it->first);
725 }
726 }
727 if (configKeysTtlExpired.size() > 0) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000728 WriteDataToDiskLocked(CONFIG_RESET, NO_TIME_CONSTRAINTS);
Yao Chen163d2602018-04-10 10:39:53 -0700729 resetConfigsLocked(timestampNs, configKeysTtlExpired);
730 }
731}
732
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700733void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
Yangster-macb0d06282018-01-05 15:44:07 -0800734 std::lock_guard<std::mutex> lock(mMetricsMutex);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700735 auto it = mMetricsManagers.find(key);
736 if (it != mMetricsManagers.end()) {
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700737 WriteDataToDiskLocked(key, getElapsedRealtimeNs(), CONFIG_REMOVED,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000738 NO_TIME_CONSTRAINTS);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700739 mMetricsManagers.erase(it);
David Chend6896892017-10-25 11:49:03 -0700740 mUidMap->OnConfigRemoved(key);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700741 }
Yao Chenb3561512017-11-21 18:07:17 -0800742 StatsdStats::getInstance().noteConfigRemoved(key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800743
David Chen1d7b0cd2017-11-15 14:20:04 -0800744 mLastBroadcastTimes.erase(key);
Chenjie Yufa22d652018-02-05 14:37:48 -0800745
Tej Singh6ede28b2019-01-29 17:06:54 -0800746 int uid = key.GetUid();
747 bool lastConfigForUid = true;
748 for (auto it : mMetricsManagers) {
749 if (it.first.GetUid() == uid) {
750 lastConfigForUid = false;
751 break;
752 }
753 }
754 if (lastConfigForUid) {
755 mLastActivationBroadcastTimes.erase(uid);
756 }
757
Chenjie Yufa22d652018-02-05 14:37:48 -0800758 if (mMetricsManagers.empty()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700759 mPullerManager->ForceClearPullerCache();
Chenjie Yufa22d652018-02-05 14:37:48 -0800760 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700761}
762
Tej Singh480392f2019-10-23 15:53:46 -0700763void StatsLogProcessor::flushIfNecessaryLocked(const ConfigKey& key,
764 MetricsManager& metricsManager) {
765 int64_t elapsedRealtimeNs = getElapsedRealtimeNs();
David Chend9269e22017-12-05 13:43:51 -0800766 auto lastCheckTime = mLastByteSizeTimes.find(key);
767 if (lastCheckTime != mLastByteSizeTimes.end()) {
Tej Singh480392f2019-10-23 15:53:46 -0700768 if (elapsedRealtimeNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
David Chend9269e22017-12-05 13:43:51 -0800769 return;
770 }
771 }
772
773 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
774 size_t totalBytes = metricsManager.byteSize();
Tej Singh480392f2019-10-23 15:53:46 -0700775 mLastByteSizeTimes[key] = elapsedRealtimeNs;
David Chen48944902018-05-03 10:29:11 -0700776 bool requestDump = false;
Tej Singh480392f2019-10-23 15:53:46 -0700777 if (totalBytes > StatsdStats::kMaxMetricsBytesPerConfig) {
778 // Too late. We need to start clearing data.
779 metricsManager.dropData(elapsedRealtimeNs);
Chenjie Yuc3c30c02018-10-26 09:48:07 -0700780 StatsdStats::getInstance().noteDataDropped(key, totalBytes);
David Chen12942952017-12-04 14:28:43 -0800781 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
David Chen48944902018-05-03 10:29:11 -0700782 } else if ((totalBytes > StatsdStats::kBytesPerConfigTriggerGetData) ||
783 (mOnDiskDataConfigs.find(key) != mOnDiskDataConfigs.end())) {
784 // Request to send a broadcast if:
785 // 1. in memory data > threshold OR
786 // 2. config has old data report on disk.
787 requestDump = true;
788 }
789
790 if (requestDump) {
David Chend9269e22017-12-05 13:43:51 -0800791 // Send broadcast so that receivers can pull data.
792 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
793 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
Tej Singh480392f2019-10-23 15:53:46 -0700794 if (elapsedRealtimeNs - lastBroadcastTime->second <
795 StatsdStats::kMinBroadcastPeriodNs) {
David Chend9269e22017-12-05 13:43:51 -0800796 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
David Chen1d7b0cd2017-11-15 14:20:04 -0800797 return;
798 }
799 }
David Chen48944902018-05-03 10:29:11 -0700800 if (mSendBroadcast(key)) {
801 mOnDiskDataConfigs.erase(key);
802 VLOG("StatsD triggered data fetch for %s", key.ToString().c_str());
Tej Singh480392f2019-10-23 15:53:46 -0700803 mLastBroadcastTimes[key] = elapsedRealtimeNs;
David Chen48944902018-05-03 10:29:11 -0700804 StatsdStats::getInstance().noteBroadcastSent(key);
805 }
yro31eb67b2017-10-24 13:33:21 -0700806 }
807}
808
Chenjie Yue36018b2018-04-16 15:18:30 -0700809void StatsLogProcessor::WriteDataToDiskLocked(const ConfigKey& key,
Yangster-mac892f3d32018-05-02 14:16:48 -0700810 const int64_t timestampNs,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000811 const DumpReportReason dumpReportReason,
812 const DumpLatency dumpLatency) {
yro028091c2018-05-09 16:03:27 -0700813 if (mMetricsManagers.find(key) == mMetricsManagers.end() ||
814 !mMetricsManagers.find(key)->second->shouldWriteToDisk()) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700815 return;
816 }
Yao Chen9a43b4f2019-04-10 10:43:20 -0700817 vector<uint8_t> buffer;
David Chen56ae0d92018-05-11 16:00:22 -0700818 onConfigMetricsReportLocked(key, timestampNs, true /* include_current_partial_bucket*/,
Yao Chen9a43b4f2019-04-10 10:43:20 -0700819 true /* erase_data */, dumpReportReason, dumpLatency, true,
820 &buffer);
821 string file_name =
822 StorageManager::getDataFileName((long)getWallClockSec(), key.GetUid(), key.GetId());
823 StorageManager::writeFile(file_name.c_str(), buffer.data(), buffer.size());
824
David Chen48944902018-05-03 10:29:11 -0700825 // We were able to write the ConfigMetricsReport to disk, so we should trigger collection ASAP.
826 mOnDiskDataConfigs.insert(key);
Yangster-mace68f3a52018-04-04 00:01:43 -0700827}
828
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700829void StatsLogProcessor::SaveActiveConfigsToDisk(int64_t currentTimeNs) {
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800830 std::lock_guard<std::mutex> lock(mMetricsMutex);
jianjin996f40d2019-03-29 13:53:48 -0700831 const int64_t timeNs = getElapsedRealtimeNs();
832 // Do not write to disk if we already have in the last few seconds.
jianjin996f40d2019-03-29 13:53:48 -0700833 if (static_cast<unsigned long long> (timeNs) <
834 mLastActiveMetricsWriteNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
835 ALOGI("Statsd skipping writing active metrics to disk. Already wrote data in last %d seconds",
836 WRITE_DATA_COOL_DOWN_SEC);
837 return;
838 }
839 mLastActiveMetricsWriteNs = timeNs;
840
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800841 ProtoOutputStream proto;
Tej Singhf53d4452019-05-09 18:17:59 -0700842 WriteActiveConfigsToProtoOutputStreamLocked(currentTimeNs, DEVICE_SHUTDOWN, &proto);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800843
844 string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
845 StorageManager::deleteFile(file_name.c_str());
846 android::base::unique_fd fd(
847 open(file_name.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
848 if (fd == -1) {
849 ALOGE("Attempt to write %s but failed", file_name.c_str());
850 return;
851 }
852 proto.flush(fd.get());
853}
854
Jeffrey Huangb8f54032020-03-23 13:42:42 -0700855void StatsLogProcessor::SaveMetadataToDisk(int64_t currentWallClockTimeNs,
856 int64_t systemElapsedTimeNs) {
857 std::lock_guard<std::mutex> lock(mMetricsMutex);
858 // Do not write to disk if we already have in the last few seconds.
859 if (static_cast<unsigned long long> (systemElapsedTimeNs) <
860 mLastMetadataWriteNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
861 ALOGI("Statsd skipping writing metadata to disk. Already wrote data in last %d seconds",
862 WRITE_DATA_COOL_DOWN_SEC);
863 return;
864 }
865 mLastMetadataWriteNs = systemElapsedTimeNs;
866
867 metadata::StatsMetadataList metadataList;
868 WriteMetadataToProtoLocked(
869 currentWallClockTimeNs, systemElapsedTimeNs, &metadataList);
870
871 string file_name = StringPrintf("%s/metadata", STATS_METADATA_DIR);
872 StorageManager::deleteFile(file_name.c_str());
873
874 if (metadataList.stats_metadata_size() == 0) {
875 // Skip the write if we have nothing to write.
876 return;
877 }
878
879 std::string data;
880 metadataList.SerializeToString(&data);
881 StorageManager::writeFile(file_name.c_str(), data.c_str(), data.size());
882}
883
884void StatsLogProcessor::WriteMetadataToProto(int64_t currentWallClockTimeNs,
885 int64_t systemElapsedTimeNs,
886 metadata::StatsMetadataList* metadataList) {
887 std::lock_guard<std::mutex> lock(mMetricsMutex);
888 WriteMetadataToProtoLocked(currentWallClockTimeNs, systemElapsedTimeNs, metadataList);
889}
890
891void StatsLogProcessor::WriteMetadataToProtoLocked(int64_t currentWallClockTimeNs,
892 int64_t systemElapsedTimeNs,
893 metadata::StatsMetadataList* metadataList) {
894 for (const auto& pair : mMetricsManagers) {
895 const sp<MetricsManager>& metricsManager = pair.second;
896 metadata::StatsMetadata* statsMetadata = metadataList->add_stats_metadata();
897 bool metadataWritten = metricsManager->writeMetadataToProto(currentWallClockTimeNs,
898 systemElapsedTimeNs, statsMetadata);
899 if (!metadataWritten) {
900 metadataList->mutable_stats_metadata()->RemoveLast();
901 }
902 }
903}
904
Tej Singhf53d4452019-05-09 18:17:59 -0700905void StatsLogProcessor::WriteActiveConfigsToProtoOutputStream(
906 int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto) {
907 std::lock_guard<std::mutex> lock(mMetricsMutex);
908 WriteActiveConfigsToProtoOutputStreamLocked(currentTimeNs, reason, proto);
909}
910
911void StatsLogProcessor::WriteActiveConfigsToProtoOutputStreamLocked(
912 int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto) {
913 for (const auto& pair : mMetricsManagers) {
914 const sp<MetricsManager>& metricsManager = pair.second;
915 uint64_t configToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
916 FIELD_ID_ACTIVE_CONFIG_LIST_CONFIG);
917 metricsManager->writeActiveConfigToProtoOutputStream(currentTimeNs, reason, proto);
918 proto->end(configToken);
919 }
920}
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700921void StatsLogProcessor::LoadActiveConfigsFromDisk() {
922 std::lock_guard<std::mutex> lock(mMetricsMutex);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800923 string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
924 int fd = open(file_name.c_str(), O_RDONLY | O_CLOEXEC);
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700925 if (-1 == fd) {
926 VLOG("Attempt to read %s but failed", file_name.c_str());
927 StorageManager::deleteFile(file_name.c_str());
928 return;
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800929 }
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700930 string content;
931 if (!android::base::ReadFdToString(fd, &content)) {
932 ALOGE("Attempt to read %s but failed", file_name.c_str());
933 close(fd);
934 StorageManager::deleteFile(file_name.c_str());
935 return;
936 }
937
938 close(fd);
939
940 ActiveConfigList activeConfigList;
941 if (!activeConfigList.ParseFromString(content)) {
942 ALOGE("Attempt to read %s but failed; failed to load active configs", file_name.c_str());
943 StorageManager::deleteFile(file_name.c_str());
944 return;
945 }
Tej Singhf53d4452019-05-09 18:17:59 -0700946 // Passing in mTimeBaseNs only works as long as we only load from disk is when statsd starts.
947 SetConfigsActiveStateLocked(activeConfigList, mTimeBaseNs);
948 StorageManager::deleteFile(file_name.c_str());
949}
950
951void StatsLogProcessor::SetConfigsActiveState(const ActiveConfigList& activeConfigList,
952 int64_t currentTimeNs) {
953 std::lock_guard<std::mutex> lock(mMetricsMutex);
954 SetConfigsActiveStateLocked(activeConfigList, currentTimeNs);
955}
956
957void StatsLogProcessor::SetConfigsActiveStateLocked(const ActiveConfigList& activeConfigList,
958 int64_t currentTimeNs) {
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700959 for (int i = 0; i < activeConfigList.config_size(); i++) {
960 const auto& config = activeConfigList.config(i);
961 ConfigKey key(config.uid(), config.id());
962 auto it = mMetricsManagers.find(key);
963 if (it == mMetricsManagers.end()) {
964 ALOGE("No config found for config %s", key.ToString().c_str());
965 continue;
966 }
967 VLOG("Setting active config %s", key.ToString().c_str());
Tej Singhf53d4452019-05-09 18:17:59 -0700968 it->second->loadActiveConfig(config, currentTimeNs);
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700969 }
970 VLOG("Successfully loaded %d active configs.", activeConfigList.config_size());
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800971}
972
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000973void StatsLogProcessor::WriteDataToDiskLocked(const DumpReportReason dumpReportReason,
974 const DumpLatency dumpLatency) {
Yangster-mac892f3d32018-05-02 14:16:48 -0700975 const int64_t timeNs = getElapsedRealtimeNs();
Tej Singh42f9e062018-11-09 10:01:00 -0800976 // Do not write to disk if we already have in the last few seconds.
977 // This is to avoid overwriting files that would have the same name if we
978 // write twice in the same second.
979 if (static_cast<unsigned long long> (timeNs) <
980 mLastWriteTimeNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
981 ALOGI("Statsd skipping writing data to disk. Already wrote data in last %d seconds",
982 WRITE_DATA_COOL_DOWN_SEC);
983 return;
984 }
985 mLastWriteTimeNs = timeNs;
Yangster-mace68f3a52018-04-04 00:01:43 -0700986 for (auto& pair : mMetricsManagers) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000987 WriteDataToDiskLocked(pair.first, timeNs, dumpReportReason, dumpLatency);
Yangster-mace68f3a52018-04-04 00:01:43 -0700988 }
989}
990
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700991void StatsLogProcessor::WriteDataToDisk(const DumpReportReason dumpReportReason,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000992 const DumpLatency dumpLatency) {
Yangster-macb0d06282018-01-05 15:44:07 -0800993 std::lock_guard<std::mutex> lock(mMetricsMutex);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000994 WriteDataToDiskLocked(dumpReportReason, dumpLatency);
yro947fbce2017-11-15 22:50:23 -0800995}
996
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700997void StatsLogProcessor::informPullAlarmFired(const int64_t timestampNs) {
Yangster6df5fcc2018-04-12 11:04:29 -0700998 std::lock_guard<std::mutex> lock(mMetricsMutex);
Chenjie Yue2219202018-06-08 10:07:51 -0700999 mPullerManager->OnAlarmFired(timestampNs);
Yangster-mac15f6bbc2018-04-08 11:52:26 -07001000}
1001
David Chend37bc232018-04-12 18:05:11 -07001002int64_t StatsLogProcessor::getLastReportTimeNs(const ConfigKey& key) {
1003 auto it = mMetricsManagers.find(key);
1004 if (it == mMetricsManagers.end()) {
1005 return 0;
1006 } else {
1007 return it->second->getLastReportTimeNs();
1008 }
1009}
1010
Tej Singh9ec159a2019-11-14 11:59:48 -08001011void StatsLogProcessor::notifyAppUpgrade(const int64_t& eventTimeNs, const string& apk,
1012 const int uid, const int64_t version) {
1013 std::lock_guard<std::mutex> lock(mMetricsMutex);
1014 ALOGW("Received app upgrade");
1015 for (auto it : mMetricsManagers) {
1016 it.second->notifyAppUpgrade(eventTimeNs, apk, uid, version);
1017 }
1018}
1019
1020void StatsLogProcessor::notifyAppRemoved(const int64_t& eventTimeNs, const string& apk,
1021 const int uid) {
1022 std::lock_guard<std::mutex> lock(mMetricsMutex);
1023 ALOGW("Received app removed");
1024 for (auto it : mMetricsManagers) {
1025 it.second->notifyAppRemoved(eventTimeNs, apk, uid);
1026 }
1027}
1028
1029void StatsLogProcessor::onUidMapReceived(const int64_t& eventTimeNs) {
1030 std::lock_guard<std::mutex> lock(mMetricsMutex);
1031 ALOGW("Received uid map");
1032 for (auto it : mMetricsManagers) {
1033 it.second->onUidMapReceived(eventTimeNs);
1034 }
1035}
1036
David Chen48944902018-05-03 10:29:11 -07001037void StatsLogProcessor::noteOnDiskData(const ConfigKey& key) {
1038 std::lock_guard<std::mutex> lock(mMetricsMutex);
1039 mOnDiskDataConfigs.insert(key);
1040}
1041
Yao Chenef99c4f2017-09-22 16:26:54 -07001042} // namespace statsd
1043} // namespace os
1044} // namespace android