1 // Copyright (C) 2018 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/anomaly/AlarmTracker.h"
16 
17 #include <gtest/gtest.h>
18 #include <log/log_time.h>
19 #include <stdio.h>
20 
21 #include <vector>
22 
23 #include "src/subscriber/SubscriberReporter.h"
24 #include "tests/statsd_test_util.h"
25 
26 using namespace testing;
27 using android::sp;
28 using std::set;
29 using std::shared_ptr;
30 using std::unordered_map;
31 using std::vector;
32 
33 #ifdef __ANDROID__
34 
35 namespace android {
36 namespace os {
37 namespace statsd {
38 
39 namespace {
40 const int kConfigUid = 0;
41 const int kConfigId = 12345;
42 const ConfigKey kConfigKey(kConfigUid, kConfigId);
43 }  // anonymous namespace
44 
TEST(AlarmTrackerTest,TestTriggerTimestamp)45 TEST(AlarmTrackerTest, TestTriggerTimestamp) {
46     sp<AlarmMonitor> subscriberAlarmMonitor =
47         new AlarmMonitor(100,
48                          [](const shared_ptr<IStatsCompanionService>&, int64_t){},
49                          [](const shared_ptr<IStatsCompanionService>&){});
50     Alarm alarm;
51     alarm.set_offset_millis(15 * MS_PER_SEC);
52     alarm.set_period_millis(60 * 60 * MS_PER_SEC);  // 1hr
53     int64_t startMillis = 100000000 * MS_PER_SEC;
54     int64_t nextAlarmTime = startMillis / MS_PER_SEC + 15;
55     AlarmTracker tracker(startMillis, startMillis, alarm, kConfigKey, subscriberAlarmMonitor);
56 
57     EXPECT_EQ(tracker.mAlarmSec, nextAlarmTime);
58 
59     uint64_t currentTimeSec = startMillis / MS_PER_SEC + 10;
60     std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> firedAlarmSet =
61         subscriberAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
62     EXPECT_TRUE(firedAlarmSet.empty());
63     tracker.informAlarmsFired(currentTimeSec * NS_PER_SEC, firedAlarmSet);
64     EXPECT_EQ(tracker.mAlarmSec, nextAlarmTime);
65     EXPECT_EQ(tracker.getAlarmTimestampSec(), nextAlarmTime);
66 
67     currentTimeSec = startMillis / MS_PER_SEC + 7000;
68     nextAlarmTime = startMillis / MS_PER_SEC + 15 + 2 * 60 * 60;
69     firedAlarmSet = subscriberAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
70     ASSERT_EQ(firedAlarmSet.size(), 1u);
71     tracker.informAlarmsFired(currentTimeSec * NS_PER_SEC, firedAlarmSet);
72     EXPECT_TRUE(firedAlarmSet.empty());
73     EXPECT_EQ(tracker.mAlarmSec, nextAlarmTime);
74     EXPECT_EQ(tracker.getAlarmTimestampSec(), nextAlarmTime);
75 
76     // Alarm fires exactly on time.
77     currentTimeSec = startMillis / MS_PER_SEC + 15 + 2 * 60 * 60;
78     nextAlarmTime = startMillis / MS_PER_SEC + 15 + 3 * 60 * 60;
79     firedAlarmSet = subscriberAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
80     ASSERT_EQ(firedAlarmSet.size(), 1u);
81     tracker.informAlarmsFired(currentTimeSec * NS_PER_SEC, firedAlarmSet);
82     EXPECT_TRUE(firedAlarmSet.empty());
83     EXPECT_EQ(tracker.mAlarmSec, nextAlarmTime);
84     EXPECT_EQ(tracker.getAlarmTimestampSec(), nextAlarmTime);
85 
86     // Alarm fires exactly 1 period late.
87     currentTimeSec = startMillis / MS_PER_SEC + 15 + 4 * 60 * 60;
88     nextAlarmTime = startMillis / MS_PER_SEC + 15 + 5 * 60 * 60;
89     firedAlarmSet = subscriberAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
90     ASSERT_EQ(firedAlarmSet.size(), 1u);
91     tracker.informAlarmsFired(currentTimeSec * NS_PER_SEC, firedAlarmSet);
92     EXPECT_TRUE(firedAlarmSet.empty());
93     EXPECT_EQ(tracker.mAlarmSec, nextAlarmTime);
94     EXPECT_EQ(tracker.getAlarmTimestampSec(), nextAlarmTime);
95 }
96 
TEST(AlarmTrackerTest,TestProbabilityOfInforming)97 TEST(AlarmTrackerTest, TestProbabilityOfInforming) {
98     // Initiating StatsdStats at the start of this test, so it doesn't call rand() during the test
99     StatsdStats::getInstance();
100     srand(/*commonly used seed=*/0);
101     sp<AlarmMonitor> subscriberAlarmMonitor = new AlarmMonitor(
102             100, [](const shared_ptr<IStatsCompanionService>&, int64_t) {},
103             [](const shared_ptr<IStatsCompanionService>&) {});
104     int broadcastSubRandId = 1, broadcastSubAlwaysId = 2, broadcastSubNeverId = 3;
105 
106     int64_t startMillis = 100000000 * MS_PER_SEC;
107     uint64_t currentTimeSec = startMillis / MS_PER_SEC + 15 + 60 * 60;
108 
109     // Alarm with probability of informing set to 0.5
110     Alarm alarmRand = createAlarm("alarmRand", /*offsetMillis=*/15 * MS_PER_SEC,
111                                   /*periodMillis=*/60 * 60 * MS_PER_SEC);
112     alarmRand.set_probability_of_informing(0.5);
113     AlarmTracker trackerRand(startMillis, startMillis, alarmRand, kConfigKey,
114                              subscriberAlarmMonitor);
115     Subscription subRand = createSubscription("subRand", /*rule_type=*/Subscription::ALARM,
116                                               /*rule_id=*/alarmRand.id());
117     subRand.mutable_broadcast_subscriber_details()->set_subscriber_id(broadcastSubRandId);
118     trackerRand.addSubscription(subRand);
119 
120     // Alarm with probability of informing set to 1.1 (always; set by default)
121     Alarm alarmAlways = createAlarm("alarmAlways", /*offsetMillis=*/15 * MS_PER_SEC,
122                                     /*periodMillis=*/60 * 60 * MS_PER_SEC);
123     AlarmTracker trackerAlways(startMillis, startMillis, alarmAlways, kConfigKey,
124                                subscriberAlarmMonitor);
125     Subscription subAlways = createSubscription("subAlways", /*rule_type=*/Subscription::ALARM,
126                                                 /*rule_id=*/alarmAlways.id());
127     subAlways.mutable_broadcast_subscriber_details()->set_subscriber_id(broadcastSubAlwaysId);
128     trackerAlways.addSubscription(subAlways);
129 
130     // Alarm with probability of informing set to -0.1 (never)
131     Alarm alarmNever = createAlarm("alarmNever", /*offsetMillis=*/15 * MS_PER_SEC,
132                                    /*periodMillis=*/60 * 60 * MS_PER_SEC);
133     alarmNever.set_probability_of_informing(-0.1);
134     AlarmTracker trackerNever(startMillis, startMillis, alarmNever, kConfigKey,
135                               subscriberAlarmMonitor);
136     Subscription subNever = createSubscription("subNever", /*rule_type=*/Subscription::ALARM,
137                                                /*rule_id=*/alarmNever.id());
138     subNever.mutable_broadcast_subscriber_details()->set_subscriber_id(broadcastSubNeverId);
139     trackerNever.addSubscription(subNever);
140 
141     std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> firedAlarmSet =
142             subscriberAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
143     ASSERT_EQ(firedAlarmSet.size(), 3u);
144 
145     int alarmRandCount = 0, alarmAlwaysCount = 0;
146     // The binder calls here will happen synchronously because they are in-process.
147     shared_ptr<MockPendingIntentRef> randBroadcast =
148             SharedRefBase::make<StrictMock<MockPendingIntentRef>>();
149     EXPECT_CALL(*randBroadcast,
150                 sendSubscriberBroadcast(kConfigUid, kConfigId, subRand.id(), alarmRand.id(), _, _))
151             .Times(3)
152             .WillRepeatedly([&alarmRandCount] {
153                 alarmRandCount++;
154                 return Status::ok();
155             });
156 
157     shared_ptr<MockPendingIntentRef> alwaysBroadcast =
158             SharedRefBase::make<StrictMock<MockPendingIntentRef>>();
159     EXPECT_CALL(*alwaysBroadcast, sendSubscriberBroadcast(kConfigUid, kConfigId, subAlways.id(),
160                                                           alarmAlways.id(), _, _))
161             .Times(10)
162             .WillRepeatedly([&alarmAlwaysCount] {
163                 alarmAlwaysCount++;
164                 return Status::ok();
165             });
166 
167     shared_ptr<MockPendingIntentRef> neverBroadcast =
168             SharedRefBase::make<StrictMock<MockPendingIntentRef>>();
169     EXPECT_CALL(*neverBroadcast, sendSubscriberBroadcast(kConfigUid, kConfigId, subNever.id(),
170                                                          alarmNever.id(), _, _))
171             .Times(0);
172 
173     SubscriberReporter::getInstance().setBroadcastSubscriber(kConfigKey, broadcastSubRandId,
174                                                              randBroadcast);
175     SubscriberReporter::getInstance().setBroadcastSubscriber(kConfigKey, broadcastSubAlwaysId,
176                                                              alwaysBroadcast);
177     SubscriberReporter::getInstance().setBroadcastSubscriber(kConfigKey, broadcastSubNeverId,
178                                                              neverBroadcast);
179     // Trying to inform the subscription 10x.
180     // Deterministic sequence for trackerRand:
181     // 0.96, 0.95, 0.95, 0.94, 0.43, 0.92, 0.92, 0.41, 0.39, 0.88
182     for (size_t i = 0; i < 10; i++) {
183         trackerRand.informAlarmsFired(currentTimeSec * NS_PER_SEC, firedAlarmSet);
184         if (i <= 3) {
185             EXPECT_EQ(alarmRandCount, 0);
186         } else if (i >= 4 && i <= 6) {
187             EXPECT_EQ(alarmRandCount, 1);
188         } else if (i == 7) {
189             EXPECT_EQ(alarmRandCount, 2);
190         } else {
191             EXPECT_EQ(alarmRandCount, 3);
192         }
193         trackerAlways.informAlarmsFired(currentTimeSec * NS_PER_SEC, firedAlarmSet);
194         EXPECT_EQ(alarmAlwaysCount, i + 1);
195         trackerNever.informAlarmsFired(currentTimeSec * NS_PER_SEC, firedAlarmSet);
196 
197         currentTimeSec = startMillis / MS_PER_SEC + 15 + (i + 2) * 60 * 60;
198         firedAlarmSet =
199                 subscriberAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
200     }
201     SubscriberReporter::getInstance().unsetBroadcastSubscriber(kConfigKey, broadcastSubRandId);
202     SubscriberReporter::getInstance().unsetBroadcastSubscriber(kConfigKey, broadcastSubAlwaysId);
203     SubscriberReporter::getInstance().unsetBroadcastSubscriber(kConfigKey, broadcastSubNeverId);
204 }
205 
206 }  // namespace statsd
207 }  // namespace os
208 }  // namespace android
209 #else
210 GTEST_LOG_(INFO) << "This test does nothing.\n";
211 #endif
212