]> git.saurik.com Git - redis.git/blame - src/ae.c
default log level is now notice.
[redis.git] / src / ae.c
CommitLineData
ed9b544e 1/* A simple event-driven programming library. Originally I wrote this code
2 * for the Jim's event-loop (Jim is a Tcl interpreter) but later translated
3 * it in form of a library for easy reuse.
4 *
12d090d2 5 * Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
ed9b544e 6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
10 *
11 * * Redistributions of source code must retain the above copyright notice,
12 * this list of conditions and the following disclaimer.
13 * * Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * * Neither the name of Redis nor the names of its contributors may be used
17 * to endorse or promote products derived from this software without
18 * specific prior written permission.
19 *
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
24 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30 * POSSIBILITY OF SUCH DAMAGE.
31 */
32
33#include <stdio.h>
34#include <sys/time.h>
35#include <sys/types.h>
36#include <unistd.h>
37#include <stdlib.h>
38
39#include "ae.h"
40#include "zmalloc.h"
266373b2 41#include "config.h"
42
43/* Include the best multiplexing layer supported by this system.
44 * The following should be ordered by performances, descending. */
45#ifdef HAVE_EPOLL
46#include "ae_epoll.c"
47#else
f3053eb0
HM
48 #ifdef HAVE_KQUEUE
49 #include "ae_kqueue.c"
50 #else
51 #include "ae_select.c"
52 #endif
266373b2 53#endif
ed9b544e 54
55aeEventLoop *aeCreateEventLoop(void) {
56 aeEventLoop *eventLoop;
266373b2 57 int i;
ed9b544e 58
59 eventLoop = zmalloc(sizeof(*eventLoop));
60 if (!eventLoop) return NULL;
ed9b544e 61 eventLoop->timeEventHead = NULL;
62 eventLoop->timeEventNextId = 0;
63 eventLoop->stop = 0;
266373b2 64 eventLoop->maxfd = -1;
d5d55fc3 65 eventLoop->beforesleep = NULL;
266373b2 66 if (aeApiCreate(eventLoop) == -1) {
67 zfree(eventLoop);
68 return NULL;
69 }
70 /* Events with mask == AE_NONE are not set. So let's initialize the
71 * vector with it. */
72 for (i = 0; i < AE_SETSIZE; i++)
73 eventLoop->events[i].mask = AE_NONE;
ed9b544e 74 return eventLoop;
75}
76
77void aeDeleteEventLoop(aeEventLoop *eventLoop) {
266373b2 78 aeApiFree(eventLoop);
ed9b544e 79 zfree(eventLoop);
80}
81
82void aeStop(aeEventLoop *eventLoop) {
83 eventLoop->stop = 1;
84}
85
86int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask,
266373b2 87 aeFileProc *proc, void *clientData)
ed9b544e 88{
266373b2 89 if (fd >= AE_SETSIZE) return AE_ERR;
90 aeFileEvent *fe = &eventLoop->events[fd];
91
92 if (aeApiAddEvent(eventLoop, fd, mask) == -1)
93 return AE_ERR;
94 fe->mask |= mask;
95 if (mask & AE_READABLE) fe->rfileProc = proc;
96 if (mask & AE_WRITABLE) fe->wfileProc = proc;
ed9b544e 97 fe->clientData = clientData;
266373b2 98 if (fd > eventLoop->maxfd)
99 eventLoop->maxfd = fd;
ed9b544e 100 return AE_OK;
101}
102
103void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask)
104{
266373b2 105 if (fd >= AE_SETSIZE) return;
106 aeFileEvent *fe = &eventLoop->events[fd];
107
108 if (fe->mask == AE_NONE) return;
109 fe->mask = fe->mask & (~mask);
110 if (fd == eventLoop->maxfd && fe->mask == AE_NONE) {
111 /* Update the max fd */
112 int j;
113
114 for (j = eventLoop->maxfd-1; j >= 0; j--)
115 if (eventLoop->events[j].mask != AE_NONE) break;
116 eventLoop->maxfd = j;
ed9b544e 117 }
266373b2 118 aeApiDelEvent(eventLoop, fd, mask);
ed9b544e 119}
120
f14479c7 121int aeGetFileEvents(aeEventLoop *eventLoop, int fd) {
122 if (fd >= AE_SETSIZE) return 0;
123 aeFileEvent *fe = &eventLoop->events[fd];
124
125 return fe->mask;
126}
127
ed9b544e 128static void aeGetTime(long *seconds, long *milliseconds)
129{
130 struct timeval tv;
131
132 gettimeofday(&tv, NULL);
133 *seconds = tv.tv_sec;
134 *milliseconds = tv.tv_usec/1000;
135}
136
137static void aeAddMillisecondsToNow(long long milliseconds, long *sec, long *ms) {
138 long cur_sec, cur_ms, when_sec, when_ms;
139
140 aeGetTime(&cur_sec, &cur_ms);
141 when_sec = cur_sec + milliseconds/1000;
142 when_ms = cur_ms + milliseconds%1000;
143 if (when_ms >= 1000) {
144 when_sec ++;
145 when_ms -= 1000;
146 }
147 *sec = when_sec;
148 *ms = when_ms;
149}
150
151long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds,
152 aeTimeProc *proc, void *clientData,
153 aeEventFinalizerProc *finalizerProc)
154{
155 long long id = eventLoop->timeEventNextId++;
156 aeTimeEvent *te;
157
158 te = zmalloc(sizeof(*te));
159 if (te == NULL) return AE_ERR;
160 te->id = id;
161 aeAddMillisecondsToNow(milliseconds,&te->when_sec,&te->when_ms);
162 te->timeProc = proc;
163 te->finalizerProc = finalizerProc;
164 te->clientData = clientData;
165 te->next = eventLoop->timeEventHead;
166 eventLoop->timeEventHead = te;
167 return id;
168}
169
170int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id)
171{
172 aeTimeEvent *te, *prev = NULL;
173
174 te = eventLoop->timeEventHead;
175 while(te) {
176 if (te->id == id) {
177 if (prev == NULL)
178 eventLoop->timeEventHead = te->next;
179 else
180 prev->next = te->next;
181 if (te->finalizerProc)
182 te->finalizerProc(eventLoop, te->clientData);
183 zfree(te);
184 return AE_OK;
185 }
186 prev = te;
187 te = te->next;
188 }
189 return AE_ERR; /* NO event with the specified ID found */
190}
191
192/* Search the first timer to fire.
193 * This operation is useful to know how many time the select can be
194 * put in sleep without to delay any event.
195 * If there are no timers NULL is returned.
196 *
5b2a1c29 197 * Note that's O(N) since time events are unsorted.
198 * Possible optimizations (not needed by Redis so far, but...):
199 * 1) Insert the event in order, so that the nearest is just the head.
200 * Much better but still insertion or deletion of timers is O(N).
201 * 2) Use a skiplist to have this operation as O(1) and insertion as O(log(N)).
202 */
ed9b544e 203static aeTimeEvent *aeSearchNearestTimer(aeEventLoop *eventLoop)
204{
205 aeTimeEvent *te = eventLoop->timeEventHead;
206 aeTimeEvent *nearest = NULL;
207
208 while(te) {
209 if (!nearest || te->when_sec < nearest->when_sec ||
210 (te->when_sec == nearest->when_sec &&
211 te->when_ms < nearest->when_ms))
212 nearest = te;
213 te = te->next;
214 }
215 return nearest;
216}
217
5b2a1c29 218/* Process time events */
219static int processTimeEvents(aeEventLoop *eventLoop) {
220 int processed = 0;
221 aeTimeEvent *te;
222 long long maxId;
223
224 te = eventLoop->timeEventHead;
225 maxId = eventLoop->timeEventNextId-1;
226 while(te) {
227 long now_sec, now_ms;
228 long long id;
229
230 if (te->id > maxId) {
231 te = te->next;
232 continue;
233 }
234 aeGetTime(&now_sec, &now_ms);
235 if (now_sec > te->when_sec ||
236 (now_sec == te->when_sec && now_ms >= te->when_ms))
237 {
238 int retval;
239
240 id = te->id;
241 retval = te->timeProc(eventLoop, id, te->clientData);
242 processed++;
243 /* After an event is processed our time event list may
244 * no longer be the same, so we restart from head.
245 * Still we make sure to don't process events registered
246 * by event handlers itself in order to don't loop forever.
247 * To do so we saved the max ID we want to handle.
248 *
249 * FUTURE OPTIMIZATIONS:
250 * Note that this is NOT great algorithmically. Redis uses
251 * a single time event so it's not a problem but the right
252 * way to do this is to add the new elements on head, and
253 * to flag deleted elements in a special way for later
254 * deletion (putting references to the nodes to delete into
255 * another linked list). */
256 if (retval != AE_NOMORE) {
257 aeAddMillisecondsToNow(retval,&te->when_sec,&te->when_ms);
258 } else {
259 aeDeleteTimeEvent(eventLoop, id);
260 }
261 te = eventLoop->timeEventHead;
262 } else {
263 te = te->next;
264 }
265 }
266 return processed;
267}
268
ed9b544e 269/* Process every pending time event, then every pending file event
270 * (that may be registered by time event callbacks just processed).
271 * Without special flags the function sleeps until some file event
272 * fires, or when the next time event occurrs (if any).
273 *
274 * If flags is 0, the function does nothing and returns.
275 * if flags has AE_ALL_EVENTS set, all the kind of events are processed.
276 * if flags has AE_FILE_EVENTS set, file events are processed.
277 * if flags has AE_TIME_EVENTS set, time events are processed.
278 * if flags has AE_DONT_WAIT set the function returns ASAP until all
279 * the events that's possible to process without to wait are processed.
280 *
281 * The function returns the number of events processed. */
282int aeProcessEvents(aeEventLoop *eventLoop, int flags)
283{
266373b2 284 int processed = 0, numevents;
ed9b544e 285
286 /* Nothing to do? return ASAP */
287 if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) return 0;
288
ed9b544e 289 /* Note that we want call select() even if there are no
290 * file events to process as long as we want to process time
291 * events, in order to sleep until the next time event is ready
292 * to fire. */
266373b2 293 if (eventLoop->maxfd != -1 ||
294 ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) {
295 int j;
ed9b544e 296 aeTimeEvent *shortest = NULL;
297 struct timeval tv, *tvp;
298
299 if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT))
300 shortest = aeSearchNearestTimer(eventLoop);
301 if (shortest) {
302 long now_sec, now_ms;
303
304 /* Calculate the time missing for the nearest
305 * timer to fire. */
306 aeGetTime(&now_sec, &now_ms);
307 tvp = &tv;
308 tvp->tv_sec = shortest->when_sec - now_sec;
309 if (shortest->when_ms < now_ms) {
310 tvp->tv_usec = ((shortest->when_ms+1000) - now_ms)*1000;
311 tvp->tv_sec --;
312 } else {
313 tvp->tv_usec = (shortest->when_ms - now_ms)*1000;
314 }
266373b2 315 if (tvp->tv_sec < 0) tvp->tv_sec = 0;
316 if (tvp->tv_usec < 0) tvp->tv_usec = 0;
ed9b544e 317 } else {
318 /* If we have to check for events but need to return
319 * ASAP because of AE_DONT_WAIT we need to se the timeout
320 * to zero */
321 if (flags & AE_DONT_WAIT) {
322 tv.tv_sec = tv.tv_usec = 0;
323 tvp = &tv;
324 } else {
325 /* Otherwise we can block */
326 tvp = NULL; /* wait forever */
327 }
328 }
329
266373b2 330 numevents = aeApiPoll(eventLoop, tvp);
331 for (j = 0; j < numevents; j++) {
332 aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd];
333 int mask = eventLoop->fired[j].mask;
334 int fd = eventLoop->fired[j].fd;
621d5c19 335 int rfired = 0;
266373b2 336
337 /* note the fe->mask & mask & ... code: maybe an already processed
338 * event removed an element that fired and we still didn't
339 * processed, so we check if the event is still valid. */
621d5c19 340 if (fe->mask & mask & AE_READABLE) {
341 rfired = 1;
266373b2 342 fe->rfileProc(eventLoop,fd,fe->clientData,mask);
621d5c19 343 }
344 if (fe->mask & mask & AE_WRITABLE) {
345 if (!rfired || fe->wfileProc != fe->rfileProc)
346 fe->wfileProc(eventLoop,fd,fe->clientData,mask);
347 }
266373b2 348 processed++;
ed9b544e 349 }
350 }
351 /* Check time events */
5b2a1c29 352 if (flags & AE_TIME_EVENTS)
353 processed += processTimeEvents(eventLoop);
ed9b544e 354
ed9b544e 355 return processed; /* return the number of processed file/time events */
356}
357
358/* Wait for millseconds until the given file descriptor becomes
359 * writable/readable/exception */
360int aeWait(int fd, int mask, long long milliseconds) {
361 struct timeval tv;
362 fd_set rfds, wfds, efds;
363 int retmask = 0, retval;
364
365 tv.tv_sec = milliseconds/1000;
366 tv.tv_usec = (milliseconds%1000)*1000;
367 FD_ZERO(&rfds);
368 FD_ZERO(&wfds);
369 FD_ZERO(&efds);
370
371 if (mask & AE_READABLE) FD_SET(fd,&rfds);
372 if (mask & AE_WRITABLE) FD_SET(fd,&wfds);
ed9b544e 373 if ((retval = select(fd+1, &rfds, &wfds, &efds, &tv)) > 0) {
374 if (FD_ISSET(fd,&rfds)) retmask |= AE_READABLE;
375 if (FD_ISSET(fd,&wfds)) retmask |= AE_WRITABLE;
ed9b544e 376 return retmask;
377 } else {
378 return retval;
379 }
380}
381
7a932b74 382void aeMain(aeEventLoop *eventLoop) {
ed9b544e 383 eventLoop->stop = 0;
d5d55fc3 384 while (!eventLoop->stop) {
385 if (eventLoop->beforesleep != NULL)
386 eventLoop->beforesleep(eventLoop);
ed9b544e 387 aeProcessEvents(eventLoop, AE_ALL_EVENTS);
d5d55fc3 388 }
ed9b544e 389}
7a932b74 390
391char *aeGetApiName(void) {
392 return aeApiName();
393}
d5d55fc3 394
395void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep) {
396 eventLoop->beforesleep = beforesleep;
397}