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