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 #ifndef METRIC_PRODUCER_H
18 #define METRIC_PRODUCER_H
19
20 #include <src/active_config_list.pb.h>
21 #include <src/guardrail/stats_log_enums.pb.h>
22 #include <utils/RefBase.h>
23
24 #include <unordered_map>
25
26 #include "HashableDimensionKey.h"
27 #include "anomaly/AnomalyTracker.h"
28 #include "condition/ConditionTimer.h"
29 #include "condition/ConditionWizard.h"
30 #include "config/ConfigKey.h"
31 #include "config/ConfigMetadataProvider.h"
32 #include "guardrail/StatsdStats.h"
33 #include "matchers/EventMatcherWizard.h"
34 #include "matchers/matcher_util.h"
35 #include "packages/PackageInfoListener.h"
36 #include "src/statsd_metadata.pb.h" // MetricMetadata
37 #include "state/StateListener.h"
38 #include "state/StateManager.h"
39 #include "utils/DbUtils.h"
40 #include "utils/ShardOffsetProvider.h"
41 #include "utils/api_tracing.h"
42
43 namespace android {
44 namespace os {
45 namespace statsd {
46
47 // If the metric has no activation requirement, it will be active once the metric producer is
48 // created.
49 // If the metric needs to be activated by atoms, the metric producer will start
50 // with kNotActive state, turn to kActive or kActiveOnBoot when the activation event arrives, become
51 // kNotActive when it reaches the duration limit (timebomb). If the activation event arrives again
52 // before or after it expires, the event producer will be re-activated and ttl will be reset.
53 enum ActivationState {
54 kNotActive = 0,
55 kActive = 1,
56 kActiveOnBoot = 2,
57 };
58
59 enum DumpLatency {
60 // In some cases, we only have a short time range to do the dump, e.g. statsd is being killed.
61 // We might be able to return all the data in this mode. For instance, pull metrics might need
62 // to be pulled when the current bucket is requested.
63 FAST = 1,
64 // In other cases, it is fine for a dump to take more than a few milliseconds, e.g. config
65 // updates.
66 NO_TIME_CONSTRAINTS = 2
67 };
68
69 enum MetricType {
70 METRIC_TYPE_EVENT = 1,
71 METRIC_TYPE_COUNT = 2,
72 METRIC_TYPE_DURATION = 3,
73 METRIC_TYPE_GAUGE = 4,
74 METRIC_TYPE_VALUE = 5,
75 METRIC_TYPE_KLL = 6,
76 };
77
78 struct Activation {
ActivationActivation79 Activation(const ActivationType& activationType, int64_t ttlNs)
80 : ttl_ns(ttlNs),
81 start_ns(0),
82 state(ActivationState::kNotActive),
83 activationType(activationType) {
84 }
85
86 const int64_t ttl_ns;
87 int64_t start_ns;
88 ActivationState state;
89 const ActivationType activationType;
90 };
91
92 struct DropEvent {
93 // Reason for dropping the bucket and/or marking the bucket invalid.
94 BucketDropReason reason;
95 // The timestamp of the drop event.
96 int64_t dropTimeNs;
97 };
98
99 struct SkippedBucket {
100 // Start time of the dropped bucket.
101 int64_t bucketStartTimeNs;
102 // End time of the dropped bucket.
103 int64_t bucketEndTimeNs;
104 // List of events that invalidated this bucket.
105 std::vector<DropEvent> dropEvents;
106
resetSkippedBucket107 void reset() {
108 bucketStartTimeNs = 0;
109 bucketEndTimeNs = 0;
110 dropEvents.clear();
111 }
112 };
113
114 struct SamplingInfo {
115 // Matchers for sampled fields. Currently only one sampled dimension is supported.
116 std::vector<Matcher> sampledWhatFields;
117
118 int shardCount = 0;
119 };
120
121 template <class T>
getAppUpgradeBucketSplit(const T & metric)122 optional<bool> getAppUpgradeBucketSplit(const T& metric) {
123 return metric.has_split_bucket_for_app_upgrade()
124 ? std::make_optional<bool>(metric.split_bucket_for_app_upgrade())
125 : std::nullopt;
126 }
127
128 // A MetricProducer is responsible for compute one single metric, creating stats log report, and
129 // writing the report to dropbox. MetricProducers should respond to package changes as required in
130 // PackageInfoListener, but if none of the metrics are slicing by package name, then the update can
131 // be a no-op.
132 class MetricProducer : public virtual RefBase, public virtual StateListener {
133 public:
134 MetricProducer(int64_t metricId, const ConfigKey& key, int64_t timeBaseNs,
135 const int conditionIndex, const vector<ConditionState>& initialConditionCache,
136 const sp<ConditionWizard>& wizard, const uint64_t protoHash,
137 const std::unordered_map<int, std::shared_ptr<Activation>>& eventActivationMap,
138 const std::unordered_map<int, std::vector<std::shared_ptr<Activation>>>&
139 eventDeactivationMap,
140 const vector<int>& slicedStateAtoms,
141 const unordered_map<int, unordered_map<int, int64_t>>& stateGroupMap,
142 const optional<bool> splitBucketForAppUpgrade,
143 const wp<ConfigMetadataProvider> configMetadataProvider);
144
~MetricProducer()145 virtual ~MetricProducer(){};
146
initialCondition(const int conditionIndex,const vector<ConditionState> & initialConditionCache)147 ConditionState initialCondition(const int conditionIndex,
148 const vector<ConditionState>& initialConditionCache) const {
149 return conditionIndex >= 0 ? initialConditionCache[conditionIndex] : ConditionState::kTrue;
150 }
151
152 // Update appropriate state on config updates. Primarily, all indices need to be updated.
153 // This metric and all of its dependencies are guaranteed to be preserved across the update.
154 // This function also updates several maps used by metricsManager.
155 // This function clears all anomaly trackers. All anomaly trackers need to be added again.
onConfigUpdated(const StatsdConfig & config,int configIndex,int metricIndex,const std::vector<sp<AtomMatchingTracker>> & allAtomMatchingTrackers,const std::unordered_map<int64_t,int> & oldAtomMatchingTrackerMap,const std::unordered_map<int64_t,int> & newAtomMatchingTrackerMap,const sp<EventMatcherWizard> & matcherWizard,const std::vector<sp<ConditionTracker>> & allConditionTrackers,const std::unordered_map<int64_t,int> & conditionTrackerMap,const sp<ConditionWizard> & wizard,const std::unordered_map<int64_t,int> & metricToActivationMap,std::unordered_map<int,std::vector<int>> & trackerToMetricMap,std::unordered_map<int,std::vector<int>> & conditionToMetricMap,std::unordered_map<int,std::vector<int>> & activationAtomTrackerToMetricMap,std::unordered_map<int,std::vector<int>> & deactivationAtomTrackerToMetricMap,std::vector<int> & metricsWithActivation)156 optional<InvalidConfigReason> onConfigUpdated(
157 const StatsdConfig& config, int configIndex, int metricIndex,
158 const std::vector<sp<AtomMatchingTracker>>& allAtomMatchingTrackers,
159 const std::unordered_map<int64_t, int>& oldAtomMatchingTrackerMap,
160 const std::unordered_map<int64_t, int>& newAtomMatchingTrackerMap,
161 const sp<EventMatcherWizard>& matcherWizard,
162 const std::vector<sp<ConditionTracker>>& allConditionTrackers,
163 const std::unordered_map<int64_t, int>& conditionTrackerMap,
164 const sp<ConditionWizard>& wizard,
165 const std::unordered_map<int64_t, int>& metricToActivationMap,
166 std::unordered_map<int, std::vector<int>>& trackerToMetricMap,
167 std::unordered_map<int, std::vector<int>>& conditionToMetricMap,
168 std::unordered_map<int, std::vector<int>>& activationAtomTrackerToMetricMap,
169 std::unordered_map<int, std::vector<int>>& deactivationAtomTrackerToMetricMap,
170 std::vector<int>& metricsWithActivation) {
171 std::lock_guard<std::mutex> lock(mMutex);
172 return onConfigUpdatedLocked(config, configIndex, metricIndex, allAtomMatchingTrackers,
173 oldAtomMatchingTrackerMap, newAtomMatchingTrackerMap,
174 matcherWizard, allConditionTrackers, conditionTrackerMap,
175 wizard, metricToActivationMap, trackerToMetricMap,
176 conditionToMetricMap, activationAtomTrackerToMetricMap,
177 deactivationAtomTrackerToMetricMap, metricsWithActivation);
178 };
179
180 /**
181 * Force a partial bucket split on app upgrade
182 */
notifyAppUpgrade(int64_t eventTimeNs)183 void notifyAppUpgrade(int64_t eventTimeNs) {
184 std::lock_guard<std::mutex> lock(mMutex);
185 const bool splitBucket =
186 mSplitBucketForAppUpgrade ? mSplitBucketForAppUpgrade.value() : false;
187 if (!splitBucket) {
188 return;
189 }
190 notifyAppUpgradeInternalLocked(eventTimeNs);
191 };
192
notifyAppRemoved(int64_t eventTimeNs)193 void notifyAppRemoved(int64_t eventTimeNs) {
194 // Force buckets to split on removal also.
195 notifyAppUpgrade(eventTimeNs);
196 };
197
198 /**
199 * Force a partial bucket split on boot complete.
200 */
onStatsdInitCompleted(int64_t eventTimeNs)201 virtual void onStatsdInitCompleted(int64_t eventTimeNs) {
202 ATRACE_CALL();
203 std::lock_guard<std::mutex> lock(mMutex);
204 flushLocked(eventTimeNs);
205 }
206
207 // Consume the parsed stats log entry that already matched the "what" of the metric.
onMatchedLogEvent(const size_t matcherIndex,const LogEvent & event)208 void onMatchedLogEvent(const size_t matcherIndex, const LogEvent& event) {
209 std::lock_guard<std::mutex> lock(mMutex);
210 onMatchedLogEventLocked(matcherIndex, event);
211 }
212
213 enum class LostAtomType {
214 kWhat = 0,
215 kCondition,
216 };
217
onMatchedLogEventLost(int32_t atomId,DataCorruptedReason reason,LostAtomType atomType)218 void onMatchedLogEventLost(int32_t atomId, DataCorruptedReason reason, LostAtomType atomType) {
219 std::lock_guard<std::mutex> lock(mMutex);
220 onMatchedLogEventLostLocked(atomId, reason, atomType);
221 }
222
onConditionChanged(const bool condition,int64_t eventTime)223 void onConditionChanged(const bool condition, int64_t eventTime) {
224 std::lock_guard<std::mutex> lock(mMutex);
225 onConditionChangedLocked(condition, eventTime);
226 }
227
onSlicedConditionMayChange(bool overallCondition,int64_t eventTime)228 void onSlicedConditionMayChange(bool overallCondition, int64_t eventTime) {
229 std::lock_guard<std::mutex> lock(mMutex);
230 onSlicedConditionMayChangeLocked(overallCondition, eventTime);
231 }
232
isConditionSliced()233 bool isConditionSliced() const {
234 std::lock_guard<std::mutex> lock(mMutex);
235 return mConditionSliced;
236 };
237
onStateChanged(const int64_t eventTimeNs,const int32_t atomId,const HashableDimensionKey & primaryKey,const FieldValue & oldState,const FieldValue & newState)238 void onStateChanged(const int64_t eventTimeNs, const int32_t atomId,
239 const HashableDimensionKey& primaryKey, const FieldValue& oldState,
240 const FieldValue& newState){};
241
242 // Output the metrics data to [protoOutput]. All metrics reports end with the same timestamp.
243 // This method clears all the past buckets.
onDumpReport(const int64_t dumpTimeNs,const bool include_current_partial_bucket,const bool erase_data,const DumpLatency dumpLatency,std::set<string> * str_set,android::util::ProtoOutputStream * protoOutput)244 void onDumpReport(const int64_t dumpTimeNs, const bool include_current_partial_bucket,
245 const bool erase_data, const DumpLatency dumpLatency,
246 std::set<string>* str_set, android::util::ProtoOutputStream* protoOutput) {
247 std::lock_guard<std::mutex> lock(mMutex);
248 onDumpReportLocked(dumpTimeNs, include_current_partial_bucket, erase_data, dumpLatency,
249 str_set, protoOutput);
250 }
251
252 virtual optional<InvalidConfigReason> onConfigUpdatedLocked(
253 const StatsdConfig& config, int configIndex, int metricIndex,
254 const std::vector<sp<AtomMatchingTracker>>& allAtomMatchingTrackers,
255 const std::unordered_map<int64_t, int>& oldAtomMatchingTrackerMap,
256 const std::unordered_map<int64_t, int>& newAtomMatchingTrackerMap,
257 const sp<EventMatcherWizard>& matcherWizard,
258 const std::vector<sp<ConditionTracker>>& allConditionTrackers,
259 const std::unordered_map<int64_t, int>& conditionTrackerMap,
260 const sp<ConditionWizard>& wizard,
261 const std::unordered_map<int64_t, int>& metricToActivationMap,
262 std::unordered_map<int, std::vector<int>>& trackerToMetricMap,
263 std::unordered_map<int, std::vector<int>>& conditionToMetricMap,
264 std::unordered_map<int, std::vector<int>>& activationAtomTrackerToMetricMap,
265 std::unordered_map<int, std::vector<int>>& deactivationAtomTrackerToMetricMap,
266 std::vector<int>& metricsWithActivation);
267
clearPastBuckets(const int64_t dumpTimeNs)268 void clearPastBuckets(const int64_t dumpTimeNs) {
269 std::lock_guard<std::mutex> lock(mMutex);
270 clearPastBucketsLocked(dumpTimeNs);
271 }
272
prepareFirstBucket()273 void prepareFirstBucket() {
274 std::lock_guard<std::mutex> lock(mMutex);
275 prepareFirstBucketLocked();
276 }
277
278 // Returns the memory in bytes currently used to store this metric's data. Does not change
279 // state.
byteSize()280 size_t byteSize() const {
281 std::lock_guard<std::mutex> lock(mMutex);
282 return byteSizeLocked();
283 }
284
dumpStates(int out,bool verbose)285 void dumpStates(int out, bool verbose) const {
286 std::lock_guard<std::mutex> lock(mMutex);
287 dumpStatesLocked(out, verbose);
288 }
289
290 // Let MetricProducer drop in-memory data to save memory.
291 // We still need to keep future data valid and anomaly tracking work, which means we will
292 // have to flush old data, informing anomaly trackers then safely drop old data.
293 // We still keep current bucket data for future metrics' validity.
dropData(const int64_t dropTimeNs)294 void dropData(const int64_t dropTimeNs) {
295 std::lock_guard<std::mutex> lock(mMutex);
296 dropDataLocked(dropTimeNs);
297 }
298
loadActiveMetric(const ActiveMetric & activeMetric,int64_t currentTimeNs)299 void loadActiveMetric(const ActiveMetric& activeMetric, int64_t currentTimeNs) {
300 std::lock_guard<std::mutex> lock(mMutex);
301 loadActiveMetricLocked(activeMetric, currentTimeNs);
302 }
303
activate(int activationTrackerIndex,int64_t elapsedTimestampNs)304 void activate(int activationTrackerIndex, int64_t elapsedTimestampNs) {
305 std::lock_guard<std::mutex> lock(mMutex);
306 activateLocked(activationTrackerIndex, elapsedTimestampNs);
307 }
308
cancelEventActivation(int deactivationTrackerIndex)309 void cancelEventActivation(int deactivationTrackerIndex) {
310 std::lock_guard<std::mutex> lock(mMutex);
311 cancelEventActivationLocked(deactivationTrackerIndex);
312 }
313
isActive()314 bool isActive() const {
315 std::lock_guard<std::mutex> lock(mMutex);
316 return isActiveLocked();
317 }
318
319 void flushIfExpire(int64_t elapsedTimestampNs);
320
321 void writeActiveMetricToProtoOutputStream(int64_t currentTimeNs, const DumpReportReason reason,
322 ProtoOutputStream* proto);
323
enforceRestrictedDataTtl(sqlite3 * db,int64_t wallClockNs)324 virtual void enforceRestrictedDataTtl(sqlite3* db, int64_t wallClockNs){};
325
writeMetricMetadataToProto(metadata::MetricMetadata * metricMetadata)326 virtual bool writeMetricMetadataToProto(metadata::MetricMetadata* metricMetadata) {
327 return false;
328 }
329
loadMetricMetadataFromProto(const metadata::MetricMetadata & metricMetadata)330 virtual void loadMetricMetadataFromProto(const metadata::MetricMetadata& metricMetadata){};
331
332 /* Called when the metric is to about to be removed from config. */
onMetricRemove()333 virtual void onMetricRemove() {
334 }
335
flushRestrictedData()336 virtual void flushRestrictedData() {
337 }
338
339 // Start: getters/setters
getMetricId()340 inline int64_t getMetricId() const {
341 return mMetricId;
342 }
343
getProtoHash()344 inline uint64_t getProtoHash() const {
345 return mProtoHash;
346 }
347
348 virtual MetricType getMetricType() const = 0;
349
350 // For test only.
getCurrentBucketNum()351 inline int64_t getCurrentBucketNum() const {
352 return mCurrentBucketNum;
353 }
354
getSlicedStateAtoms()355 inline const std::vector<int> getSlicedStateAtoms() {
356 std::lock_guard<std::mutex> lock(mMutex);
357 return mSlicedStateAtoms;
358 }
359
isValid()360 inline bool isValid() const {
361 return mValid;
362 }
363
364 /* Adds an AnomalyTracker and returns it. */
addAnomalyTracker(const Alert & alert,const sp<AlarmMonitor> & anomalyAlarmMonitor,const UpdateStatus & updateStatus,const int64_t updateTimeNs)365 virtual sp<AnomalyTracker> addAnomalyTracker(const Alert& alert,
366 const sp<AlarmMonitor>& anomalyAlarmMonitor,
367 const UpdateStatus& updateStatus,
368 const int64_t updateTimeNs) {
369 std::lock_guard<std::mutex> lock(mMutex);
370 sp<AnomalyTracker> anomalyTracker = new AnomalyTracker(alert, mConfigKey);
371 mAnomalyTrackers.push_back(anomalyTracker);
372 return anomalyTracker;
373 }
374
375 /* Adds an AnomalyTracker that has already been created */
addAnomalyTracker(sp<AnomalyTracker> & anomalyTracker,int64_t updateTimeNs)376 virtual void addAnomalyTracker(sp<AnomalyTracker>& anomalyTracker, int64_t updateTimeNs) {
377 std::lock_guard<std::mutex> lock(mMutex);
378 mAnomalyTrackers.push_back(anomalyTracker);
379 }
380
setSamplingInfo(SamplingInfo samplingInfo)381 void setSamplingInfo(SamplingInfo samplingInfo) {
382 std::lock_guard<std::mutex> lock(mMutex);
383 mSampledWhatFields.swap(samplingInfo.sampledWhatFields);
384 mShardCount = samplingInfo.shardCount;
385 }
386 // End: getters/setters
387 protected:
388 /**
389 * Flushes the current bucket if the eventTime is after the current bucket's end time.
390 */
flushIfNeededLocked(int64_t eventTime)391 virtual void flushIfNeededLocked(int64_t eventTime){};
392
393 /**
394 * For metrics that aggregate (ie, every metric producer except for EventMetricProducer),
395 * we need to be able to flush the current buckets on demand (ie, end the current bucket and
396 * start new bucket). If this function is called when eventTimeNs is greater than the current
397 * bucket's end timestamp, than we flush up to the end of the latest full bucket; otherwise,
398 * we assume that we want to flush a partial bucket. The bucket start timestamp and bucket
399 * number are not changed by this function. This method should only be called by
400 * flushIfNeededLocked or flushLocked or the app upgrade handler; the caller MUST update the
401 * bucket timestamp and bucket number as needed.
402 */
flushCurrentBucketLocked(int64_t eventTimeNs,int64_t nextBucketStartTimeNs)403 virtual void flushCurrentBucketLocked(int64_t eventTimeNs, int64_t nextBucketStartTimeNs){};
404
405 /**
406 * Flushes all the data including the current partial bucket.
407 */
flushLocked(int64_t eventTimeNs)408 void flushLocked(int64_t eventTimeNs) {
409 flushIfNeededLocked(eventTimeNs);
410 flushCurrentBucketLocked(eventTimeNs, eventTimeNs);
411 };
412
notifyAppUpgradeInternalLocked(const int64_t eventTimeNs)413 virtual void notifyAppUpgradeInternalLocked(const int64_t eventTimeNs) {
414 flushLocked(eventTimeNs);
415 }
416
417 /*
418 * Individual metrics can implement their own business logic here. All pre-processing is done.
419 *
420 * [matcherIndex]: the index of the matcher which matched this event. This is interesting to
421 * DurationMetric, because it has start/stop/stop_all 3 matchers.
422 * [eventKey]: the extracted dimension key for the final output. if the metric doesn't have
423 * dimensions, it will be DEFAULT_DIMENSION_KEY
424 * [conditionKey]: the keys of conditions which should be used to query the condition for this
425 * target event (from MetricConditionLink). This is passed to individual metrics
426 * because DurationMetric needs it to be cached.
427 * [condition]: whether condition is met. If condition is sliced, this is the result coming from
428 * query with ConditionWizard; If condition is not sliced, this is the
429 * nonSlicedCondition.
430 * [event]: the log event, just in case the metric needs its data, e.g., EventMetric.
431 */
432 virtual void onMatchedLogEventInternalLocked(
433 const size_t matcherIndex, const MetricDimensionKey& eventKey,
434 const ConditionKey& conditionKey, bool condition, const LogEvent& event,
435 const map<int, HashableDimensionKey>& statePrimaryKeys) = 0;
436
437 // Consume the parsed stats log entry that already matched the "what" of the metric.
438 virtual void onMatchedLogEventLocked(const size_t matcherIndex, const LogEvent& event);
439 virtual void onMatchedLogEventLostLocked(int32_t atomId, DataCorruptedReason reason,
440 LostAtomType atomType);
441 virtual void onConditionChangedLocked(const bool condition, int64_t eventTime) = 0;
442 virtual void onSlicedConditionMayChangeLocked(bool overallCondition,
443 const int64_t eventTime) = 0;
444 virtual void onDumpReportLocked(const int64_t dumpTimeNs,
445 const bool include_current_partial_bucket,
446 const bool erase_data, const DumpLatency dumpLatency,
447 std::set<string>* str_set,
448 android::util::ProtoOutputStream* protoOutput) = 0;
449 virtual void clearPastBucketsLocked(const int64_t dumpTimeNs) = 0;
prepareFirstBucketLocked()450 virtual void prepareFirstBucketLocked(){};
451 virtual size_t byteSizeLocked() const = 0;
452 virtual void dumpStatesLocked(int out, bool verbose) const = 0;
453 virtual void dropDataLocked(const int64_t dropTimeNs) = 0;
454 void loadActiveMetricLocked(const ActiveMetric& activeMetric, int64_t currentTimeNs);
455 void activateLocked(int activationTrackerIndex, int64_t elapsedTimestampNs);
456 void cancelEventActivationLocked(int deactivationTrackerIndex);
457
458 // Computes the size of a newly added bucket to this metric, taking into account any new
459 // dimensions that are introduced if necessary.
460 virtual size_t computeBucketSizeLocked(const bool isFullBucket,
461 const MetricDimensionKey& dimKey,
462 const bool isFirstBucket) const;
463 size_t computeOverheadSizeLocked(const bool hasPastBuckets,
464 const bool dimensionGuardrailHit) const;
465 size_t computeSkippedBucketSizeLocked(const SkippedBucket& skippedBucket) const;
466
467 bool evaluateActiveStateLocked(int64_t elapsedTimestampNs);
468
onActiveStateChangedLocked(const int64_t eventTimeNs,const bool isActive)469 virtual void onActiveStateChangedLocked(const int64_t eventTimeNs, const bool isActive) {
470 if (!isActive) {
471 flushLocked(eventTimeNs);
472 }
473 }
474
isActiveLocked()475 inline bool isActiveLocked() const {
476 return mIsActive;
477 }
478
479 // Convenience to compute the current bucket's end time, which is always aligned with the
480 // start time of the metric.
getCurrentBucketEndTimeNs()481 int64_t getCurrentBucketEndTimeNs() const {
482 return mTimeBaseNs + (mCurrentBucketNum + 1) * mBucketSizeNs;
483 }
484
getBucketNumFromEndTimeNs(const int64_t endNs)485 int64_t getBucketNumFromEndTimeNs(const int64_t endNs) {
486 return (endNs - mTimeBaseNs) / mBucketSizeNs - 1;
487 }
488
489 // Query StateManager for original state value using the queryKey.
490 // The field and value are output.
491 void queryStateValue(int32_t atomId, const HashableDimensionKey& queryKey, FieldValue* value);
492
493 // If a state map exists for the given atom, replace the original state
494 // value with the group id mapped to the value.
495 // If no state map exists, keep the original state value.
496 void mapStateValue(int32_t atomId, FieldValue* value);
497
498 // Returns a HashableDimensionKey with unknown state value for each state
499 // atom.
500 HashableDimensionKey getUnknownStateKey();
501
502 DropEvent buildDropEvent(const int64_t dropTimeNs, const BucketDropReason reason) const;
503
504 // Returns true if the number of drop events in the current bucket has
505 // exceeded the maximum number allowed, which is currently capped at 10.
506 bool maxDropEventsReached() const;
507
508 bool passesSampleCheckLocked(const vector<FieldValue>& values) const;
509
510 const int64_t mMetricId;
511
512 // Hash of the Metric's proto bytes from StatsdConfig, including any activations.
513 // Used to determine if the definition of this metric has changed across a config update.
514 const uint64_t mProtoHash;
515
516 const ConfigKey mConfigKey;
517
518 bool mValid;
519
520 // The time when this metric producer was first created. The end time for the current bucket
521 // can be computed from this based on mCurrentBucketNum.
522 int64_t mTimeBaseNs;
523
524 // Start time may not be aligned with the start of statsd if there is an app upgrade in the
525 // middle of a bucket.
526 int64_t mCurrentBucketStartTimeNs;
527
528 // Used by anomaly detector to track which bucket we are in. This is not sent with the produced
529 // report.
530 int64_t mCurrentBucketNum;
531
532 int64_t mBucketSizeNs;
533
534 ConditionState mCondition;
535
536 ConditionTimer mConditionTimer;
537
538 int mConditionTrackerIndex;
539
540 // TODO(b/185770739): use !mMetric2ConditionLinks.empty()
541 bool mConditionSliced;
542
543 sp<ConditionWizard> mWizard;
544
545 bool mContainANYPositionInDimensionsInWhat;
546
547 // Metrics slicing by primitive repeated field and/or position ALL need to use nested
548 // dimensions.
549 bool mShouldUseNestedDimensions;
550
551 vector<Matcher> mDimensionsInWhat; // The dimensions_in_what defined in statsd_config
552
553 // True iff the metric to condition links cover all dimension fields in the condition tracker.
554 // This field is always false for combinational condition trackers.
555 bool mHasLinksToAllConditionDimensionsInTracker;
556
557 std::vector<Metric2Condition> mMetric2ConditionLinks;
558
559 std::vector<sp<AnomalyTracker>> mAnomalyTrackers;
560
561 mutable std::mutex mMutex;
562
563 // When the metric producer has multiple activations, these activations are ORed to determine
564 // whether the metric producer is ready to generate metrics.
565 std::unordered_map<int, std::shared_ptr<Activation>> mEventActivationMap;
566
567 // Maps index of atom matcher for deactivation to a list of Activation structs.
568 std::unordered_map<int, std::vector<std::shared_ptr<Activation>>> mEventDeactivationMap;
569
570 bool mIsActive;
571
572 // The slice_by_state atom ids defined in statsd_config.
573 const std::vector<int32_t> mSlicedStateAtoms;
574
575 // Maps atom ids and state values to group_ids (<atom_id, <value, group_id>>).
576 const std::unordered_map<int32_t, std::unordered_map<int, int64_t>> mStateGroupMap;
577
578 // MetricStateLinks defined in statsd_config that link fields in the state
579 // atom to fields in the "what" atom.
580 std::vector<Metric2State> mMetric2StateLinks;
581
582 optional<UploadThreshold> mUploadThreshold;
583
584 const optional<bool> mSplitBucketForAppUpgrade;
585
586 SkippedBucket mCurrentSkippedBucket;
587 // Buckets that were invalidated and had their data dropped.
588 std::vector<SkippedBucket> mSkippedBuckets;
589
590 // If hard dimension guardrail is hit, do not spam logcat. This is a per bucket tracker.
591 mutable bool mHasHitGuardrail;
592
593 // Matchers for sampled fields. Currently only one sampled dimension is supported.
594 std::vector<Matcher> mSampledWhatFields;
595
596 int mShardCount;
597
598 sp<ConfigMetadataProvider> getConfigMetadataProvider() const;
599
600 wp<ConfigMetadataProvider> mConfigMetadataProvider;
601
602 enum DataCorruptionSeverity { kNone = 0, kResetOnDump, kUnrecoverable };
603
604 DataCorruptionSeverity mDataCorruptedDueToSocketLoss = DataCorruptionSeverity::kNone;
605 DataCorruptionSeverity mDataCorruptedDueToQueueOverflow = DataCorruptionSeverity::kNone;
606
607 /**
608 * @brief Determines DataCorruptionSeverity based on source and atom type being lost
609 *
610 * @return DataCorruptionSeverity
611 */
determineCorruptionSeverity(DataCorruptedReason reason,LostAtomType atomType)612 virtual DataCorruptionSeverity determineCorruptionSeverity(DataCorruptedReason reason,
613 LostAtomType atomType) const {
614 return DataCorruptionSeverity::kNone;
615 };
616
617 /**
618 * @brief Resets data corruption reason info if no unrecoverable errors observed
619 */
620 void resetDataCorruptionFlagsLocked();
621
622 size_t mTotalDataSize = 0;
623
624 FRIEND_TEST(CountMetricE2eTest, TestSlicedState);
625 FRIEND_TEST(CountMetricE2eTest, TestSlicedStateWithMap);
626 FRIEND_TEST(CountMetricE2eTest, TestMultipleSlicedStates);
627 FRIEND_TEST(CountMetricE2eTest, TestSlicedStateWithPrimaryFields);
628 FRIEND_TEST(CountMetricE2eTest, TestInitialConditionChanges);
629
630 FRIEND_TEST(DurationMetricE2eTest, TestOneBucket);
631 FRIEND_TEST(DurationMetricE2eTest, TestTwoBuckets);
632 FRIEND_TEST(DurationMetricE2eTest, TestWithActivation);
633 FRIEND_TEST(DurationMetricE2eTest, TestWithCondition);
634 FRIEND_TEST(DurationMetricE2eTest, TestWithSlicedCondition);
635 FRIEND_TEST(DurationMetricE2eTest, TestWithActivationAndSlicedCondition);
636 FRIEND_TEST(DurationMetricE2eTest, TestWithSlicedState);
637 FRIEND_TEST(DurationMetricE2eTest, TestWithConditionAndSlicedState);
638 FRIEND_TEST(DurationMetricE2eTest, TestWithSlicedStateMapped);
639 FRIEND_TEST(DurationMetricE2eTest, TestSlicedStatePrimaryFieldsNotSubsetDimInWhat);
640 FRIEND_TEST(DurationMetricE2eTest, TestWithSlicedStatePrimaryFieldsSubset);
641 FRIEND_TEST(DurationMetricE2eTest, TestUploadThreshold);
642
643 FRIEND_TEST(MetricActivationE2eTest, TestCountMetric);
644 FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithOneDeactivation);
645 FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithTwoDeactivations);
646 FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithSameDeactivation);
647 FRIEND_TEST(MetricActivationE2eTest, TestCountMetricWithTwoMetricsTwoDeactivations);
648
649 FRIEND_TEST(StatsLogProcessorTest, TestActiveConfigMetricDiskWriteRead);
650 FRIEND_TEST(StatsLogProcessorTest, TestActivationOnBoot);
651 FRIEND_TEST(StatsLogProcessorTest, TestActivationOnBootMultipleActivations);
652 FRIEND_TEST(StatsLogProcessorTest,
653 TestActivationOnBootMultipleActivationsDifferentActivationTypes);
654 FRIEND_TEST(StatsLogProcessorTest, TestActivationsPersistAcrossSystemServerRestart);
655
656 FRIEND_TEST(ValueMetricE2eTest, TestInitWithSlicedState);
657 FRIEND_TEST(ValueMetricE2eTest, TestInitWithSlicedState_WithDimensions);
658 FRIEND_TEST(ValueMetricE2eTest, TestInitWithSlicedState_WithIncorrectDimensions);
659 FRIEND_TEST(ValueMetricE2eTest, TestInitialConditionChanges);
660
661 FRIEND_TEST(SocketLossInfoTest, PropagationTest);
662
663 FRIEND_TEST(MetricsManagerUtilTest, TestInitialConditions);
664 FRIEND_TEST(MetricsManagerUtilTest, TestSampledMetrics);
665
666 FRIEND_TEST(ConfigUpdateTest, TestUpdateMetricActivations);
667 FRIEND_TEST(ConfigUpdateTest, TestUpdateCountMetrics);
668 FRIEND_TEST(ConfigUpdateTest, TestUpdateEventMetrics);
669 FRIEND_TEST(ConfigUpdateTest, TestUpdateGaugeMetrics);
670 FRIEND_TEST(ConfigUpdateTest, TestUpdateDurationMetrics);
671 FRIEND_TEST(ConfigUpdateTest, TestUpdateMetricsMultipleTypes);
672 FRIEND_TEST(ConfigUpdateTest, TestUpdateAlerts);
673
674 FRIEND_TEST(EventMetricProducerTest, TestCorruptedDataReason_OnDumpReport);
675 FRIEND_TEST(EventMetricProducerTest, TestCorruptedDataReason_OnDropData);
676 FRIEND_TEST(EventMetricProducerTest, TestCorruptedDataReason_OnClearPastBuckets);
677 FRIEND_TEST(EventMetricProducerTest, TestCorruptedDataReason_UnrecoverableLossOfCondition);
678 };
679
680 } // namespace statsd
681 } // namespace os
682 } // namespace android
683 #endif // METRIC_PRODUCER_H
684