1 /*
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
17 #define STATSD_DEBUG false // STOPSHIP if true
18 #include "Log.h"
19
20 #include "StatsLogProcessor.h"
21
22 #include <android-base/file.h>
23 #include <android-modules-utils/sdk_level.h>
24 #include <cutils/multiuser.h>
25 #include <src/active_config_list.pb.h>
26 #include <src/experiment_ids.pb.h>
27
28 #include "StatsService.h"
29 #include "android-base/stringprintf.h"
30 #include "external/StatsPullerManager.h"
31 #include "flags/FlagProvider.h"
32 #include "guardrail/StatsdStats.h"
33 #include "logd/LogEvent.h"
34 #include "metrics/CountMetricProducer.h"
35 #include "state/StateManager.h"
36 #include "stats_log_util.h"
37 #include "stats_util.h"
38 #include "statslog_statsd.h"
39 #include "storage/StorageManager.h"
40
41 using namespace android;
42 using android::base::StringPrintf;
43 using android::modules::sdklevel::IsAtLeastU;
44 using android::util::FIELD_COUNT_REPEATED;
45 using android::util::FIELD_TYPE_BOOL;
46 using android::util::FIELD_TYPE_FLOAT;
47 using android::util::FIELD_TYPE_INT32;
48 using android::util::FIELD_TYPE_INT64;
49 using android::util::FIELD_TYPE_MESSAGE;
50 using android::util::FIELD_TYPE_STRING;
51 using android::util::ProtoOutputStream;
52 using std::vector;
53
54 namespace android {
55 namespace os {
56 namespace statsd {
57
58 using aidl::android::os::IStatsQueryCallback;
59
60 // for ConfigMetricsReportList
61 const int FIELD_ID_CONFIG_KEY = 1;
62 const int FIELD_ID_REPORTS = 2;
63 // for ConfigKey
64 const int FIELD_ID_UID = 1;
65 const int FIELD_ID_ID = 2;
66 // for ConfigMetricsReport
67 // const int FIELD_ID_METRICS = 1; // written in MetricsManager.cpp
68 const int FIELD_ID_UID_MAP = 2;
69 const int FIELD_ID_LAST_REPORT_ELAPSED_NANOS = 3;
70 const int FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS = 4;
71 const int FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS = 5;
72 const int FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS = 6;
73 const int FIELD_ID_DUMP_REPORT_REASON = 8;
74 const int FIELD_ID_STRINGS = 9;
75
76 // for ActiveConfigList
77 const int FIELD_ID_ACTIVE_CONFIG_LIST_CONFIG = 1;
78
79 // for permissions checks
80 constexpr const char* kPermissionDump = "android.permission.DUMP";
81 constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
82
83 #define NS_PER_HOUR 3600 * NS_PER_SEC
84
85 #define STATS_ACTIVE_METRIC_DIR "/data/misc/stats-active-metric"
86 #define STATS_METADATA_DIR "/data/misc/stats-metadata"
87
88 // Cool down period for writing data to disk to avoid overwriting files.
89 #define WRITE_DATA_COOL_DOWN_SEC 15
90
StatsLogProcessor(const sp<UidMap> & uidMap,const sp<StatsPullerManager> & pullerManager,const sp<AlarmMonitor> & anomalyAlarmMonitor,const sp<AlarmMonitor> & periodicAlarmMonitor,const int64_t timeBaseNs,const std::function<bool (const ConfigKey &)> & sendBroadcast,const std::function<bool (const int &,const vector<int64_t> &)> & activateBroadcast,const std::function<void (const ConfigKey &,const string &,const vector<int64_t> &)> & sendRestrictedMetricsBroadcast,const std::shared_ptr<LogEventFilter> & logEventFilter)91 StatsLogProcessor::StatsLogProcessor(
92 const sp<UidMap>& uidMap, const sp<StatsPullerManager>& pullerManager,
93 const sp<AlarmMonitor>& anomalyAlarmMonitor, const sp<AlarmMonitor>& periodicAlarmMonitor,
94 const int64_t timeBaseNs, const std::function<bool(const ConfigKey&)>& sendBroadcast,
95 const std::function<bool(const int&, const vector<int64_t>&)>& activateBroadcast,
96 const std::function<void(const ConfigKey&, const string&, const vector<int64_t>&)>&
97 sendRestrictedMetricsBroadcast,
98 const std::shared_ptr<LogEventFilter>& logEventFilter)
99 : mLastTtlTime(0),
100 mLastFlushRestrictedTime(0),
101 mLastDbGuardrailEnforcementTime(0),
102 mUidMap(uidMap),
103 mPullerManager(pullerManager),
104 mAnomalyAlarmMonitor(anomalyAlarmMonitor),
105 mPeriodicAlarmMonitor(periodicAlarmMonitor),
106 mLogEventFilter(logEventFilter),
107 mSendBroadcast(sendBroadcast),
108 mSendActivationBroadcast(activateBroadcast),
109 mSendRestrictedMetricsBroadcast(sendRestrictedMetricsBroadcast),
110 mTimeBaseNs(timeBaseNs),
111 mLargestTimestampSeen(0),
112 mLastTimestampSeen(0) {
113 mPullerManager->ForceClearPullerCache();
114 StateManager::getInstance().updateLogSources(uidMap);
115 // It is safe called locked version at constructor - no concurrent access possible
116 updateLogEventFilterLocked();
117 }
118
~StatsLogProcessor()119 StatsLogProcessor::~StatsLogProcessor() {
120 }
121
flushProtoToBuffer(ProtoOutputStream & proto,vector<uint8_t> * outData)122 static void flushProtoToBuffer(ProtoOutputStream& proto, vector<uint8_t>* outData) {
123 outData->clear();
124 outData->resize(proto.size());
125 size_t pos = 0;
126 sp<android::util::ProtoReader> reader = proto.data();
127 while (reader->readBuffer() != NULL) {
128 size_t toRead = reader->currentToRead();
129 std::memcpy(&((*outData)[pos]), reader->readBuffer(), toRead);
130 pos += toRead;
131 reader->move(toRead);
132 }
133 }
134
processFiredAnomalyAlarmsLocked(const int64_t & timestampNs,unordered_set<sp<const InternalAlarm>,SpHash<InternalAlarm>> & alarmSet)135 void StatsLogProcessor::processFiredAnomalyAlarmsLocked(
136 const int64_t& timestampNs,
137 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& alarmSet) {
138 for (const auto& itr : mMetricsManagers) {
139 itr.second->onAnomalyAlarmFired(timestampNs, alarmSet);
140 }
141 }
onPeriodicAlarmFired(const int64_t & timestampNs,unordered_set<sp<const InternalAlarm>,SpHash<InternalAlarm>> & alarmSet)142 void StatsLogProcessor::onPeriodicAlarmFired(
143 const int64_t& timestampNs,
144 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& alarmSet) {
145 std::lock_guard<std::mutex> lock(mMetricsMutex);
146 for (const auto& itr : mMetricsManagers) {
147 itr.second->onPeriodicAlarmFired(timestampNs, alarmSet);
148 }
149 }
150
mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent * event) const151 void StatsLogProcessor::mapIsolatedUidToHostUidIfNecessaryLocked(LogEvent* event) const {
152 if (std::pair<size_t, size_t> indexRange; event->hasAttributionChain(&indexRange)) {
153 vector<FieldValue>* const fieldValues = event->getMutableValues();
154 for (size_t i = indexRange.first; i <= indexRange.second; i++) {
155 FieldValue& fieldValue = fieldValues->at(i);
156 if (isAttributionUidField(fieldValue)) {
157 const int hostUid = mUidMap->getHostUidOrSelf(fieldValue.mValue.int_value);
158 fieldValue.mValue.setInt(hostUid);
159 }
160 }
161 } else {
162 mapIsolatedUidsToHostUidInLogEvent(mUidMap, *event);
163 }
164 }
165
onIsolatedUidChangedEventLocked(const LogEvent & event)166 void StatsLogProcessor::onIsolatedUidChangedEventLocked(const LogEvent& event) {
167 status_t err = NO_ERROR, err2 = NO_ERROR, err3 = NO_ERROR;
168 bool is_create = event.GetBool(3, &err);
169 auto parent_uid = int(event.GetLong(1, &err2));
170 auto isolated_uid = int(event.GetLong(2, &err3));
171 if (err == NO_ERROR && err2 == NO_ERROR && err3 == NO_ERROR) {
172 if (is_create) {
173 mUidMap->assignIsolatedUid(isolated_uid, parent_uid);
174 } else {
175 mUidMap->removeIsolatedUid(isolated_uid);
176 }
177 } else {
178 ALOGE("Failed to parse uid in the isolated uid change event.");
179 }
180 }
181
onBinaryPushStateChangedEventLocked(LogEvent * event)182 void StatsLogProcessor::onBinaryPushStateChangedEventLocked(LogEvent* event) {
183 pid_t pid = event->GetPid();
184 uid_t uid = event->GetUid();
185 if (!checkPermissionForIds(kPermissionDump, pid, uid) ||
186 !checkPermissionForIds(kPermissionUsage, pid, uid)) {
187 return;
188 }
189 // The Get* functions don't modify the status on success, they only write in
190 // failure statuses, so we can use one status variable for all calls then
191 // check if it is no longer NO_ERROR.
192 status_t err = NO_ERROR;
193 InstallTrainInfo trainInfo;
194 trainInfo.trainName = string(event->GetString(1 /*train name field id*/, &err));
195 trainInfo.trainVersionCode = event->GetLong(2 /*train version field id*/, &err);
196 trainInfo.requiresStaging = event->GetBool(3 /*requires staging field id*/, &err);
197 trainInfo.rollbackEnabled = event->GetBool(4 /*rollback enabled field id*/, &err);
198 trainInfo.requiresLowLatencyMonitor =
199 event->GetBool(5 /*requires low latency monitor field id*/, &err);
200 trainInfo.status = int32_t(event->GetLong(6 /*state field id*/, &err));
201 std::vector<uint8_t> trainExperimentIdBytes =
202 event->GetStorage(7 /*experiment ids field id*/, &err);
203 bool is_rollback = event->GetBool(10 /*is rollback field id*/, &err);
204
205 if (err != NO_ERROR) {
206 ALOGE("Failed to parse fields in binary push state changed log event");
207 return;
208 }
209 ExperimentIds trainExperimentIds;
210 if (!trainExperimentIds.ParseFromArray(trainExperimentIdBytes.data(),
211 trainExperimentIdBytes.size())) {
212 ALOGE("Failed to parse experimentids in binary push state changed.");
213 return;
214 }
215 trainInfo.experimentIds = {trainExperimentIds.experiment_id().begin(),
216 trainExperimentIds.experiment_id().end()};
217
218 // Update the train info on disk and get any data the logevent is missing.
219 getAndUpdateTrainInfoOnDisk(is_rollback, &trainInfo);
220
221 std::vector<uint8_t> trainExperimentIdProto;
222 writeExperimentIdsToProto(trainInfo.experimentIds, &trainExperimentIdProto);
223 int32_t userId = multiuser_get_user_id(uid);
224
225 event->updateValue(2 /*train version field id*/, trainInfo.trainVersionCode, LONG);
226 event->updateValue(7 /*experiment ids field id*/, trainExperimentIdProto, STORAGE);
227 event->updateValue(8 /*user id field id*/, userId, INT);
228
229 // If this event is a rollback event, then the following bits in the event
230 // are invalid and we will need to update them with the values we pulled
231 // from disk.
232 if (is_rollback) {
233 int bit = trainInfo.requiresStaging ? 1 : 0;
234 event->updateValue(3 /*requires staging field id*/, bit, INT);
235 bit = trainInfo.rollbackEnabled ? 1 : 0;
236 event->updateValue(4 /*rollback enabled field id*/, bit, INT);
237 bit = trainInfo.requiresLowLatencyMonitor ? 1 : 0;
238 event->updateValue(5 /*requires low latency monitor field id*/, bit, INT);
239 }
240 }
241
getAndUpdateTrainInfoOnDisk(bool is_rollback,InstallTrainInfo * trainInfo)242 void StatsLogProcessor::getAndUpdateTrainInfoOnDisk(bool is_rollback,
243 InstallTrainInfo* trainInfo) {
244 // If the train name is empty, we don't know which train to attribute the
245 // event to, so return early.
246 if (trainInfo->trainName.empty()) {
247 return;
248 }
249 bool readTrainInfoSuccess = false;
250 InstallTrainInfo trainInfoOnDisk;
251 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfo->trainName, trainInfoOnDisk);
252
253 bool resetExperimentIds = false;
254 if (readTrainInfoSuccess) {
255 // Keep the old train version if we received an empty version.
256 if (trainInfo->trainVersionCode == -1) {
257 trainInfo->trainVersionCode = trainInfoOnDisk.trainVersionCode;
258 } else if (trainInfo->trainVersionCode != trainInfoOnDisk.trainVersionCode) {
259 // Reset experiment ids if we receive a new non-empty train version.
260 resetExperimentIds = true;
261 }
262
263 // Reset if we received a different experiment id.
264 if (!trainInfo->experimentIds.empty() &&
265 (trainInfoOnDisk.experimentIds.empty() ||
266 trainInfo->experimentIds.at(0) != trainInfoOnDisk.experimentIds[0])) {
267 resetExperimentIds = true;
268 }
269 }
270
271 // Find the right experiment IDs
272 if ((!resetExperimentIds || is_rollback) && readTrainInfoSuccess) {
273 trainInfo->experimentIds = trainInfoOnDisk.experimentIds;
274 }
275
276 if (!trainInfo->experimentIds.empty()) {
277 int64_t firstId = trainInfo->experimentIds.at(0);
278 auto& ids = trainInfo->experimentIds;
279 switch (trainInfo->status) {
280 case util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALL_SUCCESS:
281 if (find(ids.begin(), ids.end(), firstId + 1) == ids.end()) {
282 ids.push_back(firstId + 1);
283 }
284 break;
285 case util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_INITIATED:
286 if (find(ids.begin(), ids.end(), firstId + 2) == ids.end()) {
287 ids.push_back(firstId + 2);
288 }
289 break;
290 case util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_SUCCESS:
291 if (find(ids.begin(), ids.end(), firstId + 3) == ids.end()) {
292 ids.push_back(firstId + 3);
293 }
294 break;
295 }
296 }
297
298 // If this event is a rollback event, the following fields are invalid and
299 // need to be replaced by the fields stored to disk.
300 if (is_rollback) {
301 trainInfo->requiresStaging = trainInfoOnDisk.requiresStaging;
302 trainInfo->rollbackEnabled = trainInfoOnDisk.rollbackEnabled;
303 trainInfo->requiresLowLatencyMonitor = trainInfoOnDisk.requiresLowLatencyMonitor;
304 }
305
306 StorageManager::writeTrainInfo(*trainInfo);
307 }
308
onWatchdogRollbackOccurredLocked(LogEvent * event)309 void StatsLogProcessor::onWatchdogRollbackOccurredLocked(LogEvent* event) {
310 pid_t pid = event->GetPid();
311 uid_t uid = event->GetUid();
312 if (!checkPermissionForIds(kPermissionDump, pid, uid) ||
313 !checkPermissionForIds(kPermissionUsage, pid, uid)) {
314 return;
315 }
316 // The Get* functions don't modify the status on success, they only write in
317 // failure statuses, so we can use one status variable for all calls then
318 // check if it is no longer NO_ERROR.
319 status_t err = NO_ERROR;
320 int32_t rollbackType = int32_t(event->GetInt(1 /*rollback type field id*/, &err));
321 string packageName = string(event->GetString(2 /*package name field id*/, &err));
322
323 if (err != NO_ERROR) {
324 ALOGE("Failed to parse fields in watchdog rollback occurred log event");
325 return;
326 }
327
328 vector<int64_t> experimentIds =
329 processWatchdogRollbackOccurred(rollbackType, packageName);
330 vector<uint8_t> experimentIdProto;
331 writeExperimentIdsToProto(experimentIds, &experimentIdProto);
332
333 event->updateValue(6 /*experiment ids field id*/, experimentIdProto, STORAGE);
334 }
335
processWatchdogRollbackOccurred(const int32_t rollbackTypeIn,const string & packageNameIn)336 vector<int64_t> StatsLogProcessor::processWatchdogRollbackOccurred(const int32_t rollbackTypeIn,
337 const string& packageNameIn) {
338 // If the package name is empty, we can't attribute it to any train, so
339 // return early.
340 if (packageNameIn.empty()) {
341 return vector<int64_t>();
342 }
343 bool readTrainInfoSuccess = false;
344 InstallTrainInfo trainInfoOnDisk;
345 // We use the package name of the event as the train name.
346 readTrainInfoSuccess = StorageManager::readTrainInfo(packageNameIn, trainInfoOnDisk);
347
348 if (!readTrainInfoSuccess) {
349 return vector<int64_t>();
350 }
351
352 if (trainInfoOnDisk.experimentIds.empty()) {
353 return vector<int64_t>();
354 }
355
356 int64_t firstId = trainInfoOnDisk.experimentIds[0];
357 auto& ids = trainInfoOnDisk.experimentIds;
358 switch (rollbackTypeIn) {
359 case util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE:
360 if (find(ids.begin(), ids.end(), firstId + 4) == ids.end()) {
361 ids.push_back(firstId + 4);
362 }
363 StorageManager::writeTrainInfo(trainInfoOnDisk);
364 break;
365 case util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS:
366 if (find(ids.begin(), ids.end(), firstId + 5) == ids.end()) {
367 ids.push_back(firstId + 5);
368 }
369 StorageManager::writeTrainInfo(trainInfoOnDisk);
370 break;
371 }
372
373 return trainInfoOnDisk.experimentIds;
374 }
375
resetConfigs()376 void StatsLogProcessor::resetConfigs() {
377 std::lock_guard<std::mutex> lock(mMetricsMutex);
378 resetConfigsLocked(getElapsedRealtimeNs());
379 }
380
resetConfigsLocked(const int64_t timestampNs)381 void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs) {
382 std::vector<ConfigKey> configKeys;
383 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
384 configKeys.push_back(it->first);
385 }
386 resetConfigsLocked(timestampNs, configKeys);
387 }
388
OnLogEvent(LogEvent * event)389 void StatsLogProcessor::OnLogEvent(LogEvent* event) {
390 OnLogEvent(event, getElapsedRealtimeNs());
391 }
392
OnLogEvent(LogEvent * event,int64_t elapsedRealtimeNs)393 void StatsLogProcessor::OnLogEvent(LogEvent* event, int64_t elapsedRealtimeNs) {
394 std::lock_guard<std::mutex> lock(mMetricsMutex);
395
396 // Tell StatsdStats about new event
397 const int64_t eventElapsedTimeNs = event->GetElapsedTimestampNs();
398 const int atomId = event->GetTagId();
399 StatsdStats::getInstance().noteAtomLogged(atomId, eventElapsedTimeNs / NS_PER_SEC,
400 event->isParsedHeaderOnly());
401 if (!event->isValid()) {
402 StatsdStats::getInstance().noteAtomError(atomId);
403 return;
404 }
405
406 // Hard-coded logic to update train info on disk and fill in any information
407 // this log event may be missing.
408 if (atomId == util::BINARY_PUSH_STATE_CHANGED) {
409 onBinaryPushStateChangedEventLocked(event);
410 }
411
412 // Hard-coded logic to update experiment ids on disk for certain rollback
413 // types and fill the rollback atom with experiment ids
414 if (atomId == util::WATCHDOG_ROLLBACK_OCCURRED) {
415 onWatchdogRollbackOccurredLocked(event);
416 }
417
418 if (mPrintAllLogs) {
419 ALOGI("%s", event->ToString().c_str());
420 }
421 resetIfConfigTtlExpiredLocked(eventElapsedTimeNs);
422
423 // Hard-coded logic to update the isolated uid's in the uid-map.
424 // The field numbers need to be currently updated by hand with atoms.proto
425 if (atomId == util::ISOLATED_UID_CHANGED) {
426 onIsolatedUidChangedEventLocked(*event);
427 } else {
428 // Map the isolated uid to host uid if necessary.
429 mapIsolatedUidToHostUidIfNecessaryLocked(event);
430 }
431
432 StateManager::getInstance().onLogEvent(*event);
433
434 if (mMetricsManagers.empty()) {
435 return;
436 }
437
438 bool fireAlarm = false;
439 {
440 std::lock_guard<std::mutex> anomalyLock(mAnomalyAlarmMutex);
441 if (mNextAnomalyAlarmTime != 0 &&
442 MillisToNano(mNextAnomalyAlarmTime) <= elapsedRealtimeNs) {
443 mNextAnomalyAlarmTime = 0;
444 VLOG("informing anomaly alarm at time %lld", (long long)elapsedRealtimeNs);
445 fireAlarm = true;
446 }
447 }
448 if (fireAlarm) {
449 informAnomalyAlarmFiredLocked(NanoToMillis(elapsedRealtimeNs));
450 }
451
452 const int64_t curTimeSec = getElapsedRealtimeSec();
453 if (curTimeSec - mLastPullerCacheClearTimeSec > StatsdStats::kPullerCacheClearIntervalSec) {
454 mPullerManager->ClearPullerCacheIfNecessary(curTimeSec * NS_PER_SEC);
455 mLastPullerCacheClearTimeSec = curTimeSec;
456 }
457
458 flushRestrictedDataIfNecessaryLocked(elapsedRealtimeNs);
459 enforceDataTtlsIfNecessaryLocked(getWallClockNs(), elapsedRealtimeNs);
460 enforceDbGuardrailsIfNecessaryLocked(getWallClockNs(), elapsedRealtimeNs);
461
462 std::unordered_set<int> uidsWithActiveConfigsChanged;
463 std::unordered_map<int, std::vector<int64_t>> activeConfigsPerUid;
464
465 // pass the event to metrics managers.
466 for (auto& pair : mMetricsManagers) {
467 if (event->isRestricted() && !pair.second->hasRestrictedMetricsDelegate()) {
468 continue;
469 }
470 int uid = pair.first.GetUid();
471 int64_t configId = pair.first.GetId();
472 bool isPrevActive = pair.second->isActive();
473 pair.second->onLogEvent(*event);
474 bool isCurActive = pair.second->isActive();
475 // Map all active configs by uid.
476 if (isCurActive) {
477 auto activeConfigs = activeConfigsPerUid.find(uid);
478 if (activeConfigs != activeConfigsPerUid.end()) {
479 activeConfigs->second.push_back(configId);
480 } else {
481 vector<int64_t> newActiveConfigs;
482 newActiveConfigs.push_back(configId);
483 activeConfigsPerUid[uid] = newActiveConfigs;
484 }
485 }
486 // The activation state of this config changed.
487 if (isPrevActive != isCurActive) {
488 VLOG("Active status changed for uid %d", uid);
489 uidsWithActiveConfigsChanged.insert(uid);
490 StatsdStats::getInstance().noteActiveStatusChanged(pair.first, isCurActive);
491 }
492 flushIfNecessaryLocked(pair.first, *(pair.second));
493 }
494
495 // Don't use the event timestamp for the guardrail.
496 for (int uid : uidsWithActiveConfigsChanged) {
497 // Send broadcast so that receivers can pull data.
498 auto lastBroadcastTime = mLastActivationBroadcastTimes.find(uid);
499 if (lastBroadcastTime != mLastActivationBroadcastTimes.end()) {
500 if (elapsedRealtimeNs - lastBroadcastTime->second <
501 StatsdStats::kMinActivationBroadcastPeriodNs) {
502 StatsdStats::getInstance().noteActivationBroadcastGuardrailHit(uid);
503 VLOG("StatsD would've sent an activation broadcast but the rate limit stopped us.");
504 return;
505 }
506 }
507 auto activeConfigs = activeConfigsPerUid.find(uid);
508 if (activeConfigs != activeConfigsPerUid.end()) {
509 if (mSendActivationBroadcast(uid, activeConfigs->second)) {
510 VLOG("StatsD sent activation notice for uid %d", uid);
511 mLastActivationBroadcastTimes[uid] = elapsedRealtimeNs;
512 }
513 } else {
514 std::vector<int64_t> emptyActiveConfigs;
515 if (mSendActivationBroadcast(uid, emptyActiveConfigs)) {
516 VLOG("StatsD sent EMPTY activation notice for uid %d", uid);
517 mLastActivationBroadcastTimes[uid] = elapsedRealtimeNs;
518 }
519 }
520 }
521 }
522
GetActiveConfigs(const int uid,vector<int64_t> & outActiveConfigs)523 void StatsLogProcessor::GetActiveConfigs(const int uid, vector<int64_t>& outActiveConfigs) {
524 std::lock_guard<std::mutex> lock(mMetricsMutex);
525 GetActiveConfigsLocked(uid, outActiveConfigs);
526 }
527
GetActiveConfigsLocked(const int uid,vector<int64_t> & outActiveConfigs)528 void StatsLogProcessor::GetActiveConfigsLocked(const int uid, vector<int64_t>& outActiveConfigs) {
529 outActiveConfigs.clear();
530 for (auto& pair : mMetricsManagers) {
531 if (pair.first.GetUid() == uid && pair.second->isActive()) {
532 outActiveConfigs.push_back(pair.first.GetId());
533 }
534 }
535 }
536
OnConfigUpdated(const int64_t timestampNs,const int64_t wallClockNs,const ConfigKey & key,const StatsdConfig & config,bool modularUpdate)537 void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const int64_t wallClockNs,
538 const ConfigKey& key, const StatsdConfig& config,
539 bool modularUpdate) {
540 std::lock_guard<std::mutex> lock(mMetricsMutex);
541 WriteDataToDiskLocked(key, timestampNs, wallClockNs, CONFIG_UPDATED, NO_TIME_CONSTRAINTS);
542 OnConfigUpdatedLocked(timestampNs, key, config, modularUpdate);
543 }
544
OnConfigUpdated(const int64_t timestampNs,const ConfigKey & key,const StatsdConfig & config,bool modularUpdate)545 void StatsLogProcessor::OnConfigUpdated(const int64_t timestampNs, const ConfigKey& key,
546 const StatsdConfig& config, bool modularUpdate) {
547 OnConfigUpdated(timestampNs, getWallClockNs(), key, config, modularUpdate);
548 }
549
OnConfigUpdatedLocked(const int64_t timestampNs,const ConfigKey & key,const StatsdConfig & config,bool modularUpdate)550 void StatsLogProcessor::OnConfigUpdatedLocked(const int64_t timestampNs, const ConfigKey& key,
551 const StatsdConfig& config, bool modularUpdate) {
552 VLOG("Updated configuration for key %s", key.ToString().c_str());
553 const auto& it = mMetricsManagers.find(key);
554 bool configValid = false;
555 if (IsAtLeastU() && it != mMetricsManagers.end()) {
556 if (it->second->hasRestrictedMetricsDelegate() !=
557 config.has_restricted_metrics_delegate_package_name()) {
558 // Not a modular update if has_restricted_metrics_delegate changes
559 modularUpdate = false;
560 }
561 if (!modularUpdate && it->second->hasRestrictedMetricsDelegate()) {
562 // Always delete the old db if restricted metrics config is not a
563 // modular update.
564 dbutils::deleteDb(key);
565 }
566 }
567 // Create new config if this is not a modular update or if this is a new config.
568 if (!modularUpdate || it == mMetricsManagers.end()) {
569 sp<MetricsManager> newMetricsManager =
570 new MetricsManager(key, config, mTimeBaseNs, timestampNs, mUidMap, mPullerManager,
571 mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
572 configValid = newMetricsManager->isConfigValid();
573 if (configValid) {
574 newMetricsManager->init();
575 newMetricsManager->refreshTtl(timestampNs);
576 // Sdk check for U+ is unnecessary because config with restricted metrics delegate
577 // will be invalid on non U+ devices.
578 if (newMetricsManager->hasRestrictedMetricsDelegate()) {
579 mSendRestrictedMetricsBroadcast(key,
580 newMetricsManager->getRestrictedMetricsDelegate(),
581 newMetricsManager->getAllMetricIds());
582 string err;
583 if (!dbutils::updateDeviceInfoTable(key, err)) {
584 ALOGE("Failed to create device_info table for configKey %s, err: %s",
585 key.ToString().c_str(), err.c_str());
586 StatsdStats::getInstance().noteDeviceInfoTableCreationFailed(key);
587 }
588 } else if (it != mMetricsManagers.end() && it->second->hasRestrictedMetricsDelegate()) {
589 mSendRestrictedMetricsBroadcast(key, it->second->getRestrictedMetricsDelegate(),
590 {});
591 }
592 mMetricsManagers[key] = newMetricsManager;
593 VLOG("StatsdConfig valid");
594 }
595 } else {
596 // Preserve the existing MetricsManager, update necessary components and metadata in place.
597 configValid = it->second->updateConfig(config, mTimeBaseNs, timestampNs,
598 mAnomalyAlarmMonitor, mPeriodicAlarmMonitor);
599 if (configValid && it->second->hasRestrictedMetricsDelegate()) {
600 mSendRestrictedMetricsBroadcast(key, it->second->getRestrictedMetricsDelegate(),
601 it->second->getAllMetricIds());
602 }
603 }
604
605 if (configValid && !config.has_restricted_metrics_delegate_package_name()) {
606 // We do not need to track uid map changes for restricted metrics since the uidmap is not
607 // stored in the sqlite db.
608 mUidMap->OnConfigUpdated(key);
609 } else if (configValid && config.has_restricted_metrics_delegate_package_name()) {
610 mUidMap->OnConfigRemoved(key);
611 }
612 if (!configValid) {
613 // If there is any error in the config, don't use it.
614 // Remove any existing config with the same key.
615 ALOGE("StatsdConfig NOT valid");
616 // Send an empty restricted metrics broadcast if the previous config was restricted.
617 if (IsAtLeastU() && it != mMetricsManagers.end() &&
618 it->second->hasRestrictedMetricsDelegate()) {
619 mSendRestrictedMetricsBroadcast(key, it->second->getRestrictedMetricsDelegate(), {});
620 dbutils::deleteDb(key);
621 }
622 mMetricsManagers.erase(key);
623 mUidMap->OnConfigRemoved(key);
624 }
625
626 updateLogEventFilterLocked();
627 }
628
GetMetricsSize(const ConfigKey & key) const629 size_t StatsLogProcessor::GetMetricsSize(const ConfigKey& key) const {
630 std::lock_guard<std::mutex> lock(mMetricsMutex);
631 auto it = mMetricsManagers.find(key);
632 if (it == mMetricsManagers.end()) {
633 ALOGW("Config source %s does not exist", key.ToString().c_str());
634 return 0;
635 }
636 return it->second->byteSize();
637 }
638
dumpStates(int out,bool verbose)639 void StatsLogProcessor::dumpStates(int out, bool verbose) {
640 std::lock_guard<std::mutex> lock(mMetricsMutex);
641 FILE* fout = fdopen(out, "w");
642 if (fout == NULL) {
643 return;
644 }
645 fprintf(fout, "MetricsManager count: %lu\n", (unsigned long)mMetricsManagers.size());
646 for (auto metricsManager : mMetricsManagers) {
647 metricsManager.second->dumpStates(fout, verbose);
648 }
649
650 fclose(fout);
651 }
652
653 /*
654 * onDumpReport dumps serialized ConfigMetricsReportList into proto.
655 */
onDumpReport(const ConfigKey & key,const int64_t dumpTimeStampNs,const int64_t wallClockNs,const bool include_current_partial_bucket,const bool erase_data,const DumpReportReason dumpReportReason,const DumpLatency dumpLatency,ProtoOutputStream * proto)656 void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
657 const int64_t wallClockNs,
658 const bool include_current_partial_bucket,
659 const bool erase_data, const DumpReportReason dumpReportReason,
660 const DumpLatency dumpLatency, ProtoOutputStream* proto) {
661 std::lock_guard<std::mutex> lock(mMetricsMutex);
662
663 auto it = mMetricsManagers.find(key);
664 if (it != mMetricsManagers.end() && it->second->hasRestrictedMetricsDelegate()) {
665 VLOG("Unexpected call to StatsLogProcessor::onDumpReport for restricted metrics.");
666 return;
667 }
668
669 // Start of ConfigKey.
670 uint64_t configKeyToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_ID_CONFIG_KEY);
671 proto->write(FIELD_TYPE_INT32 | FIELD_ID_UID, key.GetUid());
672 proto->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)key.GetId());
673 proto->end(configKeyToken);
674 // End of ConfigKey.
675
676 bool keepFile = false;
677 if (it != mMetricsManagers.end() && it->second->shouldPersistLocalHistory()) {
678 keepFile = true;
679 }
680
681 // Then, check stats-data directory to see there's any file containing
682 // ConfigMetricsReport from previous shutdowns to concatenate to reports.
683 StorageManager::appendConfigMetricsReport(
684 key, proto, erase_data && !keepFile /* should remove file after appending it */,
685 dumpReportReason == ADB_DUMP /*if caller is adb*/);
686
687 if (it != mMetricsManagers.end()) {
688 // This allows another broadcast to be sent within the rate-limit period if we get close to
689 // filling the buffer again soon.
690 mLastBroadcastTimes.erase(key);
691
692 vector<uint8_t> buffer;
693 onConfigMetricsReportLocked(key, dumpTimeStampNs, wallClockNs,
694 include_current_partial_bucket, erase_data, dumpReportReason,
695 dumpLatency, false /* is this data going to be saved on disk */,
696 &buffer);
697 proto->write(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS,
698 reinterpret_cast<char*>(buffer.data()), buffer.size());
699 } else {
700 ALOGW("Config source %s does not exist", key.ToString().c_str());
701 }
702 }
703
704 /*
705 * onDumpReport dumps serialized ConfigMetricsReportList into outData.
706 */
onDumpReport(const ConfigKey & key,const int64_t dumpTimeStampNs,const int64_t wallClockNs,const bool include_current_partial_bucket,const bool erase_data,const DumpReportReason dumpReportReason,const DumpLatency dumpLatency,vector<uint8_t> * outData)707 void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
708 const int64_t wallClockNs,
709 const bool include_current_partial_bucket,
710 const bool erase_data, const DumpReportReason dumpReportReason,
711 const DumpLatency dumpLatency, vector<uint8_t>* outData) {
712 ProtoOutputStream proto;
713 onDumpReport(key, dumpTimeStampNs, wallClockNs, include_current_partial_bucket, erase_data,
714 dumpReportReason, dumpLatency, &proto);
715
716 if (outData != nullptr) {
717 flushProtoToBuffer(proto, outData);
718 VLOG("output data size %zu", outData->size());
719 }
720
721 StatsdStats::getInstance().noteMetricsReportSent(key, proto.size());
722 }
723
724 /*
725 * For test use only. Excludes wallclockNs.
726 * onDumpReport dumps serialized ConfigMetricsReportList into outData.
727 */
onDumpReport(const ConfigKey & key,const int64_t dumpTimeStampNs,const bool include_current_partial_bucket,const bool erase_data,const DumpReportReason dumpReportReason,const DumpLatency dumpLatency,vector<uint8_t> * outData)728 void StatsLogProcessor::onDumpReport(const ConfigKey& key, const int64_t dumpTimeStampNs,
729 const bool include_current_partial_bucket,
730 const bool erase_data, const DumpReportReason dumpReportReason,
731 const DumpLatency dumpLatency, vector<uint8_t>* outData) {
732 onDumpReport(key, dumpTimeStampNs, getWallClockNs(), include_current_partial_bucket, erase_data,
733 dumpReportReason, dumpLatency, outData);
734 }
735
736 /*
737 * onConfigMetricsReportLocked dumps serialized ConfigMetricsReport into outData.
738 */
onConfigMetricsReportLocked(const ConfigKey & key,const int64_t dumpTimeStampNs,const int64_t wallClockNs,const bool include_current_partial_bucket,const bool erase_data,const DumpReportReason dumpReportReason,const DumpLatency dumpLatency,const bool dataSavedOnDisk,vector<uint8_t> * buffer)739 void StatsLogProcessor::onConfigMetricsReportLocked(
740 const ConfigKey& key, const int64_t dumpTimeStampNs, const int64_t wallClockNs,
741 const bool include_current_partial_bucket, const bool erase_data,
742 const DumpReportReason dumpReportReason, const DumpLatency dumpLatency,
743 const bool dataSavedOnDisk, vector<uint8_t>* buffer) {
744 // We already checked whether key exists in mMetricsManagers in
745 // WriteDataToDisk.
746 auto it = mMetricsManagers.find(key);
747 if (it == mMetricsManagers.end()) {
748 return;
749 }
750 if (it->second->hasRestrictedMetricsDelegate()) {
751 VLOG("Unexpected call to StatsLogProcessor::onConfigMetricsReportLocked for restricted "
752 "metrics.");
753 // Do not call onDumpReport for restricted metrics.
754 return;
755 }
756 int64_t lastReportTimeNs = it->second->getLastReportTimeNs();
757 int64_t lastReportWallClockNs = it->second->getLastReportWallClockNs();
758
759 std::set<string> str_set;
760
761 ProtoOutputStream tempProto;
762 // First, fill in ConfigMetricsReport using current data on memory, which
763 // starts from filling in StatsLogReport's.
764 it->second->onDumpReport(dumpTimeStampNs, wallClockNs, include_current_partial_bucket,
765 erase_data, dumpLatency, &str_set, &tempProto);
766
767 // Fill in UidMap if there is at least one metric to report.
768 // This skips the uid map if it's an empty config.
769 if (it->second->getNumMetrics() > 0) {
770 uint64_t uidMapToken = tempProto.start(FIELD_TYPE_MESSAGE | FIELD_ID_UID_MAP);
771 mUidMap->appendUidMap(dumpTimeStampNs, key, it->second->versionStringsInReport(),
772 it->second->installerInReport(),
773 it->second->packageCertificateHashSizeBytes(),
774 it->second->hashStringInReport() ? &str_set : nullptr, &tempProto);
775 tempProto.end(uidMapToken);
776 }
777
778 // Fill in the timestamps.
779 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_ELAPSED_NANOS,
780 (long long)lastReportTimeNs);
781 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_ELAPSED_NANOS,
782 (long long)dumpTimeStampNs);
783 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_LAST_REPORT_WALL_CLOCK_NANOS,
784 (long long)lastReportWallClockNs);
785 tempProto.write(FIELD_TYPE_INT64 | FIELD_ID_CURRENT_REPORT_WALL_CLOCK_NANOS,
786 (long long)wallClockNs);
787 // Dump report reason
788 tempProto.write(FIELD_TYPE_INT32 | FIELD_ID_DUMP_REPORT_REASON, dumpReportReason);
789
790 for (const auto& str : str_set) {
791 tempProto.write(FIELD_TYPE_STRING | FIELD_COUNT_REPEATED | FIELD_ID_STRINGS, str);
792 }
793
794 flushProtoToBuffer(tempProto, buffer);
795
796 // save buffer to disk if needed
797 if (erase_data && !dataSavedOnDisk && it->second->shouldPersistLocalHistory()) {
798 VLOG("save history to disk");
799 string file_name = StorageManager::getDataHistoryFileName((long)getWallClockSec(),
800 key.GetUid(), key.GetId());
801 StorageManager::writeFile(file_name.c_str(), buffer->data(), buffer->size());
802 }
803 }
804
resetConfigsLocked(const int64_t timestampNs,const std::vector<ConfigKey> & configs)805 void StatsLogProcessor::resetConfigsLocked(const int64_t timestampNs,
806 const std::vector<ConfigKey>& configs) {
807 for (const auto& key : configs) {
808 StatsdConfig config;
809 if (StorageManager::readConfigFromDisk(key, &config)) {
810 // Force a full update when resetting a config.
811 OnConfigUpdatedLocked(timestampNs, key, config, /*modularUpdate=*/false);
812 StatsdStats::getInstance().noteConfigReset(key);
813 } else {
814 ALOGE("Failed to read backup config from disk for : %s", key.ToString().c_str());
815 auto it = mMetricsManagers.find(key);
816 if (it != mMetricsManagers.end()) {
817 it->second->refreshTtl(timestampNs);
818 }
819 }
820 }
821 }
822
resetIfConfigTtlExpiredLocked(const int64_t eventTimeNs)823 void StatsLogProcessor::resetIfConfigTtlExpiredLocked(const int64_t eventTimeNs) {
824 std::vector<ConfigKey> configKeysTtlExpired;
825 for (auto it = mMetricsManagers.begin(); it != mMetricsManagers.end(); it++) {
826 if (it->second != nullptr && !it->second->isInTtl(eventTimeNs)) {
827 configKeysTtlExpired.push_back(it->first);
828 }
829 }
830 if (configKeysTtlExpired.size() > 0) {
831 WriteDataToDiskLocked(CONFIG_RESET, NO_TIME_CONSTRAINTS, getElapsedRealtimeNs(),
832 getWallClockNs());
833 resetConfigsLocked(eventTimeNs, configKeysTtlExpired);
834 }
835 }
836
OnConfigRemoved(const ConfigKey & key)837 void StatsLogProcessor::OnConfigRemoved(const ConfigKey& key) {
838 std::lock_guard<std::mutex> lock(mMetricsMutex);
839 auto it = mMetricsManagers.find(key);
840 if (it != mMetricsManagers.end()) {
841 WriteDataToDiskLocked(key, getElapsedRealtimeNs(), getWallClockNs(), CONFIG_REMOVED,
842 NO_TIME_CONSTRAINTS);
843 if (IsAtLeastU() && it->second->hasRestrictedMetricsDelegate()) {
844 dbutils::deleteDb(key);
845 mSendRestrictedMetricsBroadcast(key, it->second->getRestrictedMetricsDelegate(), {});
846 }
847 mMetricsManagers.erase(it);
848 mUidMap->OnConfigRemoved(key);
849 }
850 StatsdStats::getInstance().noteConfigRemoved(key);
851
852 mLastBroadcastTimes.erase(key);
853
854 int uid = key.GetUid();
855 bool lastConfigForUid = true;
856 for (auto it : mMetricsManagers) {
857 if (it.first.GetUid() == uid) {
858 lastConfigForUid = false;
859 break;
860 }
861 }
862 if (lastConfigForUid) {
863 mLastActivationBroadcastTimes.erase(uid);
864 }
865
866 if (mMetricsManagers.empty()) {
867 mPullerManager->ForceClearPullerCache();
868 }
869
870 updateLogEventFilterLocked();
871 }
872
873 // TODO(b/267501143): Add unit tests when metric producer is ready
enforceDataTtlsIfNecessaryLocked(const int64_t wallClockNs,const int64_t elapsedRealtimeNs)874 void StatsLogProcessor::enforceDataTtlsIfNecessaryLocked(const int64_t wallClockNs,
875 const int64_t elapsedRealtimeNs) {
876 if (!IsAtLeastU()) {
877 return;
878 }
879 if (elapsedRealtimeNs - mLastTtlTime < StatsdStats::kMinTtlCheckPeriodNs) {
880 return;
881 }
882 enforceDataTtlsLocked(wallClockNs, elapsedRealtimeNs);
883 }
884
flushRestrictedDataIfNecessaryLocked(const int64_t elapsedRealtimeNs)885 void StatsLogProcessor::flushRestrictedDataIfNecessaryLocked(const int64_t elapsedRealtimeNs) {
886 if (!IsAtLeastU()) {
887 return;
888 }
889 if (elapsedRealtimeNs - mLastFlushRestrictedTime < StatsdStats::kMinFlushRestrictedPeriodNs) {
890 return;
891 }
892 flushRestrictedDataLocked(elapsedRealtimeNs);
893 }
894
querySql(const string & sqlQuery,const int32_t minSqlClientVersion,const optional<vector<uint8_t>> & policyConfig,const shared_ptr<IStatsQueryCallback> & callback,const int64_t configId,const string & configPackage,const int32_t callingUid)895 void StatsLogProcessor::querySql(const string& sqlQuery, const int32_t minSqlClientVersion,
896 const optional<vector<uint8_t>>& policyConfig,
897 const shared_ptr<IStatsQueryCallback>& callback,
898 const int64_t configId, const string& configPackage,
899 const int32_t callingUid) {
900 std::lock_guard<std::mutex> lock(mMetricsMutex);
901 string err = "";
902
903 if (!IsAtLeastU()) {
904 ALOGW("Restricted metrics query invoked on U- device");
905 StatsdStats::getInstance().noteQueryRestrictedMetricFailed(
906 configId, configPackage, std::nullopt, callingUid,
907 InvalidQueryReason(FLAG_DISABLED));
908 return;
909 }
910
911 const int64_t elapsedRealtimeNs = getElapsedRealtimeNs();
912
913 // TODO(b/268416460): validate policyConfig here
914
915 if (minSqlClientVersion > dbutils::getDbVersion()) {
916 callback->sendFailure(StringPrintf(
917 "Unsupported sqlite version. Installed Version: %d, Requested Version: %d.",
918 dbutils::getDbVersion(), minSqlClientVersion));
919 StatsdStats::getInstance().noteQueryRestrictedMetricFailed(
920 configId, configPackage, std::nullopt, callingUid,
921 InvalidQueryReason(UNSUPPORTED_SQLITE_VERSION));
922 return;
923 }
924
925 set<int32_t> configPackageUids;
926 const auto& uidMapItr = UidMap::sAidToUidMapping.find(configPackage);
927 if (uidMapItr != UidMap::sAidToUidMapping.end()) {
928 configPackageUids.insert(uidMapItr->second);
929 } else {
930 configPackageUids = mUidMap->getAppUid(configPackage);
931 }
932
933 InvalidQueryReason invalidQueryReason;
934 set<ConfigKey> keysToQuery = getRestrictedConfigKeysToQueryLocked(
935 callingUid, configId, configPackageUids, err, invalidQueryReason);
936
937 if (keysToQuery.empty()) {
938 callback->sendFailure(err);
939 StatsdStats::getInstance().noteQueryRestrictedMetricFailed(
940 configId, configPackage, std::nullopt, callingUid,
941 InvalidQueryReason(invalidQueryReason));
942 return;
943 }
944
945 if (keysToQuery.size() > 1) {
946 err = "Ambiguous ConfigKey";
947 callback->sendFailure(err);
948 StatsdStats::getInstance().noteQueryRestrictedMetricFailed(
949 configId, configPackage, std::nullopt, callingUid,
950 InvalidQueryReason(AMBIGUOUS_CONFIG_KEY));
951 return;
952 }
953
954 flushRestrictedDataLocked(elapsedRealtimeNs);
955 enforceDataTtlsLocked(getWallClockNs(), elapsedRealtimeNs);
956
957 std::vector<std::vector<std::string>> rows;
958 std::vector<int32_t> columnTypes;
959 std::vector<string> columnNames;
960 if (!dbutils::query(*(keysToQuery.begin()), sqlQuery, rows, columnTypes, columnNames, err)) {
961 callback->sendFailure(StringPrintf("failed to query db %s:", err.c_str()));
962 StatsdStats::getInstance().noteQueryRestrictedMetricFailed(
963 configId, configPackage, keysToQuery.begin()->GetUid(), callingUid,
964 InvalidQueryReason(QUERY_FAILURE), err.c_str());
965 return;
966 }
967
968 vector<string> queryData;
969 queryData.reserve(rows.size() * columnNames.size());
970 // TODO(b/268415904): avoid this vector transformation.
971 if (columnNames.size() != columnTypes.size()) {
972 callback->sendFailure("Inconsistent row sizes");
973 StatsdStats::getInstance().noteQueryRestrictedMetricFailed(
974 configId, configPackage, keysToQuery.begin()->GetUid(), callingUid,
975 InvalidQueryReason(INCONSISTENT_ROW_SIZE));
976 }
977 for (size_t i = 0; i < rows.size(); ++i) {
978 if (rows[i].size() != columnNames.size()) {
979 callback->sendFailure("Inconsistent row sizes");
980 StatsdStats::getInstance().noteQueryRestrictedMetricFailed(
981 configId, configPackage, keysToQuery.begin()->GetUid(), callingUid,
982 InvalidQueryReason(INCONSISTENT_ROW_SIZE));
983 return;
984 }
985 queryData.insert(std::end(queryData), std::make_move_iterator(std::begin(rows[i])),
986 std::make_move_iterator(std::end(rows[i])));
987 }
988 callback->sendResults(queryData, columnNames, columnTypes, rows.size());
989 StatsdStats::getInstance().noteQueryRestrictedMetricSucceed(
990 configId, configPackage, keysToQuery.begin()->GetUid(), callingUid,
991 /*queryLatencyNs=*/getElapsedRealtimeNs() - elapsedRealtimeNs);
992 }
993
getRestrictedConfigKeysToQueryLocked(const int32_t callingUid,const int64_t configId,const set<int32_t> & configPackageUids,string & err,InvalidQueryReason & invalidQueryReason)994 set<ConfigKey> StatsLogProcessor::getRestrictedConfigKeysToQueryLocked(
995 const int32_t callingUid, const int64_t configId, const set<int32_t>& configPackageUids,
996 string& err, InvalidQueryReason& invalidQueryReason) {
997 set<ConfigKey> matchedConfigKeys;
998 for (auto uid : configPackageUids) {
999 ConfigKey configKey(uid, configId);
1000 if (mMetricsManagers.find(configKey) != mMetricsManagers.end()) {
1001 matchedConfigKeys.insert(configKey);
1002 }
1003 }
1004
1005 set<ConfigKey> excludedKeys;
1006 for (auto& configKey : matchedConfigKeys) {
1007 auto it = mMetricsManagers.find(configKey);
1008 if (!it->second->validateRestrictedMetricsDelegate(callingUid)) {
1009 excludedKeys.insert(configKey);
1010 };
1011 }
1012
1013 set<ConfigKey> result;
1014 std::set_difference(matchedConfigKeys.begin(), matchedConfigKeys.end(), excludedKeys.begin(),
1015 excludedKeys.end(), std::inserter(result, result.end()));
1016 if (matchedConfigKeys.empty()) {
1017 err = "No configs found matching the config key";
1018 invalidQueryReason = InvalidQueryReason(CONFIG_KEY_NOT_FOUND);
1019 } else if (result.empty()) {
1020 err = "No matching configs for restricted metrics delegate";
1021 invalidQueryReason = InvalidQueryReason(CONFIG_KEY_WITH_UNMATCHED_DELEGATE);
1022 }
1023
1024 return result;
1025 }
1026
EnforceDataTtls(const int64_t wallClockNs,const int64_t elapsedRealtimeNs)1027 void StatsLogProcessor::EnforceDataTtls(const int64_t wallClockNs,
1028 const int64_t elapsedRealtimeNs) {
1029 if (!IsAtLeastU()) {
1030 return;
1031 }
1032 std::lock_guard<std::mutex> lock(mMetricsMutex);
1033 enforceDataTtlsLocked(wallClockNs, elapsedRealtimeNs);
1034 }
1035
enforceDataTtlsLocked(const int64_t wallClockNs,const int64_t elapsedRealtimeNs)1036 void StatsLogProcessor::enforceDataTtlsLocked(const int64_t wallClockNs,
1037 const int64_t elapsedRealtimeNs) {
1038 for (const auto& itr : mMetricsManagers) {
1039 itr.second->enforceRestrictedDataTtls(wallClockNs);
1040 }
1041 mLastTtlTime = elapsedRealtimeNs;
1042 }
1043
enforceDbGuardrailsIfNecessaryLocked(const int64_t wallClockNs,const int64_t elapsedRealtimeNs)1044 void StatsLogProcessor::enforceDbGuardrailsIfNecessaryLocked(const int64_t wallClockNs,
1045 const int64_t elapsedRealtimeNs) {
1046 if (elapsedRealtimeNs - mLastDbGuardrailEnforcementTime <
1047 StatsdStats::kMinDbGuardrailEnforcementPeriodNs) {
1048 return;
1049 }
1050 StorageManager::enforceDbGuardrails(STATS_RESTRICTED_DATA_DIR, wallClockNs / NS_PER_SEC,
1051 StatsdStats::kMaxFileSize);
1052 mLastDbGuardrailEnforcementTime = elapsedRealtimeNs;
1053 }
1054
fillRestrictedMetrics(const int64_t configId,const string & configPackage,const int32_t delegateUid,vector<int64_t> * output)1055 void StatsLogProcessor::fillRestrictedMetrics(const int64_t configId, const string& configPackage,
1056 const int32_t delegateUid, vector<int64_t>* output) {
1057 std::lock_guard<std::mutex> lock(mMetricsMutex);
1058
1059 set<int32_t> configPackageUids;
1060 const auto& uidMapItr = UidMap::sAidToUidMapping.find(configPackage);
1061 if (uidMapItr != UidMap::sAidToUidMapping.end()) {
1062 configPackageUids.insert(uidMapItr->second);
1063 } else {
1064 configPackageUids = mUidMap->getAppUid(configPackage);
1065 }
1066 string err;
1067 InvalidQueryReason invalidQueryReason;
1068 set<ConfigKey> keysToGetMetrics = getRestrictedConfigKeysToQueryLocked(
1069 delegateUid, configId, configPackageUids, err, invalidQueryReason);
1070
1071 for (const ConfigKey& key : keysToGetMetrics) {
1072 vector<int64_t> metricIds = mMetricsManagers[key]->getAllMetricIds();
1073 output->insert(output->end(), metricIds.begin(), metricIds.end());
1074 }
1075 }
1076
flushRestrictedDataLocked(const int64_t elapsedRealtimeNs)1077 void StatsLogProcessor::flushRestrictedDataLocked(const int64_t elapsedRealtimeNs) {
1078 for (const auto& it : mMetricsManagers) {
1079 // no-op if metricsManager is not restricted
1080 it.second->flushRestrictedData();
1081 }
1082
1083 mLastFlushRestrictedTime = elapsedRealtimeNs;
1084 }
1085
flushIfNecessaryLocked(const ConfigKey & key,MetricsManager & metricsManager)1086 void StatsLogProcessor::flushIfNecessaryLocked(const ConfigKey& key,
1087 MetricsManager& metricsManager) {
1088 int64_t elapsedRealtimeNs = getElapsedRealtimeNs();
1089 auto lastCheckTime = mLastByteSizeTimes.find(key);
1090 if (lastCheckTime != mLastByteSizeTimes.end()) {
1091 if (elapsedRealtimeNs - lastCheckTime->second < StatsdStats::kMinByteSizeCheckPeriodNs) {
1092 return;
1093 }
1094 }
1095
1096 // We suspect that the byteSize() computation is expensive, so we set a rate limit.
1097 size_t totalBytes = metricsManager.byteSize();
1098
1099 mLastByteSizeTimes[key] = elapsedRealtimeNs;
1100 const size_t kBytesPerConfig = metricsManager.hasRestrictedMetricsDelegate()
1101 ? StatsdStats::kBytesPerRestrictedConfigTriggerFlush
1102 : StatsdStats::kBytesPerConfigTriggerGetData;
1103 bool requestDump = false;
1104 if (totalBytes > StatsdStats::kMaxMetricsBytesPerConfig) {
1105 // Too late. We need to start clearing data.
1106 metricsManager.dropData(elapsedRealtimeNs);
1107 StatsdStats::getInstance().noteDataDropped(key, totalBytes);
1108 VLOG("StatsD had to toss out metrics for %s", key.ToString().c_str());
1109 } else if ((totalBytes > kBytesPerConfig) ||
1110 (mOnDiskDataConfigs.find(key) != mOnDiskDataConfigs.end())) {
1111 // Request to dump if:
1112 // 1. in memory data > threshold OR
1113 // 2. config has old data report on disk.
1114 requestDump = true;
1115 }
1116
1117 if (requestDump) {
1118 if (metricsManager.hasRestrictedMetricsDelegate()) {
1119 metricsManager.flushRestrictedData();
1120 // No need to send broadcast for restricted metrics.
1121 return;
1122 }
1123 // Send broadcast so that receivers can pull data.
1124 auto lastBroadcastTime = mLastBroadcastTimes.find(key);
1125 if (lastBroadcastTime != mLastBroadcastTimes.end()) {
1126 if (elapsedRealtimeNs - lastBroadcastTime->second <
1127 StatsdStats::kMinBroadcastPeriodNs) {
1128 VLOG("StatsD would've sent a broadcast but the rate limit stopped us.");
1129 return;
1130 }
1131 }
1132 if (mSendBroadcast(key)) {
1133 mOnDiskDataConfigs.erase(key);
1134 VLOG("StatsD triggered data fetch for %s", key.ToString().c_str());
1135 mLastBroadcastTimes[key] = elapsedRealtimeNs;
1136 StatsdStats::getInstance().noteBroadcastSent(key);
1137 }
1138 }
1139 }
1140
WriteDataToDiskLocked(const ConfigKey & key,const int64_t timestampNs,const int64_t wallClockNs,const DumpReportReason dumpReportReason,const DumpLatency dumpLatency)1141 void StatsLogProcessor::WriteDataToDiskLocked(const ConfigKey& key, const int64_t timestampNs,
1142 const int64_t wallClockNs,
1143 const DumpReportReason dumpReportReason,
1144 const DumpLatency dumpLatency) {
1145 if (mMetricsManagers.find(key) == mMetricsManagers.end() ||
1146 !mMetricsManagers.find(key)->second->shouldWriteToDisk()) {
1147 return;
1148 }
1149 if (mMetricsManagers.find(key)->second->hasRestrictedMetricsDelegate()) {
1150 mMetricsManagers.find(key)->second->flushRestrictedData();
1151 return;
1152 }
1153 vector<uint8_t> buffer;
1154 onConfigMetricsReportLocked(key, timestampNs, wallClockNs,
1155 true /* include_current_partial_bucket*/, true /* erase_data */,
1156 dumpReportReason, dumpLatency, true, &buffer);
1157 string file_name =
1158 StorageManager::getDataFileName((long)getWallClockSec(), key.GetUid(), key.GetId());
1159 StorageManager::writeFile(file_name.c_str(), buffer.data(), buffer.size());
1160
1161 // We were able to write the ConfigMetricsReport to disk, so we should trigger collection ASAP.
1162 mOnDiskDataConfigs.insert(key);
1163 }
1164
SaveActiveConfigsToDisk(int64_t currentTimeNs)1165 void StatsLogProcessor::SaveActiveConfigsToDisk(int64_t currentTimeNs) {
1166 std::lock_guard<std::mutex> lock(mMetricsMutex);
1167 const int64_t timeNs = getElapsedRealtimeNs();
1168 // Do not write to disk if we already have in the last few seconds.
1169 if (static_cast<unsigned long long> (timeNs) <
1170 mLastActiveMetricsWriteNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
1171 ALOGI("Statsd skipping writing active metrics to disk. Already wrote data in last %d seconds",
1172 WRITE_DATA_COOL_DOWN_SEC);
1173 return;
1174 }
1175 mLastActiveMetricsWriteNs = timeNs;
1176
1177 ProtoOutputStream proto;
1178 WriteActiveConfigsToProtoOutputStreamLocked(currentTimeNs, DEVICE_SHUTDOWN, &proto);
1179
1180 string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
1181 StorageManager::deleteFile(file_name.c_str());
1182 android::base::unique_fd fd(
1183 open(file_name.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC, S_IRUSR | S_IWUSR));
1184 if (fd == -1) {
1185 ALOGE("Attempt to write %s but failed", file_name.c_str());
1186 return;
1187 }
1188 proto.flush(fd.get());
1189 }
1190
SaveMetadataToDisk(int64_t currentWallClockTimeNs,int64_t systemElapsedTimeNs)1191 void StatsLogProcessor::SaveMetadataToDisk(int64_t currentWallClockTimeNs,
1192 int64_t systemElapsedTimeNs) {
1193 std::lock_guard<std::mutex> lock(mMetricsMutex);
1194 // Do not write to disk if we already have in the last few seconds.
1195 if (static_cast<unsigned long long> (systemElapsedTimeNs) <
1196 mLastMetadataWriteNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
1197 ALOGI("Statsd skipping writing metadata to disk. Already wrote data in last %d seconds",
1198 WRITE_DATA_COOL_DOWN_SEC);
1199 return;
1200 }
1201 mLastMetadataWriteNs = systemElapsedTimeNs;
1202
1203 metadata::StatsMetadataList metadataList;
1204 WriteMetadataToProtoLocked(
1205 currentWallClockTimeNs, systemElapsedTimeNs, &metadataList);
1206
1207 string file_name = StringPrintf("%s/metadata", STATS_METADATA_DIR);
1208 StorageManager::deleteFile(file_name.c_str());
1209
1210 if (metadataList.stats_metadata_size() == 0) {
1211 // Skip the write if we have nothing to write.
1212 return;
1213 }
1214
1215 std::string data;
1216 metadataList.SerializeToString(&data);
1217 StorageManager::writeFile(file_name.c_str(), data.c_str(), data.size());
1218 }
1219
WriteMetadataToProto(int64_t currentWallClockTimeNs,int64_t systemElapsedTimeNs,metadata::StatsMetadataList * metadataList)1220 void StatsLogProcessor::WriteMetadataToProto(int64_t currentWallClockTimeNs,
1221 int64_t systemElapsedTimeNs,
1222 metadata::StatsMetadataList* metadataList) {
1223 std::lock_guard<std::mutex> lock(mMetricsMutex);
1224 WriteMetadataToProtoLocked(currentWallClockTimeNs, systemElapsedTimeNs, metadataList);
1225 }
1226
WriteMetadataToProtoLocked(int64_t currentWallClockTimeNs,int64_t systemElapsedTimeNs,metadata::StatsMetadataList * metadataList)1227 void StatsLogProcessor::WriteMetadataToProtoLocked(int64_t currentWallClockTimeNs,
1228 int64_t systemElapsedTimeNs,
1229 metadata::StatsMetadataList* metadataList) {
1230 for (const auto& pair : mMetricsManagers) {
1231 const sp<MetricsManager>& metricsManager = pair.second;
1232 metadata::StatsMetadata* statsMetadata = metadataList->add_stats_metadata();
1233 bool metadataWritten = metricsManager->writeMetadataToProto(currentWallClockTimeNs,
1234 systemElapsedTimeNs, statsMetadata);
1235 if (!metadataWritten) {
1236 metadataList->mutable_stats_metadata()->RemoveLast();
1237 }
1238 }
1239 }
1240
LoadMetadataFromDisk(int64_t currentWallClockTimeNs,int64_t systemElapsedTimeNs)1241 void StatsLogProcessor::LoadMetadataFromDisk(int64_t currentWallClockTimeNs,
1242 int64_t systemElapsedTimeNs) {
1243 std::lock_guard<std::mutex> lock(mMetricsMutex);
1244 string file_name = StringPrintf("%s/metadata", STATS_METADATA_DIR);
1245 int fd = open(file_name.c_str(), O_RDONLY | O_CLOEXEC);
1246 if (-1 == fd) {
1247 VLOG("Attempt to read %s but failed", file_name.c_str());
1248 StorageManager::deleteFile(file_name.c_str());
1249 return;
1250 }
1251 string content;
1252 if (!android::base::ReadFdToString(fd, &content)) {
1253 ALOGE("Attempt to read %s but failed", file_name.c_str());
1254 close(fd);
1255 StorageManager::deleteFile(file_name.c_str());
1256 return;
1257 }
1258
1259 close(fd);
1260
1261 metadata::StatsMetadataList statsMetadataList;
1262 if (!statsMetadataList.ParseFromString(content)) {
1263 ALOGE("Attempt to read %s but failed; failed to metadata", file_name.c_str());
1264 StorageManager::deleteFile(file_name.c_str());
1265 return;
1266 }
1267 SetMetadataStateLocked(statsMetadataList, currentWallClockTimeNs, systemElapsedTimeNs);
1268 StorageManager::deleteFile(file_name.c_str());
1269 }
1270
SetMetadataState(const metadata::StatsMetadataList & statsMetadataList,int64_t currentWallClockTimeNs,int64_t systemElapsedTimeNs)1271 void StatsLogProcessor::SetMetadataState(const metadata::StatsMetadataList& statsMetadataList,
1272 int64_t currentWallClockTimeNs,
1273 int64_t systemElapsedTimeNs) {
1274 std::lock_guard<std::mutex> lock(mMetricsMutex);
1275 SetMetadataStateLocked(statsMetadataList, currentWallClockTimeNs, systemElapsedTimeNs);
1276 }
1277
SetMetadataStateLocked(const metadata::StatsMetadataList & statsMetadataList,int64_t currentWallClockTimeNs,int64_t systemElapsedTimeNs)1278 void StatsLogProcessor::SetMetadataStateLocked(
1279 const metadata::StatsMetadataList& statsMetadataList,
1280 int64_t currentWallClockTimeNs,
1281 int64_t systemElapsedTimeNs) {
1282 for (const metadata::StatsMetadata& metadata : statsMetadataList.stats_metadata()) {
1283 ConfigKey key(metadata.config_key().uid(), metadata.config_key().config_id());
1284 auto it = mMetricsManagers.find(key);
1285 if (it == mMetricsManagers.end()) {
1286 ALOGE("No config found for configKey %s", key.ToString().c_str());
1287 continue;
1288 }
1289 VLOG("Setting metadata %s", key.ToString().c_str());
1290 it->second->loadMetadata(metadata, currentWallClockTimeNs, systemElapsedTimeNs);
1291 }
1292 VLOG("Successfully loaded %d metadata.", statsMetadataList.stats_metadata_size());
1293 }
1294
WriteActiveConfigsToProtoOutputStream(int64_t currentTimeNs,const DumpReportReason reason,ProtoOutputStream * proto)1295 void StatsLogProcessor::WriteActiveConfigsToProtoOutputStream(
1296 int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto) {
1297 std::lock_guard<std::mutex> lock(mMetricsMutex);
1298 WriteActiveConfigsToProtoOutputStreamLocked(currentTimeNs, reason, proto);
1299 }
1300
WriteActiveConfigsToProtoOutputStreamLocked(int64_t currentTimeNs,const DumpReportReason reason,ProtoOutputStream * proto)1301 void StatsLogProcessor::WriteActiveConfigsToProtoOutputStreamLocked(
1302 int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto) {
1303 for (const auto& pair : mMetricsManagers) {
1304 const sp<MetricsManager>& metricsManager = pair.second;
1305 uint64_t configToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
1306 FIELD_ID_ACTIVE_CONFIG_LIST_CONFIG);
1307 metricsManager->writeActiveConfigToProtoOutputStream(currentTimeNs, reason, proto);
1308 proto->end(configToken);
1309 }
1310 }
LoadActiveConfigsFromDisk()1311 void StatsLogProcessor::LoadActiveConfigsFromDisk() {
1312 std::lock_guard<std::mutex> lock(mMetricsMutex);
1313 string file_name = StringPrintf("%s/active_metrics", STATS_ACTIVE_METRIC_DIR);
1314 int fd = open(file_name.c_str(), O_RDONLY | O_CLOEXEC);
1315 if (-1 == fd) {
1316 VLOG("Attempt to read %s but failed", file_name.c_str());
1317 StorageManager::deleteFile(file_name.c_str());
1318 return;
1319 }
1320 string content;
1321 if (!android::base::ReadFdToString(fd, &content)) {
1322 ALOGE("Attempt to read %s but failed", file_name.c_str());
1323 close(fd);
1324 StorageManager::deleteFile(file_name.c_str());
1325 return;
1326 }
1327
1328 close(fd);
1329
1330 ActiveConfigList activeConfigList;
1331 if (!activeConfigList.ParseFromString(content)) {
1332 ALOGE("Attempt to read %s but failed; failed to load active configs", file_name.c_str());
1333 StorageManager::deleteFile(file_name.c_str());
1334 return;
1335 }
1336 // Passing in mTimeBaseNs only works as long as we only load from disk is when statsd starts.
1337 SetConfigsActiveStateLocked(activeConfigList, mTimeBaseNs);
1338 StorageManager::deleteFile(file_name.c_str());
1339 }
1340
SetConfigsActiveState(const ActiveConfigList & activeConfigList,int64_t currentTimeNs)1341 void StatsLogProcessor::SetConfigsActiveState(const ActiveConfigList& activeConfigList,
1342 int64_t currentTimeNs) {
1343 std::lock_guard<std::mutex> lock(mMetricsMutex);
1344 SetConfigsActiveStateLocked(activeConfigList, currentTimeNs);
1345 }
1346
SetConfigsActiveStateLocked(const ActiveConfigList & activeConfigList,int64_t currentTimeNs)1347 void StatsLogProcessor::SetConfigsActiveStateLocked(const ActiveConfigList& activeConfigList,
1348 int64_t currentTimeNs) {
1349 for (int i = 0; i < activeConfigList.config_size(); i++) {
1350 const auto& config = activeConfigList.config(i);
1351 ConfigKey key(config.uid(), config.id());
1352 auto it = mMetricsManagers.find(key);
1353 if (it == mMetricsManagers.end()) {
1354 ALOGE("No config found for config %s", key.ToString().c_str());
1355 continue;
1356 }
1357 VLOG("Setting active config %s", key.ToString().c_str());
1358 it->second->loadActiveConfig(config, currentTimeNs);
1359 }
1360 VLOG("Successfully loaded %d active configs.", activeConfigList.config_size());
1361 }
1362
WriteDataToDiskLocked(const DumpReportReason dumpReportReason,const DumpLatency dumpLatency,const int64_t elapsedRealtimeNs,const int64_t wallClockNs)1363 void StatsLogProcessor::WriteDataToDiskLocked(const DumpReportReason dumpReportReason,
1364 const DumpLatency dumpLatency,
1365 const int64_t elapsedRealtimeNs,
1366 const int64_t wallClockNs) {
1367 // Do not write to disk if we already have in the last few seconds.
1368 // This is to avoid overwriting files that would have the same name if we
1369 // write twice in the same second.
1370 if (static_cast<unsigned long long>(elapsedRealtimeNs) <
1371 mLastWriteTimeNs + WRITE_DATA_COOL_DOWN_SEC * NS_PER_SEC) {
1372 ALOGI("Statsd skipping writing data to disk. Already wrote data in last %d seconds",
1373 WRITE_DATA_COOL_DOWN_SEC);
1374 return;
1375 }
1376 mLastWriteTimeNs = elapsedRealtimeNs;
1377 for (auto& pair : mMetricsManagers) {
1378 WriteDataToDiskLocked(pair.first, elapsedRealtimeNs, wallClockNs, dumpReportReason,
1379 dumpLatency);
1380 }
1381 }
1382
WriteDataToDisk(const DumpReportReason dumpReportReason,const DumpLatency dumpLatency,const int64_t elapsedRealtimeNs,const int64_t wallClockNs)1383 void StatsLogProcessor::WriteDataToDisk(const DumpReportReason dumpReportReason,
1384 const DumpLatency dumpLatency,
1385 const int64_t elapsedRealtimeNs,
1386 const int64_t wallClockNs) {
1387 std::lock_guard<std::mutex> lock(mMetricsMutex);
1388 WriteDataToDiskLocked(dumpReportReason, dumpLatency, elapsedRealtimeNs, wallClockNs);
1389 }
1390
informPullAlarmFired(const int64_t timestampNs)1391 void StatsLogProcessor::informPullAlarmFired(const int64_t timestampNs) {
1392 std::lock_guard<std::mutex> lock(mMetricsMutex);
1393 mPullerManager->OnAlarmFired(timestampNs);
1394 }
1395
getLastReportTimeNs(const ConfigKey & key)1396 int64_t StatsLogProcessor::getLastReportTimeNs(const ConfigKey& key) {
1397 auto it = mMetricsManagers.find(key);
1398 if (it == mMetricsManagers.end()) {
1399 return 0;
1400 } else {
1401 return it->second->getLastReportTimeNs();
1402 }
1403 }
1404
notifyAppUpgrade(const int64_t & eventTimeNs,const string & apk,const int uid,const int64_t version)1405 void StatsLogProcessor::notifyAppUpgrade(const int64_t& eventTimeNs, const string& apk,
1406 const int uid, const int64_t version) {
1407 std::lock_guard<std::mutex> lock(mMetricsMutex);
1408 VLOG("Received app upgrade");
1409 StateManager::getInstance().notifyAppChanged(apk, mUidMap);
1410 for (const auto& it : mMetricsManagers) {
1411 it.second->notifyAppUpgrade(eventTimeNs, apk, uid, version);
1412 }
1413 }
1414
notifyAppRemoved(const int64_t & eventTimeNs,const string & apk,const int uid)1415 void StatsLogProcessor::notifyAppRemoved(const int64_t& eventTimeNs, const string& apk,
1416 const int uid) {
1417 std::lock_guard<std::mutex> lock(mMetricsMutex);
1418 VLOG("Received app removed");
1419 StateManager::getInstance().notifyAppChanged(apk, mUidMap);
1420 for (const auto& it : mMetricsManagers) {
1421 it.second->notifyAppRemoved(eventTimeNs, apk, uid);
1422 }
1423 }
1424
onUidMapReceived(const int64_t & eventTimeNs)1425 void StatsLogProcessor::onUidMapReceived(const int64_t& eventTimeNs) {
1426 std::lock_guard<std::mutex> lock(mMetricsMutex);
1427 VLOG("Received uid map");
1428 StateManager::getInstance().updateLogSources(mUidMap);
1429 for (const auto& it : mMetricsManagers) {
1430 it.second->onUidMapReceived(eventTimeNs);
1431 }
1432 }
1433
onStatsdInitCompleted(const int64_t & elapsedTimeNs)1434 void StatsLogProcessor::onStatsdInitCompleted(const int64_t& elapsedTimeNs) {
1435 std::lock_guard<std::mutex> lock(mMetricsMutex);
1436 VLOG("Received boot completed signal");
1437 for (const auto& it : mMetricsManagers) {
1438 it.second->onStatsdInitCompleted(elapsedTimeNs);
1439 }
1440 }
1441
noteOnDiskData(const ConfigKey & key)1442 void StatsLogProcessor::noteOnDiskData(const ConfigKey& key) {
1443 std::lock_guard<std::mutex> lock(mMetricsMutex);
1444 mOnDiskDataConfigs.insert(key);
1445 }
1446
setAnomalyAlarm(const int64_t elapsedTimeMillis)1447 void StatsLogProcessor::setAnomalyAlarm(const int64_t elapsedTimeMillis) {
1448 std::lock_guard<std::mutex> lock(mAnomalyAlarmMutex);
1449 mNextAnomalyAlarmTime = elapsedTimeMillis;
1450 }
1451
cancelAnomalyAlarm()1452 void StatsLogProcessor::cancelAnomalyAlarm() {
1453 std::lock_guard<std::mutex> lock(mAnomalyAlarmMutex);
1454 mNextAnomalyAlarmTime = 0;
1455 }
1456
informAnomalyAlarmFiredLocked(const int64_t elapsedTimeMillis)1457 void StatsLogProcessor::informAnomalyAlarmFiredLocked(const int64_t elapsedTimeMillis) {
1458 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
1459 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1460 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(elapsedTimeMillis / 1000));
1461 if (alarmSet.size() > 0) {
1462 VLOG("Found periodic alarm fired.");
1463 processFiredAnomalyAlarmsLocked(MillisToNano(elapsedTimeMillis), alarmSet);
1464 } else {
1465 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
1466 }
1467 }
1468
getDefaultAtomIdSet()1469 LogEventFilter::AtomIdSet StatsLogProcessor::getDefaultAtomIdSet() {
1470 // populate hard-coded list of useful atoms
1471 // we add also atoms which could be pushed by statsd itself to simplify the logic
1472 // to handle metric configs update: APP_BREADCRUMB_REPORTED & ANOMALY_DETECTED
1473 LogEventFilter::AtomIdSet allAtomIds{
1474 util::BINARY_PUSH_STATE_CHANGED, util::DAVEY_OCCURRED,
1475 util::ISOLATED_UID_CHANGED, util::APP_BREADCRUMB_REPORTED,
1476 util::WATCHDOG_ROLLBACK_OCCURRED, util::ANOMALY_DETECTED};
1477 return allAtomIds;
1478 }
1479
updateLogEventFilterLocked() const1480 void StatsLogProcessor::updateLogEventFilterLocked() const {
1481 VLOG("StatsLogProcessor: Updating allAtomIds");
1482 if (!mLogEventFilter) {
1483 return;
1484 }
1485 LogEventFilter::AtomIdSet allAtomIds = getDefaultAtomIdSet();
1486 for (const auto& metricsManager : mMetricsManagers) {
1487 metricsManager.second->addAllAtomIds(allAtomIds);
1488 }
1489 StateManager::getInstance().addAllAtomIds(allAtomIds);
1490 VLOG("StatsLogProcessor: Updating allAtomIds done. Total atoms %d", (int)allAtomIds.size());
1491 mLogEventFilter->setAtomIds(std::move(allAtomIds), this);
1492 }
1493
1494 } // namespace statsd
1495 } // namespace os
1496 } // namespace android
1497