blob: 58a9a38b83d4f21651724b2528140b10ba517149 [file] [log] [blame]
Chenjie Yub3dda412017-10-24 13:41:59 -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
Chenjie Yu88588972018-08-03 09:49:22 -070017#define DEBUG false // STOPSHIP if true
Chenjie Yub3dda412017-10-24 13:41:59 -070018#include "Log.h"
19
20#include "ValueMetricProducer.h"
Chenjie Yuc5875052018-03-09 10:13:11 -080021#include "../guardrail/StatsdStats.h"
22#include "../stats_log_util.h"
Chenjie Yub3dda412017-10-24 13:41:59 -070023
Chenjie Yub3dda412017-10-24 13:41:59 -070024#include <limits.h>
25#include <stdlib.h>
26
yrob0378b02017-11-09 20:36:25 -080027using android::util::FIELD_COUNT_REPEATED;
yro2b0f8862017-11-06 14:27:31 -080028using android::util::FIELD_TYPE_BOOL;
Chenjie Yua0f02242018-07-06 16:14:34 -070029using android::util::FIELD_TYPE_DOUBLE;
yro2b0f8862017-11-06 14:27:31 -080030using android::util::FIELD_TYPE_INT32;
31using android::util::FIELD_TYPE_INT64;
32using android::util::FIELD_TYPE_MESSAGE;
Yangster-macd1815dc2017-11-13 21:43:15 -080033using android::util::FIELD_TYPE_STRING;
yro2b0f8862017-11-06 14:27:31 -080034using android::util::ProtoOutputStream;
Yao Chen93fe3a32017-11-02 13:52:59 -070035using std::map;
Chenjie Yub3dda412017-10-24 13:41:59 -070036using std::shared_ptr;
Yao Chen93fe3a32017-11-02 13:52:59 -070037using std::unordered_map;
Chenjie Yub3dda412017-10-24 13:41:59 -070038
39namespace android {
40namespace os {
41namespace statsd {
42
yro2b0f8862017-11-06 14:27:31 -080043// for StatsLogReport
Yangster-mac94e197c2018-01-02 16:03:03 -080044const int FIELD_ID_ID = 1;
yro2b0f8862017-11-06 14:27:31 -080045const int FIELD_ID_VALUE_METRICS = 7;
Yangster-mac9def8e32018-04-17 13:55:51 -070046const int FIELD_ID_TIME_BASE = 9;
47const int FIELD_ID_BUCKET_SIZE = 10;
48const int FIELD_ID_DIMENSION_PATH_IN_WHAT = 11;
Howard Ro9440e092018-12-16 19:15:21 -080049const int FIELD_ID_IS_ACTIVE = 14;
yro2b0f8862017-11-06 14:27:31 -080050// for ValueMetricDataWrapper
51const int FIELD_ID_DATA = 1;
David Chen81245fd2018-04-12 14:33:37 -070052const int FIELD_ID_SKIPPED = 2;
tsaichristineb87ca152019-12-09 15:19:41 -080053// for SkippedBuckets
Yangster-mac9def8e32018-04-17 13:55:51 -070054const int FIELD_ID_SKIPPED_START_MILLIS = 3;
55const int FIELD_ID_SKIPPED_END_MILLIS = 4;
tsaichristineb87ca152019-12-09 15:19:41 -080056const int FIELD_ID_SKIPPED_DROP_EVENT = 5;
57// for DumpEvent Proto
58const int FIELD_ID_BUCKET_DROP_REASON = 1;
59const int FIELD_ID_DROP_TIME = 2;
yro2b0f8862017-11-06 14:27:31 -080060// for ValueMetricData
Yangster-mac468ff042018-01-17 12:26:34 -080061const int FIELD_ID_DIMENSION_IN_WHAT = 1;
Yangster-mac468ff042018-01-17 12:26:34 -080062const int FIELD_ID_BUCKET_INFO = 3;
Yangster-mac9def8e32018-04-17 13:55:51 -070063const int FIELD_ID_DIMENSION_LEAF_IN_WHAT = 4;
tsaichristinec876b492019-12-10 13:47:05 -080064const int FIELD_ID_SLICE_BY_STATE = 6;
yro2b0f8862017-11-06 14:27:31 -080065// for ValueBucketInfo
Chenjie Yu32717c32018-10-20 23:54:48 -070066const int FIELD_ID_VALUE_INDEX = 1;
67const int FIELD_ID_VALUE_LONG = 2;
68const int FIELD_ID_VALUE_DOUBLE = 3;
69const int FIELD_ID_VALUES = 9;
Yangster-mac9def8e32018-04-17 13:55:51 -070070const int FIELD_ID_BUCKET_NUM = 4;
71const int FIELD_ID_START_BUCKET_ELAPSED_MILLIS = 5;
72const int FIELD_ID_END_BUCKET_ELAPSED_MILLIS = 6;
Yao Chene6cfb142019-04-08 12:00:01 -070073const int FIELD_ID_CONDITION_TRUE_NS = 10;
yro2b0f8862017-11-06 14:27:31 -080074
Chenjie Yuf275f612018-11-30 23:29:06 -080075const Value ZERO_LONG((int64_t)0);
76const Value ZERO_DOUBLE((int64_t)0);
77
Chenjie Yub3dda412017-10-24 13:41:59 -070078// ValueMetric has a minimum bucket size of 10min so that we don't pull too frequently
Chenjie Yuf275f612018-11-30 23:29:06 -080079ValueMetricProducer::ValueMetricProducer(
80 const ConfigKey& key, const ValueMetric& metric, const int conditionIndex,
81 const sp<ConditionWizard>& conditionWizard, const int whatMatcherIndex,
82 const sp<EventMatcherWizard>& matcherWizard, const int pullTagId, const int64_t timeBaseNs,
Ruchir Rastogi21a287b2019-10-02 12:04:33 -070083 const int64_t startTimeNs, const sp<StatsPullerManager>& pullerManager,
84 const unordered_map<int, shared_ptr<Activation>>& eventActivationMap,
tsaichristined21aacf2019-10-07 14:47:38 -070085 const unordered_map<int, vector<shared_ptr<Activation>>>& eventDeactivationMap,
86 const vector<int>& slicedStateAtoms,
87 const unordered_map<int, unordered_map<int, int64_t>>& stateGroupMap)
Ruchir Rastogi21a287b2019-10-02 12:04:33 -070088 : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, conditionWizard,
tsaichristined21aacf2019-10-07 14:47:38 -070089 eventActivationMap, eventDeactivationMap, slicedStateAtoms, stateGroupMap),
Chenjie Yu054ce9c2018-11-12 15:27:29 -080090 mWhatMatcherIndex(whatMatcherIndex),
91 mEventMatcherWizard(matcherWizard),
Chenjie Yue2219202018-06-08 10:07:51 -070092 mPullerManager(pullerManager),
Chenjie Yuc5875052018-03-09 10:13:11 -080093 mPullTagId(pullTagId),
Chenjie Yua0f02242018-07-06 16:14:34 -070094 mIsPulled(pullTagId != -1),
David Chen81245fd2018-04-12 14:33:37 -070095 mMinBucketSizeNs(metric.min_bucket_size_nanos()),
Chenjie Yuc5875052018-03-09 10:13:11 -080096 mDimensionSoftLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
97 StatsdStats::kAtomDimensionKeySizeLimitMap.end()
98 ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).first
99 : StatsdStats::kDimensionKeySizeSoftLimit),
100 mDimensionHardLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
101 StatsdStats::kAtomDimensionKeySizeLimitMap.end()
102 ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).second
Chenjie Yu47234642018-05-14 10:14:16 -0700103 : StatsdStats::kDimensionKeySizeHardLimit),
Chenjie Yua0f02242018-07-06 16:14:34 -0700104 mUseAbsoluteValueOnReset(metric.use_absolute_value_on_reset()),
105 mAggregationType(metric.aggregation_type()),
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700106 mUseDiff(metric.has_use_diff() ? metric.use_diff() : (mIsPulled ? true : false)),
107 mValueDirection(metric.value_direction()),
Chenjie Yuf275f612018-11-30 23:29:06 -0800108 mSkipZeroDiffOutput(metric.skip_zero_diff_output()),
109 mUseZeroDefaultBase(metric.use_zero_default_base()),
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800110 mHasGlobalBase(false),
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000111 mCurrentBucketIsInvalid(false),
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800112 mMaxPullDelayNs(metric.max_pull_delay_sec() > 0 ? metric.max_pull_delay_sec() * NS_PER_SEC
Chenjie Yucd1b7972019-01-16 20:38:15 -0800113 : StatsdStats::kPullMaxDelayNs),
Yao Chene6cfb142019-04-08 12:00:01 -0700114 mSplitBucketForAppUpgrade(metric.split_bucket_for_app_upgrade()),
Ruchir Rastogi21a287b2019-10-02 12:04:33 -0700115 // Condition timer will be set later within the constructor after pulling events
Tej Singhee4495e2019-06-03 18:37:35 -0700116 mConditionTimer(false, timeBaseNs) {
Yangster-macb8144812018-01-04 10:56:23 -0800117 int64_t bucketSizeMills = 0;
118 if (metric.has_bucket()) {
yro59cc24d2018-02-13 20:17:32 -0800119 bucketSizeMills = TimeUnitToBucketSizeInMillisGuardrailed(key.GetUid(), metric.bucket());
Chenjie Yu6736c892017-11-09 10:50:09 -0800120 } else {
Yangster-macb8144812018-01-04 10:56:23 -0800121 bucketSizeMills = TimeUnitToBucketSizeInMillis(ONE_HOUR);
Chenjie Yu6736c892017-11-09 10:50:09 -0800122 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700123
Yangster-macb8144812018-01-04 10:56:23 -0800124 mBucketSizeNs = bucketSizeMills * 1000000;
Chenjie Yu32717c32018-10-20 23:54:48 -0700125
126 translateFieldMatcher(metric.value_field(), &mFieldMatchers);
127
Yao Chen8a8d16c2018-02-08 14:50:40 -0800128 if (metric.has_dimensions_in_what()) {
129 translateFieldMatcher(metric.dimensions_in_what(), &mDimensionsInWhat);
Yangster13fb7e42018-03-07 17:30:49 -0800130 mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
tsaichristine90f95bb2019-11-06 17:06:53 -0800131 mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what());
Yao Chen8a8d16c2018-02-08 14:50:40 -0800132 }
133
Yao Chen93fe3a32017-11-02 13:52:59 -0700134 if (metric.links().size() > 0) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800135 for (const auto& link : metric.links()) {
136 Metric2Condition mc;
137 mc.conditionId = link.condition();
138 translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
139 translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
140 mMetric2ConditionLinks.push_back(mc);
141 }
tsaichristine76853372019-08-06 17:17:03 -0700142 mConditionSliced = true;
Yao Chen93fe3a32017-11-02 13:52:59 -0700143 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800144
tsaichristinec876b492019-12-10 13:47:05 -0800145 for (const auto& stateLink : metric.state_link()) {
146 Metric2State ms;
147 ms.stateAtomId = stateLink.state_atom_id();
148 translateFieldMatcher(stateLink.fields_in_what(), &ms.metricFields);
149 translateFieldMatcher(stateLink.fields_in_state(), &ms.stateFields);
150 mMetric2StateLinks.push_back(ms);
151 }
152
Tej Singh597c7162019-04-17 16:41:45 -0700153 int64_t numBucketsForward = calcBucketsForwardCount(startTimeNs);
154 mCurrentBucketNum += numBucketsForward;
155
Chenjie Yue1361ed2018-07-23 17:33:09 -0700156 flushIfNeededLocked(startTimeNs);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700157
Chenjie Yua0f02242018-07-06 16:14:34 -0700158 if (mIsPulled) {
Tej Singh3be093b2020-03-04 20:08:38 -0800159 mPullerManager->RegisterReceiver(mPullTagId, mConfigKey, this, getCurrentBucketEndTimeNs(),
Chenjie Yue1361ed2018-07-23 17:33:09 -0700160 mBucketSizeNs);
Yao Chen93fe3a32017-11-02 13:52:59 -0700161 }
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700162
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700163 // Only do this for partial buckets like first bucket. All other buckets should use
Chenjie Yue1361ed2018-07-23 17:33:09 -0700164 // flushIfNeeded to adjust start and end to bucket boundaries.
165 // Adjust start for partial bucket
166 mCurrentBucketStartTimeNs = startTimeNs;
Yao Chene6cfb142019-04-08 12:00:01 -0700167 mConditionTimer.newBucketStart(mCurrentBucketStartTimeNs);
Ruchir Rastogi21a287b2019-10-02 12:04:33 -0700168
Ruchir Rastogi21a287b2019-10-02 12:04:33 -0700169 // Now that activations are processed, start the condition timer if needed.
170 mConditionTimer.onConditionChanged(mIsActive && mCondition == ConditionState::kTrue,
171 mCurrentBucketStartTimeNs);
172
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700173 VLOG("value metric %lld created. bucket size %lld start_time: %lld", (long long)metric.id(),
174 (long long)mBucketSizeNs, (long long)mTimeBaseNs);
Chenjie Yub3dda412017-10-24 13:41:59 -0700175}
176
177ValueMetricProducer::~ValueMetricProducer() {
Yao Chen93fe3a32017-11-02 13:52:59 -0700178 VLOG("~ValueMetricProducer() called");
Chenjie Yua0f02242018-07-06 16:14:34 -0700179 if (mIsPulled) {
Tej Singh3be093b2020-03-04 20:08:38 -0800180 mPullerManager->UnRegisterReceiver(mPullTagId, mConfigKey, this);
Chenjie Yu6736c892017-11-09 10:50:09 -0800181 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700182}
183
tsaichristinec876b492019-12-10 13:47:05 -0800184void ValueMetricProducer::onStateChanged(int64_t eventTimeNs, int32_t atomId,
tsaichristine9f951052020-05-13 14:32:37 -0700185 const HashableDimensionKey& primaryKey,
186 const FieldValue& oldState, const FieldValue& newState) {
tsaichristinec876b492019-12-10 13:47:05 -0800187 VLOG("ValueMetric %lld onStateChanged time %lld, State %d, key %s, %d -> %d",
188 (long long)mMetricId, (long long)eventTimeNs, atomId, primaryKey.toString().c_str(),
tsaichristine9f951052020-05-13 14:32:37 -0700189 oldState.mValue.int_value, newState.mValue.int_value);
tsaichristine0f6c1bc2020-04-28 10:42:25 -0700190 // If condition is not true or metric is not active, we do not need to pull
191 // for this state change.
192 if (mCondition != ConditionState::kTrue || !mIsActive) {
tsaichristinec876b492019-12-10 13:47:05 -0800193 return;
194 }
tsaichristine9f951052020-05-13 14:32:37 -0700195
196 // If old and new states are in the same StateGroup, then we do not need to
197 // pull for this state change.
198 FieldValue oldStateCopy = oldState;
199 FieldValue newStateCopy = newState;
200 mapStateValue(atomId, &oldStateCopy);
201 mapStateValue(atomId, &newStateCopy);
202 if (oldStateCopy == newStateCopy) {
203 return;
204 }
205
tsaichristinec876b492019-12-10 13:47:05 -0800206 bool isEventLate = eventTimeNs < mCurrentBucketStartTimeNs;
207 if (isEventLate) {
208 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
209 (long long)mCurrentBucketStartTimeNs);
210 invalidateCurrentBucket(eventTimeNs, BucketDropReason::EVENT_IN_WRONG_BUCKET);
211 return;
212 }
213 mStateChangePrimaryKey.first = atomId;
214 mStateChangePrimaryKey.second = primaryKey;
215 if (mIsPulled) {
216 pullAndMatchEventsLocked(eventTimeNs);
217 }
218 mStateChangePrimaryKey.first = 0;
219 mStateChangePrimaryKey.second = DEFAULT_DIMENSION_KEY;
220 flushIfNeededLocked(eventTimeNs);
221}
222
Yao Chen427d3722018-03-22 15:21:52 -0700223void ValueMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
Yangster-macb142cc82018-03-30 15:22:08 -0700224 const int64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800225 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Chenjie Yub3dda412017-10-24 13:41:59 -0700226}
227
Yangster-macb142cc82018-03-30 15:22:08 -0700228void ValueMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
Olivier Gaillard320952b2019-02-06 13:57:24 +0000229 StatsdStats::getInstance().noteBucketDropped(mMetricId);
tsaichristineb7fcf002019-12-06 18:40:47 -0800230
231 // The current partial bucket is not flushed and does not require a pull,
232 // so the data is still valid.
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000233 flushIfNeededLocked(dropTimeNs);
234 clearPastBucketsLocked(dropTimeNs);
Yao Chen06dba5d2018-01-26 13:38:16 -0800235}
236
Yangster-maca802d732018-04-24 07:50:38 -0700237void ValueMetricProducer::clearPastBucketsLocked(const int64_t dumpTimeNs) {
Yangster-maca802d732018-04-24 07:50:38 -0700238 mPastBuckets.clear();
239 mSkippedBuckets.clear();
240}
241
Yangster-macb142cc82018-03-30 15:22:08 -0700242void ValueMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700243 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700244 const bool erase_data,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000245 const DumpLatency dumpLatency,
Yangster-mac9def8e32018-04-17 13:55:51 -0700246 std::set<string> *str_set,
Yao Chen288c6002017-12-12 13:43:18 -0800247 ProtoOutputStream* protoOutput) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800248 VLOG("metric %lld dump report now...", (long long)mMetricId);
Yangster-mace68f3a52018-04-04 00:01:43 -0700249 if (include_current_partial_bucket) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000250 // For pull metrics, we need to do a pull at bucket boundaries. If we do not do that the
251 // current bucket will have incomplete data and the next will have the wrong snapshot to do
252 // a diff against. If the condition is false, we are fine since the base data is reset and
253 // we are not tracking anything.
254 bool pullNeeded = mIsPulled && mCondition == ConditionState::kTrue;
255 if (pullNeeded) {
256 switch (dumpLatency) {
257 case FAST:
tsaichristineb87ca152019-12-09 15:19:41 -0800258 invalidateCurrentBucket(dumpTimeNs, BucketDropReason::DUMP_REPORT_REQUESTED);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000259 break;
260 case NO_TIME_CONSTRAINTS:
tsaichristine78b85702019-12-06 12:20:30 -0800261 pullAndMatchEventsLocked(dumpTimeNs);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000262 break;
263 }
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000264 }
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000265 flushCurrentBucketLocked(dumpTimeNs, dumpTimeNs);
Yangster-mace68f3a52018-04-04 00:01:43 -0700266 }
Yang Lub4722912018-11-15 11:02:03 -0800267 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Howard Ro07e23ff2018-12-17 17:28:07 -0800268 protoOutput->write(FIELD_TYPE_BOOL | FIELD_ID_IS_ACTIVE, isActiveLocked());
Yang Lub4722912018-11-15 11:02:03 -0800269
David Chen81245fd2018-04-12 14:33:37 -0700270 if (mPastBuckets.empty() && mSkippedBuckets.empty()) {
Yangster-mac635b4b32018-01-23 20:17:35 -0800271 return;
272 }
Yangster-mac9def8e32018-04-17 13:55:51 -0700273 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_TIME_BASE, (long long)mTimeBaseNs);
274 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_SIZE, (long long)mBucketSizeNs);
275 // Fills the dimension path if not slicing by ALL.
276 if (!mSliceByPositionALL) {
277 if (!mDimensionsInWhat.empty()) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700278 uint64_t dimenPathToken =
279 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_WHAT);
Yangster-mac9def8e32018-04-17 13:55:51 -0700280 writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
281 protoOutput->end(dimenPathToken);
282 }
Yangster-mac9def8e32018-04-17 13:55:51 -0700283 }
284
Yi Jin5ee07872018-03-05 18:18:27 -0800285 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_VALUE_METRICS);
Yao Chen6a8c7992017-11-29 20:02:07 +0000286
tsaichristineb87ca152019-12-09 15:19:41 -0800287 for (const auto& skippedBucket : mSkippedBuckets) {
David Chen81245fd2018-04-12 14:33:37 -0700288 uint64_t wrapperToken =
289 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_SKIPPED);
Yangster-mac9def8e32018-04-17 13:55:51 -0700290 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_START_MILLIS,
tsaichristineb87ca152019-12-09 15:19:41 -0800291 (long long)(NanoToMillis(skippedBucket.bucketStartTimeNs)));
Yangster-mac9def8e32018-04-17 13:55:51 -0700292 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_END_MILLIS,
tsaichristineb87ca152019-12-09 15:19:41 -0800293 (long long)(NanoToMillis(skippedBucket.bucketEndTimeNs)));
294 for (const auto& dropEvent : skippedBucket.dropEvents) {
295 uint64_t dropEventToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
296 FIELD_ID_SKIPPED_DROP_EVENT);
297 protoOutput->write(FIELD_TYPE_INT32 | FIELD_ID_BUCKET_DROP_REASON, dropEvent.reason);
298 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_DROP_TIME,
299 (long long)(NanoToMillis(dropEvent.dropTimeNs)));
300 ;
301 protoOutput->end(dropEventToken);
302 }
David Chen81245fd2018-04-12 14:33:37 -0700303 protoOutput->end(wrapperToken);
304 }
David Chen81245fd2018-04-12 14:33:37 -0700305
Yao Chen93fe3a32017-11-02 13:52:59 -0700306 for (const auto& pair : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800307 const MetricDimensionKey& dimensionKey = pair.first;
Yangster13fb7e42018-03-07 17:30:49 -0800308 VLOG(" dimension key %s", dimensionKey.toString().c_str());
Yi Jin5ee07872018-03-05 18:18:27 -0800309 uint64_t wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800310 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
Chenjie Yub3dda412017-10-24 13:41:59 -0700311
Yangster-mac20877162017-12-22 17:19:39 -0800312 // First fill dimension.
Yangster-mac9def8e32018-04-17 13:55:51 -0700313 if (mSliceByPositionALL) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700314 uint64_t dimensionToken =
315 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
Yangster-mac9def8e32018-04-17 13:55:51 -0700316 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), str_set, protoOutput);
317 protoOutput->end(dimensionToken);
Yangster-mac9def8e32018-04-17 13:55:51 -0700318 } else {
319 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInWhat(),
320 FIELD_ID_DIMENSION_LEAF_IN_WHAT, str_set, protoOutput);
Yangster-mac93694462018-01-22 20:49:31 -0800321 }
yro2b0f8862017-11-06 14:27:31 -0800322
tsaichristinec876b492019-12-10 13:47:05 -0800323 // Then fill slice_by_state.
324 for (auto state : dimensionKey.getStateValuesKey().getValues()) {
325 uint64_t stateToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
326 FIELD_ID_SLICE_BY_STATE);
327 writeStateToProto(state, protoOutput);
328 protoOutput->end(stateToken);
329 }
330
yro2b0f8862017-11-06 14:27:31 -0800331 // Then fill bucket_info (ValueBucketInfo).
332 for (const auto& bucket : pair.second) {
Yi Jin5ee07872018-03-05 18:18:27 -0800333 uint64_t bucketInfoToken = protoOutput->start(
Yao Chen288c6002017-12-12 13:43:18 -0800334 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
Yangster-mac9def8e32018-04-17 13:55:51 -0700335
336 if (bucket.mBucketEndNs - bucket.mBucketStartNs != mBucketSizeNs) {
337 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_MILLIS,
338 (long long)NanoToMillis(bucket.mBucketStartNs));
339 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_MILLIS,
340 (long long)NanoToMillis(bucket.mBucketEndNs));
341 } else {
342 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_NUM,
343 (long long)(getBucketNumFromEndTimeNs(bucket.mBucketEndNs)));
344 }
Yao Chene6cfb142019-04-08 12:00:01 -0700345 // only write the condition timer value if the metric has a condition.
346 if (mConditionTrackerIndex >= 0) {
347 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_CONDITION_TRUE_NS,
348 (long long)bucket.mConditionTrueNs);
349 }
tsaichristinec876b492019-12-10 13:47:05 -0800350 for (int i = 0; i < (int)bucket.valueIndex.size(); i++) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700351 int index = bucket.valueIndex[i];
352 const Value& value = bucket.values[i];
353 uint64_t valueToken = protoOutput->start(
354 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_VALUES);
355 protoOutput->write(FIELD_TYPE_INT32 | FIELD_ID_VALUE_INDEX,
356 index);
357 if (value.getType() == LONG) {
358 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_VALUE_LONG,
359 (long long)value.long_value);
360 VLOG("\t bucket [%lld - %lld] value %d: %lld", (long long)bucket.mBucketStartNs,
361 (long long)bucket.mBucketEndNs, index, (long long)value.long_value);
362 } else if (value.getType() == DOUBLE) {
363 protoOutput->write(FIELD_TYPE_DOUBLE | FIELD_ID_VALUE_DOUBLE,
364 value.double_value);
365 VLOG("\t bucket [%lld - %lld] value %d: %.2f", (long long)bucket.mBucketStartNs,
366 (long long)bucket.mBucketEndNs, index, value.double_value);
367 } else {
368 VLOG("Wrong value type for ValueMetric output: %d", value.getType());
369 }
370 protoOutput->end(valueToken);
Chenjie Yua0f02242018-07-06 16:14:34 -0700371 }
Yao Chen288c6002017-12-12 13:43:18 -0800372 protoOutput->end(bucketInfoToken);
yro2b0f8862017-11-06 14:27:31 -0800373 }
Yao Chen288c6002017-12-12 13:43:18 -0800374 protoOutput->end(wrapperToken);
Chenjie Yub3dda412017-10-24 13:41:59 -0700375 }
Yao Chen288c6002017-12-12 13:43:18 -0800376 protoOutput->end(protoToken);
yro2b0f8862017-11-06 14:27:31 -0800377
Yangster-mac94e197c2018-01-02 16:03:03 -0800378 VLOG("metric %lld dump report now...", (long long)mMetricId);
Bookatzff71cad2018-09-20 17:17:49 -0700379 if (erase_data) {
380 mPastBuckets.clear();
381 mSkippedBuckets.clear();
382 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700383}
384
tsaichristineb87ca152019-12-09 15:19:41 -0800385void ValueMetricProducer::invalidateCurrentBucketWithoutResetBase(const int64_t dropTimeNs,
386 const BucketDropReason reason) {
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000387 if (!mCurrentBucketIsInvalid) {
tsaichristineb87ca152019-12-09 15:19:41 -0800388 // Only report to StatsdStats once per invalid bucket.
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000389 StatsdStats::getInstance().noteInvalidatedBucket(mMetricId);
tsaichristineb87ca152019-12-09 15:19:41 -0800390 }
391
392 if (!maxDropEventsReached()) {
393 mCurrentSkippedBucket.dropEvents.emplace_back(buildDropEvent(dropTimeNs, reason));
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000394 }
395 mCurrentBucketIsInvalid = true;
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000396}
397
tsaichristineb87ca152019-12-09 15:19:41 -0800398void ValueMetricProducer::invalidateCurrentBucket(const int64_t dropTimeNs,
399 const BucketDropReason reason) {
400 invalidateCurrentBucketWithoutResetBase(dropTimeNs, reason);
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000401 resetBase();
402}
403
Chenjie Yuf275f612018-11-30 23:29:06 -0800404void ValueMetricProducer::resetBase() {
tsaichristinec876b492019-12-10 13:47:05 -0800405 for (auto& slice : mCurrentBaseInfo) {
406 for (auto& baseInfo : slice.second) {
407 baseInfo.hasBase = false;
408 baseInfo.hasCurrentState = false;
Chenjie Yuf275f612018-11-30 23:29:06 -0800409 }
410 }
411 mHasGlobalBase = false;
412}
413
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700414// Handle active state change. Active state change is treated like a condition change:
415// - drop bucket if active state change event arrives too late
416// - if condition is true, pull data on active state changes
417// - ConditionTimer tracks changes based on AND of condition and active state.
418void ValueMetricProducer::onActiveStateChangedLocked(const int64_t& eventTimeNs) {
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000419 bool isEventTooLate = eventTimeNs < mCurrentBucketStartTimeNs;
tsaichristine90f95bb2019-11-06 17:06:53 -0800420 if (isEventTooLate) {
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700421 // Drop bucket because event arrived too late, ie. we are missing data for this bucket.
tsaichristineb87ca152019-12-09 15:19:41 -0800422 StatsdStats::getInstance().noteLateLogEventSkipped(mMetricId);
423 invalidateCurrentBucket(eventTimeNs, BucketDropReason::EVENT_IN_WRONG_BUCKET);
Yao Chen2794da22017-12-13 16:01:55 -0800424 }
425
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700426 // Call parent method once we've verified the validity of current bucket.
427 MetricProducer::onActiveStateChangedLocked(eventTimeNs);
428
429 if (ConditionState::kTrue != mCondition) {
430 return;
431 }
432
433 // Pull on active state changes.
434 if (!isEventTooLate) {
435 if (mIsPulled) {
tsaichristine78b85702019-12-06 12:20:30 -0800436 pullAndMatchEventsLocked(eventTimeNs);
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700437 }
438 // When active state changes from true to false, clear diff base but don't
439 // reset other counters as we may accumulate more value in the bucket.
440 if (mUseDiff && !mIsActive) {
441 resetBase();
442 }
443 }
444
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700445 flushIfNeededLocked(eventTimeNs);
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700446
447 // Let condition timer know of new active state.
448 mConditionTimer.onConditionChanged(mIsActive, eventTimeNs);
Chenjie Yue1361ed2018-07-23 17:33:09 -0700449}
450
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700451void ValueMetricProducer::onConditionChangedLocked(const bool condition,
452 const int64_t eventTimeNs) {
453 ConditionState newCondition = condition ? ConditionState::kTrue : ConditionState::kFalse;
454 bool isEventTooLate = eventTimeNs < mCurrentBucketStartTimeNs;
455
tsaichristine90f95bb2019-11-06 17:06:53 -0800456 // If the config is not active, skip the event.
457 if (!mIsActive) {
458 mCondition = isEventTooLate ? ConditionState::kUnknown : newCondition;
459 return;
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700460 }
461
tsaichristine90f95bb2019-11-06 17:06:53 -0800462 // If the event arrived late, mark the bucket as invalid and skip the event.
463 if (isEventTooLate) {
464 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
465 (long long)mCurrentBucketStartTimeNs);
tsaichristineb87ca152019-12-09 15:19:41 -0800466 StatsdStats::getInstance().noteLateLogEventSkipped(mMetricId);
tsaichristine90f95bb2019-11-06 17:06:53 -0800467 StatsdStats::getInstance().noteConditionChangeInNextBucket(mMetricId);
tsaichristineb87ca152019-12-09 15:19:41 -0800468 invalidateCurrentBucket(eventTimeNs, BucketDropReason::EVENT_IN_WRONG_BUCKET);
tsaichristine90f95bb2019-11-06 17:06:53 -0800469 mCondition = ConditionState::kUnknown;
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700470 mConditionTimer.onConditionChanged(mCondition, eventTimeNs);
tsaichristine90f95bb2019-11-06 17:06:53 -0800471 return;
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700472 }
tsaichristine90f95bb2019-11-06 17:06:53 -0800473
474 // If the previous condition was unknown, mark the bucket as invalid
475 // because the bucket will contain partial data. For example, the condition
476 // change might happen close to the end of the bucket and we might miss a
477 // lot of data.
478 //
479 // We still want to pull to set the base.
480 if (mCondition == ConditionState::kUnknown) {
tsaichristineb87ca152019-12-09 15:19:41 -0800481 invalidateCurrentBucket(eventTimeNs, BucketDropReason::CONDITION_UNKNOWN);
tsaichristine90f95bb2019-11-06 17:06:53 -0800482 }
483
484 // Pull and match for the following condition change cases:
485 // unknown/false -> true - condition changed
486 // true -> false - condition changed
487 // true -> true - old condition was true so we can flush the bucket at the
488 // end if needed.
489 //
490 // We don’t need to pull for unknown -> false or false -> false.
491 //
492 // onConditionChangedLocked might happen on bucket boundaries if this is
493 // called before #onDataPulled.
494 if (mIsPulled &&
495 (newCondition == ConditionState::kTrue || mCondition == ConditionState::kTrue)) {
tsaichristine78b85702019-12-06 12:20:30 -0800496 pullAndMatchEventsLocked(eventTimeNs);
tsaichristine90f95bb2019-11-06 17:06:53 -0800497 }
498
499 // For metrics that use diff, when condition changes from true to false,
500 // clear diff base but don't reset other counts because we may accumulate
501 // more value in the bucket.
502 if (mUseDiff &&
503 (mCondition == ConditionState::kTrue && newCondition == ConditionState::kFalse)) {
504 resetBase();
505 }
506
507 // Update condition state after pulling.
508 mCondition = newCondition;
509
510 flushIfNeededLocked(eventTimeNs);
511 mConditionTimer.onConditionChanged(mCondition, eventTimeNs);
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700512}
513
Tej Singh3be093b2020-03-04 20:08:38 -0800514void ValueMetricProducer::prepareFirstBucketLocked() {
515 // Kicks off the puller immediately if condition is true and diff based.
516 if (mIsActive && mIsPulled && mCondition == ConditionState::kTrue && mUseDiff) {
517 pullAndMatchEventsLocked(mCurrentBucketStartTimeNs);
518 }
519}
520
tsaichristine78b85702019-12-06 12:20:30 -0800521void ValueMetricProducer::pullAndMatchEventsLocked(const int64_t timestampNs) {
Chenjie Yue1361ed2018-07-23 17:33:09 -0700522 vector<std::shared_ptr<LogEvent>> allData;
Tej Singh7b975a82020-05-11 11:05:08 -0700523 if (!mPullerManager->Pull(mPullTagId, mConfigKey, timestampNs, &allData)) {
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000524 ALOGE("Stats puller failed for tag: %d at %lld", mPullTagId, (long long)timestampNs);
tsaichristineb87ca152019-12-09 15:19:41 -0800525 invalidateCurrentBucket(timestampNs, BucketDropReason::PULL_FAILED);
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800526 return;
Chenjie Yub3dda412017-10-24 13:41:59 -0700527 }
Olivier Gaillard11203df2019-02-06 13:18:09 +0000528
tsaichristine78b85702019-12-06 12:20:30 -0800529 accumulateEvents(allData, timestampNs, timestampNs);
Olivier Gaillard11203df2019-02-06 13:18:09 +0000530}
531
532int64_t ValueMetricProducer::calcPreviousBucketEndTime(const int64_t currentTimeNs) {
533 return mTimeBaseNs + ((currentTimeNs - mTimeBaseNs) / mBucketSizeNs) * mBucketSizeNs;
534}
535
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000536// By design, statsd pulls data at bucket boundaries using AlarmManager. These pulls are likely
537// to be delayed. Other events like condition changes or app upgrade which are not based on
538// AlarmManager might have arrived earlier and close the bucket.
Olivier Gaillard11203df2019-02-06 13:18:09 +0000539void ValueMetricProducer::onDataPulled(const std::vector<std::shared_ptr<LogEvent>>& allData,
540 bool pullSuccess, int64_t originalPullTimeNs) {
541 std::lock_guard<std::mutex> lock(mMutex);
tsaichristine90f95bb2019-11-06 17:06:53 -0800542 if (mCondition == ConditionState::kTrue) {
543 // If the pull failed, we won't be able to compute a diff.
544 if (!pullSuccess) {
tsaichristineb87ca152019-12-09 15:19:41 -0800545 invalidateCurrentBucket(originalPullTimeNs, BucketDropReason::PULL_FAILED);
tsaichristine90f95bb2019-11-06 17:06:53 -0800546 } else {
547 bool isEventLate = originalPullTimeNs < getCurrentBucketEndTimeNs();
548 if (isEventLate) {
549 // If the event is late, we are in the middle of a bucket. Just
550 // process the data without trying to snap the data to the nearest bucket.
tsaichristine78b85702019-12-06 12:20:30 -0800551 accumulateEvents(allData, originalPullTimeNs, originalPullTimeNs);
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000552 } else {
tsaichristine90f95bb2019-11-06 17:06:53 -0800553 // For scheduled pulled data, the effective event time is snap to the nearest
554 // bucket end. In the case of waking up from a deep sleep state, we will
555 // attribute to the previous bucket end. If the sleep was long but not very
556 // long, we will be in the immediate next bucket. Previous bucket may get a
557 // larger number as we pull at a later time than real bucket end.
558 //
559 // If the sleep was very long, we skip more than one bucket before sleep. In
560 // this case, if the diff base will be cleared and this new data will serve as
561 // new diff base.
562 int64_t bucketEndTime = calcPreviousBucketEndTime(originalPullTimeNs) - 1;
563 StatsdStats::getInstance().noteBucketBoundaryDelayNs(
564 mMetricId, originalPullTimeNs - bucketEndTime);
tsaichristine78b85702019-12-06 12:20:30 -0800565 accumulateEvents(allData, originalPullTimeNs, bucketEndTime);
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000566 }
Olivier Gaillard11203df2019-02-06 13:18:09 +0000567 }
tsaichristine90f95bb2019-11-06 17:06:53 -0800568 }
Olivier Gaillard11203df2019-02-06 13:18:09 +0000569
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000570 // We can probably flush the bucket. Since we used bucketEndTime when calling
571 // #onMatchedLogEventInternalLocked, the current bucket will not have been flushed.
572 flushIfNeededLocked(originalPullTimeNs);
Olivier Gaillard11203df2019-02-06 13:18:09 +0000573}
574
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000575void ValueMetricProducer::accumulateEvents(const std::vector<std::shared_ptr<LogEvent>>& allData,
tsaichristine78b85702019-12-06 12:20:30 -0800576 int64_t originalPullTimeNs, int64_t eventElapsedTimeNs) {
Olivier Gaillard11203df2019-02-06 13:18:09 +0000577 bool isEventLate = eventElapsedTimeNs < mCurrentBucketStartTimeNs;
578 if (isEventLate) {
579 VLOG("Skip bucket end pull due to late arrival: %lld vs %lld",
580 (long long)eventElapsedTimeNs, (long long)mCurrentBucketStartTimeNs);
581 StatsdStats::getInstance().noteLateLogEventSkipped(mMetricId);
tsaichristineb87ca152019-12-09 15:19:41 -0800582 invalidateCurrentBucket(eventElapsedTimeNs, BucketDropReason::EVENT_IN_WRONG_BUCKET);
Olivier Gaillard11203df2019-02-06 13:18:09 +0000583 return;
584 }
585
tsaichristineb87ca152019-12-09 15:19:41 -0800586 const int64_t elapsedRealtimeNs = getElapsedRealtimeNs();
587 const int64_t pullDelayNs = elapsedRealtimeNs - originalPullTimeNs;
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000588 StatsdStats::getInstance().notePullDelay(mPullTagId, pullDelayNs);
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800589 if (pullDelayNs > mMaxPullDelayNs) {
590 ALOGE("Pull finish too late for atom %d, longer than %lld", mPullTagId,
591 (long long)mMaxPullDelayNs);
592 StatsdStats::getInstance().notePullExceedMaxDelay(mPullTagId);
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000593 // We are missing one pull from the bucket which means we will not have a complete view of
594 // what's going on.
tsaichristineb87ca152019-12-09 15:19:41 -0800595 invalidateCurrentBucket(eventElapsedTimeNs, BucketDropReason::PULL_DELAYED);
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800596 return;
597 }
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800598
Olivier Gaillard11203df2019-02-06 13:18:09 +0000599 mMatchedMetricDimensionKeys.clear();
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800600 for (const auto& data : allData) {
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800601 LogEvent localCopy = data->makeCopy();
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800602 if (mEventMatcherWizard->matchLogEvent(localCopy, mWhatMatcherIndex) ==
603 MatchingState::kMatched) {
Olivier Gaillard11203df2019-02-06 13:18:09 +0000604 localCopy.setElapsedTimestampNs(eventElapsedTimeNs);
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800605 onMatchedLogEventLocked(mWhatMatcherIndex, localCopy);
606 }
607 }
tsaichristinec876b492019-12-10 13:47:05 -0800608 // If a key that is:
609 // 1. Tracked in mCurrentSlicedBucket and
610 // 2. A superset of the current mStateChangePrimaryKey
611 // was not found in the new pulled data (i.e. not in mMatchedDimensionInWhatKeys)
612 // then we need to reset the base.
Olivier Gaillard11203df2019-02-06 13:18:09 +0000613 for (auto& slice : mCurrentSlicedBucket) {
tsaichristinec876b492019-12-10 13:47:05 -0800614 const auto& whatKey = slice.first.getDimensionKeyInWhat();
615 bool presentInPulledData =
616 mMatchedMetricDimensionKeys.find(whatKey) != mMatchedMetricDimensionKeys.end();
617 if (!presentInPulledData && whatKey.contains(mStateChangePrimaryKey.second)) {
618 auto it = mCurrentBaseInfo.find(whatKey);
619 for (auto& baseInfo : it->second) {
620 baseInfo.hasBase = false;
621 baseInfo.hasCurrentState = false;
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800622 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800623 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700624 }
Olivier Gaillard11203df2019-02-06 13:18:09 +0000625 mMatchedMetricDimensionKeys.clear();
626 mHasGlobalBase = true;
Olivier Gaillard1e0d8fc2019-02-11 18:08:43 +0000627
628 // If we reach the guardrail, we might have dropped some data which means the bucket is
629 // incomplete.
630 //
631 // The base also needs to be reset. If we do not have the full data, we might
632 // incorrectly compute the diff when mUseZeroDefaultBase is true since an existing key
633 // might be missing from mCurrentSlicedBucket.
634 if (hasReachedGuardRailLimit()) {
tsaichristineb87ca152019-12-09 15:19:41 -0800635 invalidateCurrentBucket(eventElapsedTimeNs, BucketDropReason::DIMENSION_GUARDRAIL_REACHED);
Olivier Gaillard1e0d8fc2019-02-11 18:08:43 +0000636 mCurrentSlicedBucket.clear();
637 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700638}
639
Yangster-maca78d0082018-03-12 12:02:56 -0700640void ValueMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
641 if (mCurrentSlicedBucket.size() == 0) {
642 return;
643 }
644
645 fprintf(out, "ValueMetric %lld dimension size %lu\n", (long long)mMetricId,
646 (unsigned long)mCurrentSlicedBucket.size());
647 if (verbose) {
648 for (const auto& it : mCurrentSlicedBucket) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700649 for (const auto& interval : it.second) {
tsaichristine69000e62019-10-18 17:34:52 -0700650 fprintf(out, "\t(what)%s\t(states)%s (value)%s\n",
651 it.first.getDimensionKeyInWhat().toString().c_str(),
652 it.first.getStateValuesKey().toString().c_str(),
653 interval.value.toString().c_str());
Chenjie Yu32717c32018-10-20 23:54:48 -0700654 }
Yangster-maca78d0082018-03-12 12:02:56 -0700655 }
656 }
657}
658
Olivier Gaillard1e0d8fc2019-02-11 18:08:43 +0000659bool ValueMetricProducer::hasReachedGuardRailLimit() const {
660 return mCurrentSlicedBucket.size() >= mDimensionHardLimit;
661}
662
Yangster-mac93694462018-01-22 20:49:31 -0800663bool ValueMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800664 // ===========GuardRail==============
665 // 1. Report the tuple count if the tuple count > soft limit
666 if (mCurrentSlicedBucket.find(newKey) != mCurrentSlicedBucket.end()) {
667 return false;
668 }
Chenjie Yuc5875052018-03-09 10:13:11 -0800669 if (mCurrentSlicedBucket.size() > mDimensionSoftLimit - 1) {
Yao Chenb3561512017-11-21 18:07:17 -0800670 size_t newTupleCount = mCurrentSlicedBucket.size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800671 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800672 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
Olivier Gaillard1e0d8fc2019-02-11 18:08:43 +0000673 if (hasReachedGuardRailLimit()) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700674 ALOGE("ValueMetric %lld dropping data for dimension key %s", (long long)mMetricId,
675 newKey.toString().c_str());
Misha Wagner1eee2212019-01-22 11:47:11 +0000676 StatsdStats::getInstance().noteHardDimensionLimitReached(mMetricId);
Yao Chenb3561512017-11-21 18:07:17 -0800677 return true;
678 }
679 }
680
681 return false;
682}
683
Chenjie Yudbe5c502018-11-30 23:15:57 -0800684bool ValueMetricProducer::hitFullBucketGuardRailLocked(const MetricDimensionKey& newKey) {
685 // ===========GuardRail==============
686 // 1. Report the tuple count if the tuple count > soft limit
687 if (mCurrentFullBucket.find(newKey) != mCurrentFullBucket.end()) {
688 return false;
689 }
690 if (mCurrentFullBucket.size() > mDimensionSoftLimit - 1) {
691 size_t newTupleCount = mCurrentFullBucket.size() + 1;
692 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
693 if (newTupleCount > mDimensionHardLimit) {
694 ALOGE("ValueMetric %lld dropping data for full bucket dimension key %s",
695 (long long)mMetricId,
696 newKey.toString().c_str());
697 return true;
698 }
699 }
700
701 return false;
702}
703
Chenjie Yu32717c32018-10-20 23:54:48 -0700704bool getDoubleOrLong(const LogEvent& event, const Matcher& matcher, Value& ret) {
705 for (const FieldValue& value : event.getValues()) {
706 if (value.mField.matches(matcher)) {
707 switch (value.mValue.type) {
708 case INT:
709 ret.setLong(value.mValue.int_value);
710 break;
711 case LONG:
712 ret.setLong(value.mValue.long_value);
713 break;
714 case FLOAT:
715 ret.setDouble(value.mValue.float_value);
716 break;
717 case DOUBLE:
718 ret.setDouble(value.mValue.double_value);
719 break;
720 default:
tsaichristine409468d2019-10-28 11:32:31 -0700721 return false;
Chenjie Yu32717c32018-10-20 23:54:48 -0700722 break;
723 }
724 return true;
725 }
Chenjie Yua0f02242018-07-06 16:14:34 -0700726 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700727 return false;
Chenjie Yua0f02242018-07-06 16:14:34 -0700728}
729
tsaichristinec876b492019-12-10 13:47:05 -0800730void ValueMetricProducer::onMatchedLogEventInternalLocked(
731 const size_t matcherIndex, const MetricDimensionKey& eventKey,
732 const ConditionKey& conditionKey, bool condition, const LogEvent& event,
733 const map<int, HashableDimensionKey>& statePrimaryKeys) {
734 auto whatKey = eventKey.getDimensionKeyInWhat();
735 auto stateKey = eventKey.getStateValuesKey();
736
737 // Skip this event if a state changed occurred for a different primary key.
738 auto it = statePrimaryKeys.find(mStateChangePrimaryKey.first);
739 // Check that both the atom id and the primary key are equal.
740 if (it != statePrimaryKeys.end() && it->second != mStateChangePrimaryKey.second) {
741 VLOG("ValueMetric skip event with primary key %s because state change primary key "
742 "is %s",
743 it->second.toString().c_str(), mStateChangePrimaryKey.second.toString().c_str());
744 return;
745 }
746
Yangster-macb142cc82018-03-30 15:22:08 -0700747 int64_t eventTimeNs = event.GetElapsedTimestampNs();
Yao Chen6a8c7992017-11-29 20:02:07 +0000748 if (eventTimeNs < mCurrentBucketStartTimeNs) {
749 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
750 (long long)mCurrentBucketStartTimeNs);
751 return;
752 }
tsaichristinec876b492019-12-10 13:47:05 -0800753 mMatchedMetricDimensionKeys.insert(whatKey);
Yao Chen6a8c7992017-11-29 20:02:07 +0000754
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000755 if (!mIsPulled) {
756 // We cannot flush without doing a pull first.
757 flushIfNeededLocked(eventTimeNs);
758 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800759
Olivier Gaillardfbee9162019-04-11 11:48:01 +0100760 // We should not accumulate the data for pushed metrics when the condition is false.
761 bool shouldSkipForPushMetric = !mIsPulled && !condition;
762 // For pulled metrics, there are two cases:
763 // - to compute diffs, we need to process all the state changes
764 // - for non-diffs metrics, we should ignore the data if the condition wasn't true. If we have a
765 // state change from
766 // + True -> True: we should process the data, it might be a bucket boundary
767 // + True -> False: we als need to process the data.
768 bool shouldSkipForPulledMetric = mIsPulled && !mUseDiff
769 && mCondition != ConditionState::kTrue;
770 if (shouldSkipForPushMetric || shouldSkipForPulledMetric) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700771 VLOG("ValueMetric skip event because condition is false");
772 return;
773 }
774
Yangsterf2bee6f2017-11-29 12:01:05 -0800775 if (hitGuardRailLocked(eventKey)) {
Yangster8de69392017-11-27 13:48:29 -0800776 return;
777 }
tsaichristinec876b492019-12-10 13:47:05 -0800778 vector<BaseInfo>& baseInfos = mCurrentBaseInfo[whatKey];
779 if (baseInfos.size() < mFieldMatchers.size()) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700780 VLOG("Resizing number of intervals to %d", (int)mFieldMatchers.size());
tsaichristinec876b492019-12-10 13:47:05 -0800781 baseInfos.resize(mFieldMatchers.size());
782 }
783
784 for (auto baseInfo : baseInfos) {
785 if (!baseInfo.hasCurrentState) {
786 baseInfo.currentState = DEFAULT_DIMENSION_KEY;
787 baseInfo.hasCurrentState = true;
788 }
789 }
790
791 // We need to get the intervals stored with the previous state key so we can
792 // close these value intervals.
793 const auto oldStateKey = baseInfos[0].currentState;
794 vector<Interval>& intervals = mCurrentSlicedBucket[MetricDimensionKey(whatKey, oldStateKey)];
795 if (intervals.size() < mFieldMatchers.size()) {
796 VLOG("Resizing number of intervals to %d", (int)mFieldMatchers.size());
797 intervals.resize(mFieldMatchers.size());
Yangster-maca7fb12d2018-01-03 17:17:20 -0800798 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000799
Misha Wagner26531762019-01-21 14:18:51 +0000800 // We only use anomaly detection under certain cases.
801 // N.B.: The anomaly detection cases were modified in order to fix an issue with value metrics
802 // containing multiple values. We tried to retain all previous behaviour, but we are unsure the
803 // previous behaviour was correct. At the time of the fix, anomaly detection had no owner.
804 // Whoever next works on it should look into the cases where it is triggered in this function.
805 // Discussion here: http://ag/6124370.
806 bool useAnomalyDetection = true;
807
Chenjie Yu32717c32018-10-20 23:54:48 -0700808 for (int i = 0; i < (int)mFieldMatchers.size(); i++) {
809 const Matcher& matcher = mFieldMatchers[i];
tsaichristinec876b492019-12-10 13:47:05 -0800810 BaseInfo& baseInfo = baseInfos[i];
811 Interval& interval = intervals[i];
Chenjie Yu32717c32018-10-20 23:54:48 -0700812 interval.valueIndex = i;
813 Value value;
814 if (!getDoubleOrLong(event, matcher, value)) {
815 VLOG("Failed to get value %d from event %s", i, event.ToString().c_str());
Misha Wagner1eee2212019-01-22 11:47:11 +0000816 StatsdStats::getInstance().noteBadValueType(mMetricId);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700817 return;
818 }
Chenjie Yudbe5c502018-11-30 23:15:57 -0800819 interval.seenNewData = true;
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700820
Chenjie Yu32717c32018-10-20 23:54:48 -0700821 if (mUseDiff) {
tsaichristinec876b492019-12-10 13:47:05 -0800822 if (!baseInfo.hasBase) {
Chenjie Yuf275f612018-11-30 23:29:06 -0800823 if (mHasGlobalBase && mUseZeroDefaultBase) {
824 // The bucket has global base. This key does not.
825 // Optionally use zero as base.
tsaichristinec876b492019-12-10 13:47:05 -0800826 baseInfo.base = (value.type == LONG ? ZERO_LONG : ZERO_DOUBLE);
827 baseInfo.hasBase = true;
Chenjie Yuf275f612018-11-30 23:29:06 -0800828 } else {
829 // no base. just update base and return.
tsaichristinec876b492019-12-10 13:47:05 -0800830 baseInfo.base = value;
831 baseInfo.hasBase = true;
Misha Wagner26531762019-01-21 14:18:51 +0000832 // If we're missing a base, do not use anomaly detection on incomplete data
833 useAnomalyDetection = false;
tsaichristinec876b492019-12-10 13:47:05 -0800834 // Continue (instead of return) here in order to set baseInfo.base and
835 // baseInfo.hasBase for other baseInfos
Misha Wagner26531762019-01-21 14:18:51 +0000836 continue;
Chenjie Yuf275f612018-11-30 23:29:06 -0800837 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700838 }
tsaichristinec876b492019-12-10 13:47:05 -0800839
Chenjie Yu32717c32018-10-20 23:54:48 -0700840 Value diff;
841 switch (mValueDirection) {
842 case ValueMetric::INCREASING:
tsaichristinec876b492019-12-10 13:47:05 -0800843 if (value >= baseInfo.base) {
844 diff = value - baseInfo.base;
Chenjie Yu32717c32018-10-20 23:54:48 -0700845 } else if (mUseAbsoluteValueOnReset) {
846 diff = value;
847 } else {
848 VLOG("Unexpected decreasing value");
849 StatsdStats::getInstance().notePullDataError(mPullTagId);
tsaichristinec876b492019-12-10 13:47:05 -0800850 baseInfo.base = value;
Misha Wagner26531762019-01-21 14:18:51 +0000851 // If we've got bad data, do not use anomaly detection
852 useAnomalyDetection = false;
853 continue;
Chenjie Yu32717c32018-10-20 23:54:48 -0700854 }
855 break;
856 case ValueMetric::DECREASING:
tsaichristinec876b492019-12-10 13:47:05 -0800857 if (baseInfo.base >= value) {
858 diff = baseInfo.base - value;
Chenjie Yu32717c32018-10-20 23:54:48 -0700859 } else if (mUseAbsoluteValueOnReset) {
860 diff = value;
861 } else {
862 VLOG("Unexpected increasing value");
863 StatsdStats::getInstance().notePullDataError(mPullTagId);
tsaichristinec876b492019-12-10 13:47:05 -0800864 baseInfo.base = value;
Misha Wagner26531762019-01-21 14:18:51 +0000865 // If we've got bad data, do not use anomaly detection
866 useAnomalyDetection = false;
867 continue;
Chenjie Yu32717c32018-10-20 23:54:48 -0700868 }
869 break;
870 case ValueMetric::ANY:
tsaichristinec876b492019-12-10 13:47:05 -0800871 diff = value - baseInfo.base;
Chenjie Yu32717c32018-10-20 23:54:48 -0700872 break;
873 default:
874 break;
875 }
tsaichristinec876b492019-12-10 13:47:05 -0800876 baseInfo.base = value;
Chenjie Yu32717c32018-10-20 23:54:48 -0700877 value = diff;
Yao Chen6a8c7992017-11-29 20:02:07 +0000878 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700879
880 if (interval.hasValue) {
881 switch (mAggregationType) {
882 case ValueMetric::SUM:
883 // for AVG, we add up and take average when flushing the bucket
884 case ValueMetric::AVG:
885 interval.value += value;
886 break;
887 case ValueMetric::MIN:
888 interval.value = std::min(value, interval.value);
889 break;
890 case ValueMetric::MAX:
891 interval.value = std::max(value, interval.value);
892 break;
893 default:
894 break;
895 }
896 } else {
897 interval.value = value;
898 interval.hasValue = true;
899 }
900 interval.sampleSize += 1;
tsaichristinec876b492019-12-10 13:47:05 -0800901 baseInfo.currentState = stateKey;
Yangster8de69392017-11-27 13:48:29 -0800902 }
Bookatzde1b55622017-12-14 18:38:27 -0800903
Misha Wagner26531762019-01-21 14:18:51 +0000904 // Only trigger the tracker if all intervals are correct
905 if (useAnomalyDetection) {
906 // TODO: propgate proper values down stream when anomaly support doubles
tsaichristinec876b492019-12-10 13:47:05 -0800907 long wholeBucketVal = intervals[0].value.long_value;
Misha Wagner26531762019-01-21 14:18:51 +0000908 auto prev = mCurrentFullBucket.find(eventKey);
909 if (prev != mCurrentFullBucket.end()) {
910 wholeBucketVal += prev->second;
911 }
912 for (auto& tracker : mAnomalyTrackers) {
Yao Chen4ce07292019-02-13 13:06:36 -0800913 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, mMetricId, eventKey,
914 wholeBucketVal);
Misha Wagner26531762019-01-21 14:18:51 +0000915 }
Bookatzde1b55622017-12-14 18:38:27 -0800916 }
Yangster8de69392017-11-27 13:48:29 -0800917}
918
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000919// For pulled metrics, we always need to make sure we do a pull before flushing the bucket
920// if mCondition is true!
Yangster-macb142cc82018-03-30 15:22:08 -0700921void ValueMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
922 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700923 if (eventTimeNs < currentBucketEndTimeNs) {
tsaichristine90f95bb2019-11-06 17:06:53 -0800924 VLOG("eventTime is %lld, less than current bucket end time %lld", (long long)eventTimeNs,
David Chen27785a82018-01-19 17:06:45 -0800925 (long long)(currentBucketEndTimeNs));
Chenjie Yub3dda412017-10-24 13:41:59 -0700926 return;
927 }
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000928 int64_t numBucketsForward = calcBucketsForwardCount(eventTimeNs);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000929 int64_t nextBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
930 flushCurrentBucketLocked(eventTimeNs, nextBucketStartTimeNs);
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000931}
David Chen27785a82018-01-19 17:06:45 -0800932
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000933int64_t ValueMetricProducer::calcBucketsForwardCount(const int64_t& eventTimeNs) const {
934 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
935 if (eventTimeNs < currentBucketEndTimeNs) {
936 return 0;
David Chen27785a82018-01-19 17:06:45 -0800937 }
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000938 return 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
David Chen27785a82018-01-19 17:06:45 -0800939}
940
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000941void ValueMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs,
942 const int64_t& nextBucketStartTimeNs) {
Olivier Gaillarde63d9e02019-02-12 14:43:59 +0000943 if (mCondition == ConditionState::kUnknown) {
944 StatsdStats::getInstance().noteBucketUnknownCondition(mMetricId);
945 }
946
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000947 int64_t numBucketsForward = calcBucketsForwardCount(eventTimeNs);
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000948 if (numBucketsForward > 1) {
949 VLOG("Skipping forward %lld buckets", (long long)numBucketsForward);
950 StatsdStats::getInstance().noteSkippedForwardBuckets(mMetricId);
951 // Something went wrong. Maybe the device was sleeping for a long time. It is better
952 // to mark the current bucket as invalid. The last pull might have been successful through.
tsaichristineb87ca152019-12-09 15:19:41 -0800953 invalidateCurrentBucketWithoutResetBase(eventTimeNs,
954 BucketDropReason::MULTIPLE_BUCKETS_SKIPPED);
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000955 }
956
Chenjie Yub3dda412017-10-24 13:41:59 -0700957 VLOG("finalizing bucket for %ld, dumping %d slices", (long)mCurrentBucketStartTimeNs,
958 (int)mCurrentSlicedBucket.size());
Yangster-macb142cc82018-03-30 15:22:08 -0700959 int64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
Chenjie Yu32717c32018-10-20 23:54:48 -0700960 int64_t bucketEndTime = eventTimeNs < fullBucketEndTimeNs ? eventTimeNs : fullBucketEndTimeNs;
Yao Chene6cfb142019-04-08 12:00:01 -0700961 // Close the current bucket.
962 int64_t conditionTrueDuration = mConditionTimer.newBucketStart(bucketEndTime);
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000963 bool isBucketLargeEnough = bucketEndTime - mCurrentBucketStartTimeNs >= mMinBucketSizeNs;
tsaichristineb87ca152019-12-09 15:19:41 -0800964 if (!isBucketLargeEnough) {
tsaichristineb87ca152019-12-09 15:19:41 -0800965 if (!maxDropEventsReached()) {
966 mCurrentSkippedBucket.dropEvents.emplace_back(
967 buildDropEvent(eventTimeNs, BucketDropReason::BUCKET_TOO_SMALL));
968 }
969 }
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000970 if (isBucketLargeEnough && !mCurrentBucketIsInvalid) {
David Chen81245fd2018-04-12 14:33:37 -0700971 // The current bucket is large enough to keep.
David Chen81245fd2018-04-12 14:33:37 -0700972 for (const auto& slice : mCurrentSlicedBucket) {
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000973 ValueBucket bucket = buildPartialBucket(bucketEndTime, slice.second);
Yao Chene6cfb142019-04-08 12:00:01 -0700974 bucket.mConditionTrueNs = conditionTrueDuration;
Chenjie Yu32717c32018-10-20 23:54:48 -0700975 // it will auto create new vector of ValuebucketInfo if the key is not found.
976 if (bucket.valueIndex.size() > 0) {
David Chen81245fd2018-04-12 14:33:37 -0700977 auto& bucketList = mPastBuckets[slice.first];
Chenjie Yu32717c32018-10-20 23:54:48 -0700978 bucketList.push_back(bucket);
David Chen81245fd2018-04-12 14:33:37 -0700979 }
Chenjie Yuae63b0a2018-04-10 14:59:31 -0700980 }
David Chen81245fd2018-04-12 14:33:37 -0700981 } else {
tsaichristine45f703b2020-02-03 10:44:39 -0800982 mCurrentSkippedBucket.bucketStartTimeNs = mCurrentBucketStartTimeNs;
983 mCurrentSkippedBucket.bucketEndTimeNs = bucketEndTime;
tsaichristineb87ca152019-12-09 15:19:41 -0800984 mSkippedBuckets.emplace_back(mCurrentSkippedBucket);
Chenjie Yub3dda412017-10-24 13:41:59 -0700985 }
986
Olivier Gaillardc3719912019-03-15 17:33:40 +0000987 appendToFullBucket(eventTimeNs, fullBucketEndTimeNs);
Olivier Gaillarda8b70112019-02-25 11:24:23 +0000988 initCurrentSlicedBucket(nextBucketStartTimeNs);
Yao Chene6cfb142019-04-08 12:00:01 -0700989 // Update the condition timer again, in case we skipped buckets.
990 mConditionTimer.newBucketStart(nextBucketStartTimeNs);
Olivier Gaillardc3719912019-03-15 17:33:40 +0000991 mCurrentBucketNum += numBucketsForward;
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000992}
993
994ValueBucket ValueMetricProducer::buildPartialBucket(int64_t bucketEndTime,
995 const std::vector<Interval>& intervals) {
996 ValueBucket bucket;
997 bucket.mBucketStartNs = mCurrentBucketStartTimeNs;
998 bucket.mBucketEndNs = bucketEndTime;
999 for (const auto& interval : intervals) {
1000 if (interval.hasValue) {
1001 // skip the output if the diff is zero
1002 if (mSkipZeroDiffOutput && mUseDiff && interval.value.isZero()) {
1003 continue;
1004 }
1005 bucket.valueIndex.push_back(interval.valueIndex);
1006 if (mAggregationType != ValueMetric::AVG) {
1007 bucket.values.push_back(interval.value);
1008 } else {
1009 double sum = interval.value.type == LONG ? (double)interval.value.long_value
1010 : interval.value.double_value;
1011 bucket.values.push_back(Value((double)sum / interval.sampleSize));
1012 }
1013 }
1014 }
1015 return bucket;
1016}
1017
Olivier Gaillarda8b70112019-02-25 11:24:23 +00001018void ValueMetricProducer::initCurrentSlicedBucket(int64_t nextBucketStartTimeNs) {
1019 StatsdStats::getInstance().noteBucketCount(mMetricId);
1020 // Cleanup data structure to aggregate values.
Olivier Gaillard9a5d3592019-02-05 15:12:39 +00001021 for (auto it = mCurrentSlicedBucket.begin(); it != mCurrentSlicedBucket.end();) {
1022 bool obsolete = true;
1023 for (auto& interval : it->second) {
1024 interval.hasValue = false;
1025 interval.sampleSize = 0;
1026 if (interval.seenNewData) {
1027 obsolete = false;
1028 }
1029 interval.seenNewData = false;
1030 }
1031
1032 if (obsolete) {
1033 it = mCurrentSlicedBucket.erase(it);
1034 } else {
1035 it++;
1036 }
tsaichristinec876b492019-12-10 13:47:05 -08001037 // TODO: remove mCurrentBaseInfo entries when obsolete
Olivier Gaillard9a5d3592019-02-05 15:12:39 +00001038 }
Olivier Gaillarda8b70112019-02-25 11:24:23 +00001039
1040 mCurrentBucketIsInvalid = false;
tsaichristineb87ca152019-12-09 15:19:41 -08001041 mCurrentSkippedBucket.reset();
1042
Olivier Gaillarda8b70112019-02-25 11:24:23 +00001043 // If we do not have a global base when the condition is true,
1044 // we will have incomplete bucket for the next bucket.
1045 if (mUseDiff && !mHasGlobalBase && mCondition) {
1046 mCurrentBucketIsInvalid = false;
1047 }
1048 mCurrentBucketStartTimeNs = nextBucketStartTimeNs;
1049 VLOG("metric %lld: new bucket start time: %lld", (long long)mMetricId,
1050 (long long)mCurrentBucketStartTimeNs);
Olivier Gaillard9a5d3592019-02-05 15:12:39 +00001051}
1052
1053void ValueMetricProducer::appendToFullBucket(int64_t eventTimeNs, int64_t fullBucketEndTimeNs) {
Olivier Gaillardc3719912019-03-15 17:33:40 +00001054 bool isFullBucketReached = eventTimeNs > fullBucketEndTimeNs;
1055 if (mCurrentBucketIsInvalid) {
1056 if (isFullBucketReached) {
1057 // If the bucket is invalid, we ignore the full bucket since it contains invalid data.
1058 mCurrentFullBucket.clear();
1059 }
1060 // Current bucket is invalid, we do not add it to the full bucket.
1061 return;
1062 }
1063
1064 if (isFullBucketReached) { // If full bucket, send to anomaly tracker.
David Chen27785a82018-01-19 17:06:45 -08001065 // Accumulate partial buckets with current value and then send to anomaly tracker.
1066 if (mCurrentFullBucket.size() > 0) {
1067 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yudbe5c502018-11-30 23:15:57 -08001068 if (hitFullBucketGuardRailLocked(slice.first)) {
1069 continue;
1070 }
Chenjie Yua0f02242018-07-06 16:14:34 -07001071 // TODO: fix this when anomaly can accept double values
Olivier Gaillardc3719912019-03-15 17:33:40 +00001072 auto& interval = slice.second[0];
1073 if (interval.hasValue) {
1074 mCurrentFullBucket[slice.first] += interval.value.long_value;
1075 }
David Chen27785a82018-01-19 17:06:45 -08001076 }
1077 for (const auto& slice : mCurrentFullBucket) {
1078 for (auto& tracker : mAnomalyTrackers) {
1079 if (tracker != nullptr) {
1080 tracker->addPastBucket(slice.first, slice.second, mCurrentBucketNum);
1081 }
1082 }
1083 }
1084 mCurrentFullBucket.clear();
1085 } else {
1086 // Skip aggregating the partial buckets since there's no previous partial bucket.
1087 for (const auto& slice : mCurrentSlicedBucket) {
1088 for (auto& tracker : mAnomalyTrackers) {
1089 if (tracker != nullptr) {
Chenjie Yua0f02242018-07-06 16:14:34 -07001090 // TODO: fix this when anomaly can accept double values
Olivier Gaillardc3719912019-03-15 17:33:40 +00001091 auto& interval = slice.second[0];
1092 if (interval.hasValue) {
1093 tracker->addPastBucket(slice.first, interval.value.long_value,
1094 mCurrentBucketNum);
1095 }
David Chen27785a82018-01-19 17:06:45 -08001096 }
1097 }
1098 }
1099 }
1100 } else {
1101 // Accumulate partial bucket.
1102 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yua0f02242018-07-06 16:14:34 -07001103 // TODO: fix this when anomaly can accept double values
Olivier Gaillardc3719912019-03-15 17:33:40 +00001104 auto& interval = slice.second[0];
1105 if (interval.hasValue) {
1106 mCurrentFullBucket[slice.first] += interval.value.long_value;
1107 }
David Chen27785a82018-01-19 17:06:45 -08001108 }
1109 }
Chenjie Yub3dda412017-10-24 13:41:59 -07001110}
1111
Yangsterf2bee6f2017-11-29 12:01:05 -08001112size_t ValueMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -08001113 size_t totalSize = 0;
1114 for (const auto& pair : mPastBuckets) {
1115 totalSize += pair.second.size() * kBucketSize;
1116 }
1117 return totalSize;
yro2b0f8862017-11-06 14:27:31 -08001118}
1119
Chenjie Yub3dda412017-10-24 13:41:59 -07001120} // namespace statsd
1121} // namespace os
Yao Chen93fe3a32017-11-02 13:52:59 -07001122} // namespace android