blob: 417145c00e54f945f02a399c4ac7a9cbc5c01d6c [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 Chen44cf27c2017-09-14 22:32:50 -070016#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"
Yao Chen44cf27c2017-09-14 22:32:50 -070029
Yao Chen93fe3a32017-11-02 13:52:59 -070030#include <log/logprint.h>
Yao Chen288c6002017-12-12 13:43:18 -080031
32using android::util::FIELD_COUNT_REPEATED;
33using android::util::FIELD_TYPE_MESSAGE;
34using android::util::ProtoOutputStream;
35
Yao Chen44cf27c2017-09-14 22:32:50 -070036using std::make_unique;
37using std::set;
38using std::string;
Yao Chen44cf27c2017-09-14 22:32:50 -070039using std::unordered_map;
40using std::vector;
41
42namespace android {
43namespace os {
44namespace statsd {
45
Yao Chen288c6002017-12-12 13:43:18 -080046const int FIELD_ID_METRICS = 1;
47
Yao Chend10f7b12017-12-18 12:53:50 -080048MetricsManager::MetricsManager(const ConfigKey& key, const StatsdConfig& config,
49 const long timeBaseSec, sp<UidMap> uidMap)
Bookatzb223c4e2018-02-01 15:35:04 -080050 : mConfigKey(key), mUidMap(uidMap), mStatsdUid(getStatsdUid()) {
Yao Chenb3561512017-11-21 18:07:17 -080051 mConfigValid =
Yangster-mac20877162017-12-22 17:19:39 -080052 initStatsdConfig(key, config, *uidMap, timeBaseSec, mTagIds, mAllAtomMatchers, mAllConditionTrackers,
Yao Chenb3561512017-11-21 18:07:17 -080053 mAllMetricProducers, mAllAnomalyTrackers, mConditionToMetricMap,
Yangster-mac94e197c2018-01-02 16:03:03 -080054 mTrackerToMetricMap, mTrackerToConditionMap, mNoReportMetricIds);
Yao Chenb3561512017-11-21 18:07:17 -080055
Yao Chen147ce602017-12-22 14:35:34 -080056 if (config.allowed_log_source_size() == 0) {
Yao Chend10f7b12017-12-18 12:53:50 -080057 // TODO(b/70794411): uncomment the following line and remove the hard coded log source
58 // after all configs have the log source added.
59 // mConfigValid = false;
60 // ALOGE("Log source white list is empty! This config won't get any data.");
61
62 mAllowedUid.push_back(1000);
63 mAllowedUid.push_back(0);
Bookatzb223c4e2018-02-01 15:35:04 -080064 mAllowedUid.push_back(mStatsdUid);
Yao Chend10f7b12017-12-18 12:53:50 -080065 mAllowedLogSources.insert(mAllowedUid.begin(), mAllowedUid.end());
66 } else {
Yao Chen147ce602017-12-22 14:35:34 -080067 for (const auto& source : config.allowed_log_source()) {
68 auto it = UidMap::sAidToUidMapping.find(source);
69 if (it != UidMap::sAidToUidMapping.end()) {
70 mAllowedUid.push_back(it->second);
71 } else {
72 mAllowedPkg.push_back(source);
73 }
74 }
Yao Chend10f7b12017-12-18 12:53:50 -080075
76 if (mAllowedUid.size() + mAllowedPkg.size() > StatsdStats::kMaxLogSourceCount) {
77 ALOGE("Too many log sources. This is likely to be an error in the config.");
78 mConfigValid = false;
79 } else {
80 initLogSourceWhiteList();
81 }
82 }
83
Yao Chenb3561512017-11-21 18:07:17 -080084 // Guardrail. Reject the config if it's too big.
85 if (mAllMetricProducers.size() > StatsdStats::kMaxMetricCountPerConfig ||
86 mAllConditionTrackers.size() > StatsdStats::kMaxConditionCountPerConfig ||
Stefan Lafonb8c9aa82017-12-03 14:27:25 -080087 mAllAtomMatchers.size() > StatsdStats::kMaxMatcherCountPerConfig) {
Yao Chenb3561512017-11-21 18:07:17 -080088 ALOGE("This config is too big! Reject!");
89 mConfigValid = false;
90 }
Yao Chenf09569f2017-12-13 17:00:51 -080091
92 // TODO: add alert size.
93 // no matter whether this config is valid, log it in the stats.
94 StatsdStats::getInstance().noteConfigReceived(key, mAllMetricProducers.size(),
95 mAllConditionTrackers.size(),
96 mAllAtomMatchers.size(), 0, mConfigValid);
Yao Chen44cf27c2017-09-14 22:32:50 -070097}
98
99MetricsManager::~MetricsManager() {
Bookatzd3606c72017-10-19 10:13:49 -0700100 VLOG("~MetricsManager()");
Yao Chen44cf27c2017-09-14 22:32:50 -0700101}
102
Yao Chend10f7b12017-12-18 12:53:50 -0800103void MetricsManager::initLogSourceWhiteList() {
104 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
105 mAllowedLogSources.clear();
106 mAllowedLogSources.insert(mAllowedUid.begin(), mAllowedUid.end());
107
108 for (const auto& pkg : mAllowedPkg) {
109 auto uids = mUidMap->getAppUid(pkg);
110 mAllowedLogSources.insert(uids.begin(), uids.end());
111 }
112 if (DEBUG) {
113 for (const auto& uid : mAllowedLogSources) {
114 VLOG("Allowed uid %d", uid);
115 }
116 }
117}
118
Yao Chencaf339d2017-10-06 16:01:10 -0700119bool MetricsManager::isConfigValid() const {
120 return mConfigValid;
121}
122
Yao Chend10f7b12017-12-18 12:53:50 -0800123void MetricsManager::notifyAppUpgrade(const string& apk, const int uid, const int64_t version) {
124 // check if we care this package
125 if (std::find(mAllowedPkg.begin(), mAllowedPkg.end(), apk) == mAllowedPkg.end()) {
126 return;
127 }
128 // We will re-initialize the whole list because we don't want to keep the multi mapping of
129 // UID<->pkg inside MetricsManager to reduce the memory usage.
130 initLogSourceWhiteList();
131}
132
133void MetricsManager::notifyAppRemoved(const string& apk, const int uid) {
134 // check if we care this package
135 if (std::find(mAllowedPkg.begin(), mAllowedPkg.end(), apk) == mAllowedPkg.end()) {
136 return;
137 }
138 // We will re-initialize the whole list because we don't want to keep the multi mapping of
139 // UID<->pkg inside MetricsManager to reduce the memory usage.
140 initLogSourceWhiteList();
141}
142
143void MetricsManager::onUidMapReceived() {
144 if (mAllowedPkg.size() == 0) {
145 return;
146 }
147 initLogSourceWhiteList();
148}
149
Yangster-mac20877162017-12-22 17:19:39 -0800150void MetricsManager::onDumpReport(const uint64_t& dumpTimeStampNs, ConfigMetricsReport* report) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800151 for (const auto& producer : mAllMetricProducers) {
152 if (mNoReportMetricIds.find(producer->getMetricId()) == mNoReportMetricIds.end()) {
153 producer->onDumpReport(dumpTimeStampNs, report->add_metrics());
154 }
Yangster-mac20877162017-12-22 17:19:39 -0800155 }
156}
157
Yao Chen884c8c12018-01-26 10:36:25 -0800158void MetricsManager::dumpStates(FILE* out, bool verbose) {
159 fprintf(out, "ConfigKey %s, allowed source:", mConfigKey.ToString().c_str());
160 {
161 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
162 for (const auto& source : mAllowedLogSources) {
163 fprintf(out, "%d ", source);
164 }
165 }
166 fprintf(out, "\n");
167 for (const auto& producer : mAllMetricProducers) {
168 producer->dumpStates(out, verbose);
169 }
170}
171
Yao Chen288c6002017-12-12 13:43:18 -0800172void MetricsManager::onDumpReport(ProtoOutputStream* protoOutput) {
Yao Chen729093d2017-10-16 10:33:26 -0700173 VLOG("=========================Metric Reports Start==========================");
Yao Chen288c6002017-12-12 13:43:18 -0800174 uint64_t dumpTimeStampNs = time(nullptr) * NS_PER_SEC;
Yao Chen729093d2017-10-16 10:33:26 -0700175 // one StatsLogReport per MetricProduer
Yangster-mac94e197c2018-01-02 16:03:03 -0800176 for (const auto& producer : mAllMetricProducers) {
177 if (mNoReportMetricIds.find(producer->getMetricId()) == mNoReportMetricIds.end()) {
178 long long token =
179 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_METRICS);
180 producer->onDumpReport(dumpTimeStampNs, protoOutput);
181 protoOutput->end(token);
182 }
Yao Chen729093d2017-10-16 10:33:26 -0700183 }
184 VLOG("=========================Metric Reports End==========================");
Yao Chen729093d2017-10-16 10:33:26 -0700185}
186
Yao Chen44cf27c2017-09-14 22:32:50 -0700187// Consume the stats log if it's interesting to this metric.
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700188void MetricsManager::onLogEvent(const LogEvent& event) {
Yao Chencaf339d2017-10-06 16:01:10 -0700189 if (!mConfigValid) {
190 return;
191 }
192
Tej Singhbb8554a2018-01-26 11:59:14 -0800193 if (event.GetTagId() == android::util::APP_HOOK) { // Check that app hook fields are valid.
David Chendaa9f3a2017-12-28 16:52:22 -0800194 // TODO: Find a way to make these checks easier to maintain if the app hooks get changed.
David Chendaa9f3a2017-12-28 16:52:22 -0800195 status_t err = NO_ERROR;
Bookatzb223c4e2018-02-01 15:35:04 -0800196
197 // Uid is 3rd from last field and must match the caller's uid,
198 // unless that caller is statsd itself (statsd is allowed to spoof uids).
199 long appHookUid = event.GetLong(event.size()-2, &err);
200 int32_t loggerUid = event.GetUid();
201 if (err != NO_ERROR || (loggerUid != appHookUid && loggerUid != mStatsdUid)) {
202 VLOG("AppHook has invalid uid: claimed %ld but caller is %d", appHookUid, loggerUid);
David Chendaa9f3a2017-12-28 16:52:22 -0800203 return;
204 }
Bookatzb223c4e2018-02-01 15:35:04 -0800205
206 // Label is 2nd from last field and must be from [0, 15].
207 long appHookLabel = event.GetLong(event.size()-1, &err);
208 if (err != NO_ERROR || appHookLabel < 0 || appHookLabel > 15) {
209 VLOG("AppHook does not have valid label %ld", appHookLabel);
210 return;
211 }
212
David Chendaa9f3a2017-12-28 16:52:22 -0800213 // The state must be from 0,3. This part of code must be manually updated.
Bookatzb223c4e2018-02-01 15:35:04 -0800214 long appHookState = event.GetLong(event.size(), &err);
215 if (err != NO_ERROR || appHookState < 0 || appHookState > 3) {
216 VLOG("AppHook does not have valid state %ld", appHookState);
David Chendaa9f3a2017-12-28 16:52:22 -0800217 return;
218 }
Tej Singhbb8554a2018-01-26 11:59:14 -0800219 } else if (event.GetTagId() == android::util::DAVEY_OCCURRED) {
220 // Daveys can be logged from any app since they are logged in libs/hwui/JankTracker.cpp.
221 // Check that the davey duration is reasonable. Max length check is for privacy.
222 status_t err = NO_ERROR;
223 long duration = event.GetLong(event.size(), &err);
224 if (err != NO_ERROR || duration > 100000) {
225 VLOG("Davey duration is unreasonably long: %ld", duration);
226 return;
227 }
228 } else {
229 std::lock_guard<std::mutex> lock(mAllowedLogSourcesMutex);
230 if (mAllowedLogSources.find(event.GetUid()) == mAllowedLogSources.end()) {
231 VLOG("log source %d not on the whitelist", event.GetUid());
232 return;
233 }
Yao Chend10f7b12017-12-18 12:53:50 -0800234 }
235
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700236 int tagId = event.GetTagId();
Yao Chen5154a3792017-10-30 22:57:06 -0700237 uint64_t eventTime = event.GetTimestampNs();
Yao Chen44cf27c2017-09-14 22:32:50 -0700238 if (mTagIds.find(tagId) == mTagIds.end()) {
239 // not interesting...
240 return;
241 }
Yao Chen44cf27c2017-09-14 22:32:50 -0700242
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800243 vector<MatchingState> matcherCache(mAllAtomMatchers.size(), MatchingState::kNotComputed);
Yao Chencaf339d2017-10-06 16:01:10 -0700244
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800245 for (auto& matcher : mAllAtomMatchers) {
246 matcher->onLogEvent(event, mAllAtomMatchers, matcherCache);
Yao Chen44cf27c2017-09-14 22:32:50 -0700247 }
248
Yao Chencaf339d2017-10-06 16:01:10 -0700249 // A bitmap to see which ConditionTracker needs to be re-evaluated.
250 vector<bool> conditionToBeEvaluated(mAllConditionTrackers.size(), false);
251
252 for (const auto& pair : mTrackerToConditionMap) {
253 if (matcherCache[pair.first] == MatchingState::kMatched) {
254 const auto& conditionList = pair.second;
255 for (const int conditionIndex : conditionList) {
256 conditionToBeEvaluated[conditionIndex] = true;
257 }
258 }
259 }
260
261 vector<ConditionState> conditionCache(mAllConditionTrackers.size(),
262 ConditionState::kNotEvaluated);
263 // A bitmap to track if a condition has changed value.
264 vector<bool> changedCache(mAllConditionTrackers.size(), false);
265 for (size_t i = 0; i < mAllConditionTrackers.size(); i++) {
266 if (conditionToBeEvaluated[i] == false) {
267 continue;
268 }
Yao Chencaf339d2017-10-06 16:01:10 -0700269 sp<ConditionTracker>& condition = mAllConditionTrackers[i];
270 condition->evaluateCondition(event, matcherCache, mAllConditionTrackers, conditionCache,
Yao Chen967b2052017-11-07 16:36:43 -0800271 changedCache);
Yao Chen729093d2017-10-16 10:33:26 -0700272 }
273
274 for (size_t i = 0; i < mAllConditionTrackers.size(); i++) {
Yao Chen967b2052017-11-07 16:36:43 -0800275 if (changedCache[i] == false) {
Yao Chen729093d2017-10-16 10:33:26 -0700276 continue;
277 }
278 auto pair = mConditionToMetricMap.find(i);
279 if (pair != mConditionToMetricMap.end()) {
280 auto& metricList = pair->second;
281 for (auto metricIndex : metricList) {
282 // metric cares about non sliced condition, and it's changed.
283 // Push the new condition to it directly.
Yao Chen967b2052017-11-07 16:36:43 -0800284 if (!mAllMetricProducers[metricIndex]->isConditionSliced()) {
Yao Chen5154a3792017-10-30 22:57:06 -0700285 mAllMetricProducers[metricIndex]->onConditionChanged(conditionCache[i],
286 eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700287 // metric cares about sliced conditions, and it may have changed. Send
288 // notification, and the metric can query the sliced conditions that are
289 // interesting to it.
Yangsterf2bee6f2017-11-29 12:01:05 -0800290 } else {
Yao Chen5154a3792017-10-30 22:57:06 -0700291 mAllMetricProducers[metricIndex]->onSlicedConditionMayChange(eventTime);
Yao Chen44cf27c2017-09-14 22:32:50 -0700292 }
Yao Chencaf339d2017-10-06 16:01:10 -0700293 }
294 }
295 }
296
Stefan Lafonb8c9aa82017-12-03 14:27:25 -0800297 // For matched AtomMatchers, tell relevant metrics that a matched event has come.
298 for (size_t i = 0; i < mAllAtomMatchers.size(); i++) {
Yao Chencaf339d2017-10-06 16:01:10 -0700299 if (matcherCache[i] == MatchingState::kMatched) {
Yao Chenb3561512017-11-21 18:07:17 -0800300 StatsdStats::getInstance().noteMatcherMatched(mConfigKey,
Yangster-mac94e197c2018-01-02 16:03:03 -0800301 mAllAtomMatchers[i]->getId());
Yao Chencaf339d2017-10-06 16:01:10 -0700302 auto pair = mTrackerToMetricMap.find(i);
303 if (pair != mTrackerToMetricMap.end()) {
304 auto& metricList = pair->second;
305 for (const int metricIndex : metricList) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700306 // pushed metrics are never scheduled pulls
Chenjie Yua7259ab2017-12-10 08:31:05 -0800307 mAllMetricProducers[metricIndex]->onMatchedLogEvent(i, event);
Yao Chencaf339d2017-10-06 16:01:10 -0700308 }
Yao Chen44cf27c2017-09-14 22:32:50 -0700309 }
310 }
311 }
312}
313
Yangster-mace2cd6d52017-11-09 20:38:30 -0800314void MetricsManager::onAnomalyAlarmFired(const uint64_t timestampNs,
Bookatzcc5adef22017-11-21 14:36:23 -0800315 unordered_set<sp<const AnomalyAlarm>, SpHash<AnomalyAlarm>>& anomalySet) {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800316 for (const auto& itr : mAllAnomalyTrackers) {
Bookatzcc5adef22017-11-21 14:36:23 -0800317 itr->informAlarmsFired(timestampNs, anomalySet);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800318 }
319}
320
321void MetricsManager::setAnomalyMonitor(const sp<AnomalyMonitor>& anomalyMonitor) {
322 for (auto& itr : mAllAnomalyTrackers) {
323 itr->setAnomalyMonitor(anomalyMonitor);
324 }
325}
326
yro69007c82017-10-26 20:42:57 -0700327// Returns the total byte size of all metrics managed by a single config source.
328size_t MetricsManager::byteSize() {
329 size_t totalSize = 0;
330 for (auto metricProducer : mAllMetricProducers) {
331 totalSize += metricProducer->byteSize();
332 }
333 return totalSize;
334}
335
Bookatzb223c4e2018-02-01 15:35:04 -0800336int32_t MetricsManager::getStatsdUid() {
337 auto suit = UidMap::sAidToUidMapping.find("AID_STATSD");
338 if (suit != UidMap::sAidToUidMapping.end()) {
339 return suit->second;
340 } else {
341 ALOGE("Statsd failed to find its own uid!");
342 return -1;
343 }
344}
345
Yao Chen44cf27c2017-09-14 22:32:50 -0700346} // namespace statsd
347} // namespace os
348} // namespace android