]> git.saurik.com Git - redis.git/blame - src/ae.c
If aeApiCreate() fails, there's probably not much one can do, but in the name of...
[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
e074416b 55aeEventLoop *aeCreateEventLoop(int setsize) {
ed9b544e 56 aeEventLoop *eventLoop;
266373b2 57 int i;
ed9b544e 58
e074416b 59 if ((eventLoop = zmalloc(sizeof(*eventLoop))) == NULL) return NULL;
60 eventLoop->events = NULL;
61 eventLoop->fired = NULL;
62 eventLoop->events = zmalloc(sizeof(aeFileEvent)*setsize);
63 eventLoop->fired = zmalloc(sizeof(aeFiredEvent)*setsize);
64 if (eventLoop->events == NULL || eventLoop->fired == NULL) {
65 zfree(eventLoop->events);
66 zfree(eventLoop->fired);
67 zfree(eventLoop);
68 return NULL;
69 }
70 eventLoop->setsize = setsize;
ed9b544e 71 eventLoop->timeEventHead = NULL;
72 eventLoop->timeEventNextId = 0;
73 eventLoop->stop = 0;
266373b2 74 eventLoop->maxfd = -1;
d5d55fc3 75 eventLoop->beforesleep = NULL;
266373b2 76 if (aeApiCreate(eventLoop) == -1) {
caa63a38
MS
77 zfree(eventLoop->events);
78 zfree(eventLoop->fired);
266373b2 79 zfree(eventLoop);
80 return NULL;
81 }
82 /* Events with mask == AE_NONE are not set. So let's initialize the
83 * vector with it. */
e074416b 84 for (i = 0; i < setsize; i++)
266373b2 85 eventLoop->events[i].mask = AE_NONE;
ed9b544e 86 return eventLoop;
87}
88
89void aeDeleteEventLoop(aeEventLoop *eventLoop) {
266373b2 90 aeApiFree(eventLoop);
18d0ef4b 91 zfree(eventLoop->events);
92 zfree(eventLoop->fired);
ed9b544e 93 zfree(eventLoop);
94}
95
96void aeStop(aeEventLoop *eventLoop) {
97 eventLoop->stop = 1;
98}
99
100int aeCreateFileEvent(aeEventLoop *eventLoop, int fd, int mask,
266373b2 101 aeFileProc *proc, void *clientData)
ed9b544e 102{
e074416b 103 if (fd >= eventLoop->setsize) return AE_ERR;
266373b2 104 aeFileEvent *fe = &eventLoop->events[fd];
105
106 if (aeApiAddEvent(eventLoop, fd, mask) == -1)
107 return AE_ERR;
108 fe->mask |= mask;
109 if (mask & AE_READABLE) fe->rfileProc = proc;
110 if (mask & AE_WRITABLE) fe->wfileProc = proc;
ed9b544e 111 fe->clientData = clientData;
266373b2 112 if (fd > eventLoop->maxfd)
113 eventLoop->maxfd = fd;
ed9b544e 114 return AE_OK;
115}
116
117void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask)
118{
e074416b 119 if (fd >= eventLoop->setsize) return;
266373b2 120 aeFileEvent *fe = &eventLoop->events[fd];
121
122 if (fe->mask == AE_NONE) return;
123 fe->mask = fe->mask & (~mask);
124 if (fd == eventLoop->maxfd && fe->mask == AE_NONE) {
125 /* Update the max fd */
126 int j;
127
128 for (j = eventLoop->maxfd-1; j >= 0; j--)
129 if (eventLoop->events[j].mask != AE_NONE) break;
130 eventLoop->maxfd = j;
ed9b544e 131 }
266373b2 132 aeApiDelEvent(eventLoop, fd, mask);
ed9b544e 133}
134
f14479c7 135int aeGetFileEvents(aeEventLoop *eventLoop, int fd) {
e074416b 136 if (fd >= eventLoop->setsize) return 0;
f14479c7 137 aeFileEvent *fe = &eventLoop->events[fd];
138
139 return fe->mask;
140}
141
ed9b544e 142static void aeGetTime(long *seconds, long *milliseconds)
143{
144 struct timeval tv;
145
146 gettimeofday(&tv, NULL);
147 *seconds = tv.tv_sec;
148 *milliseconds = tv.tv_usec/1000;
149}
150
151static void aeAddMillisecondsToNow(long long milliseconds, long *sec, long *ms) {
152 long cur_sec, cur_ms, when_sec, when_ms;
153
154 aeGetTime(&cur_sec, &cur_ms);
155 when_sec = cur_sec + milliseconds/1000;
156 when_ms = cur_ms + milliseconds%1000;
157 if (when_ms >= 1000) {
158 when_sec ++;
159 when_ms -= 1000;
160 }
161 *sec = when_sec;
162 *ms = when_ms;
163}
164
165long long aeCreateTimeEvent(aeEventLoop *eventLoop, long long milliseconds,
166 aeTimeProc *proc, void *clientData,
167 aeEventFinalizerProc *finalizerProc)
168{
169 long long id = eventLoop->timeEventNextId++;
170 aeTimeEvent *te;
171
172 te = zmalloc(sizeof(*te));
173 if (te == NULL) return AE_ERR;
174 te->id = id;
175 aeAddMillisecondsToNow(milliseconds,&te->when_sec,&te->when_ms);
176 te->timeProc = proc;
177 te->finalizerProc = finalizerProc;
178 te->clientData = clientData;
179 te->next = eventLoop->timeEventHead;
180 eventLoop->timeEventHead = te;
181 return id;
182}
183
184int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id)
185{
186 aeTimeEvent *te, *prev = NULL;
187
188 te = eventLoop->timeEventHead;
189 while(te) {
190 if (te->id == id) {
191 if (prev == NULL)
192 eventLoop->timeEventHead = te->next;
193 else
194 prev->next = te->next;
195 if (te->finalizerProc)
196 te->finalizerProc(eventLoop, te->clientData);
197 zfree(te);
198 return AE_OK;
199 }
200 prev = te;
201 te = te->next;
202 }
203 return AE_ERR; /* NO event with the specified ID found */
204}
205
206/* Search the first timer to fire.
207 * This operation is useful to know how many time the select can be
208 * put in sleep without to delay any event.
209 * If there are no timers NULL is returned.
210 *
5b2a1c29 211 * Note that's O(N) since time events are unsorted.
212 * Possible optimizations (not needed by Redis so far, but...):
213 * 1) Insert the event in order, so that the nearest is just the head.
214 * Much better but still insertion or deletion of timers is O(N).
215 * 2) Use a skiplist to have this operation as O(1) and insertion as O(log(N)).
216 */
ed9b544e 217static aeTimeEvent *aeSearchNearestTimer(aeEventLoop *eventLoop)
218{
219 aeTimeEvent *te = eventLoop->timeEventHead;
220 aeTimeEvent *nearest = NULL;
221
222 while(te) {
223 if (!nearest || te->when_sec < nearest->when_sec ||
224 (te->when_sec == nearest->when_sec &&
225 te->when_ms < nearest->when_ms))
226 nearest = te;
227 te = te->next;
228 }
229 return nearest;
230}
231
5b2a1c29 232/* Process time events */
233static int processTimeEvents(aeEventLoop *eventLoop) {
234 int processed = 0;
235 aeTimeEvent *te;
236 long long maxId;
237
238 te = eventLoop->timeEventHead;
239 maxId = eventLoop->timeEventNextId-1;
240 while(te) {
241 long now_sec, now_ms;
242 long long id;
243
244 if (te->id > maxId) {
245 te = te->next;
246 continue;
247 }
248 aeGetTime(&now_sec, &now_ms);
249 if (now_sec > te->when_sec ||
250 (now_sec == te->when_sec && now_ms >= te->when_ms))
251 {
252 int retval;
253
254 id = te->id;
255 retval = te->timeProc(eventLoop, id, te->clientData);
256 processed++;
257 /* After an event is processed our time event list may
258 * no longer be the same, so we restart from head.
259 * Still we make sure to don't process events registered
260 * by event handlers itself in order to don't loop forever.
261 * To do so we saved the max ID we want to handle.
262 *
263 * FUTURE OPTIMIZATIONS:
264 * Note that this is NOT great algorithmically. Redis uses
265 * a single time event so it's not a problem but the right
266 * way to do this is to add the new elements on head, and
267 * to flag deleted elements in a special way for later
268 * deletion (putting references to the nodes to delete into
269 * another linked list). */
270 if (retval != AE_NOMORE) {
271 aeAddMillisecondsToNow(retval,&te->when_sec,&te->when_ms);
272 } else {
273 aeDeleteTimeEvent(eventLoop, id);
274 }
275 te = eventLoop->timeEventHead;
276 } else {
277 te = te->next;
278 }
279 }
280 return processed;
281}
282
ed9b544e 283/* Process every pending time event, then every pending file event
284 * (that may be registered by time event callbacks just processed).
285 * Without special flags the function sleeps until some file event
286 * fires, or when the next time event occurrs (if any).
287 *
288 * If flags is 0, the function does nothing and returns.
289 * if flags has AE_ALL_EVENTS set, all the kind of events are processed.
290 * if flags has AE_FILE_EVENTS set, file events are processed.
291 * if flags has AE_TIME_EVENTS set, time events are processed.
292 * if flags has AE_DONT_WAIT set the function returns ASAP until all
293 * the events that's possible to process without to wait are processed.
294 *
295 * The function returns the number of events processed. */
296int aeProcessEvents(aeEventLoop *eventLoop, int flags)
297{
266373b2 298 int processed = 0, numevents;
ed9b544e 299
300 /* Nothing to do? return ASAP */
301 if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) return 0;
302
ed9b544e 303 /* Note that we want call select() even if there are no
304 * file events to process as long as we want to process time
305 * events, in order to sleep until the next time event is ready
306 * to fire. */
266373b2 307 if (eventLoop->maxfd != -1 ||
308 ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) {
309 int j;
ed9b544e 310 aeTimeEvent *shortest = NULL;
311 struct timeval tv, *tvp;
312
313 if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT))
314 shortest = aeSearchNearestTimer(eventLoop);
315 if (shortest) {
316 long now_sec, now_ms;
317
318 /* Calculate the time missing for the nearest
319 * timer to fire. */
320 aeGetTime(&now_sec, &now_ms);
321 tvp = &tv;
322 tvp->tv_sec = shortest->when_sec - now_sec;
323 if (shortest->when_ms < now_ms) {
324 tvp->tv_usec = ((shortest->when_ms+1000) - now_ms)*1000;
325 tvp->tv_sec --;
326 } else {
327 tvp->tv_usec = (shortest->when_ms - now_ms)*1000;
328 }
266373b2 329 if (tvp->tv_sec < 0) tvp->tv_sec = 0;
330 if (tvp->tv_usec < 0) tvp->tv_usec = 0;
ed9b544e 331 } else {
332 /* If we have to check for events but need to return
333 * ASAP because of AE_DONT_WAIT we need to se the timeout
334 * to zero */
335 if (flags & AE_DONT_WAIT) {
336 tv.tv_sec = tv.tv_usec = 0;
337 tvp = &tv;
338 } else {
339 /* Otherwise we can block */
340 tvp = NULL; /* wait forever */
341 }
342 }
343
266373b2 344 numevents = aeApiPoll(eventLoop, tvp);
345 for (j = 0; j < numevents; j++) {
346 aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd];
347 int mask = eventLoop->fired[j].mask;
348 int fd = eventLoop->fired[j].fd;
621d5c19 349 int rfired = 0;
266373b2 350
351 /* note the fe->mask & mask & ... code: maybe an already processed
352 * event removed an element that fired and we still didn't
353 * processed, so we check if the event is still valid. */
621d5c19 354 if (fe->mask & mask & AE_READABLE) {
355 rfired = 1;
266373b2 356 fe->rfileProc(eventLoop,fd,fe->clientData,mask);
621d5c19 357 }
358 if (fe->mask & mask & AE_WRITABLE) {
359 if (!rfired || fe->wfileProc != fe->rfileProc)
360 fe->wfileProc(eventLoop,fd,fe->clientData,mask);
361 }
266373b2 362 processed++;
ed9b544e 363 }
364 }
365 /* Check time events */
5b2a1c29 366 if (flags & AE_TIME_EVENTS)
367 processed += processTimeEvents(eventLoop);
ed9b544e 368
ed9b544e 369 return processed; /* return the number of processed file/time events */
370}
371
372/* Wait for millseconds until the given file descriptor becomes
373 * writable/readable/exception */
374int aeWait(int fd, int mask, long long milliseconds) {
375 struct timeval tv;
376 fd_set rfds, wfds, efds;
377 int retmask = 0, retval;
378
379 tv.tv_sec = milliseconds/1000;
380 tv.tv_usec = (milliseconds%1000)*1000;
381 FD_ZERO(&rfds);
382 FD_ZERO(&wfds);
383 FD_ZERO(&efds);
384
385 if (mask & AE_READABLE) FD_SET(fd,&rfds);
386 if (mask & AE_WRITABLE) FD_SET(fd,&wfds);
ed9b544e 387 if ((retval = select(fd+1, &rfds, &wfds, &efds, &tv)) > 0) {
388 if (FD_ISSET(fd,&rfds)) retmask |= AE_READABLE;
389 if (FD_ISSET(fd,&wfds)) retmask |= AE_WRITABLE;
ed9b544e 390 return retmask;
391 } else {
392 return retval;
393 }
394}
395
7a932b74 396void aeMain(aeEventLoop *eventLoop) {
ed9b544e 397 eventLoop->stop = 0;
d5d55fc3 398 while (!eventLoop->stop) {
399 if (eventLoop->beforesleep != NULL)
400 eventLoop->beforesleep(eventLoop);
ed9b544e 401 aeProcessEvents(eventLoop, AE_ALL_EVENTS);
d5d55fc3 402 }
ed9b544e 403}
7a932b74 404
405char *aeGetApiName(void) {
406 return aeApiName();
407}
d5d55fc3 408
409void aeSetBeforeSleepProc(aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep) {
410 eventLoop->beforesleep = beforesleep;
411}