blob: ae297d9eca0d3e230a22ba09c8927f53b16809ff [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 Chen44cf27c2017-09-14 22:32:50 -070017#define DEBUG true // 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"
Yao Chen44cf27c2017-09-14 22:32:50 -070023
Yao Chen44cf27c2017-09-14 22:32:50 -070024#include <limits.h>
25#include <stdlib.h>
26
yrob0378b02017-11-09 20:36:25 -080027using android::util::FIELD_COUNT_REPEATED;
yro2b0f8862017-11-06 14:27:31 -080028using android::util::FIELD_TYPE_BOOL;
29using android::util::FIELD_TYPE_FLOAT;
30using android::util::FIELD_TYPE_INT32;
31using android::util::FIELD_TYPE_INT64;
32using android::util::FIELD_TYPE_MESSAGE;
Yangster-macd1815dc2017-11-13 21:43:15 -080033using android::util::FIELD_TYPE_STRING;
yro24809bd2017-10-31 23:06:53 -070034using android::util::ProtoOutputStream;
Yao Chen729093d2017-10-16 10:33:26 -070035using std::map;
36using std::string;
Yao Chen44cf27c2017-09-14 22:32:50 -070037using std::unordered_map;
Yao Chen729093d2017-10-16 10:33:26 -070038using std::vector;
Yao Chen44cf27c2017-09-14 22:32:50 -070039
40namespace android {
41namespace os {
42namespace statsd {
43
yro24809bd2017-10-31 23:06:53 -070044// for StatsLogReport
Yangster-macd1815dc2017-11-13 21:43:15 -080045const int FIELD_ID_NAME = 1;
yro24809bd2017-10-31 23:06:53 -070046const int FIELD_ID_START_REPORT_NANOS = 2;
47const int FIELD_ID_END_REPORT_NANOS = 3;
48const int FIELD_ID_COUNT_METRICS = 5;
49// for CountMetricDataWrapper
50const int FIELD_ID_DATA = 1;
51// for CountMetricData
52const int FIELD_ID_DIMENSION = 1;
53const int FIELD_ID_BUCKET_INFO = 2;
54// for KeyValuePair
55const int FIELD_ID_KEY = 1;
56const int FIELD_ID_VALUE_STR = 2;
57const int FIELD_ID_VALUE_INT = 3;
58const int FIELD_ID_VALUE_BOOL = 4;
59const int FIELD_ID_VALUE_FLOAT = 5;
60// for CountBucketInfo
61const int FIELD_ID_START_BUCKET_NANOS = 1;
62const int FIELD_ID_END_BUCKET_NANOS = 2;
63const int FIELD_ID_COUNT = 3;
64
Yao Chenb3561512017-11-21 18:07:17 -080065CountMetricProducer::CountMetricProducer(const ConfigKey& key, const CountMetric& metric,
66 const int conditionIndex,
Yao Chen93fe3a32017-11-02 13:52:59 -070067 const sp<ConditionWizard>& wizard,
68 const uint64_t startTimeNs)
Yao Chenb3561512017-11-21 18:07:17 -080069 : MetricProducer(key, startTimeNs, conditionIndex, wizard), mMetric(metric) {
Yao Chen44cf27c2017-09-14 22:32:50 -070070 // TODO: evaluate initial conditions. and set mConditionMet.
71 if (metric.has_bucket() && metric.bucket().has_bucket_size_millis()) {
Yao Chen729093d2017-10-16 10:33:26 -070072 mBucketSizeNs = metric.bucket().bucket_size_millis() * 1000 * 1000;
Yao Chen44cf27c2017-09-14 22:32:50 -070073 } else {
Yao Chen729093d2017-10-16 10:33:26 -070074 mBucketSizeNs = LLONG_MAX;
Yao Chen44cf27c2017-09-14 22:32:50 -070075 }
76
Yao Chen729093d2017-10-16 10:33:26 -070077 // TODO: use UidMap if uid->pkg_name is required
78 mDimension.insert(mDimension.begin(), metric.dimension().begin(), metric.dimension().end());
79
80 if (metric.links().size() > 0) {
81 mConditionLinks.insert(mConditionLinks.begin(), metric.links().begin(),
82 metric.links().end());
83 mConditionSliced = true;
84 }
85
Yangster-macd1815dc2017-11-13 21:43:15 -080086 VLOG("metric %s created. bucket size %lld start_time: %lld", metric.name().c_str(),
Yao Chen729093d2017-10-16 10:33:26 -070087 (long long)mBucketSizeNs, (long long)mStartTimeNs);
Yao Chen44cf27c2017-09-14 22:32:50 -070088}
89
Yao Chen44cf27c2017-09-14 22:32:50 -070090CountMetricProducer::~CountMetricProducer() {
91 VLOG("~CountMetricProducer() called");
92}
93
Yangsterf2bee6f2017-11-29 12:01:05 -080094void CountMetricProducer::onSlicedConditionMayChangeLocked(const uint64_t eventTime) {
Yangster-macd1815dc2017-11-13 21:43:15 -080095 VLOG("Metric %s onSlicedConditionMayChange", mMetric.name().c_str());
Yao Chen729093d2017-10-16 10:33:26 -070096}
97
Yao Chen288c6002017-12-12 13:43:18 -080098void CountMetricProducer::onDumpReportLocked(const uint64_t dumpTimeNs,
99 ProtoOutputStream* protoOutput) {
100 flushIfNeededLocked(dumpTimeNs);
Yao Chen6a8c7992017-11-29 20:02:07 +0000101
Yao Chen288c6002017-12-12 13:43:18 -0800102 protoOutput->write(FIELD_TYPE_STRING | FIELD_ID_NAME, mMetric.name());
103 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_REPORT_NANOS, (long long)mStartTimeNs);
104 long long protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_COUNT_METRICS);
105
Yangster-macd1815dc2017-11-13 21:43:15 -0800106 VLOG("metric %s dump report now...", mMetric.name().c_str());
Yao Chen729093d2017-10-16 10:33:26 -0700107
Yao Chen93fe3a32017-11-02 13:52:59 -0700108 for (const auto& counter : mPastBuckets) {
yro24809bd2017-10-31 23:06:53 -0700109 const HashableDimensionKey& hashableKey = counter.first;
Yao Chen93fe3a32017-11-02 13:52:59 -0700110 VLOG(" dimension key %s", hashableKey.c_str());
Yao Chen729093d2017-10-16 10:33:26 -0700111 auto it = mDimensionKeyMap.find(hashableKey);
112 if (it == mDimensionKeyMap.end()) {
113 ALOGE("Dimension key %s not found?!?! skip...", hashableKey.c_str());
114 continue;
115 }
yrob0378b02017-11-09 20:36:25 -0800116 long long wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800117 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
Yao Chen729093d2017-10-16 10:33:26 -0700118
yro24809bd2017-10-31 23:06:53 -0700119 // First fill dimension (KeyValuePairs).
120 for (const auto& kv : it->second) {
Yao Chen288c6002017-12-12 13:43:18 -0800121 long long dimensionToken = protoOutput->start(
122 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DIMENSION);
123 protoOutput->write(FIELD_TYPE_INT32 | FIELD_ID_KEY, kv.key());
yro24809bd2017-10-31 23:06:53 -0700124 if (kv.has_value_str()) {
Yao Chen288c6002017-12-12 13:43:18 -0800125 protoOutput->write(FIELD_TYPE_STRING | FIELD_ID_VALUE_STR, kv.value_str());
yro24809bd2017-10-31 23:06:53 -0700126 } else if (kv.has_value_int()) {
Yao Chen288c6002017-12-12 13:43:18 -0800127 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_VALUE_INT, kv.value_int());
yro24809bd2017-10-31 23:06:53 -0700128 } else if (kv.has_value_bool()) {
Yao Chen288c6002017-12-12 13:43:18 -0800129 protoOutput->write(FIELD_TYPE_BOOL | FIELD_ID_VALUE_BOOL, kv.value_bool());
yro24809bd2017-10-31 23:06:53 -0700130 } else if (kv.has_value_float()) {
Yao Chen288c6002017-12-12 13:43:18 -0800131 protoOutput->write(FIELD_TYPE_FLOAT | FIELD_ID_VALUE_FLOAT, kv.value_float());
yro24809bd2017-10-31 23:06:53 -0700132 }
Yao Chen288c6002017-12-12 13:43:18 -0800133 protoOutput->end(dimensionToken);
yro24809bd2017-10-31 23:06:53 -0700134 }
135
136 // Then fill bucket_info (CountBucketInfo).
Yao Chen93fe3a32017-11-02 13:52:59 -0700137 for (const auto& bucket : counter.second) {
Yao Chen288c6002017-12-12 13:43:18 -0800138 long long bucketInfoToken = protoOutput->start(
139 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
140 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_NANOS,
141 (long long)bucket.mBucketStartNs);
142 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_NANOS,
143 (long long)bucket.mBucketEndNs);
144 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_COUNT, (long long)bucket.mCount);
145 protoOutput->end(bucketInfoToken);
Yao Chen93fe3a32017-11-02 13:52:59 -0700146 VLOG("\t bucket [%lld - %lld] count: %lld", (long long)bucket.mBucketStartNs,
147 (long long)bucket.mBucketEndNs, (long long)bucket.mCount);
yro24809bd2017-10-31 23:06:53 -0700148 }
Yao Chen288c6002017-12-12 13:43:18 -0800149 protoOutput->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700150 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000151
Yao Chen288c6002017-12-12 13:43:18 -0800152 protoOutput->end(protoToken);
153 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_REPORT_NANOS, (long long)dumpTimeNs);
yro24809bd2017-10-31 23:06:53 -0700154
Yao Chen6a8c7992017-11-29 20:02:07 +0000155 mPastBuckets.clear();
Yao Chen288c6002017-12-12 13:43:18 -0800156 mStartTimeNs = mCurrentBucketStartTimeNs;
Yao Chen6a8c7992017-11-29 20:02:07 +0000157
158 // TODO: Clear mDimensionKeyMap once the report is dumped.
Yao Chen44cf27c2017-09-14 22:32:50 -0700159}
160
Yangsterf2bee6f2017-11-29 12:01:05 -0800161void CountMetricProducer::onConditionChangedLocked(const bool conditionMet,
162 const uint64_t eventTime) {
Yangster-macd1815dc2017-11-13 21:43:15 -0800163 VLOG("Metric %s onConditionChanged", mMetric.name().c_str());
Yao Chencaf339d2017-10-06 16:01:10 -0700164 mCondition = conditionMet;
165}
166
Yangsterf2bee6f2017-11-29 12:01:05 -0800167bool CountMetricProducer::hitGuardRailLocked(const HashableDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800168 if (mCurrentSlicedCounter->find(newKey) != mCurrentSlicedCounter->end()) {
169 return false;
170 }
171 // ===========GuardRail==============
172 // 1. Report the tuple count if the tuple count > soft limit
173 if (mCurrentSlicedCounter->size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
174 size_t newTupleCount = mCurrentSlicedCounter->size() + 1;
175 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetric.name(),
176 newTupleCount);
177 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
178 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
179 ALOGE("CountMetric %s dropping data for dimension key %s", mMetric.name().c_str(),
180 newKey.c_str());
181 return true;
182 }
183 }
184
185 return false;
186}
Yangsterf2bee6f2017-11-29 12:01:05 -0800187
188void CountMetricProducer::onMatchedLogEventInternalLocked(
Yao Chenb7041772017-10-20 16:59:25 -0700189 const size_t matcherIndex, const HashableDimensionKey& eventKey,
190 const map<string, HashableDimensionKey>& conditionKey, bool condition,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800191 const LogEvent& event) {
Yao Chen729093d2017-10-16 10:33:26 -0700192 uint64_t eventTimeNs = event.GetTimestampNs();
Yao Chen44cf27c2017-09-14 22:32:50 -0700193
Yangsterf2bee6f2017-11-29 12:01:05 -0800194 flushIfNeededLocked(eventTimeNs);
Yao Chen729093d2017-10-16 10:33:26 -0700195
Yao Chen6a8c7992017-11-29 20:02:07 +0000196 if (condition == false) {
Yao Chenb7041772017-10-20 16:59:25 -0700197 return;
Yao Chen44cf27c2017-09-14 22:32:50 -0700198 }
Yao Chen729093d2017-10-16 10:33:26 -0700199
Yao Chen6a8c7992017-11-29 20:02:07 +0000200 auto it = mCurrentSlicedCounter->find(eventKey);
201
202 if (it == mCurrentSlicedCounter->end()) {
203 // ===========GuardRail==============
Yangsterf2bee6f2017-11-29 12:01:05 -0800204 if (hitGuardRailLocked(eventKey)) {
Yao Chenb3561512017-11-21 18:07:17 -0800205 return;
206 }
207
Yao Chen6a8c7992017-11-29 20:02:07 +0000208 // create a counter for the new key
209 (*mCurrentSlicedCounter)[eventKey] = 1;
210 } else {
211 // increment the existing value
212 auto& count = it->second;
213 count++;
Yao Chen729093d2017-10-16 10:33:26 -0700214 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000215
216 for (auto& tracker : mAnomalyTrackers) {
217 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, eventKey,
218 mCurrentSlicedCounter->find(eventKey)->second);
219 }
220
221 VLOG("metric %s %s->%lld", mMetric.name().c_str(), eventKey.c_str(),
222 (long long)(*mCurrentSlicedCounter)[eventKey]);
Yao Chen44cf27c2017-09-14 22:32:50 -0700223}
224
Yao Chen729093d2017-10-16 10:33:26 -0700225// When a new matched event comes in, we check if event falls into the current
226// bucket. If not, flush the old counter to past buckets and initialize the new bucket.
Yangsterf2bee6f2017-11-29 12:01:05 -0800227void CountMetricProducer::flushIfNeededLocked(const uint64_t& eventTimeNs) {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800228 if (eventTimeNs < mCurrentBucketStartTimeNs + mBucketSizeNs) {
Yao Chen44cf27c2017-09-14 22:32:50 -0700229 return;
230 }
231
Yao Chen93fe3a32017-11-02 13:52:59 -0700232 CountBucket info;
233 info.mBucketStartNs = mCurrentBucketStartTimeNs;
234 info.mBucketEndNs = mCurrentBucketStartTimeNs + mBucketSizeNs;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800235 info.mBucketNum = mCurrentBucketNum;
Yang Lu3eba6212017-10-25 19:54:45 -0700236 for (const auto& counter : *mCurrentSlicedCounter) {
Yao Chen93fe3a32017-11-02 13:52:59 -0700237 info.mCount = counter.second;
238 auto& bucketList = mPastBuckets[counter.first];
239 bucketList.push_back(info);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800240 VLOG("metric %s, dump key value: %s -> %lld", mMetric.name().c_str(), counter.first.c_str(),
241 (long long)counter.second);
Yao Chen729093d2017-10-16 10:33:26 -0700242 }
243
Yang Lu3eba6212017-10-25 19:54:45 -0700244 for (auto& tracker : mAnomalyTrackers) {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800245 tracker->addPastBucket(mCurrentSlicedCounter, mCurrentBucketNum);
Yang Lu3eba6212017-10-25 19:54:45 -0700246 }
Bookatzd3606c72017-10-19 10:13:49 -0700247
Yang Lu3eba6212017-10-25 19:54:45 -0700248 // Reset counters (do not clear, since the old one is still referenced in mAnomalyTrackers).
249 mCurrentSlicedCounter = std::make_shared<DimToValMap>();
Yangster-mace2cd6d52017-11-09 20:38:30 -0800250 uint64_t numBucketsForward = (eventTimeNs - mCurrentBucketStartTimeNs) / mBucketSizeNs;
Yao Chen729093d2017-10-16 10:33:26 -0700251 mCurrentBucketStartTimeNs = mCurrentBucketStartTimeNs + numBucketsForward * mBucketSizeNs;
Yang Lu3eba6212017-10-25 19:54:45 -0700252 mCurrentBucketNum += numBucketsForward;
Yangster-macd1815dc2017-11-13 21:43:15 -0800253 VLOG("metric %s: new bucket start time: %lld", mMetric.name().c_str(),
Yao Chen729093d2017-10-16 10:33:26 -0700254 (long long)mCurrentBucketStartTimeNs);
Yao Chen44cf27c2017-09-14 22:32:50 -0700255}
256
yro24809bd2017-10-31 23:06:53 -0700257// Rough estimate of CountMetricProducer buffer stored. This number will be
258// greater than actual data size as it contains each dimension of
259// CountMetricData is duplicated.
Yangsterf2bee6f2017-11-29 12:01:05 -0800260size_t CountMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800261 size_t totalSize = 0;
262 for (const auto& pair : mPastBuckets) {
263 totalSize += pair.second.size() * kBucketSize;
264 }
265 return totalSize;
yro69007c82017-10-26 20:42:57 -0700266}
267
Yao Chen44cf27c2017-09-14 22:32:50 -0700268} // namespace statsd
269} // namespace os
yro69007c82017-10-26 20:42:57 -0700270} // namespace android