blob: 58dd46400a9f70d8d3a8785e70579f4fc9456ca6 [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);
Yao Chen6a8c7992017-11-29 20:02:07 +0000171
Yangster-mac94e197c2018-01-02 16:03:03 -0800172 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Yao Chen288c6002017-12-12 13:43:18 -0800173 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_REPORT_NANOS, (long long)mStartTimeNs);
174 long long protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DURATION_METRICS);
175
Yangster-mac94e197c2018-01-02 16:03:03 -0800176 VLOG("metric %lld dump report now...", (long long)mMetricId);
Yao Chen6a8c7992017-11-29 20:02:07 +0000177
Yao Chen729093d2017-10-16 10:33:26 -0700178 for (const auto& pair : mPastBuckets) {
179 const HashableDimensionKey& hashableKey = pair.first;
yro2b0f8862017-11-06 14:27:31 -0800180 VLOG(" dimension key %s", hashableKey.c_str());
Yao Chen1ff4f432017-11-16 17:01:40 -0800181
yrob0378b02017-11-09 20:36:25 -0800182 long long wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800183 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
yro2b0f8862017-11-06 14:27:31 -0800184
Yangster-mac20877162017-12-22 17:19:39 -0800185 // First fill dimension.
186 long long dimensionToken = protoOutput->start(
Yangster-mac468ff042018-01-17 12:26:34 -0800187 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
Yangster-mac20877162017-12-22 17:19:39 -0800188 writeDimensionsValueProtoToStream(hashableKey.getDimensionsValue(), protoOutput);
189 protoOutput->end(dimensionToken);
yro2b0f8862017-11-06 14:27:31 -0800190
191 // Then fill bucket_info (DurationBucketInfo).
192 for (const auto& bucket : pair.second) {
Yao Chen288c6002017-12-12 13:43:18 -0800193 long long bucketInfoToken = protoOutput->start(
194 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
195 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_NANOS,
196 (long long)bucket.mBucketStartNs);
197 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_NANOS,
198 (long long)bucket.mBucketEndNs);
199 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_DURATION, (long long)bucket.mDuration);
200 protoOutput->end(bucketInfoToken);
yro2b0f8862017-11-06 14:27:31 -0800201 VLOG("\t bucket [%lld - %lld] duration: %lld", (long long)bucket.mBucketStartNs,
202 (long long)bucket.mBucketEndNs, (long long)bucket.mDuration);
203 }
204
Yao Chen288c6002017-12-12 13:43:18 -0800205 protoOutput->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700206 }
yro2b0f8862017-11-06 14:27:31 -0800207
Yao Chen288c6002017-12-12 13:43:18 -0800208 protoOutput->end(protoToken);
209 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_REPORT_NANOS, (long long)dumpTimeNs);
Yao Chenf60e0ba2017-11-29 15:06:41 -0800210 mPastBuckets.clear();
Yao Chen288c6002017-12-12 13:43:18 -0800211 mStartTimeNs = mCurrentBucketStartTimeNs;
yro2b0f8862017-11-06 14:27:31 -0800212}
Yao Chen729093d2017-10-16 10:33:26 -0700213
Yangsterf2bee6f2017-11-29 12:01:05 -0800214void DurationMetricProducer::flushIfNeededLocked(const uint64_t& eventTime) {
Yao Chen729093d2017-10-16 10:33:26 -0700215 if (mCurrentBucketStartTimeNs + mBucketSizeNs > eventTime) {
216 return;
217 }
Yao Chen5154a372017-10-30 22:57:06 -0700218 VLOG("flushing...........");
Yao Chend41c4222017-11-15 19:26:14 -0800219 for (auto it = mCurrentSlicedDuration.begin(); it != mCurrentSlicedDuration.end();) {
Yao Chenf60e0ba2017-11-29 15:06:41 -0800220 if (it->second->flushIfNeeded(eventTime, &mPastBuckets)) {
Yao Chen5154a372017-10-30 22:57:06 -0700221 VLOG("erase bucket for key %s", it->first.c_str());
Yao Chend41c4222017-11-15 19:26:14 -0800222 it = mCurrentSlicedDuration.erase(it);
223 } else {
224 ++it;
Yao Chen729093d2017-10-16 10:33:26 -0700225 }
226 }
Yao Chen5154a372017-10-30 22:57:06 -0700227
228 int numBucketsForward = (eventTime - mCurrentBucketStartTimeNs) / mBucketSizeNs;
229 mCurrentBucketStartTimeNs += numBucketsForward * mBucketSizeNs;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800230 mCurrentBucketNum += numBucketsForward;
Yao Chen5154a372017-10-30 22:57:06 -0700231}
232
Yangsterf2bee6f2017-11-29 12:01:05 -0800233bool DurationMetricProducer::hitGuardRailLocked(const HashableDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800234 // the key is not new, we are good.
235 if (mCurrentSlicedDuration.find(newKey) != mCurrentSlicedDuration.end()) {
236 return false;
237 }
238 // 1. Report the tuple count if the tuple count > soft limit
239 if (mCurrentSlicedDuration.size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
240 size_t newTupleCount = mCurrentSlicedDuration.size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800241 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800242 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
243 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800244 ALOGE("DurationMetric %lld dropping data for dimension key %s",
245 (long long)mMetricId, newKey.c_str());
Yao Chenb3561512017-11-21 18:07:17 -0800246 return true;
247 }
248 }
249 return false;
250}
251
Yangsterf2bee6f2017-11-29 12:01:05 -0800252void DurationMetricProducer::onMatchedLogEventInternalLocked(
Yao Chen5154a372017-10-30 22:57:06 -0700253 const size_t matcherIndex, const HashableDimensionKey& eventKey,
Yangster-mac20877162017-12-22 17:19:39 -0800254 const ConditionKey& conditionKeys, bool condition,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800255 const LogEvent& event) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800256 flushIfNeededLocked(event.GetTimestampNs());
Yao Chen5154a372017-10-30 22:57:06 -0700257
Yao Chen6a8c7992017-11-29 20:02:07 +0000258 if (matcherIndex == mStopAllIndex) {
259 for (auto& pair : mCurrentSlicedDuration) {
260 pair.second->noteStopAll(event.GetTimestampNs());
261 }
262 return;
263 }
264
Yao Chen6a8c7992017-11-29 20:02:07 +0000265
266 if (mCurrentSlicedDuration.find(eventKey) == mCurrentSlicedDuration.end()) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800267 if (hitGuardRailLocked(eventKey)) {
Yao Chenb3561512017-11-21 18:07:17 -0800268 return;
269 }
Yao Chenf60e0ba2017-11-29 15:06:41 -0800270 mCurrentSlicedDuration[eventKey] = createDurationTracker(eventKey);
Yao Chen6a8c7992017-11-29 20:02:07 +0000271 }
Yao Chen5154a372017-10-30 22:57:06 -0700272
Yao Chen6a8c7992017-11-29 20:02:07 +0000273 auto it = mCurrentSlicedDuration.find(eventKey);
Yao Chen5154a372017-10-30 22:57:06 -0700274
Yangster-mac20877162017-12-22 17:19:39 -0800275 std::vector<DimensionsValue> values = getDimensionKeys(event, mInternalDimensions);
276 if (values.empty()) {
277 if (matcherIndex == mStartIndex) {
278 it->second->noteStart(DEFAULT_DIMENSION_KEY, condition,
279 event.GetTimestampNs(), conditionKeys);
280 } else if (matcherIndex == mStopIndex) {
281 it->second->noteStop(DEFAULT_DIMENSION_KEY, event.GetTimestampNs(), false);
282 }
283 } else {
284 for (const DimensionsValue& value : values) {
285 if (matcherIndex == mStartIndex) {
286 it->second->noteStart(HashableDimensionKey(value), condition,
287 event.GetTimestampNs(), conditionKeys);
288 } else if (matcherIndex == mStopIndex) {
289 it->second->noteStop(HashableDimensionKey(value), event.GetTimestampNs(), false);
290 }
291 }
Yao Chen5154a372017-10-30 22:57:06 -0700292 }
Yangster-mac20877162017-12-22 17:19:39 -0800293
Yao Chen729093d2017-10-16 10:33:26 -0700294}
295
Yangsterf2bee6f2017-11-29 12:01:05 -0800296size_t DurationMetricProducer::byteSizeLocked() const {
Yangster7c334a12017-11-22 14:24:24 -0800297 size_t totalSize = 0;
298 for (const auto& pair : mPastBuckets) {
299 totalSize += pair.second.size() * kBucketSize;
300 }
301 return totalSize;
yro69007c82017-10-26 20:42:57 -0700302}
303
Yao Chen729093d2017-10-16 10:33:26 -0700304} // namespace statsd
305} // namespace os
306} // namespace android