blob: 464cec36d5e3027eed60ca924e87283a2bf5d6a5 [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
21#include <log/logprint.h>
22#include <private/android_filesystem_config.h>
23#include <utils/SystemClock.h>
Yao Chen93fe3a32017-11-02 13:52:59 -070024
Yao Chen44cf27c2017-09-14 22:32:50 -070025#include "CountMetricProducer.h"
Yao Chen93fe3a32017-11-02 13:52:59 -070026#include "condition/CombinationConditionTracker.h"
27#include "condition/SimpleConditionTracker.h"
Yao Chenb3561512017-11-21 18:07:17 -080028#include "guardrail/StatsdStats.h"
Yao Chen93fe3a32017-11-02 13:52:59 -070029#include "matchers/CombinationLogMatchingTracker.h"
30#include "matchers/SimpleLogMatchingTracker.h"
Yao Chencaf339d2017-10-06 16:01:10 -070031#include "metrics_manager_util.h"
tsaichristined21aacf2019-10-07 14:47:38 -070032#include "state/StateManager.h"
Yangster-mac330af582018-02-08 15:24:38 -080033#include "stats_log_util.h"
tsaichristined21aacf2019-10-07 14:47:38 -070034#include "stats_util.h"
35#include "statslog.h"
Yao Chen288c6002017-12-12 13:43:18 -080036
37using android::util::FIELD_COUNT_REPEATED;
David Chenfaa1af52018-03-30 15:14:04 -070038using android::util::FIELD_TYPE_INT32;
39using android::util::FIELD_TYPE_INT64;
Yao Chen288c6002017-12-12 13:43:18 -080040using android::util::FIELD_TYPE_MESSAGE;
Yangster-mac9def8e32018-04-17 13:55:51 -070041using android::util::FIELD_TYPE_STRING;
Yao Chen288c6002017-12-12 13:43:18 -080042using android::util::ProtoOutputStream;
43
Yao Chen44cf27c2017-09-14 22:32:50 -070044using std::make_unique;
45using std::set;
46using std::string;
Yao Chen44cf27c2017-09-14 22:32:50 -070047using std::unordered_map;
48using std::vector;
49
50namespace android {
51namespace os {
52namespace statsd {
53
Yao Chen288c6002017-12-12 13:43:18 -080054const int FIELD_ID_METRICS = 1;
David Chenfaa1af52018-03-30 15:14:04 -070055const int FIELD_ID_ANNOTATIONS = 7;
56const int FIELD_ID_ANNOTATIONS_INT64 = 1;
57const int FIELD_ID_ANNOTATIONS_INT32 = 2;
Yao Chen288c6002017-12-12 13:43:18 -080058
Muhammad Qureshi844694b2019-04-05 10:10:40 -070059// for ActiveConfig
60const int FIELD_ID_ACTIVE_CONFIG_ID = 1;
61const int FIELD_ID_ACTIVE_CONFIG_UID = 2;
62const int FIELD_ID_ACTIVE_CONFIG_METRIC = 3;
63
Yao Chend10f7b12017-12-18 12:53:50 -080064MetricsManager::MetricsManager(const ConfigKey& key, const StatsdConfig& config,
Yangster-mac15f6bbc2018-04-08 11:52:26 -070065 const int64_t timeBaseNs, const int64_t currentTimeNs,
Chenjie Yue2219202018-06-08 10:07:51 -070066 const sp<UidMap>& uidMap,
67 const sp<StatsPullerManager>& pullerManager,
Yangster-mac932ecec2018-02-01 10:23:52 -080068 const sp<AlarmMonitor>& anomalyAlarmMonitor,
69 const sp<AlarmMonitor>& periodicAlarmMonitor)
Chenjie Yue2219202018-06-08 10:07:51 -070070 : mConfigKey(key),
71 mUidMap(uidMap),
Yangster-macb142cc82018-03-30 15:22:08 -070072 mTtlNs(config.has_ttl_in_seconds() ? config.ttl_in_seconds() * NS_PER_SEC : -1),
73 mTtlEndNs(-1),
David Chen48944902018-05-03 10:29:11 -070074 mLastReportTimeNs(currentTimeNs),
Yao Chen9a43b4f2019-04-10 10:43:20 -070075 mLastReportWallClockNs(getWallClockNs()),
76 mShouldPersistHistory(config.persist_locally()) {
Yangster-macb142cc82018-03-30 15:22:08 -070077 // Init the ttl end timestamp.
Yangster-mac15f6bbc2018-04-08 11:52:26 -070078 refreshTtl(timeBaseNs);
Yangster-macb142cc82018-03-30 15:22:08 -070079
Chenjie Yue2219202018-06-08 10:07:51 -070080 mConfigValid = initStatsdConfig(
81 key, config, *uidMap, pullerManager, anomalyAlarmMonitor, periodicAlarmMonitor,
82 timeBaseNs, currentTimeNs, mTagIds, mAllAtomMatchers, mAllConditionTrackers,
83 mAllMetricProducers, mAllAnomalyTrackers, mAllPeriodicAlarmTrackers,
Yangster-mac849dfdc22018-10-12 15:41:45 -070084 mConditionToMetricMap, mTrackerToMetricMap, mTrackerToConditionMap,
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -070085 mActivationAtomTrackerToMetricMap, mDeactivationAtomTrackerToMetricMap,
86 mMetricIndexesWithActivation, mNoReportMetricIds);
Yao Chenb3561512017-11-21 18:07:17 -080087
Yangster-mac1c58f042018-05-17 15:52:51 -070088 mHashStringsInReport = config.hash_strings_in_metric_report();
dwchen730403e2018-10-29 11:41:56 -070089 mVersionStringsInReport = config.version_strings_in_metric_report();
90 mInstallerInReport = config.installer_in_metric_report();
Yangster-mac1c58f042018-05-17 15:52:51 -070091
Yao Chen147ce602017-12-22 14:35:34 -080092 if (config.allowed_log_source_size() == 0) {
David Chen8faaa012018-02-28 15:54:36 -080093 mConfigValid = false;
94 ALOGE("Log source whitelist is empty! This config won't get any data. Suggest adding at "
95 "least AID_SYSTEM and AID_STATSD to the allowed_log_source field.");
Yao Chend10f7b12017-12-18 12:53:50 -080096 } else {
Yao Chen147ce602017-12-22 14:35:34 -080097 for (const auto& source : config.allowed_log_source()) {
98 auto it = UidMap::sAidToUidMapping.find(source);
99 if (it != UidMap::sAidToUidMapping.end()) {
100 mAllowedUid.push_back(it->second);
101 } else {
102 mAllowedPkg.push_back(source);
103 }
104 }
Yao Chend10f7b12017-12-18 12:53:50 -0800105
106 if (mAllowedUid.size() + mAllowedPkg.size() > StatsdStats::kMaxLogSourceCount) {
107 ALOGE("Too many log sources. This is likely to be an error in the config.");
108 mConfigValid = false;
109 } else {
110 initLogSourceWhiteList();
111 }
112 }
113
David Chenfaa1af52018-03-30 15:14:04 -0700114 // Store the sub-configs used.
115 for (const auto& annotation : config.annotation()) {
116 mAnnotations.emplace_back(annotation.field_int64(), annotation.field_int32());
117 }
118
Yao Chenb3561512017-11-21 18:07:17 -0800119 // Guardrail. Reject the config if it's too big.
120 if (mAllMetricProducers.size() > StatsdStats::kMaxMetricCountPerConfig ||
121 mAllConditionTrackers.size() > StatsdStats::kMaxConditionCountPerConfig ||
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800122 mAllAtomMatchers.size() > StatsdStats::kMaxMatcherCountPerConfig) {
Yao Chenb3561512017-11-21 18:07:17 -0800123 ALOGE("This config is too big! Reject!");
124 mConfigValid = false;
125 }
Bookatz1476ef22018-02-13 12:26:01 -0800126 if (mAllAnomalyTrackers.size() > StatsdStats::kMaxAlertCountPerConfig) {
127 ALOGE("This config has too many alerts! Reject!");
128 mConfigValid = false;
129 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800130
131 mIsAlwaysActive = (mMetricIndexesWithActivation.size() != mAllMetricProducers.size()) ||
132 (mAllMetricProducers.size() == 0);
133 bool isActive = mIsAlwaysActive;
134 for (int metric : mMetricIndexesWithActivation) {
135 isActive |= mAllMetricProducers[metric]->isActive();
136 }
137 mIsActive = isActive;
138 VLOG("mIsActive is initialized to %d", mIsActive)
139
Yao Chenf09569f2017-12-13 17:00:51 -0800140 // no matter whether this config is valid, log it in the stats.
David Chenfaa1af52018-03-30 15:14:04 -0700141 StatsdStats::getInstance().noteConfigReceived(
142 key, mAllMetricProducers.size(), mAllConditionTrackers.size(), mAllAtomMatchers.size(),
143 mAllAnomalyTrackers.size(), mAnnotations, mConfigValid);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800144 // Check active
145 for (const auto& metric : mAllMetricProducers) {
146 if (metric->isActive()) {
147 mIsActive = true;
148 break;
149 }
150 }
Yao Chen44cf27c2017-09-14 22:32:50 -0700151}
152
153MetricsManager::~MetricsManager() {
tsaichristined21aacf2019-10-07 14:47:38 -0700154 for (auto it : mAllMetricProducers) {
155 for (int atomId : it->getSlicedStateAtoms()) {
156 StateManager::getInstance().unregisterListener(atomId, it);
157 }
158 }
159
Bookatzd3606c72017-10-19 10:13:49 -0700160 VLOG("~MetricsManager()");
Yao Chen44cf27c2017-09-14 22:32:50 -0700161}
162
Yao Chend10f7b12017-12-18 12:53:50 -0800163void MetricsManager::initLogSourceWhiteList() {
164 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
165 mAllowedLogSources.clear();
166 mAllowedLogSources.insert(mAllowedUid.begin(), mAllowedUid.end());
167
168 for (const auto& pkg : mAllowedPkg) {
169 auto uids = mUidMap->getAppUid(pkg);
170 mAllowedLogSources.insert(uids.begin(), uids.end());
171 }
172 if (DEBUG) {
173 for (const auto& uid : mAllowedLogSources) {
174 VLOG("Allowed uid %d", uid);
175 }
176 }
177}
178
Yao Chencaf339d2017-10-06 16:01:10 -0700179bool MetricsManager::isConfigValid() const {
180 return mConfigValid;
181}
182
Yangster-macb142cc82018-03-30 15:22:08 -0700183void MetricsManager::notifyAppUpgrade(const int64_t& eventTimeNs, const string& apk, const int uid,
David Chen27785a82018-01-19 17:06:45 -0800184 const int64_t version) {
Tej Singh9ec159a2019-11-14 11:59:48 -0800185 // Inform all metric producers.
186 for (auto it : mAllMetricProducers) {
187 it->notifyAppUpgrade(eventTimeNs, apk, uid, version);
188 }
Yao Chend10f7b12017-12-18 12:53:50 -0800189 // check if we care this package
190 if (std::find(mAllowedPkg.begin(), mAllowedPkg.end(), apk) == mAllowedPkg.end()) {
191 return;
192 }
193 // We will re-initialize the whole list because we don't want to keep the multi mapping of
194 // UID<->pkg inside MetricsManager to reduce the memory usage.
195 initLogSourceWhiteList();
196}
197
Yangster-macb142cc82018-03-30 15:22:08 -0700198void MetricsManager::notifyAppRemoved(const int64_t& eventTimeNs, const string& apk,
David Chen27785a82018-01-19 17:06:45 -0800199 const int uid) {
Tej Singh9ec159a2019-11-14 11:59:48 -0800200 // Inform all metric producers.
201 for (auto it : mAllMetricProducers) {
202 it->notifyAppRemoved(eventTimeNs, apk, uid);
203 }
Yao Chend10f7b12017-12-18 12:53:50 -0800204 // check if we care this package
205 if (std::find(mAllowedPkg.begin(), mAllowedPkg.end(), apk) == mAllowedPkg.end()) {
206 return;
207 }
208 // We will re-initialize the whole list because we don't want to keep the multi mapping of
209 // UID<->pkg inside MetricsManager to reduce the memory usage.
210 initLogSourceWhiteList();
211}
212
Yangster-macb142cc82018-03-30 15:22:08 -0700213void MetricsManager::onUidMapReceived(const int64_t& eventTimeNs) {
Tej Singh9ec159a2019-11-14 11:59:48 -0800214 // Purposefully don't inform metric producers on a new snapshot
215 // because we don't need to flush partial buckets.
216 // This occurs if a new user is added/removed or statsd crashes.
Yao Chend10f7b12017-12-18 12:53:50 -0800217 if (mAllowedPkg.size() == 0) {
218 return;
219 }
220 initLogSourceWhiteList();
221}
222
Yao Chen884c8c12018-01-26 10:36:25 -0800223void MetricsManager::dumpStates(FILE* out, bool verbose) {
224 fprintf(out, "ConfigKey %s, allowed source:", mConfigKey.ToString().c_str());
225 {
226 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
227 for (const auto& source : mAllowedLogSources) {
228 fprintf(out, "%d ", source);
229 }
230 }
231 fprintf(out, "\n");
232 for (const auto& producer : mAllMetricProducers) {
233 producer->dumpStates(out, verbose);
234 }
235}
236
Yangster-macb142cc82018-03-30 15:22:08 -0700237void MetricsManager::dropData(const int64_t dropTimeNs) {
Yao Chen06dba5d2018-01-26 13:38:16 -0800238 for (const auto& producer : mAllMetricProducers) {
239 producer->dropData(dropTimeNs);
240 }
241}
242
Yangster-mace68f3a52018-04-04 00:01:43 -0700243void MetricsManager::onDumpReport(const int64_t dumpTimeStampNs,
244 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700245 const bool erase_data,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000246 const DumpLatency dumpLatency,
Yangster-mac9def8e32018-04-17 13:55:51 -0700247 std::set<string> *str_set,
Yangster-mace68f3a52018-04-04 00:01:43 -0700248 ProtoOutputStream* protoOutput) {
Yao Chen729093d2017-10-16 10:33:26 -0700249 VLOG("=========================Metric Reports Start==========================");
250 // one StatsLogReport per MetricProduer
Yangster-mac94e197c2018-01-02 16:03:03 -0800251 for (const auto& producer : mAllMetricProducers) {
252 if (mNoReportMetricIds.find(producer->getMetricId()) == mNoReportMetricIds.end()) {
Yangster-mac9def8e32018-04-17 13:55:51 -0700253 uint64_t token = protoOutput->start(
254 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_METRICS);
Yangster-mac1c58f042018-05-17 15:52:51 -0700255 if (mHashStringsInReport) {
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, str_set, protoOutput);
Yangster-mac1c58f042018-05-17 15:52:51 -0700258 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700259 producer->onDumpReport(dumpTimeStampNs, include_current_partial_bucket, erase_data,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000260 dumpLatency, nullptr, protoOutput);
Yangster-mac1c58f042018-05-17 15:52:51 -0700261 }
Yangster-mac94e197c2018-01-02 16:03:03 -0800262 protoOutput->end(token);
Yangster-maca802d732018-04-24 07:50:38 -0700263 } else {
264 producer->clearPastBuckets(dumpTimeStampNs);
Yangster-mac94e197c2018-01-02 16:03:03 -0800265 }
Yao Chen729093d2017-10-16 10:33:26 -0700266 }
David Chenfaa1af52018-03-30 15:14:04 -0700267 for (const auto& annotation : mAnnotations) {
268 uint64_t token = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
269 FIELD_ID_ANNOTATIONS);
270 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ANNOTATIONS_INT64,
271 (long long)annotation.first);
272 protoOutput->write(FIELD_TYPE_INT32 | FIELD_ID_ANNOTATIONS_INT32, annotation.second);
273 protoOutput->end(token);
274 }
Yangster-mac9def8e32018-04-17 13:55:51 -0700275
Yangster-mac330af582018-02-08 15:24:38 -0800276 mLastReportTimeNs = dumpTimeStampNs;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -0800277 mLastReportWallClockNs = getWallClockNs();
Yao Chen729093d2017-10-16 10:33:26 -0700278 VLOG("=========================Metric Reports End==========================");
Yao Chen729093d2017-10-16 10:33:26 -0700279}
280
Yao Chencaf339d2017-10-06 16:01:10 -0700281
Andrei Oneada01ea52019-01-30 15:28:36 +0000282bool MetricsManager::checkLogCredentials(const LogEvent& event) {
283 if (android::util::AtomsInfo::kWhitelistedAtoms.find(event.GetTagId()) !=
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700284 android::util::AtomsInfo::kWhitelistedAtoms.end())
Andrei Oneada01ea52019-01-30 15:28:36 +0000285 {
286 return true;
287 }
288 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
289 if (mAllowedLogSources.find(event.GetUid()) == mAllowedLogSources.end()) {
290 VLOG("log source %d not on the whitelist", event.GetUid());
291 return false;
292 }
293 return true;
294}
295
296bool MetricsManager::eventSanityCheck(const LogEvent& event) {
David Chenb639d142018-02-14 17:29:54 -0800297 if (event.GetTagId() == android::util::APP_BREADCRUMB_REPORTED) {
298 // Check that app breadcrumb reported fields are valid.
David Chendaa9f3a2017-12-28 16:52:22 -0800299 status_t err = NO_ERROR;
Bookatzb223c4e2018-02-01 15:35:04 -0800300
301 // Uid is 3rd from last field and must match the caller's uid,
302 // unless that caller is statsd itself (statsd is allowed to spoof uids).
303 long appHookUid = event.GetLong(event.size()-2, &err);
David Chen77ef6712018-02-23 18:23:42 -0800304 if (err != NO_ERROR ) {
305 VLOG("APP_BREADCRUMB_REPORTED had error when parsing the uid");
Andrei Oneada01ea52019-01-30 15:28:36 +0000306 return false;
David Chen77ef6712018-02-23 18:23:42 -0800307 }
Bookatzb223c4e2018-02-01 15:35:04 -0800308 int32_t loggerUid = event.GetUid();
David Chen77ef6712018-02-23 18:23:42 -0800309 if (loggerUid != appHookUid && loggerUid != AID_STATSD) {
310 VLOG("APP_BREADCRUMB_REPORTED has invalid uid: claimed %ld but caller is %d",
311 appHookUid, loggerUid);
Andrei Oneada01ea52019-01-30 15:28:36 +0000312 return false;
David Chendaa9f3a2017-12-28 16:52:22 -0800313 }
Bookatzb223c4e2018-02-01 15:35:04 -0800314
David Chendaa9f3a2017-12-28 16:52:22 -0800315 // The state must be from 0,3. This part of code must be manually updated.
Bookatzb223c4e2018-02-01 15:35:04 -0800316 long appHookState = event.GetLong(event.size(), &err);
David Chen77ef6712018-02-23 18:23:42 -0800317 if (err != NO_ERROR ) {
318 VLOG("APP_BREADCRUMB_REPORTED had error when parsing the state field");
Andrei Oneada01ea52019-01-30 15:28:36 +0000319 return false;
David Chen77ef6712018-02-23 18:23:42 -0800320 } else if (appHookState < 0 || appHookState > 3) {
321 VLOG("APP_BREADCRUMB_REPORTED does not have valid state %ld", appHookState);
Andrei Oneada01ea52019-01-30 15:28:36 +0000322 return false;
David Chendaa9f3a2017-12-28 16:52:22 -0800323 }
Tej Singhbb8554a2018-01-26 11:59:14 -0800324 } else if (event.GetTagId() == android::util::DAVEY_OCCURRED) {
325 // Daveys can be logged from any app since they are logged in libs/hwui/JankTracker.cpp.
326 // Check that the davey duration is reasonable. Max length check is for privacy.
327 status_t err = NO_ERROR;
David Chen77ef6712018-02-23 18:23:42 -0800328
329 // Uid is the first field provided.
330 long jankUid = event.GetLong(1, &err);
331 if (err != NO_ERROR ) {
332 VLOG("Davey occurred had error when parsing the uid");
Andrei Oneada01ea52019-01-30 15:28:36 +0000333 return false;
David Chen77ef6712018-02-23 18:23:42 -0800334 }
335 int32_t loggerUid = event.GetUid();
336 if (loggerUid != jankUid && loggerUid != AID_STATSD) {
337 VLOG("DAVEY_OCCURRED has invalid uid: claimed %ld but caller is %d", jankUid,
338 loggerUid);
Andrei Oneada01ea52019-01-30 15:28:36 +0000339 return false;
David Chen77ef6712018-02-23 18:23:42 -0800340 }
341
Tej Singhbb8554a2018-01-26 11:59:14 -0800342 long duration = event.GetLong(event.size(), &err);
David Chen77ef6712018-02-23 18:23:42 -0800343 if (err != NO_ERROR ) {
344 VLOG("Davey occurred had error when parsing the duration");
Andrei Oneada01ea52019-01-30 15:28:36 +0000345 return false;
David Chen77ef6712018-02-23 18:23:42 -0800346 } else if (duration > 100000) {
Tej Singhbb8554a2018-01-26 11:59:14 -0800347 VLOG("Davey duration is unreasonably long: %ld", duration);
Andrei Oneada01ea52019-01-30 15:28:36 +0000348 return false;
Tej Singhbb8554a2018-01-26 11:59:14 -0800349 }
Andrei Oneada01ea52019-01-30 15:28:36 +0000350 }
351
352 return true;
353}
354
355// Consume the stats log if it's interesting to this metric.
356void MetricsManager::onLogEvent(const LogEvent& event) {
357 if (!mConfigValid) {
358 return;
359 }
360
361 if (!checkLogCredentials(event)) {
362 return;
363 }
364
365 if (!eventSanityCheck(event)) {
366 return;
Yao Chend10f7b12017-12-18 12:53:50 -0800367 }
368
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700369 int tagId = event.GetTagId();
Yangster-mac849dfdc22018-10-12 15:41:45 -0700370 int64_t eventTimeNs = event.GetElapsedTimestampNs();
371
Tej Singh6ede28b2019-01-29 17:06:54 -0800372 bool isActive = mIsAlwaysActive;
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700373
374 // Set of metrics that are still active after flushing.
375 unordered_set<int> activeMetricsIndices;
376
377 // Update state of all metrics w/ activation conditions as of eventTimeNs.
378 for (int metricIndex : mMetricIndexesWithActivation) {
379 const sp<MetricProducer>& metric = mAllMetricProducers[metricIndex];
380 metric->flushIfExpire(eventTimeNs);
381 if (metric->isActive()) {
382 // If this metric w/ activation condition is still active after
383 // flushing, remember it.
384 activeMetricsIndices.insert(metricIndex);
385 }
Yangster-mac849dfdc22018-10-12 15:41:45 -0700386 }
387
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700388 mIsActive = isActive || !activeMetricsIndices.empty();
Tej Singh6ede28b2019-01-29 17:06:54 -0800389
Yao Chen44cf27c2017-09-14 22:32:50 -0700390 if (mTagIds.find(tagId) == mTagIds.end()) {
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700391 // Not interesting...
Yao Chen44cf27c2017-09-14 22:32:50 -0700392 return;
393 }
Yao Chen44cf27c2017-09-14 22:32:50 -0700394
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800395 vector<MatchingState> matcherCache(mAllAtomMatchers.size(), MatchingState::kNotComputed);
Yao Chencaf339d2017-10-06 16:01:10 -0700396
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700397 // Evaluate all atom matchers.
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800398 for (auto& matcher : mAllAtomMatchers) {
399 matcher->onLogEvent(event, mAllAtomMatchers, matcherCache);
Yao Chen44cf27c2017-09-14 22:32:50 -0700400 }
401
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700402 // Set of metrics that received an activation cancellation.
403 unordered_set<int> metricIndicesWithCanceledActivations;
404
405 // Determine which metric activations received a cancellation and cancel them.
406 for (const auto& it : mDeactivationAtomTrackerToMetricMap) {
407 if (matcherCache[it.first] == MatchingState::kMatched) {
408 for (int metricIndex : it.second) {
409 mAllMetricProducers[metricIndex]->cancelEventActivation(it.first);
410 metricIndicesWithCanceledActivations.insert(metricIndex);
411 }
412 }
413 }
414
415 // Determine whether any metrics are no longer active after cancelling metric activations.
416 for (const int metricIndex : metricIndicesWithCanceledActivations) {
417 const sp<MetricProducer>& metric = mAllMetricProducers[metricIndex];
418 metric->flushIfExpire(eventTimeNs);
419 if (!metric->isActive()) {
420 activeMetricsIndices.erase(metricIndex);
421 }
422 }
423
424 isActive |= !activeMetricsIndices.empty();
425
426
427 // Determine which metric activations should be turned on and turn them on
Yangster-mac849dfdc22018-10-12 15:41:45 -0700428 for (const auto& it : mActivationAtomTrackerToMetricMap) {
429 if (matcherCache[it.first] == MatchingState::kMatched) {
430 for (int metricIndex : it.second) {
431 mAllMetricProducers[metricIndex]->activate(it.first, eventTimeNs);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800432 isActive |= mAllMetricProducers[metricIndex]->isActive();
Yangster-mac849dfdc22018-10-12 15:41:45 -0700433 }
434 }
435 }
436
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800437 mIsActive = isActive;
438
Yao Chencaf339d2017-10-06 16:01:10 -0700439 // A bitmap to see which ConditionTracker needs to be re-evaluated.
440 vector<bool> conditionToBeEvaluated(mAllConditionTrackers.size(), false);
441
442 for (const auto& pair : mTrackerToConditionMap) {
443 if (matcherCache[pair.first] == MatchingState::kMatched) {
444 const auto& conditionList = pair.second;
445 for (const int conditionIndex : conditionList) {
446 conditionToBeEvaluated[conditionIndex] = true;
447 }
448 }
449 }
450
451 vector<ConditionState> conditionCache(mAllConditionTrackers.size(),
452 ConditionState::kNotEvaluated);
453 // A bitmap to track if a condition has changed value.
454 vector<bool> changedCache(mAllConditionTrackers.size(), false);
455 for (size_t i = 0; i < mAllConditionTrackers.size(); i++) {
456 if (conditionToBeEvaluated[i] == false) {
457 continue;
458 }
Yao Chencaf339d2017-10-06 16:01:10 -0700459 sp<ConditionTracker>& condition = mAllConditionTrackers[i];
460 condition->evaluateCondition(event, matcherCache, mAllConditionTrackers, conditionCache,
Yao Chen967b2052017-11-07 16:36:43 -0800461 changedCache);
Yao Chen729093d2017-10-16 10:33:26 -0700462 }
463
464 for (size_t i = 0; i < mAllConditionTrackers.size(); i++) {
Yao Chen967b2052017-11-07 16:36:43 -0800465 if (changedCache[i] == false) {
Yao Chen729093d2017-10-16 10:33:26 -0700466 continue;
467 }
468 auto pair = mConditionToMetricMap.find(i);
469 if (pair != mConditionToMetricMap.end()) {
470 auto& metricList = pair->second;
471 for (auto metricIndex : metricList) {
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700472 // Metric cares about non sliced condition, and it's changed.
Yao Chen729093d2017-10-16 10:33:26 -0700473 // Push the new condition to it directly.
Yao Chen967b2052017-11-07 16:36:43 -0800474 if (!mAllMetricProducers[metricIndex]->isConditionSliced()) {
Yao Chen5154a3792017-10-30 22:57:06 -0700475 mAllMetricProducers[metricIndex]->onConditionChanged(conditionCache[i],
Yangster-mac849dfdc22018-10-12 15:41:45 -0700476 eventTimeNs);
Muhammad Qureshi3a5ebf52019-03-28 12:38:21 -0700477 // Metric cares about sliced conditions, and it may have changed. Send
Yao Chen729093d2017-10-16 10:33:26 -0700478 // notification, and the metric can query the sliced conditions that are
479 // interesting to it.
Yangsterf2bee6f2017-11-29 12:01:05 -0800480 } else {
Yao Chen427d3722018-03-22 15:21:52 -0700481 mAllMetricProducers[metricIndex]->onSlicedConditionMayChange(conditionCache[i],
Yangster-mac849dfdc22018-10-12 15:41:45 -0700482 eventTimeNs);
Yao Chen44cf27c2017-09-14 22:32:50 -0700483 }
Yao Chencaf339d2017-10-06 16:01:10 -0700484 }
485 }
486 }
487
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800488 // For matched AtomMatchers, tell relevant metrics that a matched event has come.
489 for (size_t i = 0; i < mAllAtomMatchers.size(); i++) {
Yao Chencaf339d2017-10-06 16:01:10 -0700490 if (matcherCache[i] == MatchingState::kMatched) {
Yao Chenb3561512017-11-21 18:07:17 -0800491 StatsdStats::getInstance().noteMatcherMatched(mConfigKey,
Yangster-mac94e197c2018-01-02 16:03:03 -0800492 mAllAtomMatchers[i]->getId());
Yao Chencaf339d2017-10-06 16:01:10 -0700493 auto pair = mTrackerToMetricMap.find(i);
494 if (pair != mTrackerToMetricMap.end()) {
495 auto& metricList = pair->second;
496 for (const int metricIndex : metricList) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700497 // pushed metrics are never scheduled pulls
Chenjie Yua7259ab2017-12-10 08:31:05 -0800498 mAllMetricProducers[metricIndex]->onMatchedLogEvent(i, event);
Yao Chencaf339d2017-10-06 16:01:10 -0700499 }
Yao Chen44cf27c2017-09-14 22:32:50 -0700500 }
501 }
502 }
503}
504
Yangster-mac932ecec2018-02-01 10:23:52 -0800505void MetricsManager::onAnomalyAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700506 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800507 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& alarmSet) {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800508 for (const auto& itr : mAllAnomalyTrackers) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800509 itr->informAlarmsFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800510 }
511}
512
Yangster-mac932ecec2018-02-01 10:23:52 -0800513void MetricsManager::onPeriodicAlarmFired(
Yangster-macb142cc82018-03-30 15:22:08 -0700514 const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800515 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& alarmSet) {
516 for (const auto& itr : mAllPeriodicAlarmTrackers) {
517 itr->informAlarmsFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800518 }
519}
520
yro69007c82017-10-26 20:42:57 -0700521// Returns the total byte size of all metrics managed by a single config source.
522size_t MetricsManager::byteSize() {
523 size_t totalSize = 0;
Chih-Hung Hsieha1b644e2018-12-11 11:09:20 -0800524 for (const auto& metricProducer : mAllMetricProducers) {
yro69007c82017-10-26 20:42:57 -0700525 totalSize += metricProducer->byteSize();
526 }
527 return totalSize;
528}
529
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700530void MetricsManager::loadActiveConfig(const ActiveConfig& config, int64_t currentTimeNs) {
531 if (config.metric_size() == 0) {
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800532 ALOGW("No active metric for config %s", mConfigKey.ToString().c_str());
533 return;
534 }
535
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700536 for (int i = 0; i < config.metric_size(); i++) {
537 const auto& activeMetric = config.metric(i);
538 for (int metricIndex : mMetricIndexesWithActivation) {
539 const auto& metric = mAllMetricProducers[metricIndex];
540 if (metric->getMetricId() == activeMetric.id()) {
541 VLOG("Setting active metric: %lld", (long long)metric->getMetricId());
542 metric->loadActiveMetric(activeMetric, currentTimeNs);
Tej Singh16ca28f2019-06-24 11:58:23 -0700543 if (!mIsActive && metric->isActive()) {
544 StatsdStats::getInstance().noteActiveStatusChanged(mConfigKey,
545 /*activate=*/ true);
546 }
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700547 mIsActive |= metric->isActive();
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800548 }
549 }
550 }
551}
552
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700553void MetricsManager::writeActiveConfigToProtoOutputStream(
Tej Singhf53d4452019-05-09 18:17:59 -0700554 int64_t currentTimeNs, const DumpReportReason reason, ProtoOutputStream* proto) {
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700555 proto->write(FIELD_TYPE_INT64 | FIELD_ID_ACTIVE_CONFIG_ID, (long long)mConfigKey.GetId());
556 proto->write(FIELD_TYPE_INT32 | FIELD_ID_ACTIVE_CONFIG_UID, mConfigKey.GetUid());
557 for (int metricIndex : mMetricIndexesWithActivation) {
558 const auto& metric = mAllMetricProducers[metricIndex];
559 const uint64_t metricToken = proto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
560 FIELD_ID_ACTIVE_CONFIG_METRIC);
Tej Singhf53d4452019-05-09 18:17:59 -0700561 metric->writeActiveMetricToProtoOutputStream(currentTimeNs, reason, proto);
Muhammad Qureshi844694b2019-04-05 10:10:40 -0700562 proto->end(metricToken);
563 }
564}
565
566
567
568
Yao Chen44cf27c2017-09-14 22:32:50 -0700569} // namespace statsd
570} // namespace os
571} // namespace android