1 /*
2 * Copyright (C) 2019, 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 #include <sys/eventfd.h>
18 #include <cstdlib>
19 #include <ctime>
20 #include <iostream>
21 #include <numeric>
22 #include <string>
23 #include <thread>
24
25 #include <sys/epoll.h>
26 #include <unistd.h>
27
28 #include <ILazyTestService.h>
29 #include <ILazyTestServiceCb.h>
30 #include <binder/IPCThreadState.h>
31 #include <binder/IServiceManager.h>
32 #include <gtest/gtest.h>
33 #include <utils/String8.h>
34
35 using ::ILazyTestService;
36 using ::android::IBinder;
37 using ::android::IPCThreadState;
38 using ::android::IServiceManager;
39 using ::android::sp;
40 using ::android::String16;
41 using ::android::base::unique_fd;
42 using ::android::os::ParcelFileDescriptor;
43
44 std::vector<String16> gServiceNames;
45 static constexpr size_t SHUTDOWN_WAIT_MS = 10000;
46 static constexpr size_t CALLBACK_SHUTDOWN_WAIT_MS = 5000;
47
waitForService(const String16 & name)48 sp<IBinder> waitForService(const String16& name) {
49 sp<IServiceManager> manager;
50 manager = android::defaultServiceManager();
51 EXPECT_NE(manager, nullptr);
52
53 return manager->waitForService(name);
54 }
55
isServiceRunning(const String16 & name)56 bool isServiceRunning(const String16& name) {
57 sp<IServiceManager> manager;
58 manager = android::defaultServiceManager();
59 EXPECT_NE(manager, nullptr);
60
61 return manager->checkService(name) != nullptr;
62 }
63
64 class AidlLazyTest : public ::testing::Test {
65 protected:
66 sp<IServiceManager> manager;
67
SetUp()68 void SetUp() override {
69 manager = android::defaultServiceManager();
70 ASSERT_NE(manager, nullptr);
71
72 for (size_t i = 0; i < gServiceNames.size(); i++) {
73 ASSERT_FALSE(isServiceRunning(gServiceNames.at(i)))
74 << "Service '" << android::String8(gServiceNames.at(i)) << "' is already running. "
75 << "Please ensure this is implemented as a lazy service, then kill all "
76 << "clients of this service and try again.";
77 }
78 }
79
TearDown()80 void TearDown() override {
81 std::cout << "Waiting " << SHUTDOWN_WAIT_MS << " milliseconds before checking that the "
82 << "service has shut down." << std::endl;
83 IPCThreadState::self()->flushCommands();
84 usleep(SHUTDOWN_WAIT_MS * 1000);
85 for (size_t i = 0; i < gServiceNames.size(); i++) {
86 ASSERT_FALSE(isServiceRunning(gServiceNames.at(i))) << "Service failed to shut down.";
87 }
88 }
89 };
90
91 static constexpr size_t NUM_IMMEDIATE_GETS = 100;
TEST_F(AidlLazyTest,GetRelease)92 TEST_F(AidlLazyTest, GetRelease) {
93 size_t nServices = gServiceNames.size();
94
95 for (size_t i = 0; i < nServices * NUM_IMMEDIATE_GETS; i++) {
96 IPCThreadState::self()->flushCommands();
97 sp<IBinder> service = waitForService(gServiceNames.at(i % nServices));
98 ASSERT_NE(service.get(), nullptr);
99 ASSERT_EQ(service->pingBinder(), android::NO_ERROR);
100 }
101 }
102
waitMs(size_t numTimes,size_t maxWait)103 static std::vector<size_t> waitMs(size_t numTimes, size_t maxWait) {
104 std::vector<size_t> times(numTimes);
105 for (size_t i = 0; i < numTimes; i++) {
106 times.at(i) = (size_t)(rand() % (maxWait + 1));
107 }
108 return times;
109 }
110
testWithTimes(const std::vector<size_t> & waitMs,bool beforeGet)111 static void testWithTimes(const std::vector<size_t>& waitMs, bool beforeGet) {
112 size_t nServices = gServiceNames.size();
113 for (size_t i = 0; i < waitMs.size(); i++) {
114 IPCThreadState::self()->flushCommands();
115 if (beforeGet) {
116 std::cout << "Thread waiting " << waitMs.at(i) << " while not holding service." << std::endl;
117 usleep(waitMs.at(i) * 1000);
118 }
119
120 sp<IBinder> service = waitForService(gServiceNames.at(i % nServices));
121
122 if (!beforeGet) {
123 std::cout << "Thread waiting " << waitMs.at(i) << " while holding service." << std::endl;
124 usleep(waitMs.at(i) * 1000);
125 }
126
127 ASSERT_NE(service.get(), nullptr);
128 ASSERT_EQ(service->pingBinder(), android::NO_ERROR);
129 }
130 }
131
132 static constexpr size_t NUM_TIMES_GET_RELEASE = 5;
133 static constexpr size_t MAX_WAITING_DURATION_MS = 10000;
134 static constexpr size_t NUM_CONCURRENT_THREADS = 3;
testConcurrentThreadsWithDelays(bool delayBeforeGet)135 static void testConcurrentThreadsWithDelays(bool delayBeforeGet) {
136 size_t nServices = gServiceNames.size();
137 std::vector<std::vector<size_t>> threadWaitTimes(NUM_CONCURRENT_THREADS);
138 int maxWait = 0;
139 for (size_t i = 0; i < threadWaitTimes.size(); i++) {
140 threadWaitTimes.at(i) = waitMs(NUM_TIMES_GET_RELEASE * nServices, MAX_WAITING_DURATION_MS);
141 int totalWait = std::accumulate(threadWaitTimes.at(i).begin(), threadWaitTimes.at(i).end(), 0);
142 maxWait = std::max(maxWait, totalWait);
143 }
144 std::cout << "Additional runtime expected from sleeps: " << maxWait << " millisecond(s)."
145 << std::endl;
146
147 std::vector<std::thread> threads(NUM_CONCURRENT_THREADS);
148 for (size_t i = 0; i < threads.size(); i++) {
149 threads.at(i) = std::thread(testWithTimes, threadWaitTimes.at(i), delayBeforeGet);
150 }
151
152 for (auto& thread : threads) {
153 thread.join();
154 }
155 }
156
TEST_F(AidlLazyTest,GetConcurrentWithWaitBefore)157 TEST_F(AidlLazyTest, GetConcurrentWithWaitBefore) {
158 testConcurrentThreadsWithDelays(true);
159 }
160
TEST_F(AidlLazyTest,GetConcurrentWithWaitAfter)161 TEST_F(AidlLazyTest, GetConcurrentWithWaitAfter) {
162 testConcurrentThreadsWithDelays(false);
163 }
164
165 class AidlLazyRegistrarTest : public ::testing::Test {
166 protected:
167 const String16 serviceName = String16("aidl_lazy_test_1");
SetUp()168 void SetUp() override {
169 if (std::find(gServiceNames.begin(), gServiceNames.end(), serviceName) == gServiceNames.end()) {
170 GTEST_SKIP() << "Persistence test requires special instance: " << serviceName;
171 }
172 }
173 };
174
175 template <typename T>
waitForLazyTestService(String16 name)176 sp<T> waitForLazyTestService(String16 name) {
177 sp<T> service = android::waitForService<T>(name);
178 EXPECT_NE(service, nullptr);
179 return service;
180 }
181
TEST_F(AidlLazyRegistrarTest,ForcedPersistenceTest)182 TEST_F(AidlLazyRegistrarTest, ForcedPersistenceTest) {
183 sp<ILazyTestService> service;
184 for (int i = 0; i < 2; i++) {
185 service = waitForLazyTestService<ILazyTestService>(serviceName);
186 EXPECT_TRUE(service->forcePersist(i == 0).isOk());
187 service = nullptr;
188
189 std::cout << "Waiting " << SHUTDOWN_WAIT_MS << " milliseconds before checking whether the "
190 << "service is still running." << std::endl;
191 IPCThreadState::self()->flushCommands();
192 usleep(SHUTDOWN_WAIT_MS * 1000);
193
194 if (i == 0) {
195 ASSERT_TRUE(isServiceRunning(serviceName)) << "Service shut down when it shouldn't have.";
196 } else {
197 ASSERT_FALSE(isServiceRunning(serviceName)) << "Service failed to shut down.";
198 }
199 }
200 }
201
TEST_F(AidlLazyRegistrarTest,ActiveServicesCountCallbackTest)202 TEST_F(AidlLazyRegistrarTest, ActiveServicesCountCallbackTest) {
203 const String16 cbServiceName = String16("aidl_lazy_cb_test");
204
205 int efd = eventfd(0, 0);
206 ASSERT_GE(efd, 0) << "Failed to create eventfd";
207
208 unique_fd uniqueEventFd(efd);
209 ParcelFileDescriptor parcelEventFd(std::move(uniqueEventFd));
210
211 sp<ILazyTestServiceCb> service;
212 service = waitForLazyTestService<ILazyTestServiceCb>(cbServiceName);
213 ASSERT_TRUE(service->setEventFd(parcelEventFd).isOk());
214 service = nullptr;
215
216 IPCThreadState::self()->flushCommands();
217
218 std::cout << "Waiting " << SHUTDOWN_WAIT_MS << " milliseconds for callback completion "
219 << "notification." << std::endl;
220
221 int epollFd = epoll_create1(EPOLL_CLOEXEC);
222 ASSERT_GE(epollFd, 0) << "Failed to create epoll";
223 unique_fd epollUniqueFd(epollFd);
224
225 const int EPOLL_MAX_EVENTS = 1;
226 struct epoll_event event, events[EPOLL_MAX_EVENTS];
227
228 event.events = EPOLLIN;
229 event.data.fd = efd;
230 int rc = epoll_ctl(epollFd, EPOLL_CTL_ADD, efd, &event);
231 ASSERT_GE(rc, 0) << "Failed to add fd to epoll";
232
233 rc = TEMP_FAILURE_RETRY(epoll_wait(epollFd, events, EPOLL_MAX_EVENTS, SHUTDOWN_WAIT_MS));
234 ASSERT_NE(rc, 0) << "Service shutdown timeout";
235 ASSERT_GT(rc, 0) << "Error waiting for service shutdown notification";
236
237 eventfd_t counter;
238 rc = TEMP_FAILURE_RETRY(eventfd_read(parcelEventFd.get(), &counter));
239 ASSERT_GE(rc, 0) << "Failed to get callback completion notification from service";
240 ASSERT_EQ(counter, 1);
241
242 std::cout << "Waiting " << CALLBACK_SHUTDOWN_WAIT_MS
243 << " milliseconds before checking whether the "
244 << "service is still running." << std::endl;
245
246 usleep(CALLBACK_SHUTDOWN_WAIT_MS * 1000);
247
248 ASSERT_FALSE(isServiceRunning(serviceName)) << "Service failed to shut down.";
249 }
250
main(int argc,char ** argv)251 int main(int argc, char** argv) {
252 ::testing::InitGoogleTest(&argc, argv);
253
254 srand(time(nullptr));
255
256 if (argc < 2) {
257 // If the user does not specify any service to test, default to these test interfaces
258 gServiceNames.push_back(String16("aidl_lazy_test_1"));
259 gServiceNames.push_back(String16("aidl_lazy_test_2"));
260 } else {
261 for (int i = 1; i < argc; i++) {
262 gServiceNames.push_back(String16(argv[i]));
263 }
264 }
265
266 android::ProcessState::self()->startThreadPool();
267
268 return RUN_ALL_TESTS();
269 }
270