blob: 4c8a7d8a92d5b6f44acca45bfab3f14cbf453222 [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 */
Yao Chen8a8d16c2018-02-08 14:50:40 -080016#define DEBUG true // STOPSHIP if true
Joe Onorato9fc9edf2017-10-15 20:08:52 -070017#include "Log.h"
Yao Chen44cf27c2017-09-14 22:32:50 -070018#include "MetricsManager.h"
Yao Chend10f7b12017-12-18 12:53:50 -080019#include "statslog.h"
Yao Chen93fe3a32017-11-02 13:52:59 -070020
Yao Chen44cf27c2017-09-14 22:32:50 -070021#include "CountMetricProducer.h"
Yao Chen93fe3a32017-11-02 13:52:59 -070022#include "condition/CombinationConditionTracker.h"
23#include "condition/SimpleConditionTracker.h"
Yao Chenb3561512017-11-21 18:07:17 -080024#include "guardrail/StatsdStats.h"
Yao Chen93fe3a32017-11-02 13:52:59 -070025#include "matchers/CombinationLogMatchingTracker.h"
26#include "matchers/SimpleLogMatchingTracker.h"
Yao Chencaf339d2017-10-06 16:01:10 -070027#include "metrics_manager_util.h"
28#include "stats_util.h"
Yangster-mac330af582018-02-08 15:24:38 -080029#include "stats_log_util.h"
Yao Chen44cf27c2017-09-14 22:32:50 -070030
Yao Chen93fe3a32017-11-02 13:52:59 -070031#include <log/logprint.h>
Bookatz6f197902018-02-05 12:30:14 -080032#include <private/android_filesystem_config.h>
David Chen16049572018-02-01 18:27:51 -080033#include <utils/SystemClock.h>
Yao Chen288c6002017-12-12 13:43:18 -080034
35using android::util::FIELD_COUNT_REPEATED;
36using android::util::FIELD_TYPE_MESSAGE;
37using android::util::ProtoOutputStream;
38
Yao Chen44cf27c2017-09-14 22:32:50 -070039using std::make_unique;
40using std::set;
41using std::string;
Yao Chen44cf27c2017-09-14 22:32:50 -070042using std::unordered_map;
43using std::vector;
44
45namespace android {
46namespace os {
47namespace statsd {
48
Yao Chen288c6002017-12-12 13:43:18 -080049const int FIELD_ID_METRICS = 1;
50
Yao Chend10f7b12017-12-18 12:53:50 -080051MetricsManager::MetricsManager(const ConfigKey& key, const StatsdConfig& config,
Yangster-mac932ecec2018-02-01 10:23:52 -080052 const long timeBaseSec,
53 const sp<UidMap> &uidMap,
54 const sp<AlarmMonitor>& anomalyAlarmMonitor,
55 const sp<AlarmMonitor>& periodicAlarmMonitor)
Yangster-mac330af582018-02-08 15:24:38 -080056 : mConfigKey(key), mUidMap(uidMap), mLastReportTimeNs(timeBaseSec * NS_PER_SEC) {
Yao Chenb3561512017-11-21 18:07:17 -080057 mConfigValid =
Yangster-mac932ecec2018-02-01 10:23:52 -080058 initStatsdConfig(key, config, *uidMap, anomalyAlarmMonitor, periodicAlarmMonitor,
59 timeBaseSec, mTagIds, mAllAtomMatchers,
60 mAllConditionTrackers, mAllMetricProducers, mAllAnomalyTrackers,
61 mAllPeriodicAlarmTrackers, mConditionToMetricMap, mTrackerToMetricMap,
62 mTrackerToConditionMap, mNoReportMetricIds);
Yao Chenb3561512017-11-21 18:07:17 -080063
Yao Chen147ce602017-12-22 14:35:34 -080064 if (config.allowed_log_source_size() == 0) {
Yao Chend10f7b12017-12-18 12:53:50 -080065 // TODO(b/70794411): uncomment the following line and remove the hard coded log source
66 // after all configs have the log source added.
67 // mConfigValid = false;
68 // ALOGE("Log source white list is empty! This config won't get any data.");
69
Bookatz6f197902018-02-05 12:30:14 -080070 mAllowedUid.push_back(AID_ROOT);
71 mAllowedUid.push_back(AID_STATSD);
72 mAllowedUid.push_back(AID_SYSTEM);
Yao Chend10f7b12017-12-18 12:53:50 -080073 mAllowedLogSources.insert(mAllowedUid.begin(), mAllowedUid.end());
74 } else {
Yao Chen147ce602017-12-22 14:35:34 -080075 for (const auto& source : config.allowed_log_source()) {
76 auto it = UidMap::sAidToUidMapping.find(source);
77 if (it != UidMap::sAidToUidMapping.end()) {
78 mAllowedUid.push_back(it->second);
79 } else {
80 mAllowedPkg.push_back(source);
81 }
82 }
Yao Chend10f7b12017-12-18 12:53:50 -080083
84 if (mAllowedUid.size() + mAllowedPkg.size() > StatsdStats::kMaxLogSourceCount) {
85 ALOGE("Too many log sources. This is likely to be an error in the config.");
86 mConfigValid = false;
87 } else {
88 initLogSourceWhiteList();
89 }
90 }
91
Yao Chenb3561512017-11-21 18:07:17 -080092 // Guardrail. Reject the config if it's too big.
93 if (mAllMetricProducers.size() > StatsdStats::kMaxMetricCountPerConfig ||
94 mAllConditionTrackers.size() > StatsdStats::kMaxConditionCountPerConfig ||
Stefan Lafonb8c9aa82017-12-03 14:27:25 -080095 mAllAtomMatchers.size() > StatsdStats::kMaxMatcherCountPerConfig) {
Yao Chenb3561512017-11-21 18:07:17 -080096 ALOGE("This config is too big! Reject!");
97 mConfigValid = false;
98 }
Bookatz1476ef22018-02-13 12:26:01 -080099 if (mAllAnomalyTrackers.size() > StatsdStats::kMaxAlertCountPerConfig) {
100 ALOGE("This config has too many alerts! Reject!");
101 mConfigValid = false;
102 }
Yao Chenf09569f2017-12-13 17:00:51 -0800103 // no matter whether this config is valid, log it in the stats.
104 StatsdStats::getInstance().noteConfigReceived(key, mAllMetricProducers.size(),
105 mAllConditionTrackers.size(),
106 mAllAtomMatchers.size(), 0, mConfigValid);
Yao Chen44cf27c2017-09-14 22:32:50 -0700107}
108
109MetricsManager::~MetricsManager() {
Bookatzd3606c72017-10-19 10:13:49 -0700110 VLOG("~MetricsManager()");
Yao Chen44cf27c2017-09-14 22:32:50 -0700111}
112
Yao Chend10f7b12017-12-18 12:53:50 -0800113void MetricsManager::initLogSourceWhiteList() {
114 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
115 mAllowedLogSources.clear();
116 mAllowedLogSources.insert(mAllowedUid.begin(), mAllowedUid.end());
117
118 for (const auto& pkg : mAllowedPkg) {
119 auto uids = mUidMap->getAppUid(pkg);
120 mAllowedLogSources.insert(uids.begin(), uids.end());
121 }
122 if (DEBUG) {
123 for (const auto& uid : mAllowedLogSources) {
124 VLOG("Allowed uid %d", uid);
125 }
126 }
127}
128
Yao Chencaf339d2017-10-06 16:01:10 -0700129bool MetricsManager::isConfigValid() const {
130 return mConfigValid;
131}
132
David Chen27785a82018-01-19 17:06:45 -0800133void MetricsManager::notifyAppUpgrade(const uint64_t& eventTimeNs, const string& apk, const int uid,
134 const int64_t version) {
Yao Chend10f7b12017-12-18 12:53:50 -0800135 // check if we care this package
136 if (std::find(mAllowedPkg.begin(), mAllowedPkg.end(), apk) == mAllowedPkg.end()) {
137 return;
138 }
139 // We will re-initialize the whole list because we don't want to keep the multi mapping of
140 // UID<->pkg inside MetricsManager to reduce the memory usage.
141 initLogSourceWhiteList();
142}
143
David Chen27785a82018-01-19 17:06:45 -0800144void MetricsManager::notifyAppRemoved(const uint64_t& eventTimeNs, const string& apk,
145 const int uid) {
Yao Chend10f7b12017-12-18 12:53:50 -0800146 // check if we care this package
147 if (std::find(mAllowedPkg.begin(), mAllowedPkg.end(), apk) == mAllowedPkg.end()) {
148 return;
149 }
150 // We will re-initialize the whole list because we don't want to keep the multi mapping of
151 // UID<->pkg inside MetricsManager to reduce the memory usage.
152 initLogSourceWhiteList();
153}
154
David Chen27785a82018-01-19 17:06:45 -0800155void MetricsManager::onUidMapReceived(const uint64_t& eventTimeNs) {
Yao Chend10f7b12017-12-18 12:53:50 -0800156 if (mAllowedPkg.size() == 0) {
157 return;
158 }
159 initLogSourceWhiteList();
160}
161
Yao Chen884c8c12018-01-26 10:36:25 -0800162void MetricsManager::dumpStates(FILE* out, bool verbose) {
163 fprintf(out, "ConfigKey %s, allowed source:", mConfigKey.ToString().c_str());
164 {
165 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
166 for (const auto& source : mAllowedLogSources) {
167 fprintf(out, "%d ", source);
168 }
169 }
170 fprintf(out, "\n");
171 for (const auto& producer : mAllMetricProducers) {
172 producer->dumpStates(out, verbose);
173 }
174}
175
Yao Chen8a8d16c2018-02-08 14:50:40 -0800176void MetricsManager::onDumpReport(const uint64_t dumpTimeStampNs, ProtoOutputStream* protoOutput) {
Yao Chen729093d2017-10-16 10:33:26 -0700177 VLOG("=========================Metric Reports Start==========================");
178 // one StatsLogReport per MetricProduer
Yangster-mac94e197c2018-01-02 16:03:03 -0800179 for (const auto& producer : mAllMetricProducers) {
180 if (mNoReportMetricIds.find(producer->getMetricId()) == mNoReportMetricIds.end()) {
181 long long token =
182 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_METRICS);
183 producer->onDumpReport(dumpTimeStampNs, protoOutput);
184 protoOutput->end(token);
185 }
Yao Chen729093d2017-10-16 10:33:26 -0700186 }
Yangster-mac330af582018-02-08 15:24:38 -0800187 mLastReportTimeNs = dumpTimeStampNs;
Yao Chen729093d2017-10-16 10:33:26 -0700188 VLOG("=========================Metric Reports End==========================");
Yao Chen729093d2017-10-16 10:33:26 -0700189}
190
Yao Chen44cf27c2017-09-14 22:32:50 -0700191// Consume the stats log if it's interesting to this metric.
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700192void MetricsManager::onLogEvent(const LogEvent& event) {
Yao Chencaf339d2017-10-06 16:01:10 -0700193 if (!mConfigValid) {
194 return;
195 }
196
David Chenb639d142018-02-14 17:29:54 -0800197 if (event.GetTagId() == android::util::APP_BREADCRUMB_REPORTED) {
198 // Check that app breadcrumb reported fields are valid.
199 // TODO: Find a way to make these checks easier to maintain.
David Chendaa9f3a2017-12-28 16:52:22 -0800200 status_t err = NO_ERROR;
Bookatzb223c4e2018-02-01 15:35:04 -0800201
202 // Uid is 3rd from last field and must match the caller's uid,
203 // unless that caller is statsd itself (statsd is allowed to spoof uids).
204 long appHookUid = event.GetLong(event.size()-2, &err);
David Chen77ef6712018-02-23 18:23:42 -0800205 if (err != NO_ERROR ) {
206 VLOG("APP_BREADCRUMB_REPORTED had error when parsing the uid");
207 return;
208 }
Bookatzb223c4e2018-02-01 15:35:04 -0800209 int32_t loggerUid = event.GetUid();
David Chen77ef6712018-02-23 18:23:42 -0800210 if (loggerUid != appHookUid && loggerUid != AID_STATSD) {
211 VLOG("APP_BREADCRUMB_REPORTED has invalid uid: claimed %ld but caller is %d",
212 appHookUid, loggerUid);
David Chendaa9f3a2017-12-28 16:52:22 -0800213 return;
214 }
Bookatzb223c4e2018-02-01 15:35:04 -0800215
216 // Label is 2nd from last field and must be from [0, 15].
217 long appHookLabel = event.GetLong(event.size()-1, &err);
David Chen77ef6712018-02-23 18:23:42 -0800218 if (err != NO_ERROR ) {
219 VLOG("APP_BREADCRUMB_REPORTED had error when parsing the label field");
220 return;
221 } else if (appHookLabel < 0 || appHookLabel > 15) {
222 VLOG("APP_BREADCRUMB_REPORTED does not have valid label %ld", appHookLabel);
Bookatzb223c4e2018-02-01 15:35:04 -0800223 return;
224 }
225
David Chendaa9f3a2017-12-28 16:52:22 -0800226 // The state must be from 0,3. This part of code must be manually updated.
Bookatzb223c4e2018-02-01 15:35:04 -0800227 long appHookState = event.GetLong(event.size(), &err);
David Chen77ef6712018-02-23 18:23:42 -0800228 if (err != NO_ERROR ) {
229 VLOG("APP_BREADCRUMB_REPORTED had error when parsing the state field");
230 return;
231 } else if (appHookState < 0 || appHookState > 3) {
232 VLOG("APP_BREADCRUMB_REPORTED does not have valid state %ld", appHookState);
David Chendaa9f3a2017-12-28 16:52:22 -0800233 return;
234 }
Tej Singhbb8554a2018-01-26 11:59:14 -0800235 } else if (event.GetTagId() == android::util::DAVEY_OCCURRED) {
236 // Daveys can be logged from any app since they are logged in libs/hwui/JankTracker.cpp.
237 // Check that the davey duration is reasonable. Max length check is for privacy.
238 status_t err = NO_ERROR;
David Chen77ef6712018-02-23 18:23:42 -0800239
240 // Uid is the first field provided.
241 long jankUid = event.GetLong(1, &err);
242 if (err != NO_ERROR ) {
243 VLOG("Davey occurred had error when parsing the uid");
244 return;
245 }
246 int32_t loggerUid = event.GetUid();
247 if (loggerUid != jankUid && loggerUid != AID_STATSD) {
248 VLOG("DAVEY_OCCURRED has invalid uid: claimed %ld but caller is %d", jankUid,
249 loggerUid);
250 return;
251 }
252
Tej Singhbb8554a2018-01-26 11:59:14 -0800253 long duration = event.GetLong(event.size(), &err);
David Chen77ef6712018-02-23 18:23:42 -0800254 if (err != NO_ERROR ) {
255 VLOG("Davey occurred had error when parsing the duration");
256 return;
257 } else if (duration > 100000) {
Tej Singhbb8554a2018-01-26 11:59:14 -0800258 VLOG("Davey duration is unreasonably long: %ld", duration);
259 return;
260 }
261 } else {
262 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
263 if (mAllowedLogSources.find(event.GetUid()) == mAllowedLogSources.end()) {
264 VLOG("log source %d not on the whitelist", event.GetUid());
265 return;
266 }
Yao Chend10f7b12017-12-18 12:53:50 -0800267 }
268
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700269 int tagId = event.GetTagId();
Yangster-mac330af582018-02-08 15:24:38 -0800270 uint64_t eventTime = event.GetElapsedTimestampNs();
Yao Chen44cf27c2017-09-14 22:32:50 -0700271 if (mTagIds.find(tagId) == mTagIds.end()) {
272 // not interesting...
273 return;
274 }
Yao Chen44cf27c2017-09-14 22:32:50 -0700275
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800276 vector<MatchingState> matcherCache(mAllAtomMatchers.size(), MatchingState::kNotComputed);
Yao Chencaf339d2017-10-06 16:01:10 -0700277
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800278 for (auto& matcher : mAllAtomMatchers) {
279 matcher->onLogEvent(event, mAllAtomMatchers, matcherCache);
Yao Chen44cf27c2017-09-14 22:32:50 -0700280 }
281
Yao Chencaf339d2017-10-06 16:01:10 -0700282 // A bitmap to see which ConditionTracker needs to be re-evaluated.
283 vector<bool> conditionToBeEvaluated(mAllConditionTrackers.size(), false);
284
285 for (const auto& pair : mTrackerToConditionMap) {
286 if (matcherCache[pair.first] == MatchingState::kMatched) {
287 const auto& conditionList = pair.second;
288 for (const int conditionIndex : conditionList) {
289 conditionToBeEvaluated[conditionIndex] = true;
290 }
291 }
292 }
293
294 vector<ConditionState> conditionCache(mAllConditionTrackers.size(),
295 ConditionState::kNotEvaluated);
296 // A bitmap to track if a condition has changed value.
297 vector<bool> changedCache(mAllConditionTrackers.size(), false);
298 for (size_t i = 0; i < mAllConditionTrackers.size(); i++) {
299 if (conditionToBeEvaluated[i] == false) {
300 continue;
301 }
Yao Chencaf339d2017-10-06 16:01:10 -0700302 sp<ConditionTracker>& condition = mAllConditionTrackers[i];
303 condition->evaluateCondition(event, matcherCache, mAllConditionTrackers, conditionCache,
Yao Chen967b2052017-11-07 16:36:43 -0800304 changedCache);
Yao Chen729093d2017-10-16 10:33:26 -0700305 }
306
307 for (size_t i = 0; i < mAllConditionTrackers.size(); i++) {
Yao Chen967b2052017-11-07 16:36:43 -0800308 if (changedCache[i] == false) {
Yao Chen729093d2017-10-16 10:33:26 -0700309 continue;
310 }
311 auto pair = mConditionToMetricMap.find(i);
312 if (pair != mConditionToMetricMap.end()) {
313 auto& metricList = pair->second;
314 for (auto metricIndex : metricList) {
315 // metric cares about non sliced condition, and it's changed.
316 // Push the new condition to it directly.
Yao Chen967b2052017-11-07 16:36:43 -0800317 if (!mAllMetricProducers[metricIndex]->isConditionSliced()) {
Yao Chen5154a3792017-10-30 22:57:06 -0700318 mAllMetricProducers[metricIndex]->onConditionChanged(conditionCache[i],
319 eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700320 // metric cares about sliced conditions, and it may have changed. Send
321 // notification, and the metric can query the sliced conditions that are
322 // interesting to it.
Yangsterf2bee6f2017-11-29 12:01:05 -0800323 } else {
Yao Chen5154a3792017-10-30 22:57:06 -0700324 mAllMetricProducers[metricIndex]->onSlicedConditionMayChange(eventTime);
Yao Chen44cf27c2017-09-14 22:32:50 -0700325 }
Yao Chencaf339d2017-10-06 16:01:10 -0700326 }
327 }
328 }
329
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800330 // For matched AtomMatchers, tell relevant metrics that a matched event has come.
331 for (size_t i = 0; i < mAllAtomMatchers.size(); i++) {
Yao Chencaf339d2017-10-06 16:01:10 -0700332 if (matcherCache[i] == MatchingState::kMatched) {
Yao Chenb3561512017-11-21 18:07:17 -0800333 StatsdStats::getInstance().noteMatcherMatched(mConfigKey,
Yangster-mac94e197c2018-01-02 16:03:03 -0800334 mAllAtomMatchers[i]->getId());
Yao Chencaf339d2017-10-06 16:01:10 -0700335 auto pair = mTrackerToMetricMap.find(i);
336 if (pair != mTrackerToMetricMap.end()) {
337 auto& metricList = pair->second;
338 for (const int metricIndex : metricList) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700339 // pushed metrics are never scheduled pulls
Chenjie Yua7259ab2017-12-10 08:31:05 -0800340 mAllMetricProducers[metricIndex]->onMatchedLogEvent(i, event);
Yao Chencaf339d2017-10-06 16:01:10 -0700341 }
Yao Chen44cf27c2017-09-14 22:32:50 -0700342 }
343 }
344 }
345}
346
Yangster-mac932ecec2018-02-01 10:23:52 -0800347void MetricsManager::onAnomalyAlarmFired(
348 const uint64_t timestampNs,
349 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& alarmSet) {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800350 for (const auto& itr : mAllAnomalyTrackers) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800351 itr->informAlarmsFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800352 }
353}
354
Yangster-mac932ecec2018-02-01 10:23:52 -0800355void MetricsManager::onPeriodicAlarmFired(
356 const uint64_t timestampNs,
357 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& alarmSet) {
358 for (const auto& itr : mAllPeriodicAlarmTrackers) {
359 itr->informAlarmsFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800360 }
361}
362
yro69007c82017-10-26 20:42:57 -0700363// Returns the total byte size of all metrics managed by a single config source.
364size_t MetricsManager::byteSize() {
365 size_t totalSize = 0;
366 for (auto metricProducer : mAllMetricProducers) {
367 totalSize += metricProducer->byteSize();
368 }
369 return totalSize;
370}
371
Yao Chen44cf27c2017-09-14 22:32:50 -0700372} // namespace statsd
373} // namespace os
374} // namespace android