1 // Copyright (C) 2017 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #include "src/metrics/duration_helper/MaxDurationTracker.h"
16 #include "src/condition/ConditionWizard.h"
17 #include "metrics_test_helper.h"
18 #include "tests/statsd_test_util.h"
19 
20 #include <gmock/gmock.h>
21 #include <gtest/gtest.h>
22 #include <stdio.h>
23 #include <set>
24 #include <unordered_map>
25 #include <vector>
26 
27 using namespace android::os::statsd;
28 using namespace testing;
29 using android::sp;
30 using std::set;
31 using std::unordered_map;
32 using std::vector;
33 
34 #ifdef __ANDROID__
35 
36 namespace android {
37 namespace os {
38 namespace statsd {
39 
40 const ConfigKey kConfigKey(0, 12345);
41 
42 const int TagId = 1;
43 const int64_t metricId = 123;
44 const optional<UploadThreshold> emptyThreshold;
45 
46 const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
47 const HashableDimensionKey conditionKey = getMockedDimensionKey(TagId, 4, "1");
48 const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
49 const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
50 const int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
51 
TEST(MaxDurationTrackerTest,TestSimpleMaxDuration)52 TEST(MaxDurationTrackerTest, TestSimpleMaxDuration) {
53     const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
54     const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
55     const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
56 
57 
58     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
59 
60     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
61 
62     int64_t bucketStartTimeNs = 10000000000;
63     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
64     int64_t bucketNum = 0;
65 
66     int64_t metricId = 1;
67     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, false, bucketStartTimeNs,
68                                bucketNum, bucketStartTimeNs, bucketSizeNs, false, false, {});
69 
70     tracker.noteStart(key1, true, bucketStartTimeNs, ConditionKey());
71     // Event starts again. This would not change anything as it already starts.
72     tracker.noteStart(key1, true, bucketStartTimeNs + 3, ConditionKey());
73     // Stopped.
74     tracker.noteStop(key1, bucketStartTimeNs + 10, false);
75 
76     // Another event starts in this bucket.
77     tracker.noteStart(key2, true, bucketStartTimeNs + 20, ConditionKey());
78     tracker.noteStop(key2, bucketStartTimeNs + 40, false /*stop all*/);
79 
80     tracker.flushIfNeeded(bucketStartTimeNs + bucketSizeNs + 1, emptyThreshold, &buckets);
81     EXPECT_TRUE(buckets.find(eventKey) != buckets.end());
82     ASSERT_EQ(1u, buckets[eventKey].size());
83     EXPECT_EQ(20LL, buckets[eventKey][0].mDuration);
84 }
85 
TEST(MaxDurationTrackerTest,TestStopAll)86 TEST(MaxDurationTrackerTest, TestStopAll) {
87     const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
88     const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
89     const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
90 
91     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
92 
93     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
94 
95     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
96     int64_t bucketStartTimeNs = 10000000000;
97     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
98     int64_t bucketNum = 0;
99 
100     int64_t metricId = 1;
101     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, false, bucketStartTimeNs,
102                                bucketNum, bucketStartTimeNs, bucketSizeNs, false, false, {});
103 
104     tracker.noteStart(key1, true, bucketStartTimeNs + 1, ConditionKey());
105 
106     // Another event starts in this bucket.
107     tracker.noteStart(key2, true, bucketStartTimeNs + 20, ConditionKey());
108     tracker.flushIfNeeded(bucketStartTimeNs + bucketSizeNs + 40, emptyThreshold, &buckets);
109     tracker.noteStopAll(bucketStartTimeNs + bucketSizeNs + 40);
110     EXPECT_TRUE(tracker.mInfos.empty());
111     EXPECT_TRUE(buckets.find(eventKey) == buckets.end());
112 
113     tracker.flushIfNeeded(bucketStartTimeNs + 3 * bucketSizeNs + 40, emptyThreshold, &buckets);
114     EXPECT_TRUE(buckets.find(eventKey) != buckets.end());
115     ASSERT_EQ(1u, buckets[eventKey].size());
116     EXPECT_EQ(bucketSizeNs + 40 - 1, buckets[eventKey][0].mDuration);
117     EXPECT_EQ(bucketStartTimeNs + bucketSizeNs, buckets[eventKey][0].mBucketStartNs);
118     EXPECT_EQ(bucketStartTimeNs + 2 * bucketSizeNs, buckets[eventKey][0].mBucketEndNs);
119 }
120 
TEST(MaxDurationTrackerTest,TestCrossBucketBoundary)121 TEST(MaxDurationTrackerTest, TestCrossBucketBoundary) {
122     const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
123     const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
124     const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
125     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
126 
127     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
128 
129     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
130     int64_t bucketStartTimeNs = 10000000000;
131     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
132     int64_t bucketNum = 0;
133 
134     int64_t metricId = 1;
135     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, false, bucketStartTimeNs,
136                                bucketNum, bucketStartTimeNs, bucketSizeNs, false, false, {});
137 
138     // The event starts.
139     tracker.noteStart(DEFAULT_DIMENSION_KEY, true, bucketStartTimeNs + 1, ConditionKey());
140 
141     // Starts again. Does not DEFAULT_DIMENSION_KEY anything.
142     tracker.noteStart(DEFAULT_DIMENSION_KEY, true, bucketStartTimeNs + bucketSizeNs + 1,
143                       ConditionKey());
144 
145     // The event stops at early 4th bucket.
146     // Notestop is called from DurationMetricProducer's onMatchedLogEvent, which calls
147     // flushIfneeded.
148     tracker.flushIfNeeded(bucketStartTimeNs + (3 * bucketSizeNs) + 20, emptyThreshold, &buckets);
149     tracker.noteStop(DEFAULT_DIMENSION_KEY, bucketStartTimeNs + (3 * bucketSizeNs) + 20,
150                      false /*stop all*/);
151     EXPECT_TRUE(buckets.find(eventKey) == buckets.end());
152 
153     tracker.flushIfNeeded(bucketStartTimeNs + 4 * bucketSizeNs, emptyThreshold, &buckets);
154     ASSERT_EQ(1u, buckets[eventKey].size());
155     EXPECT_EQ((3 * bucketSizeNs) + 20 - 1, buckets[eventKey][0].mDuration);
156     EXPECT_EQ(bucketStartTimeNs + 3 * bucketSizeNs, buckets[eventKey][0].mBucketStartNs);
157     EXPECT_EQ(bucketStartTimeNs + 4 * bucketSizeNs, buckets[eventKey][0].mBucketEndNs);
158 }
159 
TEST(MaxDurationTrackerTest,TestCrossBucketBoundary_nested)160 TEST(MaxDurationTrackerTest, TestCrossBucketBoundary_nested) {
161     const MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 0, "1");
162     const HashableDimensionKey key1 = getMockedDimensionKey(TagId, 1, "1");
163     const HashableDimensionKey key2 = getMockedDimensionKey(TagId, 1, "2");
164     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
165 
166     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
167 
168     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
169     int64_t bucketStartTimeNs = 10000000000;
170     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
171     int64_t bucketNum = 0;
172 
173     int64_t metricId = 1;
174     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, -1, true, bucketStartTimeNs,
175                                bucketNum, bucketStartTimeNs, bucketSizeNs, false, false, {});
176 
177     // 2 starts
178     tracker.noteStart(DEFAULT_DIMENSION_KEY, true, bucketStartTimeNs + 1, ConditionKey());
179     tracker.noteStart(DEFAULT_DIMENSION_KEY, true, bucketStartTimeNs + 10, ConditionKey());
180     // one stop
181     tracker.noteStop(DEFAULT_DIMENSION_KEY, bucketStartTimeNs + 20, false /*stop all*/);
182 
183     tracker.flushIfNeeded(bucketStartTimeNs + (2 * bucketSizeNs) + 1, emptyThreshold, &buckets);
184     // Because of nesting, still not stopped.
185     EXPECT_TRUE(buckets.find(eventKey) == buckets.end());
186 
187     // real stop now.
188     tracker.noteStop(DEFAULT_DIMENSION_KEY,
189                      bucketStartTimeNs + (2 * bucketSizeNs) + 5, false);
190     tracker.flushIfNeeded(bucketStartTimeNs + (3 * bucketSizeNs) + 1, emptyThreshold, &buckets);
191 
192     ASSERT_EQ(1u, buckets[eventKey].size());
193     EXPECT_EQ(2 * bucketSizeNs + 5 - 1, buckets[eventKey][0].mDuration);
194 }
195 
TEST(MaxDurationTrackerTest,TestMaxDurationWithCondition)196 TEST(MaxDurationTrackerTest, TestMaxDurationWithCondition) {
197     const HashableDimensionKey conditionDimKey = key1;
198 
199     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
200 
201     ConditionKey conditionKey1;
202     MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 1, "1");
203     conditionKey1[StringToId("APP_BACKGROUND")] = conditionDimKey;
204 
205     /**
206     Start in first bucket, stop in second bucket. Condition turns on and off in the first bucket
207     and again turns on and off in the second bucket.
208     */
209     int64_t bucketStartTimeNs = 10000000000;
210     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
211     int64_t eventStartTimeNs = bucketStartTimeNs + 1 * NS_PER_SEC;
212     int64_t conditionStarts1 = bucketStartTimeNs + 11 * NS_PER_SEC;
213     int64_t conditionStops1 = bucketStartTimeNs + 14 * NS_PER_SEC;
214     int64_t conditionStarts2 = bucketStartTimeNs + bucketSizeNs + 5 * NS_PER_SEC;
215     int64_t conditionStops2 = conditionStarts2 + 10 * NS_PER_SEC;
216     int64_t eventStopTimeNs = conditionStops2 + 8 * NS_PER_SEC;
217 
218     int64_t metricId = 1;
219     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
220                                0, bucketStartTimeNs, bucketSizeNs, true, false, {});
221     EXPECT_TRUE(tracker.mAnomalyTrackers.empty());
222 
223     tracker.noteStart(key1, false, eventStartTimeNs, conditionKey1);
224     tracker.noteConditionChanged(key1, true, conditionStarts1);
225     tracker.noteConditionChanged(key1, false, conditionStops1);
226     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
227     tracker.flushIfNeeded(bucketStartTimeNs + bucketSizeNs + 1, emptyThreshold, &buckets);
228     ASSERT_EQ(0U, buckets.size());
229 
230     tracker.noteConditionChanged(key1, true, conditionStarts2);
231     tracker.noteConditionChanged(key1, false, conditionStops2);
232     tracker.noteStop(key1, eventStopTimeNs, false);
233     tracker.flushIfNeeded(bucketStartTimeNs + 2 * bucketSizeNs + 1, emptyThreshold, &buckets);
234     ASSERT_EQ(1U, buckets.size());
235     vector<DurationBucket> item = buckets.begin()->second;
236     ASSERT_EQ(1UL, item.size());
237     EXPECT_EQ((int64_t)(13LL * NS_PER_SEC), item[0].mDuration);
238 }
239 
TEST(MaxDurationTrackerTest,TestAnomalyDetection)240 TEST(MaxDurationTrackerTest, TestAnomalyDetection) {
241     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
242 
243     ConditionKey conditionKey1;
244     MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 2, "maps");
245     conditionKey1[StringToId("APP_BACKGROUND")] = conditionKey;
246 
247     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
248 
249     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
250     int64_t bucketStartTimeNs = 10000000000;
251     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
252     int64_t bucketNum = 0;
253     int64_t eventStartTimeNs = 13000000000;
254     int64_t durationTimeNs = 2 * 1000;
255 
256     int64_t metricId = 1;
257     Alert alert;
258     alert.set_id(101);
259     alert.set_metric_id(1);
260     alert.set_trigger_if_sum_gt(40 * NS_PER_SEC);
261     alert.set_num_buckets(2);
262     const int32_t refPeriodSec = 45;
263     alert.set_refractory_period_secs(refPeriodSec);
264     sp<AlarmMonitor> alarmMonitor;
265     sp<DurationAnomalyTracker> anomalyTracker =
266         new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
267     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
268                                bucketNum, bucketStartTimeNs, bucketSizeNs, true, false,
269                                {anomalyTracker});
270 
271     tracker.noteStart(key1, true, eventStartTimeNs, conditionKey1);
272     sp<const InternalAlarm> alarm = anomalyTracker->mAlarms.begin()->second;
273     EXPECT_EQ((long long)(53ULL * NS_PER_SEC), (long long)(alarm->timestampSec * NS_PER_SEC));
274 
275     // Remove the anomaly alarm when the duration is no longer fully met.
276     tracker.noteConditionChanged(key1, false, eventStartTimeNs + 15 * NS_PER_SEC);
277     ASSERT_EQ(0U, anomalyTracker->mAlarms.size());
278 
279     // Since the condition was off for 10 seconds, the anomaly should trigger 10 sec later.
280     tracker.noteConditionChanged(key1, true, eventStartTimeNs + 25 * NS_PER_SEC);
281     ASSERT_EQ(1U, anomalyTracker->mAlarms.size());
282     alarm = anomalyTracker->mAlarms.begin()->second;
283     EXPECT_EQ((long long)(63ULL * NS_PER_SEC), (long long)(alarm->timestampSec * NS_PER_SEC));
284 }
285 
286 // This tests that we correctly compute the predicted time of an anomaly assuming that the current
287 // state continues forward as-is.
TEST(MaxDurationTrackerTest,TestAnomalyPredictedTimestamp)288 TEST(MaxDurationTrackerTest, TestAnomalyPredictedTimestamp) {
289     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
290 
291     ConditionKey conditionKey1;
292     MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 2, "maps");
293     conditionKey1[StringToId("APP_BACKGROUND")] = conditionKey;
294     ConditionKey conditionKey2;
295     conditionKey2[StringToId("APP_BACKGROUND")] = getMockedDimensionKey(TagId, 4, "2");
296 
297     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
298 
299     /**
300      * Suppose we have two sub-dimensions that we're taking the MAX over. In the first of these
301      * nested dimensions, we enter the pause state after 3 seconds. When we resume, the second
302      * dimension has already been running for 4 seconds. Thus, we have 40-4=36 seconds remaining
303      * before we trigger the anomaly.
304      */
305     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
306     int64_t bucketStartTimeNs = 10000000000;
307     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
308     int64_t bucketNum = 0;
309     int64_t eventStartTimeNs = bucketStartTimeNs + 5 * NS_PER_SEC;  // Condition is off at start.
310     int64_t conditionStarts1 = bucketStartTimeNs + 11 * NS_PER_SEC;
311     int64_t conditionStops1 = bucketStartTimeNs + 14 * NS_PER_SEC;
312     int64_t conditionStarts2 = bucketStartTimeNs + 20 * NS_PER_SEC;
313     int64_t eventStartTimeNs2 = conditionStarts2 - 4 * NS_PER_SEC;
314 
315     int64_t metricId = 1;
316     Alert alert;
317     alert.set_id(101);
318     alert.set_metric_id(1);
319     alert.set_trigger_if_sum_gt(40 * NS_PER_SEC);
320     alert.set_num_buckets(2);
321     const int32_t refPeriodSec = 45;
322     alert.set_refractory_period_secs(refPeriodSec);
323     sp<AlarmMonitor> alarmMonitor;
324     sp<DurationAnomalyTracker> anomalyTracker =
325         new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
326     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
327                                bucketNum, bucketStartTimeNs, bucketSizeNs, true, false,
328                                {anomalyTracker});
329 
330     tracker.noteStart(key1, false, eventStartTimeNs, conditionKey1);
331     tracker.noteConditionChanged(key1, true, conditionStarts1);
332     tracker.noteConditionChanged(key1, false, conditionStops1);
333     tracker.noteStart(key2, true, eventStartTimeNs2, conditionKey2);  // Condition is on already.
334     tracker.noteConditionChanged(key1, true, conditionStarts2);
335     ASSERT_EQ(1U, anomalyTracker->mAlarms.size());
336     auto alarm = anomalyTracker->mAlarms.begin()->second;
337     int64_t anomalyFireTimeSec = alarm->timestampSec;
338     EXPECT_EQ(conditionStarts2 + 36 * NS_PER_SEC,
339             (long long)anomalyFireTimeSec * NS_PER_SEC);
340 
341     // Now we test the calculation now that there's a refractory period.
342     // At the correct time, declare the anomaly. This will set a refractory period. Make sure it
343     // gets correctly taken into account in future predictAnomalyTimestampNs calculations.
344     std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> firedAlarms({alarm});
345     anomalyTracker->informAlarmsFired(anomalyFireTimeSec * NS_PER_SEC, firedAlarms);
346     ASSERT_EQ(0u, anomalyTracker->mAlarms.size());
347     int64_t refractoryPeriodEndsSec = anomalyFireTimeSec + refPeriodSec;
348     EXPECT_EQ(anomalyTracker->getRefractoryPeriodEndsSec(eventKey), refractoryPeriodEndsSec);
349 
350     // Now stop and start again. Make sure the new predictAnomalyTimestampNs takes into account
351     // the refractory period correctly.
352     int64_t eventStopTimeNs = anomalyFireTimeSec * NS_PER_SEC + 10;
353     tracker.noteStop(key1, eventStopTimeNs, false);
354     tracker.noteStop(key2, eventStopTimeNs, false);
355     tracker.noteStart(key1, true, eventStopTimeNs + 1000000, conditionKey1);
356     // Anomaly is ongoing, but we're still in the refractory period.
357     ASSERT_EQ(1U, anomalyTracker->mAlarms.size());
358     alarm = anomalyTracker->mAlarms.begin()->second;
359     EXPECT_EQ(refractoryPeriodEndsSec, (long long)(alarm->timestampSec));
360 
361     // Makes sure it is correct after the refractory period is over.
362     tracker.noteStop(key1, eventStopTimeNs + 2000000, false);
363     int64_t justBeforeRefPeriodNs = (refractoryPeriodEndsSec - 2) * NS_PER_SEC;
364     tracker.noteStart(key1, true, justBeforeRefPeriodNs, conditionKey1);
365     alarm = anomalyTracker->mAlarms.begin()->second;
366     EXPECT_EQ(justBeforeRefPeriodNs + 40 * NS_PER_SEC,
367                 (unsigned long long)(alarm->timestampSec * NS_PER_SEC));
368 }
369 
370 // Suppose that within one tracker there are two dimensions A and B.
371 // Suppose A starts, then B starts, and then A stops. We still need to set an anomaly based on the
372 // elapsed duration of B.
TEST(MaxDurationTrackerTest,TestAnomalyPredictedTimestamp_UpdatedOnStop)373 TEST(MaxDurationTrackerTest, TestAnomalyPredictedTimestamp_UpdatedOnStop) {
374     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
375 
376     ConditionKey conditionKey1;
377     MetricDimensionKey eventKey = getMockedMetricDimensionKey(TagId, 2, "maps");
378     conditionKey1[StringToId("APP_BACKGROUND")] = conditionKey;
379     ConditionKey conditionKey2;
380     conditionKey2[StringToId("APP_BACKGROUND")] = getMockedDimensionKey(TagId, 4, "2");
381 
382     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
383 
384     /**
385      * Suppose we have two sub-dimensions that we're taking the MAX over. In the first of these
386      * nested dimensions, are started for 8 seconds. When we stop, the other nested dimension has
387      * been started for 5 seconds. So we can only allow 35 more seconds from now.
388      */
389     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
390     int64_t bucketStartTimeNs = 10000000000;
391     int64_t bucketEndTimeNs = bucketStartTimeNs + bucketSizeNs;
392     int64_t bucketNum = 0;
393     int64_t eventStartTimeNs1 = bucketStartTimeNs + 5 * NS_PER_SEC;  // Condition is off at start.
394     int64_t eventStopTimeNs1 = bucketStartTimeNs + 13 * NS_PER_SEC;
395     int64_t eventStartTimeNs2 = bucketStartTimeNs + 8 * NS_PER_SEC;
396 
397     int64_t metricId = 1;
398     Alert alert;
399     alert.set_id(101);
400     alert.set_metric_id(1);
401     alert.set_trigger_if_sum_gt(40 * NS_PER_SEC);
402     alert.set_num_buckets(2);
403     const int32_t refPeriodSec = 45;
404     alert.set_refractory_period_secs(refPeriodSec);
405     sp<AlarmMonitor> alarmMonitor;
406     sp<DurationAnomalyTracker> anomalyTracker =
407         new DurationAnomalyTracker(alert, kConfigKey, alarmMonitor);
408     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
409                                bucketNum, bucketStartTimeNs, bucketSizeNs, true, false,
410                                {anomalyTracker});
411 
412     tracker.noteStart(key1, true, eventStartTimeNs1, conditionKey1);
413     tracker.noteStart(key2, true, eventStartTimeNs2, conditionKey2);
414     tracker.noteStop(key1, eventStopTimeNs1, false);
415     ASSERT_EQ(1U, anomalyTracker->mAlarms.size());
416     auto alarm = anomalyTracker->mAlarms.begin()->second;
417     EXPECT_EQ(eventStopTimeNs1 + 35 * NS_PER_SEC,
418               (unsigned long long)(alarm->timestampSec * NS_PER_SEC));
419 }
420 
TEST(MaxDurationTrackerTest,TestUploadThreshold)421 TEST(MaxDurationTrackerTest, TestUploadThreshold) {
422     sp<MockConditionWizard> wizard = new NaggyMock<MockConditionWizard>();
423 
424     unordered_map<MetricDimensionKey, vector<DurationBucket>> buckets;
425 
426     int64_t bucketSizeNs = 30 * 1000 * 1000 * 1000LL;
427     int64_t bucketStartTimeNs = 10000000000;
428     int64_t bucketNum = 0;
429     int64_t eventStartTimeNs = bucketStartTimeNs + 1;
430     int64_t event2StartTimeNs = bucketStartTimeNs + bucketSizeNs + 1;
431     int64_t thresholdDurationNs = 2000;
432 
433     UploadThreshold threshold;
434     threshold.set_gt_int(thresholdDurationNs);
435 
436     MaxDurationTracker tracker(kConfigKey, metricId, eventKey, wizard, 1, false, bucketStartTimeNs,
437                                bucketNum, bucketStartTimeNs, bucketSizeNs, false, false, {});
438 
439     // Duration below the gt_int threshold should not be added to past buckets.
440     tracker.noteStart(key1, true, eventStartTimeNs, ConditionKey());
441     tracker.noteStop(key1, eventStartTimeNs + thresholdDurationNs, false);
442     tracker.flushIfNeeded(eventStartTimeNs + bucketSizeNs + 1, threshold, &buckets);
443     EXPECT_TRUE(buckets.find(eventKey) == buckets.end());
444 
445     // Duration above the gt_int threshold should be added to past buckets.
446     tracker.noteStart(key1, true, event2StartTimeNs, ConditionKey());
447     tracker.noteStop(key1, event2StartTimeNs + thresholdDurationNs + 1, false);
448     tracker.flushIfNeeded(event2StartTimeNs + bucketSizeNs + 1, threshold, &buckets);
449     EXPECT_TRUE(buckets.find(eventKey) != buckets.end());
450     ASSERT_EQ(1u, buckets[eventKey].size());
451     EXPECT_EQ(thresholdDurationNs + 1, buckets[eventKey][0].mDuration);
452 }
453 
454 }  // namespace statsd
455 }  // namespace os
456 }  // namespace android
457 #else
458 GTEST_LOG_(INFO) << "This test does nothing.\n";
459 #endif
460