blob: c77e07b7698cfc8557ce568bc34ab075b63f5e7b [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
Yangster-mac330af582018-02-08 15:24:38 -080055const int FIELD_ID_START_BUCKET_ELAPSED_NANOS = 1;
56const int FIELD_ID_END_BUCKET_ELAPSED_NANOS = 2;
yro24809bd2017-10-31 23:06:53 -070057const 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,
Yangster-macb142cc82018-03-30 15:22:08 -070062 const int64_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()) {
yro59cc24d2018-02-13 20:17:32 -080066 mBucketSizeNs =
67 TimeUnitToBucketSizeInMillisGuardrailed(key.GetUid(), metric.bucket()) * 1000000;
Yao Chen44cf27c2017-09-14 22:32:50 -070068 } else {
Yao Chen729093d2017-10-16 10:33:26 -070069 mBucketSizeNs = LLONG_MAX;
Yao Chen44cf27c2017-09-14 22:32:50 -070070 }
71
Yao Chen8a8d16c2018-02-08 14:50:40 -080072 if (metric.has_dimensions_in_what()) {
73 translateFieldMatcher(metric.dimensions_in_what(), &mDimensionsInWhat);
Yangster13fb7e42018-03-07 17:30:49 -080074 mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
Yao Chen8a8d16c2018-02-08 14:50:40 -080075 }
76
77 if (metric.has_dimensions_in_condition()) {
78 translateFieldMatcher(metric.dimensions_in_condition(), &mDimensionsInCondition);
79 }
Yao Chen729093d2017-10-16 10:33:26 -070080
81 if (metric.links().size() > 0) {
Yao Chen8a8d16c2018-02-08 14:50:40 -080082 for (const auto& link : metric.links()) {
83 Metric2Condition mc;
84 mc.conditionId = link.condition();
85 translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
86 translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
87 mMetric2ConditionLinks.push_back(mc);
88 }
89 mConditionSliced = true;
Yao Chen729093d2017-10-16 10:33:26 -070090 }
Yao Chen8a8d16c2018-02-08 14:50:40 -080091
92 mConditionSliced = (metric.links().size() > 0) || (mDimensionsInCondition.size() > 0);
Yao Chen729093d2017-10-16 10:33:26 -070093
Yangster-mac94e197c2018-01-02 16:03:03 -080094 VLOG("metric %lld created. bucket size %lld start_time: %lld", (long long)metric.id(),
Yao Chen729093d2017-10-16 10:33:26 -070095 (long long)mBucketSizeNs, (long long)mStartTimeNs);
Yao Chen44cf27c2017-09-14 22:32:50 -070096}
97
Yao Chen44cf27c2017-09-14 22:32:50 -070098CountMetricProducer::~CountMetricProducer() {
99 VLOG("~CountMetricProducer() called");
100}
101
Yangster-maca78d0082018-03-12 12:02:56 -0700102void CountMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
103 if (mCurrentSlicedCounter == nullptr ||
104 mCurrentSlicedCounter->size() == 0) {
105 return;
106 }
107
108 fprintf(out, "CountMetric %lld dimension size %lu\n", (long long)mMetricId,
109 (unsigned long)mCurrentSlicedCounter->size());
110 if (verbose) {
111 for (const auto& it : *mCurrentSlicedCounter) {
112 fprintf(out, "\t(what)%s\t(condition)%s %lld\n",
113 it.first.getDimensionKeyInWhat().toString().c_str(),
114 it.first.getDimensionKeyInCondition().toString().c_str(),
115 (unsigned long long)it.second);
116 }
117 }
118}
119
Yao Chen427d3722018-03-22 15:21:52 -0700120void CountMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
Yangster-macb142cc82018-03-30 15:22:08 -0700121 const int64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800122 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Yao Chen729093d2017-10-16 10:33:26 -0700123}
124
Yangster-macb142cc82018-03-30 15:22:08 -0700125void CountMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700126 const bool include_current_partial_bucket,
Yao Chen288c6002017-12-12 13:43:18 -0800127 ProtoOutputStream* protoOutput) {
Yangster-mace68f3a52018-04-04 00:01:43 -0700128 if (include_current_partial_bucket) {
129 flushLocked(dumpTimeNs);
130 } else {
131 flushIfNeededLocked(dumpTimeNs);
132 }
Yangster-mac635b4b32018-01-23 20:17:35 -0800133 if (mPastBuckets.empty()) {
134 return;
135 }
Yangster-mac94e197c2018-01-02 16:03:03 -0800136 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Yi Jin5ee07872018-03-05 18:18:27 -0800137 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_COUNT_METRICS);
Yao Chen288c6002017-12-12 13:43:18 -0800138
Yao Chen93fe3a32017-11-02 13:52:59 -0700139 for (const auto& counter : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800140 const MetricDimensionKey& dimensionKey = counter.first;
Yangster13fb7e42018-03-07 17:30:49 -0800141 VLOG(" dimension key %s", dimensionKey.toString().c_str());
Yao Chend5aa01b32017-12-19 16:46:36 -0800142
Yi Jin5ee07872018-03-05 18:18:27 -0800143 uint64_t wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800144 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
Yao Chen729093d2017-10-16 10:33:26 -0700145
Yangster-mac20877162017-12-22 17:19:39 -0800146 // First fill dimension.
Yi Jin5ee07872018-03-05 18:18:27 -0800147 uint64_t dimensionInWhatToken = protoOutput->start(
Yangster-mac468ff042018-01-17 12:26:34 -0800148 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
Yao Chen8a8d16c2018-02-08 14:50:40 -0800149 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), protoOutput);
Yangster-mac93694462018-01-22 20:49:31 -0800150 protoOutput->end(dimensionInWhatToken);
151
152 if (dimensionKey.hasDimensionKeyInCondition()) {
Yi Jin5ee07872018-03-05 18:18:27 -0800153 uint64_t dimensionInConditionToken = protoOutput->start(
Yangster-mac93694462018-01-22 20:49:31 -0800154 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
Yao Chen8a8d16c2018-02-08 14:50:40 -0800155 writeDimensionToProto(dimensionKey.getDimensionKeyInCondition(), protoOutput);
Yangster-mac93694462018-01-22 20:49:31 -0800156 protoOutput->end(dimensionInConditionToken);
157 }
yro24809bd2017-10-31 23:06:53 -0700158
159 // Then fill bucket_info (CountBucketInfo).
Yangster-mac330af582018-02-08 15:24:38 -0800160
Yao Chen93fe3a32017-11-02 13:52:59 -0700161 for (const auto& bucket : counter.second) {
Yi Jin5ee07872018-03-05 18:18:27 -0800162 uint64_t bucketInfoToken = protoOutput->start(
Yao Chen288c6002017-12-12 13:43:18 -0800163 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
Yangster-mac330af582018-02-08 15:24:38 -0800164 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_NANOS,
Yao Chen288c6002017-12-12 13:43:18 -0800165 (long long)bucket.mBucketStartNs);
Yangster-mac330af582018-02-08 15:24:38 -0800166 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_NANOS,
Yao Chen288c6002017-12-12 13:43:18 -0800167 (long long)bucket.mBucketEndNs);
168 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_COUNT, (long long)bucket.mCount);
169 protoOutput->end(bucketInfoToken);
Yao Chen93fe3a32017-11-02 13:52:59 -0700170 VLOG("\t bucket [%lld - %lld] count: %lld", (long long)bucket.mBucketStartNs,
171 (long long)bucket.mBucketEndNs, (long long)bucket.mCount);
yro24809bd2017-10-31 23:06:53 -0700172 }
Yao Chen288c6002017-12-12 13:43:18 -0800173 protoOutput->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700174 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000175
Yao Chen288c6002017-12-12 13:43:18 -0800176 protoOutput->end(protoToken);
yro24809bd2017-10-31 23:06:53 -0700177
Yao Chen6a8c7992017-11-29 20:02:07 +0000178 mPastBuckets.clear();
Yao Chen06dba5d2018-01-26 13:38:16 -0800179}
Yao Chen6a8c7992017-11-29 20:02:07 +0000180
Yangster-macb142cc82018-03-30 15:22:08 -0700181void CountMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
Yao Chen06dba5d2018-01-26 13:38:16 -0800182 flushIfNeededLocked(dropTimeNs);
183 mPastBuckets.clear();
Yao Chen44cf27c2017-09-14 22:32:50 -0700184}
185
Yangsterf2bee6f2017-11-29 12:01:05 -0800186void CountMetricProducer::onConditionChangedLocked(const bool conditionMet,
Yangster-macb142cc82018-03-30 15:22:08 -0700187 const int64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800188 VLOG("Metric %lld onConditionChanged", (long long)mMetricId);
Yao Chencaf339d2017-10-06 16:01:10 -0700189 mCondition = conditionMet;
190}
191
Yangster-mac93694462018-01-22 20:49:31 -0800192bool CountMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800193 if (mCurrentSlicedCounter->find(newKey) != mCurrentSlicedCounter->end()) {
194 return false;
195 }
196 // ===========GuardRail==============
197 // 1. Report the tuple count if the tuple count > soft limit
198 if (mCurrentSlicedCounter->size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
199 size_t newTupleCount = mCurrentSlicedCounter->size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800200 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800201 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
202 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800203 ALOGE("CountMetric %lld dropping data for dimension key %s",
Yangster13fb7e42018-03-07 17:30:49 -0800204 (long long)mMetricId, newKey.toString().c_str());
Yao Chenb3561512017-11-21 18:07:17 -0800205 return true;
206 }
207 }
208
209 return false;
210}
Yangsterf2bee6f2017-11-29 12:01:05 -0800211
212void CountMetricProducer::onMatchedLogEventInternalLocked(
Yangster-mac93694462018-01-22 20:49:31 -0800213 const size_t matcherIndex, const MetricDimensionKey& eventKey,
Yangster-mac20877162017-12-22 17:19:39 -0800214 const ConditionKey& conditionKey, bool condition,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800215 const LogEvent& event) {
Yangster-macb142cc82018-03-30 15:22:08 -0700216 int64_t eventTimeNs = event.GetElapsedTimestampNs();
Yangsterf2bee6f2017-11-29 12:01:05 -0800217 flushIfNeededLocked(eventTimeNs);
Yao Chen729093d2017-10-16 10:33:26 -0700218
Yao Chen6a8c7992017-11-29 20:02:07 +0000219 if (condition == false) {
Yao Chenb7041772017-10-20 16:59:25 -0700220 return;
Yao Chen44cf27c2017-09-14 22:32:50 -0700221 }
Yao Chen729093d2017-10-16 10:33:26 -0700222
Yao Chen6a8c7992017-11-29 20:02:07 +0000223 auto it = mCurrentSlicedCounter->find(eventKey);
Yao Chen6a8c7992017-11-29 20:02:07 +0000224 if (it == mCurrentSlicedCounter->end()) {
225 // ===========GuardRail==============
Yangsterf2bee6f2017-11-29 12:01:05 -0800226 if (hitGuardRailLocked(eventKey)) {
Yao Chenb3561512017-11-21 18:07:17 -0800227 return;
228 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000229 // create a counter for the new key
230 (*mCurrentSlicedCounter)[eventKey] = 1;
231 } else {
232 // increment the existing value
233 auto& count = it->second;
234 count++;
Yao Chen729093d2017-10-16 10:33:26 -0700235 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000236 for (auto& tracker : mAnomalyTrackers) {
David Chen27785a82018-01-19 17:06:45 -0800237 int64_t countWholeBucket = mCurrentSlicedCounter->find(eventKey)->second;
238 auto prev = mCurrentFullCounters->find(eventKey);
239 if (prev != mCurrentFullCounters->end()) {
240 countWholeBucket += prev->second;
241 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000242 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, eventKey,
David Chen27785a82018-01-19 17:06:45 -0800243 countWholeBucket);
Yao Chen6a8c7992017-11-29 20:02:07 +0000244 }
245
Yangster13fb7e42018-03-07 17:30:49 -0800246 VLOG("metric %lld %s->%lld", (long long)mMetricId, eventKey.toString().c_str(),
Yao Chen6a8c7992017-11-29 20:02:07 +0000247 (long long)(*mCurrentSlicedCounter)[eventKey]);
Yao Chen44cf27c2017-09-14 22:32:50 -0700248}
249
Yao Chen729093d2017-10-16 10:33:26 -0700250// When a new matched event comes in, we check if event falls into the current
251// bucket. If not, flush the old counter to past buckets and initialize the new bucket.
Yangster-macb142cc82018-03-30 15:22:08 -0700252void CountMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
253 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800254 if (eventTimeNs < currentBucketEndTimeNs) {
Yao Chen44cf27c2017-09-14 22:32:50 -0700255 return;
256 }
257
David Chen27785a82018-01-19 17:06:45 -0800258 flushCurrentBucketLocked(eventTimeNs);
259 // Setup the bucket start time and number.
Yangster-macb142cc82018-03-30 15:22:08 -0700260 int64_t numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
David Chen27785a82018-01-19 17:06:45 -0800261 mCurrentBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
262 mCurrentBucketNum += numBucketsForward;
263 VLOG("metric %lld: new bucket start time: %lld", (long long)mMetricId,
264 (long long)mCurrentBucketStartTimeNs);
265}
266
Yangster-macb142cc82018-03-30 15:22:08 -0700267void CountMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs) {
268 int64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
Yao Chen93fe3a32017-11-02 13:52:59 -0700269 CountBucket info;
270 info.mBucketStartNs = mCurrentBucketStartTimeNs;
David Chen27785a82018-01-19 17:06:45 -0800271 if (eventTimeNs < fullBucketEndTimeNs) {
272 info.mBucketEndNs = eventTimeNs;
273 } else {
274 info.mBucketEndNs = fullBucketEndTimeNs;
275 }
Yang Lu3eba6212017-10-25 19:54:45 -0700276 for (const auto& counter : *mCurrentSlicedCounter) {
Yao Chen93fe3a32017-11-02 13:52:59 -0700277 info.mCount = counter.second;
278 auto& bucketList = mPastBuckets[counter.first];
279 bucketList.push_back(info);
Yangster13fb7e42018-03-07 17:30:49 -0800280 VLOG("metric %lld, dump key value: %s -> %lld", (long long)mMetricId,
281 counter.first.toString().c_str(),
David Chen27785a82018-01-19 17:06:45 -0800282 (long long)counter.second);
Yao Chen729093d2017-10-16 10:33:26 -0700283 }
284
David Chen27785a82018-01-19 17:06:45 -0800285 // If we have finished a full bucket, then send this to anomaly tracker.
286 if (eventTimeNs > fullBucketEndTimeNs) {
287 // Accumulate partial buckets with current value and then send to anomaly tracker.
288 if (mCurrentFullCounters->size() > 0) {
289 for (const auto& keyValuePair : *mCurrentSlicedCounter) {
290 (*mCurrentFullCounters)[keyValuePair.first] += keyValuePair.second;
291 }
292 for (auto& tracker : mAnomalyTrackers) {
293 tracker->addPastBucket(mCurrentFullCounters, mCurrentBucketNum);
294 }
295 mCurrentFullCounters = std::make_shared<DimToValMap>();
296 } else {
297 // Skip aggregating the partial buckets since there's no previous partial bucket.
298 for (auto& tracker : mAnomalyTrackers) {
299 tracker->addPastBucket(mCurrentSlicedCounter, mCurrentBucketNum);
300 }
301 }
302 } else {
303 // Accumulate partial bucket.
304 for (const auto& keyValuePair : *mCurrentSlicedCounter) {
305 (*mCurrentFullCounters)[keyValuePair.first] += keyValuePair.second;
306 }
Yang Lu3eba6212017-10-25 19:54:45 -0700307 }
Bookatzd3606c72017-10-19 10:13:49 -0700308
David Chen27785a82018-01-19 17:06:45 -0800309 // Only resets the counters, but doesn't setup the times nor numbers.
310 // (Do not clear since the old one is still referenced in mAnomalyTrackers).
Yang Lu3eba6212017-10-25 19:54:45 -0700311 mCurrentSlicedCounter = std::make_shared<DimToValMap>();
Yao Chen44cf27c2017-09-14 22:32:50 -0700312}
313
yro24809bd2017-10-31 23:06:53 -0700314// Rough estimate of CountMetricProducer buffer stored. This number will be
315// greater than actual data size as it contains each dimension of
316// CountMetricData is duplicated.
Yangsterf2bee6f2017-11-29 12:01:05 -0800317size_t CountMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800318 size_t totalSize = 0;
319 for (const auto& pair : mPastBuckets) {
320 totalSize += pair.second.size() * kBucketSize;
321 }
322 return totalSize;
yro69007c82017-10-26 20:42:57 -0700323}
324
Yao Chen44cf27c2017-09-14 22:32:50 -0700325} // namespace statsd
326} // namespace os
yro69007c82017-10-26 20:42:57 -0700327} // namespace android