blob: 36ec6b98b2d7b46aa37cacd4e7fe211f75c71af3 [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
Yangsterf2bee6f2017-11-29 12:01:05 -080086 startNewProtoOutputStreamLocked(mStartTimeNs);
yro24809bd2017-10-31 23:06:53 -070087
Yangster-macd1815dc2017-11-13 21:43:15 -080088 VLOG("metric %s created. bucket size %lld start_time: %lld", metric.name().c_str(),
Yao Chen729093d2017-10-16 10:33:26 -070089 (long long)mBucketSizeNs, (long long)mStartTimeNs);
Yao Chen44cf27c2017-09-14 22:32:50 -070090}
91
Yao Chen44cf27c2017-09-14 22:32:50 -070092CountMetricProducer::~CountMetricProducer() {
93 VLOG("~CountMetricProducer() called");
94}
95
Yangsterf2bee6f2017-11-29 12:01:05 -080096void CountMetricProducer::startNewProtoOutputStreamLocked(long long startTime) {
yro24809bd2017-10-31 23:06:53 -070097 mProto = std::make_unique<ProtoOutputStream>();
Yangster-macd1815dc2017-11-13 21:43:15 -080098 mProto->write(FIELD_TYPE_STRING | FIELD_ID_NAME, mMetric.name());
yro24809bd2017-10-31 23:06:53 -070099 mProto->write(FIELD_TYPE_INT64 | FIELD_ID_START_REPORT_NANOS, startTime);
100 mProtoToken = mProto->start(FIELD_TYPE_MESSAGE | FIELD_ID_COUNT_METRICS);
Yao Chen44cf27c2017-09-14 22:32:50 -0700101}
102
yro24809bd2017-10-31 23:06:53 -0700103void CountMetricProducer::finish() {
Yao Chen729093d2017-10-16 10:33:26 -0700104}
105
Yangsterf2bee6f2017-11-29 12:01:05 -0800106void CountMetricProducer::onSlicedConditionMayChangeLocked(const uint64_t eventTime) {
Yangster-macd1815dc2017-11-13 21:43:15 -0800107 VLOG("Metric %s onSlicedConditionMayChange", mMetric.name().c_str());
Yao Chen729093d2017-10-16 10:33:26 -0700108}
109
Yangsterf2bee6f2017-11-29 12:01:05 -0800110std::unique_ptr<std::vector<uint8_t>> CountMetricProducer::onDumpReportLocked() {
Yao Chen6a8c7992017-11-29 20:02:07 +0000111 long long endTime = time(nullptr) * NS_PER_SEC;
112
113 // Dump current bucket if it's stale.
114 // If current bucket is still on-going, don't force dump current bucket.
115 // In finish(), We can force dump current bucket.
Yangsterf2bee6f2017-11-29 12:01:05 -0800116 flushIfNeededLocked(endTime);
Yangster-macd1815dc2017-11-13 21:43:15 -0800117 VLOG("metric %s dump report now...", mMetric.name().c_str());
Yao Chen729093d2017-10-16 10:33:26 -0700118
Yao Chen93fe3a32017-11-02 13:52:59 -0700119 for (const auto& counter : mPastBuckets) {
yro24809bd2017-10-31 23:06:53 -0700120 const HashableDimensionKey& hashableKey = counter.first;
Yao Chen93fe3a32017-11-02 13:52:59 -0700121 VLOG(" dimension key %s", hashableKey.c_str());
Yao Chen729093d2017-10-16 10:33:26 -0700122 auto it = mDimensionKeyMap.find(hashableKey);
123 if (it == mDimensionKeyMap.end()) {
124 ALOGE("Dimension key %s not found?!?! skip...", hashableKey.c_str());
125 continue;
126 }
yrob0378b02017-11-09 20:36:25 -0800127 long long wrapperToken =
128 mProto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
Yao Chen729093d2017-10-16 10:33:26 -0700129
yro24809bd2017-10-31 23:06:53 -0700130 // First fill dimension (KeyValuePairs).
131 for (const auto& kv : it->second) {
yrob0378b02017-11-09 20:36:25 -0800132 long long dimensionToken =
133 mProto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DIMENSION);
yro24809bd2017-10-31 23:06:53 -0700134 mProto->write(FIELD_TYPE_INT32 | FIELD_ID_KEY, kv.key());
135 if (kv.has_value_str()) {
Yao Chen1ff4f432017-11-16 17:01:40 -0800136 mProto->write(FIELD_TYPE_STRING | FIELD_ID_VALUE_STR, kv.value_str());
yro24809bd2017-10-31 23:06:53 -0700137 } else if (kv.has_value_int()) {
138 mProto->write(FIELD_TYPE_INT64 | FIELD_ID_VALUE_INT, kv.value_int());
139 } else if (kv.has_value_bool()) {
140 mProto->write(FIELD_TYPE_BOOL | FIELD_ID_VALUE_BOOL, kv.value_bool());
141 } else if (kv.has_value_float()) {
142 mProto->write(FIELD_TYPE_FLOAT | FIELD_ID_VALUE_FLOAT, kv.value_float());
143 }
144 mProto->end(dimensionToken);
145 }
146
147 // Then fill bucket_info (CountBucketInfo).
Yao Chen93fe3a32017-11-02 13:52:59 -0700148 for (const auto& bucket : counter.second) {
yrob0378b02017-11-09 20:36:25 -0800149 long long bucketInfoToken =
150 mProto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
Yao Chen93fe3a32017-11-02 13:52:59 -0700151 mProto->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_NANOS,
152 (long long)bucket.mBucketStartNs);
153 mProto->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_NANOS,
154 (long long)bucket.mBucketEndNs);
155 mProto->write(FIELD_TYPE_INT64 | FIELD_ID_COUNT, (long long)bucket.mCount);
156 mProto->end(bucketInfoToken);
157 VLOG("\t bucket [%lld - %lld] count: %lld", (long long)bucket.mBucketStartNs,
158 (long long)bucket.mBucketEndNs, (long long)bucket.mCount);
yro24809bd2017-10-31 23:06:53 -0700159 }
yro24809bd2017-10-31 23:06:53 -0700160 mProto->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700161 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000162
yro24809bd2017-10-31 23:06:53 -0700163 mProto->end(mProtoToken);
164 mProto->write(FIELD_TYPE_INT64 | FIELD_ID_END_REPORT_NANOS,
165 (long long)mCurrentBucketStartTimeNs);
166
Yangster-macd1815dc2017-11-13 21:43:15 -0800167 VLOG("metric %s dump report now...", mMetric.name().c_str());
Yangsterf2bee6f2017-11-29 12:01:05 -0800168 std::unique_ptr<std::vector<uint8_t>> buffer = serializeProtoLocked();
yro24809bd2017-10-31 23:06:53 -0700169
Yangsterf2bee6f2017-11-29 12:01:05 -0800170 startNewProtoOutputStreamLocked(endTime);
Yao Chen6a8c7992017-11-29 20:02:07 +0000171 mPastBuckets.clear();
yro24809bd2017-10-31 23:06:53 -0700172
yro17adac92017-11-08 23:16:29 -0800173 return buffer;
Yao Chen6a8c7992017-11-29 20:02:07 +0000174
175 // TODO: Clear mDimensionKeyMap once the report is dumped.
Yao Chen44cf27c2017-09-14 22:32:50 -0700176}
177
Yangsterf2bee6f2017-11-29 12:01:05 -0800178void CountMetricProducer::onConditionChangedLocked(const bool conditionMet,
179 const uint64_t eventTime) {
Yangster-macd1815dc2017-11-13 21:43:15 -0800180 VLOG("Metric %s onConditionChanged", mMetric.name().c_str());
Yao Chencaf339d2017-10-06 16:01:10 -0700181 mCondition = conditionMet;
182}
183
Yangsterf2bee6f2017-11-29 12:01:05 -0800184bool CountMetricProducer::hitGuardRailLocked(const HashableDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800185 if (mCurrentSlicedCounter->find(newKey) != mCurrentSlicedCounter->end()) {
186 return false;
187 }
188 // ===========GuardRail==============
189 // 1. Report the tuple count if the tuple count > soft limit
190 if (mCurrentSlicedCounter->size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
191 size_t newTupleCount = mCurrentSlicedCounter->size() + 1;
192 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetric.name(),
193 newTupleCount);
194 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
195 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
196 ALOGE("CountMetric %s dropping data for dimension key %s", mMetric.name().c_str(),
197 newKey.c_str());
198 return true;
199 }
200 }
201
202 return false;
203}
Yangsterf2bee6f2017-11-29 12:01:05 -0800204
205void CountMetricProducer::onMatchedLogEventInternalLocked(
Yao Chenb7041772017-10-20 16:59:25 -0700206 const size_t matcherIndex, const HashableDimensionKey& eventKey,
207 const map<string, HashableDimensionKey>& conditionKey, bool condition,
Chenjie Yub3dda412017-10-24 13:41:59 -0700208 const LogEvent& event, bool scheduledPull) {
Yao Chen729093d2017-10-16 10:33:26 -0700209 uint64_t eventTimeNs = event.GetTimestampNs();
Yao Chen44cf27c2017-09-14 22:32:50 -0700210
Yangsterf2bee6f2017-11-29 12:01:05 -0800211 flushIfNeededLocked(eventTimeNs);
Yao Chen729093d2017-10-16 10:33:26 -0700212
Yao Chen6a8c7992017-11-29 20:02:07 +0000213 if (condition == false) {
Yao Chenb7041772017-10-20 16:59:25 -0700214 return;
Yao Chen44cf27c2017-09-14 22:32:50 -0700215 }
Yao Chen729093d2017-10-16 10:33:26 -0700216
Yao Chen6a8c7992017-11-29 20:02:07 +0000217 auto it = mCurrentSlicedCounter->find(eventKey);
218
219 if (it == mCurrentSlicedCounter->end()) {
220 // ===========GuardRail==============
Yangsterf2bee6f2017-11-29 12:01:05 -0800221 if (hitGuardRailLocked(eventKey)) {
Yao Chenb3561512017-11-21 18:07:17 -0800222 return;
223 }
224
Yao Chen6a8c7992017-11-29 20:02:07 +0000225 // create a counter for the new key
226 (*mCurrentSlicedCounter)[eventKey] = 1;
227 } else {
228 // increment the existing value
229 auto& count = it->second;
230 count++;
Yao Chen729093d2017-10-16 10:33:26 -0700231 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000232
233 for (auto& tracker : mAnomalyTrackers) {
234 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, eventKey,
235 mCurrentSlicedCounter->find(eventKey)->second);
236 }
237
238 VLOG("metric %s %s->%lld", mMetric.name().c_str(), eventKey.c_str(),
239 (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) {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800245 if (eventTimeNs < mCurrentBucketStartTimeNs + mBucketSizeNs) {
Yao Chen44cf27c2017-09-14 22:32:50 -0700246 return;
247 }
248
Yao Chen93fe3a32017-11-02 13:52:59 -0700249 CountBucket info;
250 info.mBucketStartNs = mCurrentBucketStartTimeNs;
251 info.mBucketEndNs = mCurrentBucketStartTimeNs + mBucketSizeNs;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800252 info.mBucketNum = mCurrentBucketNum;
Yang Lu3eba6212017-10-25 19:54:45 -0700253 for (const auto& counter : *mCurrentSlicedCounter) {
Yao Chen93fe3a32017-11-02 13:52:59 -0700254 info.mCount = counter.second;
255 auto& bucketList = mPastBuckets[counter.first];
256 bucketList.push_back(info);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800257 VLOG("metric %s, dump key value: %s -> %lld", mMetric.name().c_str(), counter.first.c_str(),
258 (long long)counter.second);
Yao Chen729093d2017-10-16 10:33:26 -0700259 }
260
Yang Lu3eba6212017-10-25 19:54:45 -0700261 for (auto& tracker : mAnomalyTrackers) {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800262 tracker->addPastBucket(mCurrentSlicedCounter, mCurrentBucketNum);
Yang Lu3eba6212017-10-25 19:54:45 -0700263 }
Bookatzd3606c72017-10-19 10:13:49 -0700264
Yang Lu3eba6212017-10-25 19:54:45 -0700265 // Reset counters (do not clear, since the old one is still referenced in mAnomalyTrackers).
266 mCurrentSlicedCounter = std::make_shared<DimToValMap>();
Yangster-mace2cd6d52017-11-09 20:38:30 -0800267 uint64_t numBucketsForward = (eventTimeNs - mCurrentBucketStartTimeNs) / mBucketSizeNs;
Yao Chen729093d2017-10-16 10:33:26 -0700268 mCurrentBucketStartTimeNs = mCurrentBucketStartTimeNs + numBucketsForward * mBucketSizeNs;
Yang Lu3eba6212017-10-25 19:54:45 -0700269 mCurrentBucketNum += numBucketsForward;
Yangster-macd1815dc2017-11-13 21:43:15 -0800270 VLOG("metric %s: new bucket start time: %lld", mMetric.name().c_str(),
Yao Chen729093d2017-10-16 10:33:26 -0700271 (long long)mCurrentBucketStartTimeNs);
Yao Chen44cf27c2017-09-14 22:32:50 -0700272}
273
yro24809bd2017-10-31 23:06:53 -0700274// Rough estimate of CountMetricProducer buffer stored. This number will be
275// greater than actual data size as it contains each dimension of
276// CountMetricData is duplicated.
Yangsterf2bee6f2017-11-29 12:01:05 -0800277size_t CountMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800278 size_t totalSize = 0;
279 for (const auto& pair : mPastBuckets) {
280 totalSize += pair.second.size() * kBucketSize;
281 }
282 return totalSize;
yro69007c82017-10-26 20:42:57 -0700283}
284
Yao Chen44cf27c2017-09-14 22:32:50 -0700285} // namespace statsd
286} // namespace os
yro69007c82017-10-26 20:42:57 -0700287} // namespace android