blob: 6209bbe75812ab8bdec0bdbafb0466dff15163ca [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-mac3fa5d7f2018-03-10 21:50:27 -080056 : mConfigKey(key), mUidMap(uidMap),
57 mLastReportTimeNs(timeBaseSec * NS_PER_SEC),
58 mLastReportWallClockNs(getWallClockNs()) {
Yao Chenb3561512017-11-21 18:07:17 -080059 mConfigValid =
Yangster-mac932ecec2018-02-01 10:23:52 -080060 initStatsdConfig(key, config, *uidMap, anomalyAlarmMonitor, periodicAlarmMonitor,
61 timeBaseSec, mTagIds, mAllAtomMatchers,
62 mAllConditionTrackers, mAllMetricProducers, mAllAnomalyTrackers,
63 mAllPeriodicAlarmTrackers, mConditionToMetricMap, mTrackerToMetricMap,
64 mTrackerToConditionMap, mNoReportMetricIds);
Yao Chenb3561512017-11-21 18:07:17 -080065
Yao Chen147ce602017-12-22 14:35:34 -080066 if (config.allowed_log_source_size() == 0) {
Yao Chend10f7b12017-12-18 12:53:50 -080067 // TODO(b/70794411): uncomment the following line and remove the hard coded log source
68 // after all configs have the log source added.
69 // mConfigValid = false;
70 // ALOGE("Log source white list is empty! This config won't get any data.");
71
Bookatz6f197902018-02-05 12:30:14 -080072 mAllowedUid.push_back(AID_ROOT);
73 mAllowedUid.push_back(AID_STATSD);
74 mAllowedUid.push_back(AID_SYSTEM);
Yao Chend10f7b12017-12-18 12:53:50 -080075 mAllowedLogSources.insert(mAllowedUid.begin(), mAllowedUid.end());
76 } else {
Yao Chen147ce602017-12-22 14:35:34 -080077 for (const auto& source : config.allowed_log_source()) {
78 auto it = UidMap::sAidToUidMapping.find(source);
79 if (it != UidMap::sAidToUidMapping.end()) {
80 mAllowedUid.push_back(it->second);
81 } else {
82 mAllowedPkg.push_back(source);
83 }
84 }
Yao Chend10f7b12017-12-18 12:53:50 -080085
86 if (mAllowedUid.size() + mAllowedPkg.size() > StatsdStats::kMaxLogSourceCount) {
87 ALOGE("Too many log sources. This is likely to be an error in the config.");
88 mConfigValid = false;
89 } else {
90 initLogSourceWhiteList();
91 }
92 }
93
Yao Chenb3561512017-11-21 18:07:17 -080094 // Guardrail. Reject the config if it's too big.
95 if (mAllMetricProducers.size() > StatsdStats::kMaxMetricCountPerConfig ||
96 mAllConditionTrackers.size() > StatsdStats::kMaxConditionCountPerConfig ||
Stefan Lafonb8c9aa82017-12-03 14:27:25 -080097 mAllAtomMatchers.size() > StatsdStats::kMaxMatcherCountPerConfig) {
Yao Chenb3561512017-11-21 18:07:17 -080098 ALOGE("This config is too big! Reject!");
99 mConfigValid = false;
100 }
Bookatz1476ef22018-02-13 12:26:01 -0800101 if (mAllAnomalyTrackers.size() > StatsdStats::kMaxAlertCountPerConfig) {
102 ALOGE("This config has too many alerts! Reject!");
103 mConfigValid = false;
104 }
Yao Chenf09569f2017-12-13 17:00:51 -0800105 // no matter whether this config is valid, log it in the stats.
106 StatsdStats::getInstance().noteConfigReceived(key, mAllMetricProducers.size(),
107 mAllConditionTrackers.size(),
Bookatzaea8d10b2018-03-02 10:37:24 -0800108 mAllAtomMatchers.size(),
109 mAllAnomalyTrackers.size(),
110 mConfigValid);
Yao Chen44cf27c2017-09-14 22:32:50 -0700111}
112
113MetricsManager::~MetricsManager() {
Bookatzd3606c72017-10-19 10:13:49 -0700114 VLOG("~MetricsManager()");
Yao Chen44cf27c2017-09-14 22:32:50 -0700115}
116
Yao Chend10f7b12017-12-18 12:53:50 -0800117void MetricsManager::initLogSourceWhiteList() {
118 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
119 mAllowedLogSources.clear();
120 mAllowedLogSources.insert(mAllowedUid.begin(), mAllowedUid.end());
121
122 for (const auto& pkg : mAllowedPkg) {
123 auto uids = mUidMap->getAppUid(pkg);
124 mAllowedLogSources.insert(uids.begin(), uids.end());
125 }
126 if (DEBUG) {
127 for (const auto& uid : mAllowedLogSources) {
128 VLOG("Allowed uid %d", uid);
129 }
130 }
131}
132
Yao Chencaf339d2017-10-06 16:01:10 -0700133bool MetricsManager::isConfigValid() const {
134 return mConfigValid;
135}
136
David Chen27785a82018-01-19 17:06:45 -0800137void MetricsManager::notifyAppUpgrade(const uint64_t& eventTimeNs, const string& apk, const int uid,
138 const int64_t version) {
Yao Chend10f7b12017-12-18 12:53:50 -0800139 // check if we care this package
140 if (std::find(mAllowedPkg.begin(), mAllowedPkg.end(), apk) == mAllowedPkg.end()) {
141 return;
142 }
143 // We will re-initialize the whole list because we don't want to keep the multi mapping of
144 // UID<->pkg inside MetricsManager to reduce the memory usage.
145 initLogSourceWhiteList();
146}
147
David Chen27785a82018-01-19 17:06:45 -0800148void MetricsManager::notifyAppRemoved(const uint64_t& eventTimeNs, const string& apk,
149 const int uid) {
Yao Chend10f7b12017-12-18 12:53:50 -0800150 // check if we care this package
151 if (std::find(mAllowedPkg.begin(), mAllowedPkg.end(), apk) == mAllowedPkg.end()) {
152 return;
153 }
154 // We will re-initialize the whole list because we don't want to keep the multi mapping of
155 // UID<->pkg inside MetricsManager to reduce the memory usage.
156 initLogSourceWhiteList();
157}
158
David Chen27785a82018-01-19 17:06:45 -0800159void MetricsManager::onUidMapReceived(const uint64_t& eventTimeNs) {
Yao Chend10f7b12017-12-18 12:53:50 -0800160 if (mAllowedPkg.size() == 0) {
161 return;
162 }
163 initLogSourceWhiteList();
164}
165
Yao Chen884c8c12018-01-26 10:36:25 -0800166void MetricsManager::dumpStates(FILE* out, bool verbose) {
167 fprintf(out, "ConfigKey %s, allowed source:", mConfigKey.ToString().c_str());
168 {
169 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
170 for (const auto& source : mAllowedLogSources) {
171 fprintf(out, "%d ", source);
172 }
173 }
174 fprintf(out, "\n");
175 for (const auto& producer : mAllMetricProducers) {
176 producer->dumpStates(out, verbose);
177 }
178}
179
Yao Chen06dba5d2018-01-26 13:38:16 -0800180void MetricsManager::dropData(const uint64_t dropTimeNs) {
181 for (const auto& producer : mAllMetricProducers) {
182 producer->dropData(dropTimeNs);
183 }
184}
185
Yao Chen8a8d16c2018-02-08 14:50:40 -0800186void MetricsManager::onDumpReport(const uint64_t dumpTimeStampNs, ProtoOutputStream* protoOutput) {
Yao Chen729093d2017-10-16 10:33:26 -0700187 VLOG("=========================Metric Reports Start==========================");
188 // one StatsLogReport per MetricProduer
Yangster-mac94e197c2018-01-02 16:03:03 -0800189 for (const auto& producer : mAllMetricProducers) {
190 if (mNoReportMetricIds.find(producer->getMetricId()) == mNoReportMetricIds.end()) {
Yi Jin5ee07872018-03-05 18:18:27 -0800191 uint64_t token =
Yangster-mac94e197c2018-01-02 16:03:03 -0800192 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_METRICS);
193 producer->onDumpReport(dumpTimeStampNs, protoOutput);
194 protoOutput->end(token);
195 }
Yao Chen729093d2017-10-16 10:33:26 -0700196 }
Yangster-mac330af582018-02-08 15:24:38 -0800197 mLastReportTimeNs = dumpTimeStampNs;
Yangster-mac3fa5d7f2018-03-10 21:50:27 -0800198 mLastReportWallClockNs = getWallClockNs();
Yao Chen729093d2017-10-16 10:33:26 -0700199 VLOG("=========================Metric Reports End==========================");
Yao Chen729093d2017-10-16 10:33:26 -0700200}
201
Yao Chen44cf27c2017-09-14 22:32:50 -0700202// Consume the stats log if it's interesting to this metric.
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700203void MetricsManager::onLogEvent(const LogEvent& event) {
Yao Chencaf339d2017-10-06 16:01:10 -0700204 if (!mConfigValid) {
205 return;
206 }
207
David Chenb639d142018-02-14 17:29:54 -0800208 if (event.GetTagId() == android::util::APP_BREADCRUMB_REPORTED) {
209 // Check that app breadcrumb reported fields are valid.
210 // TODO: Find a way to make these checks easier to maintain.
David Chendaa9f3a2017-12-28 16:52:22 -0800211 status_t err = NO_ERROR;
Bookatzb223c4e2018-02-01 15:35:04 -0800212
213 // Uid is 3rd from last field and must match the caller's uid,
214 // unless that caller is statsd itself (statsd is allowed to spoof uids).
215 long appHookUid = event.GetLong(event.size()-2, &err);
David Chen77ef6712018-02-23 18:23:42 -0800216 if (err != NO_ERROR ) {
217 VLOG("APP_BREADCRUMB_REPORTED had error when parsing the uid");
218 return;
219 }
Bookatzb223c4e2018-02-01 15:35:04 -0800220 int32_t loggerUid = event.GetUid();
David Chen77ef6712018-02-23 18:23:42 -0800221 if (loggerUid != appHookUid && loggerUid != AID_STATSD) {
222 VLOG("APP_BREADCRUMB_REPORTED has invalid uid: claimed %ld but caller is %d",
223 appHookUid, loggerUid);
David Chendaa9f3a2017-12-28 16:52:22 -0800224 return;
225 }
Bookatzb223c4e2018-02-01 15:35:04 -0800226
227 // Label is 2nd from last field and must be from [0, 15].
228 long appHookLabel = event.GetLong(event.size()-1, &err);
David Chen77ef6712018-02-23 18:23:42 -0800229 if (err != NO_ERROR ) {
230 VLOG("APP_BREADCRUMB_REPORTED had error when parsing the label field");
231 return;
232 } else if (appHookLabel < 0 || appHookLabel > 15) {
233 VLOG("APP_BREADCRUMB_REPORTED does not have valid label %ld", appHookLabel);
Bookatzb223c4e2018-02-01 15:35:04 -0800234 return;
235 }
236
David Chendaa9f3a2017-12-28 16:52:22 -0800237 // The state must be from 0,3. This part of code must be manually updated.
Bookatzb223c4e2018-02-01 15:35:04 -0800238 long appHookState = event.GetLong(event.size(), &err);
David Chen77ef6712018-02-23 18:23:42 -0800239 if (err != NO_ERROR ) {
240 VLOG("APP_BREADCRUMB_REPORTED had error when parsing the state field");
241 return;
242 } else if (appHookState < 0 || appHookState > 3) {
243 VLOG("APP_BREADCRUMB_REPORTED does not have valid state %ld", appHookState);
David Chendaa9f3a2017-12-28 16:52:22 -0800244 return;
245 }
Tej Singhbb8554a2018-01-26 11:59:14 -0800246 } else if (event.GetTagId() == android::util::DAVEY_OCCURRED) {
247 // Daveys can be logged from any app since they are logged in libs/hwui/JankTracker.cpp.
248 // Check that the davey duration is reasonable. Max length check is for privacy.
249 status_t err = NO_ERROR;
David Chen77ef6712018-02-23 18:23:42 -0800250
251 // Uid is the first field provided.
252 long jankUid = event.GetLong(1, &err);
253 if (err != NO_ERROR ) {
254 VLOG("Davey occurred had error when parsing the uid");
255 return;
256 }
257 int32_t loggerUid = event.GetUid();
258 if (loggerUid != jankUid && loggerUid != AID_STATSD) {
259 VLOG("DAVEY_OCCURRED has invalid uid: claimed %ld but caller is %d", jankUid,
260 loggerUid);
261 return;
262 }
263
Tej Singhbb8554a2018-01-26 11:59:14 -0800264 long duration = event.GetLong(event.size(), &err);
David Chen77ef6712018-02-23 18:23:42 -0800265 if (err != NO_ERROR ) {
266 VLOG("Davey occurred had error when parsing the duration");
267 return;
268 } else if (duration > 100000) {
Tej Singhbb8554a2018-01-26 11:59:14 -0800269 VLOG("Davey duration is unreasonably long: %ld", duration);
270 return;
271 }
272 } else {
273 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
274 if (mAllowedLogSources.find(event.GetUid()) == mAllowedLogSources.end()) {
275 VLOG("log source %d not on the whitelist", event.GetUid());
276 return;
277 }
Yao Chend10f7b12017-12-18 12:53:50 -0800278 }
279
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700280 int tagId = event.GetTagId();
Yangster-mac330af582018-02-08 15:24:38 -0800281 uint64_t eventTime = event.GetElapsedTimestampNs();
Yao Chen44cf27c2017-09-14 22:32:50 -0700282 if (mTagIds.find(tagId) == mTagIds.end()) {
283 // not interesting...
284 return;
285 }
Yao Chen44cf27c2017-09-14 22:32:50 -0700286
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800287 vector<MatchingState> matcherCache(mAllAtomMatchers.size(), MatchingState::kNotComputed);
Yao Chencaf339d2017-10-06 16:01:10 -0700288
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800289 for (auto& matcher : mAllAtomMatchers) {
290 matcher->onLogEvent(event, mAllAtomMatchers, matcherCache);
Yao Chen44cf27c2017-09-14 22:32:50 -0700291 }
292
Yao Chencaf339d2017-10-06 16:01:10 -0700293 // A bitmap to see which ConditionTracker needs to be re-evaluated.
294 vector<bool> conditionToBeEvaluated(mAllConditionTrackers.size(), false);
295
296 for (const auto& pair : mTrackerToConditionMap) {
297 if (matcherCache[pair.first] == MatchingState::kMatched) {
298 const auto& conditionList = pair.second;
299 for (const int conditionIndex : conditionList) {
300 conditionToBeEvaluated[conditionIndex] = true;
301 }
302 }
303 }
304
305 vector<ConditionState> conditionCache(mAllConditionTrackers.size(),
306 ConditionState::kNotEvaluated);
307 // A bitmap to track if a condition has changed value.
308 vector<bool> changedCache(mAllConditionTrackers.size(), false);
309 for (size_t i = 0; i < mAllConditionTrackers.size(); i++) {
310 if (conditionToBeEvaluated[i] == false) {
311 continue;
312 }
Yao Chencaf339d2017-10-06 16:01:10 -0700313 sp<ConditionTracker>& condition = mAllConditionTrackers[i];
314 condition->evaluateCondition(event, matcherCache, mAllConditionTrackers, conditionCache,
Yao Chen967b2052017-11-07 16:36:43 -0800315 changedCache);
Yao Chen729093d2017-10-16 10:33:26 -0700316 }
317
318 for (size_t i = 0; i < mAllConditionTrackers.size(); i++) {
Yao Chen967b2052017-11-07 16:36:43 -0800319 if (changedCache[i] == false) {
Yao Chen729093d2017-10-16 10:33:26 -0700320 continue;
321 }
322 auto pair = mConditionToMetricMap.find(i);
323 if (pair != mConditionToMetricMap.end()) {
324 auto& metricList = pair->second;
325 for (auto metricIndex : metricList) {
326 // metric cares about non sliced condition, and it's changed.
327 // Push the new condition to it directly.
Yao Chen967b2052017-11-07 16:36:43 -0800328 if (!mAllMetricProducers[metricIndex]->isConditionSliced()) {
Yao Chen5154a3792017-10-30 22:57:06 -0700329 mAllMetricProducers[metricIndex]->onConditionChanged(conditionCache[i],
330 eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700331 // metric cares about sliced conditions, and it may have changed. Send
332 // notification, and the metric can query the sliced conditions that are
333 // interesting to it.
Yangsterf2bee6f2017-11-29 12:01:05 -0800334 } else {
Yao Chen5154a3792017-10-30 22:57:06 -0700335 mAllMetricProducers[metricIndex]->onSlicedConditionMayChange(eventTime);
Yao Chen44cf27c2017-09-14 22:32:50 -0700336 }
Yao Chencaf339d2017-10-06 16:01:10 -0700337 }
338 }
339 }
340
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800341 // For matched AtomMatchers, tell relevant metrics that a matched event has come.
342 for (size_t i = 0; i < mAllAtomMatchers.size(); i++) {
Yao Chencaf339d2017-10-06 16:01:10 -0700343 if (matcherCache[i] == MatchingState::kMatched) {
Yao Chenb3561512017-11-21 18:07:17 -0800344 StatsdStats::getInstance().noteMatcherMatched(mConfigKey,
Yangster-mac94e197c2018-01-02 16:03:03 -0800345 mAllAtomMatchers[i]->getId());
Yao Chencaf339d2017-10-06 16:01:10 -0700346 auto pair = mTrackerToMetricMap.find(i);
347 if (pair != mTrackerToMetricMap.end()) {
348 auto& metricList = pair->second;
349 for (const int metricIndex : metricList) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700350 // pushed metrics are never scheduled pulls
Chenjie Yua7259ab2017-12-10 08:31:05 -0800351 mAllMetricProducers[metricIndex]->onMatchedLogEvent(i, event);
Yao Chencaf339d2017-10-06 16:01:10 -0700352 }
Yao Chen44cf27c2017-09-14 22:32:50 -0700353 }
354 }
355 }
356}
357
Yangster-mac932ecec2018-02-01 10:23:52 -0800358void MetricsManager::onAnomalyAlarmFired(
359 const uint64_t timestampNs,
360 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& alarmSet) {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800361 for (const auto& itr : mAllAnomalyTrackers) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800362 itr->informAlarmsFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800363 }
364}
365
Yangster-mac932ecec2018-02-01 10:23:52 -0800366void MetricsManager::onPeriodicAlarmFired(
367 const uint64_t timestampNs,
368 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& alarmSet) {
369 for (const auto& itr : mAllPeriodicAlarmTrackers) {
370 itr->informAlarmsFired(timestampNs, alarmSet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800371 }
372}
373
yro69007c82017-10-26 20:42:57 -0700374// Returns the total byte size of all metrics managed by a single config source.
375size_t MetricsManager::byteSize() {
376 size_t totalSize = 0;
377 for (auto metricProducer : mAllMetricProducers) {
378 totalSize += metricProducer->byteSize();
379 }
380 return totalSize;
381}
382
Yao Chen44cf27c2017-09-14 22:32:50 -0700383} // namespace statsd
384} // namespace os
385} // namespace android