blob: 51ea4b501596d32b29ffcb4b7db4c24b3eb93a02 [file] [log] [blame]
Yao Chen729093d2017-10-16 10:33:26 -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 */
16
Yao Chen3c0b95c2017-12-16 14:34:20 -080017#define DEBUG false
Yao Chen5154a372017-10-30 22:57:06 -070018
Yao Chen729093d2017-10-16 10:33:26 -070019#include "Log.h"
Yao Chen5154a372017-10-30 22:57:06 -070020#include "DurationMetricProducer.h"
Yao Chenb3561512017-11-21 18:07:17 -080021#include "guardrail/StatsdStats.h"
Yao Chen729093d2017-10-16 10:33:26 -070022#include "stats_util.h"
23
Yao Chen729093d2017-10-16 10:33:26 -070024#include <limits.h>
25#include <stdlib.h>
26
yrob0378b02017-11-09 20:36:25 -080027using android::util::FIELD_COUNT_REPEATED;
yro2b0f8862017-11-06 14:27:31 -080028using android::util::FIELD_TYPE_BOOL;
29using android::util::FIELD_TYPE_FLOAT;
30using android::util::FIELD_TYPE_INT32;
31using android::util::FIELD_TYPE_INT64;
32using android::util::FIELD_TYPE_MESSAGE;
Yangster-macd1815dc2017-11-13 21:43:15 -080033using android::util::FIELD_TYPE_STRING;
yro2b0f8862017-11-06 14:27:31 -080034using android::util::ProtoOutputStream;
Yao Chen729093d2017-10-16 10:33:26 -070035using std::string;
36using std::unordered_map;
37using std::vector;
38
39namespace android {
40namespace os {
41namespace statsd {
42
yro2b0f8862017-11-06 14:27:31 -080043// for StatsLogReport
Yangster-macd1815dc2017-11-13 21:43:15 -080044const int FIELD_ID_NAME = 1;
yro2b0f8862017-11-06 14:27:31 -080045const int FIELD_ID_START_REPORT_NANOS = 2;
46const int FIELD_ID_END_REPORT_NANOS = 3;
47const int FIELD_ID_DURATION_METRICS = 6;
48// for DurationMetricDataWrapper
49const int FIELD_ID_DATA = 1;
50// for DurationMetricData
51const int FIELD_ID_DIMENSION = 1;
52const int FIELD_ID_BUCKET_INFO = 2;
53// for KeyValuePair
54const int FIELD_ID_KEY = 1;
55const int FIELD_ID_VALUE_STR = 2;
56const int FIELD_ID_VALUE_INT = 3;
57const int FIELD_ID_VALUE_BOOL = 4;
58const int FIELD_ID_VALUE_FLOAT = 5;
59// for DurationBucketInfo
60const int FIELD_ID_START_BUCKET_NANOS = 1;
61const int FIELD_ID_END_BUCKET_NANOS = 2;
62const int FIELD_ID_DURATION = 3;
63
Yao Chenb3561512017-11-21 18:07:17 -080064DurationMetricProducer::DurationMetricProducer(const ConfigKey& key, const DurationMetric& metric,
Yao Chen729093d2017-10-16 10:33:26 -070065 const int conditionIndex, const size_t startIndex,
66 const size_t stopIndex, const size_t stopAllIndex,
Yao Chen0ea19902017-11-15 15:44:45 -080067 const bool nesting,
Yao Chen5154a372017-10-30 22:57:06 -070068 const sp<ConditionWizard>& wizard,
Yao Chen93fe3a32017-11-02 13:52:59 -070069 const vector<KeyMatcher>& internalDimension,
70 const uint64_t startTimeNs)
Yao Chenf09569f2017-12-13 17:00:51 -080071 : MetricProducer(metric.name(), key, startTimeNs, conditionIndex, wizard),
72 mAggregationType(metric.aggregation_type()),
Yao Chen729093d2017-10-16 10:33:26 -070073 mStartIndex(startIndex),
74 mStopIndex(stopIndex),
Yao Chen5154a372017-10-30 22:57:06 -070075 mStopAllIndex(stopAllIndex),
Yao Chen0ea19902017-11-15 15:44:45 -080076 mNested(nesting),
Yao Chen5154a372017-10-30 22:57:06 -070077 mInternalDimension(internalDimension) {
Yao Chen729093d2017-10-16 10:33:26 -070078 // TODO: The following boiler plate code appears in all MetricProducers, but we can't abstract
79 // them in the base class, because the proto generated CountMetric, and DurationMetric are
80 // not related. Maybe we should add a template in the future??
81 if (metric.has_bucket() && metric.bucket().has_bucket_size_millis()) {
82 mBucketSizeNs = metric.bucket().bucket_size_millis() * 1000000;
83 } else {
84 mBucketSizeNs = LLONG_MAX;
85 }
86
87 // TODO: use UidMap if uid->pkg_name is required
88 mDimension.insert(mDimension.begin(), metric.dimension().begin(), metric.dimension().end());
89
90 if (metric.links().size() > 0) {
91 mConditionLinks.insert(mConditionLinks.begin(), metric.links().begin(),
92 metric.links().end());
93 mConditionSliced = true;
94 }
95
Yangster-macd1815dc2017-11-13 21:43:15 -080096 VLOG("metric %s created. bucket size %lld start_time: %lld", metric.name().c_str(),
Yao Chen729093d2017-10-16 10:33:26 -070097 (long long)mBucketSizeNs, (long long)mStartTimeNs);
98}
99
100DurationMetricProducer::~DurationMetricProducer() {
101 VLOG("~DurationMetric() called");
102}
103
Bookatz857aaa52017-12-19 15:29:06 -0800104sp<AnomalyTracker> DurationMetricProducer::addAnomalyTracker(const Alert &alert) {
105 std::lock_guard<std::mutex> lock(mMutex);
Bookatz450099d2017-11-30 17:09:30 -0800106 if (alert.trigger_if_sum_gt() > alert.number_of_buckets() * mBucketSizeNs) {
107 ALOGW("invalid alert: threshold (%lld) > possible recordable value (%d x %lld)",
108 alert.trigger_if_sum_gt(), alert.number_of_buckets(),
109 (long long)mBucketSizeNs);
110 return nullptr;
111 }
Bookatz857aaa52017-12-19 15:29:06 -0800112 sp<DurationAnomalyTracker> anomalyTracker = new DurationAnomalyTracker(alert, mConfigKey);
113 if (anomalyTracker != nullptr) {
114 mAnomalyTrackers.push_back(anomalyTracker);
115 }
116 return anomalyTracker;
Bookatz450099d2017-11-30 17:09:30 -0800117}
118
Yao Chen5154a372017-10-30 22:57:06 -0700119unique_ptr<DurationTracker> DurationMetricProducer::createDurationTracker(
Yao Chenf60e0ba2017-11-29 15:06:41 -0800120 const HashableDimensionKey& eventKey) const {
Yao Chenf09569f2017-12-13 17:00:51 -0800121 switch (mAggregationType) {
Stefan Lafoncfed20b2017-11-18 09:26:53 -0800122 case DurationMetric_AggregationType_SUM:
Yao Chenb3561512017-11-21 18:07:17 -0800123 return make_unique<OringDurationTracker>(
Yao Chenf09569f2017-12-13 17:00:51 -0800124 mConfigKey, mName, eventKey, mWizard, mConditionTrackerIndex, mNested,
Yao Chenf60e0ba2017-11-29 15:06:41 -0800125 mCurrentBucketStartTimeNs, mBucketSizeNs, mAnomalyTrackers);
Stefan Lafoncfed20b2017-11-18 09:26:53 -0800126 case DurationMetric_AggregationType_MAX_SPARSE:
Yao Chenb3561512017-11-21 18:07:17 -0800127 return make_unique<MaxDurationTracker>(
Yao Chenf09569f2017-12-13 17:00:51 -0800128 mConfigKey, mName, eventKey, mWizard, mConditionTrackerIndex, mNested,
Yao Chenf60e0ba2017-11-29 15:06:41 -0800129 mCurrentBucketStartTimeNs, mBucketSizeNs, mAnomalyTrackers);
Yao Chen5154a372017-10-30 22:57:06 -0700130 }
131}
132
Yangsterf2bee6f2017-11-29 12:01:05 -0800133void DurationMetricProducer::onSlicedConditionMayChangeLocked(const uint64_t eventTime) {
Yao Chenf09569f2017-12-13 17:00:51 -0800134 VLOG("Metric %s onSlicedConditionMayChange", mName.c_str());
Yangsterf2bee6f2017-11-29 12:01:05 -0800135 flushIfNeededLocked(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700136 // Now for each of the on-going event, check if the condition has changed for them.
137 for (auto& pair : mCurrentSlicedDuration) {
Yao Chen5154a372017-10-30 22:57:06 -0700138 pair.second->onSlicedConditionMayChange(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700139 }
140}
141
Yangsterf2bee6f2017-11-29 12:01:05 -0800142void DurationMetricProducer::onConditionChangedLocked(const bool conditionMet,
143 const uint64_t eventTime) {
Yao Chenf09569f2017-12-13 17:00:51 -0800144 VLOG("Metric %s onConditionChanged", mName.c_str());
Yao Chen729093d2017-10-16 10:33:26 -0700145 mCondition = conditionMet;
Yangsterf2bee6f2017-11-29 12:01:05 -0800146 flushIfNeededLocked(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700147 // TODO: need to populate the condition change time from the event which triggers the condition
148 // change, instead of using current time.
149 for (auto& pair : mCurrentSlicedDuration) {
Yao Chen5154a372017-10-30 22:57:06 -0700150 pair.second->onConditionChanged(conditionMet, eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700151 }
152}
153
Yao Chen288c6002017-12-12 13:43:18 -0800154void DurationMetricProducer::onDumpReportLocked(const uint64_t dumpTimeNs,
155 ProtoOutputStream* protoOutput) {
156 flushIfNeededLocked(dumpTimeNs);
Yao Chen6a8c7992017-11-29 20:02:07 +0000157
Yao Chenf09569f2017-12-13 17:00:51 -0800158 protoOutput->write(FIELD_TYPE_STRING | FIELD_ID_NAME, mName);
Yao Chen288c6002017-12-12 13:43:18 -0800159 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_REPORT_NANOS, (long long)mStartTimeNs);
160 long long protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DURATION_METRICS);
161
Yao Chenf09569f2017-12-13 17:00:51 -0800162 VLOG("metric %s dump report now...", mName.c_str());
Yao Chen6a8c7992017-11-29 20:02:07 +0000163
Yao Chen729093d2017-10-16 10:33:26 -0700164 for (const auto& pair : mPastBuckets) {
165 const HashableDimensionKey& hashableKey = pair.first;
Yao Chend5aa01b32017-12-19 16:46:36 -0800166 const vector<KeyValuePair>& kvs = hashableKey.getKeyValuePairs();
yro2b0f8862017-11-06 14:27:31 -0800167 VLOG(" dimension key %s", hashableKey.c_str());
Yao Chen1ff4f432017-11-16 17:01:40 -0800168
yrob0378b02017-11-09 20:36:25 -0800169 long long wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800170 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
yro2b0f8862017-11-06 14:27:31 -0800171
172 // First fill dimension (KeyValuePairs).
Yao Chend5aa01b32017-12-19 16:46:36 -0800173 for (const auto& kv : kvs) {
Yao Chen288c6002017-12-12 13:43:18 -0800174 long long dimensionToken = protoOutput->start(
175 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DIMENSION);
176 protoOutput->write(FIELD_TYPE_INT32 | FIELD_ID_KEY, kv.key());
yro2b0f8862017-11-06 14:27:31 -0800177 if (kv.has_value_str()) {
Yao Chen288c6002017-12-12 13:43:18 -0800178 protoOutput->write(FIELD_TYPE_STRING | FIELD_ID_VALUE_STR, kv.value_str());
yro2b0f8862017-11-06 14:27:31 -0800179 } else if (kv.has_value_int()) {
Yao Chen288c6002017-12-12 13:43:18 -0800180 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_VALUE_INT, kv.value_int());
yro2b0f8862017-11-06 14:27:31 -0800181 } else if (kv.has_value_bool()) {
Yao Chen288c6002017-12-12 13:43:18 -0800182 protoOutput->write(FIELD_TYPE_BOOL | FIELD_ID_VALUE_BOOL, kv.value_bool());
yro2b0f8862017-11-06 14:27:31 -0800183 } else if (kv.has_value_float()) {
Yao Chen288c6002017-12-12 13:43:18 -0800184 protoOutput->write(FIELD_TYPE_FLOAT | FIELD_ID_VALUE_FLOAT, kv.value_float());
yro2b0f8862017-11-06 14:27:31 -0800185 }
Yao Chen288c6002017-12-12 13:43:18 -0800186 protoOutput->end(dimensionToken);
yro2b0f8862017-11-06 14:27:31 -0800187 }
188
189 // Then fill bucket_info (DurationBucketInfo).
190 for (const auto& bucket : pair.second) {
Yao Chen288c6002017-12-12 13:43:18 -0800191 long long bucketInfoToken = protoOutput->start(
192 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
193 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_NANOS,
194 (long long)bucket.mBucketStartNs);
195 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_NANOS,
196 (long long)bucket.mBucketEndNs);
197 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_DURATION, (long long)bucket.mDuration);
198 protoOutput->end(bucketInfoToken);
yro2b0f8862017-11-06 14:27:31 -0800199 VLOG("\t bucket [%lld - %lld] duration: %lld", (long long)bucket.mBucketStartNs,
200 (long long)bucket.mBucketEndNs, (long long)bucket.mDuration);
201 }
202
Yao Chen288c6002017-12-12 13:43:18 -0800203 protoOutput->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700204 }
yro2b0f8862017-11-06 14:27:31 -0800205
Yao Chen288c6002017-12-12 13:43:18 -0800206 protoOutput->end(protoToken);
207 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_REPORT_NANOS, (long long)dumpTimeNs);
Yao Chenf60e0ba2017-11-29 15:06:41 -0800208 mPastBuckets.clear();
Yao Chen288c6002017-12-12 13:43:18 -0800209 mStartTimeNs = mCurrentBucketStartTimeNs;
yro2b0f8862017-11-06 14:27:31 -0800210}
Yao Chen729093d2017-10-16 10:33:26 -0700211
Yangsterf2bee6f2017-11-29 12:01:05 -0800212void DurationMetricProducer::flushIfNeededLocked(const uint64_t& eventTime) {
Yao Chen729093d2017-10-16 10:33:26 -0700213 if (mCurrentBucketStartTimeNs + mBucketSizeNs > eventTime) {
214 return;
215 }
Yao Chen5154a372017-10-30 22:57:06 -0700216 VLOG("flushing...........");
Yao Chend41c4222017-11-15 19:26:14 -0800217 for (auto it = mCurrentSlicedDuration.begin(); it != mCurrentSlicedDuration.end();) {
Yao Chenf60e0ba2017-11-29 15:06:41 -0800218 if (it->second->flushIfNeeded(eventTime, &mPastBuckets)) {
Yao Chen5154a372017-10-30 22:57:06 -0700219 VLOG("erase bucket for key %s", it->first.c_str());
Yao Chend41c4222017-11-15 19:26:14 -0800220 it = mCurrentSlicedDuration.erase(it);
221 } else {
222 ++it;
Yao Chen729093d2017-10-16 10:33:26 -0700223 }
224 }
Yao Chen5154a372017-10-30 22:57:06 -0700225
226 int numBucketsForward = (eventTime - mCurrentBucketStartTimeNs) / mBucketSizeNs;
227 mCurrentBucketStartTimeNs += numBucketsForward * mBucketSizeNs;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800228 mCurrentBucketNum += numBucketsForward;
Yao Chen5154a372017-10-30 22:57:06 -0700229}
230
Yangsterf2bee6f2017-11-29 12:01:05 -0800231bool DurationMetricProducer::hitGuardRailLocked(const HashableDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800232 // the key is not new, we are good.
233 if (mCurrentSlicedDuration.find(newKey) != mCurrentSlicedDuration.end()) {
234 return false;
235 }
236 // 1. Report the tuple count if the tuple count > soft limit
237 if (mCurrentSlicedDuration.size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
238 size_t newTupleCount = mCurrentSlicedDuration.size() + 1;
Yao Chenf09569f2017-12-13 17:00:51 -0800239 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mName, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800240 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
241 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
Yao Chenf09569f2017-12-13 17:00:51 -0800242 ALOGE("DurationMetric %s dropping data for dimension key %s", mName.c_str(),
Yao Chenb3561512017-11-21 18:07:17 -0800243 newKey.c_str());
244 return true;
245 }
246 }
247 return false;
248}
249
Yangsterf2bee6f2017-11-29 12:01:05 -0800250void DurationMetricProducer::onMatchedLogEventInternalLocked(
Yao Chen5154a372017-10-30 22:57:06 -0700251 const size_t matcherIndex, const HashableDimensionKey& eventKey,
252 const map<string, HashableDimensionKey>& conditionKeys, bool condition,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800253 const LogEvent& event) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800254 flushIfNeededLocked(event.GetTimestampNs());
Yao Chen5154a372017-10-30 22:57:06 -0700255
Yao Chen6a8c7992017-11-29 20:02:07 +0000256 if (matcherIndex == mStopAllIndex) {
257 for (auto& pair : mCurrentSlicedDuration) {
258 pair.second->noteStopAll(event.GetTimestampNs());
259 }
260 return;
261 }
262
Yao Chend5aa01b32017-12-19 16:46:36 -0800263 HashableDimensionKey atomKey(getDimensionKey(event, mInternalDimension));
Yao Chen6a8c7992017-11-29 20:02:07 +0000264
265 if (mCurrentSlicedDuration.find(eventKey) == mCurrentSlicedDuration.end()) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800266 if (hitGuardRailLocked(eventKey)) {
Yao Chenb3561512017-11-21 18:07:17 -0800267 return;
268 }
Yao Chenf60e0ba2017-11-29 15:06:41 -0800269 mCurrentSlicedDuration[eventKey] = createDurationTracker(eventKey);
Yao Chen6a8c7992017-11-29 20:02:07 +0000270 }
Yao Chen5154a372017-10-30 22:57:06 -0700271
Yao Chen6a8c7992017-11-29 20:02:07 +0000272 auto it = mCurrentSlicedDuration.find(eventKey);
Yao Chen5154a372017-10-30 22:57:06 -0700273
Yao Chen6a8c7992017-11-29 20:02:07 +0000274 if (matcherIndex == mStartIndex) {
275 it->second->noteStart(atomKey, condition, event.GetTimestampNs(), conditionKeys);
276 } else if (matcherIndex == mStopIndex) {
277 it->second->noteStop(atomKey, event.GetTimestampNs(), false);
Yao Chen5154a372017-10-30 22:57:06 -0700278 }
Yao Chen729093d2017-10-16 10:33:26 -0700279}
280
Yangsterf2bee6f2017-11-29 12:01:05 -0800281size_t DurationMetricProducer::byteSizeLocked() const {
Yangster7c334a12017-11-22 14:24:24 -0800282 size_t totalSize = 0;
283 for (const auto& pair : mPastBuckets) {
284 totalSize += pair.second.size() * kBucketSize;
285 }
286 return totalSize;
yro69007c82017-10-26 20:42:57 -0700287}
288
Yao Chen729093d2017-10-16 10:33:26 -0700289} // namespace statsd
290} // namespace os
291} // namespace android