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 STATSD_DEBUG false // STOPSHIP if true
18 #include "Log.h"
19
20 #include "CountMetricProducer.h"
21
22 #include <inttypes.h>
23 #include <limits.h>
24 #include <stdlib.h>
25
26 #include "guardrail/StatsdStats.h"
27 #include "metrics/parsing_utils/metrics_manager_util.h"
28 #include "stats_log_util.h"
29 #include "stats_util.h"
30
31 using android::util::FIELD_COUNT_REPEATED;
32 using android::util::FIELD_TYPE_BOOL;
33 using android::util::FIELD_TYPE_FLOAT;
34 using android::util::FIELD_TYPE_INT32;
35 using android::util::FIELD_TYPE_INT64;
36 using android::util::FIELD_TYPE_MESSAGE;
37 using android::util::FIELD_TYPE_STRING;
38 using android::util::ProtoOutputStream;
39 using std::map;
40 using std::string;
41 using std::unordered_map;
42 using std::vector;
43 using std::shared_ptr;
44
45 namespace android {
46 namespace os {
47 namespace statsd {
48
49 // for StatsLogReport
50 const int FIELD_ID_ID = 1;
51 const int FIELD_ID_COUNT_METRICS = 5;
52 const int FIELD_ID_TIME_BASE = 9;
53 const int FIELD_ID_BUCKET_SIZE = 10;
54 const int FIELD_ID_DIMENSION_PATH_IN_WHAT = 11;
55 const int FIELD_ID_IS_ACTIVE = 14;
56
57 // for CountMetricDataWrapper
58 const int FIELD_ID_DATA = 1;
59 // for CountMetricData
60 const int FIELD_ID_DIMENSION_IN_WHAT = 1;
61 const int FIELD_ID_SLICE_BY_STATE = 6;
62 const int FIELD_ID_BUCKET_INFO = 3;
63 const int FIELD_ID_DIMENSION_LEAF_IN_WHAT = 4;
64 // for CountBucketInfo
65 const int FIELD_ID_COUNT = 3;
66 const int FIELD_ID_BUCKET_NUM = 4;
67 const int FIELD_ID_START_BUCKET_ELAPSED_MILLIS = 5;
68 const int FIELD_ID_END_BUCKET_ELAPSED_MILLIS = 6;
69 const int FIELD_ID_CONDITION_TRUE_NS = 7;
70
CountMetricProducer(const ConfigKey & key,const CountMetric & metric,const int conditionIndex,const vector<ConditionState> & initialConditionCache,const sp<ConditionWizard> & wizard,const uint64_t protoHash,const int64_t timeBaseNs,const int64_t startTimeNs,const unordered_map<int,shared_ptr<Activation>> & eventActivationMap,const unordered_map<int,vector<shared_ptr<Activation>>> & eventDeactivationMap,const vector<int> & slicedStateAtoms,const unordered_map<int,unordered_map<int,int64_t>> & stateGroupMap)71 CountMetricProducer::CountMetricProducer(
72 const ConfigKey& key, const CountMetric& metric, const int conditionIndex,
73 const vector<ConditionState>& initialConditionCache, const sp<ConditionWizard>& wizard,
74 const uint64_t protoHash, const int64_t timeBaseNs, const int64_t startTimeNs,
75 const unordered_map<int, shared_ptr<Activation>>& eventActivationMap,
76 const unordered_map<int, vector<shared_ptr<Activation>>>& eventDeactivationMap,
77 const vector<int>& slicedStateAtoms,
78 const unordered_map<int, unordered_map<int, int64_t>>& stateGroupMap)
79 : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, initialConditionCache, wizard,
80 protoHash, eventActivationMap, eventDeactivationMap, slicedStateAtoms,
81 stateGroupMap, getAppUpgradeBucketSplit(metric)) {
82 if (metric.has_bucket()) {
83 mBucketSizeNs =
84 TimeUnitToBucketSizeInMillisGuardrailed(key.GetUid(), metric.bucket()) * 1000000;
85 } else {
86 mBucketSizeNs = LLONG_MAX;
87 }
88
89 if (metric.has_dimensions_in_what()) {
90 translateFieldMatcher(metric.dimensions_in_what(), &mDimensionsInWhat);
91 mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
92 }
93
94 mShouldUseNestedDimensions = ShouldUseNestedDimensions(metric.dimensions_in_what());
95
96 if (metric.links().size() > 0) {
97 for (const auto& link : metric.links()) {
98 Metric2Condition mc;
99 mc.conditionId = link.condition();
100 translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
101 translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
102 mMetric2ConditionLinks.push_back(mc);
103 }
104 mConditionSliced = true;
105 }
106
107 for (const auto& stateLink : metric.state_link()) {
108 Metric2State ms;
109 ms.stateAtomId = stateLink.state_atom_id();
110 translateFieldMatcher(stateLink.fields_in_what(), &ms.metricFields);
111 translateFieldMatcher(stateLink.fields_in_state(), &ms.stateFields);
112 mMetric2StateLinks.push_back(ms);
113 }
114
115 if (metric.has_threshold()) {
116 mUploadThreshold = metric.threshold();
117 }
118
119 flushIfNeededLocked(startTimeNs);
120 // Adjust start for partial bucket
121 mCurrentBucketStartTimeNs = startTimeNs;
122 mConditionTimer.newBucketStart(mCurrentBucketStartTimeNs, mCurrentBucketStartTimeNs);
123 mConditionTimer.onConditionChanged(mIsActive && mCondition == ConditionState::kTrue,
124 mCurrentBucketStartTimeNs);
125
126 VLOG("metric %lld created. bucket size %lld start_time: %lld", (long long)mMetricId,
127 (long long)mBucketSizeNs, (long long)mTimeBaseNs);
128 }
129
~CountMetricProducer()130 CountMetricProducer::~CountMetricProducer() {
131 VLOG("~CountMetricProducer() called");
132 }
133
onConfigUpdatedLocked(const StatsdConfig & config,const int configIndex,const int metricIndex,const vector<sp<AtomMatchingTracker>> & allAtomMatchingTrackers,const unordered_map<int64_t,int> & oldAtomMatchingTrackerMap,const unordered_map<int64_t,int> & newAtomMatchingTrackerMap,const sp<EventMatcherWizard> & matcherWizard,const vector<sp<ConditionTracker>> & allConditionTrackers,const unordered_map<int64_t,int> & conditionTrackerMap,const sp<ConditionWizard> & wizard,const unordered_map<int64_t,int> & metricToActivationMap,unordered_map<int,vector<int>> & trackerToMetricMap,unordered_map<int,vector<int>> & conditionToMetricMap,unordered_map<int,vector<int>> & activationAtomTrackerToMetricMap,unordered_map<int,vector<int>> & deactivationAtomTrackerToMetricMap,vector<int> & metricsWithActivation)134 optional<InvalidConfigReason> CountMetricProducer::onConfigUpdatedLocked(
135 const StatsdConfig& config, const int configIndex, const int metricIndex,
136 const vector<sp<AtomMatchingTracker>>& allAtomMatchingTrackers,
137 const unordered_map<int64_t, int>& oldAtomMatchingTrackerMap,
138 const unordered_map<int64_t, int>& newAtomMatchingTrackerMap,
139 const sp<EventMatcherWizard>& matcherWizard,
140 const vector<sp<ConditionTracker>>& allConditionTrackers,
141 const unordered_map<int64_t, int>& conditionTrackerMap, const sp<ConditionWizard>& wizard,
142 const unordered_map<int64_t, int>& metricToActivationMap,
143 unordered_map<int, vector<int>>& trackerToMetricMap,
144 unordered_map<int, vector<int>>& conditionToMetricMap,
145 unordered_map<int, vector<int>>& activationAtomTrackerToMetricMap,
146 unordered_map<int, vector<int>>& deactivationAtomTrackerToMetricMap,
147 vector<int>& metricsWithActivation) {
148 optional<InvalidConfigReason> invalidConfigReason = MetricProducer::onConfigUpdatedLocked(
149 config, configIndex, metricIndex, allAtomMatchingTrackers, oldAtomMatchingTrackerMap,
150 newAtomMatchingTrackerMap, matcherWizard, allConditionTrackers, conditionTrackerMap,
151 wizard, metricToActivationMap, trackerToMetricMap, conditionToMetricMap,
152 activationAtomTrackerToMetricMap, deactivationAtomTrackerToMetricMap,
153 metricsWithActivation);
154 if (invalidConfigReason.has_value()) {
155 return invalidConfigReason;
156 }
157
158 const CountMetric& metric = config.count_metric(configIndex);
159 int trackerIndex;
160 // Update appropriate indices, specifically mConditionIndex and MetricsManager maps.
161 invalidConfigReason = handleMetricWithAtomMatchingTrackers(
162 metric.what(), mMetricId, metricIndex, false, allAtomMatchingTrackers,
163 newAtomMatchingTrackerMap, trackerToMetricMap, trackerIndex);
164 if (invalidConfigReason.has_value()) {
165 return invalidConfigReason;
166 }
167
168 if (metric.has_condition()) {
169 invalidConfigReason = handleMetricWithConditions(
170 metric.condition(), mMetricId, metricIndex, conditionTrackerMap, metric.links(),
171 allConditionTrackers, mConditionTrackerIndex, conditionToMetricMap);
172 if (invalidConfigReason.has_value()) {
173 return invalidConfigReason;
174 }
175 }
176 return nullopt;
177 }
178
onStateChanged(const int64_t eventTimeNs,const int32_t atomId,const HashableDimensionKey & primaryKey,const FieldValue & oldState,const FieldValue & newState)179 void CountMetricProducer::onStateChanged(const int64_t eventTimeNs, const int32_t atomId,
180 const HashableDimensionKey& primaryKey,
181 const FieldValue& oldState, const FieldValue& newState) {
182 VLOG("CountMetric %lld onStateChanged time %lld, State%d, key %s, %d -> %d",
183 (long long)mMetricId, (long long)eventTimeNs, atomId, primaryKey.toString().c_str(),
184 oldState.mValue.int_value, newState.mValue.int_value);
185 }
186
dumpStatesLocked(FILE * out,bool verbose) const187 void CountMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
188 if (mCurrentSlicedCounter == nullptr ||
189 mCurrentSlicedCounter->size() == 0) {
190 return;
191 }
192
193 fprintf(out, "CountMetric %lld dimension size %lu\n", (long long)mMetricId,
194 (unsigned long)mCurrentSlicedCounter->size());
195 if (verbose) {
196 for (const auto& it : *mCurrentSlicedCounter) {
197 fprintf(out, "\t(what)%s\t(state)%s %lld\n",
198 it.first.getDimensionKeyInWhat().toString().c_str(),
199 it.first.getStateValuesKey().toString().c_str(), (unsigned long long)it.second);
200 }
201 }
202 }
203
onSlicedConditionMayChangeLocked(bool overallCondition,const int64_t eventTime)204 void CountMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
205 const int64_t eventTime) {
206 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
207 }
208
209
clearPastBucketsLocked(const int64_t dumpTimeNs)210 void CountMetricProducer::clearPastBucketsLocked(const int64_t dumpTimeNs) {
211 mPastBuckets.clear();
212 }
213
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)214 void CountMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
215 const bool include_current_partial_bucket,
216 const bool erase_data,
217 const DumpLatency dumpLatency,
218 std::set<string> *str_set,
219 ProtoOutputStream* protoOutput) {
220 if (include_current_partial_bucket) {
221 flushLocked(dumpTimeNs);
222 } else {
223 flushIfNeededLocked(dumpTimeNs);
224 }
225 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
226 protoOutput->write(FIELD_TYPE_BOOL | FIELD_ID_IS_ACTIVE, isActiveLocked());
227
228
229 if (mPastBuckets.empty()) {
230 return;
231 }
232 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_TIME_BASE, (long long)mTimeBaseNs);
233 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_SIZE, (long long)mBucketSizeNs);
234
235 // Fills the dimension path if not slicing by a primitive repeated field or position ALL.
236 if (!mShouldUseNestedDimensions) {
237 if (!mDimensionsInWhat.empty()) {
238 uint64_t dimenPathToken = protoOutput->start(
239 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_WHAT);
240 writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
241 protoOutput->end(dimenPathToken);
242 }
243 }
244
245 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_COUNT_METRICS);
246
247 for (const auto& counter : mPastBuckets) {
248 const MetricDimensionKey& dimensionKey = counter.first;
249 VLOG(" dimension key %s", dimensionKey.toString().c_str());
250
251 uint64_t wrapperToken =
252 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
253
254 // First fill dimension.
255 if (mShouldUseNestedDimensions) {
256 uint64_t dimensionToken = protoOutput->start(
257 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
258 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), str_set, protoOutput);
259 protoOutput->end(dimensionToken);
260 } else {
261 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInWhat(),
262 FIELD_ID_DIMENSION_LEAF_IN_WHAT, str_set, protoOutput);
263 }
264 // Then fill slice_by_state.
265 for (auto state : dimensionKey.getStateValuesKey().getValues()) {
266 uint64_t stateToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
267 FIELD_ID_SLICE_BY_STATE);
268 writeStateToProto(state, protoOutput);
269 protoOutput->end(stateToken);
270 }
271 // Then fill bucket_info (CountBucketInfo).
272 for (const auto& bucket : counter.second) {
273 uint64_t bucketInfoToken = protoOutput->start(
274 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
275 // Partial bucket.
276 if (bucket.mBucketEndNs - bucket.mBucketStartNs != mBucketSizeNs) {
277 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_MILLIS,
278 (long long)NanoToMillis(bucket.mBucketStartNs));
279 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_MILLIS,
280 (long long)NanoToMillis(bucket.mBucketEndNs));
281 } else {
282 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_NUM,
283 (long long)(getBucketNumFromEndTimeNs(bucket.mBucketEndNs)));
284 }
285 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_COUNT, (long long)bucket.mCount);
286
287 // We only write the condition timer value if the metric has a
288 // condition and isn't sliced by state or condition.
289 // TODO(b/268531179): Slice the condition timer by state and condition
290 if (mConditionTrackerIndex >= 0 && mSlicedStateAtoms.empty() && !mConditionSliced) {
291 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_CONDITION_TRUE_NS,
292 (long long)bucket.mConditionTrueNs);
293 }
294
295 protoOutput->end(bucketInfoToken);
296 VLOG("\t bucket [%lld - %lld] count: %lld", (long long)bucket.mBucketStartNs,
297 (long long)bucket.mBucketEndNs, (long long)bucket.mCount);
298 }
299 protoOutput->end(wrapperToken);
300 }
301
302 protoOutput->end(protoToken);
303
304 if (erase_data) {
305 mPastBuckets.clear();
306 }
307 }
308
dropDataLocked(const int64_t dropTimeNs)309 void CountMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
310 flushIfNeededLocked(dropTimeNs);
311 StatsdStats::getInstance().noteBucketDropped(mMetricId);
312 mPastBuckets.clear();
313 }
314
onConditionChangedLocked(const bool conditionMet,const int64_t eventTime)315 void CountMetricProducer::onConditionChangedLocked(const bool conditionMet,
316 const int64_t eventTime) {
317 VLOG("Metric %lld onConditionChanged", (long long)mMetricId);
318 mCondition = conditionMet ? ConditionState::kTrue : ConditionState::kFalse;
319
320 if (!mIsActive) {
321 return;
322 }
323
324 mConditionTimer.onConditionChanged(mCondition, eventTime);
325 }
326
hitGuardRailLocked(const MetricDimensionKey & newKey)327 bool CountMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
328 if (mCurrentSlicedCounter->find(newKey) != mCurrentSlicedCounter->end()) {
329 return false;
330 }
331 // ===========GuardRail==============
332 // 1. Report the tuple count if the tuple count > soft limit
333 if (mCurrentSlicedCounter->size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
334 size_t newTupleCount = mCurrentSlicedCounter->size() + 1;
335 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
336 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
337 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
338 if (!mHasHitGuardrail) {
339 ALOGE("CountMetric %lld dropping data for dimension key %s", (long long)mMetricId,
340 newKey.toString().c_str());
341 mHasHitGuardrail = true;
342 }
343 StatsdStats::getInstance().noteHardDimensionLimitReached(mMetricId);
344 return true;
345 }
346 }
347
348 return false;
349 }
350
onMatchedLogEventInternalLocked(const size_t matcherIndex,const MetricDimensionKey & eventKey,const ConditionKey & conditionKey,bool condition,const LogEvent & event,const map<int,HashableDimensionKey> & statePrimaryKeys)351 void CountMetricProducer::onMatchedLogEventInternalLocked(
352 const size_t matcherIndex, const MetricDimensionKey& eventKey,
353 const ConditionKey& conditionKey, bool condition, const LogEvent& event,
354 const map<int, HashableDimensionKey>& statePrimaryKeys) {
355 int64_t eventTimeNs = event.GetElapsedTimestampNs();
356 flushIfNeededLocked(eventTimeNs);
357
358 if (!condition) {
359 return;
360 }
361
362 auto it = mCurrentSlicedCounter->find(eventKey);
363 if (it == mCurrentSlicedCounter->end()) {
364 // ===========GuardRail==============
365 if (hitGuardRailLocked(eventKey)) {
366 return;
367 }
368 // create a counter for the new key
369 (*mCurrentSlicedCounter)[eventKey] = 1;
370 } else {
371 // increment the existing value
372 auto& count = it->second;
373 count++;
374 }
375 for (auto& tracker : mAnomalyTrackers) {
376 int64_t countWholeBucket = mCurrentSlicedCounter->find(eventKey)->second;
377 auto prev = mCurrentFullCounters->find(eventKey);
378 if (prev != mCurrentFullCounters->end()) {
379 countWholeBucket += prev->second;
380 }
381 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, mMetricId, eventKey,
382 countWholeBucket);
383 }
384
385 VLOG("metric %lld %s->%lld", (long long)mMetricId, eventKey.toString().c_str(),
386 (long long)(*mCurrentSlicedCounter)[eventKey]);
387 }
388
389 // When a new matched event comes in, we check if event falls into the current
390 // bucket. If not, flush the old counter to past buckets and initialize the new bucket.
flushIfNeededLocked(const int64_t & eventTimeNs)391 void CountMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
392 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
393 if (eventTimeNs < currentBucketEndTimeNs) {
394 return;
395 }
396
397 // Setup the bucket start time and number.
398 int64_t numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
399 int64_t nextBucketNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
400 flushCurrentBucketLocked(eventTimeNs, nextBucketNs);
401
402 mCurrentBucketNum += numBucketsForward;
403 VLOG("metric %lld: new bucket start time: %lld", (long long)mMetricId,
404 (long long)mCurrentBucketStartTimeNs);
405 }
406
countPassesThreshold(const int64_t & count)407 bool CountMetricProducer::countPassesThreshold(const int64_t& count) {
408 if (mUploadThreshold == nullopt) {
409 return true;
410 }
411
412 switch (mUploadThreshold->value_comparison_case()) {
413 case UploadThreshold::kLtInt:
414 return count < mUploadThreshold->lt_int();
415 case UploadThreshold::kGtInt:
416 return count > mUploadThreshold->gt_int();
417 case UploadThreshold::kLteInt:
418 return count <= mUploadThreshold->lte_int();
419 case UploadThreshold::kGteInt:
420 return count >= mUploadThreshold->gte_int();
421 default:
422 ALOGE("Count metric incorrect upload threshold type used");
423 return false;
424 }
425 }
426
flushCurrentBucketLocked(const int64_t & eventTimeNs,const int64_t & nextBucketStartTimeNs)427 void CountMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs,
428 const int64_t& nextBucketStartTimeNs) {
429 int64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
430 CountBucket info;
431 info.mBucketStartNs = mCurrentBucketStartTimeNs;
432 if (eventTimeNs < fullBucketEndTimeNs) {
433 info.mBucketEndNs = eventTimeNs;
434 } else {
435 info.mBucketEndNs = fullBucketEndTimeNs;
436 }
437
438 const auto [globalConditionTrueNs, globalConditionCorrectionNs] =
439 mConditionTimer.newBucketStart(eventTimeNs, nextBucketStartTimeNs);
440 info.mConditionTrueNs = globalConditionTrueNs;
441
442 for (const auto& counter : *mCurrentSlicedCounter) {
443 if (countPassesThreshold(counter.second)) {
444 info.mCount = counter.second;
445 auto& bucketList = mPastBuckets[counter.first];
446 bucketList.push_back(info);
447 VLOG("metric %lld, dump key value: %s -> %lld", (long long)mMetricId,
448 counter.first.toString().c_str(), (long long)counter.second);
449 }
450 }
451
452 // Only update mCurrentFullCounters if any anomaly tackers are present.
453 if (mAnomalyTrackers.size() > 0) {
454 // If we have finished a full bucket, then send this to anomaly tracker.
455 if (eventTimeNs > fullBucketEndTimeNs) {
456 // Accumulate partial buckets with current value and then send to anomaly tracker.
457 if (mCurrentFullCounters->size() > 0) {
458 for (const auto& keyValuePair : *mCurrentSlicedCounter) {
459 (*mCurrentFullCounters)[keyValuePair.first] += keyValuePair.second;
460 }
461 for (auto& tracker : mAnomalyTrackers) {
462 tracker->addPastBucket(mCurrentFullCounters, mCurrentBucketNum);
463 }
464 mCurrentFullCounters = std::make_shared<DimToValMap>();
465 } else {
466 // Skip aggregating the partial buckets since there's no previous partial bucket.
467 for (auto& tracker : mAnomalyTrackers) {
468 tracker->addPastBucket(mCurrentSlicedCounter, mCurrentBucketNum);
469 }
470 }
471 } else {
472 // Accumulate partial bucket.
473 for (const auto& keyValuePair : *mCurrentSlicedCounter) {
474 (*mCurrentFullCounters)[keyValuePair.first] += keyValuePair.second;
475 }
476 }
477 }
478
479 StatsdStats::getInstance().noteBucketCount(mMetricId);
480 // Only resets the counters, but doesn't setup the times nor numbers.
481 // (Do not clear since the old one is still referenced in mAnomalyTrackers).
482 mCurrentSlicedCounter = std::make_shared<DimToValMap>();
483 mCurrentBucketStartTimeNs = nextBucketStartTimeNs;
484 // Reset mHasHitGuardrail boolean since bucket was reset
485 mHasHitGuardrail = false;
486 }
487
488 // Rough estimate of CountMetricProducer buffer stored. This number will be
489 // greater than actual data size as it contains each dimension of
490 // CountMetricData is duplicated.
byteSizeLocked() const491 size_t CountMetricProducer::byteSizeLocked() const {
492 size_t totalSize = 0;
493 for (const auto& pair : mPastBuckets) {
494 totalSize += pair.second.size() * kBucketSize;
495 }
496 return totalSize;
497 }
498
onActiveStateChangedLocked(const int64_t eventTimeNs,const bool isActive)499 void CountMetricProducer::onActiveStateChangedLocked(const int64_t eventTimeNs,
500 const bool isActive) {
501 MetricProducer::onActiveStateChangedLocked(eventTimeNs, isActive);
502
503 if (ConditionState::kTrue != mCondition) {
504 return;
505 }
506
507 mConditionTimer.onConditionChanged(isActive, eventTimeNs);
508 }
509
510 } // namespace statsd
511 } // namespace os
512 } // namespace android
513