blob: c6b9405e424d3e81d52099baf191b07f8eb77fea [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.
172void DurationMetricProducer::onSlicedConditionMayChangeLocked_opt1(const uint64_t eventTime) {
173 if (mMetric2ConditionLinks.size() != 1 ||
174 !mHasLinksToAllConditionDimensionsInTracker ||
175 !mDimensionsInCondition.empty()) {
176 return;
177 }
178
179 bool currentUnSlicedPartCondition = true;
180 if (!mWizard->IsSimpleCondition(mConditionTrackerIndex)) {
181 ConditionState unslicedPartState =
182 mWizard->getUnSlicedPartConditionState(mConditionTrackerIndex);
183 // When the unsliced part is still false, return directly.
184 if (mUnSlicedPartCondition == ConditionState::kFalse &&
185 unslicedPartState == ConditionState::kFalse) {
186 return;
187 }
188 mUnSlicedPartCondition = unslicedPartState;
189 currentUnSlicedPartCondition = mUnSlicedPartCondition > 0;
190 }
191
192 auto dimensionsChangedToTrue = mWizard->getChangedToTrueDimensions(mConditionTrackerIndex);
193 auto dimensionsChangedToFalse = mWizard->getChangedToFalseDimensions(mConditionTrackerIndex);
194
195 // The condition change is from the unsliced predicates.
196 // We need to find out the true dimensions from the sliced predicate and flip their condition
197 // state based on the new unsliced condition state.
198 if (dimensionsChangedToTrue == nullptr || dimensionsChangedToFalse == nullptr ||
199 (dimensionsChangedToTrue->empty() && dimensionsChangedToFalse->empty())) {
200 std::set<HashableDimensionKey> trueConditionDimensions;
201 mWizard->getTrueSlicedDimensions(mConditionTrackerIndex, &trueConditionDimensions);
202 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
203 HashableDimensionKey linkedConditionDimensionKey;
204 getDimensionForCondition(whatIt.first.getValues(),
205 mMetric2ConditionLinks[0],
206 &linkedConditionDimensionKey);
207 if (trueConditionDimensions.find(linkedConditionDimensionKey) !=
208 trueConditionDimensions.end()) {
209 for (auto& condIt : whatIt.second) {
210 condIt.second->onConditionChanged(
211 currentUnSlicedPartCondition, eventTime);
212 }
213 }
214 }
215 } else {
216 // Handle the condition change from the sliced predicate.
217 if (currentUnSlicedPartCondition) {
218 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
219 HashableDimensionKey linkedConditionDimensionKey;
220 getDimensionForCondition(whatIt.first.getValues(),
221 mMetric2ConditionLinks[0],
222 &linkedConditionDimensionKey);
223 if (dimensionsChangedToTrue->find(linkedConditionDimensionKey) !=
224 dimensionsChangedToTrue->end()) {
225 for (auto& condIt : whatIt.second) {
226 condIt.second->onConditionChanged(true, eventTime);
227 }
228 }
229 if (dimensionsChangedToFalse->find(linkedConditionDimensionKey) !=
230 dimensionsChangedToFalse->end()) {
231 for (auto& condIt : whatIt.second) {
232 condIt.second->onConditionChanged(false, eventTime);
233 }
234 }
235 }
236 }
237 }
238}
239
240
241// SlicedConditionChange optimization case 2:
242// 1. If combination condition, logical operation is AND, only one sliced child predicate.
243// 2. Has dimensions_in_condition and it equals to the output dimensions of the sliced predicate.
244void DurationMetricProducer::onSlicedConditionMayChangeLocked_opt2(const uint64_t eventTime) {
245 if (mMetric2ConditionLinks.size() > 1 || !mSameConditionDimensionsInTracker) {
246 return;
247 }
248
249 auto dimensionsChangedToTrue = mWizard->getChangedToTrueDimensions(mConditionTrackerIndex);
250 auto dimensionsChangedToFalse = mWizard->getChangedToFalseDimensions(mConditionTrackerIndex);
251
252 bool currentUnSlicedPartCondition = true;
253 if (!mWizard->IsSimpleCondition(mConditionTrackerIndex)) {
254 ConditionState unslicedPartState =
255 mWizard->getUnSlicedPartConditionState(mConditionTrackerIndex);
256 // When the unsliced part is still false, return directly.
257 if (mUnSlicedPartCondition == ConditionState::kFalse &&
258 unslicedPartState == ConditionState::kFalse) {
259 return;
260 }
261 mUnSlicedPartCondition = unslicedPartState;
262 currentUnSlicedPartCondition = mUnSlicedPartCondition > 0;
263 }
264
265 const std::set<HashableDimensionKey>* trueDimensionsToProcess = nullptr;
266 const std::set<HashableDimensionKey>* falseDimensionsToProcess = nullptr;
267
268 std::set<HashableDimensionKey> currentTrueConditionDimensions;
269 if (dimensionsChangedToTrue == nullptr || dimensionsChangedToFalse == nullptr ||
270 (dimensionsChangedToTrue->empty() && dimensionsChangedToFalse->empty())) {
271 mWizard->getTrueSlicedDimensions(mConditionTrackerIndex, &currentTrueConditionDimensions);
272 trueDimensionsToProcess = &currentTrueConditionDimensions;
273 } else if (currentUnSlicedPartCondition) {
274 // Handles the condition change from the sliced predicate. If the unsliced condition state
275 // is not true, not need to do anything.
276 trueDimensionsToProcess = dimensionsChangedToTrue;
277 falseDimensionsToProcess = dimensionsChangedToFalse;
278 }
279
280 if (trueDimensionsToProcess == nullptr && falseDimensionsToProcess == nullptr) {
281 return;
282 }
283
284 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
285 if (falseDimensionsToProcess != nullptr) {
286 for (const auto& changedDim : *falseDimensionsToProcess) {
287 auto condIt = whatIt.second.find(changedDim);
288 if (condIt != whatIt.second.end()) {
289 condIt->second->onConditionChanged(false, eventTime);
290 }
291 }
292 }
293 if (trueDimensionsToProcess != nullptr) {
294 HashableDimensionKey linkedConditionDimensionKey;
295 if (!trueDimensionsToProcess->empty() && mMetric2ConditionLinks.size() == 1) {
296 getDimensionForCondition(whatIt.first.getValues(),
297 mMetric2ConditionLinks[0],
298 &linkedConditionDimensionKey);
299 }
300 for (auto& trueDim : *trueDimensionsToProcess) {
301 auto condIt = whatIt.second.find(trueDim);
302 if (condIt != whatIt.second.end()) {
303 condIt->second->onConditionChanged(
304 currentUnSlicedPartCondition, eventTime);
305 } else {
306 if (mMetric2ConditionLinks.size() == 0 ||
307 trueDim.contains(linkedConditionDimensionKey)) {
308 if (!whatIt.second.empty()) {
309 unique_ptr<DurationTracker> newTracker =
310 whatIt.second.begin()->second->clone(eventTime);
311 if (newTracker != nullptr) {
312 newTracker->setEventKey(
313 MetricDimensionKey(whatIt.first, trueDim));
314 newTracker->onConditionChanged(true, eventTime);
315 whatIt.second[trueDim] = std::move(newTracker);
316 }
317 }
318 }
319 }
320 }
321 }
Yao Chen5154a372017-10-30 22:57:06 -0700322 }
323}
324
Yangsterf2bee6f2017-11-29 12:01:05 -0800325void DurationMetricProducer::onSlicedConditionMayChangeLocked(const uint64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800326 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Yangsterf2bee6f2017-11-29 12:01:05 -0800327 flushIfNeededLocked(eventTime);
Yangster-mac93694462018-01-22 20:49:31 -0800328
Yangster13fb7e42018-03-07 17:30:49 -0800329 if (!mConditionSliced) {
330 return;
331 }
332
333 bool changeDimTrackable = mWizard->IsChangedDimensionTrackable(mConditionTrackerIndex);
334 if (changeDimTrackable && mHasLinksToAllConditionDimensionsInTracker &&
335 mDimensionsInCondition.empty()) {
336 onSlicedConditionMayChangeLocked_opt1(eventTime);
337 return;
338 }
339
340 if (changeDimTrackable && mSameConditionDimensionsInTracker &&
341 mMetric2ConditionLinks.size() <= 1) {
342 onSlicedConditionMayChangeLocked_opt2(eventTime);
343 return;
344 }
345
Yao Chen729093d2017-10-16 10:33:26 -0700346 // Now for each of the on-going event, check if the condition has changed for them.
Yangster-mac53928882018-02-25 23:02:56 -0800347 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
348 for (auto& pair : whatIt.second) {
349 pair.second->onSlicedConditionMayChange(eventTime);
350 }
Yao Chen729093d2017-10-16 10:33:26 -0700351 }
Yangster-mac93694462018-01-22 20:49:31 -0800352
Yangster-mac53928882018-02-25 23:02:56 -0800353 if (mDimensionsInCondition.empty()) {
354 return;
Yangster-mac93694462018-01-22 20:49:31 -0800355 }
Yangster-mac53928882018-02-25 23:02:56 -0800356
357 if (mMetric2ConditionLinks.empty()) {
358 std::unordered_set<HashableDimensionKey> conditionDimensionsKeySet;
359 mWizard->getMetConditionDimension(mConditionTrackerIndex, mDimensionsInCondition,
Yangster13fb7e42018-03-07 17:30:49 -0800360 !mSameConditionDimensionsInTracker,
Yangster-mac53928882018-02-25 23:02:56 -0800361 &conditionDimensionsKeySet);
362 for (const auto& whatIt : mCurrentSlicedDurationTrackerMap) {
363 for (const auto& pair : whatIt.second) {
364 conditionDimensionsKeySet.erase(pair.first);
Yangster-mac93694462018-01-22 20:49:31 -0800365 }
Yangster-mac53928882018-02-25 23:02:56 -0800366 }
367 for (const auto& conditionDimension : conditionDimensionsKeySet) {
368 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
369 if (!whatIt.second.empty()) {
370 unique_ptr<DurationTracker> newTracker =
371 whatIt.second.begin()->second->clone(eventTime);
Yangster13fb7e42018-03-07 17:30:49 -0800372 if (newTracker != nullptr) {
373 newTracker->setEventKey(MetricDimensionKey(
374 whatIt.first, conditionDimension));
375 newTracker->onSlicedConditionMayChange(eventTime);
376 whatIt.second[conditionDimension] = std::move(newTracker);
377 }
Yangster-mac53928882018-02-25 23:02:56 -0800378 }
379 }
380 }
381 } else {
382 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
383 ConditionKey conditionKey;
384 for (const auto& link : mMetric2ConditionLinks) {
385 getDimensionForCondition(whatIt.first.getValues(), link,
386 &conditionKey[link.conditionId]);
387 }
388 std::unordered_set<HashableDimensionKey> conditionDimensionsKeys;
389 mWizard->query(mConditionTrackerIndex, conditionKey, mDimensionsInCondition,
Yangster13fb7e42018-03-07 17:30:49 -0800390 !mSameConditionDimensionsInTracker,
391 !mHasLinksToAllConditionDimensionsInTracker,
Yangster-mac53928882018-02-25 23:02:56 -0800392 &conditionDimensionsKeys);
393
394 for (const auto& conditionDimension : conditionDimensionsKeys) {
395 if (!whatIt.second.empty() &&
396 whatIt.second.find(conditionDimension) == whatIt.second.end()) {
397 auto newTracker = whatIt.second.begin()->second->clone(eventTime);
Yangster13fb7e42018-03-07 17:30:49 -0800398 if (newTracker != nullptr) {
399 newTracker->setEventKey(
400 MetricDimensionKey(whatIt.first, conditionDimension));
401 newTracker->onSlicedConditionMayChange(eventTime);
402 whatIt.second[conditionDimension] = std::move(newTracker);
403 }
Yangster-mac53928882018-02-25 23:02:56 -0800404 }
405 }
Yangster-mac93694462018-01-22 20:49:31 -0800406 }
407 }
Yao Chen729093d2017-10-16 10:33:26 -0700408}
409
Yangsterf2bee6f2017-11-29 12:01:05 -0800410void DurationMetricProducer::onConditionChangedLocked(const bool conditionMet,
411 const uint64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800412 VLOG("Metric %lld onConditionChanged", (long long)mMetricId);
Yao Chen729093d2017-10-16 10:33:26 -0700413 mCondition = conditionMet;
Yangsterf2bee6f2017-11-29 12:01:05 -0800414 flushIfNeededLocked(eventTime);
Yao Chen729093d2017-10-16 10:33:26 -0700415 // TODO: need to populate the condition change time from the event which triggers the condition
416 // change, instead of using current time.
Yangster-mac53928882018-02-25 23:02:56 -0800417 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
418 for (auto& pair : whatIt.second) {
419 pair.second->onConditionChanged(conditionMet, eventTime);
420 }
Yao Chen729093d2017-10-16 10:33:26 -0700421 }
422}
423
Yao Chen06dba5d2018-01-26 13:38:16 -0800424void DurationMetricProducer::dropDataLocked(const uint64_t dropTimeNs) {
425 flushIfNeededLocked(dropTimeNs);
426 mPastBuckets.clear();
427}
428
Yao Chen288c6002017-12-12 13:43:18 -0800429void DurationMetricProducer::onDumpReportLocked(const uint64_t dumpTimeNs,
430 ProtoOutputStream* protoOutput) {
431 flushIfNeededLocked(dumpTimeNs);
Yangster-mac635b4b32018-01-23 20:17:35 -0800432 if (mPastBuckets.empty()) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800433 VLOG(" Duration metric, empty return");
Yangster-mac635b4b32018-01-23 20:17:35 -0800434 return;
435 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000436
Yangster-mac94e197c2018-01-02 16:03:03 -0800437 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Yi Jin5ee07872018-03-05 18:18:27 -0800438 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DURATION_METRICS);
Yao Chen288c6002017-12-12 13:43:18 -0800439
Yao Chen8a8d16c2018-02-08 14:50:40 -0800440 VLOG("Duration metric %lld dump report now...", (long long)mMetricId);
Yao Chen6a8c7992017-11-29 20:02:07 +0000441
Yao Chen729093d2017-10-16 10:33:26 -0700442 for (const auto& pair : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800443 const MetricDimensionKey& dimensionKey = pair.first;
Yangster13fb7e42018-03-07 17:30:49 -0800444 VLOG(" dimension key %s", dimensionKey.toString().c_str());
Yao Chen1ff4f432017-11-16 17:01:40 -0800445
Yi Jin5ee07872018-03-05 18:18:27 -0800446 uint64_t wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800447 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
yro2b0f8862017-11-06 14:27:31 -0800448
Yangster-mac20877162017-12-22 17:19:39 -0800449 // First fill dimension.
Yi Jin5ee07872018-03-05 18:18:27 -0800450 uint64_t dimensionToken = protoOutput->start(
Yangster-mac468ff042018-01-17 12:26:34 -0800451 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
Yao Chen8a8d16c2018-02-08 14:50:40 -0800452 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), protoOutput);
Yangster-mac20877162017-12-22 17:19:39 -0800453 protoOutput->end(dimensionToken);
yro2b0f8862017-11-06 14:27:31 -0800454
Yangster-mac93694462018-01-22 20:49:31 -0800455 if (dimensionKey.hasDimensionKeyInCondition()) {
Yi Jin5ee07872018-03-05 18:18:27 -0800456 uint64_t dimensionInConditionToken = protoOutput->start(
Yangster-mac93694462018-01-22 20:49:31 -0800457 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
Yao Chen8a8d16c2018-02-08 14:50:40 -0800458 writeDimensionToProto(dimensionKey.getDimensionKeyInCondition(), protoOutput);
Yangster-mac93694462018-01-22 20:49:31 -0800459 protoOutput->end(dimensionInConditionToken);
460 }
461
yro2b0f8862017-11-06 14:27:31 -0800462 // Then fill bucket_info (DurationBucketInfo).
463 for (const auto& bucket : pair.second) {
Yi Jin5ee07872018-03-05 18:18:27 -0800464 uint64_t bucketInfoToken = protoOutput->start(
Yao Chen288c6002017-12-12 13:43:18 -0800465 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
Yangster-mac330af582018-02-08 15:24:38 -0800466 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_NANOS,
Yao Chen288c6002017-12-12 13:43:18 -0800467 (long long)bucket.mBucketStartNs);
Yangster-mac330af582018-02-08 15:24:38 -0800468 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_NANOS,
Yao Chen288c6002017-12-12 13:43:18 -0800469 (long long)bucket.mBucketEndNs);
470 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_DURATION, (long long)bucket.mDuration);
471 protoOutput->end(bucketInfoToken);
yro2b0f8862017-11-06 14:27:31 -0800472 VLOG("\t bucket [%lld - %lld] duration: %lld", (long long)bucket.mBucketStartNs,
473 (long long)bucket.mBucketEndNs, (long long)bucket.mDuration);
474 }
475
Yao Chen288c6002017-12-12 13:43:18 -0800476 protoOutput->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700477 }
yro2b0f8862017-11-06 14:27:31 -0800478
Yao Chen288c6002017-12-12 13:43:18 -0800479 protoOutput->end(protoToken);
Yao Chenf60e0ba2017-11-29 15:06:41 -0800480 mPastBuckets.clear();
yro2b0f8862017-11-06 14:27:31 -0800481}
Yao Chen729093d2017-10-16 10:33:26 -0700482
David Chen27785a82018-01-19 17:06:45 -0800483void DurationMetricProducer::flushIfNeededLocked(const uint64_t& eventTimeNs) {
484 uint64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
485
486 if (currentBucketEndTimeNs > eventTimeNs) {
Yao Chen729093d2017-10-16 10:33:26 -0700487 return;
488 }
Yao Chen5154a372017-10-30 22:57:06 -0700489 VLOG("flushing...........");
Yangster-mac53928882018-02-25 23:02:56 -0800490 for (auto whatIt = mCurrentSlicedDurationTrackerMap.begin();
491 whatIt != mCurrentSlicedDurationTrackerMap.end();) {
492 for (auto it = whatIt->second.begin(); it != whatIt->second.end();) {
493 if (it->second->flushIfNeeded(eventTimeNs, &mPastBuckets)) {
Yangster13fb7e42018-03-07 17:30:49 -0800494 VLOG("erase bucket for key %s %s",
495 whatIt->first.toString().c_str(), it->first.toString().c_str());
Yangster-mac53928882018-02-25 23:02:56 -0800496 it = whatIt->second.erase(it);
497 } else {
498 ++it;
499 }
500 }
501 if (whatIt->second.empty()) {
502 whatIt = mCurrentSlicedDurationTrackerMap.erase(whatIt);
Yao Chend41c4222017-11-15 19:26:14 -0800503 } else {
Yangster-mac53928882018-02-25 23:02:56 -0800504 whatIt++;
Yao Chen729093d2017-10-16 10:33:26 -0700505 }
506 }
Yao Chen5154a372017-10-30 22:57:06 -0700507
David Chen27785a82018-01-19 17:06:45 -0800508 int numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
509 mCurrentBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800510 mCurrentBucketNum += numBucketsForward;
Yao Chen5154a372017-10-30 22:57:06 -0700511}
512
David Chen27785a82018-01-19 17:06:45 -0800513void DurationMetricProducer::flushCurrentBucketLocked(const uint64_t& eventTimeNs) {
Yangster-mac53928882018-02-25 23:02:56 -0800514 for (auto whatIt = mCurrentSlicedDurationTrackerMap.begin();
515 whatIt != mCurrentSlicedDurationTrackerMap.end();) {
516 for (auto it = whatIt->second.begin(); it != whatIt->second.end();) {
517 if (it->second->flushCurrentBucket(eventTimeNs, &mPastBuckets)) {
Yangster13fb7e42018-03-07 17:30:49 -0800518 VLOG("erase bucket for key %s %s", whatIt->first.toString().c_str(),
519 it->first.toString().c_str());
Yangster-mac53928882018-02-25 23:02:56 -0800520 it = whatIt->second.erase(it);
521 } else {
522 ++it;
523 }
524 }
525 if (whatIt->second.empty()) {
526 whatIt = mCurrentSlicedDurationTrackerMap.erase(whatIt);
David Chen27785a82018-01-19 17:06:45 -0800527 } else {
Yangster-mac53928882018-02-25 23:02:56 -0800528 whatIt++;
David Chen27785a82018-01-19 17:06:45 -0800529 }
530 }
531}
532
Yao Chen884c8c12018-01-26 10:36:25 -0800533void DurationMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
Yangster-mac93694462018-01-22 20:49:31 -0800534 if (mCurrentSlicedDurationTrackerMap.size() == 0) {
Yao Chen884c8c12018-01-26 10:36:25 -0800535 return;
536 }
537
538 fprintf(out, "DurationMetric %lld dimension size %lu\n", (long long)mMetricId,
Yangster-mac93694462018-01-22 20:49:31 -0800539 (unsigned long)mCurrentSlicedDurationTrackerMap.size());
Yao Chen884c8c12018-01-26 10:36:25 -0800540 if (verbose) {
Yangster-mac53928882018-02-25 23:02:56 -0800541 for (const auto& whatIt : mCurrentSlicedDurationTrackerMap) {
542 for (const auto& slice : whatIt.second) {
Yangster13fb7e42018-03-07 17:30:49 -0800543 fprintf(out, "\t(what)%s\t(condition)%s\n", whatIt.first.toString().c_str(),
544 slice.first.toString().c_str());
Yangster-mac53928882018-02-25 23:02:56 -0800545 slice.second->dumpStates(out, verbose);
546 }
Yao Chen884c8c12018-01-26 10:36:25 -0800547 }
548 }
549}
550
Yangster-mac93694462018-01-22 20:49:31 -0800551bool DurationMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800552 // 1. Report the tuple count if the tuple count > soft limit
Yangster-mac93694462018-01-22 20:49:31 -0800553 if (mCurrentSlicedDurationTrackerMap.size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
554 size_t newTupleCount = mCurrentSlicedDurationTrackerMap.size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800555 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800556 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
557 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800558 ALOGE("DurationMetric %lld dropping data for dimension key %s",
Yangster13fb7e42018-03-07 17:30:49 -0800559 (long long)mMetricId, newKey.toString().c_str());
Yao Chenb3561512017-11-21 18:07:17 -0800560 return true;
561 }
562 }
563 return false;
564}
565
Yangster-mac53928882018-02-25 23:02:56 -0800566void DurationMetricProducer::handleStartEvent(const MetricDimensionKey& eventKey,
567 const ConditionKey& conditionKeys,
568 bool condition, const LogEvent& event) {
569 const auto& whatKey = eventKey.getDimensionKeyInWhat();
570 const auto& condKey = eventKey.getDimensionKeyInCondition();
Yao Chen5154a372017-10-30 22:57:06 -0700571
Yangster-mac53928882018-02-25 23:02:56 -0800572 auto whatIt = mCurrentSlicedDurationTrackerMap.find(whatKey);
573 if (whatIt == mCurrentSlicedDurationTrackerMap.end()) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800574 if (hitGuardRailLocked(eventKey)) {
Yao Chenb3561512017-11-21 18:07:17 -0800575 return;
576 }
Yangster-mac53928882018-02-25 23:02:56 -0800577 mCurrentSlicedDurationTrackerMap[whatKey][condKey] = createDurationTracker(eventKey);
578 } else {
579 if (whatIt->second.find(condKey) == whatIt->second.end()) {
580 if (hitGuardRailLocked(eventKey)) {
581 return;
582 }
583 mCurrentSlicedDurationTrackerMap[whatKey][condKey] = createDurationTracker(eventKey);
584 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000585 }
Yao Chen5154a372017-10-30 22:57:06 -0700586
Yangster-mac53928882018-02-25 23:02:56 -0800587 auto it = mCurrentSlicedDurationTrackerMap.find(whatKey)->second.find(condKey);
588 if (mUseWhatDimensionAsInternalDimension) {
589 it->second->noteStart(whatKey, condition,
590 event.GetElapsedTimestampNs(), conditionKeys);
591 return;
592 }
Yao Chen5154a372017-10-30 22:57:06 -0700593
Yangster13fb7e42018-03-07 17:30:49 -0800594 if (mInternalDimensions.empty()) {
Yangster-mac53928882018-02-25 23:02:56 -0800595 it->second->noteStart(DEFAULT_DIMENSION_KEY, condition,
596 event.GetElapsedTimestampNs(), conditionKeys);
Yangster-mac20877162017-12-22 17:19:39 -0800597 } else {
Yangster-mace06cfd72018-03-10 23:22:59 -0800598 HashableDimensionKey dimensionKey = DEFAULT_DIMENSION_KEY;
599 filterValues(mInternalDimensions, event.getValues(), &dimensionKey);
600 it->second->noteStart(
601 dimensionKey, condition, event.GetElapsedTimestampNs(), conditionKeys);
Yao Chen5154a372017-10-30 22:57:06 -0700602 }
Yangster-mac20877162017-12-22 17:19:39 -0800603
Yao Chen729093d2017-10-16 10:33:26 -0700604}
605
Yangster-mac53928882018-02-25 23:02:56 -0800606void DurationMetricProducer::onMatchedLogEventInternalLocked(
607 const size_t matcherIndex, const MetricDimensionKey& eventKey,
608 const ConditionKey& conditionKeys, bool condition,
609 const LogEvent& event) {
610 ALOGW("Not used in duration tracker.");
611}
612
Yangster-mace06cfd72018-03-10 23:22:59 -0800613void DurationMetricProducer::onMatchedLogEventLocked(const size_t matcherIndex,
614 const LogEvent& event) {
Yangster13fb7e42018-03-07 17:30:49 -0800615 uint64_t eventTimeNs = event.GetElapsedTimestampNs();
616 if (eventTimeNs < mStartTimeNs) {
617 return;
618 }
619
620 flushIfNeededLocked(event.GetElapsedTimestampNs());
621
622 // Handles Stopall events.
623 if (matcherIndex == mStopAllIndex) {
624 for (auto& whatIt : mCurrentSlicedDurationTrackerMap) {
625 for (auto& pair : whatIt.second) {
626 pair.second->noteStopAll(event.GetElapsedTimestampNs());
627 }
628 }
629 return;
630 }
631
632 HashableDimensionKey dimensionInWhat;
633 if (!mDimensionsInWhat.empty()) {
634 filterValues(mDimensionsInWhat, event.getValues(), &dimensionInWhat);
635 } else {
636 dimensionInWhat = DEFAULT_DIMENSION_KEY;
637 }
638
639 // Handles Stop events.
640 if (matcherIndex == mStopIndex) {
641 if (mUseWhatDimensionAsInternalDimension) {
642 auto whatIt = mCurrentSlicedDurationTrackerMap.find(dimensionInWhat);
643 if (whatIt != mCurrentSlicedDurationTrackerMap.end()) {
644 for (const auto& condIt : whatIt->second) {
645 condIt.second->noteStop(dimensionInWhat, event.GetElapsedTimestampNs(), false);
646 }
647 }
648 return;
649 }
650
651 HashableDimensionKey internalDimensionKey = DEFAULT_DIMENSION_KEY;
652 if (!mInternalDimensions.empty()) {
653 filterValues(mInternalDimensions, event.getValues(), &internalDimensionKey);
654 }
655
656 auto whatIt = mCurrentSlicedDurationTrackerMap.find(dimensionInWhat);
657 if (whatIt != mCurrentSlicedDurationTrackerMap.end()) {
658 for (const auto& condIt : whatIt->second) {
659 condIt.second->noteStop(
660 internalDimensionKey, event.GetElapsedTimestampNs(), false);
661 }
662 }
663 return;
664 }
665
666 bool condition;
667 ConditionKey conditionKey;
668 std::unordered_set<HashableDimensionKey> dimensionKeysInCondition;
669 if (mConditionSliced) {
670 for (const auto& link : mMetric2ConditionLinks) {
671 getDimensionForCondition(event.getValues(), link, &conditionKey[link.conditionId]);
672 }
673
674 auto conditionState =
675 mWizard->query(mConditionTrackerIndex, conditionKey, mDimensionsInCondition,
676 !mSameConditionDimensionsInTracker,
677 !mHasLinksToAllConditionDimensionsInTracker,
678 &dimensionKeysInCondition);
679 condition = (conditionState == ConditionState::kTrue);
680 if (mDimensionsInCondition.empty() && condition) {
681 dimensionKeysInCondition.insert(DEFAULT_DIMENSION_KEY);
682 }
683 } else {
684 condition = mCondition;
685 if (condition) {
686 dimensionKeysInCondition.insert(DEFAULT_DIMENSION_KEY);
687 }
688 }
689
690 if (dimensionKeysInCondition.empty()) {
691 handleStartEvent(MetricDimensionKey(dimensionInWhat, DEFAULT_DIMENSION_KEY),
692 conditionKey, condition, event);
693 } else {
694 auto whatIt = mCurrentSlicedDurationTrackerMap.find(dimensionInWhat);
695 // If the what dimension is already there, we should update all the trackers even
696 // the condition is false.
697 if (whatIt != mCurrentSlicedDurationTrackerMap.end()) {
698 for (const auto& condIt : whatIt->second) {
699 const bool cond = dimensionKeysInCondition.find(condIt.first) !=
700 dimensionKeysInCondition.end();
701 handleStartEvent(MetricDimensionKey(dimensionInWhat, condIt.first),
702 conditionKey, cond, event);
703 dimensionKeysInCondition.erase(condIt.first);
704 }
705 }
706 for (const auto& conditionDimension : dimensionKeysInCondition) {
707 handleStartEvent(MetricDimensionKey(dimensionInWhat, conditionDimension), conditionKey,
708 condition, event);
709 }
710 }
711}
712
Yangsterf2bee6f2017-11-29 12:01:05 -0800713size_t DurationMetricProducer::byteSizeLocked() const {
Yangster7c334a12017-11-22 14:24:24 -0800714 size_t totalSize = 0;
715 for (const auto& pair : mPastBuckets) {
716 totalSize += pair.second.size() * kBucketSize;
717 }
718 return totalSize;
yro69007c82017-10-26 20:42:57 -0700719}
720
Yao Chen729093d2017-10-16 10:33:26 -0700721} // namespace statsd
722} // namespace os
723} // namespace android