blob: b21fd501c2d02319d4a62ae20d270cf800fc54fa [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
17#ifndef METRIC_PRODUCER_H
18#define METRIC_PRODUCER_H
19
Yangsterf2bee6f2017-11-29 12:01:05 -080020#include <shared_mutex>
21
Yao Chen8a8d16c2018-02-08 14:50:40 -080022#include "HashableDimensionKey.h"
Yangster-mace2cd6d52017-11-09 20:38:30 -080023#include "anomaly/AnomalyTracker.h"
Yao Chen729093d2017-10-16 10:33:26 -070024#include "condition/ConditionWizard.h"
Yao Chenb3561512017-11-21 18:07:17 -080025#include "config/ConfigKey.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070026#include "matchers/matcher_util.h"
27#include "packages/PackageInfoListener.h"
28
Yao Chen44cf27c2017-09-14 22:32:50 -070029#include <log/logprint.h>
Yao Chencaf339d2017-10-06 16:01:10 -070030#include <utils/RefBase.h>
Yao Chend10f7b12017-12-18 12:53:50 -080031#include <unordered_map>
Yao Chen44cf27c2017-09-14 22:32:50 -070032
33namespace android {
34namespace os {
35namespace statsd {
36
Yangster-mac849dfdc22018-10-12 15:41:45 -070037// If the metric has no activation requirement, it will be active once the metric producer is
38// created.
39// If the metric needs to be activated by atoms, the metric producer will start
40// with kNotActive state, turn to kActive when the activation event arrives, become kNotActive
41// when it reaches the duration limit (timebomb). If the activation event arrives again before
42// or after it expires, the event producer will be re-activated and ttl will be reset.
43enum ActivationState {
44 kNotActive = 0,
45 kActive = 1,
46};
47
Yao Chen44cf27c2017-09-14 22:32:50 -070048// A MetricProducer is responsible for compute one single metrics, creating stats log report, and
David Chende701692017-10-05 13:16:02 -070049// writing the report to dropbox. MetricProducers should respond to package changes as required in
50// PackageInfoListener, but if none of the metrics are slicing by package name, then the update can
51// be a no-op.
David Chenf12b5c62017-10-13 15:54:03 -070052class MetricProducer : public virtual PackageInfoListener {
Yao Chen44cf27c2017-09-14 22:32:50 -070053public:
Yangster-mac15f6bbc2018-04-08 11:52:26 -070054 MetricProducer(const int64_t& metricId, const ConfigKey& key, const int64_t timeBaseNs,
Yao Chenf09569f2017-12-13 17:00:51 -080055 const int conditionIndex, const sp<ConditionWizard>& wizard)
Yangster-mac94e197c2018-01-02 16:03:03 -080056 : mMetricId(metricId),
Yao Chenf09569f2017-12-13 17:00:51 -080057 mConfigKey(key),
Yangster-mac15f6bbc2018-04-08 11:52:26 -070058 mTimeBaseNs(timeBaseNs),
59 mCurrentBucketStartTimeNs(timeBaseNs),
Yang Lu3eba6212017-10-25 19:54:45 -070060 mCurrentBucketNum(0),
Yao Chen729093d2017-10-16 10:33:26 -070061 mCondition(conditionIndex >= 0 ? false : true),
Yao Chen93fe3a32017-11-02 13:52:59 -070062 mConditionSliced(false),
Yao Chen729093d2017-10-16 10:33:26 -070063 mWizard(wizard),
Yangster13fb7e42018-03-07 17:30:49 -080064 mConditionTrackerIndex(conditionIndex),
65 mContainANYPositionInDimensionsInWhat(false),
Yangster-mac9def8e32018-04-17 13:55:51 -070066 mSliceByPositionALL(false),
Yangster13fb7e42018-03-07 17:30:49 -080067 mSameConditionDimensionsInTracker(false),
Yangster-mac849dfdc22018-10-12 15:41:45 -070068 mHasLinksToAllConditionDimensionsInTracker(false),
69 mIsActive(true) {
Yangster13fb7e42018-03-07 17:30:49 -080070 }
Yangster-mac20877162017-12-22 17:19:39 -080071
Yao Chen44cf27c2017-09-14 22:32:50 -070072 virtual ~MetricProducer(){};
73
David Chen27785a82018-01-19 17:06:45 -080074 /**
75 * Forces this metric to split into a partial bucket right now. If we're past a full bucket, we
76 * first call the standard flushing code to flush up to the latest full bucket. Then we call
77 * the flush again when the end timestamp is forced to be now, and then after flushing, update
78 * the start timestamp to be now.
79 */
Yangster-macb142cc82018-03-30 15:22:08 -070080 void notifyAppUpgrade(const int64_t& eventTimeNs, const string& apk, const int uid,
David Chen27785a82018-01-19 17:06:45 -080081 const int64_t version) override {
82 std::lock_guard<std::mutex> lock(mMutex);
83
84 if (eventTimeNs > getCurrentBucketEndTimeNs()) {
85 // Flush full buckets on the normal path up to the latest bucket boundary.
86 flushIfNeededLocked(eventTimeNs);
87 }
88 // Now flush a partial bucket.
89 flushCurrentBucketLocked(eventTimeNs);
90 mCurrentBucketStartTimeNs = eventTimeNs;
91 // Don't update the current bucket number so that the anomaly tracker knows this bucket
92 // is a partial bucket and can merge it with the previous bucket.
93 };
94
Yangster-macb142cc82018-03-30 15:22:08 -070095 void notifyAppRemoved(const int64_t& eventTimeNs, const string& apk, const int uid) override{
David Chenbd125272018-04-04 19:02:50 -070096 // Force buckets to split on removal also.
97 notifyAppUpgrade(eventTimeNs, apk, uid, 0);
Yao Chend10f7b12017-12-18 12:53:50 -080098 };
99
Yangster-macb142cc82018-03-30 15:22:08 -0700100 void onUidMapReceived(const int64_t& eventTimeNs) override{
David Chenbd125272018-04-04 19:02:50 -0700101 // Purposefully don't flush partial buckets on a new snapshot.
102 // This occurs if a new user is added/removed or statsd crashes.
Yao Chend10f7b12017-12-18 12:53:50 -0800103 };
104
Yao Chencaf339d2017-10-06 16:01:10 -0700105 // Consume the parsed stats log entry that already matched the "what" of the metric.
Chenjie Yua7259ab2017-12-10 08:31:05 -0800106 void onMatchedLogEvent(const size_t matcherIndex, const LogEvent& event) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800107 std::lock_guard<std::mutex> lock(mMutex);
Yangster-mac849dfdc22018-10-12 15:41:45 -0700108 if (mIsActive) {
109 onMatchedLogEventLocked(matcherIndex, event);
110 }
Yangsterf2bee6f2017-11-29 12:01:05 -0800111 }
Yao Chen44cf27c2017-09-14 22:32:50 -0700112
Yangster-macb142cc82018-03-30 15:22:08 -0700113 void onConditionChanged(const bool condition, const int64_t eventTime) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800114 std::lock_guard<std::mutex> lock(mMutex);
Yangster-mac849dfdc22018-10-12 15:41:45 -0700115 if (mIsActive) {
116 onConditionChangedLocked(condition, eventTime);
117 }
Yangsterf2bee6f2017-11-29 12:01:05 -0800118 }
Yao Chencaf339d2017-10-06 16:01:10 -0700119
Yangster-macb142cc82018-03-30 15:22:08 -0700120 void onSlicedConditionMayChange(bool overallCondition, const int64_t eventTime) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800121 std::lock_guard<std::mutex> lock(mMutex);
Yangster-mac849dfdc22018-10-12 15:41:45 -0700122 if (mIsActive) {
123 onSlicedConditionMayChangeLocked(overallCondition, eventTime);
124 }
Yangsterf2bee6f2017-11-29 12:01:05 -0800125 }
126
127 bool isConditionSliced() const {
128 std::lock_guard<std::mutex> lock(mMutex);
129 return mConditionSliced;
130 };
Yao Chen729093d2017-10-16 10:33:26 -0700131
Yao Chen288c6002017-12-12 13:43:18 -0800132 // Output the metrics data to [protoOutput]. All metrics reports end with the same timestamp.
David Chen27785a82018-01-19 17:06:45 -0800133 // This method clears all the past buckets.
Yangster-mace68f3a52018-04-04 00:01:43 -0700134 void onDumpReport(const int64_t dumpTimeNs,
135 const bool include_current_partial_bucket,
Yangster-mac9def8e32018-04-17 13:55:51 -0700136 std::set<string> *str_set,
Yangster-mace68f3a52018-04-04 00:01:43 -0700137 android::util::ProtoOutputStream* protoOutput) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800138 std::lock_guard<std::mutex> lock(mMutex);
Yangster-mac9def8e32018-04-17 13:55:51 -0700139 return onDumpReportLocked(dumpTimeNs, include_current_partial_bucket, str_set, protoOutput);
Yangsterf2bee6f2017-11-29 12:01:05 -0800140 }
Yao Chen729093d2017-10-16 10:33:26 -0700141
Yangster-maca802d732018-04-24 07:50:38 -0700142 void clearPastBuckets(const int64_t dumpTimeNs) {
143 std::lock_guard<std::mutex> lock(mMutex);
144 return clearPastBucketsLocked(dumpTimeNs);
145 }
146
Yao Chen884c8c12018-01-26 10:36:25 -0800147 void dumpStates(FILE* out, bool verbose) const {
148 std::lock_guard<std::mutex> lock(mMutex);
149 dumpStatesLocked(out, verbose);
150 }
151
David Chen1d7b0cd2017-11-15 14:20:04 -0800152 // Returns the memory in bytes currently used to store this metric's data. Does not change
153 // state.
Yangsterf2bee6f2017-11-29 12:01:05 -0800154 size_t byteSize() const {
155 std::lock_guard<std::mutex> lock(mMutex);
156 return byteSizeLocked();
157 }
yro69007c82017-10-26 20:42:57 -0700158
Bookatz1476ef22018-02-13 12:26:01 -0800159 /* If alert is valid, adds an AnomalyTracker and returns it. If invalid, returns nullptr. */
Yangster-mac932ecec2018-02-01 10:23:52 -0800160 virtual sp<AnomalyTracker> addAnomalyTracker(const Alert &alert,
161 const sp<AlarmMonitor>& anomalyAlarmMonitor) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800162 std::lock_guard<std::mutex> lock(mMutex);
Bookatz857aaa52017-12-19 15:29:06 -0800163 sp<AnomalyTracker> anomalyTracker = new AnomalyTracker(alert, mConfigKey);
164 if (anomalyTracker != nullptr) {
165 mAnomalyTrackers.push_back(anomalyTracker);
166 }
167 return anomalyTracker;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800168 }
169
170 int64_t getBuckeSizeInNs() const {
Yangsterf2bee6f2017-11-29 12:01:05 -0800171 std::lock_guard<std::mutex> lock(mMutex);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800172 return mBucketSizeNs;
173 }
174
yro59cc24d2018-02-13 20:17:32 -0800175 // Only needed for unit-testing to override guardrail.
176 void setBucketSize(int64_t bucketSize) {
177 mBucketSizeNs = bucketSize;
178 }
179
Yangster-mac94e197c2018-01-02 16:03:03 -0800180 inline const int64_t& getMetricId() {
181 return mMetricId;
Yangster-mac20877162017-12-22 17:19:39 -0800182 }
183
Yao Chen06dba5d2018-01-26 13:38:16 -0800184 // Let MetricProducer drop in-memory data to save memory.
185 // We still need to keep future data valid and anomaly tracking work, which means we will
186 // have to flush old data, informing anomaly trackers then safely drop old data.
187 // We still keep current bucket data for future metrics' validity.
Yangster-macb142cc82018-03-30 15:22:08 -0700188 void dropData(const int64_t dropTimeNs) {
Yao Chen06dba5d2018-01-26 13:38:16 -0800189 std::lock_guard<std::mutex> lock(mMutex);
190 dropDataLocked(dropTimeNs);
191 }
192
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700193 // For test only.
194 inline int64_t getCurrentBucketNum() const {
195 return mCurrentBucketNum;
196 }
197
Yangster-mac849dfdc22018-10-12 15:41:45 -0700198 void activate(int activationTrackerIndex, int64_t elapsedTimestampNs) {
199 std::lock_guard<std::mutex> lock(mMutex);
200 activateLocked(activationTrackerIndex, elapsedTimestampNs);
201 }
202
203 void addActivation(int activationTrackerIndex, int64_t ttl_seconds);
204
205 void flushIfExpire(int64_t elapsedTimestampNs);
206
Yao Chen729093d2017-10-16 10:33:26 -0700207protected:
Yangster-macb142cc82018-03-30 15:22:08 -0700208 virtual void onConditionChangedLocked(const bool condition, const int64_t eventTime) = 0;
Yao Chen427d3722018-03-22 15:21:52 -0700209 virtual void onSlicedConditionMayChangeLocked(bool overallCondition,
Yangster-macb142cc82018-03-30 15:22:08 -0700210 const int64_t eventTime) = 0;
211 virtual void onDumpReportLocked(const int64_t dumpTimeNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700212 const bool include_current_partial_bucket,
Yangster-mac9def8e32018-04-17 13:55:51 -0700213 std::set<string> *str_set,
Yao Chen288c6002017-12-12 13:43:18 -0800214 android::util::ProtoOutputStream* protoOutput) = 0;
Yangster-maca802d732018-04-24 07:50:38 -0700215 virtual void clearPastBucketsLocked(const int64_t dumpTimeNs) = 0;
Yangsterf2bee6f2017-11-29 12:01:05 -0800216 virtual size_t byteSizeLocked() const = 0;
Yao Chen884c8c12018-01-26 10:36:25 -0800217 virtual void dumpStatesLocked(FILE* out, bool verbose) const = 0;
Yangsterf2bee6f2017-11-29 12:01:05 -0800218
Yangster-mac849dfdc22018-10-12 15:41:45 -0700219 bool evaluateActiveStateLocked(int64_t elapsedTimestampNs);
220
221 void activateLocked(int activationTrackerIndex, int64_t elapsedTimestampNs);
222
David Chen27785a82018-01-19 17:06:45 -0800223 /**
Yangster-mace68f3a52018-04-04 00:01:43 -0700224 * Flushes the current bucket if the eventTime is after the current bucket's end time. This will
225 also flush the current partial bucket in memory.
David Chen27785a82018-01-19 17:06:45 -0800226 */
Yangster-macb142cc82018-03-30 15:22:08 -0700227 virtual void flushIfNeededLocked(const int64_t& eventTime){};
David Chen27785a82018-01-19 17:06:45 -0800228
229 /**
Yangster-mace68f3a52018-04-04 00:01:43 -0700230 * Flushes all the data including the current partial bucket.
231 */
Yangster-mac849dfdc22018-10-12 15:41:45 -0700232 virtual void flushLocked(const int64_t& eventTimeNs) {
233 flushIfNeededLocked(eventTimeNs);
234 flushCurrentBucketLocked(eventTimeNs);
Yangster-mace68f3a52018-04-04 00:01:43 -0700235 };
236
237 /**
David Chen27785a82018-01-19 17:06:45 -0800238 * For metrics that aggregate (ie, every metric producer except for EventMetricProducer),
239 * we need to be able to flush the current buckets on demand (ie, end the current bucket and
240 * start new bucket). If this function is called when eventTimeNs is greater than the current
241 * bucket's end timestamp, than we flush up to the end of the latest full bucket; otherwise,
242 * we assume that we want to flush a partial bucket. The bucket start timestamp and bucket
243 * number are not changed by this function. This method should only be called by
244 * flushIfNeededLocked or the app upgrade handler; the caller MUST update the bucket timestamp
245 * and bucket number as needed.
246 */
Yangster-macb142cc82018-03-30 15:22:08 -0700247 virtual void flushCurrentBucketLocked(const int64_t& eventTimeNs){};
David Chen27785a82018-01-19 17:06:45 -0800248
249 // Convenience to compute the current bucket's end time, which is always aligned with the
250 // start time of the metric.
Yangster-macb142cc82018-03-30 15:22:08 -0700251 int64_t getCurrentBucketEndTimeNs() const {
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700252 return mTimeBaseNs + (mCurrentBucketNum + 1) * mBucketSizeNs;
David Chen27785a82018-01-19 17:06:45 -0800253 }
254
Yangster-mac9def8e32018-04-17 13:55:51 -0700255 int64_t getBucketNumFromEndTimeNs(const int64_t endNs) {
256 return (endNs - mTimeBaseNs) / mBucketSizeNs - 1;
257 }
258
Yangster-macb142cc82018-03-30 15:22:08 -0700259 virtual void dropDataLocked(const int64_t dropTimeNs) = 0;
Yao Chen06dba5d2018-01-26 13:38:16 -0800260
Yangster-mac94e197c2018-01-02 16:03:03 -0800261 const int64_t mMetricId;
Yao Chenf09569f2017-12-13 17:00:51 -0800262
Yao Chenb3561512017-11-21 18:07:17 -0800263 const ConfigKey mConfigKey;
264
David Chen27785a82018-01-19 17:06:45 -0800265 // The time when this metric producer was first created. The end time for the current bucket
266 // can be computed from this based on mCurrentBucketNum.
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700267 int64_t mTimeBaseNs;
Yao Chen729093d2017-10-16 10:33:26 -0700268
David Chen27785a82018-01-19 17:06:45 -0800269 // Start time may not be aligned with the start of statsd if there is an app upgrade in the
270 // middle of a bucket.
Yangster-macb142cc82018-03-30 15:22:08 -0700271 int64_t mCurrentBucketStartTimeNs;
Yao Chen729093d2017-10-16 10:33:26 -0700272
David Chen27785a82018-01-19 17:06:45 -0800273 // Used by anomaly detector to track which bucket we are in. This is not sent with the produced
274 // report.
Yangster-macb142cc82018-03-30 15:22:08 -0700275 int64_t mCurrentBucketNum;
Yang Lu3eba6212017-10-25 19:54:45 -0700276
Yao Chen729093d2017-10-16 10:33:26 -0700277 int64_t mBucketSizeNs;
278
279 bool mCondition;
280
281 bool mConditionSliced;
282
283 sp<ConditionWizard> mWizard;
284
285 int mConditionTrackerIndex;
286
Yao Chen8a8d16c2018-02-08 14:50:40 -0800287 vector<Matcher> mDimensionsInWhat; // The dimensions_in_what defined in statsd_config
288 vector<Matcher> mDimensionsInCondition; // The dimensions_in_condition defined in statsd_config
Yao Chen729093d2017-10-16 10:33:26 -0700289
Yangster13fb7e42018-03-07 17:30:49 -0800290 bool mContainANYPositionInDimensionsInWhat;
Yangster-mac9def8e32018-04-17 13:55:51 -0700291 bool mSliceByPositionALL;
Yangster13fb7e42018-03-07 17:30:49 -0800292
293 // True iff the condition dimensions equal to the sliced dimensions in the simple condition
294 // tracker. This field is always false for combinational condition trackers.
295 bool mSameConditionDimensionsInTracker;
296
297 // True iff the metric to condition links cover all dimension fields in the condition tracker.
298 // This field is always false for combinational condition trackers.
299 bool mHasLinksToAllConditionDimensionsInTracker;
300
Yao Chen8a8d16c2018-02-08 14:50:40 -0800301 std::vector<Metric2Condition> mMetric2ConditionLinks;
Yao Chenb7041772017-10-20 16:59:25 -0700302
Yangster-mace2cd6d52017-11-09 20:38:30 -0800303 std::vector<sp<AnomalyTracker>> mAnomalyTrackers;
304
Yao Chenb7041772017-10-20 16:59:25 -0700305 /*
306 * Individual metrics can implement their own business logic here. All pre-processing is done.
307 *
308 * [matcherIndex]: the index of the matcher which matched this event. This is interesting to
309 * DurationMetric, because it has start/stop/stop_all 3 matchers.
310 * [eventKey]: the extracted dimension key for the final output. if the metric doesn't have
311 * dimensions, it will be DEFAULT_DIMENSION_KEY
312 * [conditionKey]: the keys of conditions which should be used to query the condition for this
Stefan Lafona5b51912017-12-05 21:43:52 -0800313 * target event (from MetricConditionLink). This is passed to individual metrics
Yao Chenb7041772017-10-20 16:59:25 -0700314 * because DurationMetric needs it to be cached.
315 * [condition]: whether condition is met. If condition is sliced, this is the result coming from
316 * query with ConditionWizard; If condition is not sliced, this is the
317 * nonSlicedCondition.
318 * [event]: the log event, just in case the metric needs its data, e.g., EventMetric.
319 */
Yangsterf2bee6f2017-11-29 12:01:05 -0800320 virtual void onMatchedLogEventInternalLocked(
Yangster-mac93694462018-01-22 20:49:31 -0800321 const size_t matcherIndex, const MetricDimensionKey& eventKey,
Yangster-mac20877162017-12-22 17:19:39 -0800322 const ConditionKey& conditionKey, bool condition,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800323 const LogEvent& event) = 0;
yro2b0f8862017-11-06 14:27:31 -0800324
Yangsterf2bee6f2017-11-29 12:01:05 -0800325 // Consume the parsed stats log entry that already matched the "what" of the metric.
Yangster-mac53928882018-02-25 23:02:56 -0800326 virtual void onMatchedLogEventLocked(const size_t matcherIndex, const LogEvent& event);
Yangsterf2bee6f2017-11-29 12:01:05 -0800327
Yangsterf2bee6f2017-11-29 12:01:05 -0800328 mutable std::mutex mMutex;
Yangster-mac849dfdc22018-10-12 15:41:45 -0700329
330 struct Activation {
331 Activation() : ttl_ns(0), activation_ns(0), state(ActivationState::kNotActive) {}
332
333 int64_t ttl_ns;
334 int64_t activation_ns;
335 ActivationState state;
336 };
337 // When the metric producer has multiple activations, these activations are ORed to determine
338 // whether the metric producer is ready to generate metrics.
339 std::unordered_map<int, Activation> mEventActivationMap;
340
341 bool mIsActive;
342
343 FRIEND_TEST(MetricActivationE2eTest, TestCountMetric);
Yao Chen44cf27c2017-09-14 22:32:50 -0700344};
345
346} // namespace statsd
347} // namespace os
348} // namespace android
349#endif // METRIC_PRODUCER_H