blob: 21ffff32f5398a67bced1271644020baa0eb2dfb [file] [log] [blame]
Yao Chen44cf27c2017-09-14 22:32:50 -07001/*
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
Yao Chen3c0b95c2017-12-16 14:34:20 -080017#define DEBUG false // STOPSHIP if true
Joe Onorato9fc9edf2017-10-15 20:08:52 -070018#include "Log.h"
Yao Chen44cf27c2017-09-14 22:32:50 -070019
Yao Chen729093d2017-10-16 10:33:26 -070020#include "CountMetricProducer.h"
Yao Chen44cf27c2017-09-14 22:32:50 -070021
tsaichristined21aacf2019-10-07 14:47:38 -070022#include <inttypes.h>
Yao Chen44cf27c2017-09-14 22:32:50 -070023#include <limits.h>
24#include <stdlib.h>
25
tsaichristined21aacf2019-10-07 14:47:38 -070026#include "guardrail/StatsdStats.h"
27#include "stats_log_util.h"
28#include "stats_util.h"
29
yrob0378b02017-11-09 20:36:25 -080030using android::util::FIELD_COUNT_REPEATED;
yro2b0f8862017-11-06 14:27:31 -080031using android::util::FIELD_TYPE_BOOL;
32using android::util::FIELD_TYPE_FLOAT;
33using android::util::FIELD_TYPE_INT32;
34using android::util::FIELD_TYPE_INT64;
35using android::util::FIELD_TYPE_MESSAGE;
Yangster-macd1815dc2017-11-13 21:43:15 -080036using android::util::FIELD_TYPE_STRING;
yro24809bd2017-10-31 23:06:53 -070037using android::util::ProtoOutputStream;
Yao Chen729093d2017-10-16 10:33:26 -070038using std::map;
39using std::string;
Yao Chen44cf27c2017-09-14 22:32:50 -070040using std::unordered_map;
Yao Chen729093d2017-10-16 10:33:26 -070041using std::vector;
Ruchir Rastogi21a287b2019-10-02 12:04:33 -070042using std::shared_ptr;
Yao Chen44cf27c2017-09-14 22:32:50 -070043
44namespace android {
45namespace os {
46namespace statsd {
47
yro24809bd2017-10-31 23:06:53 -070048// for StatsLogReport
Yangster-mac94e197c2018-01-02 16:03:03 -080049const int FIELD_ID_ID = 1;
yro24809bd2017-10-31 23:06:53 -070050const int FIELD_ID_COUNT_METRICS = 5;
Yangster-mac9def8e32018-04-17 13:55:51 -070051const int FIELD_ID_TIME_BASE = 9;
52const int FIELD_ID_BUCKET_SIZE = 10;
53const int FIELD_ID_DIMENSION_PATH_IN_WHAT = 11;
Howard Ro9440e092018-12-16 19:15:21 -080054const int FIELD_ID_IS_ACTIVE = 14;
Yang Lub4722912018-11-15 11:02:03 -080055
yro24809bd2017-10-31 23:06:53 -070056// for CountMetricDataWrapper
57const int FIELD_ID_DATA = 1;
58// for CountMetricData
Yangster-mac468ff042018-01-17 12:26:34 -080059const int FIELD_ID_DIMENSION_IN_WHAT = 1;
tsaichristine69000e62019-10-18 17:34:52 -070060const int FIELD_ID_SLICE_BY_STATE = 6;
Yangster-mac468ff042018-01-17 12:26:34 -080061const int FIELD_ID_BUCKET_INFO = 3;
Yangster-mac9def8e32018-04-17 13:55:51 -070062const int FIELD_ID_DIMENSION_LEAF_IN_WHAT = 4;
yro24809bd2017-10-31 23:06:53 -070063// for CountBucketInfo
yro24809bd2017-10-31 23:06:53 -070064const int FIELD_ID_COUNT = 3;
Yangster-mac9def8e32018-04-17 13:55:51 -070065const int FIELD_ID_BUCKET_NUM = 4;
66const int FIELD_ID_START_BUCKET_ELAPSED_MILLIS = 5;
67const int FIELD_ID_END_BUCKET_ELAPSED_MILLIS = 6;
yro24809bd2017-10-31 23:06:53 -070068
tsaichristined21aacf2019-10-07 14:47:38 -070069CountMetricProducer::CountMetricProducer(
70 const ConfigKey& key, const CountMetric& metric, const int conditionIndex,
71 const sp<ConditionWizard>& wizard, const int64_t timeBaseNs, const int64_t startTimeNs,
72
73 const unordered_map<int, shared_ptr<Activation>>& eventActivationMap,
74 const unordered_map<int, vector<shared_ptr<Activation>>>& eventDeactivationMap,
75 const vector<int>& slicedStateAtoms,
76 const unordered_map<int, unordered_map<int, int64_t>>& stateGroupMap)
Ruchir Rastogi21a287b2019-10-02 12:04:33 -070077 : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, wizard, eventActivationMap,
tsaichristined21aacf2019-10-07 14:47:38 -070078 eventDeactivationMap, slicedStateAtoms, stateGroupMap) {
Yangster-macb8144812018-01-04 10:56:23 -080079 if (metric.has_bucket()) {
yro59cc24d2018-02-13 20:17:32 -080080 mBucketSizeNs =
81 TimeUnitToBucketSizeInMillisGuardrailed(key.GetUid(), metric.bucket()) * 1000000;
Yao Chen44cf27c2017-09-14 22:32:50 -070082 } else {
Yao Chen729093d2017-10-16 10:33:26 -070083 mBucketSizeNs = LLONG_MAX;
Yao Chen44cf27c2017-09-14 22:32:50 -070084 }
85
Yao Chen8a8d16c2018-02-08 14:50:40 -080086 if (metric.has_dimensions_in_what()) {
87 translateFieldMatcher(metric.dimensions_in_what(), &mDimensionsInWhat);
Yangster13fb7e42018-03-07 17:30:49 -080088 mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
Yao Chen8a8d16c2018-02-08 14:50:40 -080089 }
90
tsaichristine76853372019-08-06 17:17:03 -070091 mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what());
Yao Chen729093d2017-10-16 10:33:26 -070092
93 if (metric.links().size() > 0) {
Yao Chen8a8d16c2018-02-08 14:50:40 -080094 for (const auto& link : metric.links()) {
95 Metric2Condition mc;
96 mc.conditionId = link.condition();
97 translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
98 translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
99 mMetric2ConditionLinks.push_back(mc);
100 }
101 mConditionSliced = true;
Yao Chen729093d2017-10-16 10:33:26 -0700102 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800103
tsaichristine69000e62019-10-18 17:34:52 -0700104 for (const auto& stateLink : metric.state_link()) {
105 Metric2State ms;
106 ms.stateAtomId = stateLink.state_atom_id();
107 translateFieldMatcher(stateLink.fields_in_what(), &ms.metricFields);
108 translateFieldMatcher(stateLink.fields_in_state(), &ms.stateFields);
109 mMetric2StateLinks.push_back(ms);
110 }
tsaichristined21aacf2019-10-07 14:47:38 -0700111
Chenjie Yue1361ed2018-07-23 17:33:09 -0700112 flushIfNeededLocked(startTimeNs);
113 // Adjust start for partial bucket
114 mCurrentBucketStartTimeNs = startTimeNs;
115
Yangster-mac94e197c2018-01-02 16:03:03 -0800116 VLOG("metric %lld created. bucket size %lld start_time: %lld", (long long)metric.id(),
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700117 (long long)mBucketSizeNs, (long long)mTimeBaseNs);
Yao Chen44cf27c2017-09-14 22:32:50 -0700118}
119
Yao Chen44cf27c2017-09-14 22:32:50 -0700120CountMetricProducer::~CountMetricProducer() {
121 VLOG("~CountMetricProducer() called");
122}
123
tsaichristine8d73dc92019-12-06 02:11:02 -0800124void CountMetricProducer::onStateChanged(const int64_t eventTimeNs, const int32_t atomId,
125 const HashableDimensionKey& primaryKey, int oldState,
126 int newState) {
127 VLOG("CountMetric %lld onStateChanged time %lld, State%d, key %s, %d -> %d",
128 (long long)mMetricId, (long long)eventTimeNs, atomId, primaryKey.toString().c_str(),
129 oldState, newState);
tsaichristined21aacf2019-10-07 14:47:38 -0700130}
131
Yangster-maca78d0082018-03-12 12:02:56 -0700132void CountMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
133 if (mCurrentSlicedCounter == nullptr ||
134 mCurrentSlicedCounter->size() == 0) {
135 return;
136 }
137
138 fprintf(out, "CountMetric %lld dimension size %lu\n", (long long)mMetricId,
139 (unsigned long)mCurrentSlicedCounter->size());
140 if (verbose) {
141 for (const auto& it : *mCurrentSlicedCounter) {
tsaichristine69000e62019-10-18 17:34:52 -0700142 fprintf(out, "\t(what)%s\t(state)%s %lld\n",
143 it.first.getDimensionKeyInWhat().toString().c_str(),
144 it.first.getStateValuesKey().toString().c_str(), (unsigned long long)it.second);
Yangster-maca78d0082018-03-12 12:02:56 -0700145 }
146 }
147}
148
Yao Chen427d3722018-03-22 15:21:52 -0700149void CountMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
Yangster-macb142cc82018-03-30 15:22:08 -0700150 const int64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800151 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Yao Chen729093d2017-10-16 10:33:26 -0700152}
153
Yangster-maca802d732018-04-24 07:50:38 -0700154
155void CountMetricProducer::clearPastBucketsLocked(const int64_t dumpTimeNs) {
Yangster-maca802d732018-04-24 07:50:38 -0700156 mPastBuckets.clear();
157}
158
Yangster-macb142cc82018-03-30 15:22:08 -0700159void CountMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700160 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700161 const bool erase_data,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000162 const DumpLatency dumpLatency,
Yangster-mac9def8e32018-04-17 13:55:51 -0700163 std::set<string> *str_set,
Yao Chen288c6002017-12-12 13:43:18 -0800164 ProtoOutputStream* protoOutput) {
Yangster-mace68f3a52018-04-04 00:01:43 -0700165 if (include_current_partial_bucket) {
166 flushLocked(dumpTimeNs);
167 } else {
168 flushIfNeededLocked(dumpTimeNs);
169 }
Yang Lub4722912018-11-15 11:02:03 -0800170 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Howard Ro07e23ff2018-12-17 17:28:07 -0800171 protoOutput->write(FIELD_TYPE_BOOL | FIELD_ID_IS_ACTIVE, isActiveLocked());
Yang Lub4722912018-11-15 11:02:03 -0800172
173
Yangster-mac635b4b32018-01-23 20:17:35 -0800174 if (mPastBuckets.empty()) {
175 return;
176 }
Yangster-mac9def8e32018-04-17 13:55:51 -0700177 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_TIME_BASE, (long long)mTimeBaseNs);
178 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_SIZE, (long long)mBucketSizeNs);
179
180 // Fills the dimension path if not slicing by ALL.
181 if (!mSliceByPositionALL) {
182 if (!mDimensionsInWhat.empty()) {
183 uint64_t dimenPathToken = protoOutput->start(
184 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_WHAT);
185 writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
186 protoOutput->end(dimenPathToken);
187 }
Yangster-mac9def8e32018-04-17 13:55:51 -0700188 }
189
Yi Jin5ee07872018-03-05 18:18:27 -0800190 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_COUNT_METRICS);
Yao Chen288c6002017-12-12 13:43:18 -0800191
Yao Chen93fe3a32017-11-02 13:52:59 -0700192 for (const auto& counter : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800193 const MetricDimensionKey& dimensionKey = counter.first;
Yangster13fb7e42018-03-07 17:30:49 -0800194 VLOG(" dimension key %s", dimensionKey.toString().c_str());
Yao Chend5aa01b32017-12-19 16:46:36 -0800195
Yi Jin5ee07872018-03-05 18:18:27 -0800196 uint64_t wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800197 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
Yao Chen729093d2017-10-16 10:33:26 -0700198
Yangster-mac20877162017-12-22 17:19:39 -0800199 // First fill dimension.
Yangster-mac9def8e32018-04-17 13:55:51 -0700200 if (mSliceByPositionALL) {
201 uint64_t dimensionToken = protoOutput->start(
202 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
203 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), str_set, protoOutput);
204 protoOutput->end(dimensionToken);
Yangster-mac9def8e32018-04-17 13:55:51 -0700205 } else {
206 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInWhat(),
207 FIELD_ID_DIMENSION_LEAF_IN_WHAT, str_set, protoOutput);
tsaichristine69000e62019-10-18 17:34:52 -0700208 }
209 // Then fill slice_by_state.
210 for (auto state : dimensionKey.getStateValuesKey().getValues()) {
211 uint64_t stateToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
212 FIELD_ID_SLICE_BY_STATE);
213 writeStateToProto(state, protoOutput);
214 protoOutput->end(stateToken);
Yangster-mac93694462018-01-22 20:49:31 -0800215 }
yro24809bd2017-10-31 23:06:53 -0700216 // Then fill bucket_info (CountBucketInfo).
Yao Chen93fe3a32017-11-02 13:52:59 -0700217 for (const auto& bucket : counter.second) {
Yi Jin5ee07872018-03-05 18:18:27 -0800218 uint64_t bucketInfoToken = protoOutput->start(
Yao Chen288c6002017-12-12 13:43:18 -0800219 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
Yangster-mac9def8e32018-04-17 13:55:51 -0700220 // Partial bucket.
221 if (bucket.mBucketEndNs - bucket.mBucketStartNs != mBucketSizeNs) {
222 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_MILLIS,
223 (long long)NanoToMillis(bucket.mBucketStartNs));
224 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_MILLIS,
225 (long long)NanoToMillis(bucket.mBucketEndNs));
226 } else {
227 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_NUM,
228 (long long)(getBucketNumFromEndTimeNs(bucket.mBucketEndNs)));
229 }
Yao Chen288c6002017-12-12 13:43:18 -0800230 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_COUNT, (long long)bucket.mCount);
231 protoOutput->end(bucketInfoToken);
Yao Chen93fe3a32017-11-02 13:52:59 -0700232 VLOG("\t bucket [%lld - %lld] count: %lld", (long long)bucket.mBucketStartNs,
233 (long long)bucket.mBucketEndNs, (long long)bucket.mCount);
yro24809bd2017-10-31 23:06:53 -0700234 }
Yao Chen288c6002017-12-12 13:43:18 -0800235 protoOutput->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700236 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000237
Yao Chen288c6002017-12-12 13:43:18 -0800238 protoOutput->end(protoToken);
yro24809bd2017-10-31 23:06:53 -0700239
Bookatzff71cad2018-09-20 17:17:49 -0700240 if (erase_data) {
241 mPastBuckets.clear();
242 }
Yao Chen06dba5d2018-01-26 13:38:16 -0800243}
Yao Chen6a8c7992017-11-29 20:02:07 +0000244
Yangster-macb142cc82018-03-30 15:22:08 -0700245void CountMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
Yao Chen06dba5d2018-01-26 13:38:16 -0800246 flushIfNeededLocked(dropTimeNs);
Olivier Gaillard320952b2019-02-06 13:57:24 +0000247 StatsdStats::getInstance().noteBucketDropped(mMetricId);
Yao Chen06dba5d2018-01-26 13:38:16 -0800248 mPastBuckets.clear();
Yao Chen44cf27c2017-09-14 22:32:50 -0700249}
250
Yangsterf2bee6f2017-11-29 12:01:05 -0800251void CountMetricProducer::onConditionChangedLocked(const bool conditionMet,
Yangster-macb142cc82018-03-30 15:22:08 -0700252 const int64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800253 VLOG("Metric %lld onConditionChanged", (long long)mMetricId);
Olivier Gaillarde63d9e02019-02-12 14:43:59 +0000254 mCondition = conditionMet ? ConditionState::kTrue : ConditionState::kFalse;
Yao Chencaf339d2017-10-06 16:01:10 -0700255}
256
Yangster-mac93694462018-01-22 20:49:31 -0800257bool CountMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800258 if (mCurrentSlicedCounter->find(newKey) != mCurrentSlicedCounter->end()) {
259 return false;
260 }
261 // ===========GuardRail==============
262 // 1. Report the tuple count if the tuple count > soft limit
263 if (mCurrentSlicedCounter->size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
264 size_t newTupleCount = mCurrentSlicedCounter->size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800265 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800266 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
267 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800268 ALOGE("CountMetric %lld dropping data for dimension key %s",
Yangster13fb7e42018-03-07 17:30:49 -0800269 (long long)mMetricId, newKey.toString().c_str());
Muhammad Qureshi87348a62019-02-14 16:17:52 -0800270 StatsdStats::getInstance().noteHardDimensionLimitReached(mMetricId);
Yao Chenb3561512017-11-21 18:07:17 -0800271 return true;
272 }
273 }
274
275 return false;
276}
Yangsterf2bee6f2017-11-29 12:01:05 -0800277
278void CountMetricProducer::onMatchedLogEventInternalLocked(
Yangster-mac93694462018-01-22 20:49:31 -0800279 const size_t matcherIndex, const MetricDimensionKey& eventKey,
tsaichristinec876b492019-12-10 13:47:05 -0800280 const ConditionKey& conditionKey, bool condition, const LogEvent& event,
281 const map<int, HashableDimensionKey>& statePrimaryKeys) {
Yangster-macb142cc82018-03-30 15:22:08 -0700282 int64_t eventTimeNs = event.GetElapsedTimestampNs();
Yangsterf2bee6f2017-11-29 12:01:05 -0800283 flushIfNeededLocked(eventTimeNs);
Yao Chen729093d2017-10-16 10:33:26 -0700284
tsaichristine69000e62019-10-18 17:34:52 -0700285 if (!condition) {
Yao Chenb7041772017-10-20 16:59:25 -0700286 return;
Yao Chen44cf27c2017-09-14 22:32:50 -0700287 }
Yao Chen729093d2017-10-16 10:33:26 -0700288
Yao Chen6a8c7992017-11-29 20:02:07 +0000289 auto it = mCurrentSlicedCounter->find(eventKey);
Yao Chen6a8c7992017-11-29 20:02:07 +0000290 if (it == mCurrentSlicedCounter->end()) {
291 // ===========GuardRail==============
Yangsterf2bee6f2017-11-29 12:01:05 -0800292 if (hitGuardRailLocked(eventKey)) {
Yao Chenb3561512017-11-21 18:07:17 -0800293 return;
294 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000295 // create a counter for the new key
296 (*mCurrentSlicedCounter)[eventKey] = 1;
297 } else {
298 // increment the existing value
299 auto& count = it->second;
300 count++;
Yao Chen729093d2017-10-16 10:33:26 -0700301 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000302 for (auto& tracker : mAnomalyTrackers) {
David Chen27785a82018-01-19 17:06:45 -0800303 int64_t countWholeBucket = mCurrentSlicedCounter->find(eventKey)->second;
304 auto prev = mCurrentFullCounters->find(eventKey);
305 if (prev != mCurrentFullCounters->end()) {
306 countWholeBucket += prev->second;
307 }
Yao Chen4ce07292019-02-13 13:06:36 -0800308 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, mMetricId, eventKey,
David Chen27785a82018-01-19 17:06:45 -0800309 countWholeBucket);
Yao Chen6a8c7992017-11-29 20:02:07 +0000310 }
311
Yangster13fb7e42018-03-07 17:30:49 -0800312 VLOG("metric %lld %s->%lld", (long long)mMetricId, eventKey.toString().c_str(),
Yao Chen6a8c7992017-11-29 20:02:07 +0000313 (long long)(*mCurrentSlicedCounter)[eventKey]);
Yao Chen44cf27c2017-09-14 22:32:50 -0700314}
315
Yao Chen729093d2017-10-16 10:33:26 -0700316// When a new matched event comes in, we check if event falls into the current
317// bucket. If not, flush the old counter to past buckets and initialize the new bucket.
Yangster-macb142cc82018-03-30 15:22:08 -0700318void CountMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
319 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800320 if (eventTimeNs < currentBucketEndTimeNs) {
Yao Chen44cf27c2017-09-14 22:32:50 -0700321 return;
322 }
323
David Chen27785a82018-01-19 17:06:45 -0800324 // Setup the bucket start time and number.
Yangster-macb142cc82018-03-30 15:22:08 -0700325 int64_t numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
Muhammad Qureshi902529a2019-03-14 16:03:21 -0700326 int64_t nextBucketNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
327 flushCurrentBucketLocked(eventTimeNs, nextBucketNs);
328
David Chen27785a82018-01-19 17:06:45 -0800329 mCurrentBucketNum += numBucketsForward;
330 VLOG("metric %lld: new bucket start time: %lld", (long long)mMetricId,
331 (long long)mCurrentBucketStartTimeNs);
332}
333
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000334void CountMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs,
335 const int64_t& nextBucketStartTimeNs) {
Yangster-macb142cc82018-03-30 15:22:08 -0700336 int64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
Yao Chen93fe3a32017-11-02 13:52:59 -0700337 CountBucket info;
338 info.mBucketStartNs = mCurrentBucketStartTimeNs;
David Chen27785a82018-01-19 17:06:45 -0800339 if (eventTimeNs < fullBucketEndTimeNs) {
340 info.mBucketEndNs = eventTimeNs;
341 } else {
342 info.mBucketEndNs = fullBucketEndTimeNs;
343 }
Yang Lu3eba6212017-10-25 19:54:45 -0700344 for (const auto& counter : *mCurrentSlicedCounter) {
Yao Chen93fe3a32017-11-02 13:52:59 -0700345 info.mCount = counter.second;
346 auto& bucketList = mPastBuckets[counter.first];
347 bucketList.push_back(info);
Yangster13fb7e42018-03-07 17:30:49 -0800348 VLOG("metric %lld, dump key value: %s -> %lld", (long long)mMetricId,
349 counter.first.toString().c_str(),
David Chen27785a82018-01-19 17:06:45 -0800350 (long long)counter.second);
Yao Chen729093d2017-10-16 10:33:26 -0700351 }
352
David Chen27785a82018-01-19 17:06:45 -0800353 // If we have finished a full bucket, then send this to anomaly tracker.
354 if (eventTimeNs > fullBucketEndTimeNs) {
355 // Accumulate partial buckets with current value and then send to anomaly tracker.
356 if (mCurrentFullCounters->size() > 0) {
357 for (const auto& keyValuePair : *mCurrentSlicedCounter) {
358 (*mCurrentFullCounters)[keyValuePair.first] += keyValuePair.second;
359 }
360 for (auto& tracker : mAnomalyTrackers) {
361 tracker->addPastBucket(mCurrentFullCounters, mCurrentBucketNum);
362 }
363 mCurrentFullCounters = std::make_shared<DimToValMap>();
364 } else {
365 // Skip aggregating the partial buckets since there's no previous partial bucket.
366 for (auto& tracker : mAnomalyTrackers) {
367 tracker->addPastBucket(mCurrentSlicedCounter, mCurrentBucketNum);
368 }
369 }
370 } else {
371 // Accumulate partial bucket.
372 for (const auto& keyValuePair : *mCurrentSlicedCounter) {
373 (*mCurrentFullCounters)[keyValuePair.first] += keyValuePair.second;
374 }
Yang Lu3eba6212017-10-25 19:54:45 -0700375 }
Bookatzd3606c72017-10-19 10:13:49 -0700376
Olivier Gaillardf248c0d2019-02-21 15:56:58 +0000377 StatsdStats::getInstance().noteBucketCount(mMetricId);
David Chen27785a82018-01-19 17:06:45 -0800378 // Only resets the counters, but doesn't setup the times nor numbers.
379 // (Do not clear since the old one is still referenced in mAnomalyTrackers).
Yang Lu3eba6212017-10-25 19:54:45 -0700380 mCurrentSlicedCounter = std::make_shared<DimToValMap>();
Muhammad Qureshi902529a2019-03-14 16:03:21 -0700381 mCurrentBucketStartTimeNs = nextBucketStartTimeNs;
Yao Chen44cf27c2017-09-14 22:32:50 -0700382}
383
yro24809bd2017-10-31 23:06:53 -0700384// Rough estimate of CountMetricProducer buffer stored. This number will be
385// greater than actual data size as it contains each dimension of
386// CountMetricData is duplicated.
Yangsterf2bee6f2017-11-29 12:01:05 -0800387size_t CountMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800388 size_t totalSize = 0;
389 for (const auto& pair : mPastBuckets) {
390 totalSize += pair.second.size() * kBucketSize;
391 }
392 return totalSize;
yro69007c82017-10-26 20:42:57 -0700393}
394
Yao Chen44cf27c2017-09-14 22:32:50 -0700395} // namespace statsd
396} // namespace os
yro69007c82017-10-26 20:42:57 -0700397} // namespace android