blob: f931e573eb98f94cbc8199ffcbc6c15f1df85c4b [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
37// A MetricProducer is responsible for compute one single metrics, creating stats log report, and
David Chende701692017-10-05 13:16:02 -070038// writing the report to dropbox. MetricProducers should respond to package changes as required in
39// PackageInfoListener, but if none of the metrics are slicing by package name, then the update can
40// be a no-op.
David Chenf12b5c62017-10-13 15:54:03 -070041class MetricProducer : public virtual PackageInfoListener {
Yao Chen44cf27c2017-09-14 22:32:50 -070042public:
Yangster-mac94e197c2018-01-02 16:03:03 -080043 MetricProducer(const int64_t& metricId, const ConfigKey& key, const int64_t startTimeNs,
Yao Chenf09569f2017-12-13 17:00:51 -080044 const int conditionIndex, const sp<ConditionWizard>& wizard)
Yangster-mac94e197c2018-01-02 16:03:03 -080045 : mMetricId(metricId),
Yao Chenf09569f2017-12-13 17:00:51 -080046 mConfigKey(key),
Yao Chenb3561512017-11-21 18:07:17 -080047 mStartTimeNs(startTimeNs),
Yao Chen729093d2017-10-16 10:33:26 -070048 mCurrentBucketStartTimeNs(startTimeNs),
Yang Lu3eba6212017-10-25 19:54:45 -070049 mCurrentBucketNum(0),
Yao Chen729093d2017-10-16 10:33:26 -070050 mCondition(conditionIndex >= 0 ? false : true),
Yao Chen93fe3a32017-11-02 13:52:59 -070051 mConditionSliced(false),
Yao Chen729093d2017-10-16 10:33:26 -070052 mWizard(wizard),
Yangster13fb7e42018-03-07 17:30:49 -080053 mConditionTrackerIndex(conditionIndex),
54 mContainANYPositionInDimensionsInWhat(false),
55 mSameConditionDimensionsInTracker(false),
56 mHasLinksToAllConditionDimensionsInTracker(false) {
57 }
Yangster-mac20877162017-12-22 17:19:39 -080058
Yao Chen44cf27c2017-09-14 22:32:50 -070059 virtual ~MetricProducer(){};
60
David Chen27785a82018-01-19 17:06:45 -080061 /**
62 * Forces this metric to split into a partial bucket right now. If we're past a full bucket, we
63 * first call the standard flushing code to flush up to the latest full bucket. Then we call
64 * the flush again when the end timestamp is forced to be now, and then after flushing, update
65 * the start timestamp to be now.
66 */
Yangster-macb142cc82018-03-30 15:22:08 -070067 void notifyAppUpgrade(const int64_t& eventTimeNs, const string& apk, const int uid,
David Chen27785a82018-01-19 17:06:45 -080068 const int64_t version) override {
69 std::lock_guard<std::mutex> lock(mMutex);
70
71 if (eventTimeNs > getCurrentBucketEndTimeNs()) {
72 // Flush full buckets on the normal path up to the latest bucket boundary.
73 flushIfNeededLocked(eventTimeNs);
74 }
75 // Now flush a partial bucket.
76 flushCurrentBucketLocked(eventTimeNs);
77 mCurrentBucketStartTimeNs = eventTimeNs;
78 // Don't update the current bucket number so that the anomaly tracker knows this bucket
79 // is a partial bucket and can merge it with the previous bucket.
80 };
81
Yangster-macb142cc82018-03-30 15:22:08 -070082 void notifyAppRemoved(const int64_t& eventTimeNs, const string& apk, const int uid) override{
David Chenbd125272018-04-04 19:02:50 -070083 // Force buckets to split on removal also.
84 notifyAppUpgrade(eventTimeNs, apk, uid, 0);
Yao Chend10f7b12017-12-18 12:53:50 -080085 };
86
Yangster-macb142cc82018-03-30 15:22:08 -070087 void onUidMapReceived(const int64_t& eventTimeNs) override{
David Chenbd125272018-04-04 19:02:50 -070088 // Purposefully don't flush partial buckets on a new snapshot.
89 // This occurs if a new user is added/removed or statsd crashes.
Yao Chend10f7b12017-12-18 12:53:50 -080090 };
91
Yao Chencaf339d2017-10-06 16:01:10 -070092 // Consume the parsed stats log entry that already matched the "what" of the metric.
Chenjie Yua7259ab2017-12-10 08:31:05 -080093 void onMatchedLogEvent(const size_t matcherIndex, const LogEvent& event) {
Yangsterf2bee6f2017-11-29 12:01:05 -080094 std::lock_guard<std::mutex> lock(mMutex);
Chenjie Yua7259ab2017-12-10 08:31:05 -080095 onMatchedLogEventLocked(matcherIndex, event);
Yangsterf2bee6f2017-11-29 12:01:05 -080096 }
Yao Chen44cf27c2017-09-14 22:32:50 -070097
Yangster-macb142cc82018-03-30 15:22:08 -070098 void onConditionChanged(const bool condition, const int64_t eventTime) {
Yangsterf2bee6f2017-11-29 12:01:05 -080099 std::lock_guard<std::mutex> lock(mMutex);
100 onConditionChangedLocked(condition, eventTime);
101 }
Yao Chencaf339d2017-10-06 16:01:10 -0700102
Yangster-macb142cc82018-03-30 15:22:08 -0700103 void onSlicedConditionMayChange(bool overallCondition, const int64_t eventTime) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800104 std::lock_guard<std::mutex> lock(mMutex);
Yao Chen427d3722018-03-22 15:21:52 -0700105 onSlicedConditionMayChangeLocked(overallCondition, eventTime);
Yangsterf2bee6f2017-11-29 12:01:05 -0800106 }
107
108 bool isConditionSliced() const {
109 std::lock_guard<std::mutex> lock(mMutex);
110 return mConditionSliced;
111 };
Yao Chen729093d2017-10-16 10:33:26 -0700112
Yao Chen288c6002017-12-12 13:43:18 -0800113 // Output the metrics data to [protoOutput]. All metrics reports end with the same timestamp.
David Chen27785a82018-01-19 17:06:45 -0800114 // This method clears all the past buckets.
Yangster-mace68f3a52018-04-04 00:01:43 -0700115 void onDumpReport(const int64_t dumpTimeNs,
116 const bool include_current_partial_bucket,
117 android::util::ProtoOutputStream* protoOutput) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800118 std::lock_guard<std::mutex> lock(mMutex);
Yangster-mace68f3a52018-04-04 00:01:43 -0700119 return onDumpReportLocked(dumpTimeNs, include_current_partial_bucket, protoOutput);
Yangsterf2bee6f2017-11-29 12:01:05 -0800120 }
Yao Chen729093d2017-10-16 10:33:26 -0700121
Yao Chen884c8c12018-01-26 10:36:25 -0800122 void dumpStates(FILE* out, bool verbose) const {
123 std::lock_guard<std::mutex> lock(mMutex);
124 dumpStatesLocked(out, verbose);
125 }
126
David Chen1d7b0cd2017-11-15 14:20:04 -0800127 // Returns the memory in bytes currently used to store this metric's data. Does not change
128 // state.
Yangsterf2bee6f2017-11-29 12:01:05 -0800129 size_t byteSize() const {
130 std::lock_guard<std::mutex> lock(mMutex);
131 return byteSizeLocked();
132 }
yro69007c82017-10-26 20:42:57 -0700133
Bookatz1476ef22018-02-13 12:26:01 -0800134 /* If alert is valid, adds an AnomalyTracker and returns it. If invalid, returns nullptr. */
Yangster-mac932ecec2018-02-01 10:23:52 -0800135 virtual sp<AnomalyTracker> addAnomalyTracker(const Alert &alert,
136 const sp<AlarmMonitor>& anomalyAlarmMonitor) {
Yangsterf2bee6f2017-11-29 12:01:05 -0800137 std::lock_guard<std::mutex> lock(mMutex);
Bookatz857aaa52017-12-19 15:29:06 -0800138 sp<AnomalyTracker> anomalyTracker = new AnomalyTracker(alert, mConfigKey);
139 if (anomalyTracker != nullptr) {
140 mAnomalyTrackers.push_back(anomalyTracker);
141 }
142 return anomalyTracker;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800143 }
144
145 int64_t getBuckeSizeInNs() const {
Yangsterf2bee6f2017-11-29 12:01:05 -0800146 std::lock_guard<std::mutex> lock(mMutex);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800147 return mBucketSizeNs;
148 }
149
yro59cc24d2018-02-13 20:17:32 -0800150 // Only needed for unit-testing to override guardrail.
151 void setBucketSize(int64_t bucketSize) {
152 mBucketSizeNs = bucketSize;
153 }
154
Yangster-mac94e197c2018-01-02 16:03:03 -0800155 inline const int64_t& getMetricId() {
156 return mMetricId;
Yangster-mac20877162017-12-22 17:19:39 -0800157 }
158
Yao Chen06dba5d2018-01-26 13:38:16 -0800159 // Let MetricProducer drop in-memory data to save memory.
160 // We still need to keep future data valid and anomaly tracking work, which means we will
161 // have to flush old data, informing anomaly trackers then safely drop old data.
162 // We still keep current bucket data for future metrics' validity.
Yangster-macb142cc82018-03-30 15:22:08 -0700163 void dropData(const int64_t dropTimeNs) {
Yao Chen06dba5d2018-01-26 13:38:16 -0800164 std::lock_guard<std::mutex> lock(mMutex);
165 dropDataLocked(dropTimeNs);
166 }
167
Yao Chen729093d2017-10-16 10:33:26 -0700168protected:
Yangster-macb142cc82018-03-30 15:22:08 -0700169 virtual void onConditionChangedLocked(const bool condition, const int64_t eventTime) = 0;
Yao Chen427d3722018-03-22 15:21:52 -0700170 virtual void onSlicedConditionMayChangeLocked(bool overallCondition,
Yangster-macb142cc82018-03-30 15:22:08 -0700171 const int64_t eventTime) = 0;
172 virtual void onDumpReportLocked(const int64_t dumpTimeNs,
Yangster-mace68f3a52018-04-04 00:01:43 -0700173 const bool include_current_partial_bucket,
Yao Chen288c6002017-12-12 13:43:18 -0800174 android::util::ProtoOutputStream* protoOutput) = 0;
Yangsterf2bee6f2017-11-29 12:01:05 -0800175 virtual size_t byteSizeLocked() const = 0;
Yao Chen884c8c12018-01-26 10:36:25 -0800176 virtual void dumpStatesLocked(FILE* out, bool verbose) const = 0;
Yangsterf2bee6f2017-11-29 12:01:05 -0800177
David Chen27785a82018-01-19 17:06:45 -0800178 /**
Yangster-mace68f3a52018-04-04 00:01:43 -0700179 * Flushes the current bucket if the eventTime is after the current bucket's end time. This will
180 also flush the current partial bucket in memory.
David Chen27785a82018-01-19 17:06:45 -0800181 */
Yangster-macb142cc82018-03-30 15:22:08 -0700182 virtual void flushIfNeededLocked(const int64_t& eventTime){};
David Chen27785a82018-01-19 17:06:45 -0800183
184 /**
Yangster-mace68f3a52018-04-04 00:01:43 -0700185 * Flushes all the data including the current partial bucket.
186 */
187 virtual void flushLocked(const int64_t& eventTime) {
188 flushIfNeededLocked(eventTime);
189 flushCurrentBucketLocked(eventTime);
190 };
191
192 /**
David Chen27785a82018-01-19 17:06:45 -0800193 * For metrics that aggregate (ie, every metric producer except for EventMetricProducer),
194 * we need to be able to flush the current buckets on demand (ie, end the current bucket and
195 * start new bucket). If this function is called when eventTimeNs is greater than the current
196 * bucket's end timestamp, than we flush up to the end of the latest full bucket; otherwise,
197 * we assume that we want to flush a partial bucket. The bucket start timestamp and bucket
198 * number are not changed by this function. This method should only be called by
199 * flushIfNeededLocked or the app upgrade handler; the caller MUST update the bucket timestamp
200 * and bucket number as needed.
201 */
Yangster-macb142cc82018-03-30 15:22:08 -0700202 virtual void flushCurrentBucketLocked(const int64_t& eventTimeNs){};
David Chen27785a82018-01-19 17:06:45 -0800203
204 // Convenience to compute the current bucket's end time, which is always aligned with the
205 // start time of the metric.
Yangster-macb142cc82018-03-30 15:22:08 -0700206 int64_t getCurrentBucketEndTimeNs() const {
David Chen27785a82018-01-19 17:06:45 -0800207 return mStartTimeNs + (mCurrentBucketNum + 1) * mBucketSizeNs;
208 }
209
Yangster-macb142cc82018-03-30 15:22:08 -0700210 virtual void dropDataLocked(const int64_t dropTimeNs) = 0;
Yao Chen06dba5d2018-01-26 13:38:16 -0800211
Yangster-mac94e197c2018-01-02 16:03:03 -0800212 const int64_t mMetricId;
Yao Chenf09569f2017-12-13 17:00:51 -0800213
Yao Chenb3561512017-11-21 18:07:17 -0800214 const ConfigKey mConfigKey;
215
David Chen27785a82018-01-19 17:06:45 -0800216 // The time when this metric producer was first created. The end time for the current bucket
217 // can be computed from this based on mCurrentBucketNum.
Yangster-macb142cc82018-03-30 15:22:08 -0700218 int64_t mStartTimeNs;
Yao Chen729093d2017-10-16 10:33:26 -0700219
David Chen27785a82018-01-19 17:06:45 -0800220 // Start time may not be aligned with the start of statsd if there is an app upgrade in the
221 // middle of a bucket.
Yangster-macb142cc82018-03-30 15:22:08 -0700222 int64_t mCurrentBucketStartTimeNs;
Yao Chen729093d2017-10-16 10:33:26 -0700223
David Chen27785a82018-01-19 17:06:45 -0800224 // Used by anomaly detector to track which bucket we are in. This is not sent with the produced
225 // report.
Yangster-macb142cc82018-03-30 15:22:08 -0700226 int64_t mCurrentBucketNum;
Yang Lu3eba6212017-10-25 19:54:45 -0700227
Yao Chen729093d2017-10-16 10:33:26 -0700228 int64_t mBucketSizeNs;
229
230 bool mCondition;
231
232 bool mConditionSliced;
233
234 sp<ConditionWizard> mWizard;
235
236 int mConditionTrackerIndex;
237
Yao Chen8a8d16c2018-02-08 14:50:40 -0800238 vector<Matcher> mDimensionsInWhat; // The dimensions_in_what defined in statsd_config
239 vector<Matcher> mDimensionsInCondition; // The dimensions_in_condition defined in statsd_config
Yao Chen729093d2017-10-16 10:33:26 -0700240
Yangster13fb7e42018-03-07 17:30:49 -0800241 bool mContainANYPositionInDimensionsInWhat;
242
243 // True iff the condition dimensions equal to the sliced dimensions in the simple condition
244 // tracker. This field is always false for combinational condition trackers.
245 bool mSameConditionDimensionsInTracker;
246
247 // True iff the metric to condition links cover all dimension fields in the condition tracker.
248 // This field is always false for combinational condition trackers.
249 bool mHasLinksToAllConditionDimensionsInTracker;
250
Yao Chen8a8d16c2018-02-08 14:50:40 -0800251 std::vector<Metric2Condition> mMetric2ConditionLinks;
Yao Chenb7041772017-10-20 16:59:25 -0700252
Yangster-mace2cd6d52017-11-09 20:38:30 -0800253 std::vector<sp<AnomalyTracker>> mAnomalyTrackers;
254
Yao Chenb7041772017-10-20 16:59:25 -0700255 /*
256 * Individual metrics can implement their own business logic here. All pre-processing is done.
257 *
258 * [matcherIndex]: the index of the matcher which matched this event. This is interesting to
259 * DurationMetric, because it has start/stop/stop_all 3 matchers.
260 * [eventKey]: the extracted dimension key for the final output. if the metric doesn't have
261 * dimensions, it will be DEFAULT_DIMENSION_KEY
262 * [conditionKey]: the keys of conditions which should be used to query the condition for this
Stefan Lafona5b51912017-12-05 21:43:52 -0800263 * target event (from MetricConditionLink). This is passed to individual metrics
Yao Chenb7041772017-10-20 16:59:25 -0700264 * because DurationMetric needs it to be cached.
265 * [condition]: whether condition is met. If condition is sliced, this is the result coming from
266 * query with ConditionWizard; If condition is not sliced, this is the
267 * nonSlicedCondition.
268 * [event]: the log event, just in case the metric needs its data, e.g., EventMetric.
269 */
Yangsterf2bee6f2017-11-29 12:01:05 -0800270 virtual void onMatchedLogEventInternalLocked(
Yangster-mac93694462018-01-22 20:49:31 -0800271 const size_t matcherIndex, const MetricDimensionKey& eventKey,
Yangster-mac20877162017-12-22 17:19:39 -0800272 const ConditionKey& conditionKey, bool condition,
Chenjie Yua7259ab2017-12-10 08:31:05 -0800273 const LogEvent& event) = 0;
yro2b0f8862017-11-06 14:27:31 -0800274
Yangsterf2bee6f2017-11-29 12:01:05 -0800275 // Consume the parsed stats log entry that already matched the "what" of the metric.
Yangster-mac53928882018-02-25 23:02:56 -0800276 virtual void onMatchedLogEventLocked(const size_t matcherIndex, const LogEvent& event);
Yangsterf2bee6f2017-11-29 12:01:05 -0800277
Yangsterf2bee6f2017-11-29 12:01:05 -0800278 mutable std::mutex mMutex;
Yao Chen44cf27c2017-09-14 22:32:50 -0700279};
280
281} // namespace statsd
282} // namespace os
283} // namespace android
284#endif // METRIC_PRODUCER_H