blob: bf636a4f048d6facee5fddce2d5f728029f41389 [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,
185 const HashableDimensionKey& primaryKey, int oldState,
186 int newState) {
187 VLOG("ValueMetric %lld onStateChanged time %lld, State %d, key %s, %d -> %d",
188 (long long)mMetricId, (long long)eventTimeNs, atomId, primaryKey.toString().c_str(),
189 oldState, newState);
190 // If condition is not true, we do not need to pull for this state change.
191 if (mCondition != ConditionState::kTrue) {
192 return;
193 }
194 bool isEventLate = eventTimeNs < mCurrentBucketStartTimeNs;
195 if (isEventLate) {
196 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
197 (long long)mCurrentBucketStartTimeNs);
198 invalidateCurrentBucket(eventTimeNs, BucketDropReason::EVENT_IN_WRONG_BUCKET);
199 return;
200 }
201 mStateChangePrimaryKey.first = atomId;
202 mStateChangePrimaryKey.second = primaryKey;
203 if (mIsPulled) {
204 pullAndMatchEventsLocked(eventTimeNs);
205 }
206 mStateChangePrimaryKey.first = 0;
207 mStateChangePrimaryKey.second = DEFAULT_DIMENSION_KEY;
208 flushIfNeededLocked(eventTimeNs);
209}
210
Yao Chen427d3722018-03-22 15:21:52 -0700211void ValueMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
Yangster-macb142cc82018-03-30 15:22:08 -0700212 const int64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800213 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Chenjie Yub3dda412017-10-24 13:41:59 -0700214}
215
Yangster-macb142cc82018-03-30 15:22:08 -0700216void ValueMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
Olivier Gaillard320952b2019-02-06 13:57:24 +0000217 StatsdStats::getInstance().noteBucketDropped(mMetricId);
tsaichristineb7fcf002019-12-06 18:40:47 -0800218
219 // The current partial bucket is not flushed and does not require a pull,
220 // so the data is still valid.
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000221 flushIfNeededLocked(dropTimeNs);
222 clearPastBucketsLocked(dropTimeNs);
Yao Chen06dba5d2018-01-26 13:38:16 -0800223}
224
Yangster-maca802d732018-04-24 07:50:38 -0700225void ValueMetricProducer::clearPastBucketsLocked(const int64_t dumpTimeNs) {
Yangster-maca802d732018-04-24 07:50:38 -0700226 mPastBuckets.clear();
227 mSkippedBuckets.clear();
228}
229
Yangster-macb142cc82018-03-30 15:22:08 -0700230void ValueMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700231 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700232 const bool erase_data,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000233 const DumpLatency dumpLatency,
Yangster-mac9def8e32018-04-17 13:55:51 -0700234 std::set<string> *str_set,
Yao Chen288c6002017-12-12 13:43:18 -0800235 ProtoOutputStream* protoOutput) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800236 VLOG("metric %lld dump report now...", (long long)mMetricId);
Yangster-mace68f3a52018-04-04 00:01:43 -0700237 if (include_current_partial_bucket) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000238 // For pull metrics, we need to do a pull at bucket boundaries. If we do not do that the
239 // current bucket will have incomplete data and the next will have the wrong snapshot to do
240 // a diff against. If the condition is false, we are fine since the base data is reset and
241 // we are not tracking anything.
242 bool pullNeeded = mIsPulled && mCondition == ConditionState::kTrue;
243 if (pullNeeded) {
244 switch (dumpLatency) {
245 case FAST:
tsaichristineb87ca152019-12-09 15:19:41 -0800246 invalidateCurrentBucket(dumpTimeNs, BucketDropReason::DUMP_REPORT_REQUESTED);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000247 break;
248 case NO_TIME_CONSTRAINTS:
tsaichristine78b85702019-12-06 12:20:30 -0800249 pullAndMatchEventsLocked(dumpTimeNs);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000250 break;
251 }
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000252 }
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000253 flushCurrentBucketLocked(dumpTimeNs, dumpTimeNs);
Yangster-mace68f3a52018-04-04 00:01:43 -0700254 }
Yang Lub4722912018-11-15 11:02:03 -0800255 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Howard Ro07e23ff2018-12-17 17:28:07 -0800256 protoOutput->write(FIELD_TYPE_BOOL | FIELD_ID_IS_ACTIVE, isActiveLocked());
Yang Lub4722912018-11-15 11:02:03 -0800257
David Chen81245fd2018-04-12 14:33:37 -0700258 if (mPastBuckets.empty() && mSkippedBuckets.empty()) {
Yangster-mac635b4b32018-01-23 20:17:35 -0800259 return;
260 }
Yangster-mac9def8e32018-04-17 13:55:51 -0700261 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_TIME_BASE, (long long)mTimeBaseNs);
262 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_SIZE, (long long)mBucketSizeNs);
263 // Fills the dimension path if not slicing by ALL.
264 if (!mSliceByPositionALL) {
265 if (!mDimensionsInWhat.empty()) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700266 uint64_t dimenPathToken =
267 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_WHAT);
Yangster-mac9def8e32018-04-17 13:55:51 -0700268 writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
269 protoOutput->end(dimenPathToken);
270 }
Yangster-mac9def8e32018-04-17 13:55:51 -0700271 }
272
Yi Jin5ee07872018-03-05 18:18:27 -0800273 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_VALUE_METRICS);
Yao Chen6a8c7992017-11-29 20:02:07 +0000274
tsaichristineb87ca152019-12-09 15:19:41 -0800275 for (const auto& skippedBucket : mSkippedBuckets) {
David Chen81245fd2018-04-12 14:33:37 -0700276 uint64_t wrapperToken =
277 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_SKIPPED);
Yangster-mac9def8e32018-04-17 13:55:51 -0700278 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_START_MILLIS,
tsaichristineb87ca152019-12-09 15:19:41 -0800279 (long long)(NanoToMillis(skippedBucket.bucketStartTimeNs)));
Yangster-mac9def8e32018-04-17 13:55:51 -0700280 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_END_MILLIS,
tsaichristineb87ca152019-12-09 15:19:41 -0800281 (long long)(NanoToMillis(skippedBucket.bucketEndTimeNs)));
282 for (const auto& dropEvent : skippedBucket.dropEvents) {
283 uint64_t dropEventToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
284 FIELD_ID_SKIPPED_DROP_EVENT);
285 protoOutput->write(FIELD_TYPE_INT32 | FIELD_ID_BUCKET_DROP_REASON, dropEvent.reason);
286 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_DROP_TIME,
287 (long long)(NanoToMillis(dropEvent.dropTimeNs)));
288 ;
289 protoOutput->end(dropEventToken);
290 }
David Chen81245fd2018-04-12 14:33:37 -0700291 protoOutput->end(wrapperToken);
292 }
David Chen81245fd2018-04-12 14:33:37 -0700293
Yao Chen93fe3a32017-11-02 13:52:59 -0700294 for (const auto& pair : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800295 const MetricDimensionKey& dimensionKey = pair.first;
Yangster13fb7e42018-03-07 17:30:49 -0800296 VLOG(" dimension key %s", dimensionKey.toString().c_str());
Yi Jin5ee07872018-03-05 18:18:27 -0800297 uint64_t wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800298 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
Chenjie Yub3dda412017-10-24 13:41:59 -0700299
Yangster-mac20877162017-12-22 17:19:39 -0800300 // First fill dimension.
Yangster-mac9def8e32018-04-17 13:55:51 -0700301 if (mSliceByPositionALL) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700302 uint64_t dimensionToken =
303 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
Yangster-mac9def8e32018-04-17 13:55:51 -0700304 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), str_set, protoOutput);
305 protoOutput->end(dimensionToken);
Yangster-mac9def8e32018-04-17 13:55:51 -0700306 } else {
307 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInWhat(),
308 FIELD_ID_DIMENSION_LEAF_IN_WHAT, str_set, protoOutput);
Yangster-mac93694462018-01-22 20:49:31 -0800309 }
yro2b0f8862017-11-06 14:27:31 -0800310
tsaichristinec876b492019-12-10 13:47:05 -0800311 // Then fill slice_by_state.
312 for (auto state : dimensionKey.getStateValuesKey().getValues()) {
313 uint64_t stateToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
314 FIELD_ID_SLICE_BY_STATE);
315 writeStateToProto(state, protoOutput);
316 protoOutput->end(stateToken);
317 }
318
yro2b0f8862017-11-06 14:27:31 -0800319 // Then fill bucket_info (ValueBucketInfo).
320 for (const auto& bucket : pair.second) {
Yi Jin5ee07872018-03-05 18:18:27 -0800321 uint64_t bucketInfoToken = protoOutput->start(
Yao Chen288c6002017-12-12 13:43:18 -0800322 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
Yangster-mac9def8e32018-04-17 13:55:51 -0700323
324 if (bucket.mBucketEndNs - bucket.mBucketStartNs != mBucketSizeNs) {
325 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_MILLIS,
326 (long long)NanoToMillis(bucket.mBucketStartNs));
327 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_MILLIS,
328 (long long)NanoToMillis(bucket.mBucketEndNs));
329 } else {
330 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_NUM,
331 (long long)(getBucketNumFromEndTimeNs(bucket.mBucketEndNs)));
332 }
Yao Chene6cfb142019-04-08 12:00:01 -0700333 // only write the condition timer value if the metric has a condition.
334 if (mConditionTrackerIndex >= 0) {
335 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_CONDITION_TRUE_NS,
336 (long long)bucket.mConditionTrueNs);
337 }
tsaichristinec876b492019-12-10 13:47:05 -0800338 for (int i = 0; i < (int)bucket.valueIndex.size(); i++) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700339 int index = bucket.valueIndex[i];
340 const Value& value = bucket.values[i];
341 uint64_t valueToken = protoOutput->start(
342 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_VALUES);
343 protoOutput->write(FIELD_TYPE_INT32 | FIELD_ID_VALUE_INDEX,
344 index);
345 if (value.getType() == LONG) {
346 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_VALUE_LONG,
347 (long long)value.long_value);
348 VLOG("\t bucket [%lld - %lld] value %d: %lld", (long long)bucket.mBucketStartNs,
349 (long long)bucket.mBucketEndNs, index, (long long)value.long_value);
350 } else if (value.getType() == DOUBLE) {
351 protoOutput->write(FIELD_TYPE_DOUBLE | FIELD_ID_VALUE_DOUBLE,
352 value.double_value);
353 VLOG("\t bucket [%lld - %lld] value %d: %.2f", (long long)bucket.mBucketStartNs,
354 (long long)bucket.mBucketEndNs, index, value.double_value);
355 } else {
356 VLOG("Wrong value type for ValueMetric output: %d", value.getType());
357 }
358 protoOutput->end(valueToken);
Chenjie Yua0f02242018-07-06 16:14:34 -0700359 }
Yao Chen288c6002017-12-12 13:43:18 -0800360 protoOutput->end(bucketInfoToken);
yro2b0f8862017-11-06 14:27:31 -0800361 }
Yao Chen288c6002017-12-12 13:43:18 -0800362 protoOutput->end(wrapperToken);
Chenjie Yub3dda412017-10-24 13:41:59 -0700363 }
Yao Chen288c6002017-12-12 13:43:18 -0800364 protoOutput->end(protoToken);
yro2b0f8862017-11-06 14:27:31 -0800365
Yangster-mac94e197c2018-01-02 16:03:03 -0800366 VLOG("metric %lld dump report now...", (long long)mMetricId);
Bookatzff71cad2018-09-20 17:17:49 -0700367 if (erase_data) {
368 mPastBuckets.clear();
369 mSkippedBuckets.clear();
370 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700371}
372
tsaichristineb87ca152019-12-09 15:19:41 -0800373void ValueMetricProducer::invalidateCurrentBucketWithoutResetBase(const int64_t dropTimeNs,
374 const BucketDropReason reason) {
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000375 if (!mCurrentBucketIsInvalid) {
tsaichristineb87ca152019-12-09 15:19:41 -0800376 // Only report to StatsdStats once per invalid bucket.
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000377 StatsdStats::getInstance().noteInvalidatedBucket(mMetricId);
tsaichristineb87ca152019-12-09 15:19:41 -0800378 }
379
380 if (!maxDropEventsReached()) {
381 mCurrentSkippedBucket.dropEvents.emplace_back(buildDropEvent(dropTimeNs, reason));
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000382 }
383 mCurrentBucketIsInvalid = true;
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000384}
385
tsaichristineb87ca152019-12-09 15:19:41 -0800386void ValueMetricProducer::invalidateCurrentBucket(const int64_t dropTimeNs,
387 const BucketDropReason reason) {
388 invalidateCurrentBucketWithoutResetBase(dropTimeNs, reason);
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000389 resetBase();
390}
391
Chenjie Yuf275f612018-11-30 23:29:06 -0800392void ValueMetricProducer::resetBase() {
tsaichristinec876b492019-12-10 13:47:05 -0800393 for (auto& slice : mCurrentBaseInfo) {
394 for (auto& baseInfo : slice.second) {
395 baseInfo.hasBase = false;
396 baseInfo.hasCurrentState = false;
Chenjie Yuf275f612018-11-30 23:29:06 -0800397 }
398 }
399 mHasGlobalBase = false;
400}
401
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700402// Handle active state change. Active state change is treated like a condition change:
403// - drop bucket if active state change event arrives too late
404// - if condition is true, pull data on active state changes
405// - ConditionTimer tracks changes based on AND of condition and active state.
406void ValueMetricProducer::onActiveStateChangedLocked(const int64_t& eventTimeNs) {
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000407 bool isEventTooLate = eventTimeNs < mCurrentBucketStartTimeNs;
tsaichristine90f95bb2019-11-06 17:06:53 -0800408 if (isEventTooLate) {
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700409 // Drop bucket because event arrived too late, ie. we are missing data for this bucket.
tsaichristineb87ca152019-12-09 15:19:41 -0800410 StatsdStats::getInstance().noteLateLogEventSkipped(mMetricId);
411 invalidateCurrentBucket(eventTimeNs, BucketDropReason::EVENT_IN_WRONG_BUCKET);
Yao Chen2794da22017-12-13 16:01:55 -0800412 }
413
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700414 // Call parent method once we've verified the validity of current bucket.
415 MetricProducer::onActiveStateChangedLocked(eventTimeNs);
416
417 if (ConditionState::kTrue != mCondition) {
418 return;
419 }
420
421 // Pull on active state changes.
422 if (!isEventTooLate) {
423 if (mIsPulled) {
tsaichristine78b85702019-12-06 12:20:30 -0800424 pullAndMatchEventsLocked(eventTimeNs);
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700425 }
426 // When active state changes from true to false, clear diff base but don't
427 // reset other counters as we may accumulate more value in the bucket.
428 if (mUseDiff && !mIsActive) {
429 resetBase();
430 }
431 }
432
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700433 flushIfNeededLocked(eventTimeNs);
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700434
435 // Let condition timer know of new active state.
436 mConditionTimer.onConditionChanged(mIsActive, eventTimeNs);
Chenjie Yue1361ed2018-07-23 17:33:09 -0700437}
438
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700439void ValueMetricProducer::onConditionChangedLocked(const bool condition,
440 const int64_t eventTimeNs) {
441 ConditionState newCondition = condition ? ConditionState::kTrue : ConditionState::kFalse;
442 bool isEventTooLate = eventTimeNs < mCurrentBucketStartTimeNs;
443
tsaichristine90f95bb2019-11-06 17:06:53 -0800444 // If the config is not active, skip the event.
445 if (!mIsActive) {
446 mCondition = isEventTooLate ? ConditionState::kUnknown : newCondition;
447 return;
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700448 }
449
tsaichristine90f95bb2019-11-06 17:06:53 -0800450 // If the event arrived late, mark the bucket as invalid and skip the event.
451 if (isEventTooLate) {
452 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
453 (long long)mCurrentBucketStartTimeNs);
tsaichristineb87ca152019-12-09 15:19:41 -0800454 StatsdStats::getInstance().noteLateLogEventSkipped(mMetricId);
tsaichristine90f95bb2019-11-06 17:06:53 -0800455 StatsdStats::getInstance().noteConditionChangeInNextBucket(mMetricId);
tsaichristineb87ca152019-12-09 15:19:41 -0800456 invalidateCurrentBucket(eventTimeNs, BucketDropReason::EVENT_IN_WRONG_BUCKET);
tsaichristine90f95bb2019-11-06 17:06:53 -0800457 mCondition = ConditionState::kUnknown;
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700458 mConditionTimer.onConditionChanged(mCondition, eventTimeNs);
tsaichristine90f95bb2019-11-06 17:06:53 -0800459 return;
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700460 }
tsaichristine90f95bb2019-11-06 17:06:53 -0800461
462 // If the previous condition was unknown, mark the bucket as invalid
463 // because the bucket will contain partial data. For example, the condition
464 // change might happen close to the end of the bucket and we might miss a
465 // lot of data.
466 //
467 // We still want to pull to set the base.
468 if (mCondition == ConditionState::kUnknown) {
tsaichristineb87ca152019-12-09 15:19:41 -0800469 invalidateCurrentBucket(eventTimeNs, BucketDropReason::CONDITION_UNKNOWN);
tsaichristine90f95bb2019-11-06 17:06:53 -0800470 }
471
472 // Pull and match for the following condition change cases:
473 // unknown/false -> true - condition changed
474 // true -> false - condition changed
475 // true -> true - old condition was true so we can flush the bucket at the
476 // end if needed.
477 //
478 // We don’t need to pull for unknown -> false or false -> false.
479 //
480 // onConditionChangedLocked might happen on bucket boundaries if this is
481 // called before #onDataPulled.
482 if (mIsPulled &&
483 (newCondition == ConditionState::kTrue || mCondition == ConditionState::kTrue)) {
tsaichristine78b85702019-12-06 12:20:30 -0800484 pullAndMatchEventsLocked(eventTimeNs);
tsaichristine90f95bb2019-11-06 17:06:53 -0800485 }
486
487 // For metrics that use diff, when condition changes from true to false,
488 // clear diff base but don't reset other counts because we may accumulate
489 // more value in the bucket.
490 if (mUseDiff &&
491 (mCondition == ConditionState::kTrue && newCondition == ConditionState::kFalse)) {
492 resetBase();
493 }
494
495 // Update condition state after pulling.
496 mCondition = newCondition;
497
498 flushIfNeededLocked(eventTimeNs);
499 mConditionTimer.onConditionChanged(mCondition, eventTimeNs);
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700500}
501
Tej Singh3be093b2020-03-04 20:08:38 -0800502void ValueMetricProducer::prepareFirstBucketLocked() {
503 // Kicks off the puller immediately if condition is true and diff based.
504 if (mIsActive && mIsPulled && mCondition == ConditionState::kTrue && mUseDiff) {
505 pullAndMatchEventsLocked(mCurrentBucketStartTimeNs);
506 }
507}
508
tsaichristine78b85702019-12-06 12:20:30 -0800509void ValueMetricProducer::pullAndMatchEventsLocked(const int64_t timestampNs) {
Chenjie Yue1361ed2018-07-23 17:33:09 -0700510 vector<std::shared_ptr<LogEvent>> allData;
Tej Singh7b975a82020-05-11 11:05:08 -0700511 if (!mPullerManager->Pull(mPullTagId, mConfigKey, timestampNs, &allData)) {
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000512 ALOGE("Stats puller failed for tag: %d at %lld", mPullTagId, (long long)timestampNs);
tsaichristineb87ca152019-12-09 15:19:41 -0800513 invalidateCurrentBucket(timestampNs, BucketDropReason::PULL_FAILED);
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800514 return;
Chenjie Yub3dda412017-10-24 13:41:59 -0700515 }
Olivier Gaillard11203df2019-02-06 13:18:09 +0000516
tsaichristine78b85702019-12-06 12:20:30 -0800517 accumulateEvents(allData, timestampNs, timestampNs);
Olivier Gaillard11203df2019-02-06 13:18:09 +0000518}
519
520int64_t ValueMetricProducer::calcPreviousBucketEndTime(const int64_t currentTimeNs) {
521 return mTimeBaseNs + ((currentTimeNs - mTimeBaseNs) / mBucketSizeNs) * mBucketSizeNs;
522}
523
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000524// By design, statsd pulls data at bucket boundaries using AlarmManager. These pulls are likely
525// to be delayed. Other events like condition changes or app upgrade which are not based on
526// AlarmManager might have arrived earlier and close the bucket.
Olivier Gaillard11203df2019-02-06 13:18:09 +0000527void ValueMetricProducer::onDataPulled(const std::vector<std::shared_ptr<LogEvent>>& allData,
528 bool pullSuccess, int64_t originalPullTimeNs) {
529 std::lock_guard<std::mutex> lock(mMutex);
tsaichristine90f95bb2019-11-06 17:06:53 -0800530 if (mCondition == ConditionState::kTrue) {
531 // If the pull failed, we won't be able to compute a diff.
532 if (!pullSuccess) {
tsaichristineb87ca152019-12-09 15:19:41 -0800533 invalidateCurrentBucket(originalPullTimeNs, BucketDropReason::PULL_FAILED);
tsaichristine90f95bb2019-11-06 17:06:53 -0800534 } else {
535 bool isEventLate = originalPullTimeNs < getCurrentBucketEndTimeNs();
536 if (isEventLate) {
537 // If the event is late, we are in the middle of a bucket. Just
538 // process the data without trying to snap the data to the nearest bucket.
tsaichristine78b85702019-12-06 12:20:30 -0800539 accumulateEvents(allData, originalPullTimeNs, originalPullTimeNs);
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000540 } else {
tsaichristine90f95bb2019-11-06 17:06:53 -0800541 // For scheduled pulled data, the effective event time is snap to the nearest
542 // bucket end. In the case of waking up from a deep sleep state, we will
543 // attribute to the previous bucket end. If the sleep was long but not very
544 // long, we will be in the immediate next bucket. Previous bucket may get a
545 // larger number as we pull at a later time than real bucket end.
546 //
547 // If the sleep was very long, we skip more than one bucket before sleep. In
548 // this case, if the diff base will be cleared and this new data will serve as
549 // new diff base.
550 int64_t bucketEndTime = calcPreviousBucketEndTime(originalPullTimeNs) - 1;
551 StatsdStats::getInstance().noteBucketBoundaryDelayNs(
552 mMetricId, originalPullTimeNs - bucketEndTime);
tsaichristine78b85702019-12-06 12:20:30 -0800553 accumulateEvents(allData, originalPullTimeNs, bucketEndTime);
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000554 }
Olivier Gaillard11203df2019-02-06 13:18:09 +0000555 }
tsaichristine90f95bb2019-11-06 17:06:53 -0800556 }
Olivier Gaillard11203df2019-02-06 13:18:09 +0000557
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000558 // We can probably flush the bucket. Since we used bucketEndTime when calling
559 // #onMatchedLogEventInternalLocked, the current bucket will not have been flushed.
560 flushIfNeededLocked(originalPullTimeNs);
Olivier Gaillard11203df2019-02-06 13:18:09 +0000561}
562
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000563void ValueMetricProducer::accumulateEvents(const std::vector<std::shared_ptr<LogEvent>>& allData,
tsaichristine78b85702019-12-06 12:20:30 -0800564 int64_t originalPullTimeNs, int64_t eventElapsedTimeNs) {
Olivier Gaillard11203df2019-02-06 13:18:09 +0000565 bool isEventLate = eventElapsedTimeNs < mCurrentBucketStartTimeNs;
566 if (isEventLate) {
567 VLOG("Skip bucket end pull due to late arrival: %lld vs %lld",
568 (long long)eventElapsedTimeNs, (long long)mCurrentBucketStartTimeNs);
569 StatsdStats::getInstance().noteLateLogEventSkipped(mMetricId);
tsaichristineb87ca152019-12-09 15:19:41 -0800570 invalidateCurrentBucket(eventElapsedTimeNs, BucketDropReason::EVENT_IN_WRONG_BUCKET);
Olivier Gaillard11203df2019-02-06 13:18:09 +0000571 return;
572 }
573
tsaichristineb87ca152019-12-09 15:19:41 -0800574 const int64_t elapsedRealtimeNs = getElapsedRealtimeNs();
575 const int64_t pullDelayNs = elapsedRealtimeNs - originalPullTimeNs;
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000576 StatsdStats::getInstance().notePullDelay(mPullTagId, pullDelayNs);
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800577 if (pullDelayNs > mMaxPullDelayNs) {
578 ALOGE("Pull finish too late for atom %d, longer than %lld", mPullTagId,
579 (long long)mMaxPullDelayNs);
580 StatsdStats::getInstance().notePullExceedMaxDelay(mPullTagId);
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000581 // We are missing one pull from the bucket which means we will not have a complete view of
582 // what's going on.
tsaichristineb87ca152019-12-09 15:19:41 -0800583 invalidateCurrentBucket(eventElapsedTimeNs, BucketDropReason::PULL_DELAYED);
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800584 return;
585 }
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800586
Olivier Gaillard11203df2019-02-06 13:18:09 +0000587 mMatchedMetricDimensionKeys.clear();
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800588 for (const auto& data : allData) {
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800589 LogEvent localCopy = data->makeCopy();
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800590 if (mEventMatcherWizard->matchLogEvent(localCopy, mWhatMatcherIndex) ==
591 MatchingState::kMatched) {
Olivier Gaillard11203df2019-02-06 13:18:09 +0000592 localCopy.setElapsedTimestampNs(eventElapsedTimeNs);
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800593 onMatchedLogEventLocked(mWhatMatcherIndex, localCopy);
594 }
595 }
tsaichristinec876b492019-12-10 13:47:05 -0800596 // If a key that is:
597 // 1. Tracked in mCurrentSlicedBucket and
598 // 2. A superset of the current mStateChangePrimaryKey
599 // was not found in the new pulled data (i.e. not in mMatchedDimensionInWhatKeys)
600 // then we need to reset the base.
Olivier Gaillard11203df2019-02-06 13:18:09 +0000601 for (auto& slice : mCurrentSlicedBucket) {
tsaichristinec876b492019-12-10 13:47:05 -0800602 const auto& whatKey = slice.first.getDimensionKeyInWhat();
603 bool presentInPulledData =
604 mMatchedMetricDimensionKeys.find(whatKey) != mMatchedMetricDimensionKeys.end();
605 if (!presentInPulledData && whatKey.contains(mStateChangePrimaryKey.second)) {
606 auto it = mCurrentBaseInfo.find(whatKey);
607 for (auto& baseInfo : it->second) {
608 baseInfo.hasBase = false;
609 baseInfo.hasCurrentState = false;
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800610 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800611 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700612 }
Olivier Gaillard11203df2019-02-06 13:18:09 +0000613 mMatchedMetricDimensionKeys.clear();
614 mHasGlobalBase = true;
Olivier Gaillard1e0d8fc2019-02-11 18:08:43 +0000615
616 // If we reach the guardrail, we might have dropped some data which means the bucket is
617 // incomplete.
618 //
619 // The base also needs to be reset. If we do not have the full data, we might
620 // incorrectly compute the diff when mUseZeroDefaultBase is true since an existing key
621 // might be missing from mCurrentSlicedBucket.
622 if (hasReachedGuardRailLimit()) {
tsaichristineb87ca152019-12-09 15:19:41 -0800623 invalidateCurrentBucket(eventElapsedTimeNs, BucketDropReason::DIMENSION_GUARDRAIL_REACHED);
Olivier Gaillard1e0d8fc2019-02-11 18:08:43 +0000624 mCurrentSlicedBucket.clear();
625 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700626}
627
Yangster-maca78d0082018-03-12 12:02:56 -0700628void ValueMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
629 if (mCurrentSlicedBucket.size() == 0) {
630 return;
631 }
632
633 fprintf(out, "ValueMetric %lld dimension size %lu\n", (long long)mMetricId,
634 (unsigned long)mCurrentSlicedBucket.size());
635 if (verbose) {
636 for (const auto& it : mCurrentSlicedBucket) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700637 for (const auto& interval : it.second) {
tsaichristine69000e62019-10-18 17:34:52 -0700638 fprintf(out, "\t(what)%s\t(states)%s (value)%s\n",
639 it.first.getDimensionKeyInWhat().toString().c_str(),
640 it.first.getStateValuesKey().toString().c_str(),
641 interval.value.toString().c_str());
Chenjie Yu32717c32018-10-20 23:54:48 -0700642 }
Yangster-maca78d0082018-03-12 12:02:56 -0700643 }
644 }
645}
646
Olivier Gaillard1e0d8fc2019-02-11 18:08:43 +0000647bool ValueMetricProducer::hasReachedGuardRailLimit() const {
648 return mCurrentSlicedBucket.size() >= mDimensionHardLimit;
649}
650
Yangster-mac93694462018-01-22 20:49:31 -0800651bool ValueMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800652 // ===========GuardRail==============
653 // 1. Report the tuple count if the tuple count > soft limit
654 if (mCurrentSlicedBucket.find(newKey) != mCurrentSlicedBucket.end()) {
655 return false;
656 }
Chenjie Yuc5875052018-03-09 10:13:11 -0800657 if (mCurrentSlicedBucket.size() > mDimensionSoftLimit - 1) {
Yao Chenb3561512017-11-21 18:07:17 -0800658 size_t newTupleCount = mCurrentSlicedBucket.size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800659 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800660 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
Olivier Gaillard1e0d8fc2019-02-11 18:08:43 +0000661 if (hasReachedGuardRailLimit()) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700662 ALOGE("ValueMetric %lld dropping data for dimension key %s", (long long)mMetricId,
663 newKey.toString().c_str());
Misha Wagner1eee2212019-01-22 11:47:11 +0000664 StatsdStats::getInstance().noteHardDimensionLimitReached(mMetricId);
Yao Chenb3561512017-11-21 18:07:17 -0800665 return true;
666 }
667 }
668
669 return false;
670}
671
Chenjie Yudbe5c502018-11-30 23:15:57 -0800672bool ValueMetricProducer::hitFullBucketGuardRailLocked(const MetricDimensionKey& newKey) {
673 // ===========GuardRail==============
674 // 1. Report the tuple count if the tuple count > soft limit
675 if (mCurrentFullBucket.find(newKey) != mCurrentFullBucket.end()) {
676 return false;
677 }
678 if (mCurrentFullBucket.size() > mDimensionSoftLimit - 1) {
679 size_t newTupleCount = mCurrentFullBucket.size() + 1;
680 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
681 if (newTupleCount > mDimensionHardLimit) {
682 ALOGE("ValueMetric %lld dropping data for full bucket dimension key %s",
683 (long long)mMetricId,
684 newKey.toString().c_str());
685 return true;
686 }
687 }
688
689 return false;
690}
691
Chenjie Yu32717c32018-10-20 23:54:48 -0700692bool getDoubleOrLong(const LogEvent& event, const Matcher& matcher, Value& ret) {
693 for (const FieldValue& value : event.getValues()) {
694 if (value.mField.matches(matcher)) {
695 switch (value.mValue.type) {
696 case INT:
697 ret.setLong(value.mValue.int_value);
698 break;
699 case LONG:
700 ret.setLong(value.mValue.long_value);
701 break;
702 case FLOAT:
703 ret.setDouble(value.mValue.float_value);
704 break;
705 case DOUBLE:
706 ret.setDouble(value.mValue.double_value);
707 break;
708 default:
tsaichristine409468d2019-10-28 11:32:31 -0700709 return false;
Chenjie Yu32717c32018-10-20 23:54:48 -0700710 break;
711 }
712 return true;
713 }
Chenjie Yua0f02242018-07-06 16:14:34 -0700714 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700715 return false;
Chenjie Yua0f02242018-07-06 16:14:34 -0700716}
717
tsaichristinec876b492019-12-10 13:47:05 -0800718void ValueMetricProducer::onMatchedLogEventInternalLocked(
719 const size_t matcherIndex, const MetricDimensionKey& eventKey,
720 const ConditionKey& conditionKey, bool condition, const LogEvent& event,
721 const map<int, HashableDimensionKey>& statePrimaryKeys) {
722 auto whatKey = eventKey.getDimensionKeyInWhat();
723 auto stateKey = eventKey.getStateValuesKey();
724
725 // Skip this event if a state changed occurred for a different primary key.
726 auto it = statePrimaryKeys.find(mStateChangePrimaryKey.first);
727 // Check that both the atom id and the primary key are equal.
728 if (it != statePrimaryKeys.end() && it->second != mStateChangePrimaryKey.second) {
729 VLOG("ValueMetric skip event with primary key %s because state change primary key "
730 "is %s",
731 it->second.toString().c_str(), mStateChangePrimaryKey.second.toString().c_str());
732 return;
733 }
734
Yangster-macb142cc82018-03-30 15:22:08 -0700735 int64_t eventTimeNs = event.GetElapsedTimestampNs();
Yao Chen6a8c7992017-11-29 20:02:07 +0000736 if (eventTimeNs < mCurrentBucketStartTimeNs) {
737 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
738 (long long)mCurrentBucketStartTimeNs);
739 return;
740 }
tsaichristinec876b492019-12-10 13:47:05 -0800741 mMatchedMetricDimensionKeys.insert(whatKey);
Yao Chen6a8c7992017-11-29 20:02:07 +0000742
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000743 if (!mIsPulled) {
744 // We cannot flush without doing a pull first.
745 flushIfNeededLocked(eventTimeNs);
746 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800747
Olivier Gaillardfbee9162019-04-11 11:48:01 +0100748 // We should not accumulate the data for pushed metrics when the condition is false.
749 bool shouldSkipForPushMetric = !mIsPulled && !condition;
750 // For pulled metrics, there are two cases:
751 // - to compute diffs, we need to process all the state changes
752 // - for non-diffs metrics, we should ignore the data if the condition wasn't true. If we have a
753 // state change from
754 // + True -> True: we should process the data, it might be a bucket boundary
755 // + True -> False: we als need to process the data.
756 bool shouldSkipForPulledMetric = mIsPulled && !mUseDiff
757 && mCondition != ConditionState::kTrue;
758 if (shouldSkipForPushMetric || shouldSkipForPulledMetric) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700759 VLOG("ValueMetric skip event because condition is false");
760 return;
761 }
762
Yangsterf2bee6f2017-11-29 12:01:05 -0800763 if (hitGuardRailLocked(eventKey)) {
Yangster8de69392017-11-27 13:48:29 -0800764 return;
765 }
tsaichristinec876b492019-12-10 13:47:05 -0800766 vector<BaseInfo>& baseInfos = mCurrentBaseInfo[whatKey];
767 if (baseInfos.size() < mFieldMatchers.size()) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700768 VLOG("Resizing number of intervals to %d", (int)mFieldMatchers.size());
tsaichristinec876b492019-12-10 13:47:05 -0800769 baseInfos.resize(mFieldMatchers.size());
770 }
771
772 for (auto baseInfo : baseInfos) {
773 if (!baseInfo.hasCurrentState) {
774 baseInfo.currentState = DEFAULT_DIMENSION_KEY;
775 baseInfo.hasCurrentState = true;
776 }
777 }
778
779 // We need to get the intervals stored with the previous state key so we can
780 // close these value intervals.
781 const auto oldStateKey = baseInfos[0].currentState;
782 vector<Interval>& intervals = mCurrentSlicedBucket[MetricDimensionKey(whatKey, oldStateKey)];
783 if (intervals.size() < mFieldMatchers.size()) {
784 VLOG("Resizing number of intervals to %d", (int)mFieldMatchers.size());
785 intervals.resize(mFieldMatchers.size());
Yangster-maca7fb12d2018-01-03 17:17:20 -0800786 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000787
Misha Wagner26531762019-01-21 14:18:51 +0000788 // We only use anomaly detection under certain cases.
789 // N.B.: The anomaly detection cases were modified in order to fix an issue with value metrics
790 // containing multiple values. We tried to retain all previous behaviour, but we are unsure the
791 // previous behaviour was correct. At the time of the fix, anomaly detection had no owner.
792 // Whoever next works on it should look into the cases where it is triggered in this function.
793 // Discussion here: http://ag/6124370.
794 bool useAnomalyDetection = true;
795
Chenjie Yu32717c32018-10-20 23:54:48 -0700796 for (int i = 0; i < (int)mFieldMatchers.size(); i++) {
797 const Matcher& matcher = mFieldMatchers[i];
tsaichristinec876b492019-12-10 13:47:05 -0800798 BaseInfo& baseInfo = baseInfos[i];
799 Interval& interval = intervals[i];
Chenjie Yu32717c32018-10-20 23:54:48 -0700800 interval.valueIndex = i;
801 Value value;
802 if (!getDoubleOrLong(event, matcher, value)) {
803 VLOG("Failed to get value %d from event %s", i, event.ToString().c_str());
Misha Wagner1eee2212019-01-22 11:47:11 +0000804 StatsdStats::getInstance().noteBadValueType(mMetricId);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700805 return;
806 }
Chenjie Yudbe5c502018-11-30 23:15:57 -0800807 interval.seenNewData = true;
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700808
Chenjie Yu32717c32018-10-20 23:54:48 -0700809 if (mUseDiff) {
tsaichristinec876b492019-12-10 13:47:05 -0800810 if (!baseInfo.hasBase) {
Chenjie Yuf275f612018-11-30 23:29:06 -0800811 if (mHasGlobalBase && mUseZeroDefaultBase) {
812 // The bucket has global base. This key does not.
813 // Optionally use zero as base.
tsaichristinec876b492019-12-10 13:47:05 -0800814 baseInfo.base = (value.type == LONG ? ZERO_LONG : ZERO_DOUBLE);
815 baseInfo.hasBase = true;
Chenjie Yuf275f612018-11-30 23:29:06 -0800816 } else {
817 // no base. just update base and return.
tsaichristinec876b492019-12-10 13:47:05 -0800818 baseInfo.base = value;
819 baseInfo.hasBase = true;
Misha Wagner26531762019-01-21 14:18:51 +0000820 // If we're missing a base, do not use anomaly detection on incomplete data
821 useAnomalyDetection = false;
tsaichristinec876b492019-12-10 13:47:05 -0800822 // Continue (instead of return) here in order to set baseInfo.base and
823 // baseInfo.hasBase for other baseInfos
Misha Wagner26531762019-01-21 14:18:51 +0000824 continue;
Chenjie Yuf275f612018-11-30 23:29:06 -0800825 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700826 }
tsaichristinec876b492019-12-10 13:47:05 -0800827
Chenjie Yu32717c32018-10-20 23:54:48 -0700828 Value diff;
829 switch (mValueDirection) {
830 case ValueMetric::INCREASING:
tsaichristinec876b492019-12-10 13:47:05 -0800831 if (value >= baseInfo.base) {
832 diff = value - baseInfo.base;
Chenjie Yu32717c32018-10-20 23:54:48 -0700833 } else if (mUseAbsoluteValueOnReset) {
834 diff = value;
835 } else {
836 VLOG("Unexpected decreasing value");
837 StatsdStats::getInstance().notePullDataError(mPullTagId);
tsaichristinec876b492019-12-10 13:47:05 -0800838 baseInfo.base = value;
Misha Wagner26531762019-01-21 14:18:51 +0000839 // If we've got bad data, do not use anomaly detection
840 useAnomalyDetection = false;
841 continue;
Chenjie Yu32717c32018-10-20 23:54:48 -0700842 }
843 break;
844 case ValueMetric::DECREASING:
tsaichristinec876b492019-12-10 13:47:05 -0800845 if (baseInfo.base >= value) {
846 diff = baseInfo.base - value;
Chenjie Yu32717c32018-10-20 23:54:48 -0700847 } else if (mUseAbsoluteValueOnReset) {
848 diff = value;
849 } else {
850 VLOG("Unexpected increasing value");
851 StatsdStats::getInstance().notePullDataError(mPullTagId);
tsaichristinec876b492019-12-10 13:47:05 -0800852 baseInfo.base = value;
Misha Wagner26531762019-01-21 14:18:51 +0000853 // If we've got bad data, do not use anomaly detection
854 useAnomalyDetection = false;
855 continue;
Chenjie Yu32717c32018-10-20 23:54:48 -0700856 }
857 break;
858 case ValueMetric::ANY:
tsaichristinec876b492019-12-10 13:47:05 -0800859 diff = value - baseInfo.base;
Chenjie Yu32717c32018-10-20 23:54:48 -0700860 break;
861 default:
862 break;
863 }
tsaichristinec876b492019-12-10 13:47:05 -0800864 baseInfo.base = value;
Chenjie Yu32717c32018-10-20 23:54:48 -0700865 value = diff;
Yao Chen6a8c7992017-11-29 20:02:07 +0000866 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700867
868 if (interval.hasValue) {
869 switch (mAggregationType) {
870 case ValueMetric::SUM:
871 // for AVG, we add up and take average when flushing the bucket
872 case ValueMetric::AVG:
873 interval.value += value;
874 break;
875 case ValueMetric::MIN:
876 interval.value = std::min(value, interval.value);
877 break;
878 case ValueMetric::MAX:
879 interval.value = std::max(value, interval.value);
880 break;
881 default:
882 break;
883 }
884 } else {
885 interval.value = value;
886 interval.hasValue = true;
887 }
888 interval.sampleSize += 1;
tsaichristinec876b492019-12-10 13:47:05 -0800889 baseInfo.currentState = stateKey;
Yangster8de69392017-11-27 13:48:29 -0800890 }
Bookatzde1b55622017-12-14 18:38:27 -0800891
Misha Wagner26531762019-01-21 14:18:51 +0000892 // Only trigger the tracker if all intervals are correct
893 if (useAnomalyDetection) {
894 // TODO: propgate proper values down stream when anomaly support doubles
tsaichristinec876b492019-12-10 13:47:05 -0800895 long wholeBucketVal = intervals[0].value.long_value;
Misha Wagner26531762019-01-21 14:18:51 +0000896 auto prev = mCurrentFullBucket.find(eventKey);
897 if (prev != mCurrentFullBucket.end()) {
898 wholeBucketVal += prev->second;
899 }
900 for (auto& tracker : mAnomalyTrackers) {
Yao Chen4ce07292019-02-13 13:06:36 -0800901 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, mMetricId, eventKey,
902 wholeBucketVal);
Misha Wagner26531762019-01-21 14:18:51 +0000903 }
Bookatzde1b55622017-12-14 18:38:27 -0800904 }
Yangster8de69392017-11-27 13:48:29 -0800905}
906
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000907// For pulled metrics, we always need to make sure we do a pull before flushing the bucket
908// if mCondition is true!
Yangster-macb142cc82018-03-30 15:22:08 -0700909void ValueMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
910 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700911 if (eventTimeNs < currentBucketEndTimeNs) {
tsaichristine90f95bb2019-11-06 17:06:53 -0800912 VLOG("eventTime is %lld, less than current bucket end time %lld", (long long)eventTimeNs,
David Chen27785a82018-01-19 17:06:45 -0800913 (long long)(currentBucketEndTimeNs));
Chenjie Yub3dda412017-10-24 13:41:59 -0700914 return;
915 }
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000916 int64_t numBucketsForward = calcBucketsForwardCount(eventTimeNs);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000917 int64_t nextBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
918 flushCurrentBucketLocked(eventTimeNs, nextBucketStartTimeNs);
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000919}
David Chen27785a82018-01-19 17:06:45 -0800920
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000921int64_t ValueMetricProducer::calcBucketsForwardCount(const int64_t& eventTimeNs) const {
922 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
923 if (eventTimeNs < currentBucketEndTimeNs) {
924 return 0;
David Chen27785a82018-01-19 17:06:45 -0800925 }
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000926 return 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
David Chen27785a82018-01-19 17:06:45 -0800927}
928
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000929void ValueMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs,
930 const int64_t& nextBucketStartTimeNs) {
Olivier Gaillarde63d9e02019-02-12 14:43:59 +0000931 if (mCondition == ConditionState::kUnknown) {
932 StatsdStats::getInstance().noteBucketUnknownCondition(mMetricId);
933 }
934
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000935 int64_t numBucketsForward = calcBucketsForwardCount(eventTimeNs);
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000936 if (numBucketsForward > 1) {
937 VLOG("Skipping forward %lld buckets", (long long)numBucketsForward);
938 StatsdStats::getInstance().noteSkippedForwardBuckets(mMetricId);
939 // Something went wrong. Maybe the device was sleeping for a long time. It is better
940 // to mark the current bucket as invalid. The last pull might have been successful through.
tsaichristineb87ca152019-12-09 15:19:41 -0800941 invalidateCurrentBucketWithoutResetBase(eventTimeNs,
942 BucketDropReason::MULTIPLE_BUCKETS_SKIPPED);
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000943 }
944
Chenjie Yub3dda412017-10-24 13:41:59 -0700945 VLOG("finalizing bucket for %ld, dumping %d slices", (long)mCurrentBucketStartTimeNs,
946 (int)mCurrentSlicedBucket.size());
Yangster-macb142cc82018-03-30 15:22:08 -0700947 int64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
Chenjie Yu32717c32018-10-20 23:54:48 -0700948 int64_t bucketEndTime = eventTimeNs < fullBucketEndTimeNs ? eventTimeNs : fullBucketEndTimeNs;
Yao Chene6cfb142019-04-08 12:00:01 -0700949 // Close the current bucket.
950 int64_t conditionTrueDuration = mConditionTimer.newBucketStart(bucketEndTime);
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000951 bool isBucketLargeEnough = bucketEndTime - mCurrentBucketStartTimeNs >= mMinBucketSizeNs;
tsaichristineb87ca152019-12-09 15:19:41 -0800952 if (!isBucketLargeEnough) {
tsaichristineb87ca152019-12-09 15:19:41 -0800953 if (!maxDropEventsReached()) {
954 mCurrentSkippedBucket.dropEvents.emplace_back(
955 buildDropEvent(eventTimeNs, BucketDropReason::BUCKET_TOO_SMALL));
956 }
957 }
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000958 if (isBucketLargeEnough && !mCurrentBucketIsInvalid) {
David Chen81245fd2018-04-12 14:33:37 -0700959 // The current bucket is large enough to keep.
David Chen81245fd2018-04-12 14:33:37 -0700960 for (const auto& slice : mCurrentSlicedBucket) {
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000961 ValueBucket bucket = buildPartialBucket(bucketEndTime, slice.second);
Yao Chene6cfb142019-04-08 12:00:01 -0700962 bucket.mConditionTrueNs = conditionTrueDuration;
Chenjie Yu32717c32018-10-20 23:54:48 -0700963 // it will auto create new vector of ValuebucketInfo if the key is not found.
964 if (bucket.valueIndex.size() > 0) {
David Chen81245fd2018-04-12 14:33:37 -0700965 auto& bucketList = mPastBuckets[slice.first];
Chenjie Yu32717c32018-10-20 23:54:48 -0700966 bucketList.push_back(bucket);
David Chen81245fd2018-04-12 14:33:37 -0700967 }
Chenjie Yuae63b0a2018-04-10 14:59:31 -0700968 }
David Chen81245fd2018-04-12 14:33:37 -0700969 } else {
tsaichristine45f703b2020-02-03 10:44:39 -0800970 mCurrentSkippedBucket.bucketStartTimeNs = mCurrentBucketStartTimeNs;
971 mCurrentSkippedBucket.bucketEndTimeNs = bucketEndTime;
tsaichristineb87ca152019-12-09 15:19:41 -0800972 mSkippedBuckets.emplace_back(mCurrentSkippedBucket);
Chenjie Yub3dda412017-10-24 13:41:59 -0700973 }
974
Olivier Gaillardc3719912019-03-15 17:33:40 +0000975 appendToFullBucket(eventTimeNs, fullBucketEndTimeNs);
Olivier Gaillarda8b70112019-02-25 11:24:23 +0000976 initCurrentSlicedBucket(nextBucketStartTimeNs);
Yao Chene6cfb142019-04-08 12:00:01 -0700977 // Update the condition timer again, in case we skipped buckets.
978 mConditionTimer.newBucketStart(nextBucketStartTimeNs);
Olivier Gaillardc3719912019-03-15 17:33:40 +0000979 mCurrentBucketNum += numBucketsForward;
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000980}
981
982ValueBucket ValueMetricProducer::buildPartialBucket(int64_t bucketEndTime,
983 const std::vector<Interval>& intervals) {
984 ValueBucket bucket;
985 bucket.mBucketStartNs = mCurrentBucketStartTimeNs;
986 bucket.mBucketEndNs = bucketEndTime;
987 for (const auto& interval : intervals) {
988 if (interval.hasValue) {
989 // skip the output if the diff is zero
990 if (mSkipZeroDiffOutput && mUseDiff && interval.value.isZero()) {
991 continue;
992 }
993 bucket.valueIndex.push_back(interval.valueIndex);
994 if (mAggregationType != ValueMetric::AVG) {
995 bucket.values.push_back(interval.value);
996 } else {
997 double sum = interval.value.type == LONG ? (double)interval.value.long_value
998 : interval.value.double_value;
999 bucket.values.push_back(Value((double)sum / interval.sampleSize));
1000 }
1001 }
1002 }
1003 return bucket;
1004}
1005
Olivier Gaillarda8b70112019-02-25 11:24:23 +00001006void ValueMetricProducer::initCurrentSlicedBucket(int64_t nextBucketStartTimeNs) {
1007 StatsdStats::getInstance().noteBucketCount(mMetricId);
1008 // Cleanup data structure to aggregate values.
Olivier Gaillard9a5d3592019-02-05 15:12:39 +00001009 for (auto it = mCurrentSlicedBucket.begin(); it != mCurrentSlicedBucket.end();) {
1010 bool obsolete = true;
1011 for (auto& interval : it->second) {
1012 interval.hasValue = false;
1013 interval.sampleSize = 0;
1014 if (interval.seenNewData) {
1015 obsolete = false;
1016 }
1017 interval.seenNewData = false;
1018 }
1019
1020 if (obsolete) {
1021 it = mCurrentSlicedBucket.erase(it);
1022 } else {
1023 it++;
1024 }
tsaichristinec876b492019-12-10 13:47:05 -08001025 // TODO: remove mCurrentBaseInfo entries when obsolete
Olivier Gaillard9a5d3592019-02-05 15:12:39 +00001026 }
Olivier Gaillarda8b70112019-02-25 11:24:23 +00001027
1028 mCurrentBucketIsInvalid = false;
tsaichristineb87ca152019-12-09 15:19:41 -08001029 mCurrentSkippedBucket.reset();
1030
Olivier Gaillarda8b70112019-02-25 11:24:23 +00001031 // If we do not have a global base when the condition is true,
1032 // we will have incomplete bucket for the next bucket.
1033 if (mUseDiff && !mHasGlobalBase && mCondition) {
1034 mCurrentBucketIsInvalid = false;
1035 }
1036 mCurrentBucketStartTimeNs = nextBucketStartTimeNs;
1037 VLOG("metric %lld: new bucket start time: %lld", (long long)mMetricId,
1038 (long long)mCurrentBucketStartTimeNs);
Olivier Gaillard9a5d3592019-02-05 15:12:39 +00001039}
1040
1041void ValueMetricProducer::appendToFullBucket(int64_t eventTimeNs, int64_t fullBucketEndTimeNs) {
Olivier Gaillardc3719912019-03-15 17:33:40 +00001042 bool isFullBucketReached = eventTimeNs > fullBucketEndTimeNs;
1043 if (mCurrentBucketIsInvalid) {
1044 if (isFullBucketReached) {
1045 // If the bucket is invalid, we ignore the full bucket since it contains invalid data.
1046 mCurrentFullBucket.clear();
1047 }
1048 // Current bucket is invalid, we do not add it to the full bucket.
1049 return;
1050 }
1051
1052 if (isFullBucketReached) { // If full bucket, send to anomaly tracker.
David Chen27785a82018-01-19 17:06:45 -08001053 // Accumulate partial buckets with current value and then send to anomaly tracker.
1054 if (mCurrentFullBucket.size() > 0) {
1055 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yudbe5c502018-11-30 23:15:57 -08001056 if (hitFullBucketGuardRailLocked(slice.first)) {
1057 continue;
1058 }
Chenjie Yua0f02242018-07-06 16:14:34 -07001059 // TODO: fix this when anomaly can accept double values
Olivier Gaillardc3719912019-03-15 17:33:40 +00001060 auto& interval = slice.second[0];
1061 if (interval.hasValue) {
1062 mCurrentFullBucket[slice.first] += interval.value.long_value;
1063 }
David Chen27785a82018-01-19 17:06:45 -08001064 }
1065 for (const auto& slice : mCurrentFullBucket) {
1066 for (auto& tracker : mAnomalyTrackers) {
1067 if (tracker != nullptr) {
1068 tracker->addPastBucket(slice.first, slice.second, mCurrentBucketNum);
1069 }
1070 }
1071 }
1072 mCurrentFullBucket.clear();
1073 } else {
1074 // Skip aggregating the partial buckets since there's no previous partial bucket.
1075 for (const auto& slice : mCurrentSlicedBucket) {
1076 for (auto& tracker : mAnomalyTrackers) {
1077 if (tracker != nullptr) {
Chenjie Yua0f02242018-07-06 16:14:34 -07001078 // TODO: fix this when anomaly can accept double values
Olivier Gaillardc3719912019-03-15 17:33:40 +00001079 auto& interval = slice.second[0];
1080 if (interval.hasValue) {
1081 tracker->addPastBucket(slice.first, interval.value.long_value,
1082 mCurrentBucketNum);
1083 }
David Chen27785a82018-01-19 17:06:45 -08001084 }
1085 }
1086 }
1087 }
1088 } else {
1089 // Accumulate partial bucket.
1090 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yua0f02242018-07-06 16:14:34 -07001091 // TODO: fix this when anomaly can accept double values
Olivier Gaillardc3719912019-03-15 17:33:40 +00001092 auto& interval = slice.second[0];
1093 if (interval.hasValue) {
1094 mCurrentFullBucket[slice.first] += interval.value.long_value;
1095 }
David Chen27785a82018-01-19 17:06:45 -08001096 }
1097 }
Chenjie Yub3dda412017-10-24 13:41:59 -07001098}
1099
Yangsterf2bee6f2017-11-29 12:01:05 -08001100size_t ValueMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -08001101 size_t totalSize = 0;
1102 for (const auto& pair : mPastBuckets) {
1103 totalSize += pair.second.size() * kBucketSize;
1104 }
1105 return totalSize;
yro2b0f8862017-11-06 14:27:31 -08001106}
1107
Chenjie Yub3dda412017-10-24 13:41:59 -07001108} // namespace statsd
1109} // namespace os
Yao Chen93fe3a32017-11-02 13:52:59 -07001110} // namespace android