blob: 30b105c71500785bdf23fb76c66af73755aba3d4 [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"
Yangster-mac20877162017-12-22 17:19:39 -080023#include "stats_log_util.h"
Yao Chen729093d2017-10-16 10:33:26 -070024
Yao Chen729093d2017-10-16 10:33:26 -070025#include <limits.h>
26#include <stdlib.h>
27
yrob0378b02017-11-09 20:36:25 -080028using android::util::FIELD_COUNT_REPEATED;
yro2b0f8862017-11-06 14:27:31 -080029using android::util::FIELD_TYPE_BOOL;
30using android::util::FIELD_TYPE_FLOAT;
31using android::util::FIELD_TYPE_INT32;
32using android::util::FIELD_TYPE_INT64;
33using android::util::FIELD_TYPE_MESSAGE;
Yangster-macd1815dc2017-11-13 21:43:15 -080034using android::util::FIELD_TYPE_STRING;
yro2b0f8862017-11-06 14:27:31 -080035using android::util::ProtoOutputStream;
Yao Chen729093d2017-10-16 10:33:26 -070036using std::string;
37using std::unordered_map;
38using std::vector;
39
40namespace android {
41namespace os {
42namespace statsd {
43
yro2b0f8862017-11-06 14:27:31 -080044// for StatsLogReport
Yangster-macd1815dc2017-11-13 21:43:15 -080045const int FIELD_ID_NAME = 1;
yro2b0f8862017-11-06 14:27:31 -080046const int FIELD_ID_START_REPORT_NANOS = 2;
47const int FIELD_ID_END_REPORT_NANOS = 3;
48const int FIELD_ID_DURATION_METRICS = 6;
49// for DurationMetricDataWrapper
50const int FIELD_ID_DATA = 1;
51// for DurationMetricData
52const int FIELD_ID_DIMENSION = 1;
53const int FIELD_ID_BUCKET_INFO = 2;
yro2b0f8862017-11-06 14:27:31 -080054// for DurationBucketInfo
55const int FIELD_ID_START_BUCKET_NANOS = 1;
56const int FIELD_ID_END_BUCKET_NANOS = 2;
57const int FIELD_ID_DURATION = 3;
58
Yao Chenb3561512017-11-21 18:07:17 -080059DurationMetricProducer::DurationMetricProducer(const ConfigKey& key, const DurationMetric& metric,
Yao Chen729093d2017-10-16 10:33:26 -070060 const int conditionIndex, const size_t startIndex,
61 const size_t stopIndex, const size_t stopAllIndex,
Yao Chen0ea19902017-11-15 15:44:45 -080062 const bool nesting,
Yao Chen5154a372017-10-30 22:57:06 -070063 const sp<ConditionWizard>& wizard,
Yangster-mac20877162017-12-22 17:19:39 -080064 const FieldMatcher& internalDimensions,
Yao Chen93fe3a32017-11-02 13:52:59 -070065 const uint64_t startTimeNs)
Yao Chenf09569f2017-12-13 17:00:51 -080066 : MetricProducer(metric.name(), key, startTimeNs, conditionIndex, wizard),
67 mAggregationType(metric.aggregation_type()),
Yao Chen729093d2017-10-16 10:33:26 -070068 mStartIndex(startIndex),
69 mStopIndex(stopIndex),
Yao Chen5154a372017-10-30 22:57:06 -070070 mStopAllIndex(stopAllIndex),
Yao Chen0ea19902017-11-15 15:44:45 -080071 mNested(nesting),
Yangster-mac20877162017-12-22 17:19:39 -080072 mInternalDimensions(internalDimensions) {
Yao Chen729093d2017-10-16 10:33:26 -070073 // TODO: The following boiler plate code appears in all MetricProducers, but we can't abstract
74 // them in the base class, because the proto generated CountMetric, and DurationMetric are
75 // not related. Maybe we should add a template in the future??
76 if (metric.has_bucket() && metric.bucket().has_bucket_size_millis()) {
77 mBucketSizeNs = metric.bucket().bucket_size_millis() * 1000000;
78 } else {
79 mBucketSizeNs = LLONG_MAX;
80 }
81
82 // TODO: use UidMap if uid->pkg_name is required
Yangster-mac20877162017-12-22 17:19:39 -080083 mDimensions = metric.dimensions();
Yao Chen729093d2017-10-16 10:33:26 -070084
85 if (metric.links().size() > 0) {
86 mConditionLinks.insert(mConditionLinks.begin(), metric.links().begin(),
87 metric.links().end());
88 mConditionSliced = true;
89 }
90
Yangster-macd1815dc2017-11-13 21:43:15 -080091 VLOG("metric %s created. bucket size %lld start_time: %lld", metric.name().c_str(),
Yao Chen729093d2017-10-16 10:33:26 -070092 (long long)mBucketSizeNs, (long long)mStartTimeNs);
93}
94
95DurationMetricProducer::~DurationMetricProducer() {
96 VLOG("~DurationMetric() called");
97}
98
Bookatz857aaa52017-12-19 15:29:06 -080099sp<AnomalyTracker> DurationMetricProducer::addAnomalyTracker(const Alert &alert) {
100 std::lock_guard<std::mutex> lock(mMutex);
Bookatz450099d2017-11-30 17:09:30 -0800101 if (alert.trigger_if_sum_gt() > alert.number_of_buckets() * mBucketSizeNs) {
102 ALOGW("invalid alert: threshold (%lld) > possible recordable value (%d x %lld)",
103 alert.trigger_if_sum_gt(), alert.number_of_buckets(),
104 (long long)mBucketSizeNs);
105 return nullptr;
106 }
Bookatz857aaa52017-12-19 15:29:06 -0800107 sp<DurationAnomalyTracker> anomalyTracker = new DurationAnomalyTracker(alert, mConfigKey);
108 if (anomalyTracker != nullptr) {
109 mAnomalyTrackers.push_back(anomalyTracker);
110 }
111 return anomalyTracker;
Bookatz450099d2017-11-30 17:09:30 -0800112}
113
Yao Chen5154a372017-10-30 22:57:06 -0700114unique_ptr<DurationTracker> DurationMetricProducer::createDurationTracker(
Yao Chenf60e0ba2017-11-29 15:06:41 -0800115 const HashableDimensionKey& eventKey) const {
Yao Chenf09569f2017-12-13 17:00:51 -0800116 switch (mAggregationType) {
Stefan Lafoncfed20b2017-11-18 09:26:53 -0800117 case DurationMetric_AggregationType_SUM:
Yao Chenb3561512017-11-21 18:07:17 -0800118 return make_unique<OringDurationTracker>(
Yao Chenf09569f2017-12-13 17:00:51 -0800119 mConfigKey, mName, eventKey, mWizard, mConditionTrackerIndex, mNested,
Yao Chenf60e0ba2017-11-29 15:06:41 -0800120 mCurrentBucketStartTimeNs, mBucketSizeNs, mAnomalyTrackers);
Stefan Lafoncfed20b2017-11-18 09:26:53 -0800121 case DurationMetric_AggregationType_MAX_SPARSE:
Yao Chenb3561512017-11-21 18:07:17 -0800122 return make_unique<MaxDurationTracker>(
Yao Chenf09569f2017-12-13 17:00:51 -0800123 mConfigKey, mName, eventKey, mWizard, mConditionTrackerIndex, mNested,
Yao Chenf60e0ba2017-11-29 15:06:41 -0800124 mCurrentBucketStartTimeNs, mBucketSizeNs, mAnomalyTrackers);
Yao Chen5154a372017-10-30 22:57:06 -0700125 }
126}
127
Yangsterf2bee6f2017-11-29 12:01:05 -0800128void DurationMetricProducer::onSlicedConditionMayChangeLocked(const uint64_t eventTime) {
Yao Chenf09569f2017-12-13 17:00:51 -0800129 VLOG("Metric %s onSlicedConditionMayChange", mName.c_str());
Yangsterf2bee6f2017-11-29 12:01:05 -0800130 flushIfNeededLocked(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700131 // Now for each of the on-going event, check if the condition has changed for them.
132 for (auto& pair : mCurrentSlicedDuration) {
Yao Chen5154a372017-10-30 22:57:06 -0700133 pair.second->onSlicedConditionMayChange(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700134 }
135}
136
Yangsterf2bee6f2017-11-29 12:01:05 -0800137void DurationMetricProducer::onConditionChangedLocked(const bool conditionMet,
138 const uint64_t eventTime) {
Yao Chenf09569f2017-12-13 17:00:51 -0800139 VLOG("Metric %s onConditionChanged", mName.c_str());
Yao Chen729093d2017-10-16 10:33:26 -0700140 mCondition = conditionMet;
Yangsterf2bee6f2017-11-29 12:01:05 -0800141 flushIfNeededLocked(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700142 // TODO: need to populate the condition change time from the event which triggers the condition
143 // change, instead of using current time.
144 for (auto& pair : mCurrentSlicedDuration) {
Yao Chen5154a372017-10-30 22:57:06 -0700145 pair.second->onConditionChanged(conditionMet, eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700146 }
147}
148
Yangster-mac20877162017-12-22 17:19:39 -0800149void DurationMetricProducer::onDumpReportLocked(const uint64_t dumpTimeNs, StatsLogReport* report) {
150 flushIfNeededLocked(dumpTimeNs);
151 report->set_metric_name(mName);
152 report->set_start_report_nanos(mStartTimeNs);
153
154 auto duration_metrics = report->mutable_duration_metrics();
155 for (const auto& pair : mPastBuckets) {
156 DurationMetricData* metricData = duration_metrics->add_data();
157 *metricData->mutable_dimension() = pair.first.getDimensionsValue();
158 for (const auto& bucket : pair.second) {
159 auto bucketInfo = metricData->add_bucket_info();
160 bucketInfo->set_start_bucket_nanos(bucket.mBucketStartNs);
161 bucketInfo->set_end_bucket_nanos(bucket.mBucketEndNs);
162 bucketInfo->set_duration_nanos(bucket.mDuration);
163 }
164 }
165}
166
Yao Chen288c6002017-12-12 13:43:18 -0800167void DurationMetricProducer::onDumpReportLocked(const uint64_t dumpTimeNs,
168 ProtoOutputStream* protoOutput) {
169 flushIfNeededLocked(dumpTimeNs);
Yao Chen6a8c7992017-11-29 20:02:07 +0000170
Yao Chenf09569f2017-12-13 17:00:51 -0800171 protoOutput->write(FIELD_TYPE_STRING | FIELD_ID_NAME, mName);
Yao Chen288c6002017-12-12 13:43:18 -0800172 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_REPORT_NANOS, (long long)mStartTimeNs);
173 long long protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DURATION_METRICS);
174
Yao Chenf09569f2017-12-13 17:00:51 -0800175 VLOG("metric %s dump report now...", mName.c_str());
Yao Chen6a8c7992017-11-29 20:02:07 +0000176
Yao Chen729093d2017-10-16 10:33:26 -0700177 for (const auto& pair : mPastBuckets) {
178 const HashableDimensionKey& hashableKey = pair.first;
yro2b0f8862017-11-06 14:27:31 -0800179 VLOG(" dimension key %s", hashableKey.c_str());
Yao Chen1ff4f432017-11-16 17:01:40 -0800180
yrob0378b02017-11-09 20:36:25 -0800181 long long wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800182 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
yro2b0f8862017-11-06 14:27:31 -0800183
Yangster-mac20877162017-12-22 17:19:39 -0800184 // First fill dimension.
185 long long dimensionToken = protoOutput->start(
186 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DIMENSION);
187 writeDimensionsValueProtoToStream(hashableKey.getDimensionsValue(), protoOutput);
188 protoOutput->end(dimensionToken);
yro2b0f8862017-11-06 14:27:31 -0800189
190 // Then fill bucket_info (DurationBucketInfo).
191 for (const auto& bucket : pair.second) {
Yao Chen288c6002017-12-12 13:43:18 -0800192 long long bucketInfoToken = protoOutput->start(
193 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
194 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_NANOS,
195 (long long)bucket.mBucketStartNs);
196 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_NANOS,
197 (long long)bucket.mBucketEndNs);
198 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_DURATION, (long long)bucket.mDuration);
199 protoOutput->end(bucketInfoToken);
yro2b0f8862017-11-06 14:27:31 -0800200 VLOG("\t bucket [%lld - %lld] duration: %lld", (long long)bucket.mBucketStartNs,
201 (long long)bucket.mBucketEndNs, (long long)bucket.mDuration);
202 }
203
Yao Chen288c6002017-12-12 13:43:18 -0800204 protoOutput->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700205 }
yro2b0f8862017-11-06 14:27:31 -0800206
Yao Chen288c6002017-12-12 13:43:18 -0800207 protoOutput->end(protoToken);
208 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_REPORT_NANOS, (long long)dumpTimeNs);
Yao Chenf60e0ba2017-11-29 15:06:41 -0800209 mPastBuckets.clear();
Yao Chen288c6002017-12-12 13:43:18 -0800210 mStartTimeNs = mCurrentBucketStartTimeNs;
yro2b0f8862017-11-06 14:27:31 -0800211}
Yao Chen729093d2017-10-16 10:33:26 -0700212
Yangsterf2bee6f2017-11-29 12:01:05 -0800213void DurationMetricProducer::flushIfNeededLocked(const uint64_t& eventTime) {
Yao Chen729093d2017-10-16 10:33:26 -0700214 if (mCurrentBucketStartTimeNs + mBucketSizeNs > eventTime) {
215 return;
216 }
Yao Chen5154a372017-10-30 22:57:06 -0700217 VLOG("flushing...........");
Yao Chend41c4222017-11-15 19:26:14 -0800218 for (auto it = mCurrentSlicedDuration.begin(); it != mCurrentSlicedDuration.end();) {
Yao Chenf60e0ba2017-11-29 15:06:41 -0800219 if (it->second->flushIfNeeded(eventTime, &mPastBuckets)) {
Yao Chen5154a372017-10-30 22:57:06 -0700220 VLOG("erase bucket for key %s", it->first.c_str());
Yao Chend41c4222017-11-15 19:26:14 -0800221 it = mCurrentSlicedDuration.erase(it);
222 } else {
223 ++it;
Yao Chen729093d2017-10-16 10:33:26 -0700224 }
225 }
Yao Chen5154a372017-10-30 22:57:06 -0700226
227 int numBucketsForward = (eventTime - mCurrentBucketStartTimeNs) / mBucketSizeNs;
228 mCurrentBucketStartTimeNs += numBucketsForward * mBucketSizeNs;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800229 mCurrentBucketNum += numBucketsForward;
Yao Chen5154a372017-10-30 22:57:06 -0700230}
231
Yangsterf2bee6f2017-11-29 12:01:05 -0800232bool DurationMetricProducer::hitGuardRailLocked(const HashableDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800233 // the key is not new, we are good.
234 if (mCurrentSlicedDuration.find(newKey) != mCurrentSlicedDuration.end()) {
235 return false;
236 }
237 // 1. Report the tuple count if the tuple count > soft limit
238 if (mCurrentSlicedDuration.size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
239 size_t newTupleCount = mCurrentSlicedDuration.size() + 1;
Yao Chenf09569f2017-12-13 17:00:51 -0800240 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mName, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800241 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
242 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
Yao Chenf09569f2017-12-13 17:00:51 -0800243 ALOGE("DurationMetric %s dropping data for dimension key %s", mName.c_str(),
Yao Chenb3561512017-11-21 18:07:17 -0800244 newKey.c_str());
245 return true;
246 }
247 }
248 return false;
249}
250
Yangsterf2bee6f2017-11-29 12:01:05 -0800251void DurationMetricProducer::onMatchedLogEventInternalLocked(
Yao Chen5154a372017-10-30 22:57:06 -0700252 const size_t matcherIndex, const HashableDimensionKey& eventKey,
Yangster-mac20877162017-12-22 17:19:39 -0800253 const ConditionKey& conditionKeys, bool condition,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800254 const LogEvent& event) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800255 flushIfNeededLocked(event.GetTimestampNs());
Yao Chen5154a372017-10-30 22:57:06 -0700256
Yao Chen6a8c7992017-11-29 20:02:07 +0000257 if (matcherIndex == mStopAllIndex) {
258 for (auto& pair : mCurrentSlicedDuration) {
259 pair.second->noteStopAll(event.GetTimestampNs());
260 }
261 return;
262 }
263
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
Yangster-mac20877162017-12-22 17:19:39 -0800274 std::vector<DimensionsValue> values = getDimensionKeys(event, mInternalDimensions);
275 if (values.empty()) {
276 if (matcherIndex == mStartIndex) {
277 it->second->noteStart(DEFAULT_DIMENSION_KEY, condition,
278 event.GetTimestampNs(), conditionKeys);
279 } else if (matcherIndex == mStopIndex) {
280 it->second->noteStop(DEFAULT_DIMENSION_KEY, event.GetTimestampNs(), false);
281 }
282 } else {
283 for (const DimensionsValue& value : values) {
284 if (matcherIndex == mStartIndex) {
285 it->second->noteStart(HashableDimensionKey(value), condition,
286 event.GetTimestampNs(), conditionKeys);
287 } else if (matcherIndex == mStopIndex) {
288 it->second->noteStop(HashableDimensionKey(value), event.GetTimestampNs(), false);
289 }
290 }
Yao Chen5154a372017-10-30 22:57:06 -0700291 }
Yangster-mac20877162017-12-22 17:19:39 -0800292
Yao Chen729093d2017-10-16 10:33:26 -0700293}
294
Yangsterf2bee6f2017-11-29 12:01:05 -0800295size_t DurationMetricProducer::byteSizeLocked() const {
Yangster7c334a12017-11-22 14:24:24 -0800296 size_t totalSize = 0;
297 for (const auto& pair : mPastBuckets) {
298 totalSize += pair.second.size() * kBucketSize;
299 }
300 return totalSize;
yro69007c82017-10-26 20:42:57 -0700301}
302
Yao Chen729093d2017-10-16 10:33:26 -0700303} // namespace statsd
304} // namespace os
305} // namespace android