blob: 83fe84a8fd5b6c3dab5266783c90ec7aeb5980f0 [file] [log] [blame]
Yao Chen729093d2017-10-16 10:33:26 -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
17#define DEBUG true
Yao Chen5154a372017-10-30 22:57:06 -070018
Yao Chen729093d2017-10-16 10:33:26 -070019#include "Log.h"
Yao Chen5154a372017-10-30 22:57:06 -070020#include "DurationMetricProducer.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"
23
Yao Chen729093d2017-10-16 10:33:26 -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;
yro2b0f8862017-11-06 14:27:31 -080034using android::util::ProtoOutputStream;
Yao Chen729093d2017-10-16 10:33:26 -070035using std::string;
36using std::unordered_map;
37using std::vector;
38
39namespace android {
40namespace os {
41namespace statsd {
42
yro2b0f8862017-11-06 14:27:31 -080043// for StatsLogReport
Yangster-macd1815dc2017-11-13 21:43:15 -080044const int FIELD_ID_NAME = 1;
yro2b0f8862017-11-06 14:27:31 -080045const int FIELD_ID_START_REPORT_NANOS = 2;
46const int FIELD_ID_END_REPORT_NANOS = 3;
47const int FIELD_ID_DURATION_METRICS = 6;
48// for DurationMetricDataWrapper
49const int FIELD_ID_DATA = 1;
50// for DurationMetricData
51const int FIELD_ID_DIMENSION = 1;
52const int FIELD_ID_BUCKET_INFO = 2;
53// for KeyValuePair
54const int FIELD_ID_KEY = 1;
55const int FIELD_ID_VALUE_STR = 2;
56const int FIELD_ID_VALUE_INT = 3;
57const int FIELD_ID_VALUE_BOOL = 4;
58const int FIELD_ID_VALUE_FLOAT = 5;
59// for DurationBucketInfo
60const int FIELD_ID_START_BUCKET_NANOS = 1;
61const int FIELD_ID_END_BUCKET_NANOS = 2;
62const int FIELD_ID_DURATION = 3;
63
Yao Chenb3561512017-11-21 18:07:17 -080064DurationMetricProducer::DurationMetricProducer(const ConfigKey& key, const DurationMetric& metric,
Yao Chen729093d2017-10-16 10:33:26 -070065 const int conditionIndex, const size_t startIndex,
66 const size_t stopIndex, const size_t stopAllIndex,
Yao Chen0ea19902017-11-15 15:44:45 -080067 const bool nesting,
Yao Chen5154a372017-10-30 22:57:06 -070068 const sp<ConditionWizard>& wizard,
Yao Chen93fe3a32017-11-02 13:52:59 -070069 const vector<KeyMatcher>& internalDimension,
70 const uint64_t startTimeNs)
Yao Chenb3561512017-11-21 18:07:17 -080071 : MetricProducer(key, startTimeNs, conditionIndex, wizard),
Yao Chen729093d2017-10-16 10:33:26 -070072 mMetric(metric),
73 mStartIndex(startIndex),
74 mStopIndex(stopIndex),
Yao Chen5154a372017-10-30 22:57:06 -070075 mStopAllIndex(stopAllIndex),
Yao Chen0ea19902017-11-15 15:44:45 -080076 mNested(nesting),
Yao Chen5154a372017-10-30 22:57:06 -070077 mInternalDimension(internalDimension) {
Yao Chen729093d2017-10-16 10:33:26 -070078 // TODO: The following boiler plate code appears in all MetricProducers, but we can't abstract
79 // them in the base class, because the proto generated CountMetric, and DurationMetric are
80 // not related. Maybe we should add a template in the future??
81 if (metric.has_bucket() && metric.bucket().has_bucket_size_millis()) {
82 mBucketSizeNs = metric.bucket().bucket_size_millis() * 1000000;
83 } else {
84 mBucketSizeNs = LLONG_MAX;
85 }
86
87 // TODO: use UidMap if uid->pkg_name is required
88 mDimension.insert(mDimension.begin(), metric.dimension().begin(), metric.dimension().end());
89
90 if (metric.links().size() > 0) {
91 mConditionLinks.insert(mConditionLinks.begin(), metric.links().begin(),
92 metric.links().end());
93 mConditionSliced = true;
94 }
95
Yangsterf2bee6f2017-11-29 12:01:05 -080096 startNewProtoOutputStreamLocked(mStartTimeNs);
yro2b0f8862017-11-06 14:27:31 -080097
Yangster-macd1815dc2017-11-13 21:43:15 -080098 VLOG("metric %s created. bucket size %lld start_time: %lld", metric.name().c_str(),
Yao Chen729093d2017-10-16 10:33:26 -070099 (long long)mBucketSizeNs, (long long)mStartTimeNs);
100}
101
102DurationMetricProducer::~DurationMetricProducer() {
103 VLOG("~DurationMetric() called");
104}
105
Bookatz450099d2017-11-30 17:09:30 -0800106sp<AnomalyTracker> DurationMetricProducer::createAnomalyTracker(const Alert &alert) {
107 if (alert.trigger_if_sum_gt() > alert.number_of_buckets() * mBucketSizeNs) {
108 ALOGW("invalid alert: threshold (%lld) > possible recordable value (%d x %lld)",
109 alert.trigger_if_sum_gt(), alert.number_of_buckets(),
110 (long long)mBucketSizeNs);
111 return nullptr;
112 }
113 // TODO: return a DurationAnomalyTracker (which should sublclass AnomalyTracker)
114 return new AnomalyTracker(alert);
115}
116
Yangsterf2bee6f2017-11-29 12:01:05 -0800117void DurationMetricProducer::startNewProtoOutputStreamLocked(long long startTime) {
yro2b0f8862017-11-06 14:27:31 -0800118 mProto = std::make_unique<ProtoOutputStream>();
Yangster-macd1815dc2017-11-13 21:43:15 -0800119 mProto->write(FIELD_TYPE_STRING | FIELD_ID_NAME, mMetric.name());
yro2b0f8862017-11-06 14:27:31 -0800120 mProto->write(FIELD_TYPE_INT64 | FIELD_ID_START_REPORT_NANOS, startTime);
121 mProtoToken = mProto->start(FIELD_TYPE_MESSAGE | FIELD_ID_DURATION_METRICS);
122}
123
Yao Chen5154a372017-10-30 22:57:06 -0700124unique_ptr<DurationTracker> DurationMetricProducer::createDurationTracker(
Yangsterf2bee6f2017-11-29 12:01:05 -0800125 const HashableDimensionKey& eventKey, vector<DurationBucket>& bucket) const {
Stefan Lafoncfed20b2017-11-18 09:26:53 -0800126 switch (mMetric.aggregation_type()) {
127 case DurationMetric_AggregationType_SUM:
Yao Chenb3561512017-11-21 18:07:17 -0800128 return make_unique<OringDurationTracker>(
129 mConfigKey, mMetric.name(), eventKey, mWizard, mConditionTrackerIndex, mNested,
130 mCurrentBucketStartTimeNs, mBucketSizeNs, mAnomalyTrackers, bucket);
Stefan Lafoncfed20b2017-11-18 09:26:53 -0800131 case DurationMetric_AggregationType_MAX_SPARSE:
Yao Chenb3561512017-11-21 18:07:17 -0800132 return make_unique<MaxDurationTracker>(
133 mConfigKey, mMetric.name(), eventKey, mWizard, mConditionTrackerIndex, mNested,
134 mCurrentBucketStartTimeNs, mBucketSizeNs, mAnomalyTrackers, bucket);
Yao Chen5154a372017-10-30 22:57:06 -0700135 }
136}
137
Yao Chen729093d2017-10-16 10:33:26 -0700138void DurationMetricProducer::finish() {
139 // TODO: write the StatsLogReport to dropbox using
140 // DropboxWriter.
141}
142
Yangsterf2bee6f2017-11-29 12:01:05 -0800143void DurationMetricProducer::onSlicedConditionMayChangeLocked(const uint64_t eventTime) {
Yangster-macd1815dc2017-11-13 21:43:15 -0800144 VLOG("Metric %s onSlicedConditionMayChange", mMetric.name().c_str());
Yangsterf2bee6f2017-11-29 12:01:05 -0800145 flushIfNeededLocked(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700146 // Now for each of the on-going event, check if the condition has changed for them.
147 for (auto& pair : mCurrentSlicedDuration) {
Yao Chen5154a372017-10-30 22:57:06 -0700148 pair.second->onSlicedConditionMayChange(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700149 }
150}
151
Yangsterf2bee6f2017-11-29 12:01:05 -0800152void DurationMetricProducer::onConditionChangedLocked(const bool conditionMet,
153 const uint64_t eventTime) {
Yangster-macd1815dc2017-11-13 21:43:15 -0800154 VLOG("Metric %s onConditionChanged", mMetric.name().c_str());
Yao Chen729093d2017-10-16 10:33:26 -0700155 mCondition = conditionMet;
Yangsterf2bee6f2017-11-29 12:01:05 -0800156 flushIfNeededLocked(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700157 // TODO: need to populate the condition change time from the event which triggers the condition
158 // change, instead of using current time.
159 for (auto& pair : mCurrentSlicedDuration) {
Yao Chen5154a372017-10-30 22:57:06 -0700160 pair.second->onConditionChanged(conditionMet, eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700161 }
162}
163
Yangsterf2bee6f2017-11-29 12:01:05 -0800164std::unique_ptr<std::vector<uint8_t>> DurationMetricProducer::onDumpReportLocked() {
Yao Chen6a8c7992017-11-29 20:02:07 +0000165 long long endTime = time(nullptr) * NS_PER_SEC;
166
167 // Dump current bucket if it's stale.
168 // If current bucket is still on-going, don't force dump current bucket.
169 // In finish(), We can force dump current bucket.
Yangsterf2bee6f2017-11-29 12:01:05 -0800170 flushIfNeededLocked(endTime);
Yao Chen6a8c7992017-11-29 20:02:07 +0000171 VLOG("metric %s dump report now...", mMetric.name().c_str());
172
Yao Chen729093d2017-10-16 10:33:26 -0700173 for (const auto& pair : mPastBuckets) {
174 const HashableDimensionKey& hashableKey = pair.first;
yro2b0f8862017-11-06 14:27:31 -0800175 VLOG(" dimension key %s", hashableKey.c_str());
Yao Chen729093d2017-10-16 10:33:26 -0700176 auto it = mDimensionKeyMap.find(hashableKey);
177 if (it == mDimensionKeyMap.end()) {
178 ALOGW("Dimension key %s not found?!?! skip...", hashableKey.c_str());
179 continue;
180 }
Yao Chen1ff4f432017-11-16 17:01:40 -0800181
182 // If there is no duration bucket info for this key, don't include it in the report.
183 // For example, duration started, but condition is never turned to true.
184 // TODO: Only add the key to the map when we add duration buckets info for it.
185 if (pair.second.size() == 0) {
186 continue;
187 }
188
yrob0378b02017-11-09 20:36:25 -0800189 long long wrapperToken =
190 mProto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
yro2b0f8862017-11-06 14:27:31 -0800191
192 // First fill dimension (KeyValuePairs).
193 for (const auto& kv : it->second) {
yrob0378b02017-11-09 20:36:25 -0800194 long long dimensionToken =
195 mProto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DIMENSION);
yro2b0f8862017-11-06 14:27:31 -0800196 mProto->write(FIELD_TYPE_INT32 | FIELD_ID_KEY, kv.key());
197 if (kv.has_value_str()) {
Yao Chen1ff4f432017-11-16 17:01:40 -0800198 mProto->write(FIELD_TYPE_STRING | FIELD_ID_VALUE_STR, kv.value_str());
yro2b0f8862017-11-06 14:27:31 -0800199 } else if (kv.has_value_int()) {
200 mProto->write(FIELD_TYPE_INT64 | FIELD_ID_VALUE_INT, kv.value_int());
201 } else if (kv.has_value_bool()) {
202 mProto->write(FIELD_TYPE_BOOL | FIELD_ID_VALUE_BOOL, kv.value_bool());
203 } else if (kv.has_value_float()) {
204 mProto->write(FIELD_TYPE_FLOAT | FIELD_ID_VALUE_FLOAT, kv.value_float());
205 }
206 mProto->end(dimensionToken);
207 }
208
209 // Then fill bucket_info (DurationBucketInfo).
210 for (const auto& bucket : pair.second) {
yrob0378b02017-11-09 20:36:25 -0800211 long long bucketInfoToken =
212 mProto->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
yro2b0f8862017-11-06 14:27:31 -0800213 mProto->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_NANOS,
214 (long long)bucket.mBucketStartNs);
215 mProto->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_NANOS,
216 (long long)bucket.mBucketEndNs);
217 mProto->write(FIELD_TYPE_INT64 | FIELD_ID_DURATION, (long long)bucket.mDuration);
218 mProto->end(bucketInfoToken);
219 VLOG("\t bucket [%lld - %lld] duration: %lld", (long long)bucket.mBucketStartNs,
220 (long long)bucket.mBucketEndNs, (long long)bucket.mDuration);
221 }
222
223 mProto->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700224 }
yro2b0f8862017-11-06 14:27:31 -0800225
226 mProto->end(mProtoToken);
227 mProto->write(FIELD_TYPE_INT64 | FIELD_ID_END_REPORT_NANOS,
228 (long long)mCurrentBucketStartTimeNs);
Yangsterf2bee6f2017-11-29 12:01:05 -0800229 std::unique_ptr<std::vector<uint8_t>> buffer = serializeProtoLocked();
230 startNewProtoOutputStreamLocked(endTime);
Yao Chen30b6a202017-11-18 14:14:38 -0800231 // TODO: Properly clear the old buckets.
yro17adac92017-11-08 23:16:29 -0800232 return buffer;
yro2b0f8862017-11-06 14:27:31 -0800233}
Yao Chen729093d2017-10-16 10:33:26 -0700234
Yangsterf2bee6f2017-11-29 12:01:05 -0800235void DurationMetricProducer::flushIfNeededLocked(const uint64_t& eventTime) {
Yao Chen729093d2017-10-16 10:33:26 -0700236 if (mCurrentBucketStartTimeNs + mBucketSizeNs > eventTime) {
237 return;
238 }
Yao Chen5154a372017-10-30 22:57:06 -0700239 VLOG("flushing...........");
Yao Chend41c4222017-11-15 19:26:14 -0800240 for (auto it = mCurrentSlicedDuration.begin(); it != mCurrentSlicedDuration.end();) {
Yao Chen5154a372017-10-30 22:57:06 -0700241 if (it->second->flushIfNeeded(eventTime)) {
242 VLOG("erase bucket for key %s", it->first.c_str());
Yao Chend41c4222017-11-15 19:26:14 -0800243 it = mCurrentSlicedDuration.erase(it);
244 } else {
245 ++it;
Yao Chen729093d2017-10-16 10:33:26 -0700246 }
247 }
Yao Chen5154a372017-10-30 22:57:06 -0700248
249 int numBucketsForward = (eventTime - mCurrentBucketStartTimeNs) / mBucketSizeNs;
250 mCurrentBucketStartTimeNs += numBucketsForward * mBucketSizeNs;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800251 mCurrentBucketNum += numBucketsForward;
Yao Chen5154a372017-10-30 22:57:06 -0700252}
253
Yangsterf2bee6f2017-11-29 12:01:05 -0800254bool DurationMetricProducer::hitGuardRailLocked(const HashableDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800255 // the key is not new, we are good.
256 if (mCurrentSlicedDuration.find(newKey) != mCurrentSlicedDuration.end()) {
257 return false;
258 }
259 // 1. Report the tuple count if the tuple count > soft limit
260 if (mCurrentSlicedDuration.size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
261 size_t newTupleCount = mCurrentSlicedDuration.size() + 1;
262 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetric.name(),
263 newTupleCount);
264 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
265 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
266 ALOGE("DurationMetric %s dropping data for dimension key %s", mMetric.name().c_str(),
267 newKey.c_str());
268 return true;
269 }
270 }
271 return false;
272}
273
Yangsterf2bee6f2017-11-29 12:01:05 -0800274void DurationMetricProducer::onMatchedLogEventInternalLocked(
Yao Chen5154a372017-10-30 22:57:06 -0700275 const size_t matcherIndex, const HashableDimensionKey& eventKey,
276 const map<string, HashableDimensionKey>& conditionKeys, bool condition,
Chenjie Yub3dda412017-10-24 13:41:59 -0700277 const LogEvent& event, bool scheduledPull) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800278 flushIfNeededLocked(event.GetTimestampNs());
Yao Chen5154a372017-10-30 22:57:06 -0700279
Yao Chen6a8c7992017-11-29 20:02:07 +0000280 if (matcherIndex == mStopAllIndex) {
281 for (auto& pair : mCurrentSlicedDuration) {
282 pair.second->noteStopAll(event.GetTimestampNs());
283 }
284 return;
285 }
286
287 HashableDimensionKey atomKey = getHashableKey(getDimensionKey(event, mInternalDimension));
288
289 if (mCurrentSlicedDuration.find(eventKey) == mCurrentSlicedDuration.end()) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800290 if (hitGuardRailLocked(eventKey)) {
Yao Chenb3561512017-11-21 18:07:17 -0800291 return;
292 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000293 mCurrentSlicedDuration[eventKey] = createDurationTracker(eventKey, mPastBuckets[eventKey]);
294 }
Yao Chen5154a372017-10-30 22:57:06 -0700295
Yao Chen6a8c7992017-11-29 20:02:07 +0000296 auto it = mCurrentSlicedDuration.find(eventKey);
Yao Chen5154a372017-10-30 22:57:06 -0700297
Yao Chen6a8c7992017-11-29 20:02:07 +0000298 if (matcherIndex == mStartIndex) {
299 it->second->noteStart(atomKey, condition, event.GetTimestampNs(), conditionKeys);
300 } else if (matcherIndex == mStopIndex) {
301 it->second->noteStop(atomKey, event.GetTimestampNs(), false);
Yao Chen5154a372017-10-30 22:57:06 -0700302 }
Yao Chen729093d2017-10-16 10:33:26 -0700303}
304
Yangsterf2bee6f2017-11-29 12:01:05 -0800305size_t DurationMetricProducer::byteSizeLocked() const {
Yangster7c334a12017-11-22 14:24:24 -0800306 size_t totalSize = 0;
307 for (const auto& pair : mPastBuckets) {
308 totalSize += pair.second.size() * kBucketSize;
309 }
310 return totalSize;
yro69007c82017-10-26 20:42:57 -0700311}
312
Yao Chen729093d2017-10-16 10:33:26 -0700313} // namespace statsd
314} // namespace os
315} // namespace android