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