blob: aabd3616e2fe42f3bfd543e3692dabfb24db4bdf [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-mac3fa5d7f2018-03-10 21:50:27 -080066const int FIELD_ID_WALL_CLOCK_ATOM_TIMESTAMP = 5;
Yangster-mac9def8e32018-04-17 13:55:51 -070067const int FIELD_ID_BUCKET_NUM = 6;
68const int FIELD_ID_START_BUCKET_ELAPSED_MILLIS = 7;
69const int FIELD_ID_END_BUCKET_ELAPSED_MILLIS = 8;
yro2b0f8862017-11-06 14:27:31 -080070
Yao Chenb3561512017-11-21 18:07:17 -080071GaugeMetricProducer::GaugeMetricProducer(const ConfigKey& key, const GaugeMetric& metric,
72 const int conditionIndex,
Chenjie Yuc5875052018-03-09 10:13:11 -080073 const sp<ConditionWizard>& wizard, const int pullTagId,
Yangster-mac15f6bbc2018-04-08 11:52:26 -070074 const int64_t timeBaseNs, const int64_t startTimeNs,
Chenjie Yud9dfda72017-12-11 17:41:20 -080075 shared_ptr<StatsPullerManager> statsPullerManager)
Yangster-mac15f6bbc2018-04-08 11:52:26 -070076 : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, wizard),
Chenjie Yud9dfda72017-12-11 17:41:20 -080077 mStatsPullerManager(statsPullerManager),
Chenjie Yuc5875052018-03-09 10:13:11 -080078 mPullTagId(pullTagId),
David Chen81245fd2018-04-12 14:33:37 -070079 mMinBucketSizeNs(metric.min_bucket_size_nanos()),
Chenjie Yuc5875052018-03-09 10:13:11 -080080 mDimensionSoftLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
81 StatsdStats::kAtomDimensionKeySizeLimitMap.end()
82 ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).first
83 : StatsdStats::kDimensionKeySizeSoftLimit),
84 mDimensionHardLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
85 StatsdStats::kAtomDimensionKeySizeLimitMap.end()
86 ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).second
Yangster-mac50b0c9a2018-05-10 17:13:12 -070087 : StatsdStats::kDimensionKeySizeHardLimit),
88 mGaugeAtomsPerDimensionLimit(metric.max_num_gauge_atoms_per_bucket()) {
Yangster-mac34ea1102018-01-29 12:40:55 -080089 mCurrentSlicedBucket = std::make_shared<DimToGaugeAtomsMap>();
Yangster-mac20877162017-12-22 17:19:39 -080090 mCurrentSlicedBucketForAnomaly = std::make_shared<DimToValMap>();
Yangster-macb8144812018-01-04 10:56:23 -080091 int64_t bucketSizeMills = 0;
92 if (metric.has_bucket()) {
yro59cc24d2018-02-13 20:17:32 -080093 bucketSizeMills = TimeUnitToBucketSizeInMillisGuardrailed(key.GetUid(), metric.bucket());
Yangster1d4d6862017-10-31 12:58:51 -070094 } else {
Yangster-macb8144812018-01-04 10:56:23 -080095 bucketSizeMills = TimeUnitToBucketSizeInMillis(ONE_HOUR);
Yangster1d4d6862017-10-31 12:58:51 -070096 }
Yangster-macb8144812018-01-04 10:56:23 -080097 mBucketSizeNs = bucketSizeMills * 1000000;
Yangster1d4d6862017-10-31 12:58:51 -070098
Yangster-mac34ea1102018-01-29 12:40:55 -080099 mSamplingType = metric.sampling_type();
Yao Chen8a8d16c2018-02-08 14:50:40 -0800100 if (!metric.gauge_fields_filter().include_all()) {
101 translateFieldMatcher(metric.gauge_fields_filter().fields(), &mFieldMatchers);
102 }
Chenjie Yud9dfda72017-12-11 17:41:20 -0800103
Yangster1d4d6862017-10-31 12:58:51 -0700104 // TODO: use UidMap if uid->pkg_name is required
Yao Chen8a8d16c2018-02-08 14:50:40 -0800105 if (metric.has_dimensions_in_what()) {
106 translateFieldMatcher(metric.dimensions_in_what(), &mDimensionsInWhat);
Yangster13fb7e42018-03-07 17:30:49 -0800107 mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
Yao Chen8a8d16c2018-02-08 14:50:40 -0800108 }
109
110 if (metric.has_dimensions_in_condition()) {
111 translateFieldMatcher(metric.dimensions_in_condition(), &mDimensionsInCondition);
112 }
Yangster1d4d6862017-10-31 12:58:51 -0700113
114 if (metric.links().size() > 0) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800115 for (const auto& link : metric.links()) {
116 Metric2Condition mc;
117 mc.conditionId = link.condition();
118 translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
119 translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
120 mMetric2ConditionLinks.push_back(mc);
121 }
Yangster1d4d6862017-10-31 12:58:51 -0700122 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800123 mConditionSliced = (metric.links().size() > 0) || (mDimensionsInCondition.size() > 0);
Yangster-mac9def8e32018-04-17 13:55:51 -0700124 mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what()) ||
125 HasPositionALL(metric.dimensions_in_condition());
Yangster1d4d6862017-10-31 12:58:51 -0700126
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700127 flushIfNeededLocked(startTimeNs);
Yangster1d4d6862017-10-31 12:58:51 -0700128 // Kicks off the puller immediately.
Yangster-mac34ea1102018-01-29 12:40:55 -0800129 if (mPullTagId != -1 && mSamplingType == GaugeMetric::RANDOM_ONE_SAMPLE) {
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700130 mStatsPullerManager->RegisterReceiver(
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700131 mPullTagId, this, getCurrentBucketEndTimeNs(), mBucketSizeNs);
Yangster1d4d6862017-10-31 12:58:51 -0700132 }
133
Yao Chen427d3722018-03-22 15:21:52 -0700134 VLOG("Gauge metric %lld created. bucket size %lld start_time: %lld sliced %d",
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700135 (long long)metric.id(), (long long)mBucketSizeNs, (long long)mTimeBaseNs,
Yao Chen427d3722018-03-22 15:21:52 -0700136 mConditionSliced);
Yangster1d4d6862017-10-31 12:58:51 -0700137}
138
Chenjie Yud9dfda72017-12-11 17:41:20 -0800139// for testing
140GaugeMetricProducer::GaugeMetricProducer(const ConfigKey& key, const GaugeMetric& metric,
141 const int conditionIndex,
142 const sp<ConditionWizard>& wizard, const int pullTagId,
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700143 const int64_t timeBaseNs, const int64_t startTimeNs)
144 : GaugeMetricProducer(key, metric, conditionIndex, wizard, pullTagId, timeBaseNs, startTimeNs,
Chenjie Yud9dfda72017-12-11 17:41:20 -0800145 make_shared<StatsPullerManager>()) {
146}
147
Yangster1d4d6862017-10-31 12:58:51 -0700148GaugeMetricProducer::~GaugeMetricProducer() {
149 VLOG("~GaugeMetricProducer() called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700150 if (mPullTagId != -1 && mSamplingType == GaugeMetric::RANDOM_ONE_SAMPLE) {
Chenjie Yud9dfda72017-12-11 17:41:20 -0800151 mStatsPullerManager->UnRegisterReceiver(mPullTagId, this);
Chenjie Yu032fefc2017-12-01 23:30:59 -0800152 }
Yangster1d4d6862017-10-31 12:58:51 -0700153}
154
Yangster-maca78d0082018-03-12 12:02:56 -0700155void GaugeMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
156 if (mCurrentSlicedBucket == nullptr ||
157 mCurrentSlicedBucket->size() == 0) {
158 return;
159 }
160
161 fprintf(out, "GaugeMetric %lld dimension size %lu\n", (long long)mMetricId,
162 (unsigned long)mCurrentSlicedBucket->size());
163 if (verbose) {
164 for (const auto& it : *mCurrentSlicedBucket) {
165 fprintf(out, "\t(what)%s\t(condition)%s %d atoms\n",
166 it.first.getDimensionKeyInWhat().toString().c_str(),
167 it.first.getDimensionKeyInCondition().toString().c_str(),
168 (int)it.second.size());
169 }
170 }
171}
172
Yangster-maca802d732018-04-24 07:50:38 -0700173void GaugeMetricProducer::clearPastBucketsLocked(const int64_t dumpTimeNs) {
174 flushIfNeededLocked(dumpTimeNs);
175 mPastBuckets.clear();
176 mSkippedBuckets.clear();
177}
178
Yangster-macb142cc82018-03-30 15:22:08 -0700179void GaugeMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700180 const bool include_current_partial_bucket,
Yangster-mac9def8e32018-04-17 13:55:51 -0700181 std::set<string> *str_set,
Yao Chen288c6002017-12-12 13:43:18 -0800182 ProtoOutputStream* protoOutput) {
Yao Chen427d3722018-03-22 15:21:52 -0700183 VLOG("Gauge metric %lld report now...", (long long)mMetricId);
Yangster-mace68f3a52018-04-04 00:01:43 -0700184 if (include_current_partial_bucket) {
185 flushLocked(dumpTimeNs);
186 } else {
187 flushIfNeededLocked(dumpTimeNs);
188 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000189
Yangster-mac635b4b32018-01-23 20:17:35 -0800190 if (mPastBuckets.empty()) {
191 return;
192 }
Yao Chen288c6002017-12-12 13:43:18 -0800193
Yangster-mac94e197c2018-01-02 16:03:03 -0800194 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Yangster-mac9def8e32018-04-17 13:55:51 -0700195 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_TIME_BASE, (long long)mTimeBaseNs);
196 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_SIZE, (long long)mBucketSizeNs);
197
198 // Fills the dimension path if not slicing by ALL.
199 if (!mSliceByPositionALL) {
200 if (!mDimensionsInWhat.empty()) {
201 uint64_t dimenPathToken = protoOutput->start(
202 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_WHAT);
203 writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
204 protoOutput->end(dimenPathToken);
205 }
206 if (!mDimensionsInCondition.empty()) {
207 uint64_t dimenPathToken = protoOutput->start(
208 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_CONDITION);
209 writeDimensionPathToProto(mDimensionsInCondition, protoOutput);
210 protoOutput->end(dimenPathToken);
211 }
212 }
213
Yi Jin5ee07872018-03-05 18:18:27 -0800214 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_GAUGE_METRICS);
Yao Chen6a8c7992017-11-29 20:02:07 +0000215
David Chen81245fd2018-04-12 14:33:37 -0700216 for (const auto& pair : mSkippedBuckets) {
217 uint64_t wrapperToken =
218 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_SKIPPED);
Yangster-mac9def8e32018-04-17 13:55:51 -0700219 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_START_MILLIS,
220 (long long)(NanoToMillis(pair.first)));
221 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_SKIPPED_END_MILLIS,
222 (long long)(NanoToMillis(pair.second)));
David Chen81245fd2018-04-12 14:33:37 -0700223 protoOutput->end(wrapperToken);
224 }
225 mSkippedBuckets.clear();
226
Yangster1d4d6862017-10-31 12:58:51 -0700227 for (const auto& pair : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800228 const MetricDimensionKey& dimensionKey = pair.first;
Yangster1d4d6862017-10-31 12:58:51 -0700229
Yao Chen427d3722018-03-22 15:21:52 -0700230 VLOG("Gauge dimension key %s", dimensionKey.toString().c_str());
Yi Jin5ee07872018-03-05 18:18:27 -0800231 uint64_t wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800232 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
yro2b0f8862017-11-06 14:27:31 -0800233
Yangster-mac20877162017-12-22 17:19:39 -0800234 // First fill dimension.
Yangster-mac9def8e32018-04-17 13:55:51 -0700235 if (mSliceByPositionALL) {
236 uint64_t dimensionToken = protoOutput->start(
237 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
238 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), str_set, protoOutput);
239 protoOutput->end(dimensionToken);
yro2b0f8862017-11-06 14:27:31 -0800240
Yangster-mac9def8e32018-04-17 13:55:51 -0700241 if (dimensionKey.hasDimensionKeyInCondition()) {
242 uint64_t dimensionInConditionToken = protoOutput->start(
243 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
244 writeDimensionToProto(dimensionKey.getDimensionKeyInCondition(),
245 str_set, protoOutput);
246 protoOutput->end(dimensionInConditionToken);
247 }
248 } else {
249 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInWhat(),
250 FIELD_ID_DIMENSION_LEAF_IN_WHAT, str_set, protoOutput);
251 if (dimensionKey.hasDimensionKeyInCondition()) {
252 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInCondition(),
253 FIELD_ID_DIMENSION_LEAF_IN_CONDITION,
254 str_set, protoOutput);
255 }
Yangster-mac93694462018-01-22 20:49:31 -0800256 }
257
yro2b0f8862017-11-06 14:27:31 -0800258 // Then fill bucket_info (GaugeBucketInfo).
259 for (const auto& bucket : pair.second) {
Yi Jin5ee07872018-03-05 18:18:27 -0800260 uint64_t bucketInfoToken = protoOutput->start(
Yao Chen288c6002017-12-12 13:43:18 -0800261 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
Yangster-mac9def8e32018-04-17 13:55:51 -0700262
263 if (bucket.mBucketEndNs - bucket.mBucketStartNs != mBucketSizeNs) {
264 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_MILLIS,
265 (long long)NanoToMillis(bucket.mBucketStartNs));
266 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_MILLIS,
267 (long long)NanoToMillis(bucket.mBucketEndNs));
268 } else {
269 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_NUM,
270 (long long)(getBucketNumFromEndTimeNs(bucket.mBucketEndNs)));
271 }
Yangster-mac34ea1102018-01-29 12:40:55 -0800272
273 if (!bucket.mGaugeAtoms.empty()) {
Yangster-mac34ea1102018-01-29 12:40:55 -0800274 for (const auto& atom : bucket.mGaugeAtoms) {
Yangster-mac3fa5d7f2018-03-10 21:50:27 -0800275 uint64_t atomsToken =
276 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
277 FIELD_ID_ATOM);
Yao Chen8a8d16c2018-02-08 14:50:40 -0800278 writeFieldValueTreeToStream(mTagId, *(atom.mFields), protoOutput);
Yangster-mac3fa5d7f2018-03-10 21:50:27 -0800279 protoOutput->end(atomsToken);
Yangster-mac34ea1102018-01-29 12:40:55 -0800280 }
Yangster-mac3fa5d7f2018-03-10 21:50:27 -0800281 const bool truncateTimestamp =
Yao Chenc40a19d2018-03-15 16:48:25 -0700282 android::util::AtomsInfo::kNotTruncatingTimestampAtomWhiteList.find(
283 mTagId) ==
284 android::util::AtomsInfo::kNotTruncatingTimestampAtomWhiteList.end();
Yangster-mac34ea1102018-01-29 12:40:55 -0800285 for (const auto& atom : bucket.mGaugeAtoms) {
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700286 const int64_t elapsedTimestampNs = truncateTimestamp ?
287 truncateTimestampNsToFiveMinutes(atom.mElapsedTimestamps) :
288 atom.mElapsedTimestamps;
289 const int64_t wallClockNs = truncateTimestamp ?
290 truncateTimestampNsToFiveMinutes(atom.mWallClockTimestampNs) :
291 atom.mWallClockTimestampNs;
Yangster-mac330af582018-02-08 15:24:38 -0800292 protoOutput->write(
293 FIELD_TYPE_INT64 | FIELD_COUNT_REPEATED | FIELD_ID_ELAPSED_ATOM_TIMESTAMP,
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700294 (long long)elapsedTimestampNs);
Yangster-mac3fa5d7f2018-03-10 21:50:27 -0800295 protoOutput->write(
296 FIELD_TYPE_INT64 | FIELD_COUNT_REPEATED |
297 FIELD_ID_WALL_CLOCK_ATOM_TIMESTAMP,
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700298 (long long)wallClockNs);
Yangster-mac34ea1102018-01-29 12:40:55 -0800299 }
300 }
Yao Chen288c6002017-12-12 13:43:18 -0800301 protoOutput->end(bucketInfoToken);
Yao Chen427d3722018-03-22 15:21:52 -0700302 VLOG("Gauge \t bucket [%lld - %lld] includes %d atoms.",
303 (long long)bucket.mBucketStartNs, (long long)bucket.mBucketEndNs,
304 (int)bucket.mGaugeAtoms.size());
yro2b0f8862017-11-06 14:27:31 -0800305 }
Yao Chen288c6002017-12-12 13:43:18 -0800306 protoOutput->end(wrapperToken);
Yangster1d4d6862017-10-31 12:58:51 -0700307 }
Yao Chen288c6002017-12-12 13:43:18 -0800308 protoOutput->end(protoToken);
yro2b0f8862017-11-06 14:27:31 -0800309
Yao Chen6a8c7992017-11-29 20:02:07 +0000310 mPastBuckets.clear();
yro2b0f8862017-11-06 14:27:31 -0800311 // TODO: Clear mDimensionKeyMap once the report is dumped.
Yangster1d4d6862017-10-31 12:58:51 -0700312}
313
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700314void GaugeMetricProducer::pullLocked(const int64_t timestampNs) {
Yangster-mac34ea1102018-01-29 12:40:55 -0800315 bool triggerPuller = false;
316 switch(mSamplingType) {
317 // When the metric wants to do random sampling and there is already one gauge atom for the
318 // current bucket, do not do it again.
319 case GaugeMetric::RANDOM_ONE_SAMPLE: {
320 triggerPuller = mCondition && mCurrentSlicedBucket->empty();
321 break;
322 }
323 case GaugeMetric::ALL_CONDITION_CHANGES: {
324 triggerPuller = true;
325 break;
326 }
Yangsterec3c7a32018-05-09 15:51:07 -0700327 case GaugeMetric::CONDITION_CHANGE_TO_TRUE: {
328 triggerPuller = mCondition;
329 break;
330 }
Yangster-mac34ea1102018-01-29 12:40:55 -0800331 default:
332 break;
333 }
334 if (!triggerPuller) {
Yao Chen6a8c7992017-11-29 20:02:07 +0000335 return;
336 }
Yangster-mac34ea1102018-01-29 12:40:55 -0800337
Yao Chen6a8c7992017-11-29 20:02:07 +0000338 vector<std::shared_ptr<LogEvent>> allData;
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700339 if (!mStatsPullerManager->Pull(mPullTagId, timestampNs, &allData)) {
Yao Chen427d3722018-03-22 15:21:52 -0700340 ALOGE("Gauge Stats puller failed for tag: %d", mPullTagId);
Yao Chen6a8c7992017-11-29 20:02:07 +0000341 return;
342 }
Yao Chen427d3722018-03-22 15:21:52 -0700343
Yangster1d4d6862017-10-31 12:58:51 -0700344 for (const auto& data : allData) {
Chenjie Yua7259ab2017-12-10 08:31:05 -0800345 onMatchedLogEventLocked(0, *data);
Yangster1d4d6862017-10-31 12:58:51 -0700346 }
Yangster1d4d6862017-10-31 12:58:51 -0700347}
348
Yao Chen427d3722018-03-22 15:21:52 -0700349void GaugeMetricProducer::onConditionChangedLocked(const bool conditionMet,
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700350 const int64_t eventTimeNs) {
Yao Chen427d3722018-03-22 15:21:52 -0700351 VLOG("GaugeMetric %lld onConditionChanged", (long long)mMetricId);
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700352 flushIfNeededLocked(eventTimeNs);
Yao Chen427d3722018-03-22 15:21:52 -0700353 mCondition = conditionMet;
354
Yangsterec3c7a32018-05-09 15:51:07 -0700355 if (mPullTagId != -1) {
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700356 pullLocked(eventTimeNs);
Yao Chen427d3722018-03-22 15:21:52 -0700357 } // else: Push mode. No need to proactively pull the gauge data.
358}
359
360void GaugeMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700361 const int64_t eventTimeNs) {
Yao Chen427d3722018-03-22 15:21:52 -0700362 VLOG("GaugeMetric %lld onSlicedConditionMayChange overall condition %d", (long long)mMetricId,
363 overallCondition);
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700364 flushIfNeededLocked(eventTimeNs);
Yao Chen427d3722018-03-22 15:21:52 -0700365 // If the condition is sliced, mCondition is true if any of the dimensions is true. And we will
366 // pull for every dimension.
367 mCondition = overallCondition;
368 if (mPullTagId != -1) {
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700369 pullLocked(eventTimeNs);
Yao Chen427d3722018-03-22 15:21:52 -0700370 } // else: Push mode. No need to proactively pull the gauge data.
Yangster1d4d6862017-10-31 12:58:51 -0700371}
372
Yao Chen8a8d16c2018-02-08 14:50:40 -0800373std::shared_ptr<vector<FieldValue>> GaugeMetricProducer::getGaugeFields(const LogEvent& event) {
374 if (mFieldMatchers.size() > 0) {
375 std::shared_ptr<vector<FieldValue>> gaugeFields = std::make_shared<vector<FieldValue>>();
376 filterGaugeValues(mFieldMatchers, event.getValues(), gaugeFields.get());
377 return gaugeFields;
378 } else {
379 return std::make_shared<vector<FieldValue>>(event.getValues());
Yangster1d4d6862017-10-31 12:58:51 -0700380 }
381}
382
383void GaugeMetricProducer::onDataPulled(const std::vector<std::shared_ptr<LogEvent>>& allData) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800384 std::lock_guard<std::mutex> lock(mMutex);
Chenjie Yud9dfda72017-12-11 17:41:20 -0800385 if (allData.size() == 0) {
386 return;
387 }
Yangster1d4d6862017-10-31 12:58:51 -0700388 for (const auto& data : allData) {
Chenjie Yua7259ab2017-12-10 08:31:05 -0800389 onMatchedLogEventLocked(0, *data);
Yangster1d4d6862017-10-31 12:58:51 -0700390 }
Yangster1d4d6862017-10-31 12:58:51 -0700391}
392
Yangster-mac93694462018-01-22 20:49:31 -0800393bool GaugeMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800394 if (mCurrentSlicedBucket->find(newKey) != mCurrentSlicedBucket->end()) {
395 return false;
396 }
397 // 1. Report the tuple count if the tuple count > soft limit
Chenjie Yuc5875052018-03-09 10:13:11 -0800398 if (mCurrentSlicedBucket->size() > mDimensionSoftLimit - 1) {
Yao Chenb3561512017-11-21 18:07:17 -0800399 size_t newTupleCount = mCurrentSlicedBucket->size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800400 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800401 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
Chenjie Yuc5875052018-03-09 10:13:11 -0800402 if (newTupleCount > mDimensionHardLimit) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800403 ALOGE("GaugeMetric %lld dropping data for dimension key %s",
Yangster13fb7e42018-03-07 17:30:49 -0800404 (long long)mMetricId, newKey.toString().c_str());
Yao Chenb3561512017-11-21 18:07:17 -0800405 return true;
406 }
407 }
408
409 return false;
410}
411
Yangsterf2bee6f2017-11-29 12:01:05 -0800412void GaugeMetricProducer::onMatchedLogEventInternalLocked(
Yangster-mac93694462018-01-22 20:49:31 -0800413 const size_t matcherIndex, const MetricDimensionKey& eventKey,
Yangster-mac20877162017-12-22 17:19:39 -0800414 const ConditionKey& conditionKey, bool condition,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800415 const LogEvent& event) {
Yangster1d4d6862017-10-31 12:58:51 -0700416 if (condition == false) {
417 return;
418 }
Yangster-macb142cc82018-03-30 15:22:08 -0700419 int64_t eventTimeNs = event.GetElapsedTimestampNs();
Yao Chen8a8d16c2018-02-08 14:50:40 -0800420 mTagId = event.GetTagId();
Yangster1d4d6862017-10-31 12:58:51 -0700421 if (eventTimeNs < mCurrentBucketStartTimeNs) {
Yao Chen427d3722018-03-22 15:21:52 -0700422 VLOG("Gauge Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
Yangster1d4d6862017-10-31 12:58:51 -0700423 (long long)mCurrentBucketStartTimeNs);
424 return;
425 }
Chenjie Yud9dfda72017-12-11 17:41:20 -0800426 flushIfNeededLocked(eventTimeNs);
Yao Chen6a8c7992017-11-29 20:02:07 +0000427
Yangster-mac34ea1102018-01-29 12:40:55 -0800428 // When gauge metric wants to randomly sample the output atom, we just simply use the first
429 // gauge in the given bucket.
430 if (mCurrentSlicedBucket->find(eventKey) != mCurrentSlicedBucket->end() &&
431 mSamplingType == GaugeMetric::RANDOM_ONE_SAMPLE) {
Yangster1d4d6862017-10-31 12:58:51 -0700432 return;
433 }
Chenjie Yud9dfda72017-12-11 17:41:20 -0800434 if (hitGuardRailLocked(eventKey)) {
435 return;
Yao Chen6a8c7992017-11-29 20:02:07 +0000436 }
Yangster-mac50b0c9a2018-05-10 17:13:12 -0700437 if ((*mCurrentSlicedBucket)[eventKey].size() >= mGaugeAtomsPerDimensionLimit) {
438 return;
439 }
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700440 GaugeAtom gaugeAtom(getGaugeFields(event), eventTimeNs, getWallClockNs());
Yangster-mac34ea1102018-01-29 12:40:55 -0800441 (*mCurrentSlicedBucket)[eventKey].push_back(gaugeAtom);
Chenjie Yud9dfda72017-12-11 17:41:20 -0800442 // Anomaly detection on gauge metric only works when there is one numeric
443 // field specified.
444 if (mAnomalyTrackers.size() > 0) {
Yangster-mac34ea1102018-01-29 12:40:55 -0800445 if (gaugeAtom.mFields->size() == 1) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800446 const Value& value = gaugeAtom.mFields->begin()->mValue;
Chenjie Yud9dfda72017-12-11 17:41:20 -0800447 long gaugeVal = 0;
Yao Chen8a8d16c2018-02-08 14:50:40 -0800448 if (value.getType() == INT) {
449 gaugeVal = (long)value.int_value;
450 } else if (value.getType() == LONG) {
451 gaugeVal = value.long_value;
Chenjie Yud9dfda72017-12-11 17:41:20 -0800452 }
453 for (auto& tracker : mAnomalyTrackers) {
454 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, eventKey,
455 gaugeVal);
456 }
457 }
458 }
459}
460
461void GaugeMetricProducer::updateCurrentSlicedBucketForAnomaly() {
Chenjie Yud9dfda72017-12-11 17:41:20 -0800462 for (const auto& slice : *mCurrentSlicedBucket) {
Yao Chen8a8d16c2018-02-08 14:50:40 -0800463 if (slice.second.empty()) {
Yangster-mac34ea1102018-01-29 12:40:55 -0800464 continue;
465 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800466 const Value& value = slice.second.front().mFields->front().mValue;
Chenjie Yud9dfda72017-12-11 17:41:20 -0800467 long gaugeVal = 0;
Yao Chen8a8d16c2018-02-08 14:50:40 -0800468 if (value.getType() == INT) {
469 gaugeVal = (long)value.int_value;
470 } else if (value.getType() == LONG) {
471 gaugeVal = value.long_value;
Chenjie Yud9dfda72017-12-11 17:41:20 -0800472 }
473 (*mCurrentSlicedBucketForAnomaly)[slice.first] = gaugeVal;
Yangster1d4d6862017-10-31 12:58:51 -0700474 }
475}
476
Yangster-macb142cc82018-03-30 15:22:08 -0700477void GaugeMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
Yao Chen06dba5d2018-01-26 13:38:16 -0800478 flushIfNeededLocked(dropTimeNs);
479 mPastBuckets.clear();
480}
481
Yangster1d4d6862017-10-31 12:58:51 -0700482// When a new matched event comes in, we check if event falls into the current
483// bucket. If not, flush the old counter to past buckets and initialize the new
484// bucket.
485// if data is pushed, onMatchedLogEvent will only be called through onConditionChanged() inside
486// the GaugeMetricProducer while holding the lock.
Yangster-macb142cc82018-03-30 15:22:08 -0700487void GaugeMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
488 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800489
490 if (eventTimeNs < currentBucketEndTimeNs) {
Yao Chen427d3722018-03-22 15:21:52 -0700491 VLOG("Gauge eventTime is %lld, less than next bucket start time %lld",
492 (long long)eventTimeNs, (long long)(mCurrentBucketStartTimeNs + mBucketSizeNs));
Yangster1d4d6862017-10-31 12:58:51 -0700493 return;
494 }
495
David Chen27785a82018-01-19 17:06:45 -0800496 flushCurrentBucketLocked(eventTimeNs);
497
498 // Adjusts the bucket start and end times.
499 int64_t numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
500 mCurrentBucketStartTimeNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
501 mCurrentBucketNum += numBucketsForward;
Yao Chen427d3722018-03-22 15:21:52 -0700502 VLOG("Gauge metric %lld: new bucket start time: %lld", (long long)mMetricId,
David Chen27785a82018-01-19 17:06:45 -0800503 (long long)mCurrentBucketStartTimeNs);
504}
505
Yangster-macb142cc82018-03-30 15:22:08 -0700506void GaugeMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs) {
507 int64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800508
yro2b0f8862017-11-06 14:27:31 -0800509 GaugeBucket info;
510 info.mBucketStartNs = mCurrentBucketStartTimeNs;
David Chen27785a82018-01-19 17:06:45 -0800511 if (eventTimeNs < fullBucketEndTimeNs) {
512 info.mBucketEndNs = eventTimeNs;
513 } else {
514 info.mBucketEndNs = fullBucketEndTimeNs;
515 }
Yangster1d4d6862017-10-31 12:58:51 -0700516
David Chen81245fd2018-04-12 14:33:37 -0700517 if (info.mBucketEndNs - mCurrentBucketStartTimeNs >= mMinBucketSizeNs) {
518 for (const auto& slice : *mCurrentSlicedBucket) {
519 info.mGaugeAtoms = slice.second;
520 auto& bucketList = mPastBuckets[slice.first];
521 bucketList.push_back(info);
522 VLOG("Gauge gauge metric %lld, dump key value: %s", (long long)mMetricId,
523 slice.first.toString().c_str());
524 }
525 } else {
526 mSkippedBuckets.emplace_back(info.mBucketStartNs, info.mBucketEndNs);
Yangster1d4d6862017-10-31 12:58:51 -0700527 }
Yangster1d4d6862017-10-31 12:58:51 -0700528
David Chen27785a82018-01-19 17:06:45 -0800529 // If we have anomaly trackers, we need to update the partial bucket values.
Chenjie Yud9dfda72017-12-11 17:41:20 -0800530 if (mAnomalyTrackers.size() > 0) {
531 updateCurrentSlicedBucketForAnomaly();
David Chen27785a82018-01-19 17:06:45 -0800532
533 if (eventTimeNs > fullBucketEndTimeNs) {
534 // This is known to be a full bucket, so send this data to the anomaly tracker.
535 for (auto& tracker : mAnomalyTrackers) {
536 tracker->addPastBucket(mCurrentSlicedBucketForAnomaly, mCurrentBucketNum);
537 }
538 mCurrentSlicedBucketForAnomaly = std::make_shared<DimToValMap>();
Chenjie Yud9dfda72017-12-11 17:41:20 -0800539 }
Yangster-mace2cd6d52017-11-09 20:38:30 -0800540 }
541
Yangster-mac34ea1102018-01-29 12:40:55 -0800542 mCurrentSlicedBucket = std::make_shared<DimToGaugeAtomsMap>();
Yangster1d4d6862017-10-31 12:58:51 -0700543}
544
Yangsterf2bee6f2017-11-29 12:01:05 -0800545size_t GaugeMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800546 size_t totalSize = 0;
547 for (const auto& pair : mPastBuckets) {
Yangster-macb2532da2018-04-11 13:55:04 -0700548 for (const auto& bucket : pair.second) {
549 totalSize += bucket.mGaugeAtoms.size() * sizeof(GaugeAtom);
550 for (const auto& atom : bucket.mGaugeAtoms) {
551 if (atom.mFields != nullptr) {
552 totalSize += atom.mFields->size() * sizeof(FieldValue);
553 }
554 }
555 }
Yangster-mace2cd6d52017-11-09 20:38:30 -0800556 }
557 return totalSize;
yro2b0f8862017-11-06 14:27:31 -0800558}
559
Yangster1d4d6862017-10-31 12:58:51 -0700560} // namespace statsd
561} // namespace os
562} // namespace android