blob: 5b5b57b61302da64028d1bc41826bffebd2bbe1e [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 */
16
Yao Chen3c0b95c2017-12-16 14:34:20 -080017#define DEBUG false // STOPSHIP if true
Joe Onorato9fc9edf2017-10-15 20:08:52 -070018#include "Log.h"
Yao Chen44cf27c2017-09-14 22:32:50 -070019
Yao Chen729093d2017-10-16 10:33:26 -070020#include "CountMetricProducer.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"
Yangster-mac93694462018-01-22 20:49:31 -080024#include "dimension.h"
Yao Chen44cf27c2017-09-14 22:32:50 -070025
Yao Chen44cf27c2017-09-14 22:32:50 -070026#include <limits.h>
27#include <stdlib.h>
28
yrob0378b02017-11-09 20:36:25 -080029using android::util::FIELD_COUNT_REPEATED;
yro2b0f8862017-11-06 14:27:31 -080030using android::util::FIELD_TYPE_BOOL;
31using android::util::FIELD_TYPE_FLOAT;
32using android::util::FIELD_TYPE_INT32;
33using android::util::FIELD_TYPE_INT64;
34using android::util::FIELD_TYPE_MESSAGE;
Yangster-macd1815dc2017-11-13 21:43:15 -080035using android::util::FIELD_TYPE_STRING;
yro24809bd2017-10-31 23:06:53 -070036using android::util::ProtoOutputStream;
Yao Chen729093d2017-10-16 10:33:26 -070037using std::map;
38using std::string;
Yao Chen44cf27c2017-09-14 22:32:50 -070039using std::unordered_map;
Yao Chen729093d2017-10-16 10:33:26 -070040using std::vector;
Yao Chen44cf27c2017-09-14 22:32:50 -070041
42namespace android {
43namespace os {
44namespace statsd {
45
yro24809bd2017-10-31 23:06:53 -070046// for StatsLogReport
Yangster-mac94e197c2018-01-02 16:03:03 -080047const int FIELD_ID_ID = 1;
yro24809bd2017-10-31 23:06:53 -070048const int FIELD_ID_START_REPORT_NANOS = 2;
49const int FIELD_ID_END_REPORT_NANOS = 3;
50const int FIELD_ID_COUNT_METRICS = 5;
51// for CountMetricDataWrapper
52const int FIELD_ID_DATA = 1;
53// for CountMetricData
Yangster-mac468ff042018-01-17 12:26:34 -080054const int FIELD_ID_DIMENSION_IN_WHAT = 1;
55const int FIELD_ID_DIMENSION_IN_CONDITION = 2;
56const int FIELD_ID_BUCKET_INFO = 3;
yro24809bd2017-10-31 23:06:53 -070057// for CountBucketInfo
58const int FIELD_ID_START_BUCKET_NANOS = 1;
59const int FIELD_ID_END_BUCKET_NANOS = 2;
60const int FIELD_ID_COUNT = 3;
61
Yao Chenb3561512017-11-21 18:07:17 -080062CountMetricProducer::CountMetricProducer(const ConfigKey& key, const CountMetric& metric,
63 const int conditionIndex,
Yao Chen93fe3a32017-11-02 13:52:59 -070064 const sp<ConditionWizard>& wizard,
65 const uint64_t startTimeNs)
Yangster-mac94e197c2018-01-02 16:03:03 -080066 : MetricProducer(metric.id(), key, startTimeNs, conditionIndex, wizard) {
Yao Chen44cf27c2017-09-14 22:32:50 -070067 // TODO: evaluate initial conditions. and set mConditionMet.
Yangster-macb8144812018-01-04 10:56:23 -080068 if (metric.has_bucket()) {
69 mBucketSizeNs = TimeUnitToBucketSizeInMillis(metric.bucket()) * 1000000;
Yao Chen44cf27c2017-09-14 22:32:50 -070070 } else {
Yao Chen729093d2017-10-16 10:33:26 -070071 mBucketSizeNs = LLONG_MAX;
Yao Chen44cf27c2017-09-14 22:32:50 -070072 }
73
Yao Chen729093d2017-10-16 10:33:26 -070074 // TODO: use UidMap if uid->pkg_name is required
Yangster-mac93694462018-01-22 20:49:31 -080075 mDimensionsInWhat = metric.dimensions_in_what();
76 mDimensionsInCondition = metric.dimensions_in_condition();
Yao Chen729093d2017-10-16 10:33:26 -070077
78 if (metric.links().size() > 0) {
79 mConditionLinks.insert(mConditionLinks.begin(), metric.links().begin(),
80 metric.links().end());
Yao Chen729093d2017-10-16 10:33:26 -070081 }
Yangster-mac93694462018-01-22 20:49:31 -080082 mConditionSliced = (metric.links().size() > 0)||
83 (mDimensionsInCondition.has_field() && mDimensionsInCondition.child_size() > 0);
Yao Chen729093d2017-10-16 10:33:26 -070084
Yangster-mac94e197c2018-01-02 16:03:03 -080085 VLOG("metric %lld created. bucket size %lld start_time: %lld", (long long)metric.id(),
Yao Chen729093d2017-10-16 10:33:26 -070086 (long long)mBucketSizeNs, (long long)mStartTimeNs);
Yao Chen44cf27c2017-09-14 22:32:50 -070087}
88
Yao Chen44cf27c2017-09-14 22:32:50 -070089CountMetricProducer::~CountMetricProducer() {
90 VLOG("~CountMetricProducer() called");
91}
92
Yangsterf2bee6f2017-11-29 12:01:05 -080093void CountMetricProducer::onSlicedConditionMayChangeLocked(const uint64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -080094 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Yao Chen729093d2017-10-16 10:33:26 -070095}
96
Yangster-mac20877162017-12-22 17:19:39 -080097void CountMetricProducer::onDumpReportLocked(const uint64_t dumpTimeNs, StatsLogReport* report) {
98 flushIfNeededLocked(dumpTimeNs);
Yangster-mac94e197c2018-01-02 16:03:03 -080099 report->set_metric_id(mMetricId);
Yangster-mac20877162017-12-22 17:19:39 -0800100 report->set_start_report_nanos(mStartTimeNs);
101
102 auto count_metrics = report->mutable_count_metrics();
103 for (const auto& counter : mPastBuckets) {
104 CountMetricData* metricData = count_metrics->add_data();
Yangster-mac93694462018-01-22 20:49:31 -0800105 *metricData->mutable_dimensions_in_what() =
106 counter.first.getDimensionKeyInWhat().getDimensionsValue();
107 *metricData->mutable_dimensions_in_condition() =
108 counter.first.getDimensionKeyInCondition().getDimensionsValue();
Yangster-mac20877162017-12-22 17:19:39 -0800109 for (const auto& bucket : counter.second) {
110 CountBucketInfo* bucketInfo = metricData->add_bucket_info();
111 bucketInfo->set_start_bucket_nanos(bucket.mBucketStartNs);
112 bucketInfo->set_end_bucket_nanos(bucket.mBucketEndNs);
113 bucketInfo->set_count(bucket.mCount);
114 }
115 }
116}
117
Yao Chen288c6002017-12-12 13:43:18 -0800118void CountMetricProducer::onDumpReportLocked(const uint64_t dumpTimeNs,
119 ProtoOutputStream* protoOutput) {
120 flushIfNeededLocked(dumpTimeNs);
Yangster-mac635b4b32018-01-23 20:17:35 -0800121 if (mPastBuckets.empty()) {
122 return;
123 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000124
Yangster-mac94e197c2018-01-02 16:03:03 -0800125 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Yao Chen288c6002017-12-12 13:43:18 -0800126 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_REPORT_NANOS, (long long)mStartTimeNs);
127 long long protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_COUNT_METRICS);
128
Yangster-mac94e197c2018-01-02 16:03:03 -0800129 VLOG("metric %lld dump report now...",(long long)mMetricId);
Yao Chen729093d2017-10-16 10:33:26 -0700130
Yao Chen93fe3a32017-11-02 13:52:59 -0700131 for (const auto& counter : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800132 const MetricDimensionKey& dimensionKey = counter.first;
133 VLOG(" dimension key %s", dimensionKey.c_str());
Yao Chend5aa01b32017-12-19 16:46:36 -0800134
yrob0378b02017-11-09 20:36:25 -0800135 long long wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800136 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
Yao Chen729093d2017-10-16 10:33:26 -0700137
Yangster-mac20877162017-12-22 17:19:39 -0800138 // First fill dimension.
Yangster-mac93694462018-01-22 20:49:31 -0800139 long long dimensionInWhatToken = protoOutput->start(
Yangster-mac468ff042018-01-17 12:26:34 -0800140 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
Yangster-mac93694462018-01-22 20:49:31 -0800141 writeDimensionsValueProtoToStream(
142 dimensionKey.getDimensionKeyInWhat().getDimensionsValue(), protoOutput);
143 protoOutput->end(dimensionInWhatToken);
144
145 if (dimensionKey.hasDimensionKeyInCondition()) {
146 long long dimensionInConditionToken = protoOutput->start(
147 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
148 writeDimensionsValueProtoToStream(
149 dimensionKey.getDimensionKeyInCondition().getDimensionsValue(), protoOutput);
150 protoOutput->end(dimensionInConditionToken);
151 }
yro24809bd2017-10-31 23:06:53 -0700152
153 // Then fill bucket_info (CountBucketInfo).
Yao Chen93fe3a32017-11-02 13:52:59 -0700154 for (const auto& bucket : counter.second) {
Yao Chen288c6002017-12-12 13:43:18 -0800155 long long bucketInfoToken = protoOutput->start(
156 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
157 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_NANOS,
158 (long long)bucket.mBucketStartNs);
159 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_NANOS,
160 (long long)bucket.mBucketEndNs);
161 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_COUNT, (long long)bucket.mCount);
162 protoOutput->end(bucketInfoToken);
Yao Chen93fe3a32017-11-02 13:52:59 -0700163 VLOG("\t bucket [%lld - %lld] count: %lld", (long long)bucket.mBucketStartNs,
164 (long long)bucket.mBucketEndNs, (long long)bucket.mCount);
yro24809bd2017-10-31 23:06:53 -0700165 }
Yao Chen288c6002017-12-12 13:43:18 -0800166 protoOutput->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700167 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000168
Yao Chen288c6002017-12-12 13:43:18 -0800169 protoOutput->end(protoToken);
170 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_REPORT_NANOS, (long long)dumpTimeNs);
yro24809bd2017-10-31 23:06:53 -0700171
Yao Chen6a8c7992017-11-29 20:02:07 +0000172 mPastBuckets.clear();
Yao Chen6a8c7992017-11-29 20:02:07 +0000173
174 // TODO: Clear mDimensionKeyMap once the report is dumped.
Yao Chen44cf27c2017-09-14 22:32:50 -0700175}
176
Yangsterf2bee6f2017-11-29 12:01:05 -0800177void CountMetricProducer::onConditionChangedLocked(const bool conditionMet,
178 const uint64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800179 VLOG("Metric %lld onConditionChanged", (long long)mMetricId);
Yao Chencaf339d2017-10-06 16:01:10 -0700180 mCondition = conditionMet;
181}
182
Yangster-mac93694462018-01-22 20:49:31 -0800183bool CountMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800184 if (mCurrentSlicedCounter->find(newKey) != mCurrentSlicedCounter->end()) {
185 return false;
186 }
187 // ===========GuardRail==============
188 // 1. Report the tuple count if the tuple count > soft limit
189 if (mCurrentSlicedCounter->size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
190 size_t newTupleCount = mCurrentSlicedCounter->size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800191 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800192 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
193 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800194 ALOGE("CountMetric %lld dropping data for dimension key %s",
195 (long long)mMetricId, newKey.c_str());
Yao Chenb3561512017-11-21 18:07:17 -0800196 return true;
197 }
198 }
199
200 return false;
201}
Yangsterf2bee6f2017-11-29 12:01:05 -0800202
203void CountMetricProducer::onMatchedLogEventInternalLocked(
Yangster-mac93694462018-01-22 20:49:31 -0800204 const size_t matcherIndex, const MetricDimensionKey& eventKey,
Yangster-mac20877162017-12-22 17:19:39 -0800205 const ConditionKey& conditionKey, bool condition,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800206 const LogEvent& event) {
Yao Chen729093d2017-10-16 10:33:26 -0700207 uint64_t eventTimeNs = event.GetTimestampNs();
Yao Chen44cf27c2017-09-14 22:32:50 -0700208
Yangsterf2bee6f2017-11-29 12:01:05 -0800209 flushIfNeededLocked(eventTimeNs);
Yao Chen729093d2017-10-16 10:33:26 -0700210
Yao Chen6a8c7992017-11-29 20:02:07 +0000211 if (condition == false) {
Yao Chenb7041772017-10-20 16:59:25 -0700212 return;
Yao Chen44cf27c2017-09-14 22:32:50 -0700213 }
Yao Chen729093d2017-10-16 10:33:26 -0700214
Yao Chen6a8c7992017-11-29 20:02:07 +0000215 auto it = mCurrentSlicedCounter->find(eventKey);
Yao Chen6a8c7992017-11-29 20:02:07 +0000216 if (it == mCurrentSlicedCounter->end()) {
217 // ===========GuardRail==============
Yangsterf2bee6f2017-11-29 12:01:05 -0800218 if (hitGuardRailLocked(eventKey)) {
Yao Chenb3561512017-11-21 18:07:17 -0800219 return;
220 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000221 // create a counter for the new key
222 (*mCurrentSlicedCounter)[eventKey] = 1;
223 } else {
224 // increment the existing value
225 auto& count = it->second;
226 count++;
Yao Chen729093d2017-10-16 10:33:26 -0700227 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000228 for (auto& tracker : mAnomalyTrackers) {
David Chen27785a82018-01-19 17:06:45 -0800229 int64_t countWholeBucket = mCurrentSlicedCounter->find(eventKey)->second;
230 auto prev = mCurrentFullCounters->find(eventKey);
231 if (prev != mCurrentFullCounters->end()) {
232 countWholeBucket += prev->second;
233 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000234 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, eventKey,
David Chen27785a82018-01-19 17:06:45 -0800235 countWholeBucket);
Yao Chen6a8c7992017-11-29 20:02:07 +0000236 }
237
Yangster-mac94e197c2018-01-02 16:03:03 -0800238 VLOG("metric %lld %s->%lld", (long long)mMetricId, eventKey.c_str(),
Yao Chen6a8c7992017-11-29 20:02:07 +0000239 (long long)(*mCurrentSlicedCounter)[eventKey]);
Yao Chen44cf27c2017-09-14 22:32:50 -0700240}
241
Yao Chen729093d2017-10-16 10:33:26 -0700242// When a new matched event comes in, we check if event falls into the current
243// bucket. If not, flush the old counter to past buckets and initialize the new bucket.
Yangsterf2bee6f2017-11-29 12:01:05 -0800244void CountMetricProducer::flushIfNeededLocked(const uint64_t& eventTimeNs) {
David Chen27785a82018-01-19 17:06:45 -0800245 uint64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
246 if (eventTimeNs < currentBucketEndTimeNs) {
Yao Chen44cf27c2017-09-14 22:32:50 -0700247 return;
248 }
249
David Chen27785a82018-01-19 17:06:45 -0800250 flushCurrentBucketLocked(eventTimeNs);
251 // Setup the bucket start time and number.
252 uint64_t numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
253 mCurrentBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
254 mCurrentBucketNum += numBucketsForward;
255 VLOG("metric %lld: new bucket start time: %lld", (long long)mMetricId,
256 (long long)mCurrentBucketStartTimeNs);
257}
258
259void CountMetricProducer::flushCurrentBucketLocked(const uint64_t& eventTimeNs) {
260 uint64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
Yao Chen93fe3a32017-11-02 13:52:59 -0700261 CountBucket info;
262 info.mBucketStartNs = mCurrentBucketStartTimeNs;
David Chen27785a82018-01-19 17:06:45 -0800263 if (eventTimeNs < fullBucketEndTimeNs) {
264 info.mBucketEndNs = eventTimeNs;
265 } else {
266 info.mBucketEndNs = fullBucketEndTimeNs;
267 }
Yangster-mace2cd6d52017-11-09 20:38:30 -0800268 info.mBucketNum = mCurrentBucketNum;
Yang Lu3eba6212017-10-25 19:54:45 -0700269 for (const auto& counter : *mCurrentSlicedCounter) {
Yao Chen93fe3a32017-11-02 13:52:59 -0700270 info.mCount = counter.second;
271 auto& bucketList = mPastBuckets[counter.first];
272 bucketList.push_back(info);
David Chen27785a82018-01-19 17:06:45 -0800273 VLOG("metric %lld, dump key value: %s -> %lld", (long long)mMetricId, counter.first.c_str(),
274 (long long)counter.second);
Yao Chen729093d2017-10-16 10:33:26 -0700275 }
276
David Chen27785a82018-01-19 17:06:45 -0800277 // If we have finished a full bucket, then send this to anomaly tracker.
278 if (eventTimeNs > fullBucketEndTimeNs) {
279 // Accumulate partial buckets with current value and then send to anomaly tracker.
280 if (mCurrentFullCounters->size() > 0) {
281 for (const auto& keyValuePair : *mCurrentSlicedCounter) {
282 (*mCurrentFullCounters)[keyValuePair.first] += keyValuePair.second;
283 }
284 for (auto& tracker : mAnomalyTrackers) {
285 tracker->addPastBucket(mCurrentFullCounters, mCurrentBucketNum);
286 }
287 mCurrentFullCounters = std::make_shared<DimToValMap>();
288 } else {
289 // Skip aggregating the partial buckets since there's no previous partial bucket.
290 for (auto& tracker : mAnomalyTrackers) {
291 tracker->addPastBucket(mCurrentSlicedCounter, mCurrentBucketNum);
292 }
293 }
294 } else {
295 // Accumulate partial bucket.
296 for (const auto& keyValuePair : *mCurrentSlicedCounter) {
297 (*mCurrentFullCounters)[keyValuePair.first] += keyValuePair.second;
298 }
Yang Lu3eba6212017-10-25 19:54:45 -0700299 }
Bookatzd3606c72017-10-19 10:13:49 -0700300
David Chen27785a82018-01-19 17:06:45 -0800301 // Only resets the counters, but doesn't setup the times nor numbers.
302 // (Do not clear since the old one is still referenced in mAnomalyTrackers).
Yang Lu3eba6212017-10-25 19:54:45 -0700303 mCurrentSlicedCounter = std::make_shared<DimToValMap>();
Yao Chen44cf27c2017-09-14 22:32:50 -0700304}
305
yro24809bd2017-10-31 23:06:53 -0700306// Rough estimate of CountMetricProducer buffer stored. This number will be
307// greater than actual data size as it contains each dimension of
308// CountMetricData is duplicated.
Yangsterf2bee6f2017-11-29 12:01:05 -0800309size_t CountMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800310 size_t totalSize = 0;
311 for (const auto& pair : mPastBuckets) {
312 totalSize += pair.second.size() * kBucketSize;
313 }
314 return totalSize;
yro69007c82017-10-26 20:42:57 -0700315}
316
Yao Chen44cf27c2017-09-14 22:32:50 -0700317} // namespace statsd
318} // namespace os
yro69007c82017-10-26 20:42:57 -0700319} // namespace android