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