blob: e26fe5649090a1dc640eb44127be62ba1b5a3d64 [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-mac94e197c2018-01-02 16:03:03 -080045const int FIELD_ID_ID = 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
Yangster-mac468ff042018-01-17 12:26:34 -080052const int FIELD_ID_DIMENSION_IN_WHAT = 1;
53const int FIELD_ID_DIMENSION_IN_CONDITION = 2;
54const int FIELD_ID_BUCKET_INFO = 3;
yro2b0f8862017-11-06 14:27:31 -080055// for DurationBucketInfo
56const int FIELD_ID_START_BUCKET_NANOS = 1;
57const int FIELD_ID_END_BUCKET_NANOS = 2;
58const int FIELD_ID_DURATION = 3;
59
Yao Chenb3561512017-11-21 18:07:17 -080060DurationMetricProducer::DurationMetricProducer(const ConfigKey& key, const DurationMetric& metric,
Yao Chen729093d2017-10-16 10:33:26 -070061 const int conditionIndex, const size_t startIndex,
62 const size_t stopIndex, const size_t stopAllIndex,
Yao Chen0ea19902017-11-15 15:44:45 -080063 const bool nesting,
Yao Chen5154a372017-10-30 22:57:06 -070064 const sp<ConditionWizard>& wizard,
Yangster-mac20877162017-12-22 17:19:39 -080065 const FieldMatcher& internalDimensions,
Yao Chen93fe3a32017-11-02 13:52:59 -070066 const uint64_t startTimeNs)
Yangster-mac94e197c2018-01-02 16:03:03 -080067 : MetricProducer(metric.id(), key, startTimeNs, conditionIndex, wizard),
Yao Chenf09569f2017-12-13 17:00:51 -080068 mAggregationType(metric.aggregation_type()),
Yao Chen729093d2017-10-16 10:33:26 -070069 mStartIndex(startIndex),
70 mStopIndex(stopIndex),
Yao Chen5154a372017-10-30 22:57:06 -070071 mStopAllIndex(stopAllIndex),
Yao Chen0ea19902017-11-15 15:44:45 -080072 mNested(nesting),
Yangster-mac20877162017-12-22 17:19:39 -080073 mInternalDimensions(internalDimensions) {
Yao Chen729093d2017-10-16 10:33:26 -070074 // TODO: The following boiler plate code appears in all MetricProducers, but we can't abstract
75 // them in the base class, because the proto generated CountMetric, and DurationMetric are
76 // not related. Maybe we should add a template in the future??
Yangster-macb8144812018-01-04 10:56:23 -080077 if (metric.has_bucket()) {
78 mBucketSizeNs = TimeUnitToBucketSizeInMillis(metric.bucket()) * 1000000;
Yao Chen729093d2017-10-16 10:33:26 -070079 } else {
80 mBucketSizeNs = LLONG_MAX;
81 }
82
83 // TODO: use UidMap if uid->pkg_name is required
Yangster-mac468ff042018-01-17 12:26:34 -080084 mDimensions = metric.dimensions_in_what();
Yao Chen729093d2017-10-16 10:33:26 -070085
86 if (metric.links().size() > 0) {
87 mConditionLinks.insert(mConditionLinks.begin(), metric.links().begin(),
88 metric.links().end());
89 mConditionSliced = true;
90 }
91
Yangster-mac94e197c2018-01-02 16:03:03 -080092 VLOG("metric %lld created. bucket size %lld start_time: %lld", (long long)metric.id(),
Yao Chen729093d2017-10-16 10:33:26 -070093 (long long)mBucketSizeNs, (long long)mStartTimeNs);
94}
95
96DurationMetricProducer::~DurationMetricProducer() {
97 VLOG("~DurationMetric() called");
98}
99
Bookatz857aaa52017-12-19 15:29:06 -0800100sp<AnomalyTracker> DurationMetricProducer::addAnomalyTracker(const Alert &alert) {
101 std::lock_guard<std::mutex> lock(mMutex);
Yangster-maca7fb12d2018-01-03 17:17:20 -0800102 if (alert.trigger_if_sum_gt() > alert.num_buckets() * mBucketSizeNs) {
103 ALOGW("invalid alert: threshold (%f) > possible recordable value (%d x %lld)",
104 alert.trigger_if_sum_gt(), alert.num_buckets(),
Bookatz450099d2017-11-30 17:09:30 -0800105 (long long)mBucketSizeNs);
106 return nullptr;
107 }
Bookatz857aaa52017-12-19 15:29:06 -0800108 sp<DurationAnomalyTracker> anomalyTracker = new DurationAnomalyTracker(alert, mConfigKey);
109 if (anomalyTracker != nullptr) {
110 mAnomalyTrackers.push_back(anomalyTracker);
111 }
112 return anomalyTracker;
Bookatz450099d2017-11-30 17:09:30 -0800113}
114
Yao Chen5154a372017-10-30 22:57:06 -0700115unique_ptr<DurationTracker> DurationMetricProducer::createDurationTracker(
Yao Chenf60e0ba2017-11-29 15:06:41 -0800116 const HashableDimensionKey& eventKey) const {
Yao Chenf09569f2017-12-13 17:00:51 -0800117 switch (mAggregationType) {
Stefan Lafoncfed20b2017-11-18 09:26:53 -0800118 case DurationMetric_AggregationType_SUM:
Yao Chenb3561512017-11-21 18:07:17 -0800119 return make_unique<OringDurationTracker>(
Yangster-mac94e197c2018-01-02 16:03:03 -0800120 mConfigKey, mMetricId, eventKey, mWizard, mConditionTrackerIndex, mNested,
Yao Chend59a6582018-01-08 11:17:11 -0800121 mCurrentBucketStartTimeNs, mBucketSizeNs, mConditionSliced, mAnomalyTrackers);
Stefan Lafoncfed20b2017-11-18 09:26:53 -0800122 case DurationMetric_AggregationType_MAX_SPARSE:
Yao Chenb3561512017-11-21 18:07:17 -0800123 return make_unique<MaxDurationTracker>(
Yangster-mac94e197c2018-01-02 16:03:03 -0800124 mConfigKey, mMetricId, eventKey, mWizard, mConditionTrackerIndex, mNested,
Yao Chend59a6582018-01-08 11:17:11 -0800125 mCurrentBucketStartTimeNs, mBucketSizeNs, mConditionSliced, mAnomalyTrackers);
Yao Chen5154a372017-10-30 22:57:06 -0700126 }
127}
128
Yangsterf2bee6f2017-11-29 12:01:05 -0800129void DurationMetricProducer::onSlicedConditionMayChangeLocked(const uint64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800130 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Yangsterf2bee6f2017-11-29 12:01:05 -0800131 flushIfNeededLocked(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700132 // Now for each of the on-going event, check if the condition has changed for them.
133 for (auto& pair : mCurrentSlicedDuration) {
Yao Chen5154a372017-10-30 22:57:06 -0700134 pair.second->onSlicedConditionMayChange(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700135 }
136}
137
Yangsterf2bee6f2017-11-29 12:01:05 -0800138void DurationMetricProducer::onConditionChangedLocked(const bool conditionMet,
139 const uint64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800140 VLOG("Metric %lld onConditionChanged", (long long)mMetricId);
Yao Chen729093d2017-10-16 10:33:26 -0700141 mCondition = conditionMet;
Yangsterf2bee6f2017-11-29 12:01:05 -0800142 flushIfNeededLocked(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700143 // TODO: need to populate the condition change time from the event which triggers the condition
144 // change, instead of using current time.
145 for (auto& pair : mCurrentSlicedDuration) {
Yao Chen5154a372017-10-30 22:57:06 -0700146 pair.second->onConditionChanged(conditionMet, eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700147 }
148}
149
Yangster-mac20877162017-12-22 17:19:39 -0800150void DurationMetricProducer::onDumpReportLocked(const uint64_t dumpTimeNs, StatsLogReport* report) {
151 flushIfNeededLocked(dumpTimeNs);
Yangster-mac94e197c2018-01-02 16:03:03 -0800152 report->set_metric_id(mMetricId);
Yangster-mac20877162017-12-22 17:19:39 -0800153 report->set_start_report_nanos(mStartTimeNs);
154
155 auto duration_metrics = report->mutable_duration_metrics();
156 for (const auto& pair : mPastBuckets) {
157 DurationMetricData* metricData = duration_metrics->add_data();
Yangster-mac468ff042018-01-17 12:26:34 -0800158 *metricData->mutable_dimensions_in_what() = pair.first.getDimensionsValue();
Yangster-mac20877162017-12-22 17:19:39 -0800159 for (const auto& bucket : pair.second) {
160 auto bucketInfo = metricData->add_bucket_info();
161 bucketInfo->set_start_bucket_nanos(bucket.mBucketStartNs);
162 bucketInfo->set_end_bucket_nanos(bucket.mBucketEndNs);
163 bucketInfo->set_duration_nanos(bucket.mDuration);
164 }
165 }
166}
167
Yao Chen288c6002017-12-12 13:43:18 -0800168void DurationMetricProducer::onDumpReportLocked(const uint64_t dumpTimeNs,
169 ProtoOutputStream* protoOutput) {
170 flushIfNeededLocked(dumpTimeNs);
Yangster-mac635b4b32018-01-23 20:17:35 -0800171 if (mPastBuckets.empty()) {
172 return;
173 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000174
Yangster-mac94e197c2018-01-02 16:03:03 -0800175 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Yao Chen288c6002017-12-12 13:43:18 -0800176 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_REPORT_NANOS, (long long)mStartTimeNs);
177 long long protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DURATION_METRICS);
178
Yangster-mac94e197c2018-01-02 16:03:03 -0800179 VLOG("metric %lld dump report now...", (long long)mMetricId);
Yao Chen6a8c7992017-11-29 20:02:07 +0000180
Yao Chen729093d2017-10-16 10:33:26 -0700181 for (const auto& pair : mPastBuckets) {
182 const HashableDimensionKey& hashableKey = pair.first;
yro2b0f8862017-11-06 14:27:31 -0800183 VLOG(" dimension key %s", hashableKey.c_str());
Yao Chen1ff4f432017-11-16 17:01:40 -0800184
yrob0378b02017-11-09 20:36:25 -0800185 long long wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800186 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
yro2b0f8862017-11-06 14:27:31 -0800187
Yangster-mac20877162017-12-22 17:19:39 -0800188 // First fill dimension.
189 long long dimensionToken = protoOutput->start(
Yangster-mac468ff042018-01-17 12:26:34 -0800190 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
Yangster-mac20877162017-12-22 17:19:39 -0800191 writeDimensionsValueProtoToStream(hashableKey.getDimensionsValue(), protoOutput);
192 protoOutput->end(dimensionToken);
yro2b0f8862017-11-06 14:27:31 -0800193
194 // Then fill bucket_info (DurationBucketInfo).
195 for (const auto& bucket : pair.second) {
Yao Chen288c6002017-12-12 13:43:18 -0800196 long long bucketInfoToken = protoOutput->start(
197 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
198 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_NANOS,
199 (long long)bucket.mBucketStartNs);
200 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_NANOS,
201 (long long)bucket.mBucketEndNs);
202 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_DURATION, (long long)bucket.mDuration);
203 protoOutput->end(bucketInfoToken);
yro2b0f8862017-11-06 14:27:31 -0800204 VLOG("\t bucket [%lld - %lld] duration: %lld", (long long)bucket.mBucketStartNs,
205 (long long)bucket.mBucketEndNs, (long long)bucket.mDuration);
206 }
207
Yao Chen288c6002017-12-12 13:43:18 -0800208 protoOutput->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700209 }
yro2b0f8862017-11-06 14:27:31 -0800210
Yao Chen288c6002017-12-12 13:43:18 -0800211 protoOutput->end(protoToken);
212 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_REPORT_NANOS, (long long)dumpTimeNs);
Yao Chenf60e0ba2017-11-29 15:06:41 -0800213 mPastBuckets.clear();
Yao Chen288c6002017-12-12 13:43:18 -0800214 mStartTimeNs = mCurrentBucketStartTimeNs;
yro2b0f8862017-11-06 14:27:31 -0800215}
Yao Chen729093d2017-10-16 10:33:26 -0700216
Yangsterf2bee6f2017-11-29 12:01:05 -0800217void DurationMetricProducer::flushIfNeededLocked(const uint64_t& eventTime) {
Yao Chen729093d2017-10-16 10:33:26 -0700218 if (mCurrentBucketStartTimeNs + mBucketSizeNs > eventTime) {
219 return;
220 }
Yao Chen5154a372017-10-30 22:57:06 -0700221 VLOG("flushing...........");
Yao Chend41c4222017-11-15 19:26:14 -0800222 for (auto it = mCurrentSlicedDuration.begin(); it != mCurrentSlicedDuration.end();) {
Yao Chenf60e0ba2017-11-29 15:06:41 -0800223 if (it->second->flushIfNeeded(eventTime, &mPastBuckets)) {
Yao Chen5154a372017-10-30 22:57:06 -0700224 VLOG("erase bucket for key %s", it->first.c_str());
Yao Chend41c4222017-11-15 19:26:14 -0800225 it = mCurrentSlicedDuration.erase(it);
226 } else {
227 ++it;
Yao Chen729093d2017-10-16 10:33:26 -0700228 }
229 }
Yao Chen5154a372017-10-30 22:57:06 -0700230
231 int numBucketsForward = (eventTime - mCurrentBucketStartTimeNs) / mBucketSizeNs;
232 mCurrentBucketStartTimeNs += numBucketsForward * mBucketSizeNs;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800233 mCurrentBucketNum += numBucketsForward;
Yao Chen5154a372017-10-30 22:57:06 -0700234}
235
Yangsterf2bee6f2017-11-29 12:01:05 -0800236bool DurationMetricProducer::hitGuardRailLocked(const HashableDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800237 // the key is not new, we are good.
238 if (mCurrentSlicedDuration.find(newKey) != mCurrentSlicedDuration.end()) {
239 return false;
240 }
241 // 1. Report the tuple count if the tuple count > soft limit
242 if (mCurrentSlicedDuration.size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
243 size_t newTupleCount = mCurrentSlicedDuration.size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800244 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800245 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
246 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800247 ALOGE("DurationMetric %lld dropping data for dimension key %s",
248 (long long)mMetricId, newKey.c_str());
Yao Chenb3561512017-11-21 18:07:17 -0800249 return true;
250 }
251 }
252 return false;
253}
254
Yangsterf2bee6f2017-11-29 12:01:05 -0800255void DurationMetricProducer::onMatchedLogEventInternalLocked(
Yao Chen5154a372017-10-30 22:57:06 -0700256 const size_t matcherIndex, const HashableDimensionKey& eventKey,
Yangster-mac20877162017-12-22 17:19:39 -0800257 const ConditionKey& conditionKeys, bool condition,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800258 const LogEvent& event) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800259 flushIfNeededLocked(event.GetTimestampNs());
Yao Chen5154a372017-10-30 22:57:06 -0700260
Yao Chen6a8c7992017-11-29 20:02:07 +0000261 if (matcherIndex == mStopAllIndex) {
262 for (auto& pair : mCurrentSlicedDuration) {
263 pair.second->noteStopAll(event.GetTimestampNs());
264 }
265 return;
266 }
267
Yao Chen6a8c7992017-11-29 20:02:07 +0000268
269 if (mCurrentSlicedDuration.find(eventKey) == mCurrentSlicedDuration.end()) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800270 if (hitGuardRailLocked(eventKey)) {
Yao Chenb3561512017-11-21 18:07:17 -0800271 return;
272 }
Yao Chenf60e0ba2017-11-29 15:06:41 -0800273 mCurrentSlicedDuration[eventKey] = createDurationTracker(eventKey);
Yao Chen6a8c7992017-11-29 20:02:07 +0000274 }
Yao Chen5154a372017-10-30 22:57:06 -0700275
Yao Chen6a8c7992017-11-29 20:02:07 +0000276 auto it = mCurrentSlicedDuration.find(eventKey);
Yao Chen5154a372017-10-30 22:57:06 -0700277
Yangster-mac20877162017-12-22 17:19:39 -0800278 std::vector<DimensionsValue> values = getDimensionKeys(event, mInternalDimensions);
279 if (values.empty()) {
280 if (matcherIndex == mStartIndex) {
281 it->second->noteStart(DEFAULT_DIMENSION_KEY, condition,
282 event.GetTimestampNs(), conditionKeys);
283 } else if (matcherIndex == mStopIndex) {
284 it->second->noteStop(DEFAULT_DIMENSION_KEY, event.GetTimestampNs(), false);
285 }
286 } else {
287 for (const DimensionsValue& value : values) {
288 if (matcherIndex == mStartIndex) {
289 it->second->noteStart(HashableDimensionKey(value), condition,
290 event.GetTimestampNs(), conditionKeys);
291 } else if (matcherIndex == mStopIndex) {
292 it->second->noteStop(HashableDimensionKey(value), event.GetTimestampNs(), false);
293 }
294 }
Yao Chen5154a372017-10-30 22:57:06 -0700295 }
Yangster-mac20877162017-12-22 17:19:39 -0800296
Yao Chen729093d2017-10-16 10:33:26 -0700297}
298
Yangsterf2bee6f2017-11-29 12:01:05 -0800299size_t DurationMetricProducer::byteSizeLocked() const {
Yangster7c334a12017-11-22 14:24:24 -0800300 size_t totalSize = 0;
301 for (const auto& pair : mPastBuckets) {
302 totalSize += pair.second.size() * kBucketSize;
303 }
304 return totalSize;
yro69007c82017-10-26 20:42:57 -0700305}
306
Yao Chen729093d2017-10-16 10:33:26 -0700307} // namespace statsd
308} // namespace os
309} // namespace android