blob: f5a16e96fdf5a0bb0e5b097850ff843f00fd7c1f [file] [log] [blame]
Yangster1d4d6862017-10-31 12:58:51 -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
Yangster1d4d6862017-10-31 12:58:51 -070018#include "Log.h"
19
Chenjie Yuc5875052018-03-09 10:13:11 -080020#include "../guardrail/StatsdStats.h"
Yangster1d4d6862017-10-31 12:58:51 -070021#include "GaugeMetricProducer.h"
Chenjie Yuc5875052018-03-09 10:13:11 -080022#include "../stats_log_util.h"
Yangster1d4d6862017-10-31 12:58:51 -070023
24#include <cutils/log.h>
Yangster1d4d6862017-10-31 12:58:51 -070025
yrob0378b02017-11-09 20:36:25 -080026using android::util::FIELD_COUNT_REPEATED;
yro2b0f8862017-11-06 14:27:31 -080027using android::util::FIELD_TYPE_BOOL;
28using android::util::FIELD_TYPE_FLOAT;
29using android::util::FIELD_TYPE_INT32;
30using android::util::FIELD_TYPE_INT64;
31using android::util::FIELD_TYPE_MESSAGE;
Yangster-macd1815dc2017-11-13 21:43:15 -080032using android::util::FIELD_TYPE_STRING;
yro2b0f8862017-11-06 14:27:31 -080033using android::util::ProtoOutputStream;
Yangster1d4d6862017-10-31 12:58:51 -070034using std::map;
35using std::string;
36using std::unordered_map;
37using std::vector;
Chenjie Yud9dfda72017-12-11 17:41:20 -080038using std::make_shared;
39using std::shared_ptr;
Yangster1d4d6862017-10-31 12:58:51 -070040
41namespace android {
42namespace os {
43namespace statsd {
44
yro2b0f8862017-11-06 14:27:31 -080045// for StatsLogReport
Yangster-mac94e197c2018-01-02 16:03:03 -080046const int FIELD_ID_ID = 1;
yro2b0f8862017-11-06 14:27:31 -080047const int FIELD_ID_GAUGE_METRICS = 8;
Yangster-mac9def8e32018-04-17 13:55:51 -070048const int FIELD_ID_TIME_BASE = 9;
49const int FIELD_ID_BUCKET_SIZE = 10;
50const int FIELD_ID_DIMENSION_PATH_IN_WHAT = 11;
51const int FIELD_ID_DIMENSION_PATH_IN_CONDITION = 12;
yro2b0f8862017-11-06 14:27:31 -080052// for GaugeMetricDataWrapper
53const int FIELD_ID_DATA = 1;
David Chen81245fd2018-04-12 14:33:37 -070054const int FIELD_ID_SKIPPED = 2;
Yangster-mac9def8e32018-04-17 13:55:51 -070055const int FIELD_ID_SKIPPED_START_MILLIS = 3;
56const int FIELD_ID_SKIPPED_END_MILLIS = 4;
yro2b0f8862017-11-06 14:27:31 -080057// for GaugeMetricData
Yangster-mac468ff042018-01-17 12:26:34 -080058const int FIELD_ID_DIMENSION_IN_WHAT = 1;
59const int FIELD_ID_DIMENSION_IN_CONDITION = 2;
60const int FIELD_ID_BUCKET_INFO = 3;
Yangster-mac9def8e32018-04-17 13:55:51 -070061const int FIELD_ID_DIMENSION_LEAF_IN_WHAT = 4;
62const int FIELD_ID_DIMENSION_LEAF_IN_CONDITION = 5;
yro2b0f8862017-11-06 14:27:31 -080063// for GaugeBucketInfo
Chenjie Yud9dfda72017-12-11 17:41:20 -080064const int FIELD_ID_ATOM = 3;
Yangster-mac330af582018-02-08 15:24:38 -080065const int FIELD_ID_ELAPSED_ATOM_TIMESTAMP = 4;
Yangster-mac9def8e32018-04-17 13:55:51 -070066const int FIELD_ID_BUCKET_NUM = 6;
67const int FIELD_ID_START_BUCKET_ELAPSED_MILLIS = 7;
68const int FIELD_ID_END_BUCKET_ELAPSED_MILLIS = 8;
yro2b0f8862017-11-06 14:27:31 -080069
Yao Chenb3561512017-11-21 18:07:17 -080070GaugeMetricProducer::GaugeMetricProducer(const ConfigKey& key, const GaugeMetric& metric,
71 const int conditionIndex,
Yangster-mac32f07af2018-10-13 17:08:11 -070072 const sp<ConditionWizard>& wizard,
73 const int whatMatcherIndex,
74 const sp<EventMatcherWizard>& matcherWizard,
75 const int pullTagId,
Chenjie Yu88588972018-08-03 09:49:22 -070076 const int triggerAtomId, const int atomId,
Yangster-mac15f6bbc2018-04-08 11:52:26 -070077 const int64_t timeBaseNs, const int64_t startTimeNs,
Chenjie Yue2219202018-06-08 10:07:51 -070078 const sp<StatsPullerManager>& pullerManager)
Yangster-mac15f6bbc2018-04-08 11:52:26 -070079 : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, wizard),
Yangster-mac32f07af2018-10-13 17:08:11 -070080 mWhatMatcherIndex(whatMatcherIndex),
81 mEventMatcherWizard(matcherWizard),
Chenjie Yue2219202018-06-08 10:07:51 -070082 mPullerManager(pullerManager),
Chenjie Yuc5875052018-03-09 10:13:11 -080083 mPullTagId(pullTagId),
Chenjie Yu88588972018-08-03 09:49:22 -070084 mTriggerAtomId(triggerAtomId),
85 mAtomId(atomId),
Chenjie Yue1361ed2018-07-23 17:33:09 -070086 mIsPulled(pullTagId != -1),
David Chen81245fd2018-04-12 14:33:37 -070087 mMinBucketSizeNs(metric.min_bucket_size_nanos()),
Chenjie Yuc5875052018-03-09 10:13:11 -080088 mDimensionSoftLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
89 StatsdStats::kAtomDimensionKeySizeLimitMap.end()
90 ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).first
91 : StatsdStats::kDimensionKeySizeSoftLimit),
92 mDimensionHardLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
93 StatsdStats::kAtomDimensionKeySizeLimitMap.end()
94 ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).second
Yangster-mac50b0c9a2018-05-10 17:13:12 -070095 : StatsdStats::kDimensionKeySizeHardLimit),
96 mGaugeAtomsPerDimensionLimit(metric.max_num_gauge_atoms_per_bucket()) {
Yangster-mac34ea1102018-01-29 12:40:55 -080097 mCurrentSlicedBucket = std::make_shared<DimToGaugeAtomsMap>();
Yangster-mac20877162017-12-22 17:19:39 -080098 mCurrentSlicedBucketForAnomaly = std::make_shared<DimToValMap>();
Yangster-macb8144812018-01-04 10:56:23 -080099 int64_t bucketSizeMills = 0;
100 if (metric.has_bucket()) {
yro59cc24d2018-02-13 20:17:32 -0800101 bucketSizeMills = TimeUnitToBucketSizeInMillisGuardrailed(key.GetUid(), metric.bucket());
Yangster1d4d6862017-10-31 12:58:51 -0700102 } else {
Yangster-macb8144812018-01-04 10:56:23 -0800103 bucketSizeMills = TimeUnitToBucketSizeInMillis(ONE_HOUR);
Yangster1d4d6862017-10-31 12:58:51 -0700104 }
Yangster-macb8144812018-01-04 10:56:23 -0800105 mBucketSizeNs = bucketSizeMills * 1000000;
Yangster1d4d6862017-10-31 12:58:51 -0700106
Yangster-mac34ea1102018-01-29 12:40:55 -0800107 mSamplingType = metric.sampling_type();
Yao Chen8a8d16c2018-02-08 14:50:40 -0800108 if (!metric.gauge_fields_filter().include_all()) {
109 translateFieldMatcher(metric.gauge_fields_filter().fields(), &mFieldMatchers);
110 }
Chenjie Yud9dfda72017-12-11 17:41:20 -0800111
Yao Chen8a8d16c2018-02-08 14:50:40 -0800112 if (metric.has_dimensions_in_what()) {
113 translateFieldMatcher(metric.dimensions_in_what(), &mDimensionsInWhat);
Yangster13fb7e42018-03-07 17:30:49 -0800114 mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
Yao Chen8a8d16c2018-02-08 14:50:40 -0800115 }
116
117 if (metric.has_dimensions_in_condition()) {
118 translateFieldMatcher(metric.dimensions_in_condition(), &mDimensionsInCondition);
119 }
Yangster1d4d6862017-10-31 12:58:51 -0700120
121 if (metric.links().size() > 0) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800122 for (const auto& link : metric.links()) {
123 Metric2Condition mc;
124 mc.conditionId = link.condition();
125 translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
126 translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
127 mMetric2ConditionLinks.push_back(mc);
128 }
Yangster1d4d6862017-10-31 12:58:51 -0700129 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800130 mConditionSliced = (metric.links().size() > 0) || (mDimensionsInCondition.size() > 0);
Yangster-mac9def8e32018-04-17 13:55:51 -0700131 mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what()) ||
132 HasPositionALL(metric.dimensions_in_condition());
Yangster1d4d6862017-10-31 12:58:51 -0700133
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700134 flushIfNeededLocked(startTimeNs);
Yangster1d4d6862017-10-31 12:58:51 -0700135 // Kicks off the puller immediately.
Chenjie Yue1361ed2018-07-23 17:33:09 -0700136 if (mIsPulled && mSamplingType == GaugeMetric::RANDOM_ONE_SAMPLE) {
Chenjie Yue2219202018-06-08 10:07:51 -0700137 mPullerManager->RegisterReceiver(mPullTagId, this, getCurrentBucketEndTimeNs(),
138 mBucketSizeNs);
Yangster1d4d6862017-10-31 12:58:51 -0700139 }
140
Chenjie Yue1361ed2018-07-23 17:33:09 -0700141 // Adjust start for partial bucket
142 mCurrentBucketStartTimeNs = startTimeNs;
143 if (mIsPulled) {
Yangster-mac32f07af2018-10-13 17:08:11 -0700144 pullAndMatchEventsLocked(startTimeNs);
Chenjie Yue1361ed2018-07-23 17:33:09 -0700145 }
146
Yao Chen427d3722018-03-22 15:21:52 -0700147 VLOG("Gauge metric %lld created. bucket size %lld start_time: %lld sliced %d",
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700148 (long long)metric.id(), (long long)mBucketSizeNs, (long long)mTimeBaseNs,
Yao Chen427d3722018-03-22 15:21:52 -0700149 mConditionSliced);
Yangster1d4d6862017-10-31 12:58:51 -0700150}
151
152GaugeMetricProducer::~GaugeMetricProducer() {
153 VLOG("~GaugeMetricProducer() called");
Chenjie Yue1361ed2018-07-23 17:33:09 -0700154 if (mIsPulled && mSamplingType == GaugeMetric::RANDOM_ONE_SAMPLE) {
Chenjie Yue2219202018-06-08 10:07:51 -0700155 mPullerManager->UnRegisterReceiver(mPullTagId, this);
Chenjie Yu032fefc2017-12-01 23:30:59 -0800156 }
Yangster1d4d6862017-10-31 12:58:51 -0700157}
158
Yangster-maca78d0082018-03-12 12:02:56 -0700159void GaugeMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
160 if (mCurrentSlicedBucket == nullptr ||
161 mCurrentSlicedBucket->size() == 0) {
162 return;
163 }
164
165 fprintf(out, "GaugeMetric %lld dimension size %lu\n", (long long)mMetricId,
166 (unsigned long)mCurrentSlicedBucket->size());
167 if (verbose) {
168 for (const auto& it : *mCurrentSlicedBucket) {
169 fprintf(out, "\t(what)%s\t(condition)%s %d atoms\n",
170 it.first.getDimensionKeyInWhat().toString().c_str(),
171 it.first.getDimensionKeyInCondition().toString().c_str(),
172 (int)it.second.size());
173 }
174 }
175}
176
Yangster-maca802d732018-04-24 07:50:38 -0700177void GaugeMetricProducer::clearPastBucketsLocked(const int64_t dumpTimeNs) {
178 flushIfNeededLocked(dumpTimeNs);
179 mPastBuckets.clear();
180 mSkippedBuckets.clear();
181}
182
Yangster-macb142cc82018-03-30 15:22:08 -0700183void GaugeMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700184 const bool include_current_partial_bucket,
Yangster-mac9def8e32018-04-17 13:55:51 -0700185 std::set<string> *str_set,
Yao Chen288c6002017-12-12 13:43:18 -0800186 ProtoOutputStream* protoOutput) {
Yao Chen427d3722018-03-22 15:21:52 -0700187 VLOG("Gauge metric %lld 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 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000193
Yangster-mac635b4b32018-01-23 20:17:35 -0800194 if (mPastBuckets.empty()) {
195 return;
196 }
Yao Chen288c6002017-12-12 13:43:18 -0800197
Yangster-mac94e197c2018-01-02 16:03:03 -0800198 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Yangster-mac9def8e32018-04-17 13:55:51 -0700199 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_TIME_BASE, (long long)mTimeBaseNs);
200 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_SIZE, (long long)mBucketSizeNs);
201
202 // Fills the dimension path if not slicing by ALL.
203 if (!mSliceByPositionALL) {
204 if (!mDimensionsInWhat.empty()) {
205 uint64_t dimenPathToken = protoOutput->start(
206 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_WHAT);
207 writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
208 protoOutput->end(dimenPathToken);
209 }
210 if (!mDimensionsInCondition.empty()) {
211 uint64_t dimenPathToken = protoOutput->start(
212 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_CONDITION);
213 writeDimensionPathToProto(mDimensionsInCondition, protoOutput);
214 protoOutput->end(dimenPathToken);
215 }
216 }
217
Yi Jin5ee07872018-03-05 18:18:27 -0800218 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_GAUGE_METRICS);
Yao Chen6a8c7992017-11-29 20:02:07 +0000219
David Chen81245fd2018-04-12 14:33:37 -0700220 for (const auto& pair : mSkippedBuckets) {
221 uint64_t wrapperToken =
222 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_SKIPPED);
Yangster-mac9def8e32018-04-17 13:55:51 -0700223 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_START_MILLIS,
224 (long long)(NanoToMillis(pair.first)));
225 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_END_MILLIS,
226 (long long)(NanoToMillis(pair.second)));
David Chen81245fd2018-04-12 14:33:37 -0700227 protoOutput->end(wrapperToken);
228 }
229 mSkippedBuckets.clear();
230
Yangster1d4d6862017-10-31 12:58:51 -0700231 for (const auto& pair : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800232 const MetricDimensionKey& dimensionKey = pair.first;
Yangster1d4d6862017-10-31 12:58:51 -0700233
Yao Chen427d3722018-03-22 15:21:52 -0700234 VLOG("Gauge dimension key %s", dimensionKey.toString().c_str());
Yi Jin5ee07872018-03-05 18:18:27 -0800235 uint64_t wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800236 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
yro2b0f8862017-11-06 14:27:31 -0800237
Yangster-mac20877162017-12-22 17:19:39 -0800238 // First fill dimension.
Yangster-mac9def8e32018-04-17 13:55:51 -0700239 if (mSliceByPositionALL) {
240 uint64_t dimensionToken = protoOutput->start(
241 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
242 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), str_set, protoOutput);
243 protoOutput->end(dimensionToken);
yro2b0f8862017-11-06 14:27:31 -0800244
Yangster-mac9def8e32018-04-17 13:55:51 -0700245 if (dimensionKey.hasDimensionKeyInCondition()) {
246 uint64_t dimensionInConditionToken = protoOutput->start(
247 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
248 writeDimensionToProto(dimensionKey.getDimensionKeyInCondition(),
249 str_set, protoOutput);
250 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(),
257 FIELD_ID_DIMENSION_LEAF_IN_CONDITION,
258 str_set, protoOutput);
259 }
Yangster-mac93694462018-01-22 20:49:31 -0800260 }
261
yro2b0f8862017-11-06 14:27:31 -0800262 // Then fill bucket_info (GaugeBucketInfo).
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 }
Yangster-mac34ea1102018-01-29 12:40:55 -0800276
277 if (!bucket.mGaugeAtoms.empty()) {
Yangster-mac34ea1102018-01-29 12:40:55 -0800278 for (const auto& atom : bucket.mGaugeAtoms) {
Yangster-mac3fa5d7f2018-03-10 21:50:27 -0800279 uint64_t atomsToken =
280 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
281 FIELD_ID_ATOM);
Chenjie Yu88588972018-08-03 09:49:22 -0700282 writeFieldValueTreeToStream(mAtomId, *(atom.mFields), protoOutput);
Yangster-mac3fa5d7f2018-03-10 21:50:27 -0800283 protoOutput->end(atomsToken);
Yangster-mac34ea1102018-01-29 12:40:55 -0800284 }
Yangster-mac3fa5d7f2018-03-10 21:50:27 -0800285 const bool truncateTimestamp =
Yao Chenc40a19d2018-03-15 16:48:25 -0700286 android::util::AtomsInfo::kNotTruncatingTimestampAtomWhiteList.find(
Chenjie Yu88588972018-08-03 09:49:22 -0700287 mAtomId) ==
Yao Chenc40a19d2018-03-15 16:48:25 -0700288 android::util::AtomsInfo::kNotTruncatingTimestampAtomWhiteList.end();
Yangster-mac34ea1102018-01-29 12:40:55 -0800289 for (const auto& atom : bucket.mGaugeAtoms) {
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700290 const int64_t elapsedTimestampNs = truncateTimestamp ?
291 truncateTimestampNsToFiveMinutes(atom.mElapsedTimestamps) :
292 atom.mElapsedTimestamps;
Yangster-mac330af582018-02-08 15:24:38 -0800293 protoOutput->write(
294 FIELD_TYPE_INT64 | FIELD_COUNT_REPEATED | FIELD_ID_ELAPSED_ATOM_TIMESTAMP,
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700295 (long long)elapsedTimestampNs);
Yangster-mac34ea1102018-01-29 12:40:55 -0800296 }
297 }
Yao Chen288c6002017-12-12 13:43:18 -0800298 protoOutput->end(bucketInfoToken);
Yao Chen427d3722018-03-22 15:21:52 -0700299 VLOG("Gauge \t bucket [%lld - %lld] includes %d atoms.",
300 (long long)bucket.mBucketStartNs, (long long)bucket.mBucketEndNs,
301 (int)bucket.mGaugeAtoms.size());
yro2b0f8862017-11-06 14:27:31 -0800302 }
Yao Chen288c6002017-12-12 13:43:18 -0800303 protoOutput->end(wrapperToken);
Yangster1d4d6862017-10-31 12:58:51 -0700304 }
Yao Chen288c6002017-12-12 13:43:18 -0800305 protoOutput->end(protoToken);
yro2b0f8862017-11-06 14:27:31 -0800306
Yao Chen6a8c7992017-11-29 20:02:07 +0000307 mPastBuckets.clear();
Yangster1d4d6862017-10-31 12:58:51 -0700308}
309
Yangster-mac32f07af2018-10-13 17:08:11 -0700310void GaugeMetricProducer::pullAndMatchEventsLocked(const int64_t timestampNs) {
Yangster-mac34ea1102018-01-29 12:40:55 -0800311 bool triggerPuller = false;
312 switch(mSamplingType) {
313 // When the metric wants to do random sampling and there is already one gauge atom for the
314 // current bucket, do not do it again.
315 case GaugeMetric::RANDOM_ONE_SAMPLE: {
316 triggerPuller = mCondition && mCurrentSlicedBucket->empty();
317 break;
318 }
319 case GaugeMetric::ALL_CONDITION_CHANGES: {
320 triggerPuller = true;
321 break;
322 }
Yangsterec3c7a32018-05-09 15:51:07 -0700323 case GaugeMetric::CONDITION_CHANGE_TO_TRUE: {
324 triggerPuller = mCondition;
325 break;
326 }
Yangster-mac34ea1102018-01-29 12:40:55 -0800327 default:
328 break;
329 }
330 if (!triggerPuller) {
Yao Chen6a8c7992017-11-29 20:02:07 +0000331 return;
332 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000333 vector<std::shared_ptr<LogEvent>> allData;
Chenjie Yue2219202018-06-08 10:07:51 -0700334 if (!mPullerManager->Pull(mPullTagId, timestampNs, &allData)) {
Chenjie Yue1361ed2018-07-23 17:33:09 -0700335 ALOGE("Gauge Stats puller failed for tag: %d at %lld", mPullTagId, (long long)timestampNs);
Yao Chen6a8c7992017-11-29 20:02:07 +0000336 return;
337 }
Yangster1d4d6862017-10-31 12:58:51 -0700338 for (const auto& data : allData) {
Yangster-mac32f07af2018-10-13 17:08:11 -0700339 if (mEventMatcherWizard->matchLogEvent(
340 *data, mWhatMatcherIndex) == MatchingState::kMatched) {
341 onMatchedLogEventLocked(mWhatMatcherIndex, *data);
342 }
Yangster1d4d6862017-10-31 12:58:51 -0700343 }
Yangster1d4d6862017-10-31 12:58:51 -0700344}
345
Yao Chen427d3722018-03-22 15:21:52 -0700346void GaugeMetricProducer::onConditionChangedLocked(const bool conditionMet,
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700347 const int64_t eventTimeNs) {
Yao Chen427d3722018-03-22 15:21:52 -0700348 VLOG("GaugeMetric %lld onConditionChanged", (long long)mMetricId);
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700349 flushIfNeededLocked(eventTimeNs);
Yao Chen427d3722018-03-22 15:21:52 -0700350 mCondition = conditionMet;
Chenjie Yue1361ed2018-07-23 17:33:09 -0700351 if (mIsPulled) {
Yangster-mac32f07af2018-10-13 17:08:11 -0700352 pullAndMatchEventsLocked(eventTimeNs);
Yao Chen427d3722018-03-22 15:21:52 -0700353 } // else: Push mode. No need to proactively pull the gauge data.
354}
355
356void GaugeMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700357 const int64_t eventTimeNs) {
Yao Chen427d3722018-03-22 15:21:52 -0700358 VLOG("GaugeMetric %lld onSlicedConditionMayChange overall condition %d", (long long)mMetricId,
359 overallCondition);
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700360 flushIfNeededLocked(eventTimeNs);
Yao Chen427d3722018-03-22 15:21:52 -0700361 // If the condition is sliced, mCondition is true if any of the dimensions is true. And we will
362 // pull for every dimension.
363 mCondition = overallCondition;
Chenjie Yue1361ed2018-07-23 17:33:09 -0700364 if (mIsPulled) {
Yangster-mac32f07af2018-10-13 17:08:11 -0700365 pullAndMatchEventsLocked(eventTimeNs);
Yao Chen427d3722018-03-22 15:21:52 -0700366 } // else: Push mode. No need to proactively pull the gauge data.
Yangster1d4d6862017-10-31 12:58:51 -0700367}
368
Yao Chen8a8d16c2018-02-08 14:50:40 -0800369std::shared_ptr<vector<FieldValue>> GaugeMetricProducer::getGaugeFields(const LogEvent& event) {
Chenjie Yu4c31f672018-08-21 15:42:40 -0700370 std::shared_ptr<vector<FieldValue>> gaugeFields;
Yao Chen8a8d16c2018-02-08 14:50:40 -0800371 if (mFieldMatchers.size() > 0) {
Chenjie Yu4c31f672018-08-21 15:42:40 -0700372 gaugeFields = std::make_shared<vector<FieldValue>>();
Yao Chen8a8d16c2018-02-08 14:50:40 -0800373 filterGaugeValues(mFieldMatchers, event.getValues(), gaugeFields.get());
Yao Chen8a8d16c2018-02-08 14:50:40 -0800374 } else {
Chenjie Yu4c31f672018-08-21 15:42:40 -0700375 gaugeFields = std::make_shared<vector<FieldValue>>(event.getValues());
Yangster1d4d6862017-10-31 12:58:51 -0700376 }
Chenjie Yu4c31f672018-08-21 15:42:40 -0700377 // Trim all dimension fields from output. Dimensions will appear in output report and will
378 // benefit from dictionary encoding. For large pulled atoms, this can give the benefit of
379 // optional repeated field.
380 for (const auto& field : mDimensionsInWhat) {
381 for (auto it = gaugeFields->begin(); it != gaugeFields->end();) {
382 if (it->mField.matches(field)) {
383 it = gaugeFields->erase(it);
384 } else {
385 it++;
386 }
387 }
388 }
389 return gaugeFields;
Yangster1d4d6862017-10-31 12:58:51 -0700390}
391
392void GaugeMetricProducer::onDataPulled(const std::vector<std::shared_ptr<LogEvent>>& allData) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800393 std::lock_guard<std::mutex> lock(mMutex);
Chenjie Yud9dfda72017-12-11 17:41:20 -0800394 if (allData.size() == 0) {
395 return;
396 }
Yangster1d4d6862017-10-31 12:58:51 -0700397 for (const auto& data : allData) {
Yangster-mac32f07af2018-10-13 17:08:11 -0700398 if (mEventMatcherWizard->matchLogEvent(
399 *data, mWhatMatcherIndex) == MatchingState::kMatched) {
400 onMatchedLogEventLocked(mWhatMatcherIndex, *data);
401 }
Yangster1d4d6862017-10-31 12:58:51 -0700402 }
Yangster1d4d6862017-10-31 12:58:51 -0700403}
404
Yangster-mac93694462018-01-22 20:49:31 -0800405bool GaugeMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800406 if (mCurrentSlicedBucket->find(newKey) != mCurrentSlicedBucket->end()) {
407 return false;
408 }
409 // 1. Report the tuple count if the tuple count > soft limit
Chenjie Yuc5875052018-03-09 10:13:11 -0800410 if (mCurrentSlicedBucket->size() > mDimensionSoftLimit - 1) {
Yao Chenb3561512017-11-21 18:07:17 -0800411 size_t newTupleCount = mCurrentSlicedBucket->size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800412 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800413 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
Chenjie Yuc5875052018-03-09 10:13:11 -0800414 if (newTupleCount > mDimensionHardLimit) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800415 ALOGE("GaugeMetric %lld dropping data for dimension key %s",
Yangster13fb7e42018-03-07 17:30:49 -0800416 (long long)mMetricId, newKey.toString().c_str());
Yao Chenb3561512017-11-21 18:07:17 -0800417 return true;
418 }
419 }
420
421 return false;
422}
423
Yangsterf2bee6f2017-11-29 12:01:05 -0800424void GaugeMetricProducer::onMatchedLogEventInternalLocked(
Yangster-mac93694462018-01-22 20:49:31 -0800425 const size_t matcherIndex, const MetricDimensionKey& eventKey,
Yangster-mac20877162017-12-22 17:19:39 -0800426 const ConditionKey& conditionKey, bool condition,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800427 const LogEvent& event) {
Yangster1d4d6862017-10-31 12:58:51 -0700428 if (condition == false) {
429 return;
430 }
Yangster-macb142cc82018-03-30 15:22:08 -0700431 int64_t eventTimeNs = event.GetElapsedTimestampNs();
Yangster1d4d6862017-10-31 12:58:51 -0700432 if (eventTimeNs < mCurrentBucketStartTimeNs) {
Yao Chen427d3722018-03-22 15:21:52 -0700433 VLOG("Gauge Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
Yangster1d4d6862017-10-31 12:58:51 -0700434 (long long)mCurrentBucketStartTimeNs);
435 return;
436 }
Chenjie Yud9dfda72017-12-11 17:41:20 -0800437 flushIfNeededLocked(eventTimeNs);
Yao Chen6a8c7992017-11-29 20:02:07 +0000438
Chenjie Yu88588972018-08-03 09:49:22 -0700439 if (mTriggerAtomId == event.GetTagId()) {
Yangster-mac32f07af2018-10-13 17:08:11 -0700440 pullAndMatchEventsLocked(eventTimeNs);
Chenjie Yu88588972018-08-03 09:49:22 -0700441 return;
442 }
443
Yangster-mac34ea1102018-01-29 12:40:55 -0800444 // When gauge metric wants to randomly sample the output atom, we just simply use the first
445 // gauge in the given bucket.
446 if (mCurrentSlicedBucket->find(eventKey) != mCurrentSlicedBucket->end() &&
447 mSamplingType == GaugeMetric::RANDOM_ONE_SAMPLE) {
Yangster1d4d6862017-10-31 12:58:51 -0700448 return;
449 }
Chenjie Yud9dfda72017-12-11 17:41:20 -0800450 if (hitGuardRailLocked(eventKey)) {
451 return;
Yao Chen6a8c7992017-11-29 20:02:07 +0000452 }
Yangster-mac50b0c9a2018-05-10 17:13:12 -0700453 if ((*mCurrentSlicedBucket)[eventKey].size() >= mGaugeAtomsPerDimensionLimit) {
454 return;
455 }
Bookatzfe2dde82018-08-28 13:24:40 -0700456 GaugeAtom gaugeAtom(getGaugeFields(event), eventTimeNs);
Yangster-mac34ea1102018-01-29 12:40:55 -0800457 (*mCurrentSlicedBucket)[eventKey].push_back(gaugeAtom);
Chenjie Yud9dfda72017-12-11 17:41:20 -0800458 // Anomaly detection on gauge metric only works when there is one numeric
459 // field specified.
460 if (mAnomalyTrackers.size() > 0) {
Yangster-mac34ea1102018-01-29 12:40:55 -0800461 if (gaugeAtom.mFields->size() == 1) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800462 const Value& value = gaugeAtom.mFields->begin()->mValue;
Chenjie Yud9dfda72017-12-11 17:41:20 -0800463 long gaugeVal = 0;
Yao Chen8a8d16c2018-02-08 14:50:40 -0800464 if (value.getType() == INT) {
465 gaugeVal = (long)value.int_value;
466 } else if (value.getType() == LONG) {
467 gaugeVal = value.long_value;
Chenjie Yud9dfda72017-12-11 17:41:20 -0800468 }
469 for (auto& tracker : mAnomalyTrackers) {
470 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, eventKey,
471 gaugeVal);
472 }
473 }
474 }
475}
476
477void GaugeMetricProducer::updateCurrentSlicedBucketForAnomaly() {
Chenjie Yud9dfda72017-12-11 17:41:20 -0800478 for (const auto& slice : *mCurrentSlicedBucket) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800479 if (slice.second.empty()) {
Yangster-mac34ea1102018-01-29 12:40:55 -0800480 continue;
481 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800482 const Value& value = slice.second.front().mFields->front().mValue;
Chenjie Yud9dfda72017-12-11 17:41:20 -0800483 long gaugeVal = 0;
Yao Chen8a8d16c2018-02-08 14:50:40 -0800484 if (value.getType() == INT) {
485 gaugeVal = (long)value.int_value;
486 } else if (value.getType() == LONG) {
487 gaugeVal = value.long_value;
Chenjie Yud9dfda72017-12-11 17:41:20 -0800488 }
489 (*mCurrentSlicedBucketForAnomaly)[slice.first] = gaugeVal;
Yangster1d4d6862017-10-31 12:58:51 -0700490 }
491}
492
Yangster-macb142cc82018-03-30 15:22:08 -0700493void GaugeMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
Yao Chen06dba5d2018-01-26 13:38:16 -0800494 flushIfNeededLocked(dropTimeNs);
495 mPastBuckets.clear();
496}
497
Yangster1d4d6862017-10-31 12:58:51 -0700498// When a new matched event comes in, we check if event falls into the current
499// bucket. If not, flush the old counter to past buckets and initialize the new
500// bucket.
501// if data is pushed, onMatchedLogEvent will only be called through onConditionChanged() inside
502// the GaugeMetricProducer while holding the lock.
Yangster-macb142cc82018-03-30 15:22:08 -0700503void GaugeMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
504 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800505
506 if (eventTimeNs < currentBucketEndTimeNs) {
Yao Chen427d3722018-03-22 15:21:52 -0700507 VLOG("Gauge eventTime is %lld, less than next bucket start time %lld",
508 (long long)eventTimeNs, (long long)(mCurrentBucketStartTimeNs + mBucketSizeNs));
Yangster1d4d6862017-10-31 12:58:51 -0700509 return;
510 }
511
David Chen27785a82018-01-19 17:06:45 -0800512 flushCurrentBucketLocked(eventTimeNs);
513
514 // Adjusts the bucket start and end times.
515 int64_t numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
516 mCurrentBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
517 mCurrentBucketNum += numBucketsForward;
Yao Chen427d3722018-03-22 15:21:52 -0700518 VLOG("Gauge metric %lld: new bucket start time: %lld", (long long)mMetricId,
David Chen27785a82018-01-19 17:06:45 -0800519 (long long)mCurrentBucketStartTimeNs);
520}
521
Yangster-macb142cc82018-03-30 15:22:08 -0700522void GaugeMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs) {
523 int64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800524
yro2b0f8862017-11-06 14:27:31 -0800525 GaugeBucket info;
526 info.mBucketStartNs = mCurrentBucketStartTimeNs;
David Chen27785a82018-01-19 17:06:45 -0800527 if (eventTimeNs < fullBucketEndTimeNs) {
528 info.mBucketEndNs = eventTimeNs;
529 } else {
530 info.mBucketEndNs = fullBucketEndTimeNs;
531 }
Yangster1d4d6862017-10-31 12:58:51 -0700532
David Chen81245fd2018-04-12 14:33:37 -0700533 if (info.mBucketEndNs - mCurrentBucketStartTimeNs >= mMinBucketSizeNs) {
534 for (const auto& slice : *mCurrentSlicedBucket) {
535 info.mGaugeAtoms = slice.second;
536 auto& bucketList = mPastBuckets[slice.first];
537 bucketList.push_back(info);
538 VLOG("Gauge gauge metric %lld, dump key value: %s", (long long)mMetricId,
539 slice.first.toString().c_str());
540 }
541 } else {
542 mSkippedBuckets.emplace_back(info.mBucketStartNs, info.mBucketEndNs);
Yangster1d4d6862017-10-31 12:58:51 -0700543 }
Yangster1d4d6862017-10-31 12:58:51 -0700544
David Chen27785a82018-01-19 17:06:45 -0800545 // If we have anomaly trackers, we need to update the partial bucket values.
Chenjie Yud9dfda72017-12-11 17:41:20 -0800546 if (mAnomalyTrackers.size() > 0) {
547 updateCurrentSlicedBucketForAnomaly();
David Chen27785a82018-01-19 17:06:45 -0800548
549 if (eventTimeNs > fullBucketEndTimeNs) {
550 // This is known to be a full bucket, so send this data to the anomaly tracker.
551 for (auto& tracker : mAnomalyTrackers) {
552 tracker->addPastBucket(mCurrentSlicedBucketForAnomaly, mCurrentBucketNum);
553 }
554 mCurrentSlicedBucketForAnomaly = std::make_shared<DimToValMap>();
Chenjie Yud9dfda72017-12-11 17:41:20 -0800555 }
Yangster-mace2cd6d52017-11-09 20:38:30 -0800556 }
557
Yangster-mac34ea1102018-01-29 12:40:55 -0800558 mCurrentSlicedBucket = std::make_shared<DimToGaugeAtomsMap>();
Yangster1d4d6862017-10-31 12:58:51 -0700559}
560
Yangsterf2bee6f2017-11-29 12:01:05 -0800561size_t GaugeMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800562 size_t totalSize = 0;
563 for (const auto& pair : mPastBuckets) {
Yangster-macb2532da2018-04-11 13:55:04 -0700564 for (const auto& bucket : pair.second) {
565 totalSize += bucket.mGaugeAtoms.size() * sizeof(GaugeAtom);
566 for (const auto& atom : bucket.mGaugeAtoms) {
567 if (atom.mFields != nullptr) {
568 totalSize += atom.mFields->size() * sizeof(FieldValue);
569 }
570 }
571 }
Yangster-mace2cd6d52017-11-09 20:38:30 -0800572 }
573 return totalSize;
yro2b0f8862017-11-06 14:27:31 -0800574}
575
Yangster1d4d6862017-10-31 12:58:51 -0700576} // namespace statsd
577} // namespace os
578} // namespace android