blob: 5987a723a421044a4f5c68b2b20e633fa588e506 [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,
tsaichristine6e2e92d2020-05-18 14:39:45 -070081 const vector<ConditionState>& initialConditionCache,
Chenjie Yuf275f612018-11-30 23:29:06 -080082 const sp<ConditionWizard>& conditionWizard, const int whatMatcherIndex,
83 const sp<EventMatcherWizard>& matcherWizard, const int pullTagId, const int64_t timeBaseNs,
Ruchir Rastogi21a287b2019-10-02 12:04:33 -070084 const int64_t startTimeNs, const sp<StatsPullerManager>& pullerManager,
85 const unordered_map<int, shared_ptr<Activation>>& eventActivationMap,
tsaichristined21aacf2019-10-07 14:47:38 -070086 const unordered_map<int, vector<shared_ptr<Activation>>>& eventDeactivationMap,
87 const vector<int>& slicedStateAtoms,
88 const unordered_map<int, unordered_map<int, int64_t>>& stateGroupMap)
tsaichristine6e2e92d2020-05-18 14:39:45 -070089 : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, initialConditionCache,
90 conditionWizard, eventActivationMap, eventDeactivationMap, slicedStateAtoms,
91 stateGroupMap),
Chenjie Yu054ce9c2018-11-12 15:27:29 -080092 mWhatMatcherIndex(whatMatcherIndex),
93 mEventMatcherWizard(matcherWizard),
Chenjie Yue2219202018-06-08 10:07:51 -070094 mPullerManager(pullerManager),
Chenjie Yuc5875052018-03-09 10:13:11 -080095 mPullTagId(pullTagId),
Chenjie Yua0f02242018-07-06 16:14:34 -070096 mIsPulled(pullTagId != -1),
David Chen81245fd2018-04-12 14:33:37 -070097 mMinBucketSizeNs(metric.min_bucket_size_nanos()),
Chenjie Yuc5875052018-03-09 10:13:11 -080098 mDimensionSoftLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
99 StatsdStats::kAtomDimensionKeySizeLimitMap.end()
100 ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).first
101 : StatsdStats::kDimensionKeySizeSoftLimit),
102 mDimensionHardLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
103 StatsdStats::kAtomDimensionKeySizeLimitMap.end()
104 ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).second
Chenjie Yu47234642018-05-14 10:14:16 -0700105 : StatsdStats::kDimensionKeySizeHardLimit),
Chenjie Yua0f02242018-07-06 16:14:34 -0700106 mUseAbsoluteValueOnReset(metric.use_absolute_value_on_reset()),
107 mAggregationType(metric.aggregation_type()),
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700108 mUseDiff(metric.has_use_diff() ? metric.use_diff() : (mIsPulled ? true : false)),
109 mValueDirection(metric.value_direction()),
Chenjie Yuf275f612018-11-30 23:29:06 -0800110 mSkipZeroDiffOutput(metric.skip_zero_diff_output()),
111 mUseZeroDefaultBase(metric.use_zero_default_base()),
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800112 mHasGlobalBase(false),
Jeffrey Huangde3348a2020-05-20 16:06:13 -0700113 mCurrentBucketIsSkipped(false),
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800114 mMaxPullDelayNs(metric.max_pull_delay_sec() > 0 ? metric.max_pull_delay_sec() * NS_PER_SEC
Chenjie Yucd1b7972019-01-16 20:38:15 -0800115 : StatsdStats::kPullMaxDelayNs),
Yao Chene6cfb142019-04-08 12:00:01 -0700116 mSplitBucketForAppUpgrade(metric.split_bucket_for_app_upgrade()),
Ruchir Rastogi21a287b2019-10-02 12:04:33 -0700117 // Condition timer will be set later within the constructor after pulling events
Tej Singhee4495e2019-06-03 18:37:35 -0700118 mConditionTimer(false, timeBaseNs) {
Yangster-macb8144812018-01-04 10:56:23 -0800119 int64_t bucketSizeMills = 0;
120 if (metric.has_bucket()) {
yro59cc24d2018-02-13 20:17:32 -0800121 bucketSizeMills = TimeUnitToBucketSizeInMillisGuardrailed(key.GetUid(), metric.bucket());
Chenjie Yu6736c892017-11-09 10:50:09 -0800122 } else {
Yangster-macb8144812018-01-04 10:56:23 -0800123 bucketSizeMills = TimeUnitToBucketSizeInMillis(ONE_HOUR);
Chenjie Yu6736c892017-11-09 10:50:09 -0800124 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700125
Yangster-macb8144812018-01-04 10:56:23 -0800126 mBucketSizeNs = bucketSizeMills * 1000000;
Chenjie Yu32717c32018-10-20 23:54:48 -0700127
128 translateFieldMatcher(metric.value_field(), &mFieldMatchers);
129
Yao Chen8a8d16c2018-02-08 14:50:40 -0800130 if (metric.has_dimensions_in_what()) {
131 translateFieldMatcher(metric.dimensions_in_what(), &mDimensionsInWhat);
Yangster13fb7e42018-03-07 17:30:49 -0800132 mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
tsaichristine90f95bb2019-11-06 17:06:53 -0800133 mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what());
Yao Chen8a8d16c2018-02-08 14:50:40 -0800134 }
135
Yao Chen93fe3a32017-11-02 13:52:59 -0700136 if (metric.links().size() > 0) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800137 for (const auto& link : metric.links()) {
138 Metric2Condition mc;
139 mc.conditionId = link.condition();
140 translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
141 translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
142 mMetric2ConditionLinks.push_back(mc);
143 }
tsaichristine76853372019-08-06 17:17:03 -0700144 mConditionSliced = true;
Yao Chen93fe3a32017-11-02 13:52:59 -0700145 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800146
tsaichristinec876b492019-12-10 13:47:05 -0800147 for (const auto& stateLink : metric.state_link()) {
148 Metric2State ms;
149 ms.stateAtomId = stateLink.state_atom_id();
150 translateFieldMatcher(stateLink.fields_in_what(), &ms.metricFields);
151 translateFieldMatcher(stateLink.fields_in_state(), &ms.stateFields);
152 mMetric2StateLinks.push_back(ms);
153 }
154
Tej Singh597c7162019-04-17 16:41:45 -0700155 int64_t numBucketsForward = calcBucketsForwardCount(startTimeNs);
156 mCurrentBucketNum += numBucketsForward;
157
Chenjie Yue1361ed2018-07-23 17:33:09 -0700158 flushIfNeededLocked(startTimeNs);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700159
Chenjie Yua0f02242018-07-06 16:14:34 -0700160 if (mIsPulled) {
Tej Singh3be093b2020-03-04 20:08:38 -0800161 mPullerManager->RegisterReceiver(mPullTagId, mConfigKey, this, getCurrentBucketEndTimeNs(),
Chenjie Yue1361ed2018-07-23 17:33:09 -0700162 mBucketSizeNs);
Yao Chen93fe3a32017-11-02 13:52:59 -0700163 }
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700164
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700165 // Only do this for partial buckets like first bucket. All other buckets should use
Chenjie Yue1361ed2018-07-23 17:33:09 -0700166 // flushIfNeeded to adjust start and end to bucket boundaries.
167 // Adjust start for partial bucket
168 mCurrentBucketStartTimeNs = startTimeNs;
Yao Chene6cfb142019-04-08 12:00:01 -0700169 mConditionTimer.newBucketStart(mCurrentBucketStartTimeNs);
Ruchir Rastogi21a287b2019-10-02 12:04:33 -0700170
Ruchir Rastogi21a287b2019-10-02 12:04:33 -0700171 // Now that activations are processed, start the condition timer if needed.
172 mConditionTimer.onConditionChanged(mIsActive && mCondition == ConditionState::kTrue,
173 mCurrentBucketStartTimeNs);
174
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700175 VLOG("value metric %lld created. bucket size %lld start_time: %lld", (long long)metric.id(),
176 (long long)mBucketSizeNs, (long long)mTimeBaseNs);
Chenjie Yub3dda412017-10-24 13:41:59 -0700177}
178
179ValueMetricProducer::~ValueMetricProducer() {
Yao Chen93fe3a32017-11-02 13:52:59 -0700180 VLOG("~ValueMetricProducer() called");
Chenjie Yua0f02242018-07-06 16:14:34 -0700181 if (mIsPulled) {
Tej Singh3be093b2020-03-04 20:08:38 -0800182 mPullerManager->UnRegisterReceiver(mPullTagId, mConfigKey, this);
Chenjie Yu6736c892017-11-09 10:50:09 -0800183 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700184}
185
tsaichristinec876b492019-12-10 13:47:05 -0800186void ValueMetricProducer::onStateChanged(int64_t eventTimeNs, int32_t atomId,
tsaichristine9f951052020-05-13 14:32:37 -0700187 const HashableDimensionKey& primaryKey,
188 const FieldValue& oldState, const FieldValue& newState) {
tsaichristinec876b492019-12-10 13:47:05 -0800189 VLOG("ValueMetric %lld onStateChanged time %lld, State %d, key %s, %d -> %d",
190 (long long)mMetricId, (long long)eventTimeNs, atomId, primaryKey.toString().c_str(),
tsaichristine9f951052020-05-13 14:32:37 -0700191 oldState.mValue.int_value, newState.mValue.int_value);
tsaichristine9f951052020-05-13 14:32:37 -0700192
193 // If old and new states are in the same StateGroup, then we do not need to
194 // pull for this state change.
195 FieldValue oldStateCopy = oldState;
196 FieldValue newStateCopy = newState;
197 mapStateValue(atomId, &oldStateCopy);
198 mapStateValue(atomId, &newStateCopy);
199 if (oldStateCopy == newStateCopy) {
200 return;
201 }
202
tsaichristine0893db52020-06-03 08:59:56 -0700203 // If condition is not true or metric is not active, we do not need to pull
204 // for this state change.
205 if (mCondition != ConditionState::kTrue || !mIsActive) {
206 return;
207 }
208
tsaichristinec876b492019-12-10 13:47:05 -0800209 bool isEventLate = eventTimeNs < mCurrentBucketStartTimeNs;
210 if (isEventLate) {
211 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
212 (long long)mCurrentBucketStartTimeNs);
213 invalidateCurrentBucket(eventTimeNs, BucketDropReason::EVENT_IN_WRONG_BUCKET);
214 return;
215 }
216 mStateChangePrimaryKey.first = atomId;
217 mStateChangePrimaryKey.second = primaryKey;
218 if (mIsPulled) {
219 pullAndMatchEventsLocked(eventTimeNs);
220 }
221 mStateChangePrimaryKey.first = 0;
222 mStateChangePrimaryKey.second = DEFAULT_DIMENSION_KEY;
223 flushIfNeededLocked(eventTimeNs);
224}
225
Yao Chen427d3722018-03-22 15:21:52 -0700226void ValueMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
Yangster-macb142cc82018-03-30 15:22:08 -0700227 const int64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800228 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Chenjie Yub3dda412017-10-24 13:41:59 -0700229}
230
Yangster-macb142cc82018-03-30 15:22:08 -0700231void ValueMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
Olivier Gaillard320952b2019-02-06 13:57:24 +0000232 StatsdStats::getInstance().noteBucketDropped(mMetricId);
tsaichristineb7fcf002019-12-06 18:40:47 -0800233
234 // The current partial bucket is not flushed and does not require a pull,
235 // so the data is still valid.
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000236 flushIfNeededLocked(dropTimeNs);
237 clearPastBucketsLocked(dropTimeNs);
Yao Chen06dba5d2018-01-26 13:38:16 -0800238}
239
Yangster-maca802d732018-04-24 07:50:38 -0700240void ValueMetricProducer::clearPastBucketsLocked(const int64_t dumpTimeNs) {
Yangster-maca802d732018-04-24 07:50:38 -0700241 mPastBuckets.clear();
242 mSkippedBuckets.clear();
243}
244
Yangster-macb142cc82018-03-30 15:22:08 -0700245void ValueMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700246 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700247 const bool erase_data,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000248 const DumpLatency dumpLatency,
Yangster-mac9def8e32018-04-17 13:55:51 -0700249 std::set<string> *str_set,
Yao Chen288c6002017-12-12 13:43:18 -0800250 ProtoOutputStream* protoOutput) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800251 VLOG("metric %lld dump report now...", (long long)mMetricId);
Yangster-mace68f3a52018-04-04 00:01:43 -0700252 if (include_current_partial_bucket) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000253 // For pull metrics, we need to do a pull at bucket boundaries. If we do not do that the
254 // current bucket will have incomplete data and the next will have the wrong snapshot to do
255 // a diff against. If the condition is false, we are fine since the base data is reset and
256 // we are not tracking anything.
257 bool pullNeeded = mIsPulled && mCondition == ConditionState::kTrue;
258 if (pullNeeded) {
259 switch (dumpLatency) {
260 case FAST:
tsaichristineb87ca152019-12-09 15:19:41 -0800261 invalidateCurrentBucket(dumpTimeNs, BucketDropReason::DUMP_REPORT_REQUESTED);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000262 break;
263 case NO_TIME_CONSTRAINTS:
tsaichristine78b85702019-12-06 12:20:30 -0800264 pullAndMatchEventsLocked(dumpTimeNs);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000265 break;
266 }
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000267 }
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000268 flushCurrentBucketLocked(dumpTimeNs, dumpTimeNs);
Yangster-mace68f3a52018-04-04 00:01:43 -0700269 }
Yang Lub4722912018-11-15 11:02:03 -0800270 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Howard Ro07e23ff2018-12-17 17:28:07 -0800271 protoOutput->write(FIELD_TYPE_BOOL | FIELD_ID_IS_ACTIVE, isActiveLocked());
Yang Lub4722912018-11-15 11:02:03 -0800272
David Chen81245fd2018-04-12 14:33:37 -0700273 if (mPastBuckets.empty() && mSkippedBuckets.empty()) {
Yangster-mac635b4b32018-01-23 20:17:35 -0800274 return;
275 }
Yangster-mac9def8e32018-04-17 13:55:51 -0700276 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_TIME_BASE, (long long)mTimeBaseNs);
277 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_SIZE, (long long)mBucketSizeNs);
278 // Fills the dimension path if not slicing by ALL.
279 if (!mSliceByPositionALL) {
280 if (!mDimensionsInWhat.empty()) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700281 uint64_t dimenPathToken =
282 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_WHAT);
Yangster-mac9def8e32018-04-17 13:55:51 -0700283 writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
284 protoOutput->end(dimenPathToken);
285 }
Yangster-mac9def8e32018-04-17 13:55:51 -0700286 }
287
Yi Jin5ee07872018-03-05 18:18:27 -0800288 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_VALUE_METRICS);
Yao Chen6a8c7992017-11-29 20:02:07 +0000289
tsaichristineb87ca152019-12-09 15:19:41 -0800290 for (const auto& skippedBucket : mSkippedBuckets) {
David Chen81245fd2018-04-12 14:33:37 -0700291 uint64_t wrapperToken =
292 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_SKIPPED);
Yangster-mac9def8e32018-04-17 13:55:51 -0700293 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_START_MILLIS,
tsaichristineb87ca152019-12-09 15:19:41 -0800294 (long long)(NanoToMillis(skippedBucket.bucketStartTimeNs)));
Yangster-mac9def8e32018-04-17 13:55:51 -0700295 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_END_MILLIS,
tsaichristineb87ca152019-12-09 15:19:41 -0800296 (long long)(NanoToMillis(skippedBucket.bucketEndTimeNs)));
297 for (const auto& dropEvent : skippedBucket.dropEvents) {
298 uint64_t dropEventToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
299 FIELD_ID_SKIPPED_DROP_EVENT);
300 protoOutput->write(FIELD_TYPE_INT32 | FIELD_ID_BUCKET_DROP_REASON, dropEvent.reason);
301 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_DROP_TIME,
302 (long long)(NanoToMillis(dropEvent.dropTimeNs)));
303 ;
304 protoOutput->end(dropEventToken);
305 }
David Chen81245fd2018-04-12 14:33:37 -0700306 protoOutput->end(wrapperToken);
307 }
David Chen81245fd2018-04-12 14:33:37 -0700308
Yao Chen93fe3a32017-11-02 13:52:59 -0700309 for (const auto& pair : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800310 const MetricDimensionKey& dimensionKey = pair.first;
Yangster13fb7e42018-03-07 17:30:49 -0800311 VLOG(" dimension key %s", dimensionKey.toString().c_str());
Yi Jin5ee07872018-03-05 18:18:27 -0800312 uint64_t wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800313 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
Chenjie Yub3dda412017-10-24 13:41:59 -0700314
Yangster-mac20877162017-12-22 17:19:39 -0800315 // First fill dimension.
Yangster-mac9def8e32018-04-17 13:55:51 -0700316 if (mSliceByPositionALL) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700317 uint64_t dimensionToken =
318 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
Yangster-mac9def8e32018-04-17 13:55:51 -0700319 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), str_set, protoOutput);
320 protoOutput->end(dimensionToken);
Yangster-mac9def8e32018-04-17 13:55:51 -0700321 } else {
322 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInWhat(),
323 FIELD_ID_DIMENSION_LEAF_IN_WHAT, str_set, protoOutput);
Yangster-mac93694462018-01-22 20:49:31 -0800324 }
yro2b0f8862017-11-06 14:27:31 -0800325
tsaichristinec876b492019-12-10 13:47:05 -0800326 // Then fill slice_by_state.
327 for (auto state : dimensionKey.getStateValuesKey().getValues()) {
328 uint64_t stateToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
329 FIELD_ID_SLICE_BY_STATE);
330 writeStateToProto(state, protoOutput);
331 protoOutput->end(stateToken);
332 }
333
yro2b0f8862017-11-06 14:27:31 -0800334 // Then fill bucket_info (ValueBucketInfo).
335 for (const auto& bucket : pair.second) {
Yi Jin5ee07872018-03-05 18:18:27 -0800336 uint64_t bucketInfoToken = protoOutput->start(
Yao Chen288c6002017-12-12 13:43:18 -0800337 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
Yangster-mac9def8e32018-04-17 13:55:51 -0700338
339 if (bucket.mBucketEndNs - bucket.mBucketStartNs != mBucketSizeNs) {
340 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_MILLIS,
341 (long long)NanoToMillis(bucket.mBucketStartNs));
342 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_MILLIS,
343 (long long)NanoToMillis(bucket.mBucketEndNs));
344 } else {
345 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_NUM,
346 (long long)(getBucketNumFromEndTimeNs(bucket.mBucketEndNs)));
347 }
Yao Chene6cfb142019-04-08 12:00:01 -0700348 // only write the condition timer value if the metric has a condition.
349 if (mConditionTrackerIndex >= 0) {
350 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_CONDITION_TRUE_NS,
351 (long long)bucket.mConditionTrueNs);
352 }
tsaichristinec876b492019-12-10 13:47:05 -0800353 for (int i = 0; i < (int)bucket.valueIndex.size(); i++) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700354 int index = bucket.valueIndex[i];
355 const Value& value = bucket.values[i];
356 uint64_t valueToken = protoOutput->start(
357 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_VALUES);
358 protoOutput->write(FIELD_TYPE_INT32 | FIELD_ID_VALUE_INDEX,
359 index);
360 if (value.getType() == LONG) {
361 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_VALUE_LONG,
362 (long long)value.long_value);
363 VLOG("\t bucket [%lld - %lld] value %d: %lld", (long long)bucket.mBucketStartNs,
364 (long long)bucket.mBucketEndNs, index, (long long)value.long_value);
365 } else if (value.getType() == DOUBLE) {
366 protoOutput->write(FIELD_TYPE_DOUBLE | FIELD_ID_VALUE_DOUBLE,
367 value.double_value);
368 VLOG("\t bucket [%lld - %lld] value %d: %.2f", (long long)bucket.mBucketStartNs,
369 (long long)bucket.mBucketEndNs, index, value.double_value);
370 } else {
371 VLOG("Wrong value type for ValueMetric output: %d", value.getType());
372 }
373 protoOutput->end(valueToken);
Chenjie Yua0f02242018-07-06 16:14:34 -0700374 }
Yao Chen288c6002017-12-12 13:43:18 -0800375 protoOutput->end(bucketInfoToken);
yro2b0f8862017-11-06 14:27:31 -0800376 }
Yao Chen288c6002017-12-12 13:43:18 -0800377 protoOutput->end(wrapperToken);
Chenjie Yub3dda412017-10-24 13:41:59 -0700378 }
Yao Chen288c6002017-12-12 13:43:18 -0800379 protoOutput->end(protoToken);
yro2b0f8862017-11-06 14:27:31 -0800380
Yangster-mac94e197c2018-01-02 16:03:03 -0800381 VLOG("metric %lld dump report now...", (long long)mMetricId);
Bookatzff71cad2018-09-20 17:17:49 -0700382 if (erase_data) {
383 mPastBuckets.clear();
384 mSkippedBuckets.clear();
385 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700386}
387
tsaichristineb87ca152019-12-09 15:19:41 -0800388void ValueMetricProducer::invalidateCurrentBucketWithoutResetBase(const int64_t dropTimeNs,
389 const BucketDropReason reason) {
Jeffrey Huangde3348a2020-05-20 16:06:13 -0700390 if (!mCurrentBucketIsSkipped) {
tsaichristineb87ca152019-12-09 15:19:41 -0800391 // Only report to StatsdStats once per invalid bucket.
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000392 StatsdStats::getInstance().noteInvalidatedBucket(mMetricId);
tsaichristineb87ca152019-12-09 15:19:41 -0800393 }
394
Jeffrey Huangde3348a2020-05-20 16:06:13 -0700395 skipCurrentBucket(dropTimeNs, reason);
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
Jeffrey Huangde3348a2020-05-20 16:06:13 -0700404void ValueMetricProducer::skipCurrentBucket(const int64_t dropTimeNs,
405 const BucketDropReason reason) {
406 if (!maxDropEventsReached()) {
407 mCurrentSkippedBucket.dropEvents.emplace_back(buildDropEvent(dropTimeNs, reason));
408 }
409 mCurrentBucketIsSkipped = true;
410}
411
Chenjie Yuf275f612018-11-30 23:29:06 -0800412void ValueMetricProducer::resetBase() {
tsaichristinec876b492019-12-10 13:47:05 -0800413 for (auto& slice : mCurrentBaseInfo) {
414 for (auto& baseInfo : slice.second) {
415 baseInfo.hasBase = false;
Chenjie Yuf275f612018-11-30 23:29:06 -0800416 }
417 }
418 mHasGlobalBase = false;
419}
420
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700421// Handle active state change. Active state change is treated like a condition change:
422// - drop bucket if active state change event arrives too late
423// - if condition is true, pull data on active state changes
424// - ConditionTimer tracks changes based on AND of condition and active state.
425void ValueMetricProducer::onActiveStateChangedLocked(const int64_t& eventTimeNs) {
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000426 bool isEventTooLate = eventTimeNs < mCurrentBucketStartTimeNs;
tsaichristine90f95bb2019-11-06 17:06:53 -0800427 if (isEventTooLate) {
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700428 // Drop bucket because event arrived too late, ie. we are missing data for this bucket.
tsaichristineb87ca152019-12-09 15:19:41 -0800429 StatsdStats::getInstance().noteLateLogEventSkipped(mMetricId);
430 invalidateCurrentBucket(eventTimeNs, BucketDropReason::EVENT_IN_WRONG_BUCKET);
Yao Chen2794da22017-12-13 16:01:55 -0800431 }
432
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700433 // Call parent method once we've verified the validity of current bucket.
434 MetricProducer::onActiveStateChangedLocked(eventTimeNs);
435
436 if (ConditionState::kTrue != mCondition) {
437 return;
438 }
439
440 // Pull on active state changes.
441 if (!isEventTooLate) {
442 if (mIsPulled) {
tsaichristine78b85702019-12-06 12:20:30 -0800443 pullAndMatchEventsLocked(eventTimeNs);
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700444 }
445 // When active state changes from true to false, clear diff base but don't
446 // reset other counters as we may accumulate more value in the bucket.
447 if (mUseDiff && !mIsActive) {
448 resetBase();
449 }
450 }
451
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700452 flushIfNeededLocked(eventTimeNs);
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700453
454 // Let condition timer know of new active state.
455 mConditionTimer.onConditionChanged(mIsActive, eventTimeNs);
Chenjie Yue1361ed2018-07-23 17:33:09 -0700456}
457
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700458void ValueMetricProducer::onConditionChangedLocked(const bool condition,
459 const int64_t eventTimeNs) {
460 ConditionState newCondition = condition ? ConditionState::kTrue : ConditionState::kFalse;
461 bool isEventTooLate = eventTimeNs < mCurrentBucketStartTimeNs;
462
tsaichristine90f95bb2019-11-06 17:06:53 -0800463 // If the config is not active, skip the event.
464 if (!mIsActive) {
465 mCondition = isEventTooLate ? ConditionState::kUnknown : newCondition;
466 return;
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700467 }
468
tsaichristine90f95bb2019-11-06 17:06:53 -0800469 // If the event arrived late, mark the bucket as invalid and skip the event.
470 if (isEventTooLate) {
471 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
472 (long long)mCurrentBucketStartTimeNs);
tsaichristineb87ca152019-12-09 15:19:41 -0800473 StatsdStats::getInstance().noteLateLogEventSkipped(mMetricId);
tsaichristine90f95bb2019-11-06 17:06:53 -0800474 StatsdStats::getInstance().noteConditionChangeInNextBucket(mMetricId);
tsaichristineb87ca152019-12-09 15:19:41 -0800475 invalidateCurrentBucket(eventTimeNs, BucketDropReason::EVENT_IN_WRONG_BUCKET);
tsaichristine90f95bb2019-11-06 17:06:53 -0800476 mCondition = ConditionState::kUnknown;
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700477 mConditionTimer.onConditionChanged(mCondition, eventTimeNs);
tsaichristine90f95bb2019-11-06 17:06:53 -0800478 return;
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700479 }
tsaichristine90f95bb2019-11-06 17:06:53 -0800480
481 // If the previous condition was unknown, mark the bucket as invalid
482 // because the bucket will contain partial data. For example, the condition
483 // change might happen close to the end of the bucket and we might miss a
484 // lot of data.
485 //
486 // We still want to pull to set the base.
487 if (mCondition == ConditionState::kUnknown) {
tsaichristineb87ca152019-12-09 15:19:41 -0800488 invalidateCurrentBucket(eventTimeNs, BucketDropReason::CONDITION_UNKNOWN);
tsaichristine90f95bb2019-11-06 17:06:53 -0800489 }
490
491 // Pull and match for the following condition change cases:
492 // unknown/false -> true - condition changed
493 // true -> false - condition changed
494 // true -> true - old condition was true so we can flush the bucket at the
495 // end if needed.
496 //
497 // We don’t need to pull for unknown -> false or false -> false.
498 //
499 // onConditionChangedLocked might happen on bucket boundaries if this is
500 // called before #onDataPulled.
501 if (mIsPulled &&
502 (newCondition == ConditionState::kTrue || mCondition == ConditionState::kTrue)) {
tsaichristine78b85702019-12-06 12:20:30 -0800503 pullAndMatchEventsLocked(eventTimeNs);
tsaichristine90f95bb2019-11-06 17:06:53 -0800504 }
505
506 // For metrics that use diff, when condition changes from true to false,
507 // clear diff base but don't reset other counts because we may accumulate
508 // more value in the bucket.
509 if (mUseDiff &&
510 (mCondition == ConditionState::kTrue && newCondition == ConditionState::kFalse)) {
511 resetBase();
512 }
513
514 // Update condition state after pulling.
515 mCondition = newCondition;
516
517 flushIfNeededLocked(eventTimeNs);
518 mConditionTimer.onConditionChanged(mCondition, eventTimeNs);
Muhammad Qureshi18e46922019-05-24 16:38:49 -0700519}
520
Tej Singh3be093b2020-03-04 20:08:38 -0800521void ValueMetricProducer::prepareFirstBucketLocked() {
522 // Kicks off the puller immediately if condition is true and diff based.
523 if (mIsActive && mIsPulled && mCondition == ConditionState::kTrue && mUseDiff) {
524 pullAndMatchEventsLocked(mCurrentBucketStartTimeNs);
525 }
526}
527
tsaichristine78b85702019-12-06 12:20:30 -0800528void ValueMetricProducer::pullAndMatchEventsLocked(const int64_t timestampNs) {
Chenjie Yue1361ed2018-07-23 17:33:09 -0700529 vector<std::shared_ptr<LogEvent>> allData;
Tej Singh7b975a82020-05-11 11:05:08 -0700530 if (!mPullerManager->Pull(mPullTagId, mConfigKey, timestampNs, &allData)) {
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000531 ALOGE("Stats puller failed for tag: %d at %lld", mPullTagId, (long long)timestampNs);
tsaichristineb87ca152019-12-09 15:19:41 -0800532 invalidateCurrentBucket(timestampNs, BucketDropReason::PULL_FAILED);
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800533 return;
Chenjie Yub3dda412017-10-24 13:41:59 -0700534 }
Olivier Gaillard11203df2019-02-06 13:18:09 +0000535
tsaichristine78b85702019-12-06 12:20:30 -0800536 accumulateEvents(allData, timestampNs, timestampNs);
Olivier Gaillard11203df2019-02-06 13:18:09 +0000537}
538
539int64_t ValueMetricProducer::calcPreviousBucketEndTime(const int64_t currentTimeNs) {
540 return mTimeBaseNs + ((currentTimeNs - mTimeBaseNs) / mBucketSizeNs) * mBucketSizeNs;
541}
542
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000543// By design, statsd pulls data at bucket boundaries using AlarmManager. These pulls are likely
544// to be delayed. Other events like condition changes or app upgrade which are not based on
545// AlarmManager might have arrived earlier and close the bucket.
Olivier Gaillard11203df2019-02-06 13:18:09 +0000546void ValueMetricProducer::onDataPulled(const std::vector<std::shared_ptr<LogEvent>>& allData,
547 bool pullSuccess, int64_t originalPullTimeNs) {
548 std::lock_guard<std::mutex> lock(mMutex);
tsaichristine90f95bb2019-11-06 17:06:53 -0800549 if (mCondition == ConditionState::kTrue) {
550 // If the pull failed, we won't be able to compute a diff.
551 if (!pullSuccess) {
tsaichristineb87ca152019-12-09 15:19:41 -0800552 invalidateCurrentBucket(originalPullTimeNs, BucketDropReason::PULL_FAILED);
tsaichristine90f95bb2019-11-06 17:06:53 -0800553 } else {
554 bool isEventLate = originalPullTimeNs < getCurrentBucketEndTimeNs();
555 if (isEventLate) {
556 // If the event is late, we are in the middle of a bucket. Just
557 // process the data without trying to snap the data to the nearest bucket.
tsaichristine78b85702019-12-06 12:20:30 -0800558 accumulateEvents(allData, originalPullTimeNs, originalPullTimeNs);
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000559 } else {
tsaichristine90f95bb2019-11-06 17:06:53 -0800560 // For scheduled pulled data, the effective event time is snap to the nearest
561 // bucket end. In the case of waking up from a deep sleep state, we will
562 // attribute to the previous bucket end. If the sleep was long but not very
563 // long, we will be in the immediate next bucket. Previous bucket may get a
564 // larger number as we pull at a later time than real bucket end.
565 //
566 // If the sleep was very long, we skip more than one bucket before sleep. In
567 // this case, if the diff base will be cleared and this new data will serve as
568 // new diff base.
569 int64_t bucketEndTime = calcPreviousBucketEndTime(originalPullTimeNs) - 1;
570 StatsdStats::getInstance().noteBucketBoundaryDelayNs(
571 mMetricId, originalPullTimeNs - bucketEndTime);
tsaichristine78b85702019-12-06 12:20:30 -0800572 accumulateEvents(allData, originalPullTimeNs, bucketEndTime);
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000573 }
Olivier Gaillard11203df2019-02-06 13:18:09 +0000574 }
tsaichristine90f95bb2019-11-06 17:06:53 -0800575 }
Olivier Gaillard11203df2019-02-06 13:18:09 +0000576
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000577 // We can probably flush the bucket. Since we used bucketEndTime when calling
578 // #onMatchedLogEventInternalLocked, the current bucket will not have been flushed.
579 flushIfNeededLocked(originalPullTimeNs);
Olivier Gaillard11203df2019-02-06 13:18:09 +0000580}
581
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000582void ValueMetricProducer::accumulateEvents(const std::vector<std::shared_ptr<LogEvent>>& allData,
tsaichristine78b85702019-12-06 12:20:30 -0800583 int64_t originalPullTimeNs, int64_t eventElapsedTimeNs) {
Olivier Gaillard11203df2019-02-06 13:18:09 +0000584 bool isEventLate = eventElapsedTimeNs < mCurrentBucketStartTimeNs;
585 if (isEventLate) {
586 VLOG("Skip bucket end pull due to late arrival: %lld vs %lld",
587 (long long)eventElapsedTimeNs, (long long)mCurrentBucketStartTimeNs);
588 StatsdStats::getInstance().noteLateLogEventSkipped(mMetricId);
tsaichristineb87ca152019-12-09 15:19:41 -0800589 invalidateCurrentBucket(eventElapsedTimeNs, BucketDropReason::EVENT_IN_WRONG_BUCKET);
Olivier Gaillard11203df2019-02-06 13:18:09 +0000590 return;
591 }
592
tsaichristineb87ca152019-12-09 15:19:41 -0800593 const int64_t elapsedRealtimeNs = getElapsedRealtimeNs();
594 const int64_t pullDelayNs = elapsedRealtimeNs - originalPullTimeNs;
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000595 StatsdStats::getInstance().notePullDelay(mPullTagId, pullDelayNs);
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800596 if (pullDelayNs > mMaxPullDelayNs) {
597 ALOGE("Pull finish too late for atom %d, longer than %lld", mPullTagId,
598 (long long)mMaxPullDelayNs);
599 StatsdStats::getInstance().notePullExceedMaxDelay(mPullTagId);
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000600 // We are missing one pull from the bucket which means we will not have a complete view of
601 // what's going on.
tsaichristineb87ca152019-12-09 15:19:41 -0800602 invalidateCurrentBucket(eventElapsedTimeNs, BucketDropReason::PULL_DELAYED);
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800603 return;
604 }
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800605
Olivier Gaillard11203df2019-02-06 13:18:09 +0000606 mMatchedMetricDimensionKeys.clear();
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800607 for (const auto& data : allData) {
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800608 LogEvent localCopy = data->makeCopy();
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800609 if (mEventMatcherWizard->matchLogEvent(localCopy, mWhatMatcherIndex) ==
610 MatchingState::kMatched) {
Olivier Gaillard11203df2019-02-06 13:18:09 +0000611 localCopy.setElapsedTimestampNs(eventElapsedTimeNs);
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800612 onMatchedLogEventLocked(mWhatMatcherIndex, localCopy);
613 }
614 }
tsaichristinec876b492019-12-10 13:47:05 -0800615 // If a key that is:
616 // 1. Tracked in mCurrentSlicedBucket and
617 // 2. A superset of the current mStateChangePrimaryKey
618 // was not found in the new pulled data (i.e. not in mMatchedDimensionInWhatKeys)
619 // then we need to reset the base.
Olivier Gaillard11203df2019-02-06 13:18:09 +0000620 for (auto& slice : mCurrentSlicedBucket) {
tsaichristinec876b492019-12-10 13:47:05 -0800621 const auto& whatKey = slice.first.getDimensionKeyInWhat();
622 bool presentInPulledData =
623 mMatchedMetricDimensionKeys.find(whatKey) != mMatchedMetricDimensionKeys.end();
624 if (!presentInPulledData && whatKey.contains(mStateChangePrimaryKey.second)) {
625 auto it = mCurrentBaseInfo.find(whatKey);
626 for (auto& baseInfo : it->second) {
627 baseInfo.hasBase = false;
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800628 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800629 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700630 }
Olivier Gaillard11203df2019-02-06 13:18:09 +0000631 mMatchedMetricDimensionKeys.clear();
632 mHasGlobalBase = true;
Olivier Gaillard1e0d8fc2019-02-11 18:08:43 +0000633
634 // If we reach the guardrail, we might have dropped some data which means the bucket is
635 // incomplete.
636 //
637 // The base also needs to be reset. If we do not have the full data, we might
638 // incorrectly compute the diff when mUseZeroDefaultBase is true since an existing key
639 // might be missing from mCurrentSlicedBucket.
640 if (hasReachedGuardRailLimit()) {
tsaichristineb87ca152019-12-09 15:19:41 -0800641 invalidateCurrentBucket(eventElapsedTimeNs, BucketDropReason::DIMENSION_GUARDRAIL_REACHED);
Olivier Gaillard1e0d8fc2019-02-11 18:08:43 +0000642 mCurrentSlicedBucket.clear();
643 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700644}
645
Yangster-maca78d0082018-03-12 12:02:56 -0700646void ValueMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
647 if (mCurrentSlicedBucket.size() == 0) {
648 return;
649 }
650
651 fprintf(out, "ValueMetric %lld dimension size %lu\n", (long long)mMetricId,
652 (unsigned long)mCurrentSlicedBucket.size());
653 if (verbose) {
654 for (const auto& it : mCurrentSlicedBucket) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700655 for (const auto& interval : it.second) {
tsaichristine69000e62019-10-18 17:34:52 -0700656 fprintf(out, "\t(what)%s\t(states)%s (value)%s\n",
657 it.first.getDimensionKeyInWhat().toString().c_str(),
658 it.first.getStateValuesKey().toString().c_str(),
659 interval.value.toString().c_str());
Chenjie Yu32717c32018-10-20 23:54:48 -0700660 }
Yangster-maca78d0082018-03-12 12:02:56 -0700661 }
662 }
663}
664
Olivier Gaillard1e0d8fc2019-02-11 18:08:43 +0000665bool ValueMetricProducer::hasReachedGuardRailLimit() const {
666 return mCurrentSlicedBucket.size() >= mDimensionHardLimit;
667}
668
Yangster-mac93694462018-01-22 20:49:31 -0800669bool ValueMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800670 // ===========GuardRail==============
671 // 1. Report the tuple count if the tuple count > soft limit
672 if (mCurrentSlicedBucket.find(newKey) != mCurrentSlicedBucket.end()) {
673 return false;
674 }
Chenjie Yuc5875052018-03-09 10:13:11 -0800675 if (mCurrentSlicedBucket.size() > mDimensionSoftLimit - 1) {
Yao Chenb3561512017-11-21 18:07:17 -0800676 size_t newTupleCount = mCurrentSlicedBucket.size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800677 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800678 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
Olivier Gaillard1e0d8fc2019-02-11 18:08:43 +0000679 if (hasReachedGuardRailLimit()) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700680 ALOGE("ValueMetric %lld dropping data for dimension key %s", (long long)mMetricId,
681 newKey.toString().c_str());
Misha Wagner1eee2212019-01-22 11:47:11 +0000682 StatsdStats::getInstance().noteHardDimensionLimitReached(mMetricId);
Yao Chenb3561512017-11-21 18:07:17 -0800683 return true;
684 }
685 }
686
687 return false;
688}
689
Chenjie Yudbe5c502018-11-30 23:15:57 -0800690bool ValueMetricProducer::hitFullBucketGuardRailLocked(const MetricDimensionKey& newKey) {
691 // ===========GuardRail==============
692 // 1. Report the tuple count if the tuple count > soft limit
693 if (mCurrentFullBucket.find(newKey) != mCurrentFullBucket.end()) {
694 return false;
695 }
696 if (mCurrentFullBucket.size() > mDimensionSoftLimit - 1) {
697 size_t newTupleCount = mCurrentFullBucket.size() + 1;
698 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
699 if (newTupleCount > mDimensionHardLimit) {
700 ALOGE("ValueMetric %lld dropping data for full bucket dimension key %s",
701 (long long)mMetricId,
702 newKey.toString().c_str());
703 return true;
704 }
705 }
706
707 return false;
708}
709
Chenjie Yu32717c32018-10-20 23:54:48 -0700710bool getDoubleOrLong(const LogEvent& event, const Matcher& matcher, Value& ret) {
711 for (const FieldValue& value : event.getValues()) {
712 if (value.mField.matches(matcher)) {
713 switch (value.mValue.type) {
714 case INT:
715 ret.setLong(value.mValue.int_value);
716 break;
717 case LONG:
718 ret.setLong(value.mValue.long_value);
719 break;
720 case FLOAT:
721 ret.setDouble(value.mValue.float_value);
722 break;
723 case DOUBLE:
724 ret.setDouble(value.mValue.double_value);
725 break;
726 default:
tsaichristine409468d2019-10-28 11:32:31 -0700727 return false;
Chenjie Yu32717c32018-10-20 23:54:48 -0700728 break;
729 }
730 return true;
731 }
Chenjie Yua0f02242018-07-06 16:14:34 -0700732 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700733 return false;
Chenjie Yua0f02242018-07-06 16:14:34 -0700734}
735
tsaichristinec876b492019-12-10 13:47:05 -0800736void ValueMetricProducer::onMatchedLogEventInternalLocked(
737 const size_t matcherIndex, const MetricDimensionKey& eventKey,
738 const ConditionKey& conditionKey, bool condition, const LogEvent& event,
739 const map<int, HashableDimensionKey>& statePrimaryKeys) {
740 auto whatKey = eventKey.getDimensionKeyInWhat();
741 auto stateKey = eventKey.getStateValuesKey();
742
743 // Skip this event if a state changed occurred for a different primary key.
744 auto it = statePrimaryKeys.find(mStateChangePrimaryKey.first);
745 // Check that both the atom id and the primary key are equal.
746 if (it != statePrimaryKeys.end() && it->second != mStateChangePrimaryKey.second) {
747 VLOG("ValueMetric skip event with primary key %s because state change primary key "
748 "is %s",
749 it->second.toString().c_str(), mStateChangePrimaryKey.second.toString().c_str());
750 return;
751 }
752
Yangster-macb142cc82018-03-30 15:22:08 -0700753 int64_t eventTimeNs = event.GetElapsedTimestampNs();
Yao Chen6a8c7992017-11-29 20:02:07 +0000754 if (eventTimeNs < mCurrentBucketStartTimeNs) {
755 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
756 (long long)mCurrentBucketStartTimeNs);
757 return;
758 }
tsaichristinec876b492019-12-10 13:47:05 -0800759 mMatchedMetricDimensionKeys.insert(whatKey);
Yao Chen6a8c7992017-11-29 20:02:07 +0000760
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000761 if (!mIsPulled) {
762 // We cannot flush without doing a pull first.
763 flushIfNeededLocked(eventTimeNs);
764 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800765
Olivier Gaillardfbee9162019-04-11 11:48:01 +0100766 // We should not accumulate the data for pushed metrics when the condition is false.
767 bool shouldSkipForPushMetric = !mIsPulled && !condition;
768 // For pulled metrics, there are two cases:
769 // - to compute diffs, we need to process all the state changes
770 // - for non-diffs metrics, we should ignore the data if the condition wasn't true. If we have a
771 // state change from
772 // + True -> True: we should process the data, it might be a bucket boundary
773 // + True -> False: we als need to process the data.
774 bool shouldSkipForPulledMetric = mIsPulled && !mUseDiff
775 && mCondition != ConditionState::kTrue;
776 if (shouldSkipForPushMetric || shouldSkipForPulledMetric) {
tsaichristine5088e722020-05-28 10:06:41 -0700777 VLOG("ValueMetric skip event because condition is false and we are not using diff (for "
778 "pulled metric)");
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700779 return;
780 }
781
Yangsterf2bee6f2017-11-29 12:01:05 -0800782 if (hitGuardRailLocked(eventKey)) {
Yangster8de69392017-11-27 13:48:29 -0800783 return;
784 }
tsaichristine5088e722020-05-28 10:06:41 -0700785
tsaichristinec876b492019-12-10 13:47:05 -0800786 vector<BaseInfo>& baseInfos = mCurrentBaseInfo[whatKey];
787 if (baseInfos.size() < mFieldMatchers.size()) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700788 VLOG("Resizing number of intervals to %d", (int)mFieldMatchers.size());
tsaichristinec876b492019-12-10 13:47:05 -0800789 baseInfos.resize(mFieldMatchers.size());
790 }
791
tsaichristine5088e722020-05-28 10:06:41 -0700792 for (BaseInfo& baseInfo : baseInfos) {
tsaichristinec876b492019-12-10 13:47:05 -0800793 if (!baseInfo.hasCurrentState) {
tsaichristine5088e722020-05-28 10:06:41 -0700794 baseInfo.currentState = getUnknownStateKey();
tsaichristinec876b492019-12-10 13:47:05 -0800795 baseInfo.hasCurrentState = true;
796 }
797 }
798
799 // We need to get the intervals stored with the previous state key so we can
800 // close these value intervals.
801 const auto oldStateKey = baseInfos[0].currentState;
802 vector<Interval>& intervals = mCurrentSlicedBucket[MetricDimensionKey(whatKey, oldStateKey)];
803 if (intervals.size() < mFieldMatchers.size()) {
804 VLOG("Resizing number of intervals to %d", (int)mFieldMatchers.size());
805 intervals.resize(mFieldMatchers.size());
Yangster-maca7fb12d2018-01-03 17:17:20 -0800806 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000807
Misha Wagner26531762019-01-21 14:18:51 +0000808 // We only use anomaly detection under certain cases.
809 // N.B.: The anomaly detection cases were modified in order to fix an issue with value metrics
810 // containing multiple values. We tried to retain all previous behaviour, but we are unsure the
811 // previous behaviour was correct. At the time of the fix, anomaly detection had no owner.
812 // Whoever next works on it should look into the cases where it is triggered in this function.
813 // Discussion here: http://ag/6124370.
814 bool useAnomalyDetection = true;
815
Chenjie Yu32717c32018-10-20 23:54:48 -0700816 for (int i = 0; i < (int)mFieldMatchers.size(); i++) {
817 const Matcher& matcher = mFieldMatchers[i];
tsaichristinec876b492019-12-10 13:47:05 -0800818 BaseInfo& baseInfo = baseInfos[i];
819 Interval& interval = intervals[i];
Chenjie Yu32717c32018-10-20 23:54:48 -0700820 interval.valueIndex = i;
821 Value value;
tsaichristine0893db52020-06-03 08:59:56 -0700822 baseInfo.hasCurrentState = true;
823 baseInfo.currentState = stateKey;
Chenjie Yu32717c32018-10-20 23:54:48 -0700824 if (!getDoubleOrLong(event, matcher, value)) {
825 VLOG("Failed to get value %d from event %s", i, event.ToString().c_str());
Misha Wagner1eee2212019-01-22 11:47:11 +0000826 StatsdStats::getInstance().noteBadValueType(mMetricId);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700827 return;
828 }
Chenjie Yudbe5c502018-11-30 23:15:57 -0800829 interval.seenNewData = true;
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700830
Chenjie Yu32717c32018-10-20 23:54:48 -0700831 if (mUseDiff) {
tsaichristinec876b492019-12-10 13:47:05 -0800832 if (!baseInfo.hasBase) {
Chenjie Yuf275f612018-11-30 23:29:06 -0800833 if (mHasGlobalBase && mUseZeroDefaultBase) {
834 // The bucket has global base. This key does not.
835 // Optionally use zero as base.
tsaichristinec876b492019-12-10 13:47:05 -0800836 baseInfo.base = (value.type == LONG ? ZERO_LONG : ZERO_DOUBLE);
837 baseInfo.hasBase = true;
Chenjie Yuf275f612018-11-30 23:29:06 -0800838 } else {
839 // no base. just update base and return.
tsaichristinec876b492019-12-10 13:47:05 -0800840 baseInfo.base = value;
841 baseInfo.hasBase = true;
Misha Wagner26531762019-01-21 14:18:51 +0000842 // If we're missing a base, do not use anomaly detection on incomplete data
843 useAnomalyDetection = false;
tsaichristinec876b492019-12-10 13:47:05 -0800844 // Continue (instead of return) here in order to set baseInfo.base and
845 // baseInfo.hasBase for other baseInfos
Misha Wagner26531762019-01-21 14:18:51 +0000846 continue;
Chenjie Yuf275f612018-11-30 23:29:06 -0800847 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700848 }
tsaichristinec876b492019-12-10 13:47:05 -0800849
Chenjie Yu32717c32018-10-20 23:54:48 -0700850 Value diff;
851 switch (mValueDirection) {
852 case ValueMetric::INCREASING:
tsaichristinec876b492019-12-10 13:47:05 -0800853 if (value >= baseInfo.base) {
854 diff = value - baseInfo.base;
Chenjie Yu32717c32018-10-20 23:54:48 -0700855 } else if (mUseAbsoluteValueOnReset) {
856 diff = value;
857 } else {
858 VLOG("Unexpected decreasing value");
859 StatsdStats::getInstance().notePullDataError(mPullTagId);
tsaichristinec876b492019-12-10 13:47:05 -0800860 baseInfo.base = value;
Misha Wagner26531762019-01-21 14:18:51 +0000861 // If we've got bad data, do not use anomaly detection
862 useAnomalyDetection = false;
863 continue;
Chenjie Yu32717c32018-10-20 23:54:48 -0700864 }
865 break;
866 case ValueMetric::DECREASING:
tsaichristinec876b492019-12-10 13:47:05 -0800867 if (baseInfo.base >= value) {
868 diff = baseInfo.base - value;
Chenjie Yu32717c32018-10-20 23:54:48 -0700869 } else if (mUseAbsoluteValueOnReset) {
870 diff = value;
871 } else {
872 VLOG("Unexpected increasing value");
873 StatsdStats::getInstance().notePullDataError(mPullTagId);
tsaichristinec876b492019-12-10 13:47:05 -0800874 baseInfo.base = value;
Misha Wagner26531762019-01-21 14:18:51 +0000875 // If we've got bad data, do not use anomaly detection
876 useAnomalyDetection = false;
877 continue;
Chenjie Yu32717c32018-10-20 23:54:48 -0700878 }
879 break;
880 case ValueMetric::ANY:
tsaichristinec876b492019-12-10 13:47:05 -0800881 diff = value - baseInfo.base;
Chenjie Yu32717c32018-10-20 23:54:48 -0700882 break;
883 default:
884 break;
885 }
tsaichristinec876b492019-12-10 13:47:05 -0800886 baseInfo.base = value;
Chenjie Yu32717c32018-10-20 23:54:48 -0700887 value = diff;
Yao Chen6a8c7992017-11-29 20:02:07 +0000888 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700889
890 if (interval.hasValue) {
891 switch (mAggregationType) {
892 case ValueMetric::SUM:
893 // for AVG, we add up and take average when flushing the bucket
894 case ValueMetric::AVG:
895 interval.value += value;
896 break;
897 case ValueMetric::MIN:
898 interval.value = std::min(value, interval.value);
899 break;
900 case ValueMetric::MAX:
901 interval.value = std::max(value, interval.value);
902 break;
903 default:
904 break;
905 }
906 } else {
907 interval.value = value;
908 interval.hasValue = true;
909 }
910 interval.sampleSize += 1;
Yangster8de69392017-11-27 13:48:29 -0800911 }
Bookatzde1b55622017-12-14 18:38:27 -0800912
Misha Wagner26531762019-01-21 14:18:51 +0000913 // Only trigger the tracker if all intervals are correct
914 if (useAnomalyDetection) {
915 // TODO: propgate proper values down stream when anomaly support doubles
tsaichristinec876b492019-12-10 13:47:05 -0800916 long wholeBucketVal = intervals[0].value.long_value;
Misha Wagner26531762019-01-21 14:18:51 +0000917 auto prev = mCurrentFullBucket.find(eventKey);
918 if (prev != mCurrentFullBucket.end()) {
919 wholeBucketVal += prev->second;
920 }
921 for (auto& tracker : mAnomalyTrackers) {
Yao Chen4ce07292019-02-13 13:06:36 -0800922 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, mMetricId, eventKey,
923 wholeBucketVal);
Misha Wagner26531762019-01-21 14:18:51 +0000924 }
Bookatzde1b55622017-12-14 18:38:27 -0800925 }
Yangster8de69392017-11-27 13:48:29 -0800926}
927
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000928// For pulled metrics, we always need to make sure we do a pull before flushing the bucket
929// if mCondition is true!
Yangster-macb142cc82018-03-30 15:22:08 -0700930void ValueMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
931 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700932 if (eventTimeNs < currentBucketEndTimeNs) {
tsaichristine90f95bb2019-11-06 17:06:53 -0800933 VLOG("eventTime is %lld, less than current bucket end time %lld", (long long)eventTimeNs,
David Chen27785a82018-01-19 17:06:45 -0800934 (long long)(currentBucketEndTimeNs));
Chenjie Yub3dda412017-10-24 13:41:59 -0700935 return;
936 }
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000937 int64_t numBucketsForward = calcBucketsForwardCount(eventTimeNs);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000938 int64_t nextBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
939 flushCurrentBucketLocked(eventTimeNs, nextBucketStartTimeNs);
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000940}
David Chen27785a82018-01-19 17:06:45 -0800941
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000942int64_t ValueMetricProducer::calcBucketsForwardCount(const int64_t& eventTimeNs) const {
943 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
944 if (eventTimeNs < currentBucketEndTimeNs) {
945 return 0;
David Chen27785a82018-01-19 17:06:45 -0800946 }
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000947 return 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
David Chen27785a82018-01-19 17:06:45 -0800948}
949
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000950void ValueMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs,
951 const int64_t& nextBucketStartTimeNs) {
Olivier Gaillarde63d9e02019-02-12 14:43:59 +0000952 if (mCondition == ConditionState::kUnknown) {
953 StatsdStats::getInstance().noteBucketUnknownCondition(mMetricId);
Tej Singh75654152020-06-12 18:46:27 -0700954 invalidateCurrentBucketWithoutResetBase(eventTimeNs, BucketDropReason::CONDITION_UNKNOWN);
Olivier Gaillarde63d9e02019-02-12 14:43:59 +0000955 }
956
Jeffrey Huang56ff8f32020-05-26 15:56:53 -0700957 VLOG("finalizing bucket for %ld, dumping %d slices", (long)mCurrentBucketStartTimeNs,
958 (int)mCurrentSlicedBucket.size());
959
960 int64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
961 int64_t bucketEndTime = fullBucketEndTimeNs;
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000962 int64_t numBucketsForward = calcBucketsForwardCount(eventTimeNs);
Muhammad Qureshide287062020-06-12 18:33:38 -0700963
964 // Skip buckets if this is a pulled metric or a pushed metric that is diffed.
965 if (numBucketsForward > 1 && (mIsPulled || mUseDiff)) {
966
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000967 VLOG("Skipping forward %lld buckets", (long long)numBucketsForward);
968 StatsdStats::getInstance().noteSkippedForwardBuckets(mMetricId);
969 // Something went wrong. Maybe the device was sleeping for a long time. It is better
970 // to mark the current bucket as invalid. The last pull might have been successful through.
tsaichristineb87ca152019-12-09 15:19:41 -0800971 invalidateCurrentBucketWithoutResetBase(eventTimeNs,
972 BucketDropReason::MULTIPLE_BUCKETS_SKIPPED);
Jeffrey Huang56ff8f32020-05-26 15:56:53 -0700973 // End the bucket at the next bucket start time so the entire interval is skipped.
974 bucketEndTime = nextBucketStartTimeNs;
975 } else if (eventTimeNs < fullBucketEndTimeNs) {
976 bucketEndTime = eventTimeNs;
Olivier Gaillard47a9efc2019-02-22 15:43:31 +0000977 }
978
Yao Chene6cfb142019-04-08 12:00:01 -0700979 // Close the current bucket.
980 int64_t conditionTrueDuration = mConditionTimer.newBucketStart(bucketEndTime);
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000981 bool isBucketLargeEnough = bucketEndTime - mCurrentBucketStartTimeNs >= mMinBucketSizeNs;
tsaichristineb87ca152019-12-09 15:19:41 -0800982 if (!isBucketLargeEnough) {
Jeffrey Huangde3348a2020-05-20 16:06:13 -0700983 skipCurrentBucket(eventTimeNs, BucketDropReason::BUCKET_TOO_SMALL);
tsaichristineb87ca152019-12-09 15:19:41 -0800984 }
Jeffrey Huangde3348a2020-05-20 16:06:13 -0700985 if (!mCurrentBucketIsSkipped) {
Jeffrey Huang56ff8f32020-05-26 15:56:53 -0700986 bool bucketHasData = false;
David Chen81245fd2018-04-12 14:33:37 -0700987 // The current bucket is large enough to keep.
David Chen81245fd2018-04-12 14:33:37 -0700988 for (const auto& slice : mCurrentSlicedBucket) {
Olivier Gaillard9a5d3592019-02-05 15:12:39 +0000989 ValueBucket bucket = buildPartialBucket(bucketEndTime, slice.second);
Yao Chene6cfb142019-04-08 12:00:01 -0700990 bucket.mConditionTrueNs = conditionTrueDuration;
Chenjie Yu32717c32018-10-20 23:54:48 -0700991 // it will auto create new vector of ValuebucketInfo if the key is not found.
992 if (bucket.valueIndex.size() > 0) {
David Chen81245fd2018-04-12 14:33:37 -0700993 auto& bucketList = mPastBuckets[slice.first];
Chenjie Yu32717c32018-10-20 23:54:48 -0700994 bucketList.push_back(bucket);
Jeffrey Huangde3348a2020-05-20 16:06:13 -0700995 bucketHasData = true;
David Chen81245fd2018-04-12 14:33:37 -0700996 }
Chenjie Yuae63b0a2018-04-10 14:59:31 -0700997 }
Jeffrey Huang56ff8f32020-05-26 15:56:53 -0700998 if (!bucketHasData) {
999 skipCurrentBucket(eventTimeNs, BucketDropReason::NO_DATA);
1000 }
Jeffrey Huangde3348a2020-05-20 16:06:13 -07001001 }
1002
1003 if (mCurrentBucketIsSkipped) {
tsaichristine45f703b2020-02-03 10:44:39 -08001004 mCurrentSkippedBucket.bucketStartTimeNs = mCurrentBucketStartTimeNs;
Jeffrey Huang56ff8f32020-05-26 15:56:53 -07001005 mCurrentSkippedBucket.bucketEndTimeNs = bucketEndTime;
tsaichristineb87ca152019-12-09 15:19:41 -08001006 mSkippedBuckets.emplace_back(mCurrentSkippedBucket);
Chenjie Yub3dda412017-10-24 13:41:59 -07001007 }
1008
Jeffrey Huangf1089122020-05-21 12:16:25 -07001009 // This means that the current bucket was not flushed before a forced bucket split.
Jeffrey Huang56ff8f32020-05-26 15:56:53 -07001010 // This can happen if an app update or a dump report with include_current_partial_bucket is
1011 // requested before we get a chance to flush the bucket due to receiving new data, either from
1012 // the statsd socket or the StatsPullerManager.
1013 if (bucketEndTime < nextBucketStartTimeNs) {
Jeffrey Huangf1089122020-05-21 12:16:25 -07001014 SkippedBucket bucketInGap;
1015 bucketInGap.bucketStartTimeNs = bucketEndTime;
1016 bucketInGap.bucketEndTimeNs = nextBucketStartTimeNs;
1017 bucketInGap.dropEvents.emplace_back(
1018 buildDropEvent(eventTimeNs, BucketDropReason::NO_DATA));
1019 mSkippedBuckets.emplace_back(bucketInGap);
1020 }
1021
Jeffrey Huang56ff8f32020-05-26 15:56:53 -07001022 appendToFullBucket(eventTimeNs > fullBucketEndTimeNs);
Olivier Gaillarda8b70112019-02-25 11:24:23 +00001023 initCurrentSlicedBucket(nextBucketStartTimeNs);
Yao Chene6cfb142019-04-08 12:00:01 -07001024 // Update the condition timer again, in case we skipped buckets.
1025 mConditionTimer.newBucketStart(nextBucketStartTimeNs);
Olivier Gaillardc3719912019-03-15 17:33:40 +00001026 mCurrentBucketNum += numBucketsForward;
Olivier Gaillard9a5d3592019-02-05 15:12:39 +00001027}
1028
1029ValueBucket ValueMetricProducer::buildPartialBucket(int64_t bucketEndTime,
1030 const std::vector<Interval>& intervals) {
1031 ValueBucket bucket;
1032 bucket.mBucketStartNs = mCurrentBucketStartTimeNs;
1033 bucket.mBucketEndNs = bucketEndTime;
1034 for (const auto& interval : intervals) {
1035 if (interval.hasValue) {
1036 // skip the output if the diff is zero
1037 if (mSkipZeroDiffOutput && mUseDiff && interval.value.isZero()) {
1038 continue;
1039 }
1040 bucket.valueIndex.push_back(interval.valueIndex);
1041 if (mAggregationType != ValueMetric::AVG) {
1042 bucket.values.push_back(interval.value);
1043 } else {
1044 double sum = interval.value.type == LONG ? (double)interval.value.long_value
1045 : interval.value.double_value;
1046 bucket.values.push_back(Value((double)sum / interval.sampleSize));
1047 }
1048 }
1049 }
1050 return bucket;
1051}
1052
Olivier Gaillarda8b70112019-02-25 11:24:23 +00001053void ValueMetricProducer::initCurrentSlicedBucket(int64_t nextBucketStartTimeNs) {
1054 StatsdStats::getInstance().noteBucketCount(mMetricId);
1055 // Cleanup data structure to aggregate values.
Olivier Gaillard9a5d3592019-02-05 15:12:39 +00001056 for (auto it = mCurrentSlicedBucket.begin(); it != mCurrentSlicedBucket.end();) {
1057 bool obsolete = true;
1058 for (auto& interval : it->second) {
1059 interval.hasValue = false;
1060 interval.sampleSize = 0;
1061 if (interval.seenNewData) {
1062 obsolete = false;
1063 }
1064 interval.seenNewData = false;
1065 }
1066
1067 if (obsolete) {
1068 it = mCurrentSlicedBucket.erase(it);
1069 } else {
1070 it++;
1071 }
tsaichristine5088e722020-05-28 10:06:41 -07001072 // TODO(b/157655103): remove mCurrentBaseInfo entries when obsolete
Olivier Gaillard9a5d3592019-02-05 15:12:39 +00001073 }
Olivier Gaillarda8b70112019-02-25 11:24:23 +00001074
Jeffrey Huangde3348a2020-05-20 16:06:13 -07001075 mCurrentBucketIsSkipped = false;
tsaichristineb87ca152019-12-09 15:19:41 -08001076 mCurrentSkippedBucket.reset();
1077
Olivier Gaillarda8b70112019-02-25 11:24:23 +00001078 // If we do not have a global base when the condition is true,
1079 // we will have incomplete bucket for the next bucket.
1080 if (mUseDiff && !mHasGlobalBase && mCondition) {
Jeffrey Huangde3348a2020-05-20 16:06:13 -07001081 mCurrentBucketIsSkipped = false;
Olivier Gaillarda8b70112019-02-25 11:24:23 +00001082 }
1083 mCurrentBucketStartTimeNs = nextBucketStartTimeNs;
1084 VLOG("metric %lld: new bucket start time: %lld", (long long)mMetricId,
1085 (long long)mCurrentBucketStartTimeNs);
Olivier Gaillard9a5d3592019-02-05 15:12:39 +00001086}
1087
Jeffrey Huang56ff8f32020-05-26 15:56:53 -07001088void ValueMetricProducer::appendToFullBucket(const bool isFullBucketReached) {
Jeffrey Huangde3348a2020-05-20 16:06:13 -07001089 if (mCurrentBucketIsSkipped) {
Olivier Gaillardc3719912019-03-15 17:33:40 +00001090 if (isFullBucketReached) {
1091 // If the bucket is invalid, we ignore the full bucket since it contains invalid data.
1092 mCurrentFullBucket.clear();
1093 }
1094 // Current bucket is invalid, we do not add it to the full bucket.
1095 return;
1096 }
1097
1098 if (isFullBucketReached) { // If full bucket, send to anomaly tracker.
David Chen27785a82018-01-19 17:06:45 -08001099 // Accumulate partial buckets with current value and then send to anomaly tracker.
1100 if (mCurrentFullBucket.size() > 0) {
1101 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yudbe5c502018-11-30 23:15:57 -08001102 if (hitFullBucketGuardRailLocked(slice.first)) {
1103 continue;
1104 }
Chenjie Yua0f02242018-07-06 16:14:34 -07001105 // TODO: fix this when anomaly can accept double values
Olivier Gaillardc3719912019-03-15 17:33:40 +00001106 auto& interval = slice.second[0];
1107 if (interval.hasValue) {
1108 mCurrentFullBucket[slice.first] += interval.value.long_value;
1109 }
David Chen27785a82018-01-19 17:06:45 -08001110 }
1111 for (const auto& slice : mCurrentFullBucket) {
1112 for (auto& tracker : mAnomalyTrackers) {
1113 if (tracker != nullptr) {
1114 tracker->addPastBucket(slice.first, slice.second, mCurrentBucketNum);
1115 }
1116 }
1117 }
1118 mCurrentFullBucket.clear();
1119 } else {
1120 // Skip aggregating the partial buckets since there's no previous partial bucket.
1121 for (const auto& slice : mCurrentSlicedBucket) {
1122 for (auto& tracker : mAnomalyTrackers) {
1123 if (tracker != nullptr) {
Chenjie Yua0f02242018-07-06 16:14:34 -07001124 // TODO: fix this when anomaly can accept double values
Olivier Gaillardc3719912019-03-15 17:33:40 +00001125 auto& interval = slice.second[0];
1126 if (interval.hasValue) {
1127 tracker->addPastBucket(slice.first, interval.value.long_value,
1128 mCurrentBucketNum);
1129 }
David Chen27785a82018-01-19 17:06:45 -08001130 }
1131 }
1132 }
1133 }
1134 } else {
1135 // Accumulate partial bucket.
1136 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yua0f02242018-07-06 16:14:34 -07001137 // TODO: fix this when anomaly can accept double values
Olivier Gaillardc3719912019-03-15 17:33:40 +00001138 auto& interval = slice.second[0];
1139 if (interval.hasValue) {
1140 mCurrentFullBucket[slice.first] += interval.value.long_value;
1141 }
David Chen27785a82018-01-19 17:06:45 -08001142 }
1143 }
Chenjie Yub3dda412017-10-24 13:41:59 -07001144}
1145
Yangsterf2bee6f2017-11-29 12:01:05 -08001146size_t ValueMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -08001147 size_t totalSize = 0;
1148 for (const auto& pair : mPastBuckets) {
1149 totalSize += pair.second.size() * kBucketSize;
1150 }
1151 return totalSize;
yro2b0f8862017-11-06 14:27:31 -08001152}
1153
Chenjie Yub3dda412017-10-24 13:41:59 -07001154} // namespace statsd
1155} // namespace os
Yao Chen93fe3a32017-11-02 13:52:59 -07001156} // namespace android