blob: 536700f3bfe7fc37029992c9f06385ab89dc8bbd [file] [log] [blame]
Yao Chen44cf27c2017-09-14 22:32: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 */
Yangster-mac754e29e2018-05-02 12:23:17 -070016#define DEBUG false // STOPSHIP if true
Joe Onorato9fc9edf2017-10-15 20:08:52 -070017#include "Log.h"
tsaichristined21aacf2019-10-07 14:47:38 -070018
Yao Chen44cf27c2017-09-14 22:32:50 -070019#include "MetricsManager.h"
tsaichristined21aacf2019-10-07 14:47:38 -070020
tsaichristined21aacf2019-10-07 14:47:38 -070021#include <private/android_filesystem_config.h>
Yao Chen93fe3a32017-11-02 13:52:59 -070022
Yao Chen44cf27c2017-09-14 22:32:50 -070023#include "CountMetricProducer.h"
Muhammad Qureshic8e22662019-11-20 17:18:03 -080024#include "atoms_info.h"
Yao Chen93fe3a32017-11-02 13:52:59 -070025#include "condition/CombinationConditionTracker.h"
26#include "condition/SimpleConditionTracker.h"
Yao Chenb3561512017-11-21 18:07:17 -080027#include "guardrail/StatsdStats.h"
Yao Chen93fe3a32017-11-02 13:52:59 -070028#include "matchers/CombinationLogMatchingTracker.h"
29#include "matchers/SimpleLogMatchingTracker.h"
Yao Chencaf339d2017-10-06 16:01:10 -070030#include "metrics_manager_util.h"
tsaichristined21aacf2019-10-07 14:47:38 -070031#include "state/StateManager.h"
Yangster-mac330af582018-02-08 15:24:38 -080032#include "stats_log_util.h"
tsaichristined21aacf2019-10-07 14:47:38 -070033#include "stats_util.h"
34#include "statslog.h"
Yao Chen288c6002017-12-12 13:43:18 -080035
36using android::util::FIELD_COUNT_REPEATED;
David Chenfaa1af52018-03-30 15:14:04 -070037using android::util::FIELD_TYPE_INT32;
38using android::util::FIELD_TYPE_INT64;
Yao Chen288c6002017-12-12 13:43:18 -080039using android::util::FIELD_TYPE_MESSAGE;
Yangster-mac9def8e32018-04-17 13:55:51 -070040using android::util::FIELD_TYPE_STRING;
Yao Chen288c6002017-12-12 13:43:18 -080041using android::util::ProtoOutputStream;
42
Yao Chen44cf27c2017-09-14 22:32:50 -070043using std::set;
44using std::string;
Yao Chen44cf27c2017-09-14 22:32:50 -070045using std::vector;
46
47namespace android {
48namespace os {
49namespace statsd {
50
Yao Chen288c6002017-12-12 13:43:18 -080051const int FIELD_ID_METRICS = 1;
David Chenfaa1af52018-03-30 15:14:04 -070052const int FIELD_ID_ANNOTATIONS = 7;
53const int FIELD_ID_ANNOTATIONS_INT64 = 1;
54const int FIELD_ID_ANNOTATIONS_INT32 = 2;
Yao Chen288c6002017-12-12 13:43:18 -080055
Muhammad Qureshi844694b2019-04-05 10:10:40 -070056// for ActiveConfig
57const int FIELD_ID_ACTIVE_CONFIG_ID = 1;
58const int FIELD_ID_ACTIVE_CONFIG_UID = 2;
59const int FIELD_ID_ACTIVE_CONFIG_METRIC = 3;
60
Yao Chend10f7b12017-12-18 12:53:50 -080061MetricsManager::MetricsManager(const ConfigKey& key, const StatsdConfig& config,
Yangster-mac15f6bbc2018-04-08 11:52:26 -070062 const int64_t timeBaseNs, const int64_t currentTimeNs,
Chenjie Yue2219202018-06-08 10:07:51 -070063 const sp<UidMap>& uidMap,
64 const sp<StatsPullerManager>& pullerManager,
Yangster-mac932ecec2018-02-01 10:23:52 -080065 const sp<AlarmMonitor>& anomalyAlarmMonitor,
66 const sp<AlarmMonitor>& periodicAlarmMonitor)
Chenjie Yue2219202018-06-08 10:07:51 -070067 : mConfigKey(key),
68 mUidMap(uidMap),
Yangster-macb142cc82018-03-30 15:22:08 -070069 mTtlNs(config.has_ttl_in_seconds() ? config.ttl_in_seconds() * NS_PER_SEC : -1),
70 mTtlEndNs(-1),
David Chen48944902018-05-03 10:29:11 -070071 mLastReportTimeNs(currentTimeNs),
Yao Chen9a43b4f2019-04-10 10:43:20 -070072 mLastReportWallClockNs(getWallClockNs()),
73 mShouldPersistHistory(config.persist_locally()) {
Yangster-macb142cc82018-03-30 15:22:08 -070074 // Init the ttl end timestamp.
Yangster-mac15f6bbc2018-04-08 11:52:26 -070075 refreshTtl(timeBaseNs);
Yangster-macb142cc82018-03-30 15:22:08 -070076
Chenjie Yue2219202018-06-08 10:07:51 -070077 mConfigValid = initStatsdConfig(
78 key, config, *uidMap, pullerManager, anomalyAlarmMonitor, periodicAlarmMonitor,
79 timeBaseNs, currentTimeNs, mTagIds, mAllAtomMatchers, mAllConditionTrackers,
80 mAllMetricProducers, mAllAnomalyTrackers, mAllPeriodicAlarmTrackers,
Yangster-mac849dfdc22018-10-12 15:41:45 -070081 mConditionToMetricMap, mTrackerToMetricMap, mTrackerToConditionMap,
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -070082 mActivationAtomTrackerToMetricMap, mDeactivationAtomTrackerToMetricMap,
83 mMetricIndexesWithActivation, mNoReportMetricIds);
Yao Chenb3561512017-11-21 18:07:17 -080084
Yangster-mac1c58f042018-05-17 15:52:51 -070085 mHashStringsInReport = config.hash_strings_in_metric_report();
dwchen730403e2018-10-29 11:41:56 -070086 mVersionStringsInReport = config.version_strings_in_metric_report();
87 mInstallerInReport = config.installer_in_metric_report();
Yangster-mac1c58f042018-05-17 15:52:51 -070088
Yao Chen147ce602017-12-22 14:35:34 -080089 if (config.allowed_log_source_size() == 0) {
David Chen8faaa012018-02-28 15:54:36 -080090 mConfigValid = false;
91 ALOGE("Log source whitelist is empty! This config won't get any data. Suggest adding at "
92 "least AID_SYSTEM and AID_STATSD to the allowed_log_source field.");
Yao Chend10f7b12017-12-18 12:53:50 -080093 } else {
Yao Chen147ce602017-12-22 14:35:34 -080094 for (const auto& source : config.allowed_log_source()) {
95 auto it = UidMap::sAidToUidMapping.find(source);
96 if (it != UidMap::sAidToUidMapping.end()) {
97 mAllowedUid.push_back(it->second);
98 } else {
99 mAllowedPkg.push_back(source);
100 }
101 }
Yao Chend10f7b12017-12-18 12:53:50 -0800102
103 if (mAllowedUid.size() + mAllowedPkg.size() > StatsdStats::kMaxLogSourceCount) {
104 ALOGE("Too many log sources. This is likely to be an error in the config.");
105 mConfigValid = false;
106 } else {
107 initLogSourceWhiteList();
108 }
109 }
110
David Chenfaa1af52018-03-30 15:14:04 -0700111 // Store the sub-configs used.
112 for (const auto& annotation : config.annotation()) {
113 mAnnotations.emplace_back(annotation.field_int64(), annotation.field_int32());
114 }
115
Yao Chenb3561512017-11-21 18:07:17 -0800116 // Guardrail. Reject the config if it's too big.
117 if (mAllMetricProducers.size() > StatsdStats::kMaxMetricCountPerConfig ||
118 mAllConditionTrackers.size() > StatsdStats::kMaxConditionCountPerConfig ||
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800119 mAllAtomMatchers.size() > StatsdStats::kMaxMatcherCountPerConfig) {
Yao Chenb3561512017-11-21 18:07:17 -0800120 ALOGE("This config is too big! Reject!");
121 mConfigValid = false;
122 }
Bookatz1476ef22018-02-13 12:26:01 -0800123 if (mAllAnomalyTrackers.size() > StatsdStats::kMaxAlertCountPerConfig) {
124 ALOGE("This config has too many alerts! Reject!");
125 mConfigValid = false;
126 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800127
128 mIsAlwaysActive = (mMetricIndexesWithActivation.size() != mAllMetricProducers.size()) ||
129 (mAllMetricProducers.size() == 0);
130 bool isActive = mIsAlwaysActive;
131 for (int metric : mMetricIndexesWithActivation) {
132 isActive |= mAllMetricProducers[metric]->isActive();
133 }
134 mIsActive = isActive;
135 VLOG("mIsActive is initialized to %d", mIsActive)
136
Yao Chenf09569f2017-12-13 17:00:51 -0800137 // no matter whether this config is valid, log it in the stats.
David Chenfaa1af52018-03-30 15:14:04 -0700138 StatsdStats::getInstance().noteConfigReceived(
139 key, mAllMetricProducers.size(), mAllConditionTrackers.size(), mAllAtomMatchers.size(),
140 mAllAnomalyTrackers.size(), mAnnotations, mConfigValid);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800141 // Check active
142 for (const auto& metric : mAllMetricProducers) {
143 if (metric->isActive()) {
144 mIsActive = true;
145 break;
146 }
147 }
Yao Chen44cf27c2017-09-14 22:32:50 -0700148}
149
150MetricsManager::~MetricsManager() {
tsaichristined21aacf2019-10-07 14:47:38 -0700151 for (auto it : mAllMetricProducers) {
152 for (int atomId : it->getSlicedStateAtoms()) {
153 StateManager::getInstance().unregisterListener(atomId, it);
154 }
155 }
156
Bookatzd3606c72017-10-19 10:13:49 -0700157 VLOG("~MetricsManager()");
Yao Chen44cf27c2017-09-14 22:32:50 -0700158}
159
Yao Chend10f7b12017-12-18 12:53:50 -0800160void MetricsManager::initLogSourceWhiteList() {
161 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
162 mAllowedLogSources.clear();
163 mAllowedLogSources.insert(mAllowedUid.begin(), mAllowedUid.end());
164
165 for (const auto& pkg : mAllowedPkg) {
166 auto uids = mUidMap->getAppUid(pkg);
167 mAllowedLogSources.insert(uids.begin(), uids.end());
168 }
169 if (DEBUG) {
170 for (const auto& uid : mAllowedLogSources) {
171 VLOG("Allowed uid %d", uid);
172 }
173 }
174}
175
Yao Chencaf339d2017-10-06 16:01:10 -0700176bool MetricsManager::isConfigValid() const {
177 return mConfigValid;
178}
179
Yangster-macb142cc82018-03-30 15:22:08 -0700180void MetricsManager::notifyAppUpgrade(const int64_t& eventTimeNs, const string& apk, const int uid,
David Chen27785a82018-01-19 17:06:45 -0800181 const int64_t version) {
Tej Singh9ec159a2019-11-14 11:59:48 -0800182 // Inform all metric producers.
183 for (auto it : mAllMetricProducers) {
184 it->notifyAppUpgrade(eventTimeNs, apk, uid, version);
185 }
Yao Chend10f7b12017-12-18 12:53:50 -0800186 // check if we care this package
187 if (std::find(mAllowedPkg.begin(), mAllowedPkg.end(), apk) == mAllowedPkg.end()) {
188 return;
189 }
190 // We will re-initialize the whole list because we don't want to keep the multi mapping of
191 // UID<->pkg inside MetricsManager to reduce the memory usage.
192 initLogSourceWhiteList();
193}
194
Yangster-macb142cc82018-03-30 15:22:08 -0700195void MetricsManager::notifyAppRemoved(const int64_t& eventTimeNs, const string& apk,
David Chen27785a82018-01-19 17:06:45 -0800196 const int uid) {
Tej Singh9ec159a2019-11-14 11:59:48 -0800197 // Inform all metric producers.
198 for (auto it : mAllMetricProducers) {
199 it->notifyAppRemoved(eventTimeNs, apk, uid);
200 }
Yao Chend10f7b12017-12-18 12:53:50 -0800201 // check if we care this package
202 if (std::find(mAllowedPkg.begin(), mAllowedPkg.end(), apk) == mAllowedPkg.end()) {
203 return;
204 }
205 // We will re-initialize the whole list because we don't want to keep the multi mapping of
206 // UID<->pkg inside MetricsManager to reduce the memory usage.
207 initLogSourceWhiteList();
208}
209
Yangster-macb142cc82018-03-30 15:22:08 -0700210void MetricsManager::onUidMapReceived(const int64_t& eventTimeNs) {
Tej Singh9ec159a2019-11-14 11:59:48 -0800211 // Purposefully don't inform metric producers on a new snapshot
212 // because we don't need to flush partial buckets.
213 // This occurs if a new user is added/removed or statsd crashes.
Yao Chend10f7b12017-12-18 12:53:50 -0800214 if (mAllowedPkg.size() == 0) {
215 return;
216 }
217 initLogSourceWhiteList();
218}
219
Yao Chen884c8c12018-01-26 10:36:25 -0800220void MetricsManager::dumpStates(FILE* out, bool verbose) {
221 fprintf(out, "ConfigKey %s, allowed source:", mConfigKey.ToString().c_str());
222 {
223 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
224 for (const auto& source : mAllowedLogSources) {
225 fprintf(out, "%d ", source);
226 }
227 }
228 fprintf(out, "\n");
229 for (const auto& producer : mAllMetricProducers) {
230 producer->dumpStates(out, verbose);
231 }
232}
233
Yangster-macb142cc82018-03-30 15:22:08 -0700234void MetricsManager::dropData(const int64_t dropTimeNs) {
Yao Chen06dba5d2018-01-26 13:38:16 -0800235 for (const auto& producer : mAllMetricProducers) {
236 producer->dropData(dropTimeNs);
237 }
238}
239
Yangster-mace68f3a52018-04-04 00:01:43 -0700240void MetricsManager::onDumpReport(const int64_t dumpTimeStampNs,
241 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700242 const bool erase_data,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000243 const DumpLatency dumpLatency,
Yangster-mac9def8e32018-04-17 13:55:51 -0700244 std::set<string> *str_set,
Yangster-mace68f3a52018-04-04 00:01:43 -0700245 ProtoOutputStream* protoOutput) {
Yao Chen729093d2017-10-16 10:33:26 -0700246 VLOG("=========================Metric Reports Start==========================");
247 // one StatsLogReport per MetricProduer
Yangster-mac94e197c2018-01-02 16:03:03 -0800248 for (const auto& producer : mAllMetricProducers) {
249 if (mNoReportMetricIds.find(producer->getMetricId()) == mNoReportMetricIds.end()) {
Yangster-mac9def8e32018-04-17 13:55:51 -0700250 uint64_t token = protoOutput->start(
251 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_METRICS);
Yangster-mac1c58f042018-05-17 15:52:51 -0700252 if (mHashStringsInReport) {
Bookatzff71cad2018-09-20 17:17:49 -0700253 producer->onDumpReport(dumpTimeStampNs, include_current_partial_bucket, erase_data,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000254 dumpLatency, str_set, protoOutput);
Yangster-mac1c58f042018-05-17 15:52:51 -0700255 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700256 producer->onDumpReport(dumpTimeStampNs, include_current_partial_bucket, erase_data,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000257 dumpLatency, nullptr, protoOutput);
Yangster-mac1c58f042018-05-17 15:52:51 -0700258 }
Yangster-mac94e197c2018-01-02 16:03:03 -0800259 protoOutput->end(token);
Yangster-maca802d732018-04-24 07:50:38 -0700260 } else {
261 producer->clearPastBuckets(dumpTimeStampNs);
Yangster-mac94e197c2018-01-02 16:03:03 -0800262 }
Yao Chen729093d2017-10-16 10:33:26 -0700263 }
David Chenfaa1af52018-03-30 15:14:04 -0700264 for (const auto& annotation : mAnnotations) {
265 uint64_t token = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
266 FIELD_ID_ANNOTATIONS);
267 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ANNOTATIONS_INT64,
268 (long long)annotation.first);
269 protoOutput->write(FIELD_TYPE_INT32 | FIELD_ID_ANNOTATIONS_INT32, annotation.second);
270 protoOutput->end(token);
271 }
Yangster-mac9def8e32018-04-17 13:55:51 -0700272
Yangster-mac330af582018-02-08 15:24:38 -0800273 mLastReportTimeNs = dumpTimeStampNs;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -0800274 mLastReportWallClockNs = getWallClockNs();
Yao Chen729093d2017-10-16 10:33:26 -0700275 VLOG("=========================Metric Reports End==========================");
Yao Chen729093d2017-10-16 10:33:26 -0700276}
277
Yao Chencaf339d2017-10-06 16:01:10 -0700278
Andrei Oneada01ea52019-01-30 15:28:36 +0000279bool MetricsManager::checkLogCredentials(const LogEvent& event) {
280 if (android::util::AtomsInfo::kWhitelistedAtoms.find(event.GetTagId()) !=
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700281 android::util::AtomsInfo::kWhitelistedAtoms.end())
Andrei Oneada01ea52019-01-30 15:28:36 +0000282 {
283 return true;
284 }
285 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
286 if (mAllowedLogSources.find(event.GetUid()) == mAllowedLogSources.end()) {
287 VLOG("log source %d not on the whitelist", event.GetUid());
288 return false;
289 }
290 return true;
291}
292
293bool MetricsManager::eventSanityCheck(const LogEvent& event) {
David Chenb639d142018-02-14 17:29:54 -0800294 if (event.GetTagId() == android::util::APP_BREADCRUMB_REPORTED) {
295 // Check that app breadcrumb reported fields are valid.
David Chendaa9f3a2017-12-28 16:52:22 -0800296 status_t err = NO_ERROR;
Bookatzb223c4e2018-02-01 15:35:04 -0800297
298 // Uid is 3rd from last field and must match the caller's uid,
299 // unless that caller is statsd itself (statsd is allowed to spoof uids).
300 long appHookUid = event.GetLong(event.size()-2, &err);
David Chen77ef6712018-02-23 18:23:42 -0800301 if (err != NO_ERROR ) {
302 VLOG("APP_BREADCRUMB_REPORTED had error when parsing the uid");
Andrei Oneada01ea52019-01-30 15:28:36 +0000303 return false;
David Chen77ef6712018-02-23 18:23:42 -0800304 }
Bookatzb223c4e2018-02-01 15:35:04 -0800305 int32_t loggerUid = event.GetUid();
David Chen77ef6712018-02-23 18:23:42 -0800306 if (loggerUid != appHookUid && loggerUid != AID_STATSD) {
307 VLOG("APP_BREADCRUMB_REPORTED has invalid uid: claimed %ld but caller is %d",
308 appHookUid, loggerUid);
Andrei Oneada01ea52019-01-30 15:28:36 +0000309 return false;
David Chendaa9f3a2017-12-28 16:52:22 -0800310 }
Bookatzb223c4e2018-02-01 15:35:04 -0800311
David Chendaa9f3a2017-12-28 16:52:22 -0800312 // The state must be from 0,3. This part of code must be manually updated.
Bookatzb223c4e2018-02-01 15:35:04 -0800313 long appHookState = event.GetLong(event.size(), &err);
David Chen77ef6712018-02-23 18:23:42 -0800314 if (err != NO_ERROR ) {
315 VLOG("APP_BREADCRUMB_REPORTED had error when parsing the state field");
Andrei Oneada01ea52019-01-30 15:28:36 +0000316 return false;
David Chen77ef6712018-02-23 18:23:42 -0800317 } else if (appHookState < 0 || appHookState > 3) {
318 VLOG("APP_BREADCRUMB_REPORTED does not have valid state %ld", appHookState);
Andrei Oneada01ea52019-01-30 15:28:36 +0000319 return false;
David Chendaa9f3a2017-12-28 16:52:22 -0800320 }
Tej Singhbb8554a2018-01-26 11:59:14 -0800321 } else if (event.GetTagId() == android::util::DAVEY_OCCURRED) {
322 // Daveys can be logged from any app since they are logged in libs/hwui/JankTracker.cpp.
323 // Check that the davey duration is reasonable. Max length check is for privacy.
324 status_t err = NO_ERROR;
David Chen77ef6712018-02-23 18:23:42 -0800325
326 // Uid is the first field provided.
327 long jankUid = event.GetLong(1, &err);
328 if (err != NO_ERROR ) {
329 VLOG("Davey occurred had error when parsing the uid");
Andrei Oneada01ea52019-01-30 15:28:36 +0000330 return false;
David Chen77ef6712018-02-23 18:23:42 -0800331 }
332 int32_t loggerUid = event.GetUid();
333 if (loggerUid != jankUid && loggerUid != AID_STATSD) {
334 VLOG("DAVEY_OCCURRED has invalid uid: claimed %ld but caller is %d", jankUid,
335 loggerUid);
Andrei Oneada01ea52019-01-30 15:28:36 +0000336 return false;
David Chen77ef6712018-02-23 18:23:42 -0800337 }
338
Tej Singhbb8554a2018-01-26 11:59:14 -0800339 long duration = event.GetLong(event.size(), &err);
David Chen77ef6712018-02-23 18:23:42 -0800340 if (err != NO_ERROR ) {
341 VLOG("Davey occurred had error when parsing the duration");
Andrei Oneada01ea52019-01-30 15:28:36 +0000342 return false;
David Chen77ef6712018-02-23 18:23:42 -0800343 } else if (duration > 100000) {
Tej Singhbb8554a2018-01-26 11:59:14 -0800344 VLOG("Davey duration is unreasonably long: %ld", duration);
Andrei Oneada01ea52019-01-30 15:28:36 +0000345 return false;
Tej Singhbb8554a2018-01-26 11:59:14 -0800346 }
Andrei Oneada01ea52019-01-30 15:28:36 +0000347 }
348
349 return true;
350}
351
352// Consume the stats log if it's interesting to this metric.
353void MetricsManager::onLogEvent(const LogEvent& event) {
354 if (!mConfigValid) {
355 return;
356 }
357
358 if (!checkLogCredentials(event)) {
359 return;
360 }
361
362 if (!eventSanityCheck(event)) {
363 return;
Yao Chend10f7b12017-12-18 12:53:50 -0800364 }
365
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700366 int tagId = event.GetTagId();
Yangster-mac849dfdc22018-10-12 15:41:45 -0700367 int64_t eventTimeNs = event.GetElapsedTimestampNs();
368
Tej Singh6ede28b2019-01-29 17:06:54 -0800369 bool isActive = mIsAlwaysActive;
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700370
371 // Set of metrics that are still active after flushing.
372 unordered_set<int> activeMetricsIndices;
373
374 // Update state of all metrics w/ activation conditions as of eventTimeNs.
375 for (int metricIndex : mMetricIndexesWithActivation) {
376 const sp<MetricProducer>& metric = mAllMetricProducers[metricIndex];
377 metric->flushIfExpire(eventTimeNs);
378 if (metric->isActive()) {
379 // If this metric w/ activation condition is still active after
380 // flushing, remember it.
381 activeMetricsIndices.insert(metricIndex);
382 }
Yangster-mac849dfdc22018-10-12 15:41:45 -0700383 }
384
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700385 mIsActive = isActive || !activeMetricsIndices.empty();
Tej Singh6ede28b2019-01-29 17:06:54 -0800386
Yao Chen44cf27c2017-09-14 22:32:50 -0700387 if (mTagIds.find(tagId) == mTagIds.end()) {
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700388 // Not interesting...
Yao Chen44cf27c2017-09-14 22:32:50 -0700389 return;
390 }
Yao Chen44cf27c2017-09-14 22:32:50 -0700391
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800392 vector<MatchingState> matcherCache(mAllAtomMatchers.size(), MatchingState::kNotComputed);
Yao Chencaf339d2017-10-06 16:01:10 -0700393
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700394 // Evaluate all atom matchers.
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800395 for (auto& matcher : mAllAtomMatchers) {
396 matcher->onLogEvent(event, mAllAtomMatchers, matcherCache);
Yao Chen44cf27c2017-09-14 22:32:50 -0700397 }
398
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700399 // Set of metrics that received an activation cancellation.
400 unordered_set<int> metricIndicesWithCanceledActivations;
401
402 // Determine which metric activations received a cancellation and cancel them.
403 for (const auto& it : mDeactivationAtomTrackerToMetricMap) {
404 if (matcherCache[it.first] == MatchingState::kMatched) {
405 for (int metricIndex : it.second) {
406 mAllMetricProducers[metricIndex]->cancelEventActivation(it.first);
407 metricIndicesWithCanceledActivations.insert(metricIndex);
408 }
409 }
410 }
411
412 // Determine whether any metrics are no longer active after cancelling metric activations.
413 for (const int metricIndex : metricIndicesWithCanceledActivations) {
414 const sp<MetricProducer>& metric = mAllMetricProducers[metricIndex];
415 metric->flushIfExpire(eventTimeNs);
416 if (!metric->isActive()) {
417 activeMetricsIndices.erase(metricIndex);
418 }
419 }
420
421 isActive |= !activeMetricsIndices.empty();
422
423
424 // Determine which metric activations should be turned on and turn them on
Yangster-mac849dfdc22018-10-12 15:41:45 -0700425 for (const auto& it : mActivationAtomTrackerToMetricMap) {
426 if (matcherCache[it.first] == MatchingState::kMatched) {
427 for (int metricIndex : it.second) {
428 mAllMetricProducers[metricIndex]->activate(it.first, eventTimeNs);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800429 isActive |= mAllMetricProducers[metricIndex]->isActive();
Yangster-mac849dfdc22018-10-12 15:41:45 -0700430 }
431 }
432 }
433
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800434 mIsActive = isActive;
435
Yao Chencaf339d2017-10-06 16:01:10 -0700436 // A bitmap to see which ConditionTracker needs to be re-evaluated.
437 vector<bool> conditionToBeEvaluated(mAllConditionTrackers.size(), false);
438
439 for (const auto& pair : mTrackerToConditionMap) {
440 if (matcherCache[pair.first] == MatchingState::kMatched) {
441 const auto& conditionList = pair.second;
442 for (const int conditionIndex : conditionList) {
443 conditionToBeEvaluated[conditionIndex] = true;
444 }
445 }
446 }
447
448 vector<ConditionState> conditionCache(mAllConditionTrackers.size(),
449 ConditionState::kNotEvaluated);
450 // A bitmap to track if a condition has changed value.
451 vector<bool> changedCache(mAllConditionTrackers.size(), false);
452 for (size_t i = 0; i < mAllConditionTrackers.size(); i++) {
453 if (conditionToBeEvaluated[i] == false) {
454 continue;
455 }
Yao Chencaf339d2017-10-06 16:01:10 -0700456 sp<ConditionTracker>& condition = mAllConditionTrackers[i];
457 condition->evaluateCondition(event, matcherCache, mAllConditionTrackers, conditionCache,
Yao Chen967b2052017-11-07 16:36:43 -0800458 changedCache);
Yao Chen729093d2017-10-16 10:33:26 -0700459 }
460
461 for (size_t i = 0; i < mAllConditionTrackers.size(); i++) {
Yao Chen967b2052017-11-07 16:36:43 -0800462 if (changedCache[i] == false) {
Yao Chen729093d2017-10-16 10:33:26 -0700463 continue;
464 }
465 auto pair = mConditionToMetricMap.find(i);
466 if (pair != mConditionToMetricMap.end()) {
467 auto& metricList = pair->second;
468 for (auto metricIndex : metricList) {
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700469 // Metric cares about non sliced condition, and it's changed.
Yao Chen729093d2017-10-16 10:33:26 -0700470 // Push the new condition to it directly.
Yao Chen967b2052017-11-07 16:36:43 -0800471 if (!mAllMetricProducers[metricIndex]->isConditionSliced()) {
Yao Chen5154a3792017-10-30 22:57:06 -0700472 mAllMetricProducers[metricIndex]->onConditionChanged(conditionCache[i],
Yangster-mac849dfdc22018-10-12 15:41:45 -0700473 eventTimeNs);
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700474 // Metric cares about sliced conditions, and it may have changed. Send
Yao Chen729093d2017-10-16 10:33:26 -0700475 // notification, and the metric can query the sliced conditions that are
476 // interesting to it.
Yangsterf2bee6f2017-11-29 12:01:05 -0800477 } else {
Yao Chen427d3722018-03-22 15:21:52 -0700478 mAllMetricProducers[metricIndex]->onSlicedConditionMayChange(conditionCache[i],
Yangster-mac849dfdc22018-10-12 15:41:45 -0700479 eventTimeNs);
Yao Chen44cf27c2017-09-14 22:32:50 -0700480 }
Yao Chencaf339d2017-10-06 16:01:10 -0700481 }
482 }
483 }
484
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800485 // For matched AtomMatchers, tell relevant metrics that a matched event has come.
486 for (size_t i = 0; i < mAllAtomMatchers.size(); i++) {
Yao Chencaf339d2017-10-06 16:01:10 -0700487 if (matcherCache[i] == MatchingState::kMatched) {
Yao Chenb3561512017-11-21 18:07:17 -0800488 StatsdStats::getInstance().noteMatcherMatched(mConfigKey,
Yangster-mac94e197c2018-01-02 16:03:03 -0800489 mAllAtomMatchers[i]->getId());
Yao Chencaf339d2017-10-06 16:01:10 -0700490 auto pair = mTrackerToMetricMap.find(i);
491 if (pair != mTrackerToMetricMap.end()) {
492 auto& metricList = pair->second;
493 for (const int metricIndex : metricList) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700494 // pushed metrics are never scheduled pulls
Chenjie Yua7259ab2017-12-10 08:31:05 -0800495 mAllMetricProducers[metricIndex]->onMatchedLogEvent(i, event);
Yao Chencaf339d2017-10-06 16:01:10 -0700496 }
Yao Chen44cf27c2017-09-14 22:32:50 -0700497 }
498 }
499 }
500}
501
Yangster-mac932ecec2018-02-01 10:23:52 -0800502void MetricsManager::onAnomalyAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700503 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800504 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& alarmSet) {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800505 for (const auto& itr : mAllAnomalyTrackers) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800506 itr->informAlarmsFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800507 }
508}
509
Yangster-mac932ecec2018-02-01 10:23:52 -0800510void MetricsManager::onPeriodicAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700511 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800512 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& alarmSet) {
513 for (const auto& itr : mAllPeriodicAlarmTrackers) {
514 itr->informAlarmsFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800515 }
516}
517
yro69007c82017-10-26 20:42:57 -0700518// Returns the total byte size of all metrics managed by a single config source.
519size_t MetricsManager::byteSize() {
520 size_t totalSize = 0;
Chih-Hung Hsieha1b644e2018-12-11 11:09:20 -0800521 for (const auto& metricProducer : mAllMetricProducers) {
yro69007c82017-10-26 20:42:57 -0700522 totalSize += metricProducer->byteSize();
523 }
524 return totalSize;
525}
526
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700527void MetricsManager::loadActiveConfig(const ActiveConfig& config, int64_t currentTimeNs) {
528 if (config.metric_size() == 0) {
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800529 ALOGW("No active metric for config %s", mConfigKey.ToString().c_str());
530 return;
531 }
532
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700533 for (int i = 0; i < config.metric_size(); i++) {
534 const auto& activeMetric = config.metric(i);
535 for (int metricIndex : mMetricIndexesWithActivation) {
536 const auto& metric = mAllMetricProducers[metricIndex];
537 if (metric->getMetricId() == activeMetric.id()) {
538 VLOG("Setting active metric: %lld", (long long)metric->getMetricId());
539 metric->loadActiveMetric(activeMetric, currentTimeNs);
Tej Singh16ca28f2019-06-24 11:58:23 -0700540 if (!mIsActive && metric->isActive()) {
541 StatsdStats::getInstance().noteActiveStatusChanged(mConfigKey,
542 /*activate=*/ true);
543 }
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700544 mIsActive |= metric->isActive();
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800545 }
546 }
547 }
548}
549
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700550void MetricsManager::writeActiveConfigToProtoOutputStream(
Tej Singhf53d4452019-05-09 18:17:59 -0700551 int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto) {
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700552 proto->write(FIELD_TYPE_INT64 | FIELD_ID_ACTIVE_CONFIG_ID, (long long)mConfigKey.GetId());
553 proto->write(FIELD_TYPE_INT32 | FIELD_ID_ACTIVE_CONFIG_UID, mConfigKey.GetUid());
554 for (int metricIndex : mMetricIndexesWithActivation) {
555 const auto& metric = mAllMetricProducers[metricIndex];
556 const uint64_t metricToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
557 FIELD_ID_ACTIVE_CONFIG_METRIC);
Tej Singhf53d4452019-05-09 18:17:59 -0700558 metric->writeActiveMetricToProtoOutputStream(currentTimeNs, reason, proto);
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700559 proto->end(metricToken);
560 }
561}
562
563
564
565
Yao Chen44cf27c2017-09-14 22:32:50 -0700566} // namespace statsd
567} // namespace os
568} // namespace android