blob: bd2674b86a469ef225a35c1585e6de9f81466f6f [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"
Yao Chen44cf27c2017-09-14 22:32:50 -070024
Yao Chen44cf27c2017-09-14 22:32:50 -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;
yro24809bd2017-10-31 23:06:53 -070035using android::util::ProtoOutputStream;
Yao Chen729093d2017-10-16 10:33:26 -070036using std::map;
37using std::string;
Yao Chen44cf27c2017-09-14 22:32:50 -070038using std::unordered_map;
Yao Chen729093d2017-10-16 10:33:26 -070039using std::vector;
Yao Chen44cf27c2017-09-14 22:32:50 -070040
41namespace android {
42namespace os {
43namespace statsd {
44
yro24809bd2017-10-31 23:06:53 -070045// for StatsLogReport
Yangster-mac94e197c2018-01-02 16:03:03 -080046const int FIELD_ID_ID = 1;
yro24809bd2017-10-31 23:06:53 -070047const int FIELD_ID_COUNT_METRICS = 5;
48// for CountMetricDataWrapper
49const int FIELD_ID_DATA = 1;
50// for CountMetricData
Yangster-mac468ff042018-01-17 12:26:34 -080051const int FIELD_ID_DIMENSION_IN_WHAT = 1;
52const int FIELD_ID_DIMENSION_IN_CONDITION = 2;
53const int FIELD_ID_BUCKET_INFO = 3;
yro24809bd2017-10-31 23:06:53 -070054// for CountBucketInfo
55const int FIELD_ID_START_BUCKET_NANOS = 1;
56const int FIELD_ID_END_BUCKET_NANOS = 2;
57const int FIELD_ID_COUNT = 3;
58
Yao Chenb3561512017-11-21 18:07:17 -080059CountMetricProducer::CountMetricProducer(const ConfigKey& key, const CountMetric& metric,
60 const int conditionIndex,
Yao Chen93fe3a32017-11-02 13:52:59 -070061 const sp<ConditionWizard>& wizard,
62 const uint64_t startTimeNs)
Yangster-mac94e197c2018-01-02 16:03:03 -080063 : MetricProducer(metric.id(), key, startTimeNs, conditionIndex, wizard) {
Yao Chen44cf27c2017-09-14 22:32:50 -070064 // TODO: evaluate initial conditions. and set mConditionMet.
Yangster-macb8144812018-01-04 10:56:23 -080065 if (metric.has_bucket()) {
66 mBucketSizeNs = TimeUnitToBucketSizeInMillis(metric.bucket()) * 1000000;
Yao Chen44cf27c2017-09-14 22:32:50 -070067 } else {
Yao Chen729093d2017-10-16 10:33:26 -070068 mBucketSizeNs = LLONG_MAX;
Yao Chen44cf27c2017-09-14 22:32:50 -070069 }
70
Yao Chen8a8d16c2018-02-08 14:50:40 -080071 if (metric.has_dimensions_in_what()) {
72 translateFieldMatcher(metric.dimensions_in_what(), &mDimensionsInWhat);
73 }
74
75 if (metric.has_dimensions_in_condition()) {
76 translateFieldMatcher(metric.dimensions_in_condition(), &mDimensionsInCondition);
77 }
Yao Chen729093d2017-10-16 10:33:26 -070078
79 if (metric.links().size() > 0) {
Yao Chen8a8d16c2018-02-08 14:50:40 -080080 for (const auto& link : metric.links()) {
81 Metric2Condition mc;
82 mc.conditionId = link.condition();
83 translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
84 translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
85 mMetric2ConditionLinks.push_back(mc);
86 }
87 mConditionSliced = true;
Yao Chen729093d2017-10-16 10:33:26 -070088 }
Yao Chen8a8d16c2018-02-08 14:50:40 -080089
90 mConditionSliced = (metric.links().size() > 0) || (mDimensionsInCondition.size() > 0);
Yao Chen729093d2017-10-16 10:33:26 -070091
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);
Yao Chen44cf27c2017-09-14 22:32:50 -070094}
95
Yao Chen44cf27c2017-09-14 22:32:50 -070096CountMetricProducer::~CountMetricProducer() {
97 VLOG("~CountMetricProducer() called");
98}
99
Yangsterf2bee6f2017-11-29 12:01:05 -0800100void CountMetricProducer::onSlicedConditionMayChangeLocked(const uint64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800101 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Yao Chen729093d2017-10-16 10:33:26 -0700102}
103
Yao Chen288c6002017-12-12 13:43:18 -0800104void CountMetricProducer::onDumpReportLocked(const uint64_t dumpTimeNs,
105 ProtoOutputStream* protoOutput) {
106 flushIfNeededLocked(dumpTimeNs);
Yangster-mac635b4b32018-01-23 20:17:35 -0800107 if (mPastBuckets.empty()) {
108 return;
109 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000110
Yangster-mac94e197c2018-01-02 16:03:03 -0800111 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Yao Chen288c6002017-12-12 13:43:18 -0800112 long long protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_COUNT_METRICS);
113
Yao Chen93fe3a32017-11-02 13:52:59 -0700114 for (const auto& counter : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800115 const MetricDimensionKey& dimensionKey = counter.first;
116 VLOG(" dimension key %s", dimensionKey.c_str());
Yao Chend5aa01b32017-12-19 16:46:36 -0800117
yrob0378b02017-11-09 20:36:25 -0800118 long long wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800119 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
Yao Chen729093d2017-10-16 10:33:26 -0700120
Yangster-mac20877162017-12-22 17:19:39 -0800121 // First fill dimension.
Yangster-mac93694462018-01-22 20:49:31 -0800122 long long dimensionInWhatToken = protoOutput->start(
Yangster-mac468ff042018-01-17 12:26:34 -0800123 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
Yao Chen8a8d16c2018-02-08 14:50:40 -0800124 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), protoOutput);
Yangster-mac93694462018-01-22 20:49:31 -0800125 protoOutput->end(dimensionInWhatToken);
126
127 if (dimensionKey.hasDimensionKeyInCondition()) {
128 long long dimensionInConditionToken = protoOutput->start(
129 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
Yao Chen8a8d16c2018-02-08 14:50:40 -0800130 writeDimensionToProto(dimensionKey.getDimensionKeyInCondition(), protoOutput);
Yangster-mac93694462018-01-22 20:49:31 -0800131 protoOutput->end(dimensionInConditionToken);
132 }
yro24809bd2017-10-31 23:06:53 -0700133
134 // Then fill bucket_info (CountBucketInfo).
Yao Chen93fe3a32017-11-02 13:52:59 -0700135 for (const auto& bucket : counter.second) {
Yao Chen288c6002017-12-12 13:43:18 -0800136 long long bucketInfoToken = protoOutput->start(
137 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
138 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_NANOS,
139 (long long)bucket.mBucketStartNs);
140 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_NANOS,
141 (long long)bucket.mBucketEndNs);
142 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_COUNT, (long long)bucket.mCount);
143 protoOutput->end(bucketInfoToken);
Yao Chen93fe3a32017-11-02 13:52:59 -0700144 VLOG("\t bucket [%lld - %lld] count: %lld", (long long)bucket.mBucketStartNs,
145 (long long)bucket.mBucketEndNs, (long long)bucket.mCount);
yro24809bd2017-10-31 23:06:53 -0700146 }
Yao Chen288c6002017-12-12 13:43:18 -0800147 protoOutput->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700148 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000149
Yao Chen288c6002017-12-12 13:43:18 -0800150 protoOutput->end(protoToken);
yro24809bd2017-10-31 23:06:53 -0700151
Yao Chen6a8c7992017-11-29 20:02:07 +0000152 mPastBuckets.clear();
Yao Chen6a8c7992017-11-29 20:02:07 +0000153
154 // TODO: Clear mDimensionKeyMap once the report is dumped.
Yao Chen44cf27c2017-09-14 22:32:50 -0700155}
156
Yangsterf2bee6f2017-11-29 12:01:05 -0800157void CountMetricProducer::onConditionChangedLocked(const bool conditionMet,
158 const uint64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800159 VLOG("Metric %lld onConditionChanged", (long long)mMetricId);
Yao Chencaf339d2017-10-06 16:01:10 -0700160 mCondition = conditionMet;
161}
162
Yangster-mac93694462018-01-22 20:49:31 -0800163bool CountMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800164 if (mCurrentSlicedCounter->find(newKey) != mCurrentSlicedCounter->end()) {
165 return false;
166 }
167 // ===========GuardRail==============
168 // 1. Report the tuple count if the tuple count > soft limit
169 if (mCurrentSlicedCounter->size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
170 size_t newTupleCount = mCurrentSlicedCounter->size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800171 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800172 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
173 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800174 ALOGE("CountMetric %lld dropping data for dimension key %s",
175 (long long)mMetricId, newKey.c_str());
Yao Chenb3561512017-11-21 18:07:17 -0800176 return true;
177 }
178 }
179
180 return false;
181}
Yangsterf2bee6f2017-11-29 12:01:05 -0800182
183void CountMetricProducer::onMatchedLogEventInternalLocked(
Yangster-mac93694462018-01-22 20:49:31 -0800184 const size_t matcherIndex, const MetricDimensionKey& eventKey,
Yangster-mac20877162017-12-22 17:19:39 -0800185 const ConditionKey& conditionKey, bool condition,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800186 const LogEvent& event) {
Yao Chen729093d2017-10-16 10:33:26 -0700187 uint64_t eventTimeNs = event.GetTimestampNs();
Yangsterf2bee6f2017-11-29 12:01:05 -0800188 flushIfNeededLocked(eventTimeNs);
Yao Chen729093d2017-10-16 10:33:26 -0700189
Yao Chen6a8c7992017-11-29 20:02:07 +0000190 if (condition == false) {
Yao Chenb7041772017-10-20 16:59:25 -0700191 return;
Yao Chen44cf27c2017-09-14 22:32:50 -0700192 }
Yao Chen729093d2017-10-16 10:33:26 -0700193
Yao Chen6a8c7992017-11-29 20:02:07 +0000194 auto it = mCurrentSlicedCounter->find(eventKey);
Yao Chen6a8c7992017-11-29 20:02:07 +0000195 if (it == mCurrentSlicedCounter->end()) {
196 // ===========GuardRail==============
Yangsterf2bee6f2017-11-29 12:01:05 -0800197 if (hitGuardRailLocked(eventKey)) {
Yao Chenb3561512017-11-21 18:07:17 -0800198 return;
199 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000200 // create a counter for the new key
201 (*mCurrentSlicedCounter)[eventKey] = 1;
202 } else {
203 // increment the existing value
204 auto& count = it->second;
205 count++;
Yao Chen729093d2017-10-16 10:33:26 -0700206 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000207 for (auto& tracker : mAnomalyTrackers) {
David Chen27785a82018-01-19 17:06:45 -0800208 int64_t countWholeBucket = mCurrentSlicedCounter->find(eventKey)->second;
209 auto prev = mCurrentFullCounters->find(eventKey);
210 if (prev != mCurrentFullCounters->end()) {
211 countWholeBucket += prev->second;
212 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000213 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, eventKey,
David Chen27785a82018-01-19 17:06:45 -0800214 countWholeBucket);
Yao Chen6a8c7992017-11-29 20:02:07 +0000215 }
216
Yangster-mac94e197c2018-01-02 16:03:03 -0800217 VLOG("metric %lld %s->%lld", (long long)mMetricId, eventKey.c_str(),
Yao Chen6a8c7992017-11-29 20:02:07 +0000218 (long long)(*mCurrentSlicedCounter)[eventKey]);
Yao Chen44cf27c2017-09-14 22:32:50 -0700219}
220
Yao Chen729093d2017-10-16 10:33:26 -0700221// When a new matched event comes in, we check if event falls into the current
222// bucket. If not, flush the old counter to past buckets and initialize the new bucket.
Yangsterf2bee6f2017-11-29 12:01:05 -0800223void CountMetricProducer::flushIfNeededLocked(const uint64_t& eventTimeNs) {
David Chen27785a82018-01-19 17:06:45 -0800224 uint64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
225 if (eventTimeNs < currentBucketEndTimeNs) {
Yao Chen44cf27c2017-09-14 22:32:50 -0700226 return;
227 }
228
David Chen27785a82018-01-19 17:06:45 -0800229 flushCurrentBucketLocked(eventTimeNs);
230 // Setup the bucket start time and number.
231 uint64_t numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
232 mCurrentBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
233 mCurrentBucketNum += numBucketsForward;
234 VLOG("metric %lld: new bucket start time: %lld", (long long)mMetricId,
235 (long long)mCurrentBucketStartTimeNs);
236}
237
238void CountMetricProducer::flushCurrentBucketLocked(const uint64_t& eventTimeNs) {
239 uint64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
Yao Chen93fe3a32017-11-02 13:52:59 -0700240 CountBucket info;
241 info.mBucketStartNs = mCurrentBucketStartTimeNs;
David Chen27785a82018-01-19 17:06:45 -0800242 if (eventTimeNs < fullBucketEndTimeNs) {
243 info.mBucketEndNs = eventTimeNs;
244 } else {
245 info.mBucketEndNs = fullBucketEndTimeNs;
246 }
Yangster-mace2cd6d52017-11-09 20:38:30 -0800247 info.mBucketNum = mCurrentBucketNum;
Yang Lu3eba6212017-10-25 19:54:45 -0700248 for (const auto& counter : *mCurrentSlicedCounter) {
Yao Chen93fe3a32017-11-02 13:52:59 -0700249 info.mCount = counter.second;
250 auto& bucketList = mPastBuckets[counter.first];
251 bucketList.push_back(info);
David Chen27785a82018-01-19 17:06:45 -0800252 VLOG("metric %lld, dump key value: %s -> %lld", (long long)mMetricId, counter.first.c_str(),
253 (long long)counter.second);
Yao Chen729093d2017-10-16 10:33:26 -0700254 }
255
David Chen27785a82018-01-19 17:06:45 -0800256 // If we have finished a full bucket, then send this to anomaly tracker.
257 if (eventTimeNs > fullBucketEndTimeNs) {
258 // Accumulate partial buckets with current value and then send to anomaly tracker.
259 if (mCurrentFullCounters->size() > 0) {
260 for (const auto& keyValuePair : *mCurrentSlicedCounter) {
261 (*mCurrentFullCounters)[keyValuePair.first] += keyValuePair.second;
262 }
263 for (auto& tracker : mAnomalyTrackers) {
264 tracker->addPastBucket(mCurrentFullCounters, mCurrentBucketNum);
265 }
266 mCurrentFullCounters = std::make_shared<DimToValMap>();
267 } else {
268 // Skip aggregating the partial buckets since there's no previous partial bucket.
269 for (auto& tracker : mAnomalyTrackers) {
270 tracker->addPastBucket(mCurrentSlicedCounter, mCurrentBucketNum);
271 }
272 }
273 } else {
274 // Accumulate partial bucket.
275 for (const auto& keyValuePair : *mCurrentSlicedCounter) {
276 (*mCurrentFullCounters)[keyValuePair.first] += keyValuePair.second;
277 }
Yang Lu3eba6212017-10-25 19:54:45 -0700278 }
Bookatzd3606c72017-10-19 10:13:49 -0700279
David Chen27785a82018-01-19 17:06:45 -0800280 // Only resets the counters, but doesn't setup the times nor numbers.
281 // (Do not clear since the old one is still referenced in mAnomalyTrackers).
Yang Lu3eba6212017-10-25 19:54:45 -0700282 mCurrentSlicedCounter = std::make_shared<DimToValMap>();
Yao Chen44cf27c2017-09-14 22:32:50 -0700283}
284
yro24809bd2017-10-31 23:06:53 -0700285// Rough estimate of CountMetricProducer buffer stored. This number will be
286// greater than actual data size as it contains each dimension of
287// CountMetricData is duplicated.
Yangsterf2bee6f2017-11-29 12:01:05 -0800288size_t CountMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800289 size_t totalSize = 0;
290 for (const auto& pair : mPastBuckets) {
291 totalSize += pair.second.size() * kBucketSize;
292 }
293 return totalSize;
yro69007c82017-10-26 20:42:57 -0700294}
295
Yao Chen44cf27c2017-09-14 22:32:50 -0700296} // namespace statsd
297} // namespace os
yro69007c82017-10-26 20:42:57 -0700298} // namespace android