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