1 /*
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 
17 #define DEBUG false  // STOPSHIP if true
18 #include "Log.h"
19 
20 #include "../guardrail/StatsdStats.h"
21 #include "GaugeMetricProducer.h"
22 #include "../stats_log_util.h"
23 
24 using android::util::FIELD_COUNT_REPEATED;
25 using android::util::FIELD_TYPE_BOOL;
26 using android::util::FIELD_TYPE_FLOAT;
27 using android::util::FIELD_TYPE_INT32;
28 using android::util::FIELD_TYPE_INT64;
29 using android::util::FIELD_TYPE_MESSAGE;
30 using android::util::FIELD_TYPE_STRING;
31 using android::util::ProtoOutputStream;
32 using std::map;
33 using std::string;
34 using std::unordered_map;
35 using std::vector;
36 using std::make_shared;
37 using std::shared_ptr;
38 
39 namespace android {
40 namespace os {
41 namespace statsd {
42 
43 // for StatsLogReport
44 const int FIELD_ID_ID = 1;
45 const int FIELD_ID_GAUGE_METRICS = 8;
46 const int FIELD_ID_TIME_BASE = 9;
47 const int FIELD_ID_BUCKET_SIZE = 10;
48 const int FIELD_ID_DIMENSION_PATH_IN_WHAT = 11;
49 const int FIELD_ID_DIMENSION_PATH_IN_CONDITION = 12;
50 const int FIELD_ID_IS_ACTIVE = 14;
51 // for GaugeMetricDataWrapper
52 const int FIELD_ID_DATA = 1;
53 const int FIELD_ID_SKIPPED = 2;
54 const int FIELD_ID_SKIPPED_START_MILLIS = 3;
55 const int FIELD_ID_SKIPPED_END_MILLIS = 4;
56 // for GaugeMetricData
57 const int FIELD_ID_DIMENSION_IN_WHAT = 1;
58 const int FIELD_ID_DIMENSION_IN_CONDITION = 2;
59 const int FIELD_ID_BUCKET_INFO = 3;
60 const int FIELD_ID_DIMENSION_LEAF_IN_WHAT = 4;
61 const int FIELD_ID_DIMENSION_LEAF_IN_CONDITION = 5;
62 // for GaugeBucketInfo
63 const int FIELD_ID_ATOM = 3;
64 const int FIELD_ID_ELAPSED_ATOM_TIMESTAMP = 4;
65 const int FIELD_ID_BUCKET_NUM = 6;
66 const int FIELD_ID_START_BUCKET_ELAPSED_MILLIS = 7;
67 const int FIELD_ID_END_BUCKET_ELAPSED_MILLIS = 8;
68 
GaugeMetricProducer(const ConfigKey & key,const GaugeMetric & metric,const int conditionIndex,const sp<ConditionWizard> & wizard,const int whatMatcherIndex,const sp<EventMatcherWizard> & matcherWizard,const int pullTagId,const int triggerAtomId,const int atomId,const int64_t timeBaseNs,const int64_t startTimeNs,const sp<StatsPullerManager> & pullerManager)69 GaugeMetricProducer::GaugeMetricProducer(
70         const ConfigKey& key, const GaugeMetric& metric, const int conditionIndex,
71         const sp<ConditionWizard>& wizard, const int whatMatcherIndex,
72         const sp<EventMatcherWizard>& matcherWizard, const int pullTagId, const int triggerAtomId,
73         const int atomId, const int64_t timeBaseNs, const int64_t startTimeNs,
74         const sp<StatsPullerManager>& pullerManager)
75     : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, wizard),
76       mWhatMatcherIndex(whatMatcherIndex),
77       mEventMatcherWizard(matcherWizard),
78       mPullerManager(pullerManager),
79       mPullTagId(pullTagId),
80       mTriggerAtomId(triggerAtomId),
81       mAtomId(atomId),
82       mIsPulled(pullTagId != -1),
83       mMinBucketSizeNs(metric.min_bucket_size_nanos()),
84       mMaxPullDelayNs(metric.max_pull_delay_sec() > 0 ? metric.max_pull_delay_sec() * NS_PER_SEC
85                                                       : StatsdStats::kPullMaxDelayNs),
86       mDimensionSoftLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
87                                           StatsdStats::kAtomDimensionKeySizeLimitMap.end()
88                                   ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).first
89                                   : StatsdStats::kDimensionKeySizeSoftLimit),
90       mDimensionHardLimit(StatsdStats::kAtomDimensionKeySizeLimitMap.find(pullTagId) !=
91                                           StatsdStats::kAtomDimensionKeySizeLimitMap.end()
92                                   ? StatsdStats::kAtomDimensionKeySizeLimitMap.at(pullTagId).second
93                                   : StatsdStats::kDimensionKeySizeHardLimit),
94       mGaugeAtomsPerDimensionLimit(metric.max_num_gauge_atoms_per_bucket()),
95       mSplitBucketForAppUpgrade(metric.split_bucket_for_app_upgrade()) {
96     mCurrentSlicedBucket = std::make_shared<DimToGaugeAtomsMap>();
97     mCurrentSlicedBucketForAnomaly = std::make_shared<DimToValMap>();
98     int64_t bucketSizeMills = 0;
99     if (metric.has_bucket()) {
100         bucketSizeMills = TimeUnitToBucketSizeInMillisGuardrailed(key.GetUid(), metric.bucket());
101     } else {
102         bucketSizeMills = TimeUnitToBucketSizeInMillis(ONE_HOUR);
103     }
104     mBucketSizeNs = bucketSizeMills * 1000000;
105 
106     mSamplingType = metric.sampling_type();
107     if (!metric.gauge_fields_filter().include_all()) {
108         translateFieldMatcher(metric.gauge_fields_filter().fields(), &mFieldMatchers);
109     }
110 
111     if (metric.has_dimensions_in_what()) {
112         translateFieldMatcher(metric.dimensions_in_what(), &mDimensionsInWhat);
113         mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
114     }
115 
116     if (metric.has_dimensions_in_condition()) {
117         translateFieldMatcher(metric.dimensions_in_condition(), &mDimensionsInCondition);
118     }
119 
120     if (metric.links().size() > 0) {
121         for (const auto& link : metric.links()) {
122             Metric2Condition mc;
123             mc.conditionId = link.condition();
124             translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
125             translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
126             mMetric2ConditionLinks.push_back(mc);
127         }
128     }
129     mConditionSliced = (metric.links().size() > 0) || (mDimensionsInCondition.size() > 0);
130     mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what()) ||
131             HasPositionALL(metric.dimensions_in_condition());
132 
133     flushIfNeededLocked(startTimeNs);
134     // Kicks off the puller immediately.
135     if (mIsPulled && mSamplingType == GaugeMetric::RANDOM_ONE_SAMPLE) {
136         mPullerManager->RegisterReceiver(mPullTagId, this, getCurrentBucketEndTimeNs(),
137                                          mBucketSizeNs);
138     }
139 
140     // Adjust start for partial bucket
141     mCurrentBucketStartTimeNs = startTimeNs;
142 
143     VLOG("Gauge metric %lld created. bucket size %lld start_time: %lld sliced %d",
144          (long long)metric.id(), (long long)mBucketSizeNs, (long long)mTimeBaseNs,
145          mConditionSliced);
146 }
147 
~GaugeMetricProducer()148 GaugeMetricProducer::~GaugeMetricProducer() {
149     VLOG("~GaugeMetricProducer() called");
150     if (mIsPulled && mSamplingType == GaugeMetric::RANDOM_ONE_SAMPLE) {
151         mPullerManager->UnRegisterReceiver(mPullTagId, this);
152     }
153 }
154 
dumpStatesLocked(FILE * out,bool verbose) const155 void 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 
clearPastBucketsLocked(const int64_t dumpTimeNs)173 void GaugeMetricProducer::clearPastBucketsLocked(const int64_t dumpTimeNs) {
174     flushIfNeededLocked(dumpTimeNs);
175     mPastBuckets.clear();
176     mSkippedBuckets.clear();
177 }
178 
onDumpReportLocked(const int64_t dumpTimeNs,const bool include_current_partial_bucket,const bool erase_data,const DumpLatency dumpLatency,std::set<string> * str_set,ProtoOutputStream * protoOutput)179 void GaugeMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
180                                              const bool include_current_partial_bucket,
181                                              const bool erase_data,
182                                              const DumpLatency dumpLatency,
183                                              std::set<string> *str_set,
184                                              ProtoOutputStream* protoOutput) {
185     VLOG("Gauge metric %lld report now...", (long long)mMetricId);
186     if (include_current_partial_bucket) {
187         flushLocked(dumpTimeNs);
188     } else {
189         flushIfNeededLocked(dumpTimeNs);
190     }
191 
192     protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
193     protoOutput->write(FIELD_TYPE_BOOL | FIELD_ID_IS_ACTIVE, isActiveLocked());
194 
195     if (mPastBuckets.empty()) {
196         return;
197     }
198 
199     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 
218     uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_GAUGE_METRICS);
219 
220     for (const auto& pair : mSkippedBuckets) {
221         uint64_t wrapperToken =
222                 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_SKIPPED);
223         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)));
227         protoOutput->end(wrapperToken);
228     }
229 
230     for (const auto& pair : mPastBuckets) {
231         const MetricDimensionKey& dimensionKey = pair.first;
232 
233         VLOG("Gauge dimension key %s", dimensionKey.toString().c_str());
234         uint64_t wrapperToken =
235                 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
236 
237         // First fill dimension.
238         if (mSliceByPositionALL) {
239             uint64_t dimensionToken = protoOutput->start(
240                     FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
241             writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), str_set, protoOutput);
242             protoOutput->end(dimensionToken);
243 
244             if (dimensionKey.hasDimensionKeyInCondition()) {
245                 uint64_t dimensionInConditionToken = protoOutput->start(
246                         FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_CONDITION);
247                 writeDimensionToProto(dimensionKey.getDimensionKeyInCondition(),
248                                       str_set, protoOutput);
249                 protoOutput->end(dimensionInConditionToken);
250             }
251         } else {
252             writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInWhat(),
253                                            FIELD_ID_DIMENSION_LEAF_IN_WHAT, str_set, protoOutput);
254             if (dimensionKey.hasDimensionKeyInCondition()) {
255                 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInCondition(),
256                                                FIELD_ID_DIMENSION_LEAF_IN_CONDITION,
257                                                str_set, protoOutput);
258             }
259         }
260 
261         // Then fill bucket_info (GaugeBucketInfo).
262         for (const auto& bucket : pair.second) {
263             uint64_t bucketInfoToken = protoOutput->start(
264                     FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
265 
266             if (bucket.mBucketEndNs - bucket.mBucketStartNs != mBucketSizeNs) {
267                 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_MILLIS,
268                                    (long long)NanoToMillis(bucket.mBucketStartNs));
269                 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_MILLIS,
270                                    (long long)NanoToMillis(bucket.mBucketEndNs));
271             } else {
272                 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_NUM,
273                                    (long long)(getBucketNumFromEndTimeNs(bucket.mBucketEndNs)));
274             }
275 
276             if (!bucket.mGaugeAtoms.empty()) {
277                 for (const auto& atom : bucket.mGaugeAtoms) {
278                     uint64_t atomsToken =
279                         protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
280                                            FIELD_ID_ATOM);
281                     writeFieldValueTreeToStream(mAtomId, *(atom.mFields), protoOutput);
282                     protoOutput->end(atomsToken);
283                 }
284                 for (const auto& atom : bucket.mGaugeAtoms) {
285                     const int64_t elapsedTimestampNs =
286                             truncateTimestampIfNecessary(mAtomId, atom.mElapsedTimestamps);
287                     protoOutput->write(
288                         FIELD_TYPE_INT64 | FIELD_COUNT_REPEATED | FIELD_ID_ELAPSED_ATOM_TIMESTAMP,
289                         (long long)elapsedTimestampNs);
290                 }
291             }
292             protoOutput->end(bucketInfoToken);
293             VLOG("Gauge \t bucket [%lld - %lld] includes %d atoms.",
294                  (long long)bucket.mBucketStartNs, (long long)bucket.mBucketEndNs,
295                  (int)bucket.mGaugeAtoms.size());
296         }
297         protoOutput->end(wrapperToken);
298     }
299     protoOutput->end(protoToken);
300 
301 
302     if (erase_data) {
303         mPastBuckets.clear();
304         mSkippedBuckets.clear();
305     }
306 }
307 
prepareFirstBucketLocked()308 void GaugeMetricProducer::prepareFirstBucketLocked() {
309     if (mIsActive && mIsPulled && mSamplingType == GaugeMetric::RANDOM_ONE_SAMPLE) {
310         pullAndMatchEventsLocked(mCurrentBucketStartTimeNs);
311     }
312 }
313 
pullAndMatchEventsLocked(const int64_t timestampNs)314 void GaugeMetricProducer::pullAndMatchEventsLocked(const int64_t timestampNs) {
315     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 == ConditionState::kTrue && mCurrentSlicedBucket->empty();
321             break;
322         }
323         case GaugeMetric::CONDITION_CHANGE_TO_TRUE: {
324             triggerPuller = mCondition == ConditionState::kTrue;
325             break;
326         }
327         case GaugeMetric::FIRST_N_SAMPLES: {
328             triggerPuller = mCondition == ConditionState::kTrue;
329             break;
330         }
331         default:
332             break;
333     }
334     if (!triggerPuller) {
335         return;
336     }
337     vector<std::shared_ptr<LogEvent>> allData;
338     if (!mPullerManager->Pull(mPullTagId, &allData)) {
339         ALOGE("Gauge Stats puller failed for tag: %d at %lld", mPullTagId, (long long)timestampNs);
340         return;
341     }
342     const int64_t pullDelayNs = getElapsedRealtimeNs() - timestampNs;
343     if (pullDelayNs > mMaxPullDelayNs) {
344         ALOGE("Pull finish too late for atom %d", mPullTagId);
345         StatsdStats::getInstance().notePullExceedMaxDelay(mPullTagId);
346         StatsdStats::getInstance().notePullDelay(mPullTagId, pullDelayNs);
347         return;
348     }
349     StatsdStats::getInstance().notePullDelay(mPullTagId, pullDelayNs);
350     for (const auto& data : allData) {
351         LogEvent localCopy = data->makeCopy();
352         localCopy.setElapsedTimestampNs(timestampNs);
353         if (mEventMatcherWizard->matchLogEvent(localCopy, mWhatMatcherIndex) ==
354             MatchingState::kMatched) {
355             onMatchedLogEventLocked(mWhatMatcherIndex, localCopy);
356         }
357     }
358 }
359 
onActiveStateChangedLocked(const int64_t & eventTimeNs)360 void GaugeMetricProducer::onActiveStateChangedLocked(const int64_t& eventTimeNs) {
361     MetricProducer::onActiveStateChangedLocked(eventTimeNs);
362     if (ConditionState::kTrue != mCondition || !mIsPulled) {
363         return;
364     }
365     if (mTriggerAtomId == -1 || (mIsActive && mSamplingType == GaugeMetric::RANDOM_ONE_SAMPLE)) {
366         pullAndMatchEventsLocked(eventTimeNs);
367     }
368 
369 }
370 
onConditionChangedLocked(const bool conditionMet,const int64_t eventTimeNs)371 void GaugeMetricProducer::onConditionChangedLocked(const bool conditionMet,
372                                                    const int64_t eventTimeNs) {
373     VLOG("GaugeMetric %lld onConditionChanged", (long long)mMetricId);
374 
375     mCondition = conditionMet ? ConditionState::kTrue : ConditionState::kFalse;
376     if (!mIsActive) {
377         return;
378     }
379 
380     flushIfNeededLocked(eventTimeNs);
381     if (mIsPulled && mTriggerAtomId == -1) {
382         pullAndMatchEventsLocked(eventTimeNs);
383     }  // else: Push mode. No need to proactively pull the gauge data.
384 }
385 
onSlicedConditionMayChangeLocked(bool overallCondition,const int64_t eventTimeNs)386 void GaugeMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
387                                                            const int64_t eventTimeNs) {
388     VLOG("GaugeMetric %lld onSlicedConditionMayChange overall condition %d", (long long)mMetricId,
389          overallCondition);
390     mCondition = overallCondition ? ConditionState::kTrue : ConditionState::kFalse;
391     if (!mIsActive) {
392         return;
393     }
394 
395     flushIfNeededLocked(eventTimeNs);
396     // If the condition is sliced, mCondition is true if any of the dimensions is true. And we will
397     // pull for every dimension.
398     if (mIsPulled && mTriggerAtomId == -1) {
399         pullAndMatchEventsLocked(eventTimeNs);
400     }  // else: Push mode. No need to proactively pull the gauge data.
401 }
402 
getGaugeFields(const LogEvent & event)403 std::shared_ptr<vector<FieldValue>> GaugeMetricProducer::getGaugeFields(const LogEvent& event) {
404     std::shared_ptr<vector<FieldValue>> gaugeFields;
405     if (mFieldMatchers.size() > 0) {
406         gaugeFields = std::make_shared<vector<FieldValue>>();
407         filterGaugeValues(mFieldMatchers, event.getValues(), gaugeFields.get());
408     } else {
409         gaugeFields = std::make_shared<vector<FieldValue>>(event.getValues());
410     }
411     // Trim all dimension fields from output. Dimensions will appear in output report and will
412     // benefit from dictionary encoding. For large pulled atoms, this can give the benefit of
413     // optional repeated field.
414     for (const auto& field : mDimensionsInWhat) {
415         for (auto it = gaugeFields->begin(); it != gaugeFields->end();) {
416             if (it->mField.matches(field)) {
417                 it = gaugeFields->erase(it);
418             } else {
419                 it++;
420             }
421         }
422     }
423     return gaugeFields;
424 }
425 
onDataPulled(const std::vector<std::shared_ptr<LogEvent>> & allData,bool pullSuccess,int64_t originalPullTimeNs)426 void GaugeMetricProducer::onDataPulled(const std::vector<std::shared_ptr<LogEvent>>& allData,
427                                        bool pullSuccess, int64_t originalPullTimeNs) {
428     std::lock_guard<std::mutex> lock(mMutex);
429     if (!pullSuccess || allData.size() == 0) {
430         return;
431     }
432     for (const auto& data : allData) {
433         if (mEventMatcherWizard->matchLogEvent(
434                 *data, mWhatMatcherIndex) == MatchingState::kMatched) {
435             onMatchedLogEventLocked(mWhatMatcherIndex, *data);
436         }
437     }
438 }
439 
hitGuardRailLocked(const MetricDimensionKey & newKey)440 bool GaugeMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
441     if (mCurrentSlicedBucket->find(newKey) != mCurrentSlicedBucket->end()) {
442         return false;
443     }
444     // 1. Report the tuple count if the tuple count > soft limit
445     if (mCurrentSlicedBucket->size() > mDimensionSoftLimit - 1) {
446         size_t newTupleCount = mCurrentSlicedBucket->size() + 1;
447         StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
448         // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
449         if (newTupleCount > mDimensionHardLimit) {
450             ALOGE("GaugeMetric %lld dropping data for dimension key %s",
451                 (long long)mMetricId, newKey.toString().c_str());
452             return true;
453         }
454     }
455 
456     return false;
457 }
458 
onMatchedLogEventInternalLocked(const size_t matcherIndex,const MetricDimensionKey & eventKey,const ConditionKey & conditionKey,bool condition,const LogEvent & event)459 void GaugeMetricProducer::onMatchedLogEventInternalLocked(
460         const size_t matcherIndex, const MetricDimensionKey& eventKey,
461         const ConditionKey& conditionKey, bool condition,
462         const LogEvent& event) {
463     if (condition == false) {
464         return;
465     }
466     int64_t eventTimeNs = event.GetElapsedTimestampNs();
467     if (eventTimeNs < mCurrentBucketStartTimeNs) {
468         VLOG("Gauge Skip event due to late arrival: %lld vs %lld", (long long)eventTimeNs,
469              (long long)mCurrentBucketStartTimeNs);
470         return;
471     }
472     flushIfNeededLocked(eventTimeNs);
473 
474     if (mTriggerAtomId == event.GetTagId()) {
475         pullAndMatchEventsLocked(eventTimeNs);
476         return;
477     }
478 
479     // When gauge metric wants to randomly sample the output atom, we just simply use the first
480     // gauge in the given bucket.
481     if (mCurrentSlicedBucket->find(eventKey) != mCurrentSlicedBucket->end() &&
482         mSamplingType == GaugeMetric::RANDOM_ONE_SAMPLE) {
483         return;
484     }
485     if (hitGuardRailLocked(eventKey)) {
486         return;
487     }
488     if ((*mCurrentSlicedBucket)[eventKey].size() >= mGaugeAtomsPerDimensionLimit) {
489         return;
490     }
491     GaugeAtom gaugeAtom(getGaugeFields(event), eventTimeNs);
492     (*mCurrentSlicedBucket)[eventKey].push_back(gaugeAtom);
493     // Anomaly detection on gauge metric only works when there is one numeric
494     // field specified.
495     if (mAnomalyTrackers.size() > 0) {
496         if (gaugeAtom.mFields->size() == 1) {
497             const Value& value = gaugeAtom.mFields->begin()->mValue;
498             long gaugeVal = 0;
499             if (value.getType() == INT) {
500                 gaugeVal = (long)value.int_value;
501             } else if (value.getType() == LONG) {
502                 gaugeVal = value.long_value;
503             }
504             for (auto& tracker : mAnomalyTrackers) {
505                 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, mMetricId,
506                                                  eventKey, gaugeVal);
507             }
508         }
509     }
510 }
511 
updateCurrentSlicedBucketForAnomaly()512 void GaugeMetricProducer::updateCurrentSlicedBucketForAnomaly() {
513     for (const auto& slice : *mCurrentSlicedBucket) {
514         if (slice.second.empty()) {
515             continue;
516         }
517         const Value& value = slice.second.front().mFields->front().mValue;
518         long gaugeVal = 0;
519         if (value.getType() == INT) {
520             gaugeVal = (long)value.int_value;
521         } else if (value.getType() == LONG) {
522             gaugeVal = value.long_value;
523         }
524         (*mCurrentSlicedBucketForAnomaly)[slice.first] = gaugeVal;
525     }
526 }
527 
dropDataLocked(const int64_t dropTimeNs)528 void GaugeMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
529     flushIfNeededLocked(dropTimeNs);
530     StatsdStats::getInstance().noteBucketDropped(mMetricId);
531     mPastBuckets.clear();
532 }
533 
534 // When a new matched event comes in, we check if event falls into the current
535 // bucket. If not, flush the old counter to past buckets and initialize the new
536 // bucket.
537 // if data is pushed, onMatchedLogEvent will only be called through onConditionChanged() inside
538 // the GaugeMetricProducer while holding the lock.
flushIfNeededLocked(const int64_t & eventTimeNs)539 void GaugeMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
540     int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
541 
542     if (eventTimeNs < currentBucketEndTimeNs) {
543         VLOG("Gauge eventTime is %lld, less than next bucket start time %lld",
544              (long long)eventTimeNs, (long long)(mCurrentBucketStartTimeNs + mBucketSizeNs));
545         return;
546     }
547 
548     // Adjusts the bucket start and end times.
549     int64_t numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
550     int64_t nextBucketNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
551     flushCurrentBucketLocked(eventTimeNs, nextBucketNs);
552 
553     mCurrentBucketNum += numBucketsForward;
554     VLOG("Gauge metric %lld: new bucket start time: %lld", (long long)mMetricId,
555          (long long)mCurrentBucketStartTimeNs);
556 }
557 
flushCurrentBucketLocked(const int64_t & eventTimeNs,const int64_t & nextBucketStartTimeNs)558 void GaugeMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs,
559                                                    const int64_t& nextBucketStartTimeNs) {
560     int64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
561 
562     GaugeBucket info;
563     info.mBucketStartNs = mCurrentBucketStartTimeNs;
564     if (eventTimeNs < fullBucketEndTimeNs) {
565         info.mBucketEndNs = eventTimeNs;
566     } else {
567         info.mBucketEndNs = fullBucketEndTimeNs;
568     }
569 
570     if (info.mBucketEndNs - mCurrentBucketStartTimeNs >= mMinBucketSizeNs) {
571         for (const auto& slice : *mCurrentSlicedBucket) {
572             info.mGaugeAtoms = slice.second;
573             auto& bucketList = mPastBuckets[slice.first];
574             bucketList.push_back(info);
575             VLOG("Gauge gauge metric %lld, dump key value: %s", (long long)mMetricId,
576                  slice.first.toString().c_str());
577         }
578     } else {
579         mSkippedBuckets.emplace_back(info.mBucketStartNs, info.mBucketEndNs);
580     }
581 
582     // If we have anomaly trackers, we need to update the partial bucket values.
583     if (mAnomalyTrackers.size() > 0) {
584         updateCurrentSlicedBucketForAnomaly();
585 
586         if (eventTimeNs > fullBucketEndTimeNs) {
587             // This is known to be a full bucket, so send this data to the anomaly tracker.
588             for (auto& tracker : mAnomalyTrackers) {
589                 tracker->addPastBucket(mCurrentSlicedBucketForAnomaly, mCurrentBucketNum);
590             }
591             mCurrentSlicedBucketForAnomaly = std::make_shared<DimToValMap>();
592         }
593     }
594 
595     StatsdStats::getInstance().noteBucketCount(mMetricId);
596     mCurrentSlicedBucket = std::make_shared<DimToGaugeAtomsMap>();
597     mCurrentBucketStartTimeNs = nextBucketStartTimeNs;
598 }
599 
byteSizeLocked() const600 size_t GaugeMetricProducer::byteSizeLocked() const {
601     size_t totalSize = 0;
602     for (const auto& pair : mPastBuckets) {
603         for (const auto& bucket : pair.second) {
604             totalSize += bucket.mGaugeAtoms.size() * sizeof(GaugeAtom);
605             for (const auto& atom : bucket.mGaugeAtoms) {
606                 if (atom.mFields != nullptr) {
607                     totalSize += atom.mFields->size() * sizeof(FieldValue);
608                 }
609             }
610         }
611     }
612     return totalSize;
613 }
614 
615 }  // namespace statsd
616 }  // namespace os
617 }  // namespace android
618