• 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 #define DEBUG false  // STOPSHIP if true
18 #include "Log.h"
19 
20 #include "AnomalyTracker.h"
21 #include "external/Perfetto.h"
22 #include "guardrail/StatsdStats.h"
23 #include "metadata_util.h"
24 #include "stats_log_util.h"
25 #include "subscriber_util.h"
26 #include "subscriber/IncidentdReporter.h"
27 #include "subscriber/SubscriberReporter.h"
28 
29 #include <inttypes.h>
30 #include <statslog_statsd.h>
31 #include <time.h>
32 
33 namespace android {
34 namespace os {
35 namespace statsd {
36 
AnomalyTracker(const Alert & alert,const ConfigKey & configKey)37 AnomalyTracker::AnomalyTracker(const Alert& alert, const ConfigKey& configKey)
38         : mAlert(alert), mConfigKey(configKey), mNumOfPastBuckets(mAlert.num_buckets() - 1) {
39     VLOG("AnomalyTracker() called");
40     resetStorage();  // initialization
41 }
42 
~AnomalyTracker()43 AnomalyTracker::~AnomalyTracker() {
44     VLOG("~AnomalyTracker() called");
45 }
46 
onConfigUpdated()47 void AnomalyTracker::onConfigUpdated() {
48     mSubscriptions.clear();
49 }
50 
resetStorage()51 void AnomalyTracker::resetStorage() {
52     VLOG("resetStorage() called.");
53     mPastBuckets.clear();
54     // Excludes the current bucket.
55     mPastBuckets.resize(mNumOfPastBuckets);
56     mSumOverPastBuckets.clear();
57 }
58 
index(int64_t bucketNum) const59 size_t AnomalyTracker::index(int64_t bucketNum) const {
60     if (bucketNum < 0) {
61         ALOGE("index() was passed a negative bucket number (%lld)!", (long long)bucketNum);
62     }
63     return bucketNum % mNumOfPastBuckets;
64 }
65 
advanceMostRecentBucketTo(const int64_t & bucketNum)66 void AnomalyTracker::advanceMostRecentBucketTo(const int64_t& bucketNum) {
67     VLOG("advanceMostRecentBucketTo() called.");
68     if (mNumOfPastBuckets <= 0) {
69         return;
70     }
71     if (bucketNum <= mMostRecentBucketNum) {
72         ALOGW("Cannot advance buckets backwards (bucketNum=%lld but mMostRecentBucketNum=%lld)",
73               (long long)bucketNum, (long long)mMostRecentBucketNum);
74         return;
75     }
76     // If in the future (i.e. buckets are ancient), just empty out all past info.
77     if (bucketNum >= mMostRecentBucketNum + mNumOfPastBuckets) {
78         resetStorage();
79         mMostRecentBucketNum = bucketNum;
80         return;
81     }
82 
83     // Clear out space by emptying out old mPastBuckets[i] values and update mSumOverPastBuckets.
84     for (int64_t i = mMostRecentBucketNum + 1; i <= bucketNum; i++) {
85         const int idx = index(i);
86         subtractBucketFromSum(mPastBuckets[idx]);
87         mPastBuckets[idx] = nullptr;  // release (but not clear) the old bucket.
88     }
89     mMostRecentBucketNum = bucketNum;
90 }
91 
addPastBucket(const MetricDimensionKey & key,const int64_t & bucketValue,const int64_t & bucketNum)92 void AnomalyTracker::addPastBucket(const MetricDimensionKey& key,
93                                    const int64_t& bucketValue,
94                                    const int64_t& bucketNum) {
95     VLOG("addPastBucket(bucketValue) called.");
96     if (mNumOfPastBuckets == 0 ||
97         bucketNum < 0 || bucketNum <= mMostRecentBucketNum - mNumOfPastBuckets) {
98         return;
99     }
100 
101     const int bucketIndex = index(bucketNum);
102     if (bucketNum <= mMostRecentBucketNum && (mPastBuckets[bucketIndex] != nullptr)) {
103         // We need to insert into an already existing past bucket.
104         std::shared_ptr<DimToValMap>& bucket = mPastBuckets[bucketIndex];
105         auto itr = bucket->find(key);
106         if (itr != bucket->end()) {
107             // Old entry already exists; update it.
108             subtractValueFromSum(key, itr->second);
109             itr->second = bucketValue;
110         } else {
111             bucket->insert({key, bucketValue});
112         }
113         mSumOverPastBuckets[key] += bucketValue;
114     } else {
115         // Bucket does not exist yet (in future or was never made), so we must make it.
116         std::shared_ptr<DimToValMap> bucket = std::make_shared<DimToValMap>();
117         bucket->insert({key, bucketValue});
118         addPastBucket(bucket, bucketNum);
119     }
120 }
121 
addPastBucket(std::shared_ptr<DimToValMap> bucket,const int64_t & bucketNum)122 void AnomalyTracker::addPastBucket(std::shared_ptr<DimToValMap> bucket,
123                                    const int64_t& bucketNum) {
124     VLOG("addPastBucket(bucket) called.");
125     if (mNumOfPastBuckets == 0 ||
126             bucketNum < 0 || bucketNum <= mMostRecentBucketNum - mNumOfPastBuckets) {
127         return;
128     }
129 
130     if (bucketNum <= mMostRecentBucketNum) {
131         // We are updating an old bucket, not adding a new one.
132         subtractBucketFromSum(mPastBuckets[index(bucketNum)]);
133     } else {
134         // Clear space for the new bucket to be at bucketNum.
135         advanceMostRecentBucketTo(bucketNum);
136     }
137     mPastBuckets[index(bucketNum)] = bucket;
138     addBucketToSum(bucket);
139 }
140 
subtractBucketFromSum(const shared_ptr<DimToValMap> & bucket)141 void AnomalyTracker::subtractBucketFromSum(const shared_ptr<DimToValMap>& bucket) {
142     if (bucket == nullptr) {
143         return;
144     }
145     for (const auto& keyValuePair : *bucket) {
146         subtractValueFromSum(keyValuePair.first, keyValuePair.second);
147     }
148 }
149 
150 
subtractValueFromSum(const MetricDimensionKey & key,const int64_t & bucketValue)151 void AnomalyTracker::subtractValueFromSum(const MetricDimensionKey& key,
152                                           const int64_t& bucketValue) {
153     auto itr = mSumOverPastBuckets.find(key);
154     if (itr == mSumOverPastBuckets.end()) {
155         return;
156     }
157     itr->second -= bucketValue;
158     if (itr->second == 0) {
159         mSumOverPastBuckets.erase(itr);
160     }
161 }
162 
addBucketToSum(const shared_ptr<DimToValMap> & bucket)163 void AnomalyTracker::addBucketToSum(const shared_ptr<DimToValMap>& bucket) {
164     if (bucket == nullptr) {
165         return;
166     }
167     // For each dimension present in the bucket, add its value to its corresponding sum.
168     for (const auto& keyValuePair : *bucket) {
169         mSumOverPastBuckets[keyValuePair.first] += keyValuePair.second;
170     }
171 }
172 
getPastBucketValue(const MetricDimensionKey & key,const int64_t & bucketNum) const173 int64_t AnomalyTracker::getPastBucketValue(const MetricDimensionKey& key,
174                                            const int64_t& bucketNum) const {
175     if (bucketNum < 0 || mMostRecentBucketNum < 0
176             || bucketNum <= mMostRecentBucketNum - mNumOfPastBuckets
177             || bucketNum > mMostRecentBucketNum) {
178         return 0;
179     }
180 
181     const auto& bucket = mPastBuckets[index(bucketNum)];
182     if (bucket == nullptr) {
183         return 0;
184     }
185     const auto& itr = bucket->find(key);
186     return itr == bucket->end() ? 0 : itr->second;
187 }
188 
getSumOverPastBuckets(const MetricDimensionKey & key) const189 int64_t AnomalyTracker::getSumOverPastBuckets(const MetricDimensionKey& key) const {
190     const auto& itr = mSumOverPastBuckets.find(key);
191     if (itr != mSumOverPastBuckets.end()) {
192         return itr->second;
193     }
194     return 0;
195 }
196 
detectAnomaly(const int64_t & currentBucketNum,const MetricDimensionKey & key,const int64_t & currentBucketValue)197 bool AnomalyTracker::detectAnomaly(const int64_t& currentBucketNum,
198                                    const MetricDimensionKey& key,
199                                    const int64_t& currentBucketValue) {
200 
201     // currentBucketNum should be the next bucket after pastBuckets. If not, advance so that it is.
202     if (currentBucketNum > mMostRecentBucketNum + 1) {
203         advanceMostRecentBucketTo(currentBucketNum - 1);
204     }
205     return mAlert.has_trigger_if_sum_gt() &&
206            getSumOverPastBuckets(key) + currentBucketValue > mAlert.trigger_if_sum_gt();
207 }
208 
declareAnomaly(const int64_t & timestampNs,int64_t metricId,const MetricDimensionKey & key,int64_t metricValue)209 void AnomalyTracker::declareAnomaly(const int64_t& timestampNs, int64_t metricId,
210                                     const MetricDimensionKey& key, int64_t metricValue) {
211     // TODO(b/110563466): Why receive timestamp? RefractoryPeriod should always be based on
212     // real time right now.
213     if (isInRefractoryPeriod(timestampNs, key)) {
214         VLOG("Skipping anomaly declaration since within refractory period");
215         return;
216     }
217     if (mAlert.has_refractory_period_secs()) {
218         mRefractoryPeriodEndsSec[key] = ((timestampNs + NS_PER_SEC - 1) / NS_PER_SEC) // round up
219                                         + mAlert.refractory_period_secs();
220         // TODO(b/110563466): If we had access to the bucket_size_millis, consider
221         // calling resetStorage()
222         // if (mAlert.refractory_period_secs() > mNumOfPastBuckets * bucketSizeNs) {resetStorage();}
223     }
224 
225     if (!mSubscriptions.empty()) {
226         ALOGI("An anomaly (%" PRId64 ") %s has occurred! Informing subscribers.",
227                 mAlert.id(), key.toString().c_str());
228         informSubscribers(key, metricId, metricValue);
229     } else {
230         ALOGI("An anomaly has occurred! (But no subscriber for that alert.)");
231     }
232 
233     StatsdStats::getInstance().noteAnomalyDeclared(mConfigKey, mAlert.id());
234 
235     // TODO(b/110564268): This should also take in the const MetricDimensionKey& key?
236     util::stats_write(util::ANOMALY_DETECTED, mConfigKey.GetUid(),
237                       mConfigKey.GetId(), mAlert.id());
238 }
239 
detectAndDeclareAnomaly(const int64_t & timestampNs,const int64_t & currBucketNum,int64_t metricId,const MetricDimensionKey & key,const int64_t & currentBucketValue)240 void AnomalyTracker::detectAndDeclareAnomaly(const int64_t& timestampNs,
241                                              const int64_t& currBucketNum, int64_t metricId,
242                                              const MetricDimensionKey& key,
243                                              const int64_t& currentBucketValue) {
244     if (detectAnomaly(currBucketNum, key, currentBucketValue)) {
245         declareAnomaly(timestampNs, metricId, key, currentBucketValue);
246     }
247 }
248 
isInRefractoryPeriod(const int64_t & timestampNs,const MetricDimensionKey & key) const249 bool AnomalyTracker::isInRefractoryPeriod(const int64_t& timestampNs,
250                                           const MetricDimensionKey& key) const {
251     const auto& it = mRefractoryPeriodEndsSec.find(key);
252     if (it != mRefractoryPeriodEndsSec.end()) {
253         return timestampNs < (it->second *  (int64_t)NS_PER_SEC);
254     }
255     return false;
256 }
257 
getProtoHash() const258 std::pair<bool, uint64_t> AnomalyTracker::getProtoHash() const {
259     string serializedAlert;
260     if (!mAlert.SerializeToString(&serializedAlert)) {
261         ALOGW("Unable to serialize alert %lld", (long long)mAlert.id());
262         return {false, 0};
263     }
264     return {true, Hash64(serializedAlert)};
265 }
266 
informSubscribers(const MetricDimensionKey & key,int64_t metric_id,int64_t metricValue)267 void AnomalyTracker::informSubscribers(const MetricDimensionKey& key, int64_t metric_id,
268                                        int64_t metricValue) {
269     triggerSubscribers(mAlert.id(), metric_id, key, metricValue, mConfigKey, mSubscriptions);
270 }
271 
writeAlertMetadataToProto(int64_t currentWallClockTimeNs,int64_t systemElapsedTimeNs,metadata::AlertMetadata * alertMetadata)272 bool AnomalyTracker::writeAlertMetadataToProto(int64_t currentWallClockTimeNs,
273                                                int64_t systemElapsedTimeNs,
274                                                metadata::AlertMetadata* alertMetadata) {
275     bool metadataWritten = false;
276 
277     if (mRefractoryPeriodEndsSec.empty()) {
278         return false;
279     }
280 
281     for (const auto& it: mRefractoryPeriodEndsSec) {
282         // Do not write the timestamp to disk if it has already expired
283         if (it.second < systemElapsedTimeNs / NS_PER_SEC) {
284             continue;
285         }
286 
287         metadataWritten = true;
288         if (alertMetadata->alert_dim_keyed_data_size() == 0) {
289             alertMetadata->set_alert_id(mAlert.id());
290         }
291 
292         metadata::AlertDimensionKeyedData* keyedData = alertMetadata->add_alert_dim_keyed_data();
293         // We convert and write the refractory_end_sec to wall clock time because we do not know
294         // when statsd will start again.
295         int32_t refractoryEndWallClockSec = (int32_t) ((currentWallClockTimeNs / NS_PER_SEC) +
296                 (it.second - systemElapsedTimeNs / NS_PER_SEC));
297 
298         keyedData->set_last_refractory_ends_sec(refractoryEndWallClockSec);
299         writeMetricDimensionKeyToMetadataDimensionKey(
300                 it.first, keyedData->mutable_dimension_key());
301     }
302 
303     return metadataWritten;
304 }
305 
loadAlertMetadata(const metadata::AlertMetadata & alertMetadata,int64_t currentWallClockTimeNs,int64_t systemElapsedTimeNs)306 void AnomalyTracker::loadAlertMetadata(
307         const metadata::AlertMetadata& alertMetadata,
308         int64_t currentWallClockTimeNs,
309         int64_t systemElapsedTimeNs) {
310     for (const metadata::AlertDimensionKeyedData& keyedData :
311             alertMetadata.alert_dim_keyed_data()) {
312         if ((uint64_t) keyedData.last_refractory_ends_sec() < currentWallClockTimeNs / NS_PER_SEC) {
313             // Do not update the timestamp if it has already expired.
314             continue;
315         }
316         MetricDimensionKey metricKey = loadMetricDimensionKeyFromProto(
317                 keyedData.dimension_key());
318         int32_t refractoryPeriodEndsSec = (int32_t) keyedData.last_refractory_ends_sec() -
319                 currentWallClockTimeNs / NS_PER_SEC + systemElapsedTimeNs / NS_PER_SEC;
320         mRefractoryPeriodEndsSec[metricKey] = refractoryPeriodEndsSec;
321     }
322 }
323 
324 }  // namespace statsd
325 }  // namespace os
326 }  // namespace android
327