blob: 5645461cc3aba5171f84a205fa799e14eca1bce4 [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);
Yao Chen2794da22017-12-13 16:01:55 -0800325 return;
326 }
327
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700328 flushIfNeededLocked(eventTimeNs);
Chenjie Yua7259ab2017-12-10 08:31:05 -0800329
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700330 // Pull on condition changes.
331 if (mIsPulled && (mCondition != condition)) {
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800332 pullAndMatchEventsLocked(eventTimeNs);
Chenjie Yue1361ed2018-07-23 17:33:09 -0700333 }
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700334
Chenjie Yuf275f612018-11-30 23:29:06 -0800335 // when condition change from true to false, clear diff base but don't
336 // reset other counters as we may accumulate more value in the bucket.
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700337 if (mUseDiff && mCondition && !condition) {
Chenjie Yuf275f612018-11-30 23:29:06 -0800338 resetBase();
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700339 }
340
341 mCondition = condition;
Chenjie Yue1361ed2018-07-23 17:33:09 -0700342}
343
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800344void ValueMetricProducer::pullAndMatchEventsLocked(const int64_t timestampNs) {
Chenjie Yue1361ed2018-07-23 17:33:09 -0700345 vector<std::shared_ptr<LogEvent>> allData;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800346 if (!mPullerManager->Pull(mPullTagId, &allData)) {
347 ALOGE("Gauge Stats puller failed for tag: %d at %lld", mPullTagId, (long long)timestampNs);
Chenjie Yuf275f612018-11-30 23:29:06 -0800348 resetBase();
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800349 return;
Chenjie Yub3dda412017-10-24 13:41:59 -0700350 }
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800351 const int64_t pullDelayNs = getElapsedRealtimeNs() - timestampNs;
352 if (pullDelayNs > mMaxPullDelayNs) {
353 ALOGE("Pull finish too late for atom %d, longer than %lld", mPullTagId,
354 (long long)mMaxPullDelayNs);
355 StatsdStats::getInstance().notePullExceedMaxDelay(mPullTagId);
356 StatsdStats::getInstance().notePullDelay(mPullTagId, pullDelayNs);
357 resetBase();
358 return;
359 }
360 StatsdStats::getInstance().notePullDelay(mPullTagId, pullDelayNs);
361
362 for (const auto& data : allData) {
363 // make a copy before doing and changes
364 LogEvent localCopy = data->makeCopy();
365 localCopy.setElapsedTimestampNs(timestampNs);
366 if (mEventMatcherWizard->matchLogEvent(localCopy, mWhatMatcherIndex) ==
367 MatchingState::kMatched) {
368 onMatchedLogEventLocked(mWhatMatcherIndex, localCopy);
369 }
370 }
371 mHasGlobalBase = true;
Chenjie Yub3dda412017-10-24 13:41:59 -0700372}
373
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700374int64_t ValueMetricProducer::calcPreviousBucketEndTime(const int64_t currentTimeNs) {
375 return mTimeBaseNs + ((currentTimeNs - mTimeBaseNs) / mBucketSizeNs) * mBucketSizeNs;
376}
377
Chenjie Yub3dda412017-10-24 13:41:59 -0700378void ValueMetricProducer::onDataPulled(const std::vector<std::shared_ptr<LogEvent>>& allData) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800379 std::lock_guard<std::mutex> lock(mMutex);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700380 if (mCondition) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700381 if (allData.size() == 0) {
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800382 VLOG("Data pulled is empty");
Chenjie Yub3dda412017-10-24 13:41:59 -0700383 return;
384 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800385 // For scheduled pulled data, the effective event time is snap to the nearest
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700386 // bucket end. In the case of waking up from a deep sleep state, we will
387 // attribute to the previous bucket end. If the sleep was long but not very long, we
388 // will be in the immediate next bucket. Previous bucket may get a larger number as
389 // we pull at a later time than real bucket end.
390 // If the sleep was very long, we skip more than one bucket before sleep. In this case,
391 // if the diff base will be cleared and this new data will serve as new diff base.
Yangster-macb142cc82018-03-30 15:22:08 -0700392 int64_t realEventTime = allData.at(0)->GetElapsedTimestampNs();
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700393 int64_t bucketEndTime = calcPreviousBucketEndTime(realEventTime) - 1;
394 if (bucketEndTime < mCurrentBucketStartTimeNs) {
395 VLOG("Skip bucket end pull due to late arrival: %lld vs %lld", (long long)bucketEndTime,
396 (long long)mCurrentBucketStartTimeNs);
397 return;
Chenjie Yub3dda412017-10-24 13:41:59 -0700398 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800399 for (const auto& data : allData) {
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800400 LogEvent localCopy = data->makeCopy();
401 if (mEventMatcherWizard->matchLogEvent(localCopy, mWhatMatcherIndex) ==
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800402 MatchingState::kMatched) {
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800403 localCopy.setElapsedTimestampNs(bucketEndTime);
404 onMatchedLogEventLocked(mWhatMatcherIndex, localCopy);
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800405 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800406 }
Chenjie Yuf275f612018-11-30 23:29:06 -0800407 mHasGlobalBase = true;
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800408 } else {
409 VLOG("No need to commit data on condition false.");
Chenjie Yub3dda412017-10-24 13:41:59 -0700410 }
411}
412
Yangster-maca78d0082018-03-12 12:02:56 -0700413void ValueMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
414 if (mCurrentSlicedBucket.size() == 0) {
415 return;
416 }
417
418 fprintf(out, "ValueMetric %lld dimension size %lu\n", (long long)mMetricId,
419 (unsigned long)mCurrentSlicedBucket.size());
420 if (verbose) {
421 for (const auto& it : mCurrentSlicedBucket) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700422 for (const auto& interval : it.second) {
Chenjie Yua0f02242018-07-06 16:14:34 -0700423 fprintf(out, "\t(what)%s\t(condition)%s (value)%s\n",
424 it.first.getDimensionKeyInWhat().toString().c_str(),
425 it.first.getDimensionKeyInCondition().toString().c_str(),
Chenjie Yu32717c32018-10-20 23:54:48 -0700426 interval.value.toString().c_str());
427 }
Yangster-maca78d0082018-03-12 12:02:56 -0700428 }
429 }
430}
431
Yangster-mac93694462018-01-22 20:49:31 -0800432bool ValueMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800433 // ===========GuardRail==============
434 // 1. Report the tuple count if the tuple count > soft limit
435 if (mCurrentSlicedBucket.find(newKey) != mCurrentSlicedBucket.end()) {
436 return false;
437 }
Chenjie Yuc5875052018-03-09 10:13:11 -0800438 if (mCurrentSlicedBucket.size() > mDimensionSoftLimit - 1) {
Yao Chenb3561512017-11-21 18:07:17 -0800439 size_t newTupleCount = mCurrentSlicedBucket.size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800440 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800441 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
Chenjie Yuc5875052018-03-09 10:13:11 -0800442 if (newTupleCount > mDimensionHardLimit) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700443 ALOGE("ValueMetric %lld dropping data for dimension key %s", (long long)mMetricId,
444 newKey.toString().c_str());
Yao Chenb3561512017-11-21 18:07:17 -0800445 return true;
446 }
447 }
448
449 return false;
450}
451
Chenjie Yudbe5c502018-11-30 23:15:57 -0800452bool ValueMetricProducer::hitFullBucketGuardRailLocked(const MetricDimensionKey& newKey) {
453 // ===========GuardRail==============
454 // 1. Report the tuple count if the tuple count > soft limit
455 if (mCurrentFullBucket.find(newKey) != mCurrentFullBucket.end()) {
456 return false;
457 }
458 if (mCurrentFullBucket.size() > mDimensionSoftLimit - 1) {
459 size_t newTupleCount = mCurrentFullBucket.size() + 1;
460 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
461 if (newTupleCount > mDimensionHardLimit) {
462 ALOGE("ValueMetric %lld dropping data for full bucket dimension key %s",
463 (long long)mMetricId,
464 newKey.toString().c_str());
465 return true;
466 }
467 }
468
469 return false;
470}
471
Chenjie Yu32717c32018-10-20 23:54:48 -0700472bool getDoubleOrLong(const LogEvent& event, const Matcher& matcher, Value& ret) {
473 for (const FieldValue& value : event.getValues()) {
474 if (value.mField.matches(matcher)) {
475 switch (value.mValue.type) {
476 case INT:
477 ret.setLong(value.mValue.int_value);
478 break;
479 case LONG:
480 ret.setLong(value.mValue.long_value);
481 break;
482 case FLOAT:
483 ret.setDouble(value.mValue.float_value);
484 break;
485 case DOUBLE:
486 ret.setDouble(value.mValue.double_value);
487 break;
488 default:
489 break;
490 }
491 return true;
492 }
Chenjie Yua0f02242018-07-06 16:14:34 -0700493 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700494 return false;
Chenjie Yua0f02242018-07-06 16:14:34 -0700495}
496
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700497void ValueMetricProducer::onMatchedLogEventInternalLocked(const size_t matcherIndex,
498 const MetricDimensionKey& eventKey,
499 const ConditionKey& conditionKey,
500 bool condition, const LogEvent& event) {
Yangster-macb142cc82018-03-30 15:22:08 -0700501 int64_t eventTimeNs = event.GetElapsedTimestampNs();
Yao Chen6a8c7992017-11-29 20:02:07 +0000502 if (eventTimeNs < mCurrentBucketStartTimeNs) {
503 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
504 (long long)mCurrentBucketStartTimeNs);
505 return;
506 }
507
Chenjie Yua7259ab2017-12-10 08:31:05 -0800508 flushIfNeededLocked(eventTimeNs);
509
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700510 // For pulled data, we already check condition when we decide to pull or
511 // in onDataPulled. So take all of them.
512 // For pushed data, just check condition.
513 if (!(mIsPulled || condition)) {
514 VLOG("ValueMetric skip event because condition is false");
515 return;
516 }
517
Yangsterf2bee6f2017-11-29 12:01:05 -0800518 if (hitGuardRailLocked(eventKey)) {
Yangster8de69392017-11-27 13:48:29 -0800519 return;
520 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700521 vector<Interval>& multiIntervals = mCurrentSlicedBucket[eventKey];
522 if (multiIntervals.size() < mFieldMatchers.size()) {
523 VLOG("Resizing number of intervals to %d", (int)mFieldMatchers.size());
524 multiIntervals.resize(mFieldMatchers.size());
Yangster-maca7fb12d2018-01-03 17:17:20 -0800525 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000526
Misha Wagner26531762019-01-21 14:18:51 +0000527 // We only use anomaly detection under certain cases.
528 // N.B.: The anomaly detection cases were modified in order to fix an issue with value metrics
529 // containing multiple values. We tried to retain all previous behaviour, but we are unsure the
530 // previous behaviour was correct. At the time of the fix, anomaly detection had no owner.
531 // Whoever next works on it should look into the cases where it is triggered in this function.
532 // Discussion here: http://ag/6124370.
533 bool useAnomalyDetection = true;
534
Chenjie Yu32717c32018-10-20 23:54:48 -0700535 for (int i = 0; i < (int)mFieldMatchers.size(); i++) {
536 const Matcher& matcher = mFieldMatchers[i];
537 Interval& interval = multiIntervals[i];
538 interval.valueIndex = i;
539 Value value;
540 if (!getDoubleOrLong(event, matcher, value)) {
541 VLOG("Failed to get value %d from event %s", i, event.ToString().c_str());
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700542 return;
543 }
Chenjie Yudbe5c502018-11-30 23:15:57 -0800544 interval.seenNewData = true;
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700545
Chenjie Yu32717c32018-10-20 23:54:48 -0700546 if (mUseDiff) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700547 if (!interval.hasBase) {
Chenjie Yuf275f612018-11-30 23:29:06 -0800548 if (mHasGlobalBase && mUseZeroDefaultBase) {
549 // The bucket has global base. This key does not.
550 // Optionally use zero as base.
551 interval.base = (value.type == LONG ? ZERO_LONG : ZERO_DOUBLE);
552 interval.hasBase = true;
553 } else {
554 // no base. just update base and return.
555 interval.base = value;
556 interval.hasBase = true;
Misha Wagner26531762019-01-21 14:18:51 +0000557 // If we're missing a base, do not use anomaly detection on incomplete data
558 useAnomalyDetection = false;
559 // Continue (instead of return) here in order to set interval.base and
560 // interval.hasBase for other intervals
561 continue;
Chenjie Yuf275f612018-11-30 23:29:06 -0800562 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700563 }
564 Value diff;
565 switch (mValueDirection) {
566 case ValueMetric::INCREASING:
567 if (value >= interval.base) {
568 diff = value - interval.base;
569 } else if (mUseAbsoluteValueOnReset) {
570 diff = value;
571 } else {
572 VLOG("Unexpected decreasing value");
573 StatsdStats::getInstance().notePullDataError(mPullTagId);
574 interval.base = value;
Misha Wagner26531762019-01-21 14:18:51 +0000575 // If we've got bad data, do not use anomaly detection
576 useAnomalyDetection = false;
577 continue;
Chenjie Yu32717c32018-10-20 23:54:48 -0700578 }
579 break;
580 case ValueMetric::DECREASING:
581 if (interval.base >= value) {
582 diff = interval.base - value;
583 } else if (mUseAbsoluteValueOnReset) {
584 diff = value;
585 } else {
586 VLOG("Unexpected increasing value");
587 StatsdStats::getInstance().notePullDataError(mPullTagId);
588 interval.base = value;
Misha Wagner26531762019-01-21 14:18:51 +0000589 // If we've got bad data, do not use anomaly detection
590 useAnomalyDetection = false;
591 continue;
Chenjie Yu32717c32018-10-20 23:54:48 -0700592 }
593 break;
594 case ValueMetric::ANY:
595 diff = value - interval.base;
596 break;
597 default:
598 break;
599 }
600 interval.base = value;
601 value = diff;
Yao Chen6a8c7992017-11-29 20:02:07 +0000602 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700603
604 if (interval.hasValue) {
605 switch (mAggregationType) {
606 case ValueMetric::SUM:
607 // for AVG, we add up and take average when flushing the bucket
608 case ValueMetric::AVG:
609 interval.value += value;
610 break;
611 case ValueMetric::MIN:
612 interval.value = std::min(value, interval.value);
613 break;
614 case ValueMetric::MAX:
615 interval.value = std::max(value, interval.value);
616 break;
617 default:
618 break;
619 }
620 } else {
621 interval.value = value;
622 interval.hasValue = true;
623 }
624 interval.sampleSize += 1;
Yangster8de69392017-11-27 13:48:29 -0800625 }
Bookatzde1b55622017-12-14 18:38:27 -0800626
Misha Wagner26531762019-01-21 14:18:51 +0000627 // Only trigger the tracker if all intervals are correct
628 if (useAnomalyDetection) {
629 // TODO: propgate proper values down stream when anomaly support doubles
630 long wholeBucketVal = multiIntervals[0].value.long_value;
631 auto prev = mCurrentFullBucket.find(eventKey);
632 if (prev != mCurrentFullBucket.end()) {
633 wholeBucketVal += prev->second;
634 }
635 for (auto& tracker : mAnomalyTrackers) {
636 tracker->detectAndDeclareAnomaly(
637 eventTimeNs, mCurrentBucketNum, eventKey, wholeBucketVal);
638 }
Bookatzde1b55622017-12-14 18:38:27 -0800639 }
Yangster8de69392017-11-27 13:48:29 -0800640}
641
Yangster-macb142cc82018-03-30 15:22:08 -0700642void ValueMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
643 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800644
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700645 if (eventTimeNs < currentBucketEndTimeNs) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700646 VLOG("eventTime is %lld, less than next bucket start time %lld", (long long)eventTimeNs,
David Chen27785a82018-01-19 17:06:45 -0800647 (long long)(currentBucketEndTimeNs));
Chenjie Yub3dda412017-10-24 13:41:59 -0700648 return;
649 }
David Chen27785a82018-01-19 17:06:45 -0800650
651 flushCurrentBucketLocked(eventTimeNs);
652
653 int64_t numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
654 mCurrentBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
655 mCurrentBucketNum += numBucketsForward;
656
657 if (numBucketsForward > 1) {
658 VLOG("Skipping forward %lld buckets", (long long)numBucketsForward);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700659 // take base again in future good bucket.
Chenjie Yuf275f612018-11-30 23:29:06 -0800660 resetBase();
David Chen27785a82018-01-19 17:06:45 -0800661 }
662 VLOG("metric %lld: new bucket start time: %lld", (long long)mMetricId,
663 (long long)mCurrentBucketStartTimeNs);
664}
665
Yangster-macb142cc82018-03-30 15:22:08 -0700666void ValueMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700667 VLOG("finalizing bucket for %ld, dumping %d slices", (long)mCurrentBucketStartTimeNs,
668 (int)mCurrentSlicedBucket.size());
Yangster-macb142cc82018-03-30 15:22:08 -0700669 int64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800670
Chenjie Yu32717c32018-10-20 23:54:48 -0700671 int64_t bucketEndTime = eventTimeNs < fullBucketEndTimeNs ? eventTimeNs : fullBucketEndTimeNs;
Chenjie Yub3dda412017-10-24 13:41:59 -0700672
Chenjie Yu32717c32018-10-20 23:54:48 -0700673 if (bucketEndTime - mCurrentBucketStartTimeNs >= mMinBucketSizeNs) {
David Chen81245fd2018-04-12 14:33:37 -0700674 // The current bucket is large enough to keep.
David Chen81245fd2018-04-12 14:33:37 -0700675 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700676 ValueBucket bucket;
677 bucket.mBucketStartNs = mCurrentBucketStartTimeNs;
678 bucket.mBucketEndNs = bucketEndTime;
679 for (const auto& interval : slice.second) {
680 if (interval.hasValue) {
681 // skip the output if the diff is zero
682 if (mSkipZeroDiffOutput && mUseDiff && interval.value.isZero()) {
683 continue;
684 }
685 bucket.valueIndex.push_back(interval.valueIndex);
686 if (mAggregationType != ValueMetric::AVG) {
687 bucket.values.push_back(interval.value);
688 } else {
689 double sum = interval.value.type == LONG ? (double)interval.value.long_value
690 : interval.value.double_value;
691 bucket.values.push_back(Value((double)sum / interval.sampleSize));
692 }
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700693 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700694 }
695 // it will auto create new vector of ValuebucketInfo if the key is not found.
696 if (bucket.valueIndex.size() > 0) {
David Chen81245fd2018-04-12 14:33:37 -0700697 auto& bucketList = mPastBuckets[slice.first];
Chenjie Yu32717c32018-10-20 23:54:48 -0700698 bucketList.push_back(bucket);
David Chen81245fd2018-04-12 14:33:37 -0700699 }
Chenjie Yuae63b0a2018-04-10 14:59:31 -0700700 }
David Chen81245fd2018-04-12 14:33:37 -0700701 } else {
Chenjie Yu32717c32018-10-20 23:54:48 -0700702 mSkippedBuckets.emplace_back(mCurrentBucketStartTimeNs, bucketEndTime);
Chenjie Yub3dda412017-10-24 13:41:59 -0700703 }
704
David Chen27785a82018-01-19 17:06:45 -0800705 if (eventTimeNs > fullBucketEndTimeNs) { // If full bucket, send to anomaly tracker.
706 // Accumulate partial buckets with current value and then send to anomaly tracker.
707 if (mCurrentFullBucket.size() > 0) {
708 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yudbe5c502018-11-30 23:15:57 -0800709 if (hitFullBucketGuardRailLocked(slice.first)) {
710 continue;
711 }
Chenjie Yua0f02242018-07-06 16:14:34 -0700712 // TODO: fix this when anomaly can accept double values
Chenjie Yu32717c32018-10-20 23:54:48 -0700713 mCurrentFullBucket[slice.first] += slice.second[0].value.long_value;
David Chen27785a82018-01-19 17:06:45 -0800714 }
715 for (const auto& slice : mCurrentFullBucket) {
716 for (auto& tracker : mAnomalyTrackers) {
717 if (tracker != nullptr) {
718 tracker->addPastBucket(slice.first, slice.second, mCurrentBucketNum);
719 }
720 }
721 }
722 mCurrentFullBucket.clear();
723 } else {
724 // Skip aggregating the partial buckets since there's no previous partial bucket.
725 for (const auto& slice : mCurrentSlicedBucket) {
726 for (auto& tracker : mAnomalyTrackers) {
727 if (tracker != nullptr) {
Chenjie Yua0f02242018-07-06 16:14:34 -0700728 // TODO: fix this when anomaly can accept double values
Chenjie Yu32717c32018-10-20 23:54:48 -0700729 tracker->addPastBucket(slice.first, slice.second[0].value.long_value,
Chenjie Yua0f02242018-07-06 16:14:34 -0700730 mCurrentBucketNum);
David Chen27785a82018-01-19 17:06:45 -0800731 }
732 }
733 }
734 }
735 } else {
736 // Accumulate partial bucket.
737 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yua0f02242018-07-06 16:14:34 -0700738 // TODO: fix this when anomaly can accept double values
Chenjie Yu32717c32018-10-20 23:54:48 -0700739 mCurrentFullBucket[slice.first] += slice.second[0].value.long_value;
David Chen27785a82018-01-19 17:06:45 -0800740 }
741 }
742
Chenjie Yudbe5c502018-11-30 23:15:57 -0800743 for (auto it = mCurrentSlicedBucket.begin(); it != mCurrentSlicedBucket.end();) {
744 bool obsolete = true;
745 for (auto& interval : it->second) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700746 interval.hasValue = false;
747 interval.sampleSize = 0;
Chenjie Yudbe5c502018-11-30 23:15:57 -0800748 if (interval.seenNewData) {
749 obsolete = false;
750 }
751 interval.seenNewData = false;
752 }
753
754 if (obsolete) {
755 it = mCurrentSlicedBucket.erase(it);
756 } else {
757 it++;
Chenjie Yu32717c32018-10-20 23:54:48 -0700758 }
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700759 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700760}
761
Yangsterf2bee6f2017-11-29 12:01:05 -0800762size_t ValueMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800763 size_t totalSize = 0;
764 for (const auto& pair : mPastBuckets) {
765 totalSize += pair.second.size() * kBucketSize;
766 }
767 return totalSize;
yro2b0f8862017-11-06 14:27:31 -0800768}
769
Chenjie Yub3dda412017-10-24 13:41:59 -0700770} // namespace statsd
771} // namespace os
Yao Chen93fe3a32017-11-02 13:52:59 -0700772} // namespace android