blob: 6aa8e842b021e14d838f13c49a7fadc5faf98af4 [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
24#include <cutils/log.h>
25#include <limits.h>
26#include <stdlib.h>
27
yrob0378b02017-11-09 20:36:25 -080028using android::util::FIELD_COUNT_REPEATED;
yro2b0f8862017-11-06 14:27:31 -080029using android::util::FIELD_TYPE_BOOL;
Chenjie Yua0f02242018-07-06 16:14:34 -070030using android::util::FIELD_TYPE_DOUBLE;
yro2b0f8862017-11-06 14:27:31 -080031using android::util::FIELD_TYPE_INT32;
32using android::util::FIELD_TYPE_INT64;
33using android::util::FIELD_TYPE_MESSAGE;
Yangster-macd1815dc2017-11-13 21:43:15 -080034using android::util::FIELD_TYPE_STRING;
yro2b0f8862017-11-06 14:27:31 -080035using android::util::ProtoOutputStream;
Chenjie Yub3dda412017-10-24 13:41:59 -070036using std::list;
Chenjie Yu6736c892017-11-09 10:50:09 -080037using std::make_pair;
Chenjie Yub3dda412017-10-24 13:41:59 -070038using std::make_shared;
Yao Chen93fe3a32017-11-02 13:52:59 -070039using std::map;
Chenjie Yub3dda412017-10-24 13:41:59 -070040using std::shared_ptr;
41using std::unique_ptr;
Yao Chen93fe3a32017-11-02 13:52:59 -070042using std::unordered_map;
Chenjie Yub3dda412017-10-24 13:41:59 -070043
44namespace android {
45namespace os {
46namespace statsd {
47
yro2b0f8862017-11-06 14:27:31 -080048// for StatsLogReport
Yangster-mac94e197c2018-01-02 16:03:03 -080049const int FIELD_ID_ID = 1;
yro2b0f8862017-11-06 14:27:31 -080050const int FIELD_ID_VALUE_METRICS = 7;
Yangster-mac9def8e32018-04-17 13:55:51 -070051const int FIELD_ID_TIME_BASE = 9;
52const int FIELD_ID_BUCKET_SIZE = 10;
53const int FIELD_ID_DIMENSION_PATH_IN_WHAT = 11;
54const int FIELD_ID_DIMENSION_PATH_IN_CONDITION = 12;
Howard Ro9440e092018-12-16 19:15:21 -080055const int FIELD_ID_IS_ACTIVE = 14;
yro2b0f8862017-11-06 14:27:31 -080056// for ValueMetricDataWrapper
57const int FIELD_ID_DATA = 1;
David Chen81245fd2018-04-12 14:33:37 -070058const int FIELD_ID_SKIPPED = 2;
Yangster-mac9def8e32018-04-17 13:55:51 -070059const int FIELD_ID_SKIPPED_START_MILLIS = 3;
60const int FIELD_ID_SKIPPED_END_MILLIS = 4;
yro2b0f8862017-11-06 14:27:31 -080061// for ValueMetricData
Yangster-mac468ff042018-01-17 12:26:34 -080062const int FIELD_ID_DIMENSION_IN_WHAT = 1;
63const int FIELD_ID_DIMENSION_IN_CONDITION = 2;
64const int FIELD_ID_BUCKET_INFO = 3;
Yangster-mac9def8e32018-04-17 13:55:51 -070065const int FIELD_ID_DIMENSION_LEAF_IN_WHAT = 4;
66const int FIELD_ID_DIMENSION_LEAF_IN_CONDITION = 5;
yro2b0f8862017-11-06 14:27:31 -080067// for ValueBucketInfo
Chenjie Yu32717c32018-10-20 23:54:48 -070068const int FIELD_ID_VALUE_INDEX = 1;
69const int FIELD_ID_VALUE_LONG = 2;
70const int FIELD_ID_VALUE_DOUBLE = 3;
71const int FIELD_ID_VALUES = 9;
Yangster-mac9def8e32018-04-17 13:55:51 -070072const int FIELD_ID_BUCKET_NUM = 4;
73const int FIELD_ID_START_BUCKET_ELAPSED_MILLIS = 5;
74const int FIELD_ID_END_BUCKET_ELAPSED_MILLIS = 6;
yro2b0f8862017-11-06 14:27:31 -080075
Chenjie Yuf275f612018-11-30 23:29:06 -080076const Value ZERO_LONG((int64_t)0);
77const Value ZERO_DOUBLE((int64_t)0);
78
Chenjie Yub3dda412017-10-24 13:41:59 -070079// ValueMetric has a minimum bucket size of 10min so that we don't pull too frequently
Chenjie Yuf275f612018-11-30 23:29:06 -080080ValueMetricProducer::ValueMetricProducer(
81 const ConfigKey& key, const ValueMetric& metric, const int conditionIndex,
82 const sp<ConditionWizard>& conditionWizard, const int whatMatcherIndex,
83 const sp<EventMatcherWizard>& matcherWizard, const int pullTagId, const int64_t timeBaseNs,
84 const int64_t startTimeNs, const sp<StatsPullerManager>& pullerManager)
Chenjie Yu054ce9c2018-11-12 15:27:29 -080085 : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, conditionWizard),
86 mWhatMatcherIndex(whatMatcherIndex),
87 mEventMatcherWizard(matcherWizard),
Chenjie Yue2219202018-06-08 10:07:51 -070088 mPullerManager(pullerManager),
Chenjie Yuc5875052018-03-09 10:13:11 -080089 mPullTagId(pullTagId),
Chenjie Yua0f02242018-07-06 16:14:34 -070090 mIsPulled(pullTagId != -1),
David Chen81245fd2018-04-12 14:33:37 -070091 mMinBucketSizeNs(metric.min_bucket_size_nanos()),
Chenjie Yuc5875052018-03-09 10:13:11 -080092 mDimensionSoftLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
93 StatsdStats::kAtomDimensionKeySizeLimitMap.end()
94 ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).first
95 : StatsdStats::kDimensionKeySizeSoftLimit),
96 mDimensionHardLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
97 StatsdStats::kAtomDimensionKeySizeLimitMap.end()
98 ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).second
Chenjie Yu47234642018-05-14 10:14:16 -070099 : StatsdStats::kDimensionKeySizeHardLimit),
Chenjie Yua0f02242018-07-06 16:14:34 -0700100 mUseAbsoluteValueOnReset(metric.use_absolute_value_on_reset()),
101 mAggregationType(metric.aggregation_type()),
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700102 mUseDiff(metric.has_use_diff() ? metric.use_diff() : (mIsPulled ? true : false)),
103 mValueDirection(metric.value_direction()),
Chenjie Yuf275f612018-11-30 23:29:06 -0800104 mSkipZeroDiffOutput(metric.skip_zero_diff_output()),
105 mUseZeroDefaultBase(metric.use_zero_default_base()),
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800106 mHasGlobalBase(false),
107 mMaxPullDelayNs(metric.max_pull_delay_sec() > 0 ? metric.max_pull_delay_sec() * NS_PER_SEC
Chenjie Yucd1b7972019-01-16 20:38:15 -0800108 : StatsdStats::kPullMaxDelayNs),
109 mSplitBucketForAppUpgrade(metric.split_bucket_for_app_upgrade()) {
Yangster-macb8144812018-01-04 10:56:23 -0800110 int64_t bucketSizeMills = 0;
111 if (metric.has_bucket()) {
yro59cc24d2018-02-13 20:17:32 -0800112 bucketSizeMills = TimeUnitToBucketSizeInMillisGuardrailed(key.GetUid(), metric.bucket());
Chenjie Yu6736c892017-11-09 10:50:09 -0800113 } else {
Yangster-macb8144812018-01-04 10:56:23 -0800114 bucketSizeMills = TimeUnitToBucketSizeInMillis(ONE_HOUR);
Chenjie Yu6736c892017-11-09 10:50:09 -0800115 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700116
Yangster-macb8144812018-01-04 10:56:23 -0800117 mBucketSizeNs = bucketSizeMills * 1000000;
Chenjie Yu32717c32018-10-20 23:54:48 -0700118
119 translateFieldMatcher(metric.value_field(), &mFieldMatchers);
120
Yao Chen8a8d16c2018-02-08 14:50:40 -0800121 if (metric.has_dimensions_in_what()) {
122 translateFieldMatcher(metric.dimensions_in_what(), &mDimensionsInWhat);
Yangster13fb7e42018-03-07 17:30:49 -0800123 mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
Yao Chen8a8d16c2018-02-08 14:50:40 -0800124 }
125
126 if (metric.has_dimensions_in_condition()) {
127 translateFieldMatcher(metric.dimensions_in_condition(), &mDimensionsInCondition);
128 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700129
Yao Chen93fe3a32017-11-02 13:52:59 -0700130 if (metric.links().size() > 0) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800131 for (const auto& link : metric.links()) {
132 Metric2Condition mc;
133 mc.conditionId = link.condition();
134 translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
135 translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
136 mMetric2ConditionLinks.push_back(mc);
137 }
Yao Chen93fe3a32017-11-02 13:52:59 -0700138 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800139
Yao Chen8a8d16c2018-02-08 14:50:40 -0800140 mConditionSliced = (metric.links().size() > 0) || (mDimensionsInCondition.size() > 0);
Yangster-mac9def8e32018-04-17 13:55:51 -0700141 mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what()) ||
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700142 HasPositionALL(metric.dimensions_in_condition());
Chenjie Yub3dda412017-10-24 13:41:59 -0700143
Chenjie Yue1361ed2018-07-23 17:33:09 -0700144 flushIfNeededLocked(startTimeNs);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700145
Chenjie Yua0f02242018-07-06 16:14:34 -0700146 if (mIsPulled) {
Chenjie Yue1361ed2018-07-23 17:33:09 -0700147 mPullerManager->RegisterReceiver(mPullTagId, this, getCurrentBucketEndTimeNs(),
148 mBucketSizeNs);
Yao Chen93fe3a32017-11-02 13:52:59 -0700149 }
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700150
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700151 // Only do this for partial buckets like first bucket. All other buckets should use
Chenjie Yue1361ed2018-07-23 17:33:09 -0700152 // flushIfNeeded to adjust start and end to bucket boundaries.
153 // Adjust start for partial bucket
154 mCurrentBucketStartTimeNs = startTimeNs;
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700155 // Kicks off the puller immediately if condition is true and diff based.
156 if (mIsPulled && mCondition && mUseDiff) {
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800157 pullAndMatchEventsLocked(startTimeNs);
Chenjie Yue1361ed2018-07-23 17:33:09 -0700158 }
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700159 VLOG("value metric %lld created. bucket size %lld start_time: %lld", (long long)metric.id(),
160 (long long)mBucketSizeNs, (long long)mTimeBaseNs);
Chenjie Yub3dda412017-10-24 13:41:59 -0700161}
162
163ValueMetricProducer::~ValueMetricProducer() {
Yao Chen93fe3a32017-11-02 13:52:59 -0700164 VLOG("~ValueMetricProducer() called");
Chenjie Yua0f02242018-07-06 16:14:34 -0700165 if (mIsPulled) {
Chenjie Yue2219202018-06-08 10:07:51 -0700166 mPullerManager->UnRegisterReceiver(mPullTagId, this);
Chenjie Yu6736c892017-11-09 10:50:09 -0800167 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700168}
169
Yao Chen427d3722018-03-22 15:21:52 -0700170void ValueMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
Yangster-macb142cc82018-03-30 15:22:08 -0700171 const int64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800172 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Chenjie Yub3dda412017-10-24 13:41:59 -0700173}
174
Yangster-macb142cc82018-03-30 15:22:08 -0700175void ValueMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
Yao Chen06dba5d2018-01-26 13:38:16 -0800176 flushIfNeededLocked(dropTimeNs);
177 mPastBuckets.clear();
178}
179
Yangster-maca802d732018-04-24 07:50:38 -0700180void ValueMetricProducer::clearPastBucketsLocked(const int64_t dumpTimeNs) {
181 flushIfNeededLocked(dumpTimeNs);
182 mPastBuckets.clear();
183 mSkippedBuckets.clear();
184}
185
Yangster-macb142cc82018-03-30 15:22:08 -0700186void ValueMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700187 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700188 const bool erase_data,
Yangster-mac9def8e32018-04-17 13:55:51 -0700189 std::set<string> *str_set,
Yao Chen288c6002017-12-12 13:43:18 -0800190 ProtoOutputStream* protoOutput) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800191 VLOG("metric %lld dump report now...", (long long)mMetricId);
Yangster-mace68f3a52018-04-04 00:01:43 -0700192 if (include_current_partial_bucket) {
193 flushLocked(dumpTimeNs);
194 } else {
195 flushIfNeededLocked(dumpTimeNs);
196 }
Yang Lub4722912018-11-15 11:02:03 -0800197 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Howard Ro07e23ff2018-12-17 17:28:07 -0800198 protoOutput->write(FIELD_TYPE_BOOL | FIELD_ID_IS_ACTIVE, isActiveLocked());
Yang Lub4722912018-11-15 11:02:03 -0800199
David Chen81245fd2018-04-12 14:33:37 -0700200 if (mPastBuckets.empty() && mSkippedBuckets.empty()) {
Yangster-mac635b4b32018-01-23 20:17:35 -0800201 return;
202 }
Yangster-mac9def8e32018-04-17 13:55:51 -0700203 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_TIME_BASE, (long long)mTimeBaseNs);
204 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_SIZE, (long long)mBucketSizeNs);
205 // Fills the dimension path if not slicing by ALL.
206 if (!mSliceByPositionALL) {
207 if (!mDimensionsInWhat.empty()) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700208 uint64_t dimenPathToken =
209 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_WHAT);
Yangster-mac9def8e32018-04-17 13:55:51 -0700210 writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
211 protoOutput->end(dimenPathToken);
212 }
213 if (!mDimensionsInCondition.empty()) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700214 uint64_t dimenPathToken =
215 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_CONDITION);
Yangster-mac9def8e32018-04-17 13:55:51 -0700216 writeDimensionPathToProto(mDimensionsInCondition, protoOutput);
217 protoOutput->end(dimenPathToken);
218 }
219 }
220
Yi Jin5ee07872018-03-05 18:18:27 -0800221 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_VALUE_METRICS);
Yao Chen6a8c7992017-11-29 20:02:07 +0000222
David Chen81245fd2018-04-12 14:33:37 -0700223 for (const auto& pair : mSkippedBuckets) {
224 uint64_t wrapperToken =
225 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_SKIPPED);
Yangster-mac9def8e32018-04-17 13:55:51 -0700226 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_START_MILLIS,
227 (long long)(NanoToMillis(pair.first)));
228 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_END_MILLIS,
229 (long long)(NanoToMillis(pair.second)));
David Chen81245fd2018-04-12 14:33:37 -0700230 protoOutput->end(wrapperToken);
231 }
David Chen81245fd2018-04-12 14:33:37 -0700232
Yao Chen93fe3a32017-11-02 13:52:59 -0700233 for (const auto& pair : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800234 const MetricDimensionKey& dimensionKey = pair.first;
Yangster13fb7e42018-03-07 17:30:49 -0800235 VLOG(" dimension key %s", dimensionKey.toString().c_str());
Yi Jin5ee07872018-03-05 18:18:27 -0800236 uint64_t wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800237 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
Chenjie Yub3dda412017-10-24 13:41:59 -0700238
Yangster-mac20877162017-12-22 17:19:39 -0800239 // First fill dimension.
Yangster-mac9def8e32018-04-17 13:55:51 -0700240 if (mSliceByPositionALL) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700241 uint64_t dimensionToken =
242 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
Yangster-mac9def8e32018-04-17 13:55:51 -0700243 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), str_set, protoOutput);
244 protoOutput->end(dimensionToken);
245 if (dimensionKey.hasDimensionKeyInCondition()) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700246 uint64_t dimensionInConditionToken =
247 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
248 writeDimensionToProto(dimensionKey.getDimensionKeyInCondition(), str_set,
249 protoOutput);
Yangster-mac9def8e32018-04-17 13:55:51 -0700250 protoOutput->end(dimensionInConditionToken);
251 }
252 } else {
253 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInWhat(),
254 FIELD_ID_DIMENSION_LEAF_IN_WHAT, str_set, protoOutput);
255 if (dimensionKey.hasDimensionKeyInCondition()) {
256 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInCondition(),
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700257 FIELD_ID_DIMENSION_LEAF_IN_CONDITION, str_set,
258 protoOutput);
Yangster-mac9def8e32018-04-17 13:55:51 -0700259 }
Yangster-mac93694462018-01-22 20:49:31 -0800260 }
yro2b0f8862017-11-06 14:27:31 -0800261
262 // Then fill bucket_info (ValueBucketInfo).
263 for (const auto& bucket : pair.second) {
Yi Jin5ee07872018-03-05 18:18:27 -0800264 uint64_t bucketInfoToken = protoOutput->start(
Yao Chen288c6002017-12-12 13:43:18 -0800265 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
Yangster-mac9def8e32018-04-17 13:55:51 -0700266
267 if (bucket.mBucketEndNs - bucket.mBucketStartNs != mBucketSizeNs) {
268 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_MILLIS,
269 (long long)NanoToMillis(bucket.mBucketStartNs));
270 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_MILLIS,
271 (long long)NanoToMillis(bucket.mBucketEndNs));
272 } else {
273 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_NUM,
274 (long long)(getBucketNumFromEndTimeNs(bucket.mBucketEndNs)));
275 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700276 for (int i = 0; i < (int)bucket.valueIndex.size(); i ++) {
277 int index = bucket.valueIndex[i];
278 const Value& value = bucket.values[i];
279 uint64_t valueToken = protoOutput->start(
280 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_VALUES);
281 protoOutput->write(FIELD_TYPE_INT32 | FIELD_ID_VALUE_INDEX,
282 index);
283 if (value.getType() == LONG) {
284 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_VALUE_LONG,
285 (long long)value.long_value);
286 VLOG("\t bucket [%lld - %lld] value %d: %lld", (long long)bucket.mBucketStartNs,
287 (long long)bucket.mBucketEndNs, index, (long long)value.long_value);
288 } else if (value.getType() == DOUBLE) {
289 protoOutput->write(FIELD_TYPE_DOUBLE | FIELD_ID_VALUE_DOUBLE,
290 value.double_value);
291 VLOG("\t bucket [%lld - %lld] value %d: %.2f", (long long)bucket.mBucketStartNs,
292 (long long)bucket.mBucketEndNs, index, value.double_value);
293 } else {
294 VLOG("Wrong value type for ValueMetric output: %d", value.getType());
295 }
296 protoOutput->end(valueToken);
Chenjie Yua0f02242018-07-06 16:14:34 -0700297 }
Yao Chen288c6002017-12-12 13:43:18 -0800298 protoOutput->end(bucketInfoToken);
yro2b0f8862017-11-06 14:27:31 -0800299 }
Yao Chen288c6002017-12-12 13:43:18 -0800300 protoOutput->end(wrapperToken);
Chenjie Yub3dda412017-10-24 13:41:59 -0700301 }
Yao Chen288c6002017-12-12 13:43:18 -0800302 protoOutput->end(protoToken);
yro2b0f8862017-11-06 14:27:31 -0800303
Yangster-mac94e197c2018-01-02 16:03:03 -0800304 VLOG("metric %lld dump report now...", (long long)mMetricId);
Bookatzff71cad2018-09-20 17:17:49 -0700305 if (erase_data) {
306 mPastBuckets.clear();
307 mSkippedBuckets.clear();
308 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700309}
310
Chenjie Yuf275f612018-11-30 23:29:06 -0800311void ValueMetricProducer::resetBase() {
312 for (auto& slice : mCurrentSlicedBucket) {
313 for (auto& interval : slice.second) {
314 interval.hasBase = false;
315 }
316 }
317 mHasGlobalBase = false;
318}
319
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700320void ValueMetricProducer::onConditionChangedLocked(const bool condition,
Yangster-macb142cc82018-03-30 15:22:08 -0700321 const int64_t eventTimeNs) {
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700322 if (eventTimeNs < mCurrentBucketStartTimeNs) {
323 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800324 (long long)mCurrentBucketStartTimeNs);
Misha Wagner1eee2212019-01-22 11:47:11 +0000325 StatsdStats::getInstance().noteConditionChangeInNextBucket(mMetricId);
Yao Chen2794da22017-12-13 16:01:55 -0800326 return;
327 }
328
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700329 flushIfNeededLocked(eventTimeNs);
Chenjie Yua7259ab2017-12-10 08:31:05 -0800330
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700331 // Pull on condition changes.
332 if (mIsPulled && (mCondition != condition)) {
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800333 pullAndMatchEventsLocked(eventTimeNs);
Chenjie Yue1361ed2018-07-23 17:33:09 -0700334 }
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700335
Chenjie Yuf275f612018-11-30 23:29:06 -0800336 // when condition change from true to false, clear diff base but don't
337 // reset other counters as we may accumulate more value in the bucket.
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700338 if (mUseDiff && mCondition && !condition) {
Chenjie Yuf275f612018-11-30 23:29:06 -0800339 resetBase();
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700340 }
341
342 mCondition = condition;
Chenjie Yue1361ed2018-07-23 17:33:09 -0700343}
344
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800345void ValueMetricProducer::pullAndMatchEventsLocked(const int64_t timestampNs) {
Chenjie Yue1361ed2018-07-23 17:33:09 -0700346 vector<std::shared_ptr<LogEvent>> allData;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800347 if (!mPullerManager->Pull(mPullTagId, &allData)) {
348 ALOGE("Gauge Stats puller failed for tag: %d at %lld", mPullTagId, (long long)timestampNs);
Chenjie Yuf275f612018-11-30 23:29:06 -0800349 resetBase();
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800350 return;
Chenjie Yub3dda412017-10-24 13:41:59 -0700351 }
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800352 const int64_t pullDelayNs = getElapsedRealtimeNs() - timestampNs;
353 if (pullDelayNs > mMaxPullDelayNs) {
354 ALOGE("Pull finish too late for atom %d, longer than %lld", mPullTagId,
355 (long long)mMaxPullDelayNs);
356 StatsdStats::getInstance().notePullExceedMaxDelay(mPullTagId);
357 StatsdStats::getInstance().notePullDelay(mPullTagId, pullDelayNs);
358 resetBase();
359 return;
360 }
361 StatsdStats::getInstance().notePullDelay(mPullTagId, pullDelayNs);
362
Misha Wagner1eee2212019-01-22 11:47:11 +0000363 if (timestampNs < mCurrentBucketStartTimeNs) {
364 // The data will be skipped in onMatchedLogEventInternalLocked, but we don't want to report
365 // for every event, just the pull
366 StatsdStats::getInstance().noteLateLogEventSkipped(mMetricId);
367 }
368
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800369 for (const auto& data : allData) {
370 // make a copy before doing and changes
371 LogEvent localCopy = data->makeCopy();
372 localCopy.setElapsedTimestampNs(timestampNs);
373 if (mEventMatcherWizard->matchLogEvent(localCopy, mWhatMatcherIndex) ==
374 MatchingState::kMatched) {
375 onMatchedLogEventLocked(mWhatMatcherIndex, localCopy);
376 }
377 }
378 mHasGlobalBase = true;
Chenjie Yub3dda412017-10-24 13:41:59 -0700379}
380
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700381int64_t ValueMetricProducer::calcPreviousBucketEndTime(const int64_t currentTimeNs) {
382 return mTimeBaseNs + ((currentTimeNs - mTimeBaseNs) / mBucketSizeNs) * mBucketSizeNs;
383}
384
Chenjie Yub3dda412017-10-24 13:41:59 -0700385void ValueMetricProducer::onDataPulled(const std::vector<std::shared_ptr<LogEvent>>& allData) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800386 std::lock_guard<std::mutex> lock(mMutex);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700387 if (mCondition) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700388 if (allData.size() == 0) {
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800389 VLOG("Data pulled is empty");
Misha Wagner1eee2212019-01-22 11:47:11 +0000390 StatsdStats::getInstance().noteEmptyData(mPullTagId);
Chenjie Yub3dda412017-10-24 13:41:59 -0700391 return;
392 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800393 // For scheduled pulled data, the effective event time is snap to the nearest
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700394 // bucket end. In the case of waking up from a deep sleep state, we will
395 // attribute to the previous bucket end. If the sleep was long but not very long, we
396 // will be in the immediate next bucket. Previous bucket may get a larger number as
397 // we pull at a later time than real bucket end.
398 // If the sleep was very long, we skip more than one bucket before sleep. In this case,
399 // if the diff base will be cleared and this new data will serve as new diff base.
Yangster-macb142cc82018-03-30 15:22:08 -0700400 int64_t realEventTime = allData.at(0)->GetElapsedTimestampNs();
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700401 int64_t bucketEndTime = calcPreviousBucketEndTime(realEventTime) - 1;
402 if (bucketEndTime < mCurrentBucketStartTimeNs) {
403 VLOG("Skip bucket end pull due to late arrival: %lld vs %lld", (long long)bucketEndTime,
404 (long long)mCurrentBucketStartTimeNs);
Misha Wagner1eee2212019-01-22 11:47:11 +0000405 StatsdStats::getInstance().noteLateLogEventSkipped(mMetricId);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700406 return;
Chenjie Yub3dda412017-10-24 13:41:59 -0700407 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800408 for (const auto& data : allData) {
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800409 LogEvent localCopy = data->makeCopy();
410 if (mEventMatcherWizard->matchLogEvent(localCopy, mWhatMatcherIndex) ==
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800411 MatchingState::kMatched) {
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800412 localCopy.setElapsedTimestampNs(bucketEndTime);
413 onMatchedLogEventLocked(mWhatMatcherIndex, localCopy);
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800414 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800415 }
Chenjie Yuf275f612018-11-30 23:29:06 -0800416 mHasGlobalBase = true;
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800417 } else {
418 VLOG("No need to commit data on condition false.");
Chenjie Yub3dda412017-10-24 13:41:59 -0700419 }
420}
421
Yangster-maca78d0082018-03-12 12:02:56 -0700422void ValueMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
423 if (mCurrentSlicedBucket.size() == 0) {
424 return;
425 }
426
427 fprintf(out, "ValueMetric %lld dimension size %lu\n", (long long)mMetricId,
428 (unsigned long)mCurrentSlicedBucket.size());
429 if (verbose) {
430 for (const auto& it : mCurrentSlicedBucket) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700431 for (const auto& interval : it.second) {
Chenjie Yua0f02242018-07-06 16:14:34 -0700432 fprintf(out, "\t(what)%s\t(condition)%s (value)%s\n",
433 it.first.getDimensionKeyInWhat().toString().c_str(),
434 it.first.getDimensionKeyInCondition().toString().c_str(),
Chenjie Yu32717c32018-10-20 23:54:48 -0700435 interval.value.toString().c_str());
436 }
Yangster-maca78d0082018-03-12 12:02:56 -0700437 }
438 }
439}
440
Yangster-mac93694462018-01-22 20:49:31 -0800441bool ValueMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800442 // ===========GuardRail==============
443 // 1. Report the tuple count if the tuple count > soft limit
444 if (mCurrentSlicedBucket.find(newKey) != mCurrentSlicedBucket.end()) {
445 return false;
446 }
Chenjie Yuc5875052018-03-09 10:13:11 -0800447 if (mCurrentSlicedBucket.size() > mDimensionSoftLimit - 1) {
Yao Chenb3561512017-11-21 18:07:17 -0800448 size_t newTupleCount = mCurrentSlicedBucket.size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800449 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800450 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
Chenjie Yuc5875052018-03-09 10:13:11 -0800451 if (newTupleCount > mDimensionHardLimit) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700452 ALOGE("ValueMetric %lld dropping data for dimension key %s", (long long)mMetricId,
453 newKey.toString().c_str());
Misha Wagner1eee2212019-01-22 11:47:11 +0000454 StatsdStats::getInstance().noteHardDimensionLimitReached(mMetricId);
Yao Chenb3561512017-11-21 18:07:17 -0800455 return true;
456 }
457 }
458
459 return false;
460}
461
Chenjie Yudbe5c502018-11-30 23:15:57 -0800462bool ValueMetricProducer::hitFullBucketGuardRailLocked(const MetricDimensionKey& newKey) {
463 // ===========GuardRail==============
464 // 1. Report the tuple count if the tuple count > soft limit
465 if (mCurrentFullBucket.find(newKey) != mCurrentFullBucket.end()) {
466 return false;
467 }
468 if (mCurrentFullBucket.size() > mDimensionSoftLimit - 1) {
469 size_t newTupleCount = mCurrentFullBucket.size() + 1;
470 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
471 if (newTupleCount > mDimensionHardLimit) {
472 ALOGE("ValueMetric %lld dropping data for full bucket dimension key %s",
473 (long long)mMetricId,
474 newKey.toString().c_str());
475 return true;
476 }
477 }
478
479 return false;
480}
481
Chenjie Yu32717c32018-10-20 23:54:48 -0700482bool getDoubleOrLong(const LogEvent& event, const Matcher& matcher, Value& ret) {
483 for (const FieldValue& value : event.getValues()) {
484 if (value.mField.matches(matcher)) {
485 switch (value.mValue.type) {
486 case INT:
487 ret.setLong(value.mValue.int_value);
488 break;
489 case LONG:
490 ret.setLong(value.mValue.long_value);
491 break;
492 case FLOAT:
493 ret.setDouble(value.mValue.float_value);
494 break;
495 case DOUBLE:
496 ret.setDouble(value.mValue.double_value);
497 break;
498 default:
499 break;
500 }
501 return true;
502 }
Chenjie Yua0f02242018-07-06 16:14:34 -0700503 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700504 return false;
Chenjie Yua0f02242018-07-06 16:14:34 -0700505}
506
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700507void ValueMetricProducer::onMatchedLogEventInternalLocked(const size_t matcherIndex,
508 const MetricDimensionKey& eventKey,
509 const ConditionKey& conditionKey,
510 bool condition, const LogEvent& event) {
Yangster-macb142cc82018-03-30 15:22:08 -0700511 int64_t eventTimeNs = event.GetElapsedTimestampNs();
Yao Chen6a8c7992017-11-29 20:02:07 +0000512 if (eventTimeNs < mCurrentBucketStartTimeNs) {
513 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
514 (long long)mCurrentBucketStartTimeNs);
515 return;
516 }
517
Chenjie Yua7259ab2017-12-10 08:31:05 -0800518 flushIfNeededLocked(eventTimeNs);
519
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700520 // For pulled data, we already check condition when we decide to pull or
521 // in onDataPulled. So take all of them.
522 // For pushed data, just check condition.
523 if (!(mIsPulled || condition)) {
524 VLOG("ValueMetric skip event because condition is false");
525 return;
526 }
527
Yangsterf2bee6f2017-11-29 12:01:05 -0800528 if (hitGuardRailLocked(eventKey)) {
Yangster8de69392017-11-27 13:48:29 -0800529 return;
530 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700531 vector<Interval>& multiIntervals = mCurrentSlicedBucket[eventKey];
532 if (multiIntervals.size() < mFieldMatchers.size()) {
533 VLOG("Resizing number of intervals to %d", (int)mFieldMatchers.size());
534 multiIntervals.resize(mFieldMatchers.size());
Yangster-maca7fb12d2018-01-03 17:17:20 -0800535 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000536
Misha Wagner26531762019-01-21 14:18:51 +0000537 // We only use anomaly detection under certain cases.
538 // N.B.: The anomaly detection cases were modified in order to fix an issue with value metrics
539 // containing multiple values. We tried to retain all previous behaviour, but we are unsure the
540 // previous behaviour was correct. At the time of the fix, anomaly detection had no owner.
541 // Whoever next works on it should look into the cases where it is triggered in this function.
542 // Discussion here: http://ag/6124370.
543 bool useAnomalyDetection = true;
544
Chenjie Yu32717c32018-10-20 23:54:48 -0700545 for (int i = 0; i < (int)mFieldMatchers.size(); i++) {
546 const Matcher& matcher = mFieldMatchers[i];
547 Interval& interval = multiIntervals[i];
548 interval.valueIndex = i;
549 Value value;
550 if (!getDoubleOrLong(event, matcher, value)) {
551 VLOG("Failed to get value %d from event %s", i, event.ToString().c_str());
Misha Wagner1eee2212019-01-22 11:47:11 +0000552 StatsdStats::getInstance().noteBadValueType(mMetricId);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700553 return;
554 }
Chenjie Yudbe5c502018-11-30 23:15:57 -0800555 interval.seenNewData = true;
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700556
Chenjie Yu32717c32018-10-20 23:54:48 -0700557 if (mUseDiff) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700558 if (!interval.hasBase) {
Chenjie Yuf275f612018-11-30 23:29:06 -0800559 if (mHasGlobalBase && mUseZeroDefaultBase) {
560 // The bucket has global base. This key does not.
561 // Optionally use zero as base.
562 interval.base = (value.type == LONG ? ZERO_LONG : ZERO_DOUBLE);
563 interval.hasBase = true;
564 } else {
565 // no base. just update base and return.
566 interval.base = value;
567 interval.hasBase = true;
Misha Wagner26531762019-01-21 14:18:51 +0000568 // If we're missing a base, do not use anomaly detection on incomplete data
569 useAnomalyDetection = false;
570 // Continue (instead of return) here in order to set interval.base and
571 // interval.hasBase for other intervals
572 continue;
Chenjie Yuf275f612018-11-30 23:29:06 -0800573 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700574 }
575 Value diff;
576 switch (mValueDirection) {
577 case ValueMetric::INCREASING:
578 if (value >= interval.base) {
579 diff = value - interval.base;
580 } else if (mUseAbsoluteValueOnReset) {
581 diff = value;
582 } else {
583 VLOG("Unexpected decreasing value");
584 StatsdStats::getInstance().notePullDataError(mPullTagId);
585 interval.base = value;
Misha Wagner26531762019-01-21 14:18:51 +0000586 // If we've got bad data, do not use anomaly detection
587 useAnomalyDetection = false;
588 continue;
Chenjie Yu32717c32018-10-20 23:54:48 -0700589 }
590 break;
591 case ValueMetric::DECREASING:
592 if (interval.base >= value) {
593 diff = interval.base - value;
594 } else if (mUseAbsoluteValueOnReset) {
595 diff = value;
596 } else {
597 VLOG("Unexpected increasing value");
598 StatsdStats::getInstance().notePullDataError(mPullTagId);
599 interval.base = value;
Misha Wagner26531762019-01-21 14:18:51 +0000600 // If we've got bad data, do not use anomaly detection
601 useAnomalyDetection = false;
602 continue;
Chenjie Yu32717c32018-10-20 23:54:48 -0700603 }
604 break;
605 case ValueMetric::ANY:
606 diff = value - interval.base;
607 break;
608 default:
609 break;
610 }
611 interval.base = value;
612 value = diff;
Yao Chen6a8c7992017-11-29 20:02:07 +0000613 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700614
615 if (interval.hasValue) {
616 switch (mAggregationType) {
617 case ValueMetric::SUM:
618 // for AVG, we add up and take average when flushing the bucket
619 case ValueMetric::AVG:
620 interval.value += value;
621 break;
622 case ValueMetric::MIN:
623 interval.value = std::min(value, interval.value);
624 break;
625 case ValueMetric::MAX:
626 interval.value = std::max(value, interval.value);
627 break;
628 default:
629 break;
630 }
631 } else {
632 interval.value = value;
633 interval.hasValue = true;
634 }
635 interval.sampleSize += 1;
Yangster8de69392017-11-27 13:48:29 -0800636 }
Bookatzde1b55622017-12-14 18:38:27 -0800637
Misha Wagner26531762019-01-21 14:18:51 +0000638 // Only trigger the tracker if all intervals are correct
639 if (useAnomalyDetection) {
640 // TODO: propgate proper values down stream when anomaly support doubles
641 long wholeBucketVal = multiIntervals[0].value.long_value;
642 auto prev = mCurrentFullBucket.find(eventKey);
643 if (prev != mCurrentFullBucket.end()) {
644 wholeBucketVal += prev->second;
645 }
646 for (auto& tracker : mAnomalyTrackers) {
647 tracker->detectAndDeclareAnomaly(
648 eventTimeNs, mCurrentBucketNum, eventKey, wholeBucketVal);
649 }
Bookatzde1b55622017-12-14 18:38:27 -0800650 }
Yangster8de69392017-11-27 13:48:29 -0800651}
652
Yangster-macb142cc82018-03-30 15:22:08 -0700653void ValueMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
654 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800655
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700656 if (eventTimeNs < currentBucketEndTimeNs) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700657 VLOG("eventTime is %lld, less than next bucket start time %lld", (long long)eventTimeNs,
David Chen27785a82018-01-19 17:06:45 -0800658 (long long)(currentBucketEndTimeNs));
Chenjie Yub3dda412017-10-24 13:41:59 -0700659 return;
660 }
David Chen27785a82018-01-19 17:06:45 -0800661
662 flushCurrentBucketLocked(eventTimeNs);
663
664 int64_t numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
665 mCurrentBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
666 mCurrentBucketNum += numBucketsForward;
667
668 if (numBucketsForward > 1) {
669 VLOG("Skipping forward %lld buckets", (long long)numBucketsForward);
Misha Wagner1eee2212019-01-22 11:47:11 +0000670 StatsdStats::getInstance().noteSkippedForwardBuckets(mMetricId);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700671 // take base again in future good bucket.
Chenjie Yuf275f612018-11-30 23:29:06 -0800672 resetBase();
David Chen27785a82018-01-19 17:06:45 -0800673 }
674 VLOG("metric %lld: new bucket start time: %lld", (long long)mMetricId,
675 (long long)mCurrentBucketStartTimeNs);
676}
677
Yangster-macb142cc82018-03-30 15:22:08 -0700678void ValueMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700679 VLOG("finalizing bucket for %ld, dumping %d slices", (long)mCurrentBucketStartTimeNs,
680 (int)mCurrentSlicedBucket.size());
Yangster-macb142cc82018-03-30 15:22:08 -0700681 int64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800682
Chenjie Yu32717c32018-10-20 23:54:48 -0700683 int64_t bucketEndTime = eventTimeNs < fullBucketEndTimeNs ? eventTimeNs : fullBucketEndTimeNs;
Chenjie Yub3dda412017-10-24 13:41:59 -0700684
Chenjie Yu32717c32018-10-20 23:54:48 -0700685 if (bucketEndTime - mCurrentBucketStartTimeNs >= mMinBucketSizeNs) {
David Chen81245fd2018-04-12 14:33:37 -0700686 // The current bucket is large enough to keep.
David Chen81245fd2018-04-12 14:33:37 -0700687 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700688 ValueBucket bucket;
689 bucket.mBucketStartNs = mCurrentBucketStartTimeNs;
690 bucket.mBucketEndNs = bucketEndTime;
691 for (const auto& interval : slice.second) {
692 if (interval.hasValue) {
693 // skip the output if the diff is zero
694 if (mSkipZeroDiffOutput && mUseDiff && interval.value.isZero()) {
695 continue;
696 }
697 bucket.valueIndex.push_back(interval.valueIndex);
698 if (mAggregationType != ValueMetric::AVG) {
699 bucket.values.push_back(interval.value);
700 } else {
701 double sum = interval.value.type == LONG ? (double)interval.value.long_value
702 : interval.value.double_value;
703 bucket.values.push_back(Value((double)sum / interval.sampleSize));
704 }
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700705 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700706 }
707 // it will auto create new vector of ValuebucketInfo if the key is not found.
708 if (bucket.valueIndex.size() > 0) {
David Chen81245fd2018-04-12 14:33:37 -0700709 auto& bucketList = mPastBuckets[slice.first];
Chenjie Yu32717c32018-10-20 23:54:48 -0700710 bucketList.push_back(bucket);
David Chen81245fd2018-04-12 14:33:37 -0700711 }
Chenjie Yuae63b0a2018-04-10 14:59:31 -0700712 }
David Chen81245fd2018-04-12 14:33:37 -0700713 } else {
Chenjie Yu32717c32018-10-20 23:54:48 -0700714 mSkippedBuckets.emplace_back(mCurrentBucketStartTimeNs, bucketEndTime);
Chenjie Yub3dda412017-10-24 13:41:59 -0700715 }
716
David Chen27785a82018-01-19 17:06:45 -0800717 if (eventTimeNs > fullBucketEndTimeNs) { // If full bucket, send to anomaly tracker.
718 // Accumulate partial buckets with current value and then send to anomaly tracker.
719 if (mCurrentFullBucket.size() > 0) {
720 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yudbe5c502018-11-30 23:15:57 -0800721 if (hitFullBucketGuardRailLocked(slice.first)) {
722 continue;
723 }
Chenjie Yua0f02242018-07-06 16:14:34 -0700724 // TODO: fix this when anomaly can accept double values
Chenjie Yu32717c32018-10-20 23:54:48 -0700725 mCurrentFullBucket[slice.first] += slice.second[0].value.long_value;
David Chen27785a82018-01-19 17:06:45 -0800726 }
727 for (const auto& slice : mCurrentFullBucket) {
728 for (auto& tracker : mAnomalyTrackers) {
729 if (tracker != nullptr) {
730 tracker->addPastBucket(slice.first, slice.second, mCurrentBucketNum);
731 }
732 }
733 }
734 mCurrentFullBucket.clear();
735 } else {
736 // Skip aggregating the partial buckets since there's no previous partial bucket.
737 for (const auto& slice : mCurrentSlicedBucket) {
738 for (auto& tracker : mAnomalyTrackers) {
739 if (tracker != nullptr) {
Chenjie Yua0f02242018-07-06 16:14:34 -0700740 // TODO: fix this when anomaly can accept double values
Chenjie Yu32717c32018-10-20 23:54:48 -0700741 tracker->addPastBucket(slice.first, slice.second[0].value.long_value,
Chenjie Yua0f02242018-07-06 16:14:34 -0700742 mCurrentBucketNum);
David Chen27785a82018-01-19 17:06:45 -0800743 }
744 }
745 }
746 }
747 } else {
748 // Accumulate partial bucket.
749 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yua0f02242018-07-06 16:14:34 -0700750 // TODO: fix this when anomaly can accept double values
Chenjie Yu32717c32018-10-20 23:54:48 -0700751 mCurrentFullBucket[slice.first] += slice.second[0].value.long_value;
David Chen27785a82018-01-19 17:06:45 -0800752 }
753 }
754
Chenjie Yudbe5c502018-11-30 23:15:57 -0800755 for (auto it = mCurrentSlicedBucket.begin(); it != mCurrentSlicedBucket.end();) {
756 bool obsolete = true;
757 for (auto& interval : it->second) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700758 interval.hasValue = false;
759 interval.sampleSize = 0;
Chenjie Yudbe5c502018-11-30 23:15:57 -0800760 if (interval.seenNewData) {
761 obsolete = false;
762 }
763 interval.seenNewData = false;
764 }
765
766 if (obsolete) {
767 it = mCurrentSlicedBucket.erase(it);
768 } else {
769 it++;
Chenjie Yu32717c32018-10-20 23:54:48 -0700770 }
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700771 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700772}
773
Yangsterf2bee6f2017-11-29 12:01:05 -0800774size_t ValueMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800775 size_t totalSize = 0;
776 for (const auto& pair : mPastBuckets) {
777 totalSize += pair.second.size() * kBucketSize;
778 }
779 return totalSize;
yro2b0f8862017-11-06 14:27:31 -0800780}
781
Chenjie Yub3dda412017-10-24 13:41:59 -0700782} // namespace statsd
783} // namespace os
Yao Chen93fe3a32017-11-02 13:52:59 -0700784} // namespace android