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