blob: bff23345a060fd5758685f1123623b3d31b2079c [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;
yro2b0f8862017-11-06 14:27:31 -080055// for ValueMetricDataWrapper
56const int FIELD_ID_DATA = 1;
David Chen81245fd2018-04-12 14:33:37 -070057const int FIELD_ID_SKIPPED = 2;
Yangster-mac9def8e32018-04-17 13:55:51 -070058const int FIELD_ID_SKIPPED_START_MILLIS = 3;
59const int FIELD_ID_SKIPPED_END_MILLIS = 4;
yro2b0f8862017-11-06 14:27:31 -080060// for ValueMetricData
Yangster-mac468ff042018-01-17 12:26:34 -080061const int FIELD_ID_DIMENSION_IN_WHAT = 1;
62const int FIELD_ID_DIMENSION_IN_CONDITION = 2;
63const int FIELD_ID_BUCKET_INFO = 3;
Yangster-mac9def8e32018-04-17 13:55:51 -070064const int FIELD_ID_DIMENSION_LEAF_IN_WHAT = 4;
65const int FIELD_ID_DIMENSION_LEAF_IN_CONDITION = 5;
yro2b0f8862017-11-06 14:27:31 -080066// for ValueBucketInfo
Chenjie Yu32717c32018-10-20 23:54:48 -070067const int FIELD_ID_VALUE_INDEX = 1;
68const int FIELD_ID_VALUE_LONG = 2;
69const int FIELD_ID_VALUE_DOUBLE = 3;
70const int FIELD_ID_VALUES = 9;
Yangster-mac9def8e32018-04-17 13:55:51 -070071const int FIELD_ID_BUCKET_NUM = 4;
72const int FIELD_ID_START_BUCKET_ELAPSED_MILLIS = 5;
73const int FIELD_ID_END_BUCKET_ELAPSED_MILLIS = 6;
yro2b0f8862017-11-06 14:27:31 -080074
Chenjie Yuf275f612018-11-30 23:29:06 -080075const Value ZERO_LONG((int64_t)0);
76const Value ZERO_DOUBLE((int64_t)0);
77
Chenjie Yub3dda412017-10-24 13:41:59 -070078// ValueMetric has a minimum bucket size of 10min so that we don't pull too frequently
Chenjie Yuf275f612018-11-30 23:29:06 -080079ValueMetricProducer::ValueMetricProducer(
80 const ConfigKey& key, const ValueMetric& metric, const int conditionIndex,
81 const sp<ConditionWizard>& conditionWizard, const int whatMatcherIndex,
82 const sp<EventMatcherWizard>& matcherWizard, const int pullTagId, const int64_t timeBaseNs,
83 const int64_t startTimeNs, const sp<StatsPullerManager>& pullerManager)
Chenjie Yu054ce9c2018-11-12 15:27:29 -080084 : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, conditionWizard),
85 mWhatMatcherIndex(whatMatcherIndex),
86 mEventMatcherWizard(matcherWizard),
Chenjie Yue2219202018-06-08 10:07:51 -070087 mPullerManager(pullerManager),
Chenjie Yuc5875052018-03-09 10:13:11 -080088 mPullTagId(pullTagId),
Chenjie Yua0f02242018-07-06 16:14:34 -070089 mIsPulled(pullTagId != -1),
David Chen81245fd2018-04-12 14:33:37 -070090 mMinBucketSizeNs(metric.min_bucket_size_nanos()),
Chenjie Yuc5875052018-03-09 10:13:11 -080091 mDimensionSoftLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
92 StatsdStats::kAtomDimensionKeySizeLimitMap.end()
93 ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).first
94 : StatsdStats::kDimensionKeySizeSoftLimit),
95 mDimensionHardLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
96 StatsdStats::kAtomDimensionKeySizeLimitMap.end()
97 ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).second
Chenjie Yu47234642018-05-14 10:14:16 -070098 : StatsdStats::kDimensionKeySizeHardLimit),
Chenjie Yua0f02242018-07-06 16:14:34 -070099 mUseAbsoluteValueOnReset(metric.use_absolute_value_on_reset()),
100 mAggregationType(metric.aggregation_type()),
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700101 mUseDiff(metric.has_use_diff() ? metric.use_diff() : (mIsPulled ? true : false)),
102 mValueDirection(metric.value_direction()),
Chenjie Yuf275f612018-11-30 23:29:06 -0800103 mSkipZeroDiffOutput(metric.skip_zero_diff_output()),
104 mUseZeroDefaultBase(metric.use_zero_default_base()),
105 mHasGlobalBase(false) {
Yangster-macb8144812018-01-04 10:56:23 -0800106 int64_t bucketSizeMills = 0;
107 if (metric.has_bucket()) {
yro59cc24d2018-02-13 20:17:32 -0800108 bucketSizeMills = TimeUnitToBucketSizeInMillisGuardrailed(key.GetUid(), metric.bucket());
Chenjie Yu6736c892017-11-09 10:50:09 -0800109 } else {
Yangster-macb8144812018-01-04 10:56:23 -0800110 bucketSizeMills = TimeUnitToBucketSizeInMillis(ONE_HOUR);
Chenjie Yu6736c892017-11-09 10:50:09 -0800111 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700112
Yangster-macb8144812018-01-04 10:56:23 -0800113 mBucketSizeNs = bucketSizeMills * 1000000;
Chenjie Yu32717c32018-10-20 23:54:48 -0700114
115 translateFieldMatcher(metric.value_field(), &mFieldMatchers);
116
Yao Chen8a8d16c2018-02-08 14:50:40 -0800117 if (metric.has_dimensions_in_what()) {
118 translateFieldMatcher(metric.dimensions_in_what(), &mDimensionsInWhat);
Yangster13fb7e42018-03-07 17:30:49 -0800119 mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
Yao Chen8a8d16c2018-02-08 14:50:40 -0800120 }
121
122 if (metric.has_dimensions_in_condition()) {
123 translateFieldMatcher(metric.dimensions_in_condition(), &mDimensionsInCondition);
124 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700125
Yao Chen93fe3a32017-11-02 13:52:59 -0700126 if (metric.links().size() > 0) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800127 for (const auto& link : metric.links()) {
128 Metric2Condition mc;
129 mc.conditionId = link.condition();
130 translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
131 translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
132 mMetric2ConditionLinks.push_back(mc);
133 }
Yao Chen93fe3a32017-11-02 13:52:59 -0700134 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800135
Yao Chen8a8d16c2018-02-08 14:50:40 -0800136 mConditionSliced = (metric.links().size() > 0) || (mDimensionsInCondition.size() > 0);
Yangster-mac9def8e32018-04-17 13:55:51 -0700137 mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what()) ||
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700138 HasPositionALL(metric.dimensions_in_condition());
Chenjie Yub3dda412017-10-24 13:41:59 -0700139
Chenjie Yue1361ed2018-07-23 17:33:09 -0700140 flushIfNeededLocked(startTimeNs);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700141
Chenjie Yua0f02242018-07-06 16:14:34 -0700142 if (mIsPulled) {
Chenjie Yue1361ed2018-07-23 17:33:09 -0700143 mPullerManager->RegisterReceiver(mPullTagId, this, getCurrentBucketEndTimeNs(),
144 mBucketSizeNs);
Yao Chen93fe3a32017-11-02 13:52:59 -0700145 }
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700146
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700147 // Only do this for partial buckets like first bucket. All other buckets should use
Chenjie Yue1361ed2018-07-23 17:33:09 -0700148 // flushIfNeeded to adjust start and end to bucket boundaries.
149 // Adjust start for partial bucket
150 mCurrentBucketStartTimeNs = startTimeNs;
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700151 // Kicks off the puller immediately if condition is true and diff based.
152 if (mIsPulled && mCondition && mUseDiff) {
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800153 pullAndMatchEventsLocked(startTimeNs);
Chenjie Yue1361ed2018-07-23 17:33:09 -0700154 }
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700155 VLOG("value metric %lld created. bucket size %lld start_time: %lld", (long long)metric.id(),
156 (long long)mBucketSizeNs, (long long)mTimeBaseNs);
Chenjie Yub3dda412017-10-24 13:41:59 -0700157}
158
159ValueMetricProducer::~ValueMetricProducer() {
Yao Chen93fe3a32017-11-02 13:52:59 -0700160 VLOG("~ValueMetricProducer() called");
Chenjie Yua0f02242018-07-06 16:14:34 -0700161 if (mIsPulled) {
Chenjie Yue2219202018-06-08 10:07:51 -0700162 mPullerManager->UnRegisterReceiver(mPullTagId, this);
Chenjie Yu6736c892017-11-09 10:50:09 -0800163 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700164}
165
Yao Chen427d3722018-03-22 15:21:52 -0700166void ValueMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
Yangster-macb142cc82018-03-30 15:22:08 -0700167 const int64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800168 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Chenjie Yub3dda412017-10-24 13:41:59 -0700169}
170
Yangster-macb142cc82018-03-30 15:22:08 -0700171void ValueMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
Yao Chen06dba5d2018-01-26 13:38:16 -0800172 flushIfNeededLocked(dropTimeNs);
173 mPastBuckets.clear();
174}
175
Yangster-maca802d732018-04-24 07:50:38 -0700176void ValueMetricProducer::clearPastBucketsLocked(const int64_t dumpTimeNs) {
177 flushIfNeededLocked(dumpTimeNs);
178 mPastBuckets.clear();
179 mSkippedBuckets.clear();
180}
181
Yangster-macb142cc82018-03-30 15:22:08 -0700182void ValueMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700183 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700184 const bool erase_data,
Yangster-mac9def8e32018-04-17 13:55:51 -0700185 std::set<string> *str_set,
Yao Chen288c6002017-12-12 13:43:18 -0800186 ProtoOutputStream* protoOutput) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800187 VLOG("metric %lld dump report now...", (long long)mMetricId);
Yangster-mace68f3a52018-04-04 00:01:43 -0700188 if (include_current_partial_bucket) {
189 flushLocked(dumpTimeNs);
190 } else {
191 flushIfNeededLocked(dumpTimeNs);
192 }
David Chen81245fd2018-04-12 14:33:37 -0700193 if (mPastBuckets.empty() && mSkippedBuckets.empty()) {
Yangster-mac635b4b32018-01-23 20:17:35 -0800194 return;
195 }
Yangster-mac94e197c2018-01-02 16:03:03 -0800196 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Yangster-mac9def8e32018-04-17 13:55:51 -0700197 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_TIME_BASE, (long long)mTimeBaseNs);
198 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_SIZE, (long long)mBucketSizeNs);
199 // Fills the dimension path if not slicing by ALL.
200 if (!mSliceByPositionALL) {
201 if (!mDimensionsInWhat.empty()) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700202 uint64_t dimenPathToken =
203 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_WHAT);
Yangster-mac9def8e32018-04-17 13:55:51 -0700204 writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
205 protoOutput->end(dimenPathToken);
206 }
207 if (!mDimensionsInCondition.empty()) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700208 uint64_t dimenPathToken =
209 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_CONDITION);
Yangster-mac9def8e32018-04-17 13:55:51 -0700210 writeDimensionPathToProto(mDimensionsInCondition, protoOutput);
211 protoOutput->end(dimenPathToken);
212 }
213 }
214
Yi Jin5ee07872018-03-05 18:18:27 -0800215 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_VALUE_METRICS);
Yao Chen6a8c7992017-11-29 20:02:07 +0000216
David Chen81245fd2018-04-12 14:33:37 -0700217 for (const auto& pair : mSkippedBuckets) {
218 uint64_t wrapperToken =
219 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_SKIPPED);
Yangster-mac9def8e32018-04-17 13:55:51 -0700220 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_START_MILLIS,
221 (long long)(NanoToMillis(pair.first)));
222 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_END_MILLIS,
223 (long long)(NanoToMillis(pair.second)));
David Chen81245fd2018-04-12 14:33:37 -0700224 protoOutput->end(wrapperToken);
225 }
David Chen81245fd2018-04-12 14:33:37 -0700226
Yao Chen93fe3a32017-11-02 13:52:59 -0700227 for (const auto& pair : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800228 const MetricDimensionKey& dimensionKey = pair.first;
Yangster13fb7e42018-03-07 17:30:49 -0800229 VLOG(" dimension key %s", dimensionKey.toString().c_str());
Yi Jin5ee07872018-03-05 18:18:27 -0800230 uint64_t wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800231 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
Chenjie Yub3dda412017-10-24 13:41:59 -0700232
Yangster-mac20877162017-12-22 17:19:39 -0800233 // First fill dimension.
Yangster-mac9def8e32018-04-17 13:55:51 -0700234 if (mSliceByPositionALL) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700235 uint64_t dimensionToken =
236 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
Yangster-mac9def8e32018-04-17 13:55:51 -0700237 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), str_set, protoOutput);
238 protoOutput->end(dimensionToken);
239 if (dimensionKey.hasDimensionKeyInCondition()) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700240 uint64_t dimensionInConditionToken =
241 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
242 writeDimensionToProto(dimensionKey.getDimensionKeyInCondition(), str_set,
243 protoOutput);
Yangster-mac9def8e32018-04-17 13:55:51 -0700244 protoOutput->end(dimensionInConditionToken);
245 }
246 } else {
247 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInWhat(),
248 FIELD_ID_DIMENSION_LEAF_IN_WHAT, str_set, protoOutput);
249 if (dimensionKey.hasDimensionKeyInCondition()) {
250 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInCondition(),
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700251 FIELD_ID_DIMENSION_LEAF_IN_CONDITION, str_set,
252 protoOutput);
Yangster-mac9def8e32018-04-17 13:55:51 -0700253 }
Yangster-mac93694462018-01-22 20:49:31 -0800254 }
yro2b0f8862017-11-06 14:27:31 -0800255
256 // Then fill bucket_info (ValueBucketInfo).
257 for (const auto& bucket : pair.second) {
Yi Jin5ee07872018-03-05 18:18:27 -0800258 uint64_t bucketInfoToken = protoOutput->start(
Yao Chen288c6002017-12-12 13:43:18 -0800259 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
Yangster-mac9def8e32018-04-17 13:55:51 -0700260
261 if (bucket.mBucketEndNs - bucket.mBucketStartNs != mBucketSizeNs) {
262 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_MILLIS,
263 (long long)NanoToMillis(bucket.mBucketStartNs));
264 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_MILLIS,
265 (long long)NanoToMillis(bucket.mBucketEndNs));
266 } else {
267 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_NUM,
268 (long long)(getBucketNumFromEndTimeNs(bucket.mBucketEndNs)));
269 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700270 for (int i = 0; i < (int)bucket.valueIndex.size(); i ++) {
271 int index = bucket.valueIndex[i];
272 const Value& value = bucket.values[i];
273 uint64_t valueToken = protoOutput->start(
274 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_VALUES);
275 protoOutput->write(FIELD_TYPE_INT32 | FIELD_ID_VALUE_INDEX,
276 index);
277 if (value.getType() == LONG) {
278 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_VALUE_LONG,
279 (long long)value.long_value);
280 VLOG("\t bucket [%lld - %lld] value %d: %lld", (long long)bucket.mBucketStartNs,
281 (long long)bucket.mBucketEndNs, index, (long long)value.long_value);
282 } else if (value.getType() == DOUBLE) {
283 protoOutput->write(FIELD_TYPE_DOUBLE | FIELD_ID_VALUE_DOUBLE,
284 value.double_value);
285 VLOG("\t bucket [%lld - %lld] value %d: %.2f", (long long)bucket.mBucketStartNs,
286 (long long)bucket.mBucketEndNs, index, value.double_value);
287 } else {
288 VLOG("Wrong value type for ValueMetric output: %d", value.getType());
289 }
290 protoOutput->end(valueToken);
Chenjie Yua0f02242018-07-06 16:14:34 -0700291 }
Yao Chen288c6002017-12-12 13:43:18 -0800292 protoOutput->end(bucketInfoToken);
yro2b0f8862017-11-06 14:27:31 -0800293 }
Yao Chen288c6002017-12-12 13:43:18 -0800294 protoOutput->end(wrapperToken);
Chenjie Yub3dda412017-10-24 13:41:59 -0700295 }
Yao Chen288c6002017-12-12 13:43:18 -0800296 protoOutput->end(protoToken);
yro2b0f8862017-11-06 14:27:31 -0800297
Yangster-mac94e197c2018-01-02 16:03:03 -0800298 VLOG("metric %lld dump report now...", (long long)mMetricId);
Bookatzff71cad2018-09-20 17:17:49 -0700299 if (erase_data) {
300 mPastBuckets.clear();
301 mSkippedBuckets.clear();
302 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700303}
304
Chenjie Yuf275f612018-11-30 23:29:06 -0800305void ValueMetricProducer::resetBase() {
306 for (auto& slice : mCurrentSlicedBucket) {
307 for (auto& interval : slice.second) {
308 interval.hasBase = false;
309 }
310 }
311 mHasGlobalBase = false;
312}
313
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700314void ValueMetricProducer::onConditionChangedLocked(const bool condition,
Yangster-macb142cc82018-03-30 15:22:08 -0700315 const int64_t eventTimeNs) {
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700316 if (eventTimeNs < mCurrentBucketStartTimeNs) {
317 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800318 (long long)mCurrentBucketStartTimeNs);
Yao Chen2794da22017-12-13 16:01:55 -0800319 return;
320 }
321
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700322 flushIfNeededLocked(eventTimeNs);
Chenjie Yua7259ab2017-12-10 08:31:05 -0800323
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700324 // Pull on condition changes.
325 if (mIsPulled && (mCondition != condition)) {
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800326 pullAndMatchEventsLocked(eventTimeNs);
Chenjie Yue1361ed2018-07-23 17:33:09 -0700327 }
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700328
Chenjie Yuf275f612018-11-30 23:29:06 -0800329 // when condition change from true to false, clear diff base but don't
330 // reset other counters as we may accumulate more value in the bucket.
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700331 if (mUseDiff && mCondition && !condition) {
Chenjie Yuf275f612018-11-30 23:29:06 -0800332 resetBase();
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700333 }
334
335 mCondition = condition;
Chenjie Yue1361ed2018-07-23 17:33:09 -0700336}
337
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800338void ValueMetricProducer::pullAndMatchEventsLocked(const int64_t timestampNs) {
Chenjie Yue1361ed2018-07-23 17:33:09 -0700339 vector<std::shared_ptr<LogEvent>> allData;
340 if (mPullerManager->Pull(mPullTagId, timestampNs, &allData)) {
Chenjie Yue1361ed2018-07-23 17:33:09 -0700341 for (const auto& data : allData) {
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800342 if (mEventMatcherWizard->matchLogEvent(
343 *data, mWhatMatcherIndex) == MatchingState::kMatched) {
344 onMatchedLogEventLocked(mWhatMatcherIndex, *data);
345 }
Chenjie Yue1361ed2018-07-23 17:33:09 -0700346 }
Chenjie Yuf275f612018-11-30 23:29:06 -0800347 mHasGlobalBase = true;
348 } else {
349 // for pulled data, every pull is needed. So we reset the base if any
350 // pull fails.
351 resetBase();
Chenjie Yub3dda412017-10-24 13:41:59 -0700352 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700353}
354
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700355int64_t ValueMetricProducer::calcPreviousBucketEndTime(const int64_t currentTimeNs) {
356 return mTimeBaseNs + ((currentTimeNs - mTimeBaseNs) / mBucketSizeNs) * mBucketSizeNs;
357}
358
Chenjie Yub3dda412017-10-24 13:41:59 -0700359void ValueMetricProducer::onDataPulled(const std::vector<std::shared_ptr<LogEvent>>& allData) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800360 std::lock_guard<std::mutex> lock(mMutex);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700361 if (mCondition) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700362 if (allData.size() == 0) {
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800363 VLOG("Data pulled is empty");
Chenjie Yub3dda412017-10-24 13:41:59 -0700364 return;
365 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800366 // For scheduled pulled data, the effective event time is snap to the nearest
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700367 // bucket end. In the case of waking up from a deep sleep state, we will
368 // attribute to the previous bucket end. If the sleep was long but not very long, we
369 // will be in the immediate next bucket. Previous bucket may get a larger number as
370 // we pull at a later time than real bucket end.
371 // If the sleep was very long, we skip more than one bucket before sleep. In this case,
372 // if the diff base will be cleared and this new data will serve as new diff base.
Yangster-macb142cc82018-03-30 15:22:08 -0700373 int64_t realEventTime = allData.at(0)->GetElapsedTimestampNs();
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700374 int64_t bucketEndTime = calcPreviousBucketEndTime(realEventTime) - 1;
375 if (bucketEndTime < mCurrentBucketStartTimeNs) {
376 VLOG("Skip bucket end pull due to late arrival: %lld vs %lld", (long long)bucketEndTime,
377 (long long)mCurrentBucketStartTimeNs);
378 return;
Chenjie Yub3dda412017-10-24 13:41:59 -0700379 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800380 for (const auto& data : allData) {
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800381 if (mEventMatcherWizard->matchLogEvent(*data, mWhatMatcherIndex) ==
382 MatchingState::kMatched) {
383 data->setElapsedTimestampNs(bucketEndTime);
384 onMatchedLogEventLocked(mWhatMatcherIndex, *data);
385 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800386 }
Chenjie Yuf275f612018-11-30 23:29:06 -0800387 mHasGlobalBase = true;
Chenjie Yu054ce9c2018-11-12 15:27:29 -0800388 } else {
389 VLOG("No need to commit data on condition false.");
Chenjie Yub3dda412017-10-24 13:41:59 -0700390 }
391}
392
Yangster-maca78d0082018-03-12 12:02:56 -0700393void ValueMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
394 if (mCurrentSlicedBucket.size() == 0) {
395 return;
396 }
397
398 fprintf(out, "ValueMetric %lld dimension size %lu\n", (long long)mMetricId,
399 (unsigned long)mCurrentSlicedBucket.size());
400 if (verbose) {
401 for (const auto& it : mCurrentSlicedBucket) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700402 for (const auto& interval : it.second) {
Chenjie Yua0f02242018-07-06 16:14:34 -0700403 fprintf(out, "\t(what)%s\t(condition)%s (value)%s\n",
404 it.first.getDimensionKeyInWhat().toString().c_str(),
405 it.first.getDimensionKeyInCondition().toString().c_str(),
Chenjie Yu32717c32018-10-20 23:54:48 -0700406 interval.value.toString().c_str());
407 }
Yangster-maca78d0082018-03-12 12:02:56 -0700408 }
409 }
410}
411
Yangster-mac93694462018-01-22 20:49:31 -0800412bool ValueMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800413 // ===========GuardRail==============
414 // 1. Report the tuple count if the tuple count > soft limit
415 if (mCurrentSlicedBucket.find(newKey) != mCurrentSlicedBucket.end()) {
416 return false;
417 }
Chenjie Yuc5875052018-03-09 10:13:11 -0800418 if (mCurrentSlicedBucket.size() > mDimensionSoftLimit - 1) {
Yao Chenb3561512017-11-21 18:07:17 -0800419 size_t newTupleCount = mCurrentSlicedBucket.size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800420 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800421 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
Chenjie Yuc5875052018-03-09 10:13:11 -0800422 if (newTupleCount > mDimensionHardLimit) {
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700423 ALOGE("ValueMetric %lld dropping data for dimension key %s", (long long)mMetricId,
424 newKey.toString().c_str());
Yao Chenb3561512017-11-21 18:07:17 -0800425 return true;
426 }
427 }
428
429 return false;
430}
431
Chenjie Yu32717c32018-10-20 23:54:48 -0700432bool getDoubleOrLong(const LogEvent& event, const Matcher& matcher, Value& ret) {
433 for (const FieldValue& value : event.getValues()) {
434 if (value.mField.matches(matcher)) {
435 switch (value.mValue.type) {
436 case INT:
437 ret.setLong(value.mValue.int_value);
438 break;
439 case LONG:
440 ret.setLong(value.mValue.long_value);
441 break;
442 case FLOAT:
443 ret.setDouble(value.mValue.float_value);
444 break;
445 case DOUBLE:
446 ret.setDouble(value.mValue.double_value);
447 break;
448 default:
449 break;
450 }
451 return true;
452 }
Chenjie Yua0f02242018-07-06 16:14:34 -0700453 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700454 return false;
Chenjie Yua0f02242018-07-06 16:14:34 -0700455}
456
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700457void ValueMetricProducer::onMatchedLogEventInternalLocked(const size_t matcherIndex,
458 const MetricDimensionKey& eventKey,
459 const ConditionKey& conditionKey,
460 bool condition, const LogEvent& event) {
Yangster-macb142cc82018-03-30 15:22:08 -0700461 int64_t eventTimeNs = event.GetElapsedTimestampNs();
Yao Chen6a8c7992017-11-29 20:02:07 +0000462 if (eventTimeNs < mCurrentBucketStartTimeNs) {
463 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
464 (long long)mCurrentBucketStartTimeNs);
465 return;
466 }
467
Chenjie Yua7259ab2017-12-10 08:31:05 -0800468 flushIfNeededLocked(eventTimeNs);
469
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700470 // For pulled data, we already check condition when we decide to pull or
471 // in onDataPulled. So take all of them.
472 // For pushed data, just check condition.
473 if (!(mIsPulled || condition)) {
474 VLOG("ValueMetric skip event because condition is false");
475 return;
476 }
477
Yangsterf2bee6f2017-11-29 12:01:05 -0800478 if (hitGuardRailLocked(eventKey)) {
Yangster8de69392017-11-27 13:48:29 -0800479 return;
480 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700481 vector<Interval>& multiIntervals = mCurrentSlicedBucket[eventKey];
482 if (multiIntervals.size() < mFieldMatchers.size()) {
483 VLOG("Resizing number of intervals to %d", (int)mFieldMatchers.size());
484 multiIntervals.resize(mFieldMatchers.size());
Yangster-maca7fb12d2018-01-03 17:17:20 -0800485 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000486
Chenjie Yu32717c32018-10-20 23:54:48 -0700487 for (int i = 0; i < (int)mFieldMatchers.size(); i++) {
488 const Matcher& matcher = mFieldMatchers[i];
489 Interval& interval = multiIntervals[i];
490 interval.valueIndex = i;
491 Value value;
492 if (!getDoubleOrLong(event, matcher, value)) {
493 VLOG("Failed to get value %d from event %s", i, event.ToString().c_str());
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700494 return;
495 }
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700496
Chenjie Yu32717c32018-10-20 23:54:48 -0700497 if (mUseDiff) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700498 if (!interval.hasBase) {
Chenjie Yuf275f612018-11-30 23:29:06 -0800499 if (mHasGlobalBase && mUseZeroDefaultBase) {
500 // The bucket has global base. This key does not.
501 // Optionally use zero as base.
502 interval.base = (value.type == LONG ? ZERO_LONG : ZERO_DOUBLE);
503 interval.hasBase = true;
504 } else {
505 // no base. just update base and return.
506 interval.base = value;
507 interval.hasBase = true;
508 return;
509 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700510 }
511 Value diff;
512 switch (mValueDirection) {
513 case ValueMetric::INCREASING:
514 if (value >= interval.base) {
515 diff = value - interval.base;
516 } else if (mUseAbsoluteValueOnReset) {
517 diff = value;
518 } else {
519 VLOG("Unexpected decreasing value");
520 StatsdStats::getInstance().notePullDataError(mPullTagId);
521 interval.base = value;
522 return;
523 }
524 break;
525 case ValueMetric::DECREASING:
526 if (interval.base >= value) {
527 diff = interval.base - value;
528 } else if (mUseAbsoluteValueOnReset) {
529 diff = value;
530 } else {
531 VLOG("Unexpected increasing value");
532 StatsdStats::getInstance().notePullDataError(mPullTagId);
533 interval.base = value;
534 return;
535 }
536 break;
537 case ValueMetric::ANY:
538 diff = value - interval.base;
539 break;
540 default:
541 break;
542 }
543 interval.base = value;
544 value = diff;
Yao Chen6a8c7992017-11-29 20:02:07 +0000545 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700546
547 if (interval.hasValue) {
548 switch (mAggregationType) {
549 case ValueMetric::SUM:
550 // for AVG, we add up and take average when flushing the bucket
551 case ValueMetric::AVG:
552 interval.value += value;
553 break;
554 case ValueMetric::MIN:
555 interval.value = std::min(value, interval.value);
556 break;
557 case ValueMetric::MAX:
558 interval.value = std::max(value, interval.value);
559 break;
560 default:
561 break;
562 }
563 } else {
564 interval.value = value;
565 interval.hasValue = true;
566 }
567 interval.sampleSize += 1;
Yangster8de69392017-11-27 13:48:29 -0800568 }
Bookatzde1b55622017-12-14 18:38:27 -0800569
Chenjie Yua0f02242018-07-06 16:14:34 -0700570 // TODO: propgate proper values down stream when anomaly support doubles
Chenjie Yu32717c32018-10-20 23:54:48 -0700571 long wholeBucketVal = multiIntervals[0].value.long_value;
David Chen27785a82018-01-19 17:06:45 -0800572 auto prev = mCurrentFullBucket.find(eventKey);
573 if (prev != mCurrentFullBucket.end()) {
574 wholeBucketVal += prev->second;
575 }
Bookatzde1b55622017-12-14 18:38:27 -0800576 for (auto& tracker : mAnomalyTrackers) {
David Chen27785a82018-01-19 17:06:45 -0800577 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, eventKey, wholeBucketVal);
Bookatzde1b55622017-12-14 18:38:27 -0800578 }
Yangster8de69392017-11-27 13:48:29 -0800579}
580
Yangster-macb142cc82018-03-30 15:22:08 -0700581void ValueMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
582 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800583
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700584 if (eventTimeNs < currentBucketEndTimeNs) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700585 VLOG("eventTime is %lld, less than next bucket start time %lld", (long long)eventTimeNs,
David Chen27785a82018-01-19 17:06:45 -0800586 (long long)(currentBucketEndTimeNs));
Chenjie Yub3dda412017-10-24 13:41:59 -0700587 return;
588 }
David Chen27785a82018-01-19 17:06:45 -0800589
590 flushCurrentBucketLocked(eventTimeNs);
591
592 int64_t numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
593 mCurrentBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
594 mCurrentBucketNum += numBucketsForward;
595
596 if (numBucketsForward > 1) {
597 VLOG("Skipping forward %lld buckets", (long long)numBucketsForward);
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700598 // take base again in future good bucket.
Chenjie Yuf275f612018-11-30 23:29:06 -0800599 resetBase();
David Chen27785a82018-01-19 17:06:45 -0800600 }
601 VLOG("metric %lld: new bucket start time: %lld", (long long)mMetricId,
602 (long long)mCurrentBucketStartTimeNs);
603}
604
Yangster-macb142cc82018-03-30 15:22:08 -0700605void ValueMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700606 VLOG("finalizing bucket for %ld, dumping %d slices", (long)mCurrentBucketStartTimeNs,
607 (int)mCurrentSlicedBucket.size());
Yangster-macb142cc82018-03-30 15:22:08 -0700608 int64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800609
Chenjie Yu32717c32018-10-20 23:54:48 -0700610 int64_t bucketEndTime = eventTimeNs < fullBucketEndTimeNs ? eventTimeNs : fullBucketEndTimeNs;
Chenjie Yub3dda412017-10-24 13:41:59 -0700611
Chenjie Yu32717c32018-10-20 23:54:48 -0700612 if (bucketEndTime - mCurrentBucketStartTimeNs >= mMinBucketSizeNs) {
David Chen81245fd2018-04-12 14:33:37 -0700613 // The current bucket is large enough to keep.
David Chen81245fd2018-04-12 14:33:37 -0700614 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700615 ValueBucket bucket;
616 bucket.mBucketStartNs = mCurrentBucketStartTimeNs;
617 bucket.mBucketEndNs = bucketEndTime;
618 for (const auto& interval : slice.second) {
619 if (interval.hasValue) {
620 // skip the output if the diff is zero
621 if (mSkipZeroDiffOutput && mUseDiff && interval.value.isZero()) {
622 continue;
623 }
624 bucket.valueIndex.push_back(interval.valueIndex);
625 if (mAggregationType != ValueMetric::AVG) {
626 bucket.values.push_back(interval.value);
627 } else {
628 double sum = interval.value.type == LONG ? (double)interval.value.long_value
629 : interval.value.double_value;
630 bucket.values.push_back(Value((double)sum / interval.sampleSize));
631 }
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700632 }
Chenjie Yu32717c32018-10-20 23:54:48 -0700633 }
634 // it will auto create new vector of ValuebucketInfo if the key is not found.
635 if (bucket.valueIndex.size() > 0) {
David Chen81245fd2018-04-12 14:33:37 -0700636 auto& bucketList = mPastBuckets[slice.first];
Chenjie Yu32717c32018-10-20 23:54:48 -0700637 bucketList.push_back(bucket);
David Chen81245fd2018-04-12 14:33:37 -0700638 }
Chenjie Yuae63b0a2018-04-10 14:59:31 -0700639 }
David Chen81245fd2018-04-12 14:33:37 -0700640 } else {
Chenjie Yu32717c32018-10-20 23:54:48 -0700641 mSkippedBuckets.emplace_back(mCurrentBucketStartTimeNs, bucketEndTime);
Chenjie Yub3dda412017-10-24 13:41:59 -0700642 }
643
David Chen27785a82018-01-19 17:06:45 -0800644 if (eventTimeNs > fullBucketEndTimeNs) { // If full bucket, send to anomaly tracker.
645 // Accumulate partial buckets with current value and then send to anomaly tracker.
646 if (mCurrentFullBucket.size() > 0) {
647 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yua0f02242018-07-06 16:14:34 -0700648 // TODO: fix this when anomaly can accept double values
Chenjie Yu32717c32018-10-20 23:54:48 -0700649 mCurrentFullBucket[slice.first] += slice.second[0].value.long_value;
David Chen27785a82018-01-19 17:06:45 -0800650 }
651 for (const auto& slice : mCurrentFullBucket) {
652 for (auto& tracker : mAnomalyTrackers) {
653 if (tracker != nullptr) {
654 tracker->addPastBucket(slice.first, slice.second, mCurrentBucketNum);
655 }
656 }
657 }
658 mCurrentFullBucket.clear();
659 } else {
660 // Skip aggregating the partial buckets since there's no previous partial bucket.
661 for (const auto& slice : mCurrentSlicedBucket) {
662 for (auto& tracker : mAnomalyTrackers) {
663 if (tracker != nullptr) {
Chenjie Yua0f02242018-07-06 16:14:34 -0700664 // TODO: fix this when anomaly can accept double values
Chenjie Yu32717c32018-10-20 23:54:48 -0700665 tracker->addPastBucket(slice.first, slice.second[0].value.long_value,
Chenjie Yua0f02242018-07-06 16:14:34 -0700666 mCurrentBucketNum);
David Chen27785a82018-01-19 17:06:45 -0800667 }
668 }
669 }
670 }
671 } else {
672 // Accumulate partial bucket.
673 for (const auto& slice : mCurrentSlicedBucket) {
Chenjie Yua0f02242018-07-06 16:14:34 -0700674 // TODO: fix this when anomaly can accept double values
Chenjie Yu32717c32018-10-20 23:54:48 -0700675 mCurrentFullBucket[slice.first] += slice.second[0].value.long_value;
David Chen27785a82018-01-19 17:06:45 -0800676 }
677 }
678
Chenjie Yub3dda412017-10-24 13:41:59 -0700679 // Reset counters
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700680 for (auto& slice : mCurrentSlicedBucket) {
Chenjie Yu32717c32018-10-20 23:54:48 -0700681 for (auto& interval : slice.second) {
682 interval.hasValue = false;
683 interval.sampleSize = 0;
684 }
Chenjie Yuc715b9e2018-10-19 07:52:12 -0700685 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700686}
687
Yangsterf2bee6f2017-11-29 12:01:05 -0800688size_t ValueMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800689 size_t totalSize = 0;
690 for (const auto& pair : mPastBuckets) {
691 totalSize += pair.second.size() * kBucketSize;
692 }
693 return totalSize;
yro2b0f8862017-11-06 14:27:31 -0800694}
695
Chenjie Yub3dda412017-10-24 13:41:59 -0700696} // namespace statsd
697} // namespace os
Yao Chen93fe3a32017-11-02 13:52:59 -0700698} // namespace android