blob: a8ef54a335c49556cfaa14c0f5c6dbf5db99e7e4 [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"
Tej Singhef6cd7f2020-09-18 23:40:47 -070027#include "metrics/parsing_utils/metrics_manager_util.h"
tsaichristined21aacf2019-10-07 14:47:38 -070028#include "stats_log_util.h"
29#include "stats_util.h"
30
yrob0378b02017-11-09 20:36:25 -080031using android::util::FIELD_COUNT_REPEATED;
yro2b0f8862017-11-06 14:27:31 -080032using android::util::FIELD_TYPE_BOOL;
33using android::util::FIELD_TYPE_FLOAT;
34using android::util::FIELD_TYPE_INT32;
35using android::util::FIELD_TYPE_INT64;
36using android::util::FIELD_TYPE_MESSAGE;
Yangster-macd1815dc2017-11-13 21:43:15 -080037using android::util::FIELD_TYPE_STRING;
yro24809bd2017-10-31 23:06:53 -070038using android::util::ProtoOutputStream;
Yao Chen729093d2017-10-16 10:33:26 -070039using std::map;
40using std::string;
Yao Chen44cf27c2017-09-14 22:32:50 -070041using std::unordered_map;
Yao Chen729093d2017-10-16 10:33:26 -070042using std::vector;
Ruchir Rastogi21a287b2019-10-02 12:04:33 -070043using std::shared_ptr;
Yao Chen44cf27c2017-09-14 22:32:50 -070044
45namespace android {
46namespace os {
47namespace statsd {
48
yro24809bd2017-10-31 23:06:53 -070049// for StatsLogReport
Yangster-mac94e197c2018-01-02 16:03:03 -080050const int FIELD_ID_ID = 1;
yro24809bd2017-10-31 23:06:53 -070051const int FIELD_ID_COUNT_METRICS = 5;
Yangster-mac9def8e32018-04-17 13:55:51 -070052const int FIELD_ID_TIME_BASE = 9;
53const int FIELD_ID_BUCKET_SIZE = 10;
54const int FIELD_ID_DIMENSION_PATH_IN_WHAT = 11;
Howard Ro9440e092018-12-16 19:15:21 -080055const int FIELD_ID_IS_ACTIVE = 14;
Yang Lub4722912018-11-15 11:02:03 -080056
yro24809bd2017-10-31 23:06:53 -070057// for CountMetricDataWrapper
58const int FIELD_ID_DATA = 1;
59// for CountMetricData
Yangster-mac468ff042018-01-17 12:26:34 -080060const int FIELD_ID_DIMENSION_IN_WHAT = 1;
tsaichristine69000e62019-10-18 17:34:52 -070061const int FIELD_ID_SLICE_BY_STATE = 6;
Yangster-mac468ff042018-01-17 12:26:34 -080062const int FIELD_ID_BUCKET_INFO = 3;
Yangster-mac9def8e32018-04-17 13:55:51 -070063const int FIELD_ID_DIMENSION_LEAF_IN_WHAT = 4;
yro24809bd2017-10-31 23:06:53 -070064// for CountBucketInfo
yro24809bd2017-10-31 23:06:53 -070065const int FIELD_ID_COUNT = 3;
Yangster-mac9def8e32018-04-17 13:55:51 -070066const int FIELD_ID_BUCKET_NUM = 4;
67const int FIELD_ID_START_BUCKET_ELAPSED_MILLIS = 5;
68const int FIELD_ID_END_BUCKET_ELAPSED_MILLIS = 6;
yro24809bd2017-10-31 23:06:53 -070069
tsaichristined21aacf2019-10-07 14:47:38 -070070CountMetricProducer::CountMetricProducer(
71 const ConfigKey& key, const CountMetric& metric, const int conditionIndex,
tsaichristine6e2e92d2020-05-18 14:39:45 -070072 const vector<ConditionState>& initialConditionCache, const sp<ConditionWizard>& wizard,
Tej Singh052d11c2020-08-28 02:48:40 -070073 const uint64_t protoHash, const int64_t timeBaseNs, const int64_t startTimeNs,
tsaichristined21aacf2019-10-07 14:47:38 -070074 const unordered_map<int, shared_ptr<Activation>>& eventActivationMap,
75 const unordered_map<int, vector<shared_ptr<Activation>>>& eventDeactivationMap,
76 const vector<int>& slicedStateAtoms,
77 const unordered_map<int, unordered_map<int, int64_t>>& stateGroupMap)
tsaichristine6e2e92d2020-05-18 14:39:45 -070078 : MetricProducer(metric.id(), key, timeBaseNs, conditionIndex, initialConditionCache, wizard,
Tej Singh052d11c2020-08-28 02:48:40 -070079 protoHash, eventActivationMap, eventDeactivationMap, slicedStateAtoms,
80 stateGroupMap) {
Yangster-macb8144812018-01-04 10:56:23 -080081 if (metric.has_bucket()) {
yro59cc24d2018-02-13 20:17:32 -080082 mBucketSizeNs =
83 TimeUnitToBucketSizeInMillisGuardrailed(key.GetUid(), metric.bucket()) * 1000000;
Yao Chen44cf27c2017-09-14 22:32:50 -070084 } else {
Yao Chen729093d2017-10-16 10:33:26 -070085 mBucketSizeNs = LLONG_MAX;
Yao Chen44cf27c2017-09-14 22:32:50 -070086 }
87
Yao Chen8a8d16c2018-02-08 14:50:40 -080088 if (metric.has_dimensions_in_what()) {
89 translateFieldMatcher(metric.dimensions_in_what(), &mDimensionsInWhat);
Yangster13fb7e42018-03-07 17:30:49 -080090 mContainANYPositionInDimensionsInWhat = HasPositionANY(metric.dimensions_in_what());
Yao Chen8a8d16c2018-02-08 14:50:40 -080091 }
92
tsaichristine76853372019-08-06 17:17:03 -070093 mSliceByPositionALL = HasPositionALL(metric.dimensions_in_what());
Yao Chen729093d2017-10-16 10:33:26 -070094
95 if (metric.links().size() > 0) {
Yao Chen8a8d16c2018-02-08 14:50:40 -080096 for (const auto& link : metric.links()) {
97 Metric2Condition mc;
98 mc.conditionId = link.condition();
99 translateFieldMatcher(link.fields_in_what(), &mc.metricFields);
100 translateFieldMatcher(link.fields_in_condition(), &mc.conditionFields);
101 mMetric2ConditionLinks.push_back(mc);
102 }
103 mConditionSliced = true;
Yao Chen729093d2017-10-16 10:33:26 -0700104 }
Yao Chen8a8d16c2018-02-08 14:50:40 -0800105
tsaichristine69000e62019-10-18 17:34:52 -0700106 for (const auto& stateLink : metric.state_link()) {
107 Metric2State ms;
108 ms.stateAtomId = stateLink.state_atom_id();
109 translateFieldMatcher(stateLink.fields_in_what(), &ms.metricFields);
110 translateFieldMatcher(stateLink.fields_in_state(), &ms.stateFields);
111 mMetric2StateLinks.push_back(ms);
112 }
tsaichristined21aacf2019-10-07 14:47:38 -0700113
Chenjie Yue1361ed2018-07-23 17:33:09 -0700114 flushIfNeededLocked(startTimeNs);
115 // Adjust start for partial bucket
116 mCurrentBucketStartTimeNs = startTimeNs;
117
Yangster-mac94e197c2018-01-02 16:03:03 -0800118 VLOG("metric %lld created. bucket size %lld start_time: %lld", (long long)metric.id(),
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700119 (long long)mBucketSizeNs, (long long)mTimeBaseNs);
Yao Chen44cf27c2017-09-14 22:32:50 -0700120}
121
Yao Chen44cf27c2017-09-14 22:32:50 -0700122CountMetricProducer::~CountMetricProducer() {
123 VLOG("~CountMetricProducer() called");
124}
125
Tej Singhef6cd7f2020-09-18 23:40:47 -0700126bool CountMetricProducer::onConfigUpdatedLocked(
127 const StatsdConfig& config, const int configIndex, const int metricIndex,
128 const vector<sp<AtomMatchingTracker>>& allAtomMatchingTrackers,
129 const unordered_map<int64_t, int>& oldAtomMatchingTrackerMap,
130 const unordered_map<int64_t, int>& newAtomMatchingTrackerMap,
131 const sp<EventMatcherWizard>& matcherWizard,
132 const vector<sp<ConditionTracker>>& allConditionTrackers,
133 const unordered_map<int64_t, int>& conditionTrackerMap, const sp<ConditionWizard>& wizard,
134 const unordered_map<int64_t, int>& metricToActivationMap,
135 unordered_map<int, vector<int>>& trackerToMetricMap,
136 unordered_map<int, vector<int>>& conditionToMetricMap,
137 unordered_map<int, vector<int>>& activationAtomTrackerToMetricMap,
138 unordered_map<int, vector<int>>& deactivationAtomTrackerToMetricMap,
139 vector<int>& metricsWithActivation) {
140 if (!MetricProducer::onConfigUpdatedLocked(
141 config, configIndex, metricIndex, allAtomMatchingTrackers,
142 oldAtomMatchingTrackerMap, newAtomMatchingTrackerMap, matcherWizard,
143 allConditionTrackers, conditionTrackerMap, wizard, metricToActivationMap,
144 trackerToMetricMap, conditionToMetricMap, activationAtomTrackerToMetricMap,
145 deactivationAtomTrackerToMetricMap, metricsWithActivation)) {
146 return false;
147 }
148
149 const CountMetric& metric = config.count_metric(configIndex);
150 int trackerIndex;
151 // Update appropriate indices, specifically mConditionIndex and MetricsManager maps.
152 if (!handleMetricWithAtomMatchingTrackers(metric.what(), metricIndex, false,
153 allAtomMatchingTrackers, newAtomMatchingTrackerMap,
154 trackerToMetricMap, trackerIndex)) {
155 return false;
156 }
157
158 if (metric.has_condition() &&
159 !handleMetricWithConditions(metric.condition(), metricIndex, conditionTrackerMap,
160 metric.links(), allConditionTrackers, mConditionTrackerIndex,
161 conditionToMetricMap)) {
162 return false;
163 }
164 return true;
165}
166
tsaichristine8d73dc92019-12-06 02:11:02 -0800167void CountMetricProducer::onStateChanged(const int64_t eventTimeNs, const int32_t atomId,
tsaichristine9f951052020-05-13 14:32:37 -0700168 const HashableDimensionKey& primaryKey,
169 const FieldValue& oldState, const FieldValue& newState) {
tsaichristine8d73dc92019-12-06 02:11:02 -0800170 VLOG("CountMetric %lld onStateChanged time %lld, State%d, key %s, %d -> %d",
171 (long long)mMetricId, (long long)eventTimeNs, atomId, primaryKey.toString().c_str(),
tsaichristine9f951052020-05-13 14:32:37 -0700172 oldState.mValue.int_value, newState.mValue.int_value);
tsaichristined21aacf2019-10-07 14:47:38 -0700173}
174
Yangster-maca78d0082018-03-12 12:02:56 -0700175void CountMetricProducer::dumpStatesLocked(FILE* out, bool verbose) const {
176 if (mCurrentSlicedCounter == nullptr ||
177 mCurrentSlicedCounter->size() == 0) {
178 return;
179 }
180
181 fprintf(out, "CountMetric %lld dimension size %lu\n", (long long)mMetricId,
182 (unsigned long)mCurrentSlicedCounter->size());
183 if (verbose) {
184 for (const auto& it : *mCurrentSlicedCounter) {
tsaichristine69000e62019-10-18 17:34:52 -0700185 fprintf(out, "\t(what)%s\t(state)%s %lld\n",
186 it.first.getDimensionKeyInWhat().toString().c_str(),
187 it.first.getStateValuesKey().toString().c_str(), (unsigned long long)it.second);
Yangster-maca78d0082018-03-12 12:02:56 -0700188 }
189 }
190}
191
Yao Chen427d3722018-03-22 15:21:52 -0700192void CountMetricProducer::onSlicedConditionMayChangeLocked(bool overallCondition,
Yangster-macb142cc82018-03-30 15:22:08 -0700193 const int64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800194 VLOG("Metric %lld onSlicedConditionMayChange", (long long)mMetricId);
Yao Chen729093d2017-10-16 10:33:26 -0700195}
196
Yangster-maca802d732018-04-24 07:50:38 -0700197
198void CountMetricProducer::clearPastBucketsLocked(const int64_t dumpTimeNs) {
Yangster-maca802d732018-04-24 07:50:38 -0700199 mPastBuckets.clear();
200}
201
Yangster-macb142cc82018-03-30 15:22:08 -0700202void CountMetricProducer::onDumpReportLocked(const int64_t dumpTimeNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700203 const bool include_current_partial_bucket,
Bookatzff71cad2018-09-20 17:17:49 -0700204 const bool erase_data,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000205 const DumpLatency dumpLatency,
Yangster-mac9def8e32018-04-17 13:55:51 -0700206 std::set<string> *str_set,
Yao Chen288c6002017-12-12 13:43:18 -0800207 ProtoOutputStream* protoOutput) {
Yangster-mace68f3a52018-04-04 00:01:43 -0700208 if (include_current_partial_bucket) {
209 flushLocked(dumpTimeNs);
210 } else {
211 flushIfNeededLocked(dumpTimeNs);
212 }
Yang Lub4722912018-11-15 11:02:03 -0800213 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_ID, (long long)mMetricId);
Howard Ro07e23ff2018-12-17 17:28:07 -0800214 protoOutput->write(FIELD_TYPE_BOOL | FIELD_ID_IS_ACTIVE, isActiveLocked());
Yang Lub4722912018-11-15 11:02:03 -0800215
216
Yangster-mac635b4b32018-01-23 20:17:35 -0800217 if (mPastBuckets.empty()) {
218 return;
219 }
Yangster-mac9def8e32018-04-17 13:55:51 -0700220 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_TIME_BASE, (long long)mTimeBaseNs);
221 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_SIZE, (long long)mBucketSizeNs);
222
223 // Fills the dimension path if not slicing by ALL.
224 if (!mSliceByPositionALL) {
225 if (!mDimensionsInWhat.empty()) {
226 uint64_t dimenPathToken = protoOutput->start(
227 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_PATH_IN_WHAT);
228 writeDimensionPathToProto(mDimensionsInWhat, protoOutput);
229 protoOutput->end(dimenPathToken);
230 }
Yangster-mac9def8e32018-04-17 13:55:51 -0700231 }
232
Yi Jin5ee07872018-03-05 18:18:27 -0800233 uint64_t protoToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_ID_COUNT_METRICS);
Yao Chen288c6002017-12-12 13:43:18 -0800234
Yao Chen93fe3a32017-11-02 13:52:59 -0700235 for (const auto& counter : mPastBuckets) {
Yangster-mac93694462018-01-22 20:49:31 -0800236 const MetricDimensionKey& dimensionKey = counter.first;
Yangster13fb7e42018-03-07 17:30:49 -0800237 VLOG(" dimension key %s", dimensionKey.toString().c_str());
Yao Chend5aa01b32017-12-19 16:46:36 -0800238
Yi Jin5ee07872018-03-05 18:18:27 -0800239 uint64_t wrapperToken =
Yao Chen288c6002017-12-12 13:43:18 -0800240 protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_DATA);
Yao Chen729093d2017-10-16 10:33:26 -0700241
Yangster-mac20877162017-12-22 17:19:39 -0800242 // First fill dimension.
Yangster-mac9def8e32018-04-17 13:55:51 -0700243 if (mSliceByPositionALL) {
244 uint64_t dimensionToken = protoOutput->start(
245 FIELD_TYPE_MESSAGE | FIELD_ID_DIMENSION_IN_WHAT);
246 writeDimensionToProto(dimensionKey.getDimensionKeyInWhat(), str_set, protoOutput);
247 protoOutput->end(dimensionToken);
Yangster-mac9def8e32018-04-17 13:55:51 -0700248 } else {
249 writeDimensionLeafNodesToProto(dimensionKey.getDimensionKeyInWhat(),
250 FIELD_ID_DIMENSION_LEAF_IN_WHAT, str_set, protoOutput);
tsaichristine69000e62019-10-18 17:34:52 -0700251 }
252 // Then fill slice_by_state.
253 for (auto state : dimensionKey.getStateValuesKey().getValues()) {
254 uint64_t stateToken = protoOutput->start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED |
255 FIELD_ID_SLICE_BY_STATE);
256 writeStateToProto(state, protoOutput);
257 protoOutput->end(stateToken);
Yangster-mac93694462018-01-22 20:49:31 -0800258 }
yro24809bd2017-10-31 23:06:53 -0700259 // Then fill bucket_info (CountBucketInfo).
Yao Chen93fe3a32017-11-02 13:52:59 -0700260 for (const auto& bucket : counter.second) {
Yi Jin5ee07872018-03-05 18:18:27 -0800261 uint64_t bucketInfoToken = protoOutput->start(
Yao Chen288c6002017-12-12 13:43:18 -0800262 FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_BUCKET_INFO);
Yangster-mac9def8e32018-04-17 13:55:51 -0700263 // Partial bucket.
264 if (bucket.mBucketEndNs - bucket.mBucketStartNs != mBucketSizeNs) {
265 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_START_BUCKET_ELAPSED_MILLIS,
266 (long long)NanoToMillis(bucket.mBucketStartNs));
267 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_END_BUCKET_ELAPSED_MILLIS,
268 (long long)NanoToMillis(bucket.mBucketEndNs));
269 } else {
270 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_BUCKET_NUM,
271 (long long)(getBucketNumFromEndTimeNs(bucket.mBucketEndNs)));
272 }
Yao Chen288c6002017-12-12 13:43:18 -0800273 protoOutput->write(FIELD_TYPE_INT64 | FIELD_ID_COUNT, (long long)bucket.mCount);
274 protoOutput->end(bucketInfoToken);
Yao Chen93fe3a32017-11-02 13:52:59 -0700275 VLOG("\t bucket [%lld - %lld] count: %lld", (long long)bucket.mBucketStartNs,
276 (long long)bucket.mBucketEndNs, (long long)bucket.mCount);
yro24809bd2017-10-31 23:06:53 -0700277 }
Yao Chen288c6002017-12-12 13:43:18 -0800278 protoOutput->end(wrapperToken);
Yao Chen729093d2017-10-16 10:33:26 -0700279 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000280
Yao Chen288c6002017-12-12 13:43:18 -0800281 protoOutput->end(protoToken);
yro24809bd2017-10-31 23:06:53 -0700282
Bookatzff71cad2018-09-20 17:17:49 -0700283 if (erase_data) {
284 mPastBuckets.clear();
285 }
Yao Chen06dba5d2018-01-26 13:38:16 -0800286}
Yao Chen6a8c7992017-11-29 20:02:07 +0000287
Yangster-macb142cc82018-03-30 15:22:08 -0700288void CountMetricProducer::dropDataLocked(const int64_t dropTimeNs) {
Yao Chen06dba5d2018-01-26 13:38:16 -0800289 flushIfNeededLocked(dropTimeNs);
Olivier Gaillard320952b2019-02-06 13:57:24 +0000290 StatsdStats::getInstance().noteBucketDropped(mMetricId);
Yao Chen06dba5d2018-01-26 13:38:16 -0800291 mPastBuckets.clear();
Yao Chen44cf27c2017-09-14 22:32:50 -0700292}
293
Yangsterf2bee6f2017-11-29 12:01:05 -0800294void CountMetricProducer::onConditionChangedLocked(const bool conditionMet,
Yangster-macb142cc82018-03-30 15:22:08 -0700295 const int64_t eventTime) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800296 VLOG("Metric %lld onConditionChanged", (long long)mMetricId);
Olivier Gaillarde63d9e02019-02-12 14:43:59 +0000297 mCondition = conditionMet ? ConditionState::kTrue : ConditionState::kFalse;
Yao Chencaf339d2017-10-06 16:01:10 -0700298}
299
Yangster-mac93694462018-01-22 20:49:31 -0800300bool CountMetricProducer::hitGuardRailLocked(const MetricDimensionKey& newKey) {
Yao Chenb3561512017-11-21 18:07:17 -0800301 if (mCurrentSlicedCounter->find(newKey) != mCurrentSlicedCounter->end()) {
302 return false;
303 }
304 // ===========GuardRail==============
305 // 1. Report the tuple count if the tuple count > soft limit
306 if (mCurrentSlicedCounter->size() > StatsdStats::kDimensionKeySizeSoftLimit - 1) {
307 size_t newTupleCount = mCurrentSlicedCounter->size() + 1;
Yangster-mac94e197c2018-01-02 16:03:03 -0800308 StatsdStats::getInstance().noteMetricDimensionSize(mConfigKey, mMetricId, newTupleCount);
Yao Chenb3561512017-11-21 18:07:17 -0800309 // 2. Don't add more tuples, we are above the allowed threshold. Drop the data.
310 if (newTupleCount > StatsdStats::kDimensionKeySizeHardLimit) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800311 ALOGE("CountMetric %lld dropping data for dimension key %s",
Yangster13fb7e42018-03-07 17:30:49 -0800312 (long long)mMetricId, newKey.toString().c_str());
Muhammad Qureshi87348a62019-02-14 16:17:52 -0800313 StatsdStats::getInstance().noteHardDimensionLimitReached(mMetricId);
Yao Chenb3561512017-11-21 18:07:17 -0800314 return true;
315 }
316 }
317
318 return false;
319}
Yangsterf2bee6f2017-11-29 12:01:05 -0800320
321void CountMetricProducer::onMatchedLogEventInternalLocked(
Yangster-mac93694462018-01-22 20:49:31 -0800322 const size_t matcherIndex, const MetricDimensionKey& eventKey,
tsaichristinec876b492019-12-10 13:47:05 -0800323 const ConditionKey& conditionKey, bool condition, const LogEvent& event,
324 const map<int, HashableDimensionKey>& statePrimaryKeys) {
Yangster-macb142cc82018-03-30 15:22:08 -0700325 int64_t eventTimeNs = event.GetElapsedTimestampNs();
Yangsterf2bee6f2017-11-29 12:01:05 -0800326 flushIfNeededLocked(eventTimeNs);
Yao Chen729093d2017-10-16 10:33:26 -0700327
tsaichristine69000e62019-10-18 17:34:52 -0700328 if (!condition) {
Yao Chenb7041772017-10-20 16:59:25 -0700329 return;
Yao Chen44cf27c2017-09-14 22:32:50 -0700330 }
Yao Chen729093d2017-10-16 10:33:26 -0700331
Yao Chen6a8c7992017-11-29 20:02:07 +0000332 auto it = mCurrentSlicedCounter->find(eventKey);
Yao Chen6a8c7992017-11-29 20:02:07 +0000333 if (it == mCurrentSlicedCounter->end()) {
334 // ===========GuardRail==============
Yangsterf2bee6f2017-11-29 12:01:05 -0800335 if (hitGuardRailLocked(eventKey)) {
Yao Chenb3561512017-11-21 18:07:17 -0800336 return;
337 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000338 // create a counter for the new key
339 (*mCurrentSlicedCounter)[eventKey] = 1;
340 } else {
341 // increment the existing value
342 auto& count = it->second;
343 count++;
Yao Chen729093d2017-10-16 10:33:26 -0700344 }
Yao Chen6a8c7992017-11-29 20:02:07 +0000345 for (auto& tracker : mAnomalyTrackers) {
David Chen27785a82018-01-19 17:06:45 -0800346 int64_t countWholeBucket = mCurrentSlicedCounter->find(eventKey)->second;
347 auto prev = mCurrentFullCounters->find(eventKey);
348 if (prev != mCurrentFullCounters->end()) {
349 countWholeBucket += prev->second;
350 }
Yao Chen4ce07292019-02-13 13:06:36 -0800351 tracker->detectAndDeclareAnomaly(eventTimeNs, mCurrentBucketNum, mMetricId, eventKey,
David Chen27785a82018-01-19 17:06:45 -0800352 countWholeBucket);
Yao Chen6a8c7992017-11-29 20:02:07 +0000353 }
354
Yangster13fb7e42018-03-07 17:30:49 -0800355 VLOG("metric %lld %s->%lld", (long long)mMetricId, eventKey.toString().c_str(),
Yao Chen6a8c7992017-11-29 20:02:07 +0000356 (long long)(*mCurrentSlicedCounter)[eventKey]);
Yao Chen44cf27c2017-09-14 22:32:50 -0700357}
358
Yao Chen729093d2017-10-16 10:33:26 -0700359// When a new matched event comes in, we check if event falls into the current
360// bucket. If not, flush the old counter to past buckets and initialize the new bucket.
Yangster-macb142cc82018-03-30 15:22:08 -0700361void CountMetricProducer::flushIfNeededLocked(const int64_t& eventTimeNs) {
362 int64_t currentBucketEndTimeNs = getCurrentBucketEndTimeNs();
David Chen27785a82018-01-19 17:06:45 -0800363 if (eventTimeNs < currentBucketEndTimeNs) {
Yao Chen44cf27c2017-09-14 22:32:50 -0700364 return;
365 }
366
David Chen27785a82018-01-19 17:06:45 -0800367 // Setup the bucket start time and number.
Yangster-macb142cc82018-03-30 15:22:08 -0700368 int64_t numBucketsForward = 1 + (eventTimeNs - currentBucketEndTimeNs) / mBucketSizeNs;
Muhammad Qureshi902529a2019-03-14 16:03:21 -0700369 int64_t nextBucketNs = currentBucketEndTimeNs + (numBucketsForward - 1) * mBucketSizeNs;
370 flushCurrentBucketLocked(eventTimeNs, nextBucketNs);
371
David Chen27785a82018-01-19 17:06:45 -0800372 mCurrentBucketNum += numBucketsForward;
373 VLOG("metric %lld: new bucket start time: %lld", (long long)mMetricId,
374 (long long)mCurrentBucketStartTimeNs);
375}
376
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000377void CountMetricProducer::flushCurrentBucketLocked(const int64_t& eventTimeNs,
378 const int64_t& nextBucketStartTimeNs) {
Yangster-macb142cc82018-03-30 15:22:08 -0700379 int64_t fullBucketEndTimeNs = getCurrentBucketEndTimeNs();
Yao Chen93fe3a32017-11-02 13:52:59 -0700380 CountBucket info;
381 info.mBucketStartNs = mCurrentBucketStartTimeNs;
David Chen27785a82018-01-19 17:06:45 -0800382 if (eventTimeNs < fullBucketEndTimeNs) {
383 info.mBucketEndNs = eventTimeNs;
384 } else {
385 info.mBucketEndNs = fullBucketEndTimeNs;
386 }
Yang Lu3eba6212017-10-25 19:54:45 -0700387 for (const auto& counter : *mCurrentSlicedCounter) {
Yao Chen93fe3a32017-11-02 13:52:59 -0700388 info.mCount = counter.second;
389 auto& bucketList = mPastBuckets[counter.first];
390 bucketList.push_back(info);
Yangster13fb7e42018-03-07 17:30:49 -0800391 VLOG("metric %lld, dump key value: %s -> %lld", (long long)mMetricId,
392 counter.first.toString().c_str(),
David Chen27785a82018-01-19 17:06:45 -0800393 (long long)counter.second);
Yao Chen729093d2017-10-16 10:33:26 -0700394 }
395
David Chen27785a82018-01-19 17:06:45 -0800396 // If we have finished a full bucket, then send this to anomaly tracker.
397 if (eventTimeNs > fullBucketEndTimeNs) {
398 // Accumulate partial buckets with current value and then send to anomaly tracker.
399 if (mCurrentFullCounters->size() > 0) {
400 for (const auto& keyValuePair : *mCurrentSlicedCounter) {
401 (*mCurrentFullCounters)[keyValuePair.first] += keyValuePair.second;
402 }
403 for (auto& tracker : mAnomalyTrackers) {
404 tracker->addPastBucket(mCurrentFullCounters, mCurrentBucketNum);
405 }
406 mCurrentFullCounters = std::make_shared<DimToValMap>();
407 } else {
408 // Skip aggregating the partial buckets since there's no previous partial bucket.
409 for (auto& tracker : mAnomalyTrackers) {
410 tracker->addPastBucket(mCurrentSlicedCounter, mCurrentBucketNum);
411 }
412 }
413 } else {
414 // Accumulate partial bucket.
415 for (const auto& keyValuePair : *mCurrentSlicedCounter) {
416 (*mCurrentFullCounters)[keyValuePair.first] += keyValuePair.second;
417 }
Yang Lu3eba6212017-10-25 19:54:45 -0700418 }
Bookatzd3606c72017-10-19 10:13:49 -0700419
Olivier Gaillardf248c0d2019-02-21 15:56:58 +0000420 StatsdStats::getInstance().noteBucketCount(mMetricId);
David Chen27785a82018-01-19 17:06:45 -0800421 // Only resets the counters, but doesn't setup the times nor numbers.
422 // (Do not clear since the old one is still referenced in mAnomalyTrackers).
Yang Lu3eba6212017-10-25 19:54:45 -0700423 mCurrentSlicedCounter = std::make_shared<DimToValMap>();
Muhammad Qureshi902529a2019-03-14 16:03:21 -0700424 mCurrentBucketStartTimeNs = nextBucketStartTimeNs;
Yao Chen44cf27c2017-09-14 22:32:50 -0700425}
426
yro24809bd2017-10-31 23:06:53 -0700427// Rough estimate of CountMetricProducer buffer stored. This number will be
428// greater than actual data size as it contains each dimension of
429// CountMetricData is duplicated.
Yangsterf2bee6f2017-11-29 12:01:05 -0800430size_t CountMetricProducer::byteSizeLocked() const {
Yangster-mace2cd6d52017-11-09 20:38:30 -0800431 size_t totalSize = 0;
432 for (const auto& pair : mPastBuckets) {
433 totalSize += pair.second.size() * kBucketSize;
434 }
435 return totalSize;
yro69007c82017-10-26 20:42:57 -0700436}
437
Yao Chen44cf27c2017-09-14 22:32:50 -0700438} // namespace statsd
439} // namespace os
yro69007c82017-10-26 20:42:57 -0700440} // namespace android