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