blob: c28bb8800e20af11ea616ed47778a4f9c57570d7 [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,
Yao Chen93fe3a32017-11-02 13:52:59 -070064 const uint64_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,
173 const uint64_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,
246 const uint64_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()) {
311 unique_ptr<DurationTracker> newTracker =
312 whatIt.second.begin()->second->clone(eventTime);
313 if (newTracker != nullptr) {
314 newTracker->setEventKey(
315 MetricDimensionKey(whatIt.first, trueDim));
316 newTracker->onConditionChanged(true, eventTime);
317 whatIt.second[trueDim] = std::move(newTracker);
318 }
319 }
320 }
321 }
322 }
323 }
Yao Chen5154a372017-10-30 22:57:06 -0700324 }
325}
326
Yao Chen427d3722018-03-22 15:21:52 -0700327void DurationMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
328 const uint64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800329 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Yangsterf2bee6f2017-11-29 12:01:05 -0800330 flushIfNeededLocked(eventTime);
Yangster-mac93694462018-01-22 20:49:31 -0800331
Yangster13fb7e42018-03-07 17:30:49 -0800332 if (!mConditionSliced) {
333 return;
334 }
335
336 bool changeDimTrackable = mWizard->IsChangedDimensionTrackable(mConditionTrackerIndex);
337 if (changeDimTrackable && mHasLinksToAllConditionDimensionsInTracker &&
338 mDimensionsInCondition.empty()) {
Yao Chen427d3722018-03-22 15:21:52 -0700339 onSlicedConditionMayChangeLocked_opt1(overallCondition, eventTime);
Yangster13fb7e42018-03-07 17:30:49 -0800340 return;
341 }
342
343 if (changeDimTrackable && mSameConditionDimensionsInTracker &&
344 mMetric2ConditionLinks.size() <= 1) {
Yao Chen427d3722018-03-22 15:21:52 -0700345 onSlicedConditionMayChangeLocked_opt2(overallCondition, eventTime);
Yangster13fb7e42018-03-07 17:30:49 -0800346 return;
347 }
348
Yao Chen729093d2017-10-16 10:33:26 -0700349 // Now for each of the on-going event, check if the condition has changed for them.
Yangster-mac53928882018-02-25 23:02:56 -0800350 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
351 for (auto& pair : whatIt.second) {
Yao Chen427d3722018-03-22 15:21:52 -0700352 pair.second->onSlicedConditionMayChange(overallCondition, eventTime);
Yangster-mac53928882018-02-25 23:02:56 -0800353 }
Yao Chen729093d2017-10-16 10:33:26 -0700354 }
Yangster-mac93694462018-01-22 20:49:31 -0800355
Yangster-mac53928882018-02-25 23:02:56 -0800356 if (mDimensionsInCondition.empty()) {
357 return;
Yangster-mac93694462018-01-22 20:49:31 -0800358 }
Yangster-mac53928882018-02-25 23:02:56 -0800359
360 if (mMetric2ConditionLinks.empty()) {
361 std::unordered_set<HashableDimensionKey> conditionDimensionsKeySet;
362 mWizard->getMetConditionDimension(mConditionTrackerIndex, mDimensionsInCondition,
Yangster13fb7e42018-03-07 17:30:49 -0800363 !mSameConditionDimensionsInTracker,
Yangster-mac53928882018-02-25 23:02:56 -0800364 &conditionDimensionsKeySet);
365 for (const auto& whatIt : mCurrentSlicedDurationTrackerMap) {
366 for (const auto& pair : whatIt.second) {
367 conditionDimensionsKeySet.erase(pair.first);
Yangster-mac93694462018-01-22 20:49:31 -0800368 }
Yangster-mac53928882018-02-25 23:02:56 -0800369 }
370 for (const auto& conditionDimension : conditionDimensionsKeySet) {
371 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
372 if (!whatIt.second.empty()) {
373 unique_ptr<DurationTracker> newTracker =
374 whatIt.second.begin()->second->clone(eventTime);
Yangster13fb7e42018-03-07 17:30:49 -0800375 if (newTracker != nullptr) {
376 newTracker->setEventKey(MetricDimensionKey(
377 whatIt.first, conditionDimension));
Yao Chen427d3722018-03-22 15:21:52 -0700378 newTracker->onSlicedConditionMayChange(overallCondition, eventTime);
Yangster13fb7e42018-03-07 17:30:49 -0800379 whatIt.second[conditionDimension] = std::move(newTracker);
380 }
Yangster-mac53928882018-02-25 23:02:56 -0800381 }
382 }
383 }
384 } else {
385 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
386 ConditionKey conditionKey;
387 for (const auto& link : mMetric2ConditionLinks) {
388 getDimensionForCondition(whatIt.first.getValues(), link,
389 &conditionKey[link.conditionId]);
390 }
391 std::unordered_set<HashableDimensionKey> conditionDimensionsKeys;
392 mWizard->query(mConditionTrackerIndex, conditionKey, mDimensionsInCondition,
Yangster13fb7e42018-03-07 17:30:49 -0800393 !mSameConditionDimensionsInTracker,
394 !mHasLinksToAllConditionDimensionsInTracker,
Yangster-mac53928882018-02-25 23:02:56 -0800395 &conditionDimensionsKeys);
396
397 for (const auto& conditionDimension : conditionDimensionsKeys) {
398 if (!whatIt.second.empty() &&
399 whatIt.second.find(conditionDimension) == whatIt.second.end()) {
400 auto newTracker = whatIt.second.begin()->second->clone(eventTime);
Yangster13fb7e42018-03-07 17:30:49 -0800401 if (newTracker != nullptr) {
402 newTracker->setEventKey(
403 MetricDimensionKey(whatIt.first, conditionDimension));
Yao Chen427d3722018-03-22 15:21:52 -0700404 newTracker->onSlicedConditionMayChange(overallCondition, eventTime);
Yangster13fb7e42018-03-07 17:30:49 -0800405 whatIt.second[conditionDimension] = std::move(newTracker);
406 }
Yangster-mac53928882018-02-25 23:02:56 -0800407 }
408 }
Yangster-mac93694462018-01-22 20:49:31 -0800409 }
410 }
Yao Chen729093d2017-10-16 10:33:26 -0700411}
412
Yangsterf2bee6f2017-11-29 12:01:05 -0800413void DurationMetricProducer::onConditionChangedLocked(const bool conditionMet,
414 const uint64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800415 VLOG("Metric %lld onConditionChanged", (long long)mMetricId);
Yao Chen729093d2017-10-16 10:33:26 -0700416 mCondition = conditionMet;
Yangsterf2bee6f2017-11-29 12:01:05 -0800417 flushIfNeededLocked(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700418 // TODO: need to populate the condition change time from the event which triggers the condition
419 // change, instead of using current time.
Yangster-mac53928882018-02-25 23:02:56 -0800420 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
421 for (auto& pair : whatIt.second) {
422 pair.second->onConditionChanged(conditionMet, eventTime);
423 }
Yao Chen729093d2017-10-16 10:33:26 -0700424 }
425}
426
Yao Chen06dba5d2018-01-26 13:38:16 -0800427void DurationMetricProducer::dropDataLocked(const uint64_t dropTimeNs) {
428 flushIfNeededLocked(dropTimeNs);
429 mPastBuckets.clear();
430}
431
Yao Chen288c6002017-12-12 13:43:18 -0800432void DurationMetricProducer::onDumpReportLocked(const uint64_t dumpTimeNs,
433 ProtoOutputStream* protoOutput) {
434 flushIfNeededLocked(dumpTimeNs);
Yangster-mac635b4b32018-01-23 20:17:35 -0800435 if (mPastBuckets.empty()) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800436 VLOG(" Duration metric, empty return");
Yangster-mac635b4b32018-01-23 20:17:35 -0800437 return;
438 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000439
Yangster-mac94e197c2018-01-02 16:03:03 -0800440 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Yi Jin5ee07872018-03-05 18:18:27 -0800441 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DURATION_METRICS);
Yao Chen288c6002017-12-12 13:43:18 -0800442
Yao Chen8a8d16c2018-02-08 14:50:40 -0800443 VLOG("Duration metric %lld dump report now...", (long long)mMetricId);
Yao Chen6a8c7992017-11-29 20:02:07 +0000444
Yao Chen729093d2017-10-16 10:33:26 -0700445 for (const auto& pair : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800446 const MetricDimensionKey& dimensionKey = pair.first;
Yangster13fb7e42018-03-07 17:30:49 -0800447 VLOG(" dimension key %s", dimensionKey.toString().c_str());
Yao Chen1ff4f432017-11-16 17:01:40 -0800448
Yi Jin5ee07872018-03-05 18:18:27 -0800449 uint64_t wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800450 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
yro2b0f8862017-11-06 14:27:31 -0800451
Yangster-mac20877162017-12-22 17:19:39 -0800452 // First fill dimension.
Yi Jin5ee07872018-03-05 18:18:27 -0800453 uint64_t dimensionToken = protoOutput->start(
Yangster-mac468ff042018-01-17 12:26:34 -0800454 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
Yao Chen8a8d16c2018-02-08 14:50:40 -0800455 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), protoOutput);
Yangster-mac20877162017-12-22 17:19:39 -0800456 protoOutput->end(dimensionToken);
yro2b0f8862017-11-06 14:27:31 -0800457
Yangster-mac93694462018-01-22 20:49:31 -0800458 if (dimensionKey.hasDimensionKeyInCondition()) {
Yi Jin5ee07872018-03-05 18:18:27 -0800459 uint64_t dimensionInConditionToken = protoOutput->start(
Yangster-mac93694462018-01-22 20:49:31 -0800460 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
Yao Chen8a8d16c2018-02-08 14:50:40 -0800461 writeDimensionToProto(dimensionKey.getDimensionKeyInCondition(), protoOutput);
Yangster-mac93694462018-01-22 20:49:31 -0800462 protoOutput->end(dimensionInConditionToken);
463 }
464
yro2b0f8862017-11-06 14:27:31 -0800465 // Then fill bucket_info (DurationBucketInfo).
466 for (const auto& bucket : pair.second) {
Yi Jin5ee07872018-03-05 18:18:27 -0800467 uint64_t bucketInfoToken = protoOutput->start(
Yao Chen288c6002017-12-12 13:43:18 -0800468 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
Yangster-mac330af582018-02-08 15:24:38 -0800469 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_NANOS,
Yao Chen288c6002017-12-12 13:43:18 -0800470 (long long)bucket.mBucketStartNs);
Yangster-mac330af582018-02-08 15:24:38 -0800471 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_NANOS,
Yao Chen288c6002017-12-12 13:43:18 -0800472 (long long)bucket.mBucketEndNs);
473 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_DURATION, (long long)bucket.mDuration);
474 protoOutput->end(bucketInfoToken);
yro2b0f8862017-11-06 14:27:31 -0800475 VLOG("\t bucket [%lld - %lld] duration: %lld", (long long)bucket.mBucketStartNs,
476 (long long)bucket.mBucketEndNs, (long long)bucket.mDuration);
477 }
478
Yao Chen288c6002017-12-12 13:43:18 -0800479 protoOutput->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700480 }
yro2b0f8862017-11-06 14:27:31 -0800481
Yao Chen288c6002017-12-12 13:43:18 -0800482 protoOutput->end(protoToken);
Yao Chenf60e0ba2017-11-29 15:06:41 -0800483 mPastBuckets.clear();
yro2b0f8862017-11-06 14:27:31 -0800484}
Yao Chen729093d2017-10-16 10:33:26 -0700485
David Chen27785a82018-01-19 17:06:45 -0800486void DurationMetricProducer::flushIfNeededLocked(const uint64_t& eventTimeNs) {
487 uint64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
488
489 if (currentBucketEndTimeNs > eventTimeNs) {
Yao Chen729093d2017-10-16 10:33:26 -0700490 return;
491 }
Yao Chen5154a372017-10-30 22:57:06 -0700492 VLOG("flushing...........");
Yangster-mac53928882018-02-25 23:02:56 -0800493 for (auto whatIt = mCurrentSlicedDurationTrackerMap.begin();
494 whatIt != mCurrentSlicedDurationTrackerMap.end();) {
495 for (auto it = whatIt->second.begin(); it != whatIt->second.end();) {
496 if (it->second->flushIfNeeded(eventTimeNs, &mPastBuckets)) {
Yangster13fb7e42018-03-07 17:30:49 -0800497 VLOG("erase bucket for key %s %s",
498 whatIt->first.toString().c_str(), it->first.toString().c_str());
Yangster-mac53928882018-02-25 23:02:56 -0800499 it = whatIt->second.erase(it);
500 } else {
501 ++it;
502 }
503 }
504 if (whatIt->second.empty()) {
505 whatIt = mCurrentSlicedDurationTrackerMap.erase(whatIt);
Yao Chend41c4222017-11-15 19:26:14 -0800506 } else {
Yangster-mac53928882018-02-25 23:02:56 -0800507 whatIt++;
Yao Chen729093d2017-10-16 10:33:26 -0700508 }
509 }
Yao Chen5154a372017-10-30 22:57:06 -0700510
David Chen27785a82018-01-19 17:06:45 -0800511 int numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
512 mCurrentBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800513 mCurrentBucketNum += numBucketsForward;
Yao Chen5154a372017-10-30 22:57:06 -0700514}
515
David Chen27785a82018-01-19 17:06:45 -0800516void DurationMetricProducer::flushCurrentBucketLocked(const uint64_t& eventTimeNs) {
Yangster-mac53928882018-02-25 23:02:56 -0800517 for (auto whatIt = mCurrentSlicedDurationTrackerMap.begin();
518 whatIt != mCurrentSlicedDurationTrackerMap.end();) {
519 for (auto it = whatIt->second.begin(); it != whatIt->second.end();) {
520 if (it->second->flushCurrentBucket(eventTimeNs, &mPastBuckets)) {
Yangster13fb7e42018-03-07 17:30:49 -0800521 VLOG("erase bucket for key %s %s", whatIt->first.toString().c_str(),
522 it->first.toString().c_str());
Yangster-mac53928882018-02-25 23:02:56 -0800523 it = whatIt->second.erase(it);
524 } else {
525 ++it;
526 }
527 }
528 if (whatIt->second.empty()) {
529 whatIt = mCurrentSlicedDurationTrackerMap.erase(whatIt);
David Chen27785a82018-01-19 17:06:45 -0800530 } else {
Yangster-mac53928882018-02-25 23:02:56 -0800531 whatIt++;
David Chen27785a82018-01-19 17:06:45 -0800532 }
533 }
534}
535
Yao Chen884c8c12018-01-26 10:36:25 -0800536void DurationMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
Yangster-mac93694462018-01-22 20:49:31 -0800537 if (mCurrentSlicedDurationTrackerMap.size() == 0) {
Yao Chen884c8c12018-01-26 10:36:25 -0800538 return;
539 }
540
541 fprintf(out, "DurationMetric %lld dimension size %lu\n", (long long)mMetricId,
Yangster-mac93694462018-01-22 20:49:31 -0800542 (unsigned long)mCurrentSlicedDurationTrackerMap.size());
Yao Chen884c8c12018-01-26 10:36:25 -0800543 if (verbose) {
Yangster-mac53928882018-02-25 23:02:56 -0800544 for (const auto& whatIt : mCurrentSlicedDurationTrackerMap) {
545 for (const auto& slice : whatIt.second) {
Yangster13fb7e42018-03-07 17:30:49 -0800546 fprintf(out, "\t(what)%s\t(condition)%s\n", whatIt.first.toString().c_str(),
547 slice.first.toString().c_str());
Yangster-mac53928882018-02-25 23:02:56 -0800548 slice.second->dumpStates(out, verbose);
549 }
Yao Chen884c8c12018-01-26 10:36:25 -0800550 }
551 }
552}
553
Yangster-mac93694462018-01-22 20:49:31 -0800554bool DurationMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800555 // 1. Report the tuple count if the tuple count > soft limit
Yangster-mac93694462018-01-22 20:49:31 -0800556 if (mCurrentSlicedDurationTrackerMap.size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
557 size_t newTupleCount = mCurrentSlicedDurationTrackerMap.size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800558 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800559 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
560 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800561 ALOGE("DurationMetric %lld dropping data for dimension key %s",
Yangster13fb7e42018-03-07 17:30:49 -0800562 (long long)mMetricId, newKey.toString().c_str());
Yao Chenb3561512017-11-21 18:07:17 -0800563 return true;
564 }
565 }
566 return false;
567}
568
Yangster-mac53928882018-02-25 23:02:56 -0800569void DurationMetricProducer::handleStartEvent(const MetricDimensionKey& eventKey,
570 const ConditionKey& conditionKeys,
571 bool condition, const LogEvent& event) {
572 const auto& whatKey = eventKey.getDimensionKeyInWhat();
573 const auto& condKey = eventKey.getDimensionKeyInCondition();
Yao Chen5154a372017-10-30 22:57:06 -0700574
Yangster-mac53928882018-02-25 23:02:56 -0800575 auto whatIt = mCurrentSlicedDurationTrackerMap.find(whatKey);
576 if (whatIt == mCurrentSlicedDurationTrackerMap.end()) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800577 if (hitGuardRailLocked(eventKey)) {
Yao Chenb3561512017-11-21 18:07:17 -0800578 return;
579 }
Yangster-mac53928882018-02-25 23:02:56 -0800580 mCurrentSlicedDurationTrackerMap[whatKey][condKey] = createDurationTracker(eventKey);
581 } else {
582 if (whatIt->second.find(condKey) == whatIt->second.end()) {
583 if (hitGuardRailLocked(eventKey)) {
584 return;
585 }
586 mCurrentSlicedDurationTrackerMap[whatKey][condKey] = createDurationTracker(eventKey);
587 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000588 }
Yao Chen5154a372017-10-30 22:57:06 -0700589
Yangster-mac53928882018-02-25 23:02:56 -0800590 auto it = mCurrentSlicedDurationTrackerMap.find(whatKey)->second.find(condKey);
591 if (mUseWhatDimensionAsInternalDimension) {
592 it->second->noteStart(whatKey, condition,
593 event.GetElapsedTimestampNs(), conditionKeys);
594 return;
595 }
Yao Chen5154a372017-10-30 22:57:06 -0700596
Yangster13fb7e42018-03-07 17:30:49 -0800597 if (mInternalDimensions.empty()) {
Yangster-mac53928882018-02-25 23:02:56 -0800598 it->second->noteStart(DEFAULT_DIMENSION_KEY, condition,
599 event.GetElapsedTimestampNs(), conditionKeys);
Yangster-mac20877162017-12-22 17:19:39 -0800600 } else {
Yangster-mace06cfd72018-03-10 23:22:59 -0800601 HashableDimensionKey dimensionKey = DEFAULT_DIMENSION_KEY;
602 filterValues(mInternalDimensions, event.getValues(), &dimensionKey);
603 it->second->noteStart(
604 dimensionKey, condition, event.GetElapsedTimestampNs(), conditionKeys);
Yao Chen5154a372017-10-30 22:57:06 -0700605 }
Yangster-mac20877162017-12-22 17:19:39 -0800606
Yao Chen729093d2017-10-16 10:33:26 -0700607}
608
Yangster-mac53928882018-02-25 23:02:56 -0800609void DurationMetricProducer::onMatchedLogEventInternalLocked(
610 const size_t matcherIndex, const MetricDimensionKey& eventKey,
611 const ConditionKey& conditionKeys, bool condition,
612 const LogEvent& event) {
613 ALOGW("Not used in duration tracker.");
614}
615
Yangster-mace06cfd72018-03-10 23:22:59 -0800616void DurationMetricProducer::onMatchedLogEventLocked(const size_t matcherIndex,
617 const LogEvent& event) {
Yangster13fb7e42018-03-07 17:30:49 -0800618 uint64_t eventTimeNs = event.GetElapsedTimestampNs();
619 if (eventTimeNs < mStartTimeNs) {
620 return;
621 }
622
623 flushIfNeededLocked(event.GetElapsedTimestampNs());
624
625 // Handles Stopall events.
626 if (matcherIndex == mStopAllIndex) {
627 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
628 for (auto& pair : whatIt.second) {
629 pair.second->noteStopAll(event.GetElapsedTimestampNs());
630 }
631 }
632 return;
633 }
634
635 HashableDimensionKey dimensionInWhat;
636 if (!mDimensionsInWhat.empty()) {
637 filterValues(mDimensionsInWhat, event.getValues(), &dimensionInWhat);
638 } else {
639 dimensionInWhat = DEFAULT_DIMENSION_KEY;
640 }
641
642 // Handles Stop events.
643 if (matcherIndex == mStopIndex) {
644 if (mUseWhatDimensionAsInternalDimension) {
645 auto whatIt = mCurrentSlicedDurationTrackerMap.find(dimensionInWhat);
646 if (whatIt != mCurrentSlicedDurationTrackerMap.end()) {
647 for (const auto& condIt : whatIt->second) {
648 condIt.second->noteStop(dimensionInWhat, event.GetElapsedTimestampNs(), false);
649 }
650 }
651 return;
652 }
653
654 HashableDimensionKey internalDimensionKey = DEFAULT_DIMENSION_KEY;
655 if (!mInternalDimensions.empty()) {
656 filterValues(mInternalDimensions, event.getValues(), &internalDimensionKey);
657 }
658
659 auto whatIt = mCurrentSlicedDurationTrackerMap.find(dimensionInWhat);
660 if (whatIt != mCurrentSlicedDurationTrackerMap.end()) {
661 for (const auto& condIt : whatIt->second) {
662 condIt.second->noteStop(
663 internalDimensionKey, event.GetElapsedTimestampNs(), false);
664 }
665 }
666 return;
667 }
668
669 bool condition;
670 ConditionKey conditionKey;
671 std::unordered_set<HashableDimensionKey> dimensionKeysInCondition;
672 if (mConditionSliced) {
673 for (const auto& link : mMetric2ConditionLinks) {
674 getDimensionForCondition(event.getValues(), link, &conditionKey[link.conditionId]);
675 }
676
677 auto conditionState =
678 mWizard->query(mConditionTrackerIndex, conditionKey, mDimensionsInCondition,
679 !mSameConditionDimensionsInTracker,
680 !mHasLinksToAllConditionDimensionsInTracker,
681 &dimensionKeysInCondition);
682 condition = (conditionState == ConditionState::kTrue);
683 if (mDimensionsInCondition.empty() && condition) {
684 dimensionKeysInCondition.insert(DEFAULT_DIMENSION_KEY);
685 }
686 } else {
687 condition = mCondition;
688 if (condition) {
689 dimensionKeysInCondition.insert(DEFAULT_DIMENSION_KEY);
690 }
691 }
692
693 if (dimensionKeysInCondition.empty()) {
694 handleStartEvent(MetricDimensionKey(dimensionInWhat, DEFAULT_DIMENSION_KEY),
695 conditionKey, condition, event);
696 } else {
697 auto whatIt = mCurrentSlicedDurationTrackerMap.find(dimensionInWhat);
698 // If the what dimension is already there, we should update all the trackers even
699 // the condition is false.
700 if (whatIt != mCurrentSlicedDurationTrackerMap.end()) {
701 for (const auto& condIt : whatIt->second) {
702 const bool cond = dimensionKeysInCondition.find(condIt.first) !=
703 dimensionKeysInCondition.end();
704 handleStartEvent(MetricDimensionKey(dimensionInWhat, condIt.first),
705 conditionKey, cond, event);
706 dimensionKeysInCondition.erase(condIt.first);
707 }
708 }
709 for (const auto& conditionDimension : dimensionKeysInCondition) {
710 handleStartEvent(MetricDimensionKey(dimensionInWhat, conditionDimension), conditionKey,
711 condition, event);
712 }
713 }
714}
715
Yangsterf2bee6f2017-11-29 12:01:05 -0800716size_t DurationMetricProducer::byteSizeLocked() const {
Yangster7c334a12017-11-22 14:24:24 -0800717 size_t totalSize = 0;
718 for (const auto& pair : mPastBuckets) {
719 totalSize += pair.second.size() * kBucketSize;
720 }
721 return totalSize;
yro69007c82017-10-26 20:42:57 -0700722}
723
Yao Chen729093d2017-10-16 10:33:26 -0700724} // namespace statsd
725} // namespace os
726} // namespace android