blob: bf36a3bc89901f05d1907e8827002dcb60f8c89c [file] [log] [blame]
Yangster-mace2cd6d52017-11-09 20:38:30 -08001/*
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#pragma once
18
Yi Jinafb36062018-01-31 19:14:25 -080019#include <stdlib.h>
20
Yangster-mace2cd6d52017-11-09 20:38:30 -080021#include <gtest/gtest_prod.h>
Yi Jinafb36062018-01-31 19:14:25 -080022#include <utils/RefBase.h>
23
Yangster-mac932ecec2018-02-01 10:23:52 -080024#include "AlarmMonitor.h"
Bookatz8f2f3d82017-12-07 13:53:21 -080025#include "config/ConfigKey.h"
Yangster-mace2cd6d52017-11-09 20:38:30 -080026#include "frameworks/base/cmds/statsd/src/statsd_config.pb.h" // Alert
Jeffrey Huang475677e2020-03-30 19:52:07 -070027#include "frameworks/base/cmds/statsd/src/statsd_metadata.pb.h" // AlertMetadata
Yangster-mace2cd6d52017-11-09 20:38:30 -080028#include "stats_util.h" // HashableDimensionKey and DimToValMap
29
Yangster-mace2cd6d52017-11-09 20:38:30 -080030namespace android {
31namespace os {
32namespace statsd {
33
Yangster-mace2cd6d52017-11-09 20:38:30 -080034using std::shared_ptr;
Yi Jinafb36062018-01-31 19:14:25 -080035using std::unordered_map;
Yangster-mace2cd6d52017-11-09 20:38:30 -080036
Bookatzcc5adef22017-11-21 14:36:23 -080037// Does NOT allow negative values.
Yangster-mace2cd6d52017-11-09 20:38:30 -080038class AnomalyTracker : public virtual RefBase {
39public:
Bookatz8f2f3d82017-12-07 13:53:21 -080040 AnomalyTracker(const Alert& alert, const ConfigKey& configKey);
Yangster-mace2cd6d52017-11-09 20:38:30 -080041
42 virtual ~AnomalyTracker();
43
Yangster-mac94e197c2018-01-02 16:03:03 -080044 // Add subscriptions that depend on this alert.
45 void addSubscription(const Subscription& subscription) {
46 mSubscriptions.push_back(subscription);
47 }
48
Bookatz6bf98252018-03-14 10:44:24 -070049 // Adds a bucket for the given bucketNum (index starting at 0).
50 // If a bucket for bucketNum already exists, it will be replaced.
51 // Also, advances to bucketNum (if not in the past), effectively filling any intervening
52 // buckets with 0s.
53 void addPastBucket(std::shared_ptr<DimToValMap> bucket, const int64_t& bucketNum);
54
55 // Inserts (or replaces) the bucket entry for the given bucketNum at the given key to be the
56 // given bucketValue. If the bucket does not exist, it will be created.
57 // Also, advances to bucketNum (if not in the past), effectively filling any intervening
58 // buckets with 0s.
Yangster-mac93694462018-01-22 20:49:31 -080059 void addPastBucket(const MetricDimensionKey& key, const int64_t& bucketValue,
Yangster-mace2cd6d52017-11-09 20:38:30 -080060 const int64_t& bucketNum);
61
Bookatz6bf98252018-03-14 10:44:24 -070062 // Returns true if, based on past buckets plus the new currentBucketValue (which generally
63 // represents the partially-filled current bucket), an anomaly has happened.
Bookatz3e8cd352018-03-16 10:09:59 -070064 // Also advances to currBucketNum-1.
Yangster-mac93694462018-01-22 20:49:31 -080065 bool detectAnomaly(const int64_t& currBucketNum, const MetricDimensionKey& key,
Yangster-mace2cd6d52017-11-09 20:38:30 -080066 const int64_t& currentBucketValue);
67
68 // Informs incidentd about the detected alert.
Yao Chen4ce07292019-02-13 13:06:36 -080069 void declareAnomaly(const int64_t& timestampNs, int64_t metricId, const MetricDimensionKey& key,
70 int64_t metricValue);
Yangster-mace2cd6d52017-11-09 20:38:30 -080071
Bookatz6bf98252018-03-14 10:44:24 -070072 // Detects if, based on past buckets plus the new currentBucketValue (which generally
73 // represents the partially-filled current bucket), an anomaly has happened, and if so,
74 // declares an anomaly and informs relevant subscribers.
Bookatz3e8cd352018-03-16 10:09:59 -070075 // Also advances to currBucketNum-1.
Yangster-macb142cc82018-03-30 15:22:08 -070076 void detectAndDeclareAnomaly(const int64_t& timestampNs, const int64_t& currBucketNum,
Yao Chen4ce07292019-02-13 13:06:36 -080077 int64_t metricId, const MetricDimensionKey& key,
78 const int64_t& currentBucketValue);
Yangster-mace2cd6d52017-11-09 20:38:30 -080079
Yangster-mac932ecec2018-02-01 10:23:52 -080080 // Init the AlarmMonitor which is shared across anomaly trackers.
81 virtual void setAlarmMonitor(const sp<AlarmMonitor>& alarmMonitor) {
82 return; // Base AnomalyTracker class has no need for the AlarmMonitor.
Yangster-mace2cd6d52017-11-09 20:38:30 -080083 }
84
Bookatz6bf98252018-03-14 10:44:24 -070085 // Returns the sum of all past bucket values for the given dimension key.
Yangster-mac93694462018-01-22 20:49:31 -080086 int64_t getSumOverPastBuckets(const MetricDimensionKey& key) const;
Yangster-mace2cd6d52017-11-09 20:38:30 -080087
Bookatz6bf98252018-03-14 10:44:24 -070088 // Returns the value for a past bucket, or 0 if that bucket doesn't exist.
Yangster-mac93694462018-01-22 20:49:31 -080089 int64_t getPastBucketValue(const MetricDimensionKey& key, const int64_t& bucketNum) const;
Yangster-mace2cd6d52017-11-09 20:38:30 -080090
Bookatz6bf98252018-03-14 10:44:24 -070091 // Returns the anomaly threshold set in the configuration.
Yangster-mace2cd6d52017-11-09 20:38:30 -080092 inline int64_t getAnomalyThreshold() const {
93 return mAlert.trigger_if_sum_gt();
94 }
95
Bookatz6bf98252018-03-14 10:44:24 -070096 // Returns the refractory period ending timestamp (in seconds) for the given key.
97 // Before this moment, any detected anomaly will be ignored.
Bookatz1bf94382018-01-04 11:43:20 -080098 // If there is no stored refractory period ending timestamp, returns 0.
Yangster-mac93694462018-01-22 20:49:31 -080099 uint32_t getRefractoryPeriodEndsSec(const MetricDimensionKey& key) const {
Bookatz1bf94382018-01-04 11:43:20 -0800100 const auto& it = mRefractoryPeriodEndsSec.find(key);
101 return it != mRefractoryPeriodEndsSec.end() ? it->second : 0;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800102 }
103
Bookatz6bf98252018-03-14 10:44:24 -0700104 // Returns the (constant) number of past buckets this anomaly tracker can store.
Bookatzcc5adef22017-11-21 14:36:23 -0800105 inline int getNumOfPastBuckets() const {
106 return mNumOfPastBuckets;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800107 }
108
Bookatzcc5adef22017-11-21 14:36:23 -0800109 // Declares an anomaly for each alarm in firedAlarms that belongs to this AnomalyTracker,
Yangster-mac932ecec2018-02-01 10:23:52 -0800110 // and removes it from firedAlarms. Does NOT remove the alarm from the AlarmMonitor.
Yangster-macb142cc82018-03-30 15:22:08 -0700111 virtual void informAlarmsFired(const int64_t& timestampNs,
Yangster-mac932ecec2018-02-01 10:23:52 -0800112 unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>>& firedAlarms) {
113 return; // The base AnomalyTracker class doesn't have alarms.
Bookatz857aaa52017-12-19 15:29:06 -0800114 }
Bookatzcc5adef22017-11-21 14:36:23 -0800115
Jeffrey Huangb8f54032020-03-23 13:42:42 -0700116 // Writes metadata of the alert (refractory_period_end_sec) to AlertMetadata.
117 // Returns true if at least one element is written to alertMetadata.
118 bool writeAlertMetadataToProto(
119 int64_t currentWallClockTimeNs,
120 int64_t systemElapsedTimeNs, metadata::AlertMetadata* alertMetadata);
121
Jeffrey Huang475677e2020-03-30 19:52:07 -0700122 void loadAlertMetadata(
123 const metadata::AlertMetadata& alertMetadata,
124 int64_t currentWallClockTimeNs,
125 int64_t systemElapsedTimeNs);
126
Yangster-mace2cd6d52017-11-09 20:38:30 -0800127protected:
Yangster-macbe10ddf2018-03-13 15:39:51 -0700128 // For testing only.
129 // Returns the alarm timestamp in seconds for the query dimension if it exists. Otherwise
130 // returns 0.
131 virtual uint32_t getAlarmTimestampSec(const MetricDimensionKey& dimensionKey) const {
132 return 0; // The base AnomalyTracker class doesn't have alarms.
133 }
134
Yangster-mace2cd6d52017-11-09 20:38:30 -0800135 // statsd_config.proto Alert message that defines this tracker.
136 const Alert mAlert;
137
Yangster-mac94e197c2018-01-02 16:03:03 -0800138 // The subscriptions that depend on this alert.
139 std::vector<Subscription> mSubscriptions;
140
Bookatz8f2f3d82017-12-07 13:53:21 -0800141 // A reference to the Alert's config key.
Yangster-macc04feba2018-04-02 14:37:33 -0700142 const ConfigKey mConfigKey;
Bookatz8f2f3d82017-12-07 13:53:21 -0800143
Bookatzcc5adef22017-11-21 14:36:23 -0800144 // Number of past buckets. One less than the total number of buckets needed
145 // for the anomaly detection (since the current bucket is not in the past).
Bookatz2fb56532018-03-08 11:16:48 -0800146 const int mNumOfPastBuckets;
Yangster-mace2cd6d52017-11-09 20:38:30 -0800147
Bookatz6bf98252018-03-14 10:44:24 -0700148 // Values for each of the past mNumOfPastBuckets buckets. Always of size mNumOfPastBuckets.
149 // mPastBuckets[i] can be null, meaning that no data is present in that bucket.
Yangster-mace2cd6d52017-11-09 20:38:30 -0800150 std::vector<shared_ptr<DimToValMap>> mPastBuckets;
151
Bookatz6bf98252018-03-14 10:44:24 -0700152 // Cached sum over all existing buckets in mPastBuckets.
153 // Its buckets never contain entries of 0.
Yangster-mace2cd6d52017-11-09 20:38:30 -0800154 DimToValMap mSumOverPastBuckets;
155
156 // The bucket number of the last added bucket.
157 int64_t mMostRecentBucketNum = -1;
158
Bookatz1bf94382018-01-04 11:43:20 -0800159 // Map from each dimension to the timestamp that its refractory period (if this anomaly was
Bookatz6bf98252018-03-14 10:44:24 -0700160 // declared for that dimension) ends, in seconds. From this moment and onwards, anomalies
161 // can be declared again.
Bookatz1bf94382018-01-04 11:43:20 -0800162 // Entries may be, but are not guaranteed to be, removed after the period is finished.
Yangster-mac93694462018-01-22 20:49:31 -0800163 unordered_map<MetricDimensionKey, uint32_t> mRefractoryPeriodEndsSec;
Bookatz857aaa52017-12-19 15:29:06 -0800164
Bookatz6bf98252018-03-14 10:44:24 -0700165 // Advances mMostRecentBucketNum to bucketNum, deleting any data that is now too old.
166 // Specifically, since it is now too old, removes the data for
167 // [mMostRecentBucketNum - mNumOfPastBuckets + 1, bucketNum - mNumOfPastBuckets].
168 void advanceMostRecentBucketTo(const int64_t& bucketNum);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800169
170 // Add the information in the given bucket to mSumOverPastBuckets.
171 void addBucketToSum(const shared_ptr<DimToValMap>& bucket);
172
173 // Subtract the information in the given bucket from mSumOverPastBuckets
174 // and remove any items with value 0.
175 void subtractBucketFromSum(const shared_ptr<DimToValMap>& bucket);
176
Bookatz6bf98252018-03-14 10:44:24 -0700177 // From mSumOverPastBuckets[key], subtracts bucketValue, removing it if it is now 0.
178 void subtractValueFromSum(const MetricDimensionKey& key, const int64_t& bucketValue);
179
180 // Returns true if in the refractory period, else false.
Yangster-macb142cc82018-03-30 15:22:08 -0700181 bool isInRefractoryPeriod(const int64_t& timestampNs, const MetricDimensionKey& key) const;
Bookatzcc5adef22017-11-21 14:36:23 -0800182
Yangster-mace2cd6d52017-11-09 20:38:30 -0800183 // Calculates the corresponding bucket index within the circular array.
Bookatz6bf98252018-03-14 10:44:24 -0700184 // Requires bucketNum >= 0.
Yangster-mace2cd6d52017-11-09 20:38:30 -0800185 size_t index(int64_t bucketNum) const;
186
Bookatzcc5adef22017-11-21 14:36:23 -0800187 // Resets all bucket data. For use when all the data gets stale.
Bookatz857aaa52017-12-19 15:29:06 -0800188 virtual void resetStorage();
Yangster-mace2cd6d52017-11-09 20:38:30 -0800189
Bookatz6bf98252018-03-14 10:44:24 -0700190 // Informs the subscribers (incidentd, perfetto, broadcasts, etc) that an anomaly has occurred.
Yao Chen4ce07292019-02-13 13:06:36 -0800191 void informSubscribers(const MetricDimensionKey& key, int64_t metricId, int64_t metricValue);
Bookatzd1fd2422017-11-22 15:21:03 -0800192
Yangster-mace2cd6d52017-11-09 20:38:30 -0800193 FRIEND_TEST(AnomalyTrackerTest, TestConsecutiveBuckets);
194 FRIEND_TEST(AnomalyTrackerTest, TestSparseBuckets);
195 FRIEND_TEST(GaugeMetricProducerTest, TestAnomalyDetection);
Bookatz1bf94382018-01-04 11:43:20 -0800196 FRIEND_TEST(CountMetricProducerTest, TestAnomalyDetectionUnSliced);
Yangster-macbe10ddf2018-03-13 15:39:51 -0700197 FRIEND_TEST(AnomalyDetectionE2eTest, TestDurationMetric_SUM_single_bucket);
198 FRIEND_TEST(AnomalyDetectionE2eTest, TestDurationMetric_SUM_multiple_buckets);
199 FRIEND_TEST(AnomalyDetectionE2eTest, TestDurationMetric_SUM_long_refractory_period);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800200};
201
202} // namespace statsd
203} // namespace os
204} // namespace android