blob: 19155ded39bf3533eb8165cfff08a8cc454ac314 [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
Yao Chen3c0b95c2017-12-16 14:34:20 -080017#define DEBUG false
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"
Yangster-mac20877162017-12-22 17:19:39 -080023#include "stats_log_util.h"
Yao Chen729093d2017-10-16 10:33:26 -070024
Yao Chen729093d2017-10-16 10:33:26 -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;
yro2b0f8862017-11-06 14:27:31 -080035using android::util::ProtoOutputStream;
Yao Chen729093d2017-10-16 10:33:26 -070036using std::string;
37using std::unordered_map;
38using std::vector;
39
40namespace android {
41namespace os {
42namespace statsd {
43
yro2b0f8862017-11-06 14:27:31 -080044// for StatsLogReport
Yangster-mac94e197c2018-01-02 16:03:03 -080045const int FIELD_ID_ID = 1;
yro2b0f8862017-11-06 14:27:31 -080046const int FIELD_ID_DURATION_METRICS = 6;
47// for DurationMetricDataWrapper
48const int FIELD_ID_DATA = 1;
49// for DurationMetricData
Yangster-mac468ff042018-01-17 12:26:34 -080050const int FIELD_ID_DIMENSION_IN_WHAT = 1;
51const int FIELD_ID_DIMENSION_IN_CONDITION = 2;
52const int FIELD_ID_BUCKET_INFO = 3;
yro2b0f8862017-11-06 14:27:31 -080053// for DurationBucketInfo
Yangster-mac330af582018-02-08 15:24:38 -080054const int FIELD_ID_START_BUCKET_ELAPSED_NANOS = 1;
55const int FIELD_ID_END_BUCKET_ELAPSED_NANOS = 2;
yro2b0f8862017-11-06 14:27:31 -080056const int FIELD_ID_DURATION = 3;
57
Yao Chenb3561512017-11-21 18:07:17 -080058DurationMetricProducer::DurationMetricProducer(const ConfigKey& key, const DurationMetric& metric,
Yao Chen729093d2017-10-16 10:33:26 -070059 const int conditionIndex, const size_t startIndex,
60 const size_t stopIndex, const size_t stopAllIndex,
Yao Chen0ea19902017-11-15 15:44:45 -080061 const bool nesting,
Yao Chen5154a372017-10-30 22:57:06 -070062 const sp<ConditionWizard>& wizard,
Yangster-mac20877162017-12-22 17:19:39 -080063 const FieldMatcher& internalDimensions,
Yangster-macb142cc82018-03-30 15:22:08 -070064 const int64_t startTimeNs)
Yangster-mac94e197c2018-01-02 16:03:03 -080065 : MetricProducer(metric.id(), key, startTimeNs, conditionIndex, wizard),
Yao Chenf09569f2017-12-13 17:00:51 -080066 mAggregationType(metric.aggregation_type()),
Yao Chen729093d2017-10-16 10:33:26 -070067 mStartIndex(startIndex),
68 mStopIndex(stopIndex),
Yao Chen5154a372017-10-30 22:57:06 -070069 mStopAllIndex(stopAllIndex),
Yangster13fb7e42018-03-07 17:30:49 -080070 mNested(nesting),
71 mContainANYPositionInInternalDimensions(false) {
Yao Chen729093d2017-10-16 10:33:26 -070072 // TODO: The following boiler plate code appears in all MetricProducers, but we can't abstract
73 // them in the base class, because the proto generated CountMetric, and DurationMetric are
74 // not related. Maybe we should add a template in the future??
Yangster-macb8144812018-01-04 10:56:23 -080075 if (metric.has_bucket()) {
yro59cc24d2018-02-13 20:17:32 -080076 mBucketSizeNs =
77 TimeUnitToBucketSizeInMillisGuardrailed(key.GetUid(), metric.bucket()) * 1000000;
Yao Chen729093d2017-10-16 10:33:26 -070078 } else {
79 mBucketSizeNs = LLONG_MAX;
80 }
81
Yao Chen8a8d16c2018-02-08 14:50:40 -080082 if (metric.has_dimensions_in_what()) {
83 translateFieldMatcher(metric.dimensions_in_what(), &mDimensionsInWhat);
Yangster13fb7e42018-03-07 17:30:49 -080084 mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
Yao Chen8a8d16c2018-02-08 14:50:40 -080085 }
86
87 if (internalDimensions.has_field()) {
88 translateFieldMatcher(internalDimensions, &mInternalDimensions);
Yangster13fb7e42018-03-07 17:30:49 -080089 mContainANYPositionInInternalDimensions = HasPositionANY(internalDimensions);
Yao Chen8a8d16c2018-02-08 14:50:40 -080090 }
Yangster-mace06cfd72018-03-10 23:22:59 -080091 if (mContainANYPositionInInternalDimensions) {
92 ALOGE("Position ANY in internal dimension not supported.");
93 }
94 if (mContainANYPositionInDimensionsInWhat) {
95 ALOGE("Position ANY in dimension_in_what not supported.");
96 }
Yao Chen8a8d16c2018-02-08 14:50:40 -080097
98 if (metric.has_dimensions_in_condition()) {
99 translateFieldMatcher(metric.dimensions_in_condition(), &mDimensionsInCondition);
100 }
Yao Chen729093d2017-10-16 10:33:26 -0700101
102 if (metric.links().size() > 0) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800103 for (const auto& link : metric.links()) {
104 Metric2Condition mc;
105 mc.conditionId = link.condition();
106 translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
107 translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
108 mMetric2ConditionLinks.push_back(mc);
109 }
Yao Chen729093d2017-10-16 10:33:26 -0700110 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800111 mConditionSliced = (metric.links().size() > 0) || (mDimensionsInCondition.size() > 0);
Yangster13fb7e42018-03-07 17:30:49 -0800112 mUnSlicedPartCondition = ConditionState::kUnknown;
Yao Chen729093d2017-10-16 10:33:26 -0700113
Yangster13fb7e42018-03-07 17:30:49 -0800114 mUseWhatDimensionAsInternalDimension = equalDimensions(mDimensionsInWhat, mInternalDimensions);
115 if (mWizard != nullptr && mConditionTrackerIndex >= 0) {
116 mSameConditionDimensionsInTracker =
117 mWizard->equalOutputDimensions(mConditionTrackerIndex, mDimensionsInCondition);
118 if (mMetric2ConditionLinks.size() == 1) {
119 mHasLinksToAllConditionDimensionsInTracker =
120 mWizard->equalOutputDimensions(mConditionTrackerIndex,
121 mMetric2ConditionLinks.begin()->conditionFields);
Yangster-mac53928882018-02-25 23:02:56 -0800122 }
Yangster-mac53928882018-02-25 23:02:56 -0800123 }
Yangster-mac94e197c2018-01-02 16:03:03 -0800124 VLOG("metric %lld created. bucket size %lld start_time: %lld", (long long)metric.id(),
Yao Chen729093d2017-10-16 10:33:26 -0700125 (long long)mBucketSizeNs, (long long)mStartTimeNs);
126}
127
128DurationMetricProducer::~DurationMetricProducer() {
129 VLOG("~DurationMetric() called");
130}
131
Yangster-mac932ecec2018-02-01 10:23:52 -0800132sp<AnomalyTracker> DurationMetricProducer::addAnomalyTracker(
133 const Alert &alert, const sp<AlarmMonitor>& anomalyAlarmMonitor) {
Bookatz857aaa52017-12-19 15:29:06 -0800134 std::lock_guard<std::mutex> lock(mMutex);
Bookatz423f7532018-03-08 15:45:14 -0800135 if (mAggregationType == DurationMetric_AggregationType_SUM) {
136 if (alert.trigger_if_sum_gt() > alert.num_buckets() * mBucketSizeNs) {
137 ALOGW("invalid alert for SUM: threshold (%f) > possible recordable value (%d x %lld)",
138 alert.trigger_if_sum_gt(), alert.num_buckets(), (long long)mBucketSizeNs);
139 return nullptr;
140 }
141 }
Yangster-mac932ecec2018-02-01 10:23:52 -0800142 sp<DurationAnomalyTracker> anomalyTracker =
143 new DurationAnomalyTracker(alert, mConfigKey, anomalyAlarmMonitor);
Bookatz857aaa52017-12-19 15:29:06 -0800144 if (anomalyTracker != nullptr) {
145 mAnomalyTrackers.push_back(anomalyTracker);
146 }
147 return anomalyTracker;
Bookatz450099d2017-11-30 17:09:30 -0800148}
149
Yao Chen5154a372017-10-30 22:57:06 -0700150unique_ptr<DurationTracker> DurationMetricProducer::createDurationTracker(
Yangster-mac93694462018-01-22 20:49:31 -0800151 const MetricDimensionKey& eventKey) const {
Yao Chenf09569f2017-12-13 17:00:51 -0800152 switch (mAggregationType) {
Stefan Lafoncfed20b2017-11-18 09:26:53 -0800153 case DurationMetric_AggregationType_SUM:
Yao Chenb3561512017-11-21 18:07:17 -0800154 return make_unique<OringDurationTracker>(
Yangster-mac93694462018-01-22 20:49:31 -0800155 mConfigKey, mMetricId, eventKey, mWizard, mConditionTrackerIndex,
David Chen27785a82018-01-19 17:06:45 -0800156 mDimensionsInCondition, mNested, mCurrentBucketStartTimeNs, mCurrentBucketNum,
Yangster13fb7e42018-03-07 17:30:49 -0800157 mStartTimeNs, mBucketSizeNs, mConditionSliced,
158 mHasLinksToAllConditionDimensionsInTracker, mAnomalyTrackers);
Stefan Lafoncfed20b2017-11-18 09:26:53 -0800159 case DurationMetric_AggregationType_MAX_SPARSE:
Yao Chenb3561512017-11-21 18:07:17 -0800160 return make_unique<MaxDurationTracker>(
Yangster-mac93694462018-01-22 20:49:31 -0800161 mConfigKey, mMetricId, eventKey, mWizard, mConditionTrackerIndex,
David Chen27785a82018-01-19 17:06:45 -0800162 mDimensionsInCondition, mNested, mCurrentBucketStartTimeNs, mCurrentBucketNum,
Yangster13fb7e42018-03-07 17:30:49 -0800163 mStartTimeNs, mBucketSizeNs, mConditionSliced,
164 mHasLinksToAllConditionDimensionsInTracker, mAnomalyTrackers);
165 }
166}
167
168// SlicedConditionChange optimization case 1:
169// 1. If combination condition, logical operation is AND, only one sliced child predicate.
170// 2. No condition in dimension
171// 3. The links covers all dimension fields in the sliced child condition predicate.
Yao Chen427d3722018-03-22 15:21:52 -0700172void DurationMetricProducer::onSlicedConditionMayChangeLocked_opt1(bool condition,
Yangster-macb142cc82018-03-30 15:22:08 -0700173 const int64_t eventTime) {
Yangster13fb7e42018-03-07 17:30:49 -0800174 if (mMetric2ConditionLinks.size() != 1 ||
175 !mHasLinksToAllConditionDimensionsInTracker ||
176 !mDimensionsInCondition.empty()) {
177 return;
178 }
179
180 bool currentUnSlicedPartCondition = true;
181 if (!mWizard->IsSimpleCondition(mConditionTrackerIndex)) {
182 ConditionState unslicedPartState =
183 mWizard->getUnSlicedPartConditionState(mConditionTrackerIndex);
184 // When the unsliced part is still false, return directly.
185 if (mUnSlicedPartCondition == ConditionState::kFalse &&
186 unslicedPartState == ConditionState::kFalse) {
187 return;
188 }
189 mUnSlicedPartCondition = unslicedPartState;
190 currentUnSlicedPartCondition = mUnSlicedPartCondition > 0;
191 }
192
193 auto dimensionsChangedToTrue = mWizard->getChangedToTrueDimensions(mConditionTrackerIndex);
194 auto dimensionsChangedToFalse = mWizard->getChangedToFalseDimensions(mConditionTrackerIndex);
195
196 // The condition change is from the unsliced predicates.
197 // We need to find out the true dimensions from the sliced predicate and flip their condition
198 // state based on the new unsliced condition state.
199 if (dimensionsChangedToTrue == nullptr || dimensionsChangedToFalse == nullptr ||
200 (dimensionsChangedToTrue->empty() && dimensionsChangedToFalse->empty())) {
201 std::set<HashableDimensionKey> trueConditionDimensions;
202 mWizard->getTrueSlicedDimensions(mConditionTrackerIndex, &trueConditionDimensions);
203 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
204 HashableDimensionKey linkedConditionDimensionKey;
205 getDimensionForCondition(whatIt.first.getValues(),
206 mMetric2ConditionLinks[0],
207 &linkedConditionDimensionKey);
208 if (trueConditionDimensions.find(linkedConditionDimensionKey) !=
209 trueConditionDimensions.end()) {
210 for (auto& condIt : whatIt.second) {
211 condIt.second->onConditionChanged(
212 currentUnSlicedPartCondition, eventTime);
213 }
214 }
215 }
216 } else {
217 // Handle the condition change from the sliced predicate.
218 if (currentUnSlicedPartCondition) {
219 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
220 HashableDimensionKey linkedConditionDimensionKey;
221 getDimensionForCondition(whatIt.first.getValues(),
222 mMetric2ConditionLinks[0],
223 &linkedConditionDimensionKey);
224 if (dimensionsChangedToTrue->find(linkedConditionDimensionKey) !=
225 dimensionsChangedToTrue->end()) {
226 for (auto& condIt : whatIt.second) {
227 condIt.second->onConditionChanged(true, eventTime);
228 }
229 }
230 if (dimensionsChangedToFalse->find(linkedConditionDimensionKey) !=
231 dimensionsChangedToFalse->end()) {
232 for (auto& condIt : whatIt.second) {
233 condIt.second->onConditionChanged(false, eventTime);
234 }
235 }
236 }
237 }
238 }
239}
240
241
242// SlicedConditionChange optimization case 2:
243// 1. If combination condition, logical operation is AND, only one sliced child predicate.
244// 2. Has dimensions_in_condition and it equals to the output dimensions of the sliced predicate.
Yao Chen427d3722018-03-22 15:21:52 -0700245void DurationMetricProducer::onSlicedConditionMayChangeLocked_opt2(bool condition,
Yangster-macb142cc82018-03-30 15:22:08 -0700246 const int64_t eventTime) {
Yangster13fb7e42018-03-07 17:30:49 -0800247 if (mMetric2ConditionLinks.size() > 1 || !mSameConditionDimensionsInTracker) {
248 return;
249 }
250
251 auto dimensionsChangedToTrue = mWizard->getChangedToTrueDimensions(mConditionTrackerIndex);
252 auto dimensionsChangedToFalse = mWizard->getChangedToFalseDimensions(mConditionTrackerIndex);
253
254 bool currentUnSlicedPartCondition = true;
255 if (!mWizard->IsSimpleCondition(mConditionTrackerIndex)) {
256 ConditionState unslicedPartState =
257 mWizard->getUnSlicedPartConditionState(mConditionTrackerIndex);
258 // When the unsliced part is still false, return directly.
259 if (mUnSlicedPartCondition == ConditionState::kFalse &&
260 unslicedPartState == ConditionState::kFalse) {
261 return;
262 }
263 mUnSlicedPartCondition = unslicedPartState;
264 currentUnSlicedPartCondition = mUnSlicedPartCondition > 0;
265 }
266
267 const std::set<HashableDimensionKey>* trueDimensionsToProcess = nullptr;
268 const std::set<HashableDimensionKey>* falseDimensionsToProcess = nullptr;
269
270 std::set<HashableDimensionKey> currentTrueConditionDimensions;
271 if (dimensionsChangedToTrue == nullptr || dimensionsChangedToFalse == nullptr ||
272 (dimensionsChangedToTrue->empty() && dimensionsChangedToFalse->empty())) {
273 mWizard->getTrueSlicedDimensions(mConditionTrackerIndex, &currentTrueConditionDimensions);
274 trueDimensionsToProcess = &currentTrueConditionDimensions;
275 } else if (currentUnSlicedPartCondition) {
276 // Handles the condition change from the sliced predicate. If the unsliced condition state
277 // is not true, not need to do anything.
278 trueDimensionsToProcess = dimensionsChangedToTrue;
279 falseDimensionsToProcess = dimensionsChangedToFalse;
280 }
281
282 if (trueDimensionsToProcess == nullptr && falseDimensionsToProcess == nullptr) {
283 return;
284 }
285
286 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
287 if (falseDimensionsToProcess != nullptr) {
288 for (const auto& changedDim : *falseDimensionsToProcess) {
289 auto condIt = whatIt.second.find(changedDim);
290 if (condIt != whatIt.second.end()) {
291 condIt->second->onConditionChanged(false, eventTime);
292 }
293 }
294 }
295 if (trueDimensionsToProcess != nullptr) {
296 HashableDimensionKey linkedConditionDimensionKey;
297 if (!trueDimensionsToProcess->empty() && mMetric2ConditionLinks.size() == 1) {
298 getDimensionForCondition(whatIt.first.getValues(),
299 mMetric2ConditionLinks[0],
300 &linkedConditionDimensionKey);
301 }
302 for (auto& trueDim : *trueDimensionsToProcess) {
303 auto condIt = whatIt.second.find(trueDim);
304 if (condIt != whatIt.second.end()) {
305 condIt->second->onConditionChanged(
306 currentUnSlicedPartCondition, eventTime);
307 } else {
308 if (mMetric2ConditionLinks.size() == 0 ||
309 trueDim.contains(linkedConditionDimensionKey)) {
310 if (!whatIt.second.empty()) {
Yangster-mac306ccc22018-03-24 15:03:40 -0700311 auto newEventKey = MetricDimensionKey(whatIt.first, trueDim);
312 if (hitGuardRailLocked(newEventKey)) {
313 continue;
314 }
Yangster13fb7e42018-03-07 17:30:49 -0800315 unique_ptr<DurationTracker> newTracker =
316 whatIt.second.begin()->second->clone(eventTime);
317 if (newTracker != nullptr) {
Yangster-mac306ccc22018-03-24 15:03:40 -0700318 newTracker->setEventKey(newEventKey);
Yangster13fb7e42018-03-07 17:30:49 -0800319 newTracker->onConditionChanged(true, eventTime);
320 whatIt.second[trueDim] = std::move(newTracker);
321 }
322 }
323 }
324 }
325 }
326 }
Yao Chen5154a372017-10-30 22:57:06 -0700327 }
328}
329
Yao Chen427d3722018-03-22 15:21:52 -0700330void DurationMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
Yangster-macb142cc82018-03-30 15:22:08 -0700331 const int64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800332 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Yangsterf2bee6f2017-11-29 12:01:05 -0800333 flushIfNeededLocked(eventTime);
Yangster-mac93694462018-01-22 20:49:31 -0800334
Yangster13fb7e42018-03-07 17:30:49 -0800335 if (!mConditionSliced) {
336 return;
337 }
338
339 bool changeDimTrackable = mWizard->IsChangedDimensionTrackable(mConditionTrackerIndex);
340 if (changeDimTrackable && mHasLinksToAllConditionDimensionsInTracker &&
341 mDimensionsInCondition.empty()) {
Yao Chen427d3722018-03-22 15:21:52 -0700342 onSlicedConditionMayChangeLocked_opt1(overallCondition, eventTime);
Yangster13fb7e42018-03-07 17:30:49 -0800343 return;
344 }
345
346 if (changeDimTrackable && mSameConditionDimensionsInTracker &&
347 mMetric2ConditionLinks.size() <= 1) {
Yao Chen427d3722018-03-22 15:21:52 -0700348 onSlicedConditionMayChangeLocked_opt2(overallCondition, eventTime);
Yangster13fb7e42018-03-07 17:30:49 -0800349 return;
350 }
351
Yao Chen729093d2017-10-16 10:33:26 -0700352 // Now for each of the on-going event, check if the condition has changed for them.
Yangster-mac53928882018-02-25 23:02:56 -0800353 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
354 for (auto& pair : whatIt.second) {
Yao Chen427d3722018-03-22 15:21:52 -0700355 pair.second->onSlicedConditionMayChange(overallCondition, eventTime);
Yangster-mac53928882018-02-25 23:02:56 -0800356 }
Yao Chen729093d2017-10-16 10:33:26 -0700357 }
Yangster-mac93694462018-01-22 20:49:31 -0800358
Yangster-mac53928882018-02-25 23:02:56 -0800359 if (mDimensionsInCondition.empty()) {
360 return;
Yangster-mac93694462018-01-22 20:49:31 -0800361 }
Yangster-mac53928882018-02-25 23:02:56 -0800362
363 if (mMetric2ConditionLinks.empty()) {
364 std::unordered_set<HashableDimensionKey> conditionDimensionsKeySet;
365 mWizard->getMetConditionDimension(mConditionTrackerIndex, mDimensionsInCondition,
Yangster13fb7e42018-03-07 17:30:49 -0800366 !mSameConditionDimensionsInTracker,
Yangster-mac53928882018-02-25 23:02:56 -0800367 &conditionDimensionsKeySet);
368 for (const auto& whatIt : mCurrentSlicedDurationTrackerMap) {
369 for (const auto& pair : whatIt.second) {
370 conditionDimensionsKeySet.erase(pair.first);
Yangster-mac93694462018-01-22 20:49:31 -0800371 }
Yangster-mac53928882018-02-25 23:02:56 -0800372 }
373 for (const auto& conditionDimension : conditionDimensionsKeySet) {
374 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
375 if (!whatIt.second.empty()) {
Yangster-mac306ccc22018-03-24 15:03:40 -0700376 auto newEventKey = MetricDimensionKey(whatIt.first, conditionDimension);
377 if (hitGuardRailLocked(newEventKey)) {
378 continue;
379 }
Yangster-mac53928882018-02-25 23:02:56 -0800380 unique_ptr<DurationTracker> newTracker =
381 whatIt.second.begin()->second->clone(eventTime);
Yangster13fb7e42018-03-07 17:30:49 -0800382 if (newTracker != nullptr) {
Yangster-mac306ccc22018-03-24 15:03:40 -0700383 newTracker->setEventKey(MetricDimensionKey(newEventKey));
Yao Chen427d3722018-03-22 15:21:52 -0700384 newTracker->onSlicedConditionMayChange(overallCondition, eventTime);
Yangster13fb7e42018-03-07 17:30:49 -0800385 whatIt.second[conditionDimension] = std::move(newTracker);
386 }
Yangster-mac53928882018-02-25 23:02:56 -0800387 }
388 }
389 }
390 } else {
391 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
392 ConditionKey conditionKey;
393 for (const auto& link : mMetric2ConditionLinks) {
394 getDimensionForCondition(whatIt.first.getValues(), link,
395 &conditionKey[link.conditionId]);
396 }
397 std::unordered_set<HashableDimensionKey> conditionDimensionsKeys;
398 mWizard->query(mConditionTrackerIndex, conditionKey, mDimensionsInCondition,
Yangster13fb7e42018-03-07 17:30:49 -0800399 !mSameConditionDimensionsInTracker,
400 !mHasLinksToAllConditionDimensionsInTracker,
Yangster-mac53928882018-02-25 23:02:56 -0800401 &conditionDimensionsKeys);
402
403 for (const auto& conditionDimension : conditionDimensionsKeys) {
404 if (!whatIt.second.empty() &&
405 whatIt.second.find(conditionDimension) == whatIt.second.end()) {
Yangster-mac306ccc22018-03-24 15:03:40 -0700406 auto newEventKey = MetricDimensionKey(whatIt.first, conditionDimension);
407 if (hitGuardRailLocked(newEventKey)) {
408 continue;
409 }
Yangster-mac53928882018-02-25 23:02:56 -0800410 auto newTracker = whatIt.second.begin()->second->clone(eventTime);
Yangster13fb7e42018-03-07 17:30:49 -0800411 if (newTracker != nullptr) {
Yangster-mac306ccc22018-03-24 15:03:40 -0700412 newTracker->setEventKey(newEventKey);
Yao Chen427d3722018-03-22 15:21:52 -0700413 newTracker->onSlicedConditionMayChange(overallCondition, eventTime);
Yangster13fb7e42018-03-07 17:30:49 -0800414 whatIt.second[conditionDimension] = std::move(newTracker);
415 }
Yangster-mac53928882018-02-25 23:02:56 -0800416 }
417 }
Yangster-mac93694462018-01-22 20:49:31 -0800418 }
419 }
Yao Chen729093d2017-10-16 10:33:26 -0700420}
421
Yangsterf2bee6f2017-11-29 12:01:05 -0800422void DurationMetricProducer::onConditionChangedLocked(const bool conditionMet,
Yangster-macb142cc82018-03-30 15:22:08 -0700423 const int64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800424 VLOG("Metric %lld onConditionChanged", (long long)mMetricId);
Yao Chen729093d2017-10-16 10:33:26 -0700425 mCondition = conditionMet;
Yangsterf2bee6f2017-11-29 12:01:05 -0800426 flushIfNeededLocked(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700427 // TODO: need to populate the condition change time from the event which triggers the condition
428 // change, instead of using current time.
Yangster-mac53928882018-02-25 23:02:56 -0800429 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
430 for (auto& pair : whatIt.second) {
431 pair.second->onConditionChanged(conditionMet, eventTime);
432 }
Yao Chen729093d2017-10-16 10:33:26 -0700433 }
434}
435
Yangster-macb142cc82018-03-30 15:22:08 -0700436void DurationMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
Yao Chen06dba5d2018-01-26 13:38:16 -0800437 flushIfNeededLocked(dropTimeNs);
438 mPastBuckets.clear();
439}
440
Yangster-macb142cc82018-03-30 15:22:08 -0700441void DurationMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
Yao Chen288c6002017-12-12 13:43:18 -0800442 ProtoOutputStream* protoOutput) {
443 flushIfNeededLocked(dumpTimeNs);
Yangster-mac635b4b32018-01-23 20:17:35 -0800444 if (mPastBuckets.empty()) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800445 VLOG(" Duration metric, empty return");
Yangster-mac635b4b32018-01-23 20:17:35 -0800446 return;
447 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000448
Yangster-mac94e197c2018-01-02 16:03:03 -0800449 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Yi Jin5ee07872018-03-05 18:18:27 -0800450 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DURATION_METRICS);
Yao Chen288c6002017-12-12 13:43:18 -0800451
Yao Chen8a8d16c2018-02-08 14:50:40 -0800452 VLOG("Duration metric %lld dump report now...", (long long)mMetricId);
Yao Chen6a8c7992017-11-29 20:02:07 +0000453
Yao Chen729093d2017-10-16 10:33:26 -0700454 for (const auto& pair : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800455 const MetricDimensionKey& dimensionKey = pair.first;
Yangster13fb7e42018-03-07 17:30:49 -0800456 VLOG(" dimension key %s", dimensionKey.toString().c_str());
Yao Chen1ff4f432017-11-16 17:01:40 -0800457
Yi Jin5ee07872018-03-05 18:18:27 -0800458 uint64_t wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800459 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
yro2b0f8862017-11-06 14:27:31 -0800460
Yangster-mac20877162017-12-22 17:19:39 -0800461 // First fill dimension.
Yi Jin5ee07872018-03-05 18:18:27 -0800462 uint64_t dimensionToken = protoOutput->start(
Yangster-mac468ff042018-01-17 12:26:34 -0800463 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
Yao Chen8a8d16c2018-02-08 14:50:40 -0800464 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), protoOutput);
Yangster-mac20877162017-12-22 17:19:39 -0800465 protoOutput->end(dimensionToken);
yro2b0f8862017-11-06 14:27:31 -0800466
Yangster-mac93694462018-01-22 20:49:31 -0800467 if (dimensionKey.hasDimensionKeyInCondition()) {
Yi Jin5ee07872018-03-05 18:18:27 -0800468 uint64_t dimensionInConditionToken = protoOutput->start(
Yangster-mac93694462018-01-22 20:49:31 -0800469 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
Yao Chen8a8d16c2018-02-08 14:50:40 -0800470 writeDimensionToProto(dimensionKey.getDimensionKeyInCondition(), protoOutput);
Yangster-mac93694462018-01-22 20:49:31 -0800471 protoOutput->end(dimensionInConditionToken);
472 }
473
yro2b0f8862017-11-06 14:27:31 -0800474 // Then fill bucket_info (DurationBucketInfo).
475 for (const auto& bucket : pair.second) {
Yi Jin5ee07872018-03-05 18:18:27 -0800476 uint64_t bucketInfoToken = protoOutput->start(
Yao Chen288c6002017-12-12 13:43:18 -0800477 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
Yangster-mac330af582018-02-08 15:24:38 -0800478 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_NANOS,
Yao Chen288c6002017-12-12 13:43:18 -0800479 (long long)bucket.mBucketStartNs);
Yangster-mac330af582018-02-08 15:24:38 -0800480 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_NANOS,
Yao Chen288c6002017-12-12 13:43:18 -0800481 (long long)bucket.mBucketEndNs);
482 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_DURATION, (long long)bucket.mDuration);
483 protoOutput->end(bucketInfoToken);
yro2b0f8862017-11-06 14:27:31 -0800484 VLOG("\t bucket [%lld - %lld] duration: %lld", (long long)bucket.mBucketStartNs,
485 (long long)bucket.mBucketEndNs, (long long)bucket.mDuration);
486 }
487
Yao Chen288c6002017-12-12 13:43:18 -0800488 protoOutput->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700489 }
yro2b0f8862017-11-06 14:27:31 -0800490
Yao Chen288c6002017-12-12 13:43:18 -0800491 protoOutput->end(protoToken);
Yao Chenf60e0ba2017-11-29 15:06:41 -0800492 mPastBuckets.clear();
yro2b0f8862017-11-06 14:27:31 -0800493}
Yao Chen729093d2017-10-16 10:33:26 -0700494
Yangster-macb142cc82018-03-30 15:22:08 -0700495void DurationMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
496 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800497
498 if (currentBucketEndTimeNs > eventTimeNs) {
Yao Chen729093d2017-10-16 10:33:26 -0700499 return;
500 }
Yao Chen5154a372017-10-30 22:57:06 -0700501 VLOG("flushing...........");
Yangster-mac53928882018-02-25 23:02:56 -0800502 for (auto whatIt = mCurrentSlicedDurationTrackerMap.begin();
503 whatIt != mCurrentSlicedDurationTrackerMap.end();) {
504 for (auto it = whatIt->second.begin(); it != whatIt->second.end();) {
505 if (it->second->flushIfNeeded(eventTimeNs, &mPastBuckets)) {
Yangster13fb7e42018-03-07 17:30:49 -0800506 VLOG("erase bucket for key %s %s",
507 whatIt->first.toString().c_str(), it->first.toString().c_str());
Yangster-mac53928882018-02-25 23:02:56 -0800508 it = whatIt->second.erase(it);
509 } else {
510 ++it;
511 }
512 }
513 if (whatIt->second.empty()) {
514 whatIt = mCurrentSlicedDurationTrackerMap.erase(whatIt);
Yao Chend41c4222017-11-15 19:26:14 -0800515 } else {
Yangster-mac53928882018-02-25 23:02:56 -0800516 whatIt++;
Yao Chen729093d2017-10-16 10:33:26 -0700517 }
518 }
Yao Chen5154a372017-10-30 22:57:06 -0700519
David Chen27785a82018-01-19 17:06:45 -0800520 int numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
521 mCurrentBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800522 mCurrentBucketNum += numBucketsForward;
Yao Chen5154a372017-10-30 22:57:06 -0700523}
524
Yangster-macb142cc82018-03-30 15:22:08 -0700525void DurationMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs) {
Yangster-mac53928882018-02-25 23:02:56 -0800526 for (auto whatIt = mCurrentSlicedDurationTrackerMap.begin();
527 whatIt != mCurrentSlicedDurationTrackerMap.end();) {
528 for (auto it = whatIt->second.begin(); it != whatIt->second.end();) {
529 if (it->second->flushCurrentBucket(eventTimeNs, &mPastBuckets)) {
Yangster13fb7e42018-03-07 17:30:49 -0800530 VLOG("erase bucket for key %s %s", whatIt->first.toString().c_str(),
531 it->first.toString().c_str());
Yangster-mac53928882018-02-25 23:02:56 -0800532 it = whatIt->second.erase(it);
533 } else {
534 ++it;
535 }
536 }
537 if (whatIt->second.empty()) {
538 whatIt = mCurrentSlicedDurationTrackerMap.erase(whatIt);
David Chen27785a82018-01-19 17:06:45 -0800539 } else {
Yangster-mac53928882018-02-25 23:02:56 -0800540 whatIt++;
David Chen27785a82018-01-19 17:06:45 -0800541 }
542 }
543}
544
Yao Chen884c8c12018-01-26 10:36:25 -0800545void DurationMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
Yangster-mac93694462018-01-22 20:49:31 -0800546 if (mCurrentSlicedDurationTrackerMap.size() == 0) {
Yao Chen884c8c12018-01-26 10:36:25 -0800547 return;
548 }
549
550 fprintf(out, "DurationMetric %lld dimension size %lu\n", (long long)mMetricId,
Yangster-mac93694462018-01-22 20:49:31 -0800551 (unsigned long)mCurrentSlicedDurationTrackerMap.size());
Yao Chen884c8c12018-01-26 10:36:25 -0800552 if (verbose) {
Yangster-mac53928882018-02-25 23:02:56 -0800553 for (const auto& whatIt : mCurrentSlicedDurationTrackerMap) {
554 for (const auto& slice : whatIt.second) {
Yangster13fb7e42018-03-07 17:30:49 -0800555 fprintf(out, "\t(what)%s\t(condition)%s\n", whatIt.first.toString().c_str(),
556 slice.first.toString().c_str());
Yangster-mac53928882018-02-25 23:02:56 -0800557 slice.second->dumpStates(out, verbose);
558 }
Yao Chen884c8c12018-01-26 10:36:25 -0800559 }
560 }
561}
562
Yangster-mac93694462018-01-22 20:49:31 -0800563bool DurationMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yangster-mac306ccc22018-03-24 15:03:40 -0700564 auto whatIt = mCurrentSlicedDurationTrackerMap.find(newKey.getDimensionKeyInWhat());
565 if (whatIt != mCurrentSlicedDurationTrackerMap.end()) {
566 auto condIt = whatIt->second.find(newKey.getDimensionKeyInCondition());
567 if (condIt != whatIt->second.end()) {
568 return false;
569 }
570 if (whatIt->second.size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
571 size_t newTupleCount = whatIt->second.size() + 1;
572 StatsdStats::getInstance().noteMetricDimensionInConditionSize(
573 mConfigKey, mMetricId, newTupleCount);
574 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
575 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
576 ALOGE("DurationMetric %lld dropping data for condition dimension key %s",
577 (long long)mMetricId, newKey.getDimensionKeyInCondition().toString().c_str());
578 return true;
579 }
580 }
581 } else {
582 // 1. Report the tuple count if the tuple count > soft limit
583 if (mCurrentSlicedDurationTrackerMap.size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
584 size_t newTupleCount = mCurrentSlicedDurationTrackerMap.size() + 1;
585 StatsdStats::getInstance().noteMetricDimensionSize(
586 mConfigKey, mMetricId, newTupleCount);
587 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
588 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
589 ALOGE("DurationMetric %lld dropping data for what dimension key %s",
590 (long long)mMetricId, newKey.getDimensionKeyInWhat().toString().c_str());
591 return true;
592 }
Yao Chenb3561512017-11-21 18:07:17 -0800593 }
594 }
595 return false;
596}
597
Yangster-mac53928882018-02-25 23:02:56 -0800598void DurationMetricProducer::handleStartEvent(const MetricDimensionKey& eventKey,
599 const ConditionKey& conditionKeys,
600 bool condition, const LogEvent& event) {
601 const auto& whatKey = eventKey.getDimensionKeyInWhat();
602 const auto& condKey = eventKey.getDimensionKeyInCondition();
Yao Chen5154a372017-10-30 22:57:06 -0700603
Yangster-mac53928882018-02-25 23:02:56 -0800604 auto whatIt = mCurrentSlicedDurationTrackerMap.find(whatKey);
605 if (whatIt == mCurrentSlicedDurationTrackerMap.end()) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800606 if (hitGuardRailLocked(eventKey)) {
Yao Chenb3561512017-11-21 18:07:17 -0800607 return;
608 }
Yangster-mac53928882018-02-25 23:02:56 -0800609 mCurrentSlicedDurationTrackerMap[whatKey][condKey] = createDurationTracker(eventKey);
610 } else {
611 if (whatIt->second.find(condKey) == whatIt->second.end()) {
612 if (hitGuardRailLocked(eventKey)) {
613 return;
614 }
615 mCurrentSlicedDurationTrackerMap[whatKey][condKey] = createDurationTracker(eventKey);
616 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000617 }
Yao Chen5154a372017-10-30 22:57:06 -0700618
Yangster-mac53928882018-02-25 23:02:56 -0800619 auto it = mCurrentSlicedDurationTrackerMap.find(whatKey)->second.find(condKey);
620 if (mUseWhatDimensionAsInternalDimension) {
621 it->second->noteStart(whatKey, condition,
622 event.GetElapsedTimestampNs(), conditionKeys);
623 return;
624 }
Yao Chen5154a372017-10-30 22:57:06 -0700625
Yangster13fb7e42018-03-07 17:30:49 -0800626 if (mInternalDimensions.empty()) {
Yangster-mac53928882018-02-25 23:02:56 -0800627 it->second->noteStart(DEFAULT_DIMENSION_KEY, condition,
628 event.GetElapsedTimestampNs(), conditionKeys);
Yangster-mac20877162017-12-22 17:19:39 -0800629 } else {
Yangster-mace06cfd72018-03-10 23:22:59 -0800630 HashableDimensionKey dimensionKey = DEFAULT_DIMENSION_KEY;
631 filterValues(mInternalDimensions, event.getValues(), &dimensionKey);
632 it->second->noteStart(
633 dimensionKey, condition, event.GetElapsedTimestampNs(), conditionKeys);
Yao Chen5154a372017-10-30 22:57:06 -0700634 }
Yangster-mac20877162017-12-22 17:19:39 -0800635
Yao Chen729093d2017-10-16 10:33:26 -0700636}
637
Yangster-mac53928882018-02-25 23:02:56 -0800638void DurationMetricProducer::onMatchedLogEventInternalLocked(
639 const size_t matcherIndex, const MetricDimensionKey& eventKey,
640 const ConditionKey& conditionKeys, bool condition,
641 const LogEvent& event) {
642 ALOGW("Not used in duration tracker.");
643}
644
Yangster-mace06cfd72018-03-10 23:22:59 -0800645void DurationMetricProducer::onMatchedLogEventLocked(const size_t matcherIndex,
646 const LogEvent& event) {
Yangster-macb142cc82018-03-30 15:22:08 -0700647 int64_t eventTimeNs = event.GetElapsedTimestampNs();
Yangster13fb7e42018-03-07 17:30:49 -0800648 if (eventTimeNs < mStartTimeNs) {
649 return;
650 }
651
652 flushIfNeededLocked(event.GetElapsedTimestampNs());
653
654 // Handles Stopall events.
655 if (matcherIndex == mStopAllIndex) {
656 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
657 for (auto& pair : whatIt.second) {
658 pair.second->noteStopAll(event.GetElapsedTimestampNs());
659 }
660 }
661 return;
662 }
663
664 HashableDimensionKey dimensionInWhat;
665 if (!mDimensionsInWhat.empty()) {
666 filterValues(mDimensionsInWhat, event.getValues(), &dimensionInWhat);
667 } else {
668 dimensionInWhat = DEFAULT_DIMENSION_KEY;
669 }
670
671 // Handles Stop events.
672 if (matcherIndex == mStopIndex) {
673 if (mUseWhatDimensionAsInternalDimension) {
674 auto whatIt = mCurrentSlicedDurationTrackerMap.find(dimensionInWhat);
675 if (whatIt != mCurrentSlicedDurationTrackerMap.end()) {
676 for (const auto& condIt : whatIt->second) {
677 condIt.second->noteStop(dimensionInWhat, event.GetElapsedTimestampNs(), false);
678 }
679 }
680 return;
681 }
682
683 HashableDimensionKey internalDimensionKey = DEFAULT_DIMENSION_KEY;
684 if (!mInternalDimensions.empty()) {
685 filterValues(mInternalDimensions, event.getValues(), &internalDimensionKey);
686 }
687
688 auto whatIt = mCurrentSlicedDurationTrackerMap.find(dimensionInWhat);
689 if (whatIt != mCurrentSlicedDurationTrackerMap.end()) {
690 for (const auto& condIt : whatIt->second) {
691 condIt.second->noteStop(
692 internalDimensionKey, event.GetElapsedTimestampNs(), false);
693 }
694 }
695 return;
696 }
697
698 bool condition;
699 ConditionKey conditionKey;
700 std::unordered_set<HashableDimensionKey> dimensionKeysInCondition;
701 if (mConditionSliced) {
702 for (const auto& link : mMetric2ConditionLinks) {
703 getDimensionForCondition(event.getValues(), link, &conditionKey[link.conditionId]);
704 }
705
706 auto conditionState =
707 mWizard->query(mConditionTrackerIndex, conditionKey, mDimensionsInCondition,
708 !mSameConditionDimensionsInTracker,
709 !mHasLinksToAllConditionDimensionsInTracker,
710 &dimensionKeysInCondition);
711 condition = (conditionState == ConditionState::kTrue);
712 if (mDimensionsInCondition.empty() && condition) {
713 dimensionKeysInCondition.insert(DEFAULT_DIMENSION_KEY);
714 }
715 } else {
716 condition = mCondition;
717 if (condition) {
718 dimensionKeysInCondition.insert(DEFAULT_DIMENSION_KEY);
719 }
720 }
721
722 if (dimensionKeysInCondition.empty()) {
723 handleStartEvent(MetricDimensionKey(dimensionInWhat, DEFAULT_DIMENSION_KEY),
724 conditionKey, condition, event);
725 } else {
726 auto whatIt = mCurrentSlicedDurationTrackerMap.find(dimensionInWhat);
727 // If the what dimension is already there, we should update all the trackers even
728 // the condition is false.
729 if (whatIt != mCurrentSlicedDurationTrackerMap.end()) {
730 for (const auto& condIt : whatIt->second) {
731 const bool cond = dimensionKeysInCondition.find(condIt.first) !=
732 dimensionKeysInCondition.end();
733 handleStartEvent(MetricDimensionKey(dimensionInWhat, condIt.first),
734 conditionKey, cond, event);
735 dimensionKeysInCondition.erase(condIt.first);
736 }
737 }
738 for (const auto& conditionDimension : dimensionKeysInCondition) {
739 handleStartEvent(MetricDimensionKey(dimensionInWhat, conditionDimension), conditionKey,
740 condition, event);
741 }
742 }
743}
744
Yangsterf2bee6f2017-11-29 12:01:05 -0800745size_t DurationMetricProducer::byteSizeLocked() const {
Yangster7c334a12017-11-22 14:24:24 -0800746 size_t totalSize = 0;
747 for (const auto& pair : mPastBuckets) {
748 totalSize += pair.second.size() * kBucketSize;
749 }
750 return totalSize;
yro69007c82017-10-26 20:42:57 -0700751}
752
Yao Chen729093d2017-10-16 10:33:26 -0700753} // namespace statsd
754} // namespace os
755} // namespace android