blob: a5ecbac39bb898ae3526b6e865ca226ee5ef9db3 [file] [log] [blame]
QUICHE team53f08a32019-04-15 14:47:31 -04001// Copyright 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5// Epoll tests which determine that the right things happen in the right order.
6// Also lots of testing of individual functions.
7
8#include "net/third_party/quiche/src/epoll_server/simple_epoll_server.h"
9
10#include <errno.h>
11#include <fcntl.h>
12#include <netinet/in.h>
13#include <sys/epoll.h>
14#include <sys/socket.h>
15#include <unistd.h>
16
17#include <algorithm>
18#include <cstddef>
19#include <cstdlib>
20#include <cstring>
QUICHE team53f08a32019-04-15 14:47:31 -040021#include <memory>
22#include <string>
danzh840edb62019-04-15 19:11:03 -040023#include <unordered_map>
QUICHE team53f08a32019-04-15 14:47:31 -040024#include <utility>
25#include <vector>
26
27#include "net/third_party/quiche/src/epoll_server/fake_simple_epoll_server.h"
28#include "net/third_party/quiche/src/epoll_server/platform/api/epoll_address_test_utils.h"
29#include "net/third_party/quiche/src/epoll_server/platform/api/epoll_expect_bug.h"
30#include "net/third_party/quiche/src/epoll_server/platform/api/epoll_test.h"
31#include "net/third_party/quiche/src/epoll_server/platform/api/epoll_thread.h"
32#include "net/third_party/quiche/src/epoll_server/platform/api/epoll_time.h"
33
34namespace epoll_server {
35
36namespace test {
37
38namespace {
39
40const int kPageSize = 4096;
41const int kMaxBufLen = 10000;
42
43// These are used to record what is happening.
44enum {
45 CREATION,
46 REGISTRATION,
47 MODIFICATION,
48 EVENT,
49 UNREGISTRATION,
50 SHUTDOWN,
51 DESTRUCTION
52};
53
54////////////////////////////////////////////////////////////////////////////////
55////////////////////////////////////////////////////////////////////////////////
56
57
58////////////////////////////////////////////////////////////////////////////////
59////////////////////////////////////////////////////////////////////////////////
60
61struct RecordEntry {
62 RecordEntry() : time(0), instance(nullptr), event_type(0), fd(0), data(0) {}
63
64 RecordEntry(int64_t time, void* instance, int event_type, int fd, int data)
65 : time(time),
66 instance(instance),
67 event_type(event_type),
68 fd(fd),
69 data(data) {}
70
71 int64_t time;
72 void* instance;
73 int event_type;
74 int fd;
75 int data;
76
77 bool IsEqual(const RecordEntry *entry) const {
78 bool retval = true;
79
80 if (instance != entry->instance) {
81 retval = false;
82 EPOLL_LOG(INFO) << " instance (" << instance << ") != entry->instance("
83 << entry->instance << ")";
84 }
85 if (event_type != entry->event_type) {
86 retval = false;
87 EPOLL_LOG(INFO) << " event_type (" << event_type
88 << ") != entry->event_type(" << entry->event_type << ")";
89 }
90 if ( fd != entry->fd ) {
91 retval = false;
92 EPOLL_LOG(INFO) << " fd (" << fd << ") != entry->fd (" << entry->fd
93 << ")";
94 }
95 if (data != entry->data) {
96 retval = false;
97 EPOLL_LOG(INFO) << " data (" << data << ") != entry->data(" << entry->data
98 << ")";
99 }
100 return retval;
101 }
102};
103
104////////////////////////////////////////////////////////////////////////////////
105////////////////////////////////////////////////////////////////////////////////
106
107class Recorder {
108 public:
109 void Record(void* instance, int event_type, int fd, int data) {
110 records_.push_back(
111 RecordEntry(WallTimeNowInUsec(), instance, event_type, fd, data));
112 }
113
114 const std::vector<RecordEntry> *records() const { return &records_; }
115
116 bool IsEqual(const Recorder *recorder) const {
117 const std::vector<RecordEntry> *records = recorder->records();
118
119 if (records_.size() != records->size()) {
120 EPOLL_LOG(INFO) << "records_.size() (" << records_.size()
121 << ") != records->size() (" << records->size() << ")";
122 return false;
123 }
124 for (size_t i = 0; i < std::min(records_.size(), records->size()); ++i) {
125 if (!records_[i].IsEqual(&(*records)[i])) {
126 EPOLL_LOG(INFO) << "entry in index: " << i
127 << " differs from recorder.";
128 return false;
129 }
130 }
131 return true;
132 }
133
134 private:
135 std::vector<RecordEntry> records_;
136};
137
138
139////////////////////////////////////////////////////////////////////////////////
140////////////////////////////////////////////////////////////////////////////////
141
142class RecordingCB : public EpollCallbackInterface {
143 public:
144 RecordingCB() : recorder_(new Recorder()) {
145 recorder_->Record(this, CREATION, 0, 0);
146 }
147
148 ~RecordingCB() override {
149 recorder_->Record(this, DESTRUCTION, 0, 0);
150 delete recorder_;
151 }
152
153 void OnRegistration(SimpleEpollServer* eps, int fd, int event_mask) override {
154 recorder_->Record(this, REGISTRATION, fd, event_mask);
155 }
156
157 void OnModification(int fd, int event_mask) override {
158 recorder_->Record(this, MODIFICATION, fd, event_mask);
159 }
160
161 void OnEvent(int fd, EpollEvent* event) override {
162 recorder_->Record(this, EVENT, fd, event->in_events);
163 if (event->in_events & EPOLLIN) {
164 const int kLength = 1024;
165 char buf[kLength];
166 read(fd, &buf, kLength);
167 }
168 }
169
170 void OnUnregistration(int fd, bool replaced) override {
171 recorder_->Record(this, UNREGISTRATION, fd, replaced);
172 }
173
174 void OnShutdown(SimpleEpollServer* eps, int fd) override {
175 if (fd >= 0) {
176 eps->UnregisterFD(fd);
177 }
178 recorder_->Record(this, SHUTDOWN, fd, 0);
179 }
180
181 string Name() const override { return "RecordingCB"; }
182
183 const Recorder* recorder() const { return recorder_; }
184
185 protected:
186 Recorder* recorder_;
187};
188
189////////////////////////////////////////////////////////////////////////////////
190////////////////////////////////////////////////////////////////////////////////
191
192// A simple test server that adds some test functions to SimpleEpollServer as
193// well as allowing access to protected functions.
194class EpollTestServer : public SimpleEpollServer {
195 public:
196 EpollTestServer() : SimpleEpollServer() {}
197
198 ~EpollTestServer() override {}
199
200 void CheckMapping(int fd, CB* cb) {
201 CBAndEventMask tmp;
202 tmp.fd = fd;
203 FDToCBMap::iterator fd_i = cb_map_.find(tmp);
204 CHECK(fd_i != cb_map_.end()); // Chokes CHECK_NE.
205 CHECK(fd_i->cb == cb);
206 }
207
208 void CheckNotMapped(int fd) {
209 CBAndEventMask tmp;
210 tmp.fd = fd;
211 FDToCBMap::iterator fd_i = cb_map_.find(tmp);
212 CHECK(fd_i == cb_map_.end()); // Chokes CHECK_EQ.
213 }
214
215 void CheckEventMask(int fd, int event_mask) {
216 CBAndEventMask tmp;
217 tmp.fd = fd;
218 FDToCBMap::iterator fd_i = cb_map_.find(tmp);
219 CHECK(cb_map_.end() != fd_i); // Chokes CHECK_NE.
220 CHECK_EQ(fd_i->event_mask, event_mask);
221 }
222
223 void CheckNotRegistered(int fd) {
224 struct epoll_event ee;
225 memset(&ee, 0, sizeof(ee));
226 // If the fd is registered, the epoll_ctl call would succeed (return 0) and
227 // the CHECK would fail.
228 CHECK(epoll_ctl(epoll_fd_, EPOLL_CTL_DEL, fd, &ee));
229 }
230
231 size_t GetNumPendingAlarmsForTest() const { return alarm_map_.size(); }
232
233 bool ContainsAlarm(AlarmCB* ac) {
234 return all_alarms_.find(ac) != all_alarms_.end();
235 }
236
237 using SimpleEpollServer::WaitForEventsAndCallHandleEvents;
238};
239
240class EpollFunctionTest : public EpollTest {
241 public:
242 EpollFunctionTest()
243 : fd_(-1), fd2_(-1), recorder_(nullptr), cb_(nullptr), ep_(nullptr) {
244 }
245
246 ~EpollFunctionTest() override {
247 delete ep_;
248 delete cb_;
249 }
250
251 void SetUp() override {
252 ep_ = new EpollTestServer();
253 cb_ = new RecordingCB();
254 // recorder_ is safe to use directly as we know it has the same scope as
255 // cb_
256 recorder_ = cb_->recorder();
257
258 int pipe_fds[2];
259 if (pipe(pipe_fds) < 0) {
260 PLOG(FATAL) << "pipe() failed";
261 }
262 fd_ = pipe_fds[0];
263 fd2_ = pipe_fds[1];
264 }
265
266 void TearDown() override {
267 close(fd_);
268 close(fd2_);
269 }
270
271 void DeleteSimpleEpollServer() {
272 delete ep_;
273 ep_ = nullptr;
274 }
275
276 int fd() { return fd_; }
277 int fd2() { return fd2_; }
278 EpollTestServer* ep() { return ep_; }
279 EpollCallbackInterface* cb() { return cb_; }
280 const Recorder* recorder() { return recorder_; }
281
282 private:
283 int fd_;
284 int fd2_;
285 const Recorder *recorder_;
286 RecordingCB* cb_;
287 EpollTestServer* ep_;
288};
289
290TEST_F(EpollFunctionTest, TestUnconnectedSocket) {
291 int fd = socket(AddressFamilyUnderTest(), SOCK_STREAM, IPPROTO_TCP);
292 ep()->RegisterFD(fd, cb(), EPOLLIN | EPOLLOUT);
293 ep()->WaitForEventsAndExecuteCallbacks();
294
295 Recorder tmp;
296 tmp.Record(cb(), CREATION, 0, 0);
297 tmp.Record(cb(), REGISTRATION, fd, EPOLLIN | EPOLLOUT);
298 tmp.Record(cb(), EVENT, fd, EPOLLOUT | EPOLLHUP);
299 EXPECT_TRUE(recorder()->IsEqual(&tmp));
300}
301
302TEST_F(EpollFunctionTest, TestRegisterFD) {
303 // Check that the basic register works.
304 ep()->RegisterFD(fd(), cb(), EPOLLIN);
305
306 // Make sure that the fd-CB mapping is there.
307 ep()->CheckMapping(fd(), cb());
308 ep()->CheckEventMask(fd(), EPOLLIN);
309
310 // Now make sure that if we register again, we stomp the old callback.
311 // Also make sure we handle O_NONBLOCK correctly
312 RecordingCB cb2;
313 ep()->RegisterFD(fd(), &cb2, EPOLLOUT | O_NONBLOCK);
314 ep()->CheckMapping(fd(), &cb2);
315 ep()->CheckEventMask(fd(), EPOLLOUT | O_NONBLOCK);
316
317 // Clean up.
318 ep()->UnregisterFD(fd());
319}
320
321TEST_F(EpollFunctionTest, TestRegisterFDForWrite) {
322 ep()->RegisterFDForWrite(fd(), cb());
323 ep()->CheckMapping(fd(), cb());
324 ep()->CheckEventMask(fd(), EPOLLOUT);
325
326 // Clean up.
327 ep()->UnregisterFD(fd());
328}
329
330TEST_F(EpollFunctionTest, TestRegisterFDForReadWrite) {
331 ep()->RegisterFDForReadWrite(fd(), cb());
332 ep()->CheckMapping(fd(), cb());
333 ep()->CheckEventMask(fd(), EPOLLIN | EPOLLOUT);
334
335 // Clean up.
336 ep()->UnregisterFD(fd());
337}
338
339TEST_F(EpollFunctionTest, TestRegisterFDForRead) {
340 ep()->RegisterFDForRead(fd(), cb());
341 ep()->CheckMapping(fd(), cb());
342 ep()->CheckEventMask(fd(), EPOLLIN);
343
344 ep()->UnregisterFD(fd());
345}
346
347TEST_F(EpollFunctionTest, TestUnregisterFD) {
348 ep()->RegisterFDForRead(fd(), cb());
349 ep()->CheckMapping(fd(), cb());
350 ep()->CheckEventMask(fd(), EPOLLIN);
351
352 // Unregister and make sure that it's gone.
353 ep()->UnregisterFD(fd());
354 ep()->CheckNotMapped(fd());
355 ep()->CheckNotRegistered(fd());
356
357 // And make sure that unregistering something a second time doesn't cause
358 // crashes.
359 ep()->UnregisterFD(fd());
360 ep()->CheckNotMapped(fd());
361 ep()->CheckNotRegistered(fd());
362}
363
364TEST_F(EpollFunctionTest, TestModifyCallback) {
365 // Check that nothing terrible happens if we modify an unregistered fd.
366 ep()->ModifyCallback(fd(), EPOLLOUT);
367 ep()->CheckNotMapped(fd());
368 ep()->CheckNotRegistered(fd());
369
370 // Check that the basic register works.
371 ep()->RegisterFD(fd(), cb(), EPOLLIN);
372 ep()->CheckMapping(fd(), cb());
373 ep()->CheckEventMask(fd(), EPOLLIN);
374
375 // Check that adding a signal swaps it out for the first.
376 ep()->ModifyCallback(fd(), EPOLLOUT);
377 ep()->CheckMapping(fd(), cb());
378 ep()->CheckEventMask(fd(), EPOLLOUT);
379
380 // Check that modifying from X to X works correctly.
381 ep()->ModifyCallback(fd(), EPOLLOUT);
382 ep()->CheckMapping(fd(), cb());
383 ep()->CheckEventMask(fd(), EPOLLOUT);
384
385 // Check that modifying from something to nothing works.
386 ep()->ModifyCallback(fd(), 0);
387 ep()->CheckMapping(fd(), cb());
388 ep()->CheckEventMask(fd(), 0);
389
390 ep()->UnregisterFD(fd());
391}
392
393TEST_F(EpollFunctionTest, TestStopRead) {
394 ep()->RegisterFDForReadWrite(fd(), cb());
395 ep()->CheckMapping(fd(), cb());
396 ep()->CheckEventMask(fd(), EPOLLIN | EPOLLOUT);
397
398 // Unregister and make sure you only lose the read event.
399 ep()->StopRead(fd());
400 ep()->CheckMapping(fd(), cb());
401 ep()->CheckEventMask(fd(), EPOLLOUT);
402
403 ep()->UnregisterFD(fd());
404}
405
406TEST_F(EpollFunctionTest, TestStartRead) {
407 ep()->RegisterFDForWrite(fd(), cb());
408 ep()->CheckMapping(fd(), cb());
409 ep()->CheckEventMask(fd(), EPOLLOUT);
410
411 // Make sure that StartRead adds EPOLLIN and doesn't remove other signals.
412 ep()->StartRead(fd());
413 ep()->CheckMapping(fd(), cb());
414 ep()->CheckEventMask(fd(), EPOLLIN | EPOLLOUT);
415
416 // Clean up.
417 ep()->UnregisterFD(fd());
418}
419
420TEST_F(EpollFunctionTest, TestStopWrite) {
421 ep()->RegisterFDForReadWrite(fd(), cb());
422 ep()->CheckMapping(fd(), cb());
423 ep()->CheckEventMask(fd(), EPOLLIN | EPOLLOUT);
424
425 // Unregister write and make sure you only lose the write event.
426 ep()->StopWrite(fd());
427 ep()->CheckMapping(fd(), cb());
428 ep()->CheckEventMask(fd(), EPOLLIN);
429
430 ep()->UnregisterFD(fd());
431}
432
433TEST_F(EpollFunctionTest, TestStartWrite) {
434 ep()->RegisterFDForRead(fd(), cb());
435 ep()->CheckMapping(fd(), cb());
436 ep()->CheckEventMask(fd(), EPOLLIN);
437
438 // Make sure that StartWrite adds EPOLLOUT and doesn't remove other
439 // signals.
440 ep()->StartWrite(fd());
441 ep()->CheckMapping(fd(), cb());
442 ep()->CheckEventMask(fd(), EPOLLIN | EPOLLOUT);
443
444 // Clean up.
445 ep()->UnregisterFD(fd());
446}
447
448TEST_F(EpollFunctionTest, TestSet_timeout_in_us) {
449 // Check that set works with various values. There's a separate test below
450 // to make sure the values are used properly.
451 ep()->set_timeout_in_us(10);
452 EXPECT_EQ(10, ep()->timeout_in_us_for_test());
453
454 ep()->set_timeout_in_us(-1);
455 EXPECT_EQ(-1, ep()->timeout_in_us_for_test());
456}
457
458TEST_F(EpollFunctionTest, TestHandleEvent) {
459 const std::vector<RecordEntry> *records = recorder()->records();
460
461 // Test that nothing bad happens if the FD is not in the map.
462 ep()->HandleEvent(fd(), EPOLLOUT);
463 ep()->CallReadyListCallbacks();
464
465 ep()->RegisterFD(fd(), cb(), 0);
466 ep()->CheckMapping(fd(), cb());
467 ep()->CheckEventMask(fd(), 0);
468
469 // At this point we should have creation and registration recorded.
470 EXPECT_EQ(2, records->size());
471
472 // Call handle event and make sure something was recorded.
473 ep()->HandleEvent(fd(), EPOLLOUT);
474 ep()->CallReadyListCallbacks();
475 EXPECT_EQ(3, records->size());
476
477 // Call handle event and make sure something was recorded.
478 ep()->HandleEvent(fd(), EPOLLIN | O_NONBLOCK);
479 ep()->CallReadyListCallbacks();
480 EXPECT_EQ(4, records->size());
481
482 Recorder tmp;
483 tmp.Record(cb(), CREATION, 0, 0);
484 tmp.Record(cb(), REGISTRATION, fd(), 0);
485 tmp.Record(cb(), EVENT, fd(), EPOLLOUT);
486 tmp.Record(cb(), EVENT, fd(), EPOLLIN | O_NONBLOCK);
487
488 EXPECT_TRUE(recorder()->IsEqual(&tmp));
489 ep()->UnregisterFD(fd());
490}
491
492TEST_F(EpollFunctionTest, TestNumFDsRegistered) {
493 EXPECT_EQ(0, ep()->NumFDsRegistered());
494
495 ep()->RegisterFD(fd(), cb(), 0);
496 EXPECT_EQ(1, ep()->NumFDsRegistered());
497
498 ep()->RegisterFD(fd2(), cb(), 0);
499 EXPECT_EQ(2, ep()->NumFDsRegistered());
500
501 ep()->RegisterFD(fd2(), cb(), 0);
502 EXPECT_EQ(2, ep()->NumFDsRegistered());
503
504 ep()->UnregisterFD(fd2());
505 EXPECT_EQ(1, ep()->NumFDsRegistered());
506
507 ep()->UnregisterFD(fd());
508 EXPECT_EQ(0, ep()->NumFDsRegistered());
509}
510
511// Check all of the individual signals and 1-2 combinations.
512TEST_F(EpollFunctionTest, TestEventMaskToString) {
513 string test;
514
515 test = SimpleEpollServer::EventMaskToString(EPOLLIN);
516 EXPECT_EQ(test, "EPOLLIN ");
517
518 test = SimpleEpollServer::EventMaskToString(EPOLLOUT);
519 EXPECT_EQ(test, "EPOLLOUT ");
520
521 test = SimpleEpollServer::EventMaskToString(EPOLLPRI);
522 EXPECT_EQ(test, "EPOLLPRI ");
523
524 test = SimpleEpollServer::EventMaskToString(EPOLLERR);
525 EXPECT_EQ(test, "EPOLLERR ");
526
527 test = SimpleEpollServer::EventMaskToString(EPOLLHUP);
528 EXPECT_EQ(test, "EPOLLHUP ");
529
530 test = SimpleEpollServer::EventMaskToString(EPOLLHUP | EPOLLIN);
531 EXPECT_EQ(test, "EPOLLIN EPOLLHUP ");
532
533 test = SimpleEpollServer::EventMaskToString(EPOLLIN | EPOLLOUT);
534 EXPECT_EQ(test, "EPOLLIN EPOLLOUT ");
535}
536
537class TestAlarm : public EpollAlarmCallbackInterface {
538 public:
539 TestAlarm()
540 : time_before_next_alarm_(-1),
541 was_called_(false),
542 num_called_(0),
543 absolute_time_(false),
544 onshutdown_called_(false),
545 has_token_(false),
546 eps_(nullptr) {
547 }
548 ~TestAlarm() override {
549 }
550 int64_t OnAlarm() override {
551 has_token_ = false;
552 was_called_ = true;
553 ++num_called_;
554 if (time_before_next_alarm_ < 0) {
555 return 0;
556 }
557 if (absolute_time_) {
558 return time_before_next_alarm_;
559 } else {
560 return WallTimeNowInUsec() + time_before_next_alarm_;
561 }
562 }
563
564 void OnShutdown(SimpleEpollServer* eps) override {
565 onshutdown_called_ = true;
566 has_token_ = false;
567 }
568 void OnRegistration(const SimpleEpollServer::AlarmRegToken& token,
569 SimpleEpollServer* eps) override {
570 has_token_ = true;
571 last_token_ = token;
572 eps_ = eps;
573 }
574 void OnUnregistration() override {
575 has_token_ = false;
576 }
577
578 void UnregisterIfRegistered(SimpleEpollServer* eps) {
579 if (has_token_) {
580 eps->UnregisterAlarm(last_token_);
581 }
582 }
583
584 void ReregisterAlarm(int64_t timeout_in_us) {
585 CHECK(has_token_);
586 eps_->ReregisterAlarm(last_token_, timeout_in_us);
587 }
588
589 void Reset() {
590 time_before_next_alarm_ = -1;
591 was_called_ = false;
592 absolute_time_ = false;
593 }
594
595 bool was_called() const { return was_called_; }
596 int num_called() const { return num_called_; }
597
598 void set_time_before_next_alarm(int64_t time) {
599 time_before_next_alarm_ = time;
600 }
601 void set_absolute_time(bool absolute) {
602 absolute_time_ = absolute;
603 }
604 bool onshutdown_called() { return onshutdown_called_; }
605
606 protected:
607 int64_t time_before_next_alarm_;
608 bool was_called_;
609 int num_called_;
610 // Is time_before_next_alarm relative to the current time or absolute?
611 bool absolute_time_;
612 bool onshutdown_called_;
613 bool has_token_;
614 SimpleEpollServer::AlarmRegToken last_token_;
615 SimpleEpollServer* eps_;
616};
617
618class TestChildAlarm;
619
620// This node unregister all other alarms when it receives
621// OnShutdown() from any one child.
622class TestParentAlarm {
623 public:
624 void OnShutdown(TestChildAlarm* child, SimpleEpollServer* eps) {
625 // Unregister
626 for (ChildTokenMap::const_iterator it = child_tokens_.begin();
627 it != child_tokens_.end(); ++it) {
628 if (it->first != child) {
629 eps->UnregisterAlarm(it->second);
630 }
631 }
632 child_tokens_.clear();
633 }
634
635 void OnRegistration(TestChildAlarm* child,
636 const SimpleEpollServer::AlarmRegToken& token) {
637 child_tokens_[child] = token;
638 }
639
640 protected:
danzh840edb62019-04-15 19:11:03 -0400641 typedef std::unordered_map<TestChildAlarm*, SimpleEpollServer::AlarmRegToken>
QUICHE team53f08a32019-04-15 14:47:31 -0400642 ChildTokenMap;
643
644 ChildTokenMap child_tokens_;
645};
646
647class TestChildAlarm : public TestAlarm {
648 public:
649 void set_parent(TestParentAlarm* tp) { parent_ = tp; }
650 void OnShutdown(SimpleEpollServer* eps) override {
651 onshutdown_called_ = true;
652 // Inform parent of shutdown
653 parent_->OnShutdown(this, eps);
654 }
655 void OnRegistration(const SimpleEpollServer::AlarmRegToken& token,
656 SimpleEpollServer* eps) override {
657 parent_->OnRegistration(this, token);
658 }
659
660 protected:
661 TestParentAlarm* parent_;
662};
663
664class TestAlarmThatRegistersAnotherAlarm : public TestAlarm {
665 public:
666 TestAlarmThatRegistersAnotherAlarm()
667 : alarm_(nullptr),
668 reg_time_delta_usec_(0),
669 eps_to_register_(nullptr),
670 has_reg_alarm_(false) {}
671 void SetRegisterAlarm(TestAlarm* alarm, int64_t time_delta_usec,
672 SimpleEpollServer* eps) {
673 alarm_ = alarm;
674 reg_time_delta_usec_ = time_delta_usec;
675 has_reg_alarm_ = true;
676 eps_to_register_ = eps;
677 }
678 int64_t OnAlarm() override {
679 if (has_reg_alarm_) {
680 eps_to_register_->RegisterAlarm(
681 eps_to_register_->ApproximateNowInUsec() + reg_time_delta_usec_,
682 alarm_);
683 has_reg_alarm_ = false;
684 }
685 return TestAlarm::OnAlarm();
686 }
687
688 protected:
689 TestAlarm* alarm_;
690 int64_t reg_time_delta_usec_;
691 SimpleEpollServer* eps_to_register_;
692 bool has_reg_alarm_;
693};
694
695class TestAlarmThatRegistersAndReregistersAnotherAlarm : public TestAlarm {
696 public:
697 TestAlarmThatRegistersAndReregistersAnotherAlarm()
698 : alarm_(nullptr),
699 reg_time_delta_usec_(0),
700 reregister_time_delta_usec_(0),
701 eps_to_register_(nullptr),
702 has_reg_alarm_(false) {}
703 void SetRegisterAndReregisterAlarm(TestAlarm* alarm, int64_t time_delta_usec,
704 int64_t reregister_delta_usec,
705 SimpleEpollServer* eps) {
706 alarm_ = alarm;
707 reg_time_delta_usec_ = time_delta_usec;
708 reregister_time_delta_usec_ = reregister_delta_usec;
709 has_reg_alarm_ = true;
710 eps_to_register_ = eps;
711 }
712 int64_t OnAlarm() override {
713 if (has_reg_alarm_) {
714 eps_to_register_->RegisterAlarm(
715 eps_to_register_->ApproximateNowInUsec() + reg_time_delta_usec_,
716 alarm_);
717 alarm_->ReregisterAlarm(eps_to_register_->ApproximateNowInUsec() +
718 reregister_time_delta_usec_);
719 has_reg_alarm_ = false;
720 }
721 return TestAlarm::OnAlarm();
722 }
723
724 protected:
725 TestAlarm* alarm_;
726 int64_t reg_time_delta_usec_;
727 int64_t reregister_time_delta_usec_;
728 SimpleEpollServer* eps_to_register_;
729 bool has_reg_alarm_;
730};
731
732class TestAlarmThatUnregistersAnotherAlarm : public TestAlarm {
733 public:
734 TestAlarmThatUnregistersAnotherAlarm()
735 : alarm_(nullptr), eps_to_register_(nullptr), has_unreg_alarm_(false) {}
736 void SetUnregisterAlarm(TestAlarm* alarm, SimpleEpollServer* eps) {
737 alarm_ = alarm;
738 has_unreg_alarm_ = true;
739 eps_to_register_ = eps;
740 }
741 int64_t OnAlarm() override {
742 if (has_unreg_alarm_) {
743 has_unreg_alarm_ = false;
744 alarm_->UnregisterIfRegistered(eps_to_register_);
745 }
746 return TestAlarm::OnAlarm();
747 }
748
749 protected:
750 TestAlarm* alarm_;
751 SimpleEpollServer* eps_to_register_;
752 bool has_unreg_alarm_;
753};
754
755class TestAlarmUnregister : public TestAlarm {
756 public:
757 TestAlarmUnregister()
758 : onunregistration_called_(false),
759 iterator_token_(nullptr) {
760 }
761 ~TestAlarmUnregister() override {
762 delete iterator_token_;
763 }
764
765 void OnShutdown(SimpleEpollServer* eps) override {
766 onshutdown_called_ = true;
767 }
768
769 int64_t OnAlarm() override {
770 delete iterator_token_;
771 iterator_token_ = nullptr;
772
773 return TestAlarm::OnAlarm();
774 }
775
776 void OnRegistration(const SimpleEpollServer::AlarmRegToken& token,
777 SimpleEpollServer* eps) override {
778 // Multiple iterator tokens are not maintained by this code,
779 // so we should have reset the iterator_token in OnAlarm or
780 // OnUnregistration.
781 CHECK(iterator_token_ == nullptr);
782 iterator_token_ = new SimpleEpollServer::AlarmRegToken(token);
783 }
784 void OnUnregistration() override {
785 delete iterator_token_;
786 iterator_token_ = nullptr;
787 // Make sure that this alarm was not already unregistered.
788 CHECK(onunregistration_called_ == false);
789 onunregistration_called_ = true;
790 }
791
792 bool onunregistration_called() { return onunregistration_called_; }
793 // Returns true if the token has been filled in with the saved iterator
794 // and false if it has not.
795 bool get_token(SimpleEpollServer::AlarmRegToken* token) {
796 if (iterator_token_ != nullptr) {
797 *token = *iterator_token_;
798 return true;
799 } else {
800 return false;
801 }
802 }
803
804 protected:
805 bool onunregistration_called_;
806 SimpleEpollServer::AlarmRegToken* iterator_token_;
807};
808
809void WaitForAlarm(SimpleEpollServer* eps, const TestAlarm& alarm) {
810 for (int i = 0; i < 5; ++i) {
811 // Ideally we would only have to call this once but it could wake up a bit
812 // early and so not call the alarm. If it wakes up early several times
813 // there is something wrong.
814 eps->WaitForEventsAndExecuteCallbacks();
815 if (alarm.was_called()) {
816 break;
817 }
818 }
819}
820
821// Check a couple of alarm times to make sure they're falling within a
822// reasonable range.
823TEST(SimpleEpollServerTest, TestAlarms) {
824 EpollTestServer ep;
825 TestAlarm alarm;
826
827 int alarm_time = 10;
828
829 // Register an alarm and make sure we wait long enough to hit it.
830 ep.set_timeout_in_us(alarm_time * 1000 * 2);
831 ep.RegisterAlarm(WallTimeNowInUsec() + alarm_time, &alarm);
832 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
833 WaitForAlarm(&ep, alarm);
834 EXPECT_TRUE(alarm.was_called());
835 EXPECT_EQ(0, ep.GetNumPendingAlarmsForTest());
836 alarm.Reset();
837
838 // Test a different time just to be careful.
839 alarm_time = 20;
840 ep.set_timeout_in_us(alarm_time * 1000 * 2);
841 ep.RegisterAlarm(WallTimeNowInUsec() + alarm_time, &alarm);
842 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
843 WaitForAlarm(&ep, alarm);
844 EXPECT_TRUE(alarm.was_called());
845 alarm.Reset();
846
847 // The alarm was a one-time thing. Make sure that we don't hit it again.
848 EXPECT_EQ(0, ep.GetNumPendingAlarmsForTest());
849 ep.WaitForEventsAndExecuteCallbacks();
850 EXPECT_FALSE(alarm.was_called());
851 alarm.Reset();
852}
853
854// Same as above, but using RegisterAlarmApproximateDelta.
855TEST(SimpleEpollServerTest, TestRegisterAlarmApproximateDelta) {
856 EpollTestServer ep;
857 TestAlarm alarm;
858
859 int alarm_time = 10;
860
861 // Register an alarm and make sure we wait long enough to hit it.
862 ep.set_timeout_in_us(alarm_time * 1000 * 2);
863 ep.RegisterAlarmApproximateDelta(alarm_time * 1000, &alarm);
864 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
865 WaitForAlarm(&ep, alarm);
866 EXPECT_TRUE(alarm.was_called());
867 EXPECT_EQ(0, ep.GetNumPendingAlarmsForTest());
868 alarm.Reset();
869 int64_t first_now = ep.ApproximateNowInUsec();
870 EXPECT_LT(0, first_now);
871
872 // Test a different time just to be careful.
873 alarm_time = 20;
874 ep.set_timeout_in_us(alarm_time * 1000 * 2);
875 ep.RegisterAlarmApproximateDelta(alarm_time * 1000, &alarm);
876 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
877 WaitForAlarm(&ep, alarm);
878 EXPECT_TRUE(alarm.was_called());
879 alarm.Reset();
880 int64_t second_now = ep.ApproximateNowInUsec();
881
882 EXPECT_LT(first_now, second_now);
883
884
885 // The alarm was a one-time thing. Make sure that we don't hit it again.
886 EXPECT_EQ(0, ep.GetNumPendingAlarmsForTest());
887 ep.WaitForEventsAndExecuteCallbacks();
888 EXPECT_FALSE(alarm.was_called());
889 alarm.Reset();
890}
891
892TEST(SimpleEpollServerTest, TestAlarmsWithInfiniteWait) {
893 EpollTestServer ep;
894 TestAlarm alarm;
895
896 int alarm_time = 10;
897
898 // Register an alarm and make sure we wait long enough to hit it.
899 ep.set_timeout_in_us(-1);
900 ep.RegisterAlarm(WallTimeNowInUsec() + alarm_time, &alarm);
901 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
902 WaitForAlarm(&ep, alarm);
903 EXPECT_TRUE(alarm.was_called());
904 EXPECT_EQ(0, ep.GetNumPendingAlarmsForTest());
905 alarm.Reset();
906}
907
908// In this test we have an alarm that when fires gets re-registered
909// at almost the same time at which it fires. Here, we want to make
910// sure that when the alarm gets re-registered we do not call OnAlarm()
911// on the same Alarm object again, until we have called
912// WaitForEventsAndExecuteCallbacks(). A poor implementation of epoll
913// server alarm handling can potentially cause OnAlarm() to be called
914// multiple times. We make sure that the epoll server is not going in
915// an infinite loop by checking that OnAlarm() is called exactly once
916// on the alarm object that got registered again.
917TEST(SimpleEpollServerTest, TestAlarmsThatGetReRegisteredAreNotCalledTwice) {
918 // This alarm would get registered again
919 TestAlarm alarm;
920 TestAlarm alarm2;
921 EpollTestServer ep;
922 ep.set_timeout_in_us(-1);
923
924 int64_t alarm_time = 10;
925 int64_t abs_time = WallTimeNowInUsec() + alarm_time * 1000;
926
927 // This will make the alarm re-register when OnAlarm is called.
928 alarm.set_absolute_time(true);
929 alarm.set_time_before_next_alarm(abs_time + 2);
930
931 // Register two alarms and make sure we wait long enough to hit it.
932 ep.RegisterAlarm(abs_time, &alarm);
933 ep.RegisterAlarm(abs_time, &alarm2);
934 EXPECT_EQ(2, ep.GetNumPendingAlarmsForTest());
935
936 WaitForAlarm(&ep, alarm);
937
938 EXPECT_TRUE(alarm.was_called());
939 // Make sure that alarm is called only once.
940 EXPECT_EQ(1, alarm.num_called());
941 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
942 alarm.Reset();
943}
944
945// Here we make sure that when one alarm unregisters another alarm
946// (that is supposed to be registered again because its OnAlarm
947// returned > 0), the alarm thats supposed to be unregistered does
948// actually gets unregistered.
949TEST(SimpleEpollServerTest, TestAlarmsOneOnAlarmUnRegistersAnotherAlarm) {
950 TestAlarm alarm;
951 TestAlarmThatUnregistersAnotherAlarm alarm2;
952 EpollTestServer ep;
953 ep.set_timeout_in_us(-1);
954
955 int64_t alarm_time = 1;
956 int64_t abs_time = WallTimeNowInUsec() + alarm_time * 1000;
957
958 // This will make the alarm re-register when OnAlarm is called.
959 alarm.set_absolute_time(true);
960 alarm.set_time_before_next_alarm(abs_time + 2);
961
962
963 // Register two alarms and make sure we wait long enough to hit it.
964 ep.RegisterAlarm(abs_time, &alarm);
965 // This would cause us to unregister alarm when OnAlarm is called
966 // on alarm2.
967 alarm2.SetUnregisterAlarm(&alarm, &ep);
968 ep.RegisterAlarm(abs_time + 1, &alarm2);
969 EXPECT_EQ(2, ep.GetNumPendingAlarmsForTest());
970
971 WaitForAlarm(&ep, alarm);
972
973 EXPECT_TRUE(alarm.was_called());
974 // Make sure that alarm is called only once.
975 EXPECT_EQ(1, alarm.num_called());
976 EXPECT_EQ(0, ep.GetNumPendingAlarmsForTest());
977 alarm.Reset();
978}
979
980// Check a couple of alarm times to make sure they're falling within a
981// reasonable range.
982TEST(SimpleEpollServerTest, TestRepeatAlarms) {
983 EpollTestServer ep;
984 TestAlarm alarm;
985
986 int alarm_time = 20;
987
988 // Register an alarm and make sure we wait long enough to hit it.
989 ep.set_timeout_in_us(alarm_time * 1000 * 2);
990 alarm.set_time_before_next_alarm(1000*alarm_time);
991 ep.RegisterAlarm(WallTimeNowInUsec() + alarm_time, &alarm);
992 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
993
994 WaitForAlarm(&ep, alarm);
995 // When we wake up it should be because the Alarm has been called, and has
996 // registered itself to be called again.
997
998 // Make sure the first alarm was called properly.
999 EXPECT_TRUE(alarm.was_called());
1000
1001 // Resetting means that the alarm is no longer a recurring alarm. It will be
1002 // called once more and then stop.
1003 alarm.Reset();
1004
1005 // Make sure the alarm is called one final time.
1006 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
1007 ep.set_timeout_in_us(alarm_time * 1000 * 2);
1008 WaitForAlarm(&ep, alarm);
1009
1010 EXPECT_TRUE(alarm.was_called());
1011 alarm.Reset();
1012
1013 // The alarm was a one-time thing. Make sure that we don't hit it again.
1014 EXPECT_EQ(0, ep.GetNumPendingAlarmsForTest());
1015 ep.WaitForEventsAndExecuteCallbacks();
1016 EXPECT_FALSE(alarm.was_called());
1017}
1018
1019// Verify that an alarm that repeats itself in the past works properly.
1020TEST(SimpleEpollServerTest, TestRepeatAlarmInPast) {
1021 EpollTestServer ep;
1022 TestAlarm alarm;
1023
1024 int64_t alarm_time = 20;
1025 int64_t abs_time = WallTimeNowInUsec() + alarm_time * 1000;
1026
1027 // Make the alarm re-register in the past when OnAlarm is called.
1028 alarm.set_absolute_time(true);
1029 alarm.set_time_before_next_alarm(abs_time - 1000);
1030
1031 // Register the alarm and make sure we wait long enough to hit it.
1032 ep.set_timeout_in_us(alarm_time * 1000 * 2);
1033 ep.RegisterAlarm(abs_time, &alarm);
1034 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
1035
1036 WaitForAlarm(&ep, alarm);
1037 // When we wake up it should be because the Alarm has been called, and has
1038 // registered itself to be called again.
1039
1040 // Make sure the first alarm was called properly.
1041 EXPECT_TRUE(alarm.was_called());
1042
1043 // Resetting means that the alarm is no longer a recurring alarm. It will be
1044 // called once more and then stop.
1045 alarm.Reset();
1046
1047 // Make sure the alarm is called one final time.
1048 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
1049 ep.set_timeout_in_us(alarm_time * 1000 * 2);
1050 WaitForAlarm(&ep, alarm);
1051
1052 EXPECT_TRUE(alarm.was_called());
1053 alarm.Reset();
1054
1055 // The alarm was a one-time thing. Make sure that we don't hit it again.
1056 EXPECT_EQ(0, ep.GetNumPendingAlarmsForTest());
1057 ep.WaitForEventsAndExecuteCallbacks();
1058 EXPECT_FALSE(alarm.was_called());
1059}
1060
1061class EpollTestAlarms : public SimpleEpollServer {
1062 public:
1063 EpollTestAlarms() : SimpleEpollServer() {}
1064
1065 inline int64_t NowInUsec() const override { return time_; }
1066
1067 void CallAndReregisterAlarmEvents() override {
1068 recorded_now_in_us_ = NowInUsec();
1069 SimpleEpollServer::CallAndReregisterAlarmEvents();
1070 }
1071
1072 void set_time(int64_t time) { time_ = time; }
1073
1074 size_t GetNumPendingAlarmsForTest() const { return alarm_map_.size(); }
1075
1076 private:
1077 int64_t time_;
1078};
1079
1080// Test multiple interleaving alarms to make sure they work right.
1081// Pattern is roughly:
1082// time: 15 20 30 40
1083// alarm: A B A' C
1084TEST(SimpleEpollServerTest, TestMultipleAlarms) {
1085 EpollTestAlarms ep;
1086 TestAlarm alarmA;
1087 TestAlarm alarmB;
1088 TestAlarm alarmC;
1089
1090 ep.set_timeout_in_us(50 * 1000 * 2);
1091 alarmA.set_time_before_next_alarm(1000 * 30);
1092 alarmA.set_absolute_time(true);
1093 ep.RegisterAlarm(15 * 1000, &alarmA);
1094 ep.RegisterAlarm(20 * 1000, &alarmB);
1095 ep.RegisterAlarm(40 * 1000, &alarmC);
1096
1097 ep.set_time(15 * 1000);
1098 ep.CallAndReregisterAlarmEvents(); // A
1099 EXPECT_TRUE(alarmA.was_called());
1100 EXPECT_FALSE(alarmB.was_called());
1101 EXPECT_FALSE(alarmC.was_called());
1102 alarmA.Reset(); // Unregister A in the future.
1103
1104 ep.set_time(20 * 1000);
1105 ep.CallAndReregisterAlarmEvents(); // B
1106 EXPECT_FALSE(alarmA.was_called());
1107 EXPECT_TRUE(alarmB.was_called());
1108 EXPECT_FALSE(alarmC.was_called());
1109 alarmB.Reset();
1110
1111 ep.set_time(30 * 1000);
1112 ep.CallAndReregisterAlarmEvents(); // A
1113 EXPECT_TRUE(alarmA.was_called());
1114 EXPECT_FALSE(alarmB.was_called());
1115 EXPECT_FALSE(alarmC.was_called());
1116 alarmA.Reset();
1117
1118 ep.set_time(40 * 1000);
1119 ep.CallAndReregisterAlarmEvents(); // C
1120 EXPECT_FALSE(alarmA.was_called());
1121 EXPECT_FALSE(alarmB.was_called());
1122 EXPECT_TRUE(alarmC.was_called());
1123 alarmC.Reset();
1124
1125 ep.CallAndReregisterAlarmEvents(); // None.
1126 EXPECT_FALSE(alarmA.was_called());
1127 EXPECT_FALSE(alarmB.was_called());
1128 EXPECT_FALSE(alarmC.was_called());
1129}
1130
1131TEST(SimpleEpollServerTest, TestAlarmOnShutdown) {
1132 TestAlarm alarm1;
1133 {
1134 EpollTestServer ep;
1135 const int64_t now = WallTimeNowInUsec();
1136 ep.RegisterAlarm(now + 5000, &alarm1);
1137 }
1138
1139 EXPECT_TRUE(alarm1.onshutdown_called());
1140}
1141
1142// Tests that if we have multiple alarms
1143// OnShutdown then we handle them properly.
1144TEST(SimpleEpollServerTest, TestMultipleAlarmOnShutdown) {
1145 TestAlarm alarm1;
1146 TestAlarm alarm2;
1147 TestAlarm alarm3;
1148 {
1149 EpollTestServer ep;
1150 const int64_t now = WallTimeNowInUsec();
1151 ep.RegisterAlarm(now + 5000, &alarm1);
1152 ep.RegisterAlarm(now + 9000, &alarm2);
1153 ep.RegisterAlarm(now + 9000, &alarm3);
1154 }
1155
1156 EXPECT_TRUE(alarm1.onshutdown_called());
1157 EXPECT_TRUE(alarm2.onshutdown_called());
1158 EXPECT_TRUE(alarm3.onshutdown_called());
1159}
1160TEST(SimpleEpollServerTest, TestMultipleAlarmUnregistrationOnShutdown) {
1161 TestParentAlarm tp;
1162 TestChildAlarm alarm1;
1163 TestChildAlarm alarm2;
1164 alarm1.set_parent(&tp);
1165 alarm2.set_parent(&tp);
1166 {
1167 EpollTestServer ep;
1168 const int64_t now = WallTimeNowInUsec();
1169 ep.RegisterAlarm(now + 5000, &alarm1);
1170 ep.RegisterAlarm(now + 9000, &alarm2);
1171 }
1172
1173 EXPECT_TRUE(alarm1.onshutdown_called());
1174 EXPECT_FALSE(alarm2.onshutdown_called());
1175}
1176
1177// Check an alarm set in the past runs right away.
1178TEST(SimpleEpollServerTest, TestPastAlarm) {
1179 EpollTestServer ep;
1180 TestAlarm alarm;
1181
1182 // Register the alarm and make sure we wait long enough to hit it.
1183 ep.set_timeout_in_us(1000 * 2);
1184 ep.RegisterAlarm(WallTimeNowInUsec() - 1000, &alarm);
1185 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
1186 ep.WaitForEventsAndExecuteCallbacks();
1187 EXPECT_TRUE(alarm.was_called());
1188 EXPECT_EQ(0, ep.GetNumPendingAlarmsForTest());
1189 alarm.Reset();
1190}
1191
1192// Test Unregistering of Alarms
1193TEST(SimpleEpollServerTest, TestUnregisterAlarm) {
1194 EpollTestServer ep;
1195 SimpleEpollServer::AlarmRegToken temptok;
1196
1197 TestAlarmUnregister alarm1;
1198 TestAlarmUnregister alarm2;
1199
1200 ep.RegisterAlarm(WallTimeNowInUsec() + 5 * 1000, &alarm1);
1201 ep.RegisterAlarm(WallTimeNowInUsec() + 13 * 1000, &alarm2);
1202
1203 // Unregister an alarm.
1204 if (alarm2.get_token(&temptok)) {
1205 ep.UnregisterAlarm(temptok);
1206 }
1207 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
1208 EXPECT_TRUE(alarm2.onunregistration_called());
1209
1210 if (alarm1.get_token(&temptok)) {
1211 ep.UnregisterAlarm(temptok);
1212 }
1213 EXPECT_EQ(0, ep.GetNumPendingAlarmsForTest());
1214 EXPECT_TRUE(alarm1.onunregistration_called());
1215}
1216
1217// Test Reregistering of Alarms
1218TEST(SimpleEpollServerTest, TestReregisterAlarm) {
1219 EpollTestAlarms ep;
1220 SimpleEpollServer::AlarmRegToken token;
1221
1222 TestAlarmUnregister alarm;
1223 ep.set_time(1000);
1224 ep.RegisterAlarm(5000, &alarm);
1225
1226 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
1227 ASSERT_TRUE(alarm.get_token(&token));
1228 ep.ReregisterAlarm(token, 6000);
1229 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
1230
1231 ep.set_time(5000);
1232 ep.set_timeout_in_us(0);
1233 ep.CallAndReregisterAlarmEvents();
1234 EXPECT_FALSE(alarm.was_called());
1235
1236 ep.set_time(6000);
1237 ep.CallAndReregisterAlarmEvents();
1238 EXPECT_TRUE(alarm.was_called());
1239}
1240
1241TEST(SimpleEpollServerTest, TestReregisterDeferredAlarm) {
1242 EpollTestAlarms ep;
1243 ep.set_timeout_in_us(0);
1244
1245 TestAlarm alarm;
1246 TestAlarmThatRegistersAndReregistersAnotherAlarm register_alarm;
1247 // Register the alarm in the past so it is added as a deferred alarm.
1248 register_alarm.SetRegisterAndReregisterAlarm(&alarm, -500, 500, &ep);
1249 ep.set_time(1000);
1250 ep.RegisterAlarm(1000, &register_alarm);
1251 // Call reregister twice, first to run register_alarm and second to run any
1252 // scheduled deferred alarms.
1253 ep.CallAndReregisterAlarmEvents();
1254 ep.CallAndReregisterAlarmEvents();
1255
1256 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
1257 EXPECT_FALSE(alarm.was_called());
1258
1259 ep.set_time(1500);
1260 ep.CallAndReregisterAlarmEvents();
1261 EXPECT_TRUE(alarm.was_called());
1262}
1263
1264// Check if an alarm fired and got reregistered, you are able to
1265// unregister the second registration.
1266TEST(SimpleEpollServerTest, TestFiredReregisteredAlarm) {
1267 EpollTestAlarms ep;
1268 TestAlarmUnregister alarmA;
1269
1270 SimpleEpollServer::AlarmRegToken first_token;
1271 SimpleEpollServer::AlarmRegToken second_token;
1272 bool found;
1273
1274 ep.set_timeout_in_us(50 * 1000 * 2);
1275 alarmA.set_time_before_next_alarm(1000 * 30);
1276 alarmA.set_absolute_time(true);
1277
1278// Alarm A first fires at 15, then 30
1279 ep.RegisterAlarm(15 * 1000, &alarmA);
1280
1281 found = alarmA.get_token(&first_token);
1282 EXPECT_TRUE(found);
1283
1284 ep.set_time(15 * 1000);
1285 ep.CallAndReregisterAlarmEvents(); // A
1286 EXPECT_TRUE(alarmA.was_called());
1287
1288 alarmA.Reset();
1289
1290 found = alarmA.get_token(&second_token);
1291 EXPECT_TRUE(found);
1292 if (found) {
1293 ep.UnregisterAlarm(second_token);
1294 }
1295
1296 ep.set_time(30 * 1000);
1297 ep.CallAndReregisterAlarmEvents(); // A
1298
1299 alarmA.Reset();
1300}
1301
1302// Here we make sure that one alarm can unregister another alarm
1303// in OnShutdown().
1304TEST(SimpleEpollServerTest, TestAlarmCanUnregistersAnotherAlarmOnShutdown) {
1305 TestAlarmThatUnregistersAnotherAlarm alarm1;
1306 TestAlarm alarm2;
1307 {
1308 EpollTestServer ep;
1309 // Register two alarms and make alarm1 is placed in queue in front of alarm2
1310 // so that when the queue is cleared, alarm1 is processed first.
1311 const int64_t now = WallTimeNowInUsec();
1312 ep.RegisterAlarm(now + 5000, &alarm1);
1313 ep.RegisterAlarm(now + 9000, &alarm2);
1314 alarm1.SetUnregisterAlarm(&alarm2, &ep);
1315 EXPECT_EQ(2, ep.GetNumPendingAlarmsForTest());
1316 }
1317}
1318
1319class TestAlarmRegisterAnotherAlarmShutdown : public TestAlarmUnregister {
1320 public:
1321 TestAlarmRegisterAnotherAlarmShutdown(EpollAlarmCallbackInterface* alarm2,
1322 int64_t when)
1323 : alarm2_(alarm2), when_(when) {}
1324 void OnShutdown(SimpleEpollServer* eps) override {
1325 TestAlarmUnregister::OnShutdown(eps);
1326 eps->RegisterAlarm(when_, alarm2_);
1327 }
1328
1329 private:
1330 EpollAlarmCallbackInterface* alarm2_;
1331 int64_t when_;
1332};
1333
1334// This tests that alarm registers another alarm when shutting down.
1335// The two cases are: new alarm comes before and after the alarm being
1336// notified by OnShutdown()
1337TEST(SimpleEpollServerTest, AlarmRegistersAnotherAlarmOnShutdownBeforeSelf) {
1338 TestAlarm alarm2;
1339 int64_t alarm_time = WallTimeNowInUsec() + 5000;
1340 TestAlarmRegisterAnotherAlarmShutdown alarm1(&alarm2, alarm_time - 1000);
1341 {
1342 EpollTestAlarms ep;
1343 ep.RegisterAlarm(alarm_time, &alarm1);
1344 }
1345 EXPECT_TRUE(alarm1.onshutdown_called());
1346 EXPECT_FALSE(alarm2.onshutdown_called());
1347}
1348
1349TEST(SimpleEpollServerTest, AlarmRegistersAnotherAlarmOnShutdownAfterSelf) {
1350 TestAlarm alarm2;
1351 int64_t alarm_time = WallTimeNowInUsec() + 5000;
1352 TestAlarmRegisterAnotherAlarmShutdown alarm1(&alarm2, alarm_time + 1000);
1353 {
1354 EpollTestAlarms ep;
1355 ep.RegisterAlarm(alarm_time, &alarm1);
1356 }
1357 EXPECT_TRUE(alarm1.onshutdown_called());
1358 EXPECT_TRUE(alarm2.onshutdown_called());
1359}
1360
1361TEST(SimpleEpollServerTest, TestWrite) {
1362 SimpleEpollServer ep;
1363 ep.set_timeout_in_us(1);
1364 char data[kPageSize] = {0};
1365
1366 int pipe_fds[2];
1367 if (pipe(pipe_fds) < 0) {
1368 EPOLL_PLOG(FATAL) << "pipe() failed";
1369 }
1370 int read_fd = pipe_fds[0];
1371 int write_fd = pipe_fds[1];
1372
1373 RecordingCB recording_cb;
1374 const Recorder* recorder = recording_cb.recorder();
1375 const std::vector<RecordEntry> *records = recorder->records();
1376
1377 // Register to listen to write events.
1378 ep.RegisterFD(write_fd, &recording_cb, EPOLLOUT | O_NONBLOCK);
1379 // At this point the recorder should have the creation and registration
1380 // events.
1381 EXPECT_EQ(2, records->size());
1382
1383 // Fill up the pipe.
1384 int written = 1;
1385 for (int i = 0; i < 17 && written > 0 ; ++i) {
1386 written = write(write_fd, &data, kPageSize);
1387 }
1388 EXPECT_LT(written, 0);
1389
1390 // There should be no new events as the pipe is not available for writing.
1391 ep.WaitForEventsAndExecuteCallbacks();
1392 EXPECT_EQ(2, records->size());
1393
1394 // Now read data from the pipe to make it writable again. This time the
1395 // we should get an EPOLLOUT event.
1396 int size = read(read_fd, &data, kPageSize);
1397 EXPECT_EQ(kPageSize, size);
1398 ep.WaitForEventsAndExecuteCallbacks();
1399 EXPECT_EQ(3, records->size());
1400
1401 // Now unsubscribe from writable events (which adds a modification record)
1402 // and wait to verify that no event records are added.
1403 ep.StopWrite(write_fd);
1404 ep.WaitForEventsAndExecuteCallbacks();
1405 EXPECT_EQ(4, records->size());
1406
1407 // We had the right number of events all along. Make sure they were actually
1408 // the right events.
1409 Recorder tmp;
1410 tmp.Record(&recording_cb, CREATION, 0, 0);
1411 tmp.Record(&recording_cb, REGISTRATION, write_fd, EPOLLOUT | O_NONBLOCK);
1412 tmp.Record(&recording_cb, EVENT, write_fd, EPOLLOUT);
1413 tmp.Record(&recording_cb, MODIFICATION, write_fd, O_NONBLOCK);
1414
1415 EXPECT_TRUE(recorder->IsEqual(&tmp));
1416 ep.UnregisterFD(write_fd);
1417
1418 close(read_fd);
1419 close(write_fd);
1420}
1421
1422TEST(SimpleEpollServerTest, TestReadWrite) {
1423 SimpleEpollServer ep;
1424 ep.set_timeout_in_us(1);
1425 char data[kPageSize] = {0};
1426
1427 int pipe_fds[2];
1428 if (pipe(pipe_fds) < 0) {
1429 EPOLL_PLOG(FATAL) << "pipe() failed";
1430 }
1431 int read_fd = pipe_fds[0];
1432 int write_fd = pipe_fds[1];
1433
1434 RecordingCB recording_cb;
1435 const Recorder* recorder = recording_cb.recorder();
1436 const std::vector<RecordEntry> *records = recorder->records();
1437
1438 // Register to listen to read and write events.
1439 ep.RegisterFDForReadWrite(read_fd, &recording_cb);
1440 // At this point the recorder should have the creation and registration
1441 // events.
1442 EXPECT_EQ(2, records->size());
1443
1444 int written = write(write_fd, &data, kPageSize);
1445 EXPECT_EQ(kPageSize, written);
1446
1447 ep.WaitForEventsAndExecuteCallbacks();
1448 ep.UnregisterFD(read_fd);
1449
1450 close(read_fd);
1451 close(write_fd);
1452}
1453
1454TEST(SimpleEpollServerTest, TestMultipleFDs) {
1455 SimpleEpollServer ep;
1456 ep.set_timeout_in_us(1);
1457 char data = 'x';
1458
1459 int pipe_one[2];
1460 if (pipe(pipe_one) < 0) {
1461 EPOLL_PLOG(FATAL) << "pipe() failed";
1462 }
1463 int pipe_two[2];
1464 if (pipe(pipe_two) < 0) {
1465 EPOLL_PLOG(FATAL) << "pipe() failed";
1466 }
1467
1468 RecordingCB recording_cb_one;
1469 const Recorder* recorder_one = recording_cb_one.recorder();
1470 const std::vector<RecordEntry> *records_one = recorder_one->records();
1471
1472 RecordingCB recording_cb_two;
1473 const Recorder* recorder_two = recording_cb_two.recorder();
1474 const std::vector<RecordEntry> *records_two = recorder_two->records();
1475
1476 // Register to listen to read events for both pipes
1477 ep.RegisterFDForRead(pipe_one[0], &recording_cb_one);
1478 ep.RegisterFDForRead(pipe_two[0], &recording_cb_two);
1479
1480
1481 EXPECT_EQ(2, records_one->size());
1482 EXPECT_EQ(2, records_two->size());
1483
1484 write(pipe_one[1], &data, 1);
1485 ep.WaitForEventsAndExecuteCallbacks();
1486 EXPECT_EQ(3, records_one->size());
1487 EXPECT_EQ(2, records_two->size());
1488
1489
1490 write(pipe_two[1], &data, 1);
1491 ep.WaitForEventsAndExecuteCallbacks();
1492 EXPECT_EQ(3, records_one->size());
1493 EXPECT_EQ(3, records_two->size());
1494
1495 write(pipe_one[1], &data, 1);
1496 write(pipe_two[1], &data, 1);
1497 ep.WaitForEventsAndExecuteCallbacks();
1498 EXPECT_EQ(4, records_one->size());
1499 EXPECT_EQ(4, records_two->size());
1500
1501 ep.WaitForEventsAndExecuteCallbacks();
1502 ep.UnregisterFD(pipe_one[0]);
1503 ep.UnregisterFD(pipe_two[0]);
1504 close(pipe_one[0]);
1505 close(pipe_one[1]);
1506 close(pipe_two[0]);
1507 close(pipe_two[1]);
1508}
1509
1510// Check that the SimpleEpollServer calls OnShutdown for any registered FDs.
1511TEST(SimpleEpollServerTest, TestFDOnShutdown) {
1512 int pipe_fds[2];
1513 if (pipe(pipe_fds) < 0) {
1514 EPOLL_PLOG(FATAL) << "pipe() failed";
1515 }
1516 int read_fd = pipe_fds[0];
1517 int write_fd = pipe_fds[1];
1518
1519 RecordingCB recording_cb1;
1520 RecordingCB recording_cb2;
1521 const Recorder* recorder1 = recording_cb1.recorder();
1522 const Recorder* recorder2 = recording_cb2.recorder();
1523
1524 {
1525 SimpleEpollServer ep;
1526 ep.set_timeout_in_us(1);
1527
1528 // Register to listen to write events.
1529 ep.RegisterFD(write_fd, &recording_cb1, EPOLLOUT | O_NONBLOCK);
1530 ep.RegisterFD(read_fd, &recording_cb2, EPOLLIN | O_NONBLOCK);
1531 }
1532
1533 // Make sure OnShutdown was called for both callbacks.
1534 Recorder write_recorder;
1535 write_recorder.Record(&recording_cb1, CREATION, 0, 0);
1536 write_recorder.Record(
1537 &recording_cb1, REGISTRATION, write_fd, EPOLLOUT | O_NONBLOCK);
1538 write_recorder.Record(&recording_cb1, UNREGISTRATION, write_fd, false);
1539 write_recorder.Record(&recording_cb1, SHUTDOWN, write_fd, 0);
1540 EXPECT_TRUE(recorder1->IsEqual(&write_recorder));
1541
1542 Recorder read_recorder;
1543 read_recorder.Record(&recording_cb2, CREATION, 0, 0);
1544 read_recorder.Record(
1545 &recording_cb2, REGISTRATION, read_fd, EPOLLIN | O_NONBLOCK);
1546 read_recorder.Record(&recording_cb2, UNREGISTRATION, read_fd, false);
1547 read_recorder.Record(&recording_cb2, SHUTDOWN, read_fd, 0);
1548 EXPECT_TRUE(recorder2->IsEqual(&read_recorder));
1549
1550 close(read_fd);
1551 close(write_fd);
1552}
1553
1554class UnregisterCB : public EpollCallbackInterface {
1555 public:
1556 explicit UnregisterCB(int fd)
1557 : eps_(nullptr), fd_(fd), onshutdown_called_(false) {
1558 }
1559
1560 ~UnregisterCB() override {
1561 }
1562
1563 void OnShutdown(SimpleEpollServer* eps, int fd) override {
1564 eps_->UnregisterFD(fd_);
1565 eps_->UnregisterFD(fd);
1566 onshutdown_called_ = true;
1567 eps_ = nullptr;
1568 }
1569
1570 void set_epollserver(SimpleEpollServer* eps) { eps_ = eps; }
1571 bool onshutdown_called() { return onshutdown_called_; }
1572
1573 void OnRegistration(SimpleEpollServer* eps, int fd, int event_mask) override {
1574 }
1575 void OnModification(int fd, int event_mask) override {}
1576 void OnEvent(int fd, EpollEvent* event) override {}
1577 void OnUnregistration(int fd, bool replaced) override {}
1578
1579 string Name() const override { return "UnregisterCB"; }
1580
1581 protected:
1582 SimpleEpollServer* eps_;
1583 int fd_;
1584 bool onshutdown_called_;
1585};
1586
1587// Check that unregistering fds in OnShutdown works cleanly.
1588TEST(SimpleEpollServerTest, TestUnregisteringFDsOnShutdown) {
1589 int pipe_fds[2];
1590 if (pipe(pipe_fds) < 0) {
1591 EPOLL_PLOG(FATAL) << "pipe() failed";
1592 }
1593 int read_fd = pipe_fds[0];
1594 int write_fd = pipe_fds[1];
1595
1596 UnregisterCB unreg_cb1(read_fd);
1597 UnregisterCB unreg_cb2(write_fd);
1598
1599 {
1600 SimpleEpollServer ep;
1601 ep.set_timeout_in_us(1);
1602
1603 unreg_cb1.set_epollserver(&ep);
1604 unreg_cb2.set_epollserver(&ep);
1605
1606 // Register to listen to write events.
1607 ep.RegisterFD(write_fd, &unreg_cb1, EPOLLOUT | O_NONBLOCK);
1608 ep.RegisterFD(read_fd, &unreg_cb2, EPOLLIN | O_NONBLOCK);
1609 }
1610
1611 // Make sure at least one onshutdown was called.
1612 EXPECT_TRUE(unreg_cb1.onshutdown_called() ||
1613 unreg_cb2.onshutdown_called());
1614 // Make sure that both onshutdowns were not called.
1615 EXPECT_TRUE(!(unreg_cb1.onshutdown_called() &&
1616 unreg_cb2.onshutdown_called()));
1617
1618 close(read_fd);
1619 close(write_fd);
1620}
1621
1622TEST(SimpleEpollServerTest, TestFDsAndAlarms) {
1623 SimpleEpollServer ep;
1624 ep.set_timeout_in_us(5);
1625 char data = 'x';
1626
1627 int pipe_fds[2];
1628 if (pipe(pipe_fds) < 0) {
1629 EPOLL_PLOG(FATAL) << "pipe() failed";
1630 }
1631
1632 RecordingCB recording_cb;
1633 const Recorder* recorder = recording_cb.recorder();
1634 const std::vector<RecordEntry> *records = recorder->records();
1635
1636 TestAlarm alarm;
1637
1638 ep.RegisterFDForRead(pipe_fds[0], &recording_cb);
1639
1640 EXPECT_EQ(2, records->size());
1641 EXPECT_FALSE(alarm.was_called());
1642
1643 // Write to the pipe and set a longish alarm so we get a read event followed
1644 // by an alarm event.
1645 int written = write(pipe_fds[1], &data, 1);
1646 EXPECT_EQ(1, written);
1647 ep.WaitForEventsAndExecuteCallbacks();
1648 EXPECT_EQ(3, records->size());
1649 EXPECT_FALSE(alarm.was_called());
1650 ep.RegisterAlarm(WallTimeNowInUsec() + 1000, &alarm);
1651 WaitForAlarm(&ep, alarm);
1652 EXPECT_EQ(3, records->size());
1653 EXPECT_TRUE(alarm.was_called());
1654 alarm.Reset();
1655
1656 // Now set a short alarm so the alarm and the read event are called together.
1657 ep.RegisterAlarm(WallTimeNowInUsec(), &alarm);
1658 written = write(pipe_fds[1], &data, 1);
1659 EXPECT_EQ(1, written);
1660 ep.WaitForEventsAndExecuteCallbacks();
1661 EXPECT_TRUE(alarm.was_called());
1662 EXPECT_EQ(4, records->size());
1663
1664 ep.UnregisterFD(pipe_fds[0]);
1665
1666 close(pipe_fds[0]);
1667 close(pipe_fds[1]);
1668}
1669
1670class EpollReader: public EpollCallbackInterface {
1671 public:
1672 explicit EpollReader(int len)
1673 : len_(0),
1674 expected_len_(len),
1675 done_reading_(false) {
1676 memset(&buf_, 0, kMaxBufLen);
1677 }
1678
1679 ~EpollReader() override {}
1680
1681 void OnRegistration(SimpleEpollServer* eps, int fd, int event_mask) override {
1682 }
1683
1684 void OnModification(int fd, int event_mask) override {}
1685
1686 void OnEvent(int fd, EpollEvent* event) override {
1687 if (event->in_events & EPOLLIN) {
1688 len_ += read(fd, &buf_ + len_, kMaxBufLen - len_);
1689 }
1690
1691 // If we have finished reading...
1692 if (event->in_events & EPOLLHUP) {
1693 CHECK_EQ(len_, expected_len_);
1694 done_reading_ = true;
1695 }
1696 }
1697
1698 void OnUnregistration(int fd, bool replaced) override {}
1699
1700 void OnShutdown(SimpleEpollServer* eps, int fd) override {
1701 // None of the current tests involve having active callbacks when the
1702 // server shuts down.
1703 EPOLL_LOG(FATAL);
1704 }
1705
1706 string Name() const override { return "EpollReader"; }
1707
1708 // Returns true if the data in buf is the same as buf_, false otherwise.
1709 bool CheckOutput(char* buf, int len) {
1710 if (len != len_) {
1711 return false;
1712 }
1713 return !memcmp(buf, buf_, len);
1714 }
1715
1716 bool done_reading() { return done_reading_; }
1717
1718 protected:
1719 int len_;
1720 int expected_len_;
1721 char buf_[kMaxBufLen];
1722 bool done_reading_;
1723};
1724
1725void TestPipe(char *test_message, int len) {
1726 int pipe_fds[2];
1727 if (pipe(pipe_fds) < 0) {
1728 PLOG(FATAL) << "pipe failed()";
1729 }
1730 int reader_pipe = pipe_fds[0];
1731 int writer_pipe = pipe_fds[1];
1732 int child_pid;
1733 memset(test_message, 'x', len);
1734
1735 switch (child_pid = fork()) {
1736 case 0: { // Child will send message.
1737 const char *message = test_message;
1738 int size;
1739 close(reader_pipe);
1740 while ((size = write(writer_pipe, message, len)) > 0) {
1741 message += size;
1742 len -= size;
1743 if (len == 0) {
1744 break;
1745 }
1746 }
1747 if (len > 0) {
1748 PLOG(FATAL) << "write() failed";
1749 }
1750 close(writer_pipe);
1751
1752 _exit(0);
1753 }
1754 case -1:
1755 PLOG(FATAL) << "fork() failed";
1756 break;
1757 default: { // Parent will receive message.
1758 close(writer_pipe);
1759 auto ep = absl::make_unique<SimpleEpollServer>();
1760 ep->set_timeout_in_us(1);
1761 EpollReader reader(len);
1762 ep->RegisterFD(reader_pipe, &reader, EPOLLIN);
1763
1764 int64_t start_ms = WallTimeNowInUsec() / 1000;
1765 // Loop until we're either done reading, or have waited ~10 us.
1766 while (!reader.done_reading() &&
1767 (WallTimeNowInUsec() / 1000 - start_ms) < 10000) {
1768 ep->WaitForEventsAndExecuteCallbacks();
1769 }
1770 ep->UnregisterFD(reader_pipe);
1771 CHECK(reader.CheckOutput(test_message, len));
1772 break;
1773 }
1774 }
1775
1776 close(reader_pipe);
1777 close(writer_pipe);
1778}
1779
1780TEST(SimpleEpollServerTest, TestSmallPipe) {
1781 char buf[kMaxBufLen];
1782 TestPipe(buf, 10);
1783}
1784
1785TEST(SimpleEpollServerTest, TestLargePipe) {
1786 char buf[kMaxBufLen];
1787 TestPipe(buf, kMaxBufLen);
1788}
1789
1790// Tests RegisterFDForRead as well as StopRead.
1791TEST(SimpleEpollServerTest, TestRead) {
1792 SimpleEpollServer ep;
1793 ep.set_timeout_in_us(1);
1794 int len = 1;
1795
1796 int pipe_fds[2];
1797 if (pipe(pipe_fds) < 0) {
1798 EPOLL_PLOG(FATAL) << "pipe() failed";
1799 }
1800 int read_fd = pipe_fds[0];
1801 int write_fd = pipe_fds[1];
1802
1803 auto reader = absl::make_unique<EpollReader>(len);
1804
1805 // Check that registering a FD for read alerts us when there is data to be
1806 // read.
1807 ep.RegisterFDForRead(read_fd, reader.get());
1808 char data = 'a';
1809 int size = write(write_fd, &data, 1);
1810 EXPECT_EQ(1, size);
1811 ep.WaitForEventsAndExecuteCallbacks();
1812 EXPECT_TRUE(reader->CheckOutput(&data, len));
1813
1814 // Remove the callback for read events, write to the pipe and make sure that
1815 // we did not read more data.
1816 ep.StopRead(read_fd);
1817 size = write(write_fd, &data, len);
1818 EXPECT_EQ(1, size);
1819 // The wait will return after timeout.
1820 ep.WaitForEventsAndExecuteCallbacks();
1821 EXPECT_TRUE(reader->CheckOutput(&data, len));
1822 ep.UnregisterFD(read_fd);
1823
1824 close(read_fd);
1825 close(write_fd);
1826}
1827
1828class EdgeTriggerCB : public EpollCallbackInterface {
1829 public:
1830 EdgeTriggerCB(int read_size, int write_size, char write_char, char peer_char)
1831 : eps_(nullptr),
1832 read_buf_(read_size),
1833 write_buf_(write_size, write_char),
1834 peer_char_(peer_char) {
1835 Reset();
1836 }
1837
1838 ~EdgeTriggerCB() override {}
1839
1840 void Reset() {
1841 CHECK(eps_ == nullptr);
1842 bytes_read_ = 0;
1843 bytes_written_ = 0;
1844 can_read_ = false;
1845 will_read_ = false;
1846 can_write_ = false;
1847 will_write_ = false;
1848 read_closed_ = false;
1849 write_closed_ = false;
1850 }
1851
1852 void ResetByteCounts() {
1853 bytes_read_ = bytes_written_ = 0;
1854 }
1855
1856 void set_will_read(bool will_read) { will_read_ = will_read; }
1857
1858 void set_will_write(bool will_write) { will_write_ = will_write; }
1859
1860 bool can_write() const { return can_write_; }
1861
1862 int bytes_read() const { return bytes_read_; }
1863
1864 int bytes_written() const { return bytes_written_; }
1865
1866 void OnRegistration(SimpleEpollServer* eps, int fd, int event_mask) override {
1867 EXPECT_TRUE(eps_ == nullptr);
1868 eps_ = eps;
1869 Initialize(fd, event_mask);
1870 }
1871
1872 void OnModification(int fd, int event_mask) override {
1873 EXPECT_TRUE(eps_ != nullptr);
1874 if (event_mask & EPOLLET) {
1875 Initialize(fd, event_mask);
1876 } else {
1877 eps_->SetFDNotReady(fd);
1878 }
1879 }
1880
1881 void OnEvent(int fd, EpollEvent* event) override {
1882 const int event_mask = event->in_events;
1883 if (event_mask & (EPOLLHUP | EPOLLERR)) {
1884 write_closed_ = true;
1885 return;
1886 }
1887 if (will_read_ && event_mask & EPOLLIN) {
1888 EXPECT_FALSE(read_closed_);
1889 int read_size = read_buf_.size();
1890 memset(&read_buf_[0], 0, read_size);
1891 int len = recv(fd, &read_buf_[0], read_size, MSG_DONTWAIT);
1892 // Update the readiness states
1893 can_read_ = (len == read_size);
1894
1895 if (len > 0) {
1896 bytes_read_ += len;
1897 EPOLL_VLOG(1) << "fd: " << fd << ", read " << len
1898 << ", total: " << bytes_read_;
1899 // Now check the bytes read
1900 EXPECT_TRUE(CheckReadBuffer(len));
1901 } else if (len < 0) {
1902 EPOLL_VLOG(1) << "fd: " << fd << " read hit EAGAIN";
1903 EXPECT_EQ(EAGAIN, errno) << strerror(errno);
1904 can_read_ = false;
1905 } else {
1906 read_closed_ = true;
1907 }
1908 }
1909 if (will_write_ && event_mask & EPOLLOUT) {
1910 // Write side close/full close can only detected by EPOLLHUP, which is
1911 // caused by EPIPE.
1912 EXPECT_FALSE(write_closed_);
1913 int write_size = write_buf_.size();
1914 int len = send(fd, &write_buf_[0], write_size, MSG_DONTWAIT);
1915 can_write_ = (len == write_size);
1916 if (len > 0) {
1917 bytes_written_ += len;
1918 EPOLL_VLOG(1) << "fd: " << fd << ", write " << len
1919 << ", total: " << bytes_written_;
1920 } else {
1921 EPOLL_VLOG(1) << "fd: " << fd << " write hit EAGAIN";
1922 EXPECT_EQ(EAGAIN, errno) << strerror(errno);
1923 can_write_ = false;
1924 }
1925 }
1926 // Since we can only get on the ready list once, wait till we confirm both
1927 // read and write side continuation state and set the correct event mask
1928 // for the ready list.
1929 event->out_ready_mask = can_read_ ? EPOLLIN : 0;
1930 if (can_write_) {
1931 event->out_ready_mask |= EPOLLOUT;
1932 }
1933 }
1934
1935 void OnUnregistration(int fd, bool replaced) override {
1936 EXPECT_TRUE(eps_ != nullptr);
1937 eps_ = nullptr;
1938 }
1939
1940 void OnShutdown(SimpleEpollServer* eps, int fd) override {
1941 // None of the current tests involve having active callbacks when the
1942 // server shuts down.
1943 EPOLL_LOG(FATAL);
1944 }
1945
1946 string Name() const override { return "EdgeTriggerCB"; }
1947
1948 private:
1949 SimpleEpollServer* eps_;
1950 std::vector<char> read_buf_;
1951 int bytes_read_;
1952 std::vector<char> write_buf_;
1953 int bytes_written_;
1954 char peer_char_; // The char we expected to read.
1955 bool can_read_;
1956 bool will_read_;
1957 bool can_write_;
1958 bool will_write_;
1959 bool read_closed_;
1960 bool write_closed_;
1961
1962 void Initialize(int fd, int event_mask) {
1963 CHECK(eps_);
1964 can_read_ = can_write_ = false;
1965 if (event_mask & EPOLLET) {
1966 int events = 0;
1967 if (event_mask & EPOLLIN) {
1968 events |= EPOLLIN;
1969 can_read_ = true;
1970 }
1971 if (event_mask & EPOLLOUT) {
1972 events |= EPOLLOUT;
1973 can_write_ = true;
1974 }
1975 eps_->SetFDReady(fd, events);
1976 }
1977 }
1978
1979 bool CheckReadBuffer(int len) const {
1980 for (int i = 0; i < len; ++i) {
1981 if (peer_char_ != read_buf_[i]) {
1982 return false;
1983 }
1984 }
1985 return true;
1986 }
1987};
1988
1989// Test adding and removing from the ready list.
1990TEST(SimpleEpollServerTest, TestReadyList) {
1991 SimpleEpollServer ep;
1992 int pipe_fds[2];
1993 if (pipe(pipe_fds) < 0) {
1994 EPOLL_PLOG(FATAL) << "pipe() failed";
1995 }
1996
1997 // Just use any CB will do, since we never wait on epoll events.
1998 EdgeTriggerCB reader1(0, 0, 0, 0);
1999 EdgeTriggerCB reader2(0, 0, 0, 0);
2000
2001 ep.RegisterFD(pipe_fds[0], &reader1, EPOLLIN);
2002 ep.RegisterFD(pipe_fds[1], &reader2, EPOLLOUT);
2003
2004 // Adding fds that are registered with eps
2005 EXPECT_FALSE(ep.IsFDReady(pipe_fds[0]));
2006 EXPECT_FALSE(ep.IsFDReady(pipe_fds[1]));
2007
2008 ep.SetFDReady(pipe_fds[0], EPOLLIN);
2009 EXPECT_TRUE(ep.IsFDReady(pipe_fds[0]));
2010 EXPECT_FALSE(ep.IsFDReady(pipe_fds[1]));
2011 EXPECT_EQ(1, ep.ReadyListSize());
2012 ep.SetFDReady(pipe_fds[1], EPOLLOUT);
2013 EXPECT_TRUE(ep.IsFDReady(pipe_fds[0]));
2014 EXPECT_TRUE(ep.IsFDReady(pipe_fds[1]));
2015 EXPECT_EQ(2, ep.ReadyListSize());
2016
2017 // Now check that SetFDNotReady doesn't affect other fds
2018 ep.SetFDNotReady(pipe_fds[0]);
2019 EXPECT_FALSE(ep.IsFDReady(pipe_fds[0]));
2020 EXPECT_TRUE(ep.IsFDReady(pipe_fds[1]));
2021 EXPECT_EQ(1, ep.ReadyListSize());
2022
2023 ep.UnregisterFD(pipe_fds[0]);
2024 ep.UnregisterFD(pipe_fds[1]);
2025 EXPECT_EQ(0, ep.ReadyListSize());
2026
2027 // Now try adding them when they are not registered, and it shouldn't work.
2028 ep.SetFDReady(pipe_fds[0], EPOLLIN);
2029 EXPECT_FALSE(ep.IsFDReady(pipe_fds[0]));
2030 EXPECT_EQ(0, ep.ReadyListSize());
2031
2032 close(pipe_fds[0]);
2033 close(pipe_fds[1]);
2034}
2035
2036class EPSWaitThread : public EpollThread {
2037 public:
2038 explicit EPSWaitThread(SimpleEpollServer* eps)
2039 : EpollThread("EPSWait"), eps_(eps), done_(false) {}
2040
2041 void Run() override {
2042 eps_->WaitForEventsAndExecuteCallbacks();
2043 }
2044
2045 bool done() { return done_; }
2046 private:
2047 SimpleEpollServer* eps_;
2048 bool done_;
2049};
2050
2051TEST(EpollServerTest, TestWake) {
2052 SimpleEpollServer eps;
2053 eps.set_timeout_in_us(-1);
2054 EPSWaitThread eps_thread(&eps);
2055 eps_thread.Start();
2056
2057 EXPECT_FALSE(eps_thread.done());
2058 eps.Wake();
2059 eps_thread.Join();
2060}
2061
2062class UnRegisterWhileProcessingCB: public EpollCallbackInterface {
2063 public:
2064 explicit UnRegisterWhileProcessingCB(int fd) : eps_(nullptr), fd_(fd) {}
2065
2066 ~UnRegisterWhileProcessingCB() override {
2067 }
2068
2069 void OnShutdown(SimpleEpollServer* eps, int fd) override {}
2070
2071 void set_epoll_server(SimpleEpollServer* eps) { eps_ = eps; }
2072 void OnRegistration(SimpleEpollServer* eps, int fd, int event_mask) override {
2073 }
2074 void OnModification(int fd, int event_mask) override {}
2075 void OnEvent(int fd, EpollEvent* event) override {
2076 // This should cause no problems.
2077 eps_->UnregisterFD(fd_);
2078 }
2079 void OnUnregistration(int fd, bool replaced) override {}
2080 string Name() const override { return "UnRegisterWhileProcessingCB"; }
2081
2082 protected:
2083 SimpleEpollServer* eps_;
2084 int fd_;
2085};
2086
2087class RegisterWhileProcessingCB: public EpollCallbackInterface {
2088 public:
2089 RegisterWhileProcessingCB(int fd, EpollCallbackInterface* cb)
2090 : eps_(nullptr), fd_(fd), cb_(cb) {}
2091
2092 ~RegisterWhileProcessingCB() override {
2093 }
2094
2095 void OnShutdown(SimpleEpollServer* eps, int fd) override {}
2096
2097 void set_epoll_server(SimpleEpollServer* eps) { eps_ = eps; }
2098 void OnRegistration(SimpleEpollServer* eps, int fd, int event_mask) override {
2099 }
2100 void OnModification(int fd, int event_mask) override {}
2101 void OnEvent(int fd, EpollEvent* event) override {
2102 // This should cause no problems.
2103 eps_->RegisterFDForReadWrite(fd_, cb_);
2104 }
2105 void OnUnregistration(int fd, bool replaced) override {}
2106 string Name() const override { return "RegisterWhileProcessingCB"; }
2107
2108 protected:
2109 SimpleEpollServer* eps_;
2110 int fd_;
2111 EpollCallbackInterface* cb_;
2112};
2113
2114// Nothing bad should happen when we do this. We're -only-
2115// testing that nothing bad occurs in this test.
2116TEST(SimpleEpollServerTest, NothingBadWhenUnRegisteringFDWhileProcessingIt) {
2117 UnRegisterWhileProcessingCB cb(0);
2118 {
2119 FakeSimpleEpollServer epoll_server;
2120 cb.set_epoll_server(&epoll_server);
2121 epoll_server.RegisterFDForReadWrite(0, &cb);
2122 epoll_event ee;
2123 ee.data.fd = 0;
2124 epoll_server.AddEvent(0, ee);
2125 epoll_server.AdvanceBy(1);
2126 epoll_server.WaitForEventsAndExecuteCallbacks();
2127 }
2128}
2129
2130//
2131// testing that nothing bad occurs in this test.
2132TEST(SimpleEpollServerTest,
2133 NoEventsDeliveredForFdsOfUnregisteredCBsWithReRegdFD) {
2134 // events: fd0, fd1, fd2
2135 // fd0 -> unreg fd2
2136 // fd1 -> reg fd2
2137 // fd2 -> no event should be seen
2138 RecordingCB recorder_cb;
2139 UnRegisterWhileProcessingCB unreg_cb(-3);
2140 RegisterWhileProcessingCB reg_other_cb(-3, &recorder_cb);
2141 {
2142 FakeSimpleEpollServer epoll_server;
2143 unreg_cb.set_epoll_server(&epoll_server);
2144 reg_other_cb.set_epoll_server(&epoll_server);
2145 epoll_server.RegisterFDForReadWrite(-1, &unreg_cb);
2146 epoll_server.RegisterFDForReadWrite(-2, &reg_other_cb);
2147 epoll_server.RegisterFDForReadWrite(-3, &recorder_cb);
2148
2149 epoll_event ee;
2150 ee.events = EPOLLIN; // asserted for all events for this test.
2151
2152 // Note that these events are in 'backwards' order in terms of time.
2153 // Currently, the SimpleEpollServer code invokes the CBs from last delivered
2154 // to first delivered, so this is to be sure that we invoke the CB for -1
2155 // before -2, before -3.
2156 ee.data.fd = -1;
2157 epoll_server.AddEvent(2, ee);
2158 ee.data.fd = -2;
2159 epoll_server.AddEvent(1, ee);
2160 ee.data.fd = -3;
2161 epoll_server.AddEvent(0, ee);
2162
2163 epoll_server.AdvanceBy(5);
2164 epoll_server.WaitForEventsAndExecuteCallbacks();
2165 }
2166
2167 Recorder correct_recorder;
2168 correct_recorder.Record(&recorder_cb, CREATION, 0, 0);
2169 correct_recorder.Record(&recorder_cb, REGISTRATION, -3,
2170 EPOLLIN | EPOLLOUT);
2171 correct_recorder.Record(&recorder_cb, UNREGISTRATION, -3, 0);
2172 correct_recorder.Record(&recorder_cb, REGISTRATION, -3,
2173 EPOLLIN | EPOLLOUT);
2174 correct_recorder.Record(&recorder_cb, SHUTDOWN, -3, 0);
2175
2176 EXPECT_TRUE(correct_recorder.IsEqual(recorder_cb.recorder()));
2177}
2178
2179class ReRegWhileReadyListOnEvent: public EpollCallbackInterface {
2180 public:
2181 explicit ReRegWhileReadyListOnEvent(int fd) : eps_(nullptr) {}
2182
2183 void OnShutdown(SimpleEpollServer* eps, int fd) override {}
2184
2185 void set_epoll_server(SimpleEpollServer* eps) { eps_ = eps; }
2186 void OnRegistration(SimpleEpollServer* eps, int fd, int event_mask) override {
2187 }
2188 void OnModification(int fd, int event_mask) override {}
2189 void OnEvent(int fd, EpollEvent* event) override {
2190 // This should cause no problems.
2191 eps_->UnregisterFD(fd);
2192 eps_->RegisterFDForReadWrite(fd, this);
2193 eps_->UnregisterFD(fd);
2194 }
2195 void OnUnregistration(int fd, bool replaced) override {}
2196 string Name() const override { return "ReRegWhileReadyListOnEvent"; }
2197
2198 protected:
2199 SimpleEpollServer* eps_;
2200};
2201
2202// Nothing bad should happen when we do this. We're -only-
2203// testing that nothing bad occurs in this test.
2204TEST(SimpleEpollServerTest,
2205 NothingBadWhenReRegisteringFDWhileProcessingFromReadyList) {
2206 ReRegWhileReadyListOnEvent cb(0);
2207 {
2208 FakeSimpleEpollServer epoll_server;
2209 cb.set_epoll_server(&epoll_server);
2210 epoll_server.RegisterFDForReadWrite(0, &cb);
2211 epoll_event ee;
2212 ee.data.fd = 0;
2213 epoll_server.AddEvent(0, ee);
2214 epoll_server.AdvanceBy(1);
2215 epoll_server.WaitForEventsAndExecuteCallbacks();
2216 }
2217}
2218
2219class UnRegEverythingReadyListOnEvent: public EpollCallbackInterface {
2220 public:
2221 UnRegEverythingReadyListOnEvent() : eps_(nullptr), fd_(0), fd_range_(0) {}
2222
2223 void set_fd(int fd) { fd_ = fd; }
2224 void set_fd_range(int fd_range) { fd_range_ = fd_range; }
2225 void set_num_called(int* num_called) { num_called_ = num_called; }
2226
2227 void OnShutdown(SimpleEpollServer* eps, int fd) override {}
2228
2229 void set_epoll_server(SimpleEpollServer* eps) { eps_ = eps; }
2230 void OnRegistration(SimpleEpollServer* eps, int fd, int event_mask) override {
2231 eps->SetFDReady(fd, EPOLLIN);
2232 }
2233 void OnModification(int fd, int event_mask) override {}
2234 void OnEvent(int fd, EpollEvent* event) override {
2235 // This should cause no problems.
2236 CHECK(num_called_ != nullptr);
2237 ++(*num_called_);
2238 // Note that we're iterating from -fd_range + 1 -> 0.
2239 // We do this because there is an FD installed into the
2240 // epollserver somewhere in the low numbers.
2241 // Using negative FD numbers (which are guaranteed to not
2242 // exist in the epoll-server) ensures that we will not
2243 // come in conflict with the preexisting FD.
2244 for (int i = -fd_range_ + 1; i <= 0; ++i) {
2245 eps_->UnregisterFD(i);
2246 }
2247 }
2248 void OnUnregistration(int fd, bool replaced) override {}
2249 string Name() const override { return "UnRegEverythingReadyListOnEvent"; }
2250
2251 protected:
2252 SimpleEpollServer* eps_;
2253 int fd_;
2254 int fd_range_;
2255 int* num_called_;
2256};
2257
2258TEST(SimpleEpollServerTest,
2259 NothingBadWhenUnRegisteredWhileProcessingFromReadyList) {
2260 UnRegEverythingReadyListOnEvent callbacks[32];
2261 int num_called = 0;
2262 {
2263 FakeSimpleEpollServer epoll_server;
2264 for (size_t i = 0; i < ABSL_ARRAYSIZE(callbacks); ++i) {
2265 callbacks[i].set_fd(-i);
2266 callbacks[i].set_fd_range(ABSL_ARRAYSIZE(callbacks));
2267 callbacks[i].set_num_called(&num_called);
2268 callbacks[i].set_epoll_server(&epoll_server);
2269 epoll_server.RegisterFDForReadWrite(0, &callbacks[i]);
2270 epoll_event ee;
2271 ee.data.fd = -i;
2272 epoll_server.AddEvent(0, ee);
2273 }
2274 epoll_server.AdvanceBy(1);
2275 epoll_server.WaitForEventsAndExecuteCallbacks();
2276 epoll_server.WaitForEventsAndExecuteCallbacks();
2277 }
2278 EXPECT_EQ(1, num_called);
2279}
2280
2281TEST(SimpleEpollServerTest, TestThatVerifyReadyListWorksWithNothingInList) {
2282 FakeSimpleEpollServer epoll_server;
2283 epoll_server.VerifyReadyList();
2284}
2285
2286TEST(SimpleEpollServerTest, TestThatVerifyReadyListWorksWithStuffInLists) {
2287 FakeSimpleEpollServer epoll_server;
2288 epoll_server.VerifyReadyList();
2289}
2290
2291TEST(SimpleEpollServerTest,
2292 ApproximateNowInUsAccurateOutideOfWaitForEventsAndExecuteCallbacks) {
2293 FakeSimpleEpollServer epoll_server;
2294 epoll_server.AdvanceBy(1232);
2295 EXPECT_EQ(epoll_server.ApproximateNowInUsec(), epoll_server.NowInUsec());
2296 epoll_server.AdvanceBy(1111);
2297 EXPECT_EQ(epoll_server.ApproximateNowInUsec(), epoll_server.NowInUsec());
2298}
2299
2300class ApproximateNowInUsecTestCB: public EpollCallbackInterface {
2301 public:
2302 ApproximateNowInUsecTestCB() : feps_(nullptr), called_(false) {}
2303
2304 void OnRegistration(SimpleEpollServer* eps, int fd, int event_mask) override {
2305 }
2306 void OnModification(int fd, int event_mask) override {}
2307 void OnEvent(int fd, EpollEvent* event) override {
2308 EXPECT_EQ(feps_->ApproximateNowInUsec(), feps_->NowInUsec());
2309 feps_->AdvanceBy(1111);
2310 EXPECT_EQ(1 * 1111 + feps_->ApproximateNowInUsec(), feps_->NowInUsec());
2311 feps_->AdvanceBy(1111);
2312 EXPECT_EQ(2 * 1111 + feps_->ApproximateNowInUsec(), feps_->NowInUsec());
2313 called_ = true;
2314 }
2315 void OnUnregistration(int fd, bool replaced) override {}
2316 void OnShutdown(SimpleEpollServer* eps, int fd) override {}
2317 string Name() const override { return "ApproximateNowInUsecTestCB"; }
2318
2319 void set_fakeepollserver(FakeSimpleEpollServer* feps) { feps_ = feps; }
2320 bool called() const { return called_; }
2321
2322 protected:
2323 FakeSimpleEpollServer* feps_;
2324 bool called_;
2325};
2326
2327TEST(SimpleEpollServerTest,
2328 ApproximateNowInUsApproximateInsideOfWaitForEventsAndExecuteCallbacks) {
2329 int dummy_fd = 11111;
2330 ApproximateNowInUsecTestCB aniutcb;
2331 {
2332 FakeSimpleEpollServer epoll_server;
2333 aniutcb.set_fakeepollserver(&epoll_server);
2334
2335 epoll_server.RegisterFD(dummy_fd, &aniutcb, EPOLLIN);
2336 epoll_event ee;
2337 ee.data.fd = dummy_fd;
2338 ee.events = EPOLLIN;
2339 epoll_server.AddEvent(10242, ee);
2340 epoll_server.set_timeout_in_us(-1);
2341 epoll_server.AdvanceByAndWaitForEventsAndExecuteCallbacks(20000);
2342 EXPECT_TRUE(aniutcb.called());
2343 }
2344}
2345
2346// A mock epoll server that also simulates kernel delay in scheduling epoll
2347// events.
2348class FakeEpollServerWithDelay : public FakeSimpleEpollServer {
2349 public:
2350 FakeEpollServerWithDelay() : FakeSimpleEpollServer(), delay(0) {}
2351
2352 int delay;
2353
2354 protected:
2355 int epoll_wait_impl(int epfd, struct epoll_event* events, int max_events,
2356 int timeout_in_ms) override {
2357 int out = FakeSimpleEpollServer::epoll_wait_impl(epfd, events, max_events,
2358 timeout_in_ms);
2359 AdvanceBy(delay);
2360 return out;
2361 }
2362};
2363
2364// A callback that records the epoll event's delay.
2365class RecordDelayOnEvent: public EpollCallbackInterface {
2366 public:
2367 RecordDelayOnEvent() : last_delay(-1), eps_(nullptr) {}
2368
2369 ~RecordDelayOnEvent() override {
2370 }
2371
2372 void OnShutdown(SimpleEpollServer* eps, int fd) override {}
2373
2374 string Name() const override {
2375 return "RecordDelayOnEvent";
2376 }
2377
2378 void set_epoll_server(SimpleEpollServer* eps) { eps_ = eps; }
2379 void OnRegistration(SimpleEpollServer* eps, int fd, int event_mask) override {
2380 }
2381 void OnModification(int fd, int event_mask) override {}
2382 void OnEvent(int fd, EpollEvent* event) override {
2383 last_delay = eps_->LastDelayInUsec();
2384 }
2385 void OnUnregistration(int fd, bool replaced) override {}
2386
2387 int64_t last_delay;
2388
2389 protected:
2390 SimpleEpollServer* eps_;
2391};
2392
2393// Tests that an epoll callback sees the correct delay for its event when it
2394// calls LastDelayInUsec().
2395TEST(EpollServerTest, TestLastDelay) {
2396 RecordDelayOnEvent cb;
2397 FakeEpollServerWithDelay epoll_server;
2398
2399 cb.set_epoll_server(&epoll_server);
2400
2401 epoll_server.RegisterFDForReadWrite(0, &cb);
2402 epoll_event ee;
2403 ee.data.fd = 0;
2404
2405 // Inject delay, and confirm that it's reported.
2406 epoll_server.set_timeout_in_us(5000);
2407 epoll_server.delay = 6000;
2408 epoll_server.AddEvent(0, ee);
2409 epoll_server.AdvanceBy(1);
2410 epoll_server.WaitForEventsAndExecuteCallbacks();
2411 EXPECT_EQ(cb.last_delay, 1000);
2412
2413 // Fire an event before the timeout ends, and confirm that reported delay
2414 // isn't negative.
2415 epoll_server.set_timeout_in_us(5000);
2416 epoll_server.delay = 0;
2417 epoll_server.AddEvent(0, ee);
2418 epoll_server.AdvanceBy(1);
2419 epoll_server.WaitForEventsAndExecuteCallbacks();
2420 EXPECT_EQ(cb.last_delay, 0);
2421
2422 // Wait forever until an event fires, and confirm there's no reported delay.
2423 epoll_server.set_timeout_in_us(-1);
2424 epoll_server.delay = 6000;
2425 epoll_server.AddEvent(0, ee);
2426 epoll_server.AdvanceBy(1);
2427 epoll_server.WaitForEventsAndExecuteCallbacks();
2428 EXPECT_EQ(cb.last_delay, 0);
2429}
2430
2431TEST(SimpleEpollServerAlarmTest, TestShutdown) {
2432 std::unique_ptr<SimpleEpollServer> eps(new SimpleEpollServer);
2433 EpollAlarm alarm1;
2434 EpollAlarm alarm2;
2435
2436 eps->RegisterAlarmApproximateDelta(10000000, &alarm1);
2437 eps->RegisterAlarmApproximateDelta(10000000, &alarm2);
2438
2439 alarm2.UnregisterIfRegistered();
2440 EXPECT_FALSE(alarm2.registered());
2441 eps = nullptr;
2442
2443 EXPECT_FALSE(alarm1.registered());
2444}
2445
2446TEST(SimpleEpollServerAlarmTest, TestUnregister) {
2447 SimpleEpollServer eps;
2448 EpollAlarm alarm;
2449
2450 eps.RegisterAlarmApproximateDelta(10000000, &alarm);
2451 EXPECT_TRUE(alarm.registered());
2452
2453 alarm.UnregisterIfRegistered();
2454 EXPECT_FALSE(alarm.registered());
2455
2456 alarm.UnregisterIfRegistered();
2457 EXPECT_FALSE(alarm.registered());
2458}
2459
2460TEST(SimpleEpollServerAlarmTest, TestUnregisterOnDestruction) {
2461 EpollTestServer eps;
2462 std::unique_ptr<EpollAlarm> alarm(new EpollAlarm());
2463 EpollAlarm* alarm_ptr = alarm.get();
2464
2465 eps.RegisterAlarmApproximateDelta(10000000, alarm.get());
2466 EXPECT_TRUE(eps.ContainsAlarm(alarm_ptr));
2467 alarm = nullptr;
2468 EXPECT_EQ(0, eps.GetNumPendingAlarmsForTest());
2469}
2470
2471TEST(SimpleEpollServerAlarmTest, TestUnregisterOnAlarm) {
2472 EpollTestServer eps;
2473 EpollAlarm alarm;
2474
2475 eps.RegisterAlarmApproximateDelta(1, &alarm);
2476 EXPECT_TRUE(eps.ContainsAlarm(&alarm));
2477
2478 while (alarm.registered()) {
2479 eps.WaitForEventsAndExecuteCallbacks();
2480 }
2481 EXPECT_FALSE(eps.ContainsAlarm(&alarm));
2482}
2483
2484TEST(SimpleEpollServerAlarmTest, TestReregisterAlarm) {
2485 EpollTestAlarms ep;
2486
2487 EpollAlarm alarm;
2488 ep.set_time(1000);
2489 ep.RegisterAlarm(5000, &alarm);
2490
2491 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
2492 alarm.ReregisterAlarm(6000);
2493 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
2494
2495 ep.set_time(5000);
2496 ep.set_timeout_in_us(0);
2497 ep.CallAndReregisterAlarmEvents();
2498 EXPECT_EQ(1, ep.GetNumPendingAlarmsForTest());
2499
2500 ep.set_time(6000);
2501 ep.CallAndReregisterAlarmEvents();
2502 EXPECT_EQ(0, ep.GetNumPendingAlarmsForTest());
2503}
2504
2505TEST(SimpleEpollServerAlarmTest, TestThatSameAlarmCanNotBeRegisteredTwice) {
2506 TestAlarm alarm;
2507 SimpleEpollServer epoll_server;
2508 epoll_server.RegisterAlarm(1, &alarm);
2509 EXPECT_EPOLL_BUG(epoll_server.RegisterAlarm(1, &alarm),
2510 "Alarm already exists");
2511}
2512
2513} // namespace
2514
2515} // namespace test
2516
2517} // namespace epoll_server