blob: c505d225d5d3850bee767455261d387153ffc7ee [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
Yao Chen3c0b95c2017-12-16 14:34:20 -080017#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;
30using android::util::FIELD_TYPE_FLOAT;
31using 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
yro2b0f8862017-11-06 14:27:31 -080067const int FIELD_ID_VALUE = 3;
Yangster-mac9def8e32018-04-17 13:55:51 -070068const int FIELD_ID_BUCKET_NUM = 4;
69const int FIELD_ID_START_BUCKET_ELAPSED_MILLIS = 5;
70const int FIELD_ID_END_BUCKET_ELAPSED_MILLIS = 6;
yro2b0f8862017-11-06 14:27:31 -080071
Chenjie Yub3dda412017-10-24 13:41:59 -070072// ValueMetric has a minimum bucket size of 10min so that we don't pull too frequently
Yao Chenb3561512017-11-21 18:07:17 -080073ValueMetricProducer::ValueMetricProducer(const ConfigKey& key, const ValueMetric& metric,
74 const int conditionIndex,
Yao Chen93fe3a32017-11-02 13:52:59 -070075 const sp<ConditionWizard>& wizard, const int pullTagId,
Yangster-mac15f6bbc2018-04-08 11:52:26 -070076 const int64_t timeBaseNs, const int64_t startTimestampNs,
Chenjie Yu6736c892017-11-09 10:50:09 -080077 shared_ptr<StatsPullerManager> statsPullerManager)
Yangster-mac15f6bbc2018-04-08 11:52:26 -070078 : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, wizard),
Yao Chenf09569f2017-12-13 17:00:51 -080079 mValueField(metric.value_field()),
Chenjie Yu6736c892017-11-09 10:50:09 -080080 mStatsPullerManager(statsPullerManager),
Chenjie Yuc5875052018-03-09 10:13:11 -080081 mPullTagId(pullTagId),
David Chen81245fd2018-04-12 14:33:37 -070082 mMinBucketSizeNs(metric.min_bucket_size_nanos()),
Chenjie Yuc5875052018-03-09 10:13:11 -080083 mDimensionSoftLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
84 StatsdStats::kAtomDimensionKeySizeLimitMap.end()
85 ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).first
86 : StatsdStats::kDimensionKeySizeSoftLimit),
87 mDimensionHardLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
88 StatsdStats::kAtomDimensionKeySizeLimitMap.end()
89 ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).second
90 : StatsdStats::kDimensionKeySizeHardLimit) {
Yao Chen93fe3a32017-11-02 13:52:59 -070091 // TODO: valuemetric for pushed events may need unlimited bucket length
Yangster-macb8144812018-01-04 10:56:23 -080092 int64_t bucketSizeMills = 0;
93 if (metric.has_bucket()) {
yro59cc24d2018-02-13 20:17:32 -080094 bucketSizeMills = TimeUnitToBucketSizeInMillisGuardrailed(key.GetUid(), metric.bucket());
Chenjie Yu6736c892017-11-09 10:50:09 -080095 } else {
Yangster-macb8144812018-01-04 10:56:23 -080096 bucketSizeMills = TimeUnitToBucketSizeInMillis(ONE_HOUR);
Chenjie Yu6736c892017-11-09 10:50:09 -080097 }
Chenjie Yub3dda412017-10-24 13:41:59 -070098
Yangster-macb8144812018-01-04 10:56:23 -080099 mBucketSizeNs = bucketSizeMills * 1000000;
Yao Chen8a8d16c2018-02-08 14:50:40 -0800100 if (metric.has_dimensions_in_what()) {
101 translateFieldMatcher(metric.dimensions_in_what(), &mDimensionsInWhat);
Yangster13fb7e42018-03-07 17:30:49 -0800102 mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
Yao Chen8a8d16c2018-02-08 14:50:40 -0800103 }
104
105 if (metric.has_dimensions_in_condition()) {
106 translateFieldMatcher(metric.dimensions_in_condition(), &mDimensionsInCondition);
107 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700108
Yao Chen93fe3a32017-11-02 13:52:59 -0700109 if (metric.links().size() > 0) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800110 for (const auto& link : metric.links()) {
111 Metric2Condition mc;
112 mc.conditionId = link.condition();
113 translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
114 translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
115 mMetric2ConditionLinks.push_back(mc);
116 }
Yao Chen93fe3a32017-11-02 13:52:59 -0700117 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800118
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700119 if (mValueField.child_size() > 0) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800120 mField = mValueField.child(0).field();
121 }
122 mConditionSliced = (metric.links().size() > 0) || (mDimensionsInCondition.size() > 0);
Yangster-mac9def8e32018-04-17 13:55:51 -0700123 mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what()) ||
124 HasPositionALL(metric.dimensions_in_condition());
Chenjie Yub3dda412017-10-24 13:41:59 -0700125
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700126 // Kicks off the puller immediately.
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700127 flushIfNeededLocked(startTimestampNs);
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700128 if (mPullTagId != -1) {
129 mStatsPullerManager->RegisterReceiver(
130 mPullTagId, this, mCurrentBucketStartTimeNs + mBucketSizeNs, mBucketSizeNs);
Yao Chen93fe3a32017-11-02 13:52:59 -0700131 }
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700132
Yangster-mac94e197c2018-01-02 16:03:03 -0800133 VLOG("value metric %lld created. bucket size %lld start_time: %lld",
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700134 (long long)metric.id(), (long long)mBucketSizeNs, (long long)mTimeBaseNs);
Chenjie Yub3dda412017-10-24 13:41:59 -0700135}
136
Chenjie Yu6736c892017-11-09 10:50:09 -0800137// for testing
Yao Chenb3561512017-11-21 18:07:17 -0800138ValueMetricProducer::ValueMetricProducer(const ConfigKey& key, const ValueMetric& metric,
139 const int conditionIndex,
Chenjie Yu6736c892017-11-09 10:50:09 -0800140 const sp<ConditionWizard>& wizard, const int pullTagId,
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700141 const int64_t timeBaseNs, const int64_t startTimeNs)
142 : ValueMetricProducer(key, metric, conditionIndex, wizard, pullTagId, timeBaseNs, startTimeNs,
Chenjie Yu6736c892017-11-09 10:50:09 -0800143 make_shared<StatsPullerManager>()) {
144}
145
Chenjie Yub3dda412017-10-24 13:41:59 -0700146ValueMetricProducer::~ValueMetricProducer() {
Yao Chen93fe3a32017-11-02 13:52:59 -0700147 VLOG("~ValueMetricProducer() called");
Chenjie Yu6736c892017-11-09 10:50:09 -0800148 if (mPullTagId != -1) {
149 mStatsPullerManager->UnRegisterReceiver(mPullTagId, this);
150 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700151}
152
Yao Chen427d3722018-03-22 15:21:52 -0700153void ValueMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
Yangster-macb142cc82018-03-30 15:22:08 -0700154 const int64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800155 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Chenjie Yub3dda412017-10-24 13:41:59 -0700156}
157
Yangster-macb142cc82018-03-30 15:22:08 -0700158void ValueMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
Yao Chen06dba5d2018-01-26 13:38:16 -0800159 flushIfNeededLocked(dropTimeNs);
160 mPastBuckets.clear();
161}
162
Yangster-macb142cc82018-03-30 15:22:08 -0700163void ValueMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700164 const bool include_current_partial_bucket,
Yangster-mac9def8e32018-04-17 13:55:51 -0700165 std::set<string> *str_set,
Yao Chen288c6002017-12-12 13:43:18 -0800166 ProtoOutputStream* protoOutput) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800167 VLOG("metric %lld dump report now...", (long long)mMetricId);
Yangster-mace68f3a52018-04-04 00:01:43 -0700168 if (include_current_partial_bucket) {
169 flushLocked(dumpTimeNs);
170 } else {
171 flushIfNeededLocked(dumpTimeNs);
172 }
David Chen81245fd2018-04-12 14:33:37 -0700173 if (mPastBuckets.empty() && mSkippedBuckets.empty()) {
Yangster-mac635b4b32018-01-23 20:17:35 -0800174 return;
175 }
Yangster-mac94e197c2018-01-02 16:03:03 -0800176 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Yangster-mac9def8e32018-04-17 13:55:51 -0700177 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_TIME_BASE, (long long)mTimeBaseNs);
178 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_SIZE, (long long)mBucketSizeNs);
179 // Fills the dimension path if not slicing by ALL.
180 if (!mSliceByPositionALL) {
181 if (!mDimensionsInWhat.empty()) {
182 uint64_t dimenPathToken = protoOutput->start(
183 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_WHAT);
184 writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
185 protoOutput->end(dimenPathToken);
186 }
187 if (!mDimensionsInCondition.empty()) {
188 uint64_t dimenPathToken = protoOutput->start(
189 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_CONDITION);
190 writeDimensionPathToProto(mDimensionsInCondition, protoOutput);
191 protoOutput->end(dimenPathToken);
192 }
193 }
194
Yi Jin5ee07872018-03-05 18:18:27 -0800195 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_VALUE_METRICS);
Yao Chen6a8c7992017-11-29 20:02:07 +0000196
David Chen81245fd2018-04-12 14:33:37 -0700197 for (const auto& pair : mSkippedBuckets) {
198 uint64_t wrapperToken =
199 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_SKIPPED);
Yangster-mac9def8e32018-04-17 13:55:51 -0700200 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_START_MILLIS,
201 (long long)(NanoToMillis(pair.first)));
202 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_END_MILLIS,
203 (long long)(NanoToMillis(pair.second)));
David Chen81245fd2018-04-12 14:33:37 -0700204 protoOutput->end(wrapperToken);
205 }
206 mSkippedBuckets.clear();
207
Yao Chen93fe3a32017-11-02 13:52:59 -0700208 for (const auto& pair : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800209 const MetricDimensionKey& dimensionKey = pair.first;
Yangster13fb7e42018-03-07 17:30:49 -0800210 VLOG(" dimension key %s", dimensionKey.toString().c_str());
Yi Jin5ee07872018-03-05 18:18:27 -0800211 uint64_t wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800212 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
Chenjie Yub3dda412017-10-24 13:41:59 -0700213
Yangster-mac20877162017-12-22 17:19:39 -0800214 // First fill dimension.
Yangster-mac9def8e32018-04-17 13:55:51 -0700215 if (mSliceByPositionALL) {
216 uint64_t dimensionToken = protoOutput->start(
217 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
218 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), str_set, protoOutput);
219 protoOutput->end(dimensionToken);
220 if (dimensionKey.hasDimensionKeyInCondition()) {
221 uint64_t dimensionInConditionToken = protoOutput->start(
222 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
223 writeDimensionToProto(dimensionKey.getDimensionKeyInCondition(),
224 str_set, protoOutput);
225 protoOutput->end(dimensionInConditionToken);
226 }
227 } else {
228 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInWhat(),
229 FIELD_ID_DIMENSION_LEAF_IN_WHAT, str_set, protoOutput);
230 if (dimensionKey.hasDimensionKeyInCondition()) {
231 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInCondition(),
232 FIELD_ID_DIMENSION_LEAF_IN_CONDITION,
233 str_set, protoOutput);
234 }
Yangster-mac93694462018-01-22 20:49:31 -0800235 }
yro2b0f8862017-11-06 14:27:31 -0800236
237 // Then fill bucket_info (ValueBucketInfo).
238 for (const auto& bucket : pair.second) {
Yi Jin5ee07872018-03-05 18:18:27 -0800239 uint64_t bucketInfoToken = protoOutput->start(
Yao Chen288c6002017-12-12 13:43:18 -0800240 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
Yangster-mac9def8e32018-04-17 13:55:51 -0700241
242 if (bucket.mBucketEndNs - bucket.mBucketStartNs != mBucketSizeNs) {
243 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_MILLIS,
244 (long long)NanoToMillis(bucket.mBucketStartNs));
245 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_MILLIS,
246 (long long)NanoToMillis(bucket.mBucketEndNs));
247 } else {
248 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_NUM,
249 (long long)(getBucketNumFromEndTimeNs(bucket.mBucketEndNs)));
250 }
251
Yao Chen288c6002017-12-12 13:43:18 -0800252 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_VALUE, (long long)bucket.mValue);
253 protoOutput->end(bucketInfoToken);
yro2b0f8862017-11-06 14:27:31 -0800254 VLOG("\t bucket [%lld - %lld] count: %lld", (long long)bucket.mBucketStartNs,
255 (long long)bucket.mBucketEndNs, (long long)bucket.mValue);
256 }
Yao Chen288c6002017-12-12 13:43:18 -0800257 protoOutput->end(wrapperToken);
Chenjie Yub3dda412017-10-24 13:41:59 -0700258 }
Yao Chen288c6002017-12-12 13:43:18 -0800259 protoOutput->end(protoToken);
yro2b0f8862017-11-06 14:27:31 -0800260
Yangster-mac94e197c2018-01-02 16:03:03 -0800261 VLOG("metric %lld dump report now...", (long long)mMetricId);
Yao Chen6a8c7992017-11-29 20:02:07 +0000262 mPastBuckets.clear();
Chenjie Yub3dda412017-10-24 13:41:59 -0700263}
264
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700265void ValueMetricProducer::onConditionChangedLocked(const bool condition,
Yangster-macb142cc82018-03-30 15:22:08 -0700266 const int64_t eventTimeNs) {
Yao Chen6a8c7992017-11-29 20:02:07 +0000267 mCondition = condition;
Chenjie Yub3dda412017-10-24 13:41:59 -0700268
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700269 if (eventTimeNs < mCurrentBucketStartTimeNs) {
270 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800271 (long long)mCurrentBucketStartTimeNs);
Yao Chen2794da22017-12-13 16:01:55 -0800272 return;
273 }
274
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700275 flushIfNeededLocked(eventTimeNs);
Chenjie Yua7259ab2017-12-10 08:31:05 -0800276
Yao Chen6a8c7992017-11-29 20:02:07 +0000277 if (mPullTagId != -1) {
Yao Chen6a8c7992017-11-29 20:02:07 +0000278 vector<shared_ptr<LogEvent>> allData;
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700279 if (mStatsPullerManager->Pull(mPullTagId, eventTimeNs, &allData)) {
Yao Chen6a8c7992017-11-29 20:02:07 +0000280 if (allData.size() == 0) {
281 return;
282 }
283 for (const auto& data : allData) {
Chenjie Yua7259ab2017-12-10 08:31:05 -0800284 onMatchedLogEventLocked(0, *data);
Yao Chen6a8c7992017-11-29 20:02:07 +0000285 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000286 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700287 return;
Chenjie Yub3dda412017-10-24 13:41:59 -0700288 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700289}
290
291void ValueMetricProducer::onDataPulled(const std::vector<std::shared_ptr<LogEvent>>& allData) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800292 std::lock_guard<std::mutex> lock(mMutex);
293
Yao Chenf09569f2017-12-13 17:00:51 -0800294 if (mCondition == true || mConditionTrackerIndex < 0) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700295 if (allData.size() == 0) {
296 return;
297 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800298 // For scheduled pulled data, the effective event time is snap to the nearest
299 // bucket boundary to make bucket finalize.
Yangster-macb142cc82018-03-30 15:22:08 -0700300 int64_t realEventTime = allData.at(0)->GetElapsedTimestampNs();
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700301 int64_t eventTime = mTimeBaseNs +
302 ((realEventTime - mTimeBaseNs) / mBucketSizeNs) * mBucketSizeNs;
Chenjie Yua7259ab2017-12-10 08:31:05 -0800303
304 mCondition = false;
Chenjie Yub3dda412017-10-24 13:41:59 -0700305 for (const auto& data : allData) {
Yangster-mac330af582018-02-08 15:24:38 -0800306 data->setElapsedTimestampNs(eventTime - 1);
Chenjie Yua7259ab2017-12-10 08:31:05 -0800307 onMatchedLogEventLocked(0, *data);
Chenjie Yub3dda412017-10-24 13:41:59 -0700308 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800309
310 mCondition = true;
311 for (const auto& data : allData) {
Yangster-mac330af582018-02-08 15:24:38 -0800312 data->setElapsedTimestampNs(eventTime);
Chenjie Yua7259ab2017-12-10 08:31:05 -0800313 onMatchedLogEventLocked(0, *data);
314 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700315 }
316}
317
Yangster-maca78d0082018-03-12 12:02:56 -0700318void ValueMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
319 if (mCurrentSlicedBucket.size() == 0) {
320 return;
321 }
322
323 fprintf(out, "ValueMetric %lld dimension size %lu\n", (long long)mMetricId,
324 (unsigned long)mCurrentSlicedBucket.size());
325 if (verbose) {
326 for (const auto& it : mCurrentSlicedBucket) {
327 fprintf(out, "\t(what)%s\t(condition)%s (value)%lld\n",
328 it.first.getDimensionKeyInWhat().toString().c_str(),
329 it.first.getDimensionKeyInCondition().toString().c_str(),
330 (unsigned long long)it.second.sum);
331 }
332 }
333}
334
Yangster-mac93694462018-01-22 20:49:31 -0800335bool ValueMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800336 // ===========GuardRail==============
337 // 1. Report the tuple count if the tuple count > soft limit
338 if (mCurrentSlicedBucket.find(newKey) != mCurrentSlicedBucket.end()) {
339 return false;
340 }
Chenjie Yuc5875052018-03-09 10:13:11 -0800341 if (mCurrentSlicedBucket.size() > mDimensionSoftLimit - 1) {
Yao Chenb3561512017-11-21 18:07:17 -0800342 size_t newTupleCount = mCurrentSlicedBucket.size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800343 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800344 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
Chenjie Yuc5875052018-03-09 10:13:11 -0800345 if (newTupleCount > mDimensionHardLimit) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800346 ALOGE("ValueMetric %lld dropping data for dimension key %s",
Yangster13fb7e42018-03-07 17:30:49 -0800347 (long long)mMetricId, newKey.toString().c_str());
Yao Chenb3561512017-11-21 18:07:17 -0800348 return true;
349 }
350 }
351
352 return false;
353}
354
Yangsterf2bee6f2017-11-29 12:01:05 -0800355void ValueMetricProducer::onMatchedLogEventInternalLocked(
Yangster-mac93694462018-01-22 20:49:31 -0800356 const size_t matcherIndex, const MetricDimensionKey& eventKey,
Yangster-mac20877162017-12-22 17:19:39 -0800357 const ConditionKey& conditionKey, bool condition,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800358 const LogEvent& event) {
Yangster-macb142cc82018-03-30 15:22:08 -0700359 int64_t eventTimeNs = event.GetElapsedTimestampNs();
Yao Chen6a8c7992017-11-29 20:02:07 +0000360 if (eventTimeNs < mCurrentBucketStartTimeNs) {
361 VLOG("Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
362 (long long)mCurrentBucketStartTimeNs);
363 return;
364 }
365
Chenjie Yua7259ab2017-12-10 08:31:05 -0800366 flushIfNeededLocked(eventTimeNs);
367
Yangsterf2bee6f2017-11-29 12:01:05 -0800368 if (hitGuardRailLocked(eventKey)) {
Yangster8de69392017-11-27 13:48:29 -0800369 return;
370 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000371 Interval& interval = mCurrentSlicedBucket[eventKey];
372
Yao Chen8a8d16c2018-02-08 14:50:40 -0800373 int error = 0;
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700374 const int64_t value = event.GetLong(mField, &error);
Yao Chen8a8d16c2018-02-08 14:50:40 -0800375 if (error < 0) {
Yangster-maca7fb12d2018-01-03 17:17:20 -0800376 return;
377 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000378
Chenjie Yua7259ab2017-12-10 08:31:05 -0800379 if (mPullTagId != -1) { // for pulled events
380 if (mCondition == true) {
Chenjie Yu6d370f42018-03-25 14:57:30 -0700381 if (!interval.startUpdated) {
382 interval.start = value;
383 interval.startUpdated = true;
384 } else {
385 // skip it if there is already value recorded for the start
386 VLOG("Already recorded value for this dimension %s", eventKey.toString().c_str());
387 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000388 } else {
Chenjie Yu0ed268b2018-01-10 09:37:10 -0800389 // Generally we expect value to be monotonically increasing.
390 // If not, there was a reset event. We take the absolute value as
391 // diff in this case.
Chenjie Yua7259ab2017-12-10 08:31:05 -0800392 if (interval.startUpdated) {
Chenjie Yu0ed268b2018-01-10 09:37:10 -0800393 if (value > interval.start) {
394 interval.sum += (value - interval.start);
395 } else {
396 interval.sum += value;
397 }
Chenjie Yuae63b0a2018-04-10 14:59:31 -0700398 interval.hasValue = true;
Chenjie Yua7259ab2017-12-10 08:31:05 -0800399 interval.startUpdated = false;
Yao Chen6a8c7992017-11-29 20:02:07 +0000400 } else {
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700401 VLOG("No start for matching end %lld", (long long)value);
Chenjie Yua7259ab2017-12-10 08:31:05 -0800402 interval.tainted += 1;
Yao Chen6a8c7992017-11-29 20:02:07 +0000403 }
404 }
Chenjie Yua7259ab2017-12-10 08:31:05 -0800405 } else { // for pushed events
406 interval.sum += value;
Chenjie Yuae63b0a2018-04-10 14:59:31 -0700407 interval.hasValue = true;
Yangster8de69392017-11-27 13:48:29 -0800408 }
Bookatzde1b55622017-12-14 18:38:27 -0800409
David Chen27785a82018-01-19 17:06:45 -0800410 long wholeBucketVal = interval.sum;
411 auto prev = mCurrentFullBucket.find(eventKey);
412 if (prev != mCurrentFullBucket.end()) {
413 wholeBucketVal += prev->second;
414 }
Bookatzde1b55622017-12-14 18:38:27 -0800415 for (auto& tracker : mAnomalyTrackers) {
David Chen27785a82018-01-19 17:06:45 -0800416 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, eventKey, wholeBucketVal);
Bookatzde1b55622017-12-14 18:38:27 -0800417 }
Yangster8de69392017-11-27 13:48:29 -0800418}
419
Yangster-macb142cc82018-03-30 15:22:08 -0700420void ValueMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
421 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800422
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700423 if (eventTimeNs < currentBucketEndTimeNs) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700424 VLOG("eventTime is %lld, less than next bucket start time %lld", (long long)eventTimeNs,
David Chen27785a82018-01-19 17:06:45 -0800425 (long long)(currentBucketEndTimeNs));
Chenjie Yub3dda412017-10-24 13:41:59 -0700426 return;
427 }
David Chen27785a82018-01-19 17:06:45 -0800428
429 flushCurrentBucketLocked(eventTimeNs);
430
431 int64_t numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
432 mCurrentBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
433 mCurrentBucketNum += numBucketsForward;
434
435 if (numBucketsForward > 1) {
436 VLOG("Skipping forward %lld buckets", (long long)numBucketsForward);
437 }
438 VLOG("metric %lld: new bucket start time: %lld", (long long)mMetricId,
439 (long long)mCurrentBucketStartTimeNs);
440}
441
Yangster-macb142cc82018-03-30 15:22:08 -0700442void ValueMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs) {
Chenjie Yub3dda412017-10-24 13:41:59 -0700443 VLOG("finalizing bucket for %ld, dumping %d slices", (long)mCurrentBucketStartTimeNs,
444 (int)mCurrentSlicedBucket.size());
Yangster-macb142cc82018-03-30 15:22:08 -0700445 int64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800446
yro2b0f8862017-11-06 14:27:31 -0800447 ValueBucket info;
448 info.mBucketStartNs = mCurrentBucketStartTimeNs;
David Chen27785a82018-01-19 17:06:45 -0800449 if (eventTimeNs < fullBucketEndTimeNs) {
450 info.mBucketEndNs = eventTimeNs;
451 } else {
452 info.mBucketEndNs = fullBucketEndTimeNs;
453 }
Chenjie Yub3dda412017-10-24 13:41:59 -0700454
David Chen81245fd2018-04-12 14:33:37 -0700455 if (info.mBucketEndNs - mCurrentBucketStartTimeNs >= mMinBucketSizeNs) {
456 // The current bucket is large enough to keep.
457 int tainted = 0;
458 for (const auto& slice : mCurrentSlicedBucket) {
459 tainted += slice.second.tainted;
460 tainted += slice.second.startUpdated;
461 if (slice.second.hasValue) {
462 info.mValue = slice.second.sum;
463 // it will auto create new vector of ValuebucketInfo if the key is not found.
464 auto& bucketList = mPastBuckets[slice.first];
465 bucketList.push_back(info);
466 }
Chenjie Yuae63b0a2018-04-10 14:59:31 -0700467 }
David Chen81245fd2018-04-12 14:33:37 -0700468 VLOG("%d tainted pairs in the bucket", tainted);
469 } else {
470 mSkippedBuckets.emplace_back(info.mBucketStartNs, info.mBucketEndNs);
Chenjie Yub3dda412017-10-24 13:41:59 -0700471 }
472
David Chen27785a82018-01-19 17:06:45 -0800473 if (eventTimeNs > fullBucketEndTimeNs) { // If full bucket, send to anomaly tracker.
474 // Accumulate partial buckets with current value and then send to anomaly tracker.
475 if (mCurrentFullBucket.size() > 0) {
476 for (const auto& slice : mCurrentSlicedBucket) {
477 mCurrentFullBucket[slice.first] += slice.second.sum;
478 }
479 for (const auto& slice : mCurrentFullBucket) {
480 for (auto& tracker : mAnomalyTrackers) {
481 if (tracker != nullptr) {
482 tracker->addPastBucket(slice.first, slice.second, mCurrentBucketNum);
483 }
484 }
485 }
486 mCurrentFullBucket.clear();
487 } else {
488 // Skip aggregating the partial buckets since there's no previous partial bucket.
489 for (const auto& slice : mCurrentSlicedBucket) {
490 for (auto& tracker : mAnomalyTrackers) {
491 if (tracker != nullptr) {
492 tracker->addPastBucket(slice.first, slice.second.sum, mCurrentBucketNum);
493 }
494 }
495 }
496 }
497 } else {
498 // Accumulate partial bucket.
499 for (const auto& slice : mCurrentSlicedBucket) {
500 mCurrentFullBucket[slice.first] += slice.second.sum;
501 }
502 }
503
Chenjie Yub3dda412017-10-24 13:41:59 -0700504 // Reset counters
Chenjie Yua7259ab2017-12-10 08:31:05 -0800505 mCurrentSlicedBucket.clear();
Chenjie Yub3dda412017-10-24 13:41:59 -0700506}
507
Yangsterf2bee6f2017-11-29 12:01:05 -0800508size_t ValueMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800509 size_t totalSize = 0;
510 for (const auto& pair : mPastBuckets) {
511 totalSize += pair.second.size() * kBucketSize;
512 }
513 return totalSize;
yro2b0f8862017-11-06 14:27:31 -0800514}
515
Chenjie Yub3dda412017-10-24 13:41:59 -0700516} // namespace statsd
517} // namespace os
Yao Chen93fe3a32017-11-02 13:52:59 -0700518} // namespace android