886042001fa2af8546017a205e32b57a46b8174e
[folly.git] / folly / io / async / EventHandler.cpp
1 /*
2  * Copyright 2014 Facebook, Inc.
3  *
4  * Licensed to the Apache Software Foundation (ASF) under one
5  * or more contributor license agreements. See the NOTICE file
6  * distributed with this work for additional information
7  * regarding copyright ownership. The ASF licenses this file
8  * to you under the Apache License, Version 2.0 (the
9  * "License"); you may not use this file except in compliance
10  * with the License. You may obtain a copy of the License at
11  *
12  *   http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing,
15  * software distributed under the License is distributed on an
16  * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17  * KIND, either express or implied. See the License for the
18  * specific language governing permissions and limitations
19  * under the License.
20  */
21 #include <folly/io/async/EventHandler.h>
22 #include <folly/io/async/EventBase.h>
23
24 #include <assert.h>
25
26 namespace folly {
27
28 EventHandler::EventHandler(EventBase* eventBase, int fd) {
29   event_set(&event_, fd, 0, &EventHandler::libeventCallback, this);
30   if (eventBase != nullptr) {
31     setEventBase(eventBase);
32   } else {
33     // Callers must set the EventBase and fd before using this timeout.
34     // Set event_->ev_base to nullptr to ensure that this happens.
35     // (otherwise libevent will initialize it to the "default" event_base)
36     event_.ev_base = nullptr;
37     eventBase_ = nullptr;
38   }
39 }
40
41 EventHandler::~EventHandler() {
42   unregisterHandler();
43 }
44
45 bool EventHandler::registerImpl(uint16_t events, bool internal) {
46   assert(event_.ev_base != nullptr);
47
48   // We have to unregister the event before we can change the event flags
49   if (isHandlerRegistered()) {
50     // If the new events are the same are the same as the already registered
51     // flags, we don't have to do anything.  Just return.
52     if (events == event_.ev_events &&
53         static_cast<bool>(event_.ev_flags & EVLIST_INTERNAL) == internal) {
54       return true;
55     }
56
57     event_del(&event_);
58   }
59
60   // Update the event flags
61   // Unfortunately, event_set() resets the event_base, so we have to remember
62   // it before hand, then pass it back into event_base_set() afterwards
63   struct event_base* evb = event_.ev_base;
64   event_set(&event_, event_.ev_fd, events,
65             &EventHandler::libeventCallback, this);
66   event_base_set(evb, &event_);
67
68   // Set EVLIST_INTERNAL if this is an internal event
69   if (internal) {
70     event_.ev_flags |= EVLIST_INTERNAL;
71   }
72
73   // Add the event.
74   //
75   // Although libevent allows events to wait on both I/O and a timeout,
76   // we intentionally don't allow an EventHandler to also use a timeout.
77   // Callers must maintain a separate AsyncTimeout object if they want a
78   // timeout.
79   //
80   // Otherwise, it is difficult to handle persistent events properly.  (The I/O
81   // event and timeout may both fire together the same time around the event
82   // loop.  Normally we would want to inform the caller of the I/O event first,
83   // then the timeout.  However, it is difficult to do this properly since the
84   // I/O callback could delete the EventHandler.)  Additionally, if a caller
85   // uses the same struct event for both I/O and timeout, and they just want to
86   // reschedule the timeout, libevent currently makes an epoll_ctl() call even
87   // if the I/O event flags haven't changed.  Using a separate event struct is
88   // therefore slightly more efficient in this case (although it does take up
89   // more space).
90   if (event_add(&event_, nullptr) < 0) {
91     LOG(ERROR) << "EventBase: failed to register event handler for fd "
92                << event_.ev_fd << ": " << strerror(errno);
93     // Call event_del() to make sure the event is completely uninstalled
94     event_del(&event_);
95     return false;
96   }
97
98   return true;
99 }
100
101 void EventHandler::unregisterHandler() {
102   if (isHandlerRegistered()) {
103     event_del(&event_);
104   }
105 }
106
107 void EventHandler::attachEventBase(EventBase* eventBase) {
108   // attachEventBase() may only be called on detached handlers
109   assert(event_.ev_base == nullptr);
110   assert(!isHandlerRegistered());
111   // This must be invoked from the EventBase's thread
112   assert(eventBase->isInEventBaseThread());
113
114   setEventBase(eventBase);
115 }
116
117 void EventHandler::detachEventBase() {
118   ensureNotRegistered(__func__);
119   event_.ev_base = nullptr;
120 }
121
122 void EventHandler::changeHandlerFD(int fd) {
123   ensureNotRegistered(__func__);
124   // event_set() resets event_base.ev_base, so manually restore it afterwards
125   struct event_base* evb = event_.ev_base;
126   event_set(&event_, fd, 0, &EventHandler::libeventCallback, this);
127   event_.ev_base = evb; // don't use event_base_set(), since evb may be nullptr
128 }
129
130 void EventHandler::initHandler(EventBase* eventBase, int fd) {
131   ensureNotRegistered(__func__);
132   event_set(&event_, fd, 0, &EventHandler::libeventCallback, this);
133   setEventBase(eventBase);
134 }
135
136 void EventHandler::ensureNotRegistered(const char* fn) {
137   // Neither the EventBase nor file descriptor may be changed while the
138   // handler is registered.  Treat it as a programmer bug and abort the program
139   // if this requirement is violated.
140   if (isHandlerRegistered()) {
141     LOG(ERROR) << fn << " called on registered handler; aborting";
142     abort();
143   }
144 }
145
146 void EventHandler::libeventCallback(int fd, short events, void* arg) {
147   EventHandler* handler = reinterpret_cast<EventHandler*>(arg);
148   assert(fd == handler->event_.ev_fd);
149
150   // this can't possibly fire if handler->eventBase_ is nullptr
151   (void) handler->eventBase_->bumpHandlingTime();
152
153   handler->handlerReady(events);
154 }
155
156 void EventHandler::setEventBase(EventBase* eventBase) {
157   event_base_set(eventBase->getLibeventBase(), &event_);
158   eventBase_ = eventBase;
159 }
160
161 bool EventHandler::isPending() const {
162   if (event_.ev_flags & EVLIST_ACTIVE) {
163     if (event_.ev_res & EV_READ) {
164       return true;
165     }
166   }
167   return false;
168 }
169
170 } // folly