123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501 |
- /* A simple event-driven programming library. Originally I wrote this code
- * for the Jim's event-loop (Jim is a Tcl interpreter) but later translated
- * it in form of a library for easy reuse.
- *
- * Copyright (c) 2006-2010, Salvatore Sanfilippo <antirez at gmail dot com>
- * All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *
- * * Redistributions of source code must retain the above copyright notice,
- * this list of conditions and the following disclaimer.
- * * Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * * Neither the name of Redis nor the names of its contributors may be used
- * to endorse or promote products derived from this software without
- * specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
- * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
- * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
- * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
- * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
- * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
- * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
- * POSSIBILITY OF SUCH DAMAGE.
- */
- #include "../inc/cs.h"
- #include "../inc/ae.h"
- /* Include the best multiplexing layer supported by this system.
- * The following should be ordered by performances, descending. */
- #ifdef HAVE_EVPORT
- #include "ev/ae_evport.c"
- #else
- #ifdef HAVE_EPOLL
- #include "ev/ae_epoll.c"
- #else
- #ifdef HAVE_KQUEUE
- #include "ev/ae_kqueue.c"
- #else
- #include "ev/ae_select.c"
- #endif
- #endif
- #endif
- CS_API aeEventLoop *aeCreateEventLoop(int setsize) {
- aeEventLoop *eventLoop;
- int i;
- if ((eventLoop = zmalloc(sizeof(*eventLoop))) == NULL) goto err;
- eventLoop->events = zmalloc(sizeof(aeFileEvent)*setsize);
- eventLoop->fired = zmalloc(sizeof(aeFiredEvent)*setsize);
- if (eventLoop->events == NULL || eventLoop->fired == NULL) goto err;
- eventLoop->setsize = setsize;
- eventLoop->lastTime = time(NULL);
- eventLoop->timeEventHead = NULL;
- eventLoop->timeEventNextId = 0;
- eventLoop->stop = 0;
- eventLoop->maxfd = -1;
- eventLoop->beforesleep = NULL;
- eventLoop->aftersleep = NULL;
- if (aeApiCreate(eventLoop) == -1) goto err;
- /* Events with mask == AE_NONE are not set. So let's initialize the
- * vector with it. */
- for (i = 0; i < setsize; i++)
- eventLoop->events[i].mask = AE_NONE;
- return eventLoop;
- err:
- if (eventLoop) {
- zfree(eventLoop->events);
- zfree(eventLoop->fired);
- zfree(eventLoop);
- }
- return NULL;
- }
- /* Return the current set size. */
- CS_API int aeGetSetSize(aeEventLoop *eventLoop) {
- return eventLoop->setsize;
- }
- /* Resize the maximum set size of the event loop.
- * If the requested set size is smaller than the current set size, but
- * there is already a file descriptor in use that is >= the requested
- * set size minus one, AE_ERR is returned and the operation is not
- * performed at all.
- *
- * Otherwise AE_OK is returned and the operation is successful. */
- CS_API int aeResizeSetSize(aeEventLoop *eventLoop, int setsize) {
- int i;
- if (setsize == eventLoop->setsize) return AE_OK;
- if (eventLoop->maxfd >= setsize) return AE_ERR;
- if (aeApiResize(eventLoop,setsize) == -1) return AE_ERR;
- eventLoop->events = zrealloc(eventLoop->events,sizeof(aeFileEvent)*setsize);
- eventLoop->fired = zrealloc(eventLoop->fired,sizeof(aeFiredEvent)*setsize);
- eventLoop->setsize = setsize;
- /* Make sure that if we created new slots, they are initialized with
- * an AE_NONE mask. */
- for (i = eventLoop->maxfd+1; i < setsize; i++)
- eventLoop->events[i].mask = AE_NONE;
- return AE_OK;
- }
- CS_API void aeDeleteEventLoop(aeEventLoop *eventLoop) {
- aeApiFree(eventLoop);
- zfree(eventLoop->events);
- zfree(eventLoop->fired);
- zfree(eventLoop);
- }
- CS_API void aeStop(aeEventLoop *eventLoop) {
- eventLoop->stop = 1;
- }
- CS_API int aeCreateFileEvent(
- aeEventLoop *eventLoop,
- int fd,
- int mask,
- aeFileProc *proc,
- void *clientData) {
- if (fd >= eventLoop->setsize) {
- errno = ERANGE;
- return AE_ERR;
- }
- aeFileEvent *fe = &eventLoop->events[fd];
- if (aeApiAddEvent(eventLoop, fd, mask) == -1)
- return AE_ERR;
- fe->mask |= mask;
- if (mask & AE_READABLE) fe->rfileProc = proc;
- if (mask & AE_WRITABLE) fe->wfileProc = proc;
- fe->clientData = clientData;
- if (fd > eventLoop->maxfd)
- eventLoop->maxfd = fd;
- return AE_OK;
- }
- CS_API void aeDeleteFileEvent(aeEventLoop *eventLoop, int fd, int mask) {
- if (fd >= eventLoop->setsize) return;
- aeFileEvent *fe = &eventLoop->events[fd];
- if (fe->mask == AE_NONE) return;
- aeApiDelEvent(eventLoop, fd, mask);
- fe->mask = fe->mask & (~mask);
- if (fd == eventLoop->maxfd && fe->mask == AE_NONE) {
- /* Update the max fd */
- int j;
- for (j = eventLoop->maxfd-1; j >= 0; j--)
- if (eventLoop->events[j].mask != AE_NONE) break;
- eventLoop->maxfd = j;
- }
- }
- CS_API int aeGetFileEvents(aeEventLoop *eventLoop, int fd) {
- if (fd >= eventLoop->setsize) return 0;
- aeFileEvent *fe = &eventLoop->events[fd];
- return fe->mask;
- }
- static void aeGetTime(long *seconds, long *milliseconds) {
- #ifdef _WIN32
- struct _timeb tb;
- memset(&tb, 0, sizeof(struct _timeb));
- _ftime_s(&tb);
- (*seconds) = tb.time;
- (*milliseconds) = tb.millitm;
- #else
- struct timeval tv;
- gettimeofday(&tv, NULL);
- *seconds = tv.tv_sec;
- *milliseconds = tv.tv_usec/1000;
- #endif
- }
- static void aeAddMillisecondsToNow(
- long long milliseconds, long *sec, long *ms) {
- long cur_sec, cur_ms, when_sec, when_ms;
- aeGetTime(&cur_sec, &cur_ms);
- when_sec = cur_sec + milliseconds/1000;
- when_ms = cur_ms + milliseconds%1000;
- if (when_ms >= 1000) {
- when_sec ++;
- when_ms -= 1000;
- }
- *sec = when_sec;
- *ms = when_ms;
- }
- CS_API long long aeCreateTimeEvent(
- aeEventLoop *eventLoop,
- long long milliseconds,
- aeTimeProc *proc,
- void *clientData,
- aeEventFinalizerProc *finalizerProc) {
- long long id = eventLoop->timeEventNextId++;
- aeTimeEvent *te;
- te = zmalloc(sizeof(*te));
- if (te == NULL) return AE_ERR;
- te->id = id;
- aeAddMillisecondsToNow(milliseconds,&te->when_sec,&te->when_ms);
- te->timeProc = proc;
- te->finalizerProc = finalizerProc;
- te->clientData = clientData;
- te->next = eventLoop->timeEventHead;
- eventLoop->timeEventHead = te;
- return id;
- }
- CS_API int aeDeleteTimeEvent(aeEventLoop *eventLoop, long long id) {
- aeTimeEvent *te = eventLoop->timeEventHead;
- while(te) {
- if (te->id == id) {
- te->id = AE_DELETED_EVENT_ID;
- return AE_OK;
- }
- te = te->next;
- }
- return AE_ERR; /* NO event with the specified ID found */
- }
- /* Search the first timer to fire.
- * This operation is useful to know how many time the select can be
- * put in sleep without to delay any event.
- * If there are no timers NULL is returned.
- *
- * Note that's O(N) since time events are unsorted.
- * Possible optimizations (not needed by Redis so far, but...):
- * 1) Insert the event in order, so that the nearest is just the head.
- * Much better but still insertion or deletion of timers is O(N).
- * 2) Use a skiplist to have this operation as O(1) and insertion as O(log(N)).
- */
- static aeTimeEvent *aeSearchNearestTimer(aeEventLoop *eventLoop) {
- aeTimeEvent *te = eventLoop->timeEventHead;
- aeTimeEvent *nearest = NULL;
- while(te) {
- if (!nearest || te->when_sec < nearest->when_sec ||
- (te->when_sec == nearest->when_sec &&
- te->when_ms < nearest->when_ms))
- nearest = te;
- te = te->next;
- }
- return nearest;
- }
- /* Process time events */
- static int processTimeEvents(aeEventLoop *eventLoop) {
- int processed = 0;
- aeTimeEvent *te, *prev;
- long long maxId;
- time_t now = time(NULL);
- /* If the system clock is moved to the future, and then set back to the
- * right value, time events may be delayed in a random way. Often this
- * means that scheduled operations will not be performed soon enough.
- *
- * Here we try to detect system clock skews, and force all the time
- * events to be processed ASAP when this happens: the idea is that
- * processing events earlier is less dangerous than delaying them
- * indefinitely, and practice suggests it is. */
- if (now < eventLoop->lastTime) {
- te = eventLoop->timeEventHead;
- while(te) {
- te->when_sec = 0;
- te = te->next;
- }
- }
- eventLoop->lastTime = now;
- prev = NULL;
- te = eventLoop->timeEventHead;
- maxId = eventLoop->timeEventNextId-1;
- while(te) {
- long now_sec, now_ms;
- long long id;
- /* Remove events scheduled for deletion. */
- if (te->id == AE_DELETED_EVENT_ID) {
- aeTimeEvent *next = te->next;
- if (prev == NULL)
- eventLoop->timeEventHead = te->next;
- else
- prev->next = te->next;
- if (te->finalizerProc)
- te->finalizerProc(eventLoop, te->clientData);
- zfree(te);
- te = next;
- continue;
- }
- /* Make sure we don't process time events created by time events in
- * this iteration. Note that this check is currently useless: we always
- * add new timers on the head, however if we change the implementation
- * detail, this check may be useful again: we keep it here for future
- * defense. */
- if (te->id > maxId) {
- te = te->next;
- continue;
- }
- aeGetTime(&now_sec, &now_ms);
- if (now_sec > te->when_sec ||
- (now_sec == te->when_sec && now_ms >= te->when_ms))
- {
- int retval;
- id = te->id;
- retval = te->timeProc(eventLoop, id, te->clientData);
- processed++;
- if (retval != AE_NOMORE) {
- aeAddMillisecondsToNow(retval,&te->when_sec,&te->when_ms);
- } else {
- te->id = AE_DELETED_EVENT_ID;
- }
- }
- prev = te;
- te = te->next;
- }
- return processed;
- }
- /* Process every pending time event, then every pending file event
- * (that may be registered by time event callbacks just processed).
- * Without special flags the function sleeps until some file event
- * fires, or when the next time event occurs (if any).
- *
- * If flags is 0, the function does nothing and returns.
- * if flags has AE_ALL_EVENTS set, all the kind of events are processed.
- * if flags has AE_FILE_EVENTS set, file events are processed.
- * if flags has AE_TIME_EVENTS set, time events are processed.
- * if flags has AE_DONT_WAIT set the function returns ASAP until all
- * if flags has AE_CALL_AFTER_SLEEP set, the aftersleep callback is called.
- * the events that's possible to process without to wait are processed.
- *
- * The function returns the number of events processed. */
- CS_API int aeProcessEvents(aeEventLoop *eventLoop, int flags) {
- int processed = 0, numevents;
- /* Nothing to do? return ASAP */
- if (!(flags & AE_TIME_EVENTS) && !(flags & AE_FILE_EVENTS)) return 0;
- /* Note that we want call select() even if there are no
- * file events to process as long as we want to process time
- * events, in order to sleep until the next time event is ready
- * to fire. */
- if (eventLoop->maxfd != -1 ||
- ((flags & AE_TIME_EVENTS) && !(flags & AE_DONT_WAIT))) {
- int j;
- aeTimeEvent *shortest = NULL;
- struct timeval tv, *tvp;
- if (flags & AE_TIME_EVENTS && !(flags & AE_DONT_WAIT))
- shortest = aeSearchNearestTimer(eventLoop);
- if (shortest) {
- long now_sec, now_ms;
- aeGetTime(&now_sec, &now_ms);
- tvp = &tv;
- /* How many milliseconds we need to wait for the next
- * time event to fire? */
- long long ms =
- (shortest->when_sec - now_sec)*1000 +
- shortest->when_ms - now_ms;
- if (ms > 0) {
- tvp->tv_sec = ms/1000;
- tvp->tv_usec = (ms % 1000)*1000;
- } else {
- tvp->tv_sec = 0;
- tvp->tv_usec = 0;
- }
- } else {
- /* If we have to check for events but need to return
- * ASAP because of AE_DONT_WAIT we need to set the timeout
- * to zero */
- if (flags & AE_DONT_WAIT) {
- tv.tv_sec = tv.tv_usec = 0;
- tvp = &tv;
- } else {
- /* Otherwise we can block */
- tvp = NULL; /* wait forever */
- }
- }
- /* Call the multiplexing API, will return only on timeout or when
- * some event fires. */
- numevents = aeApiPoll(eventLoop, tvp);
- /* After sleep callback. */
- if (eventLoop->aftersleep != NULL && flags & AE_CALL_AFTER_SLEEP)
- eventLoop->aftersleep(eventLoop);
- for (j = 0; j < numevents; j++) {
- aeFileEvent *fe = &eventLoop->events[eventLoop->fired[j].fd];
- int mask = eventLoop->fired[j].mask;
- int fd = eventLoop->fired[j].fd;
- int rfired = 0;
- /* note the fe->mask & mask & ... code: maybe an already processed
- * event removed an element that fired and we still didn't
- * processed, so we check if the event is still valid. */
- if (fe->mask & mask & AE_READABLE) {
- rfired = 1;
- fe->rfileProc(eventLoop,fd,fe->clientData,mask);
- }
- if (fe->mask & mask & AE_WRITABLE) {
- if (!rfired || fe->wfileProc != fe->rfileProc)
- fe->wfileProc(eventLoop,fd,fe->clientData,mask);
- }
- processed++;
- }
- }
- /* Check time events */
- if (flags & AE_TIME_EVENTS)
- processed += processTimeEvents(eventLoop);
- return processed; /* return the number of processed file/time events */
- }
- /* Wait for milliseconds until the given file descriptor becomes
- * writable/readable/exception */
- CS_API int aeWait(int fd, int mask, long long milliseconds) {
- #ifdef _WIN32
- struct timeval tv;
- fd_set rfds, wfds, efds;
- int retmask = 0, retval;
- tv.tv_sec = (long)(milliseconds/1000);
- tv.tv_usec = (milliseconds%1000)*1000;
- FD_ZERO(&rfds);
- FD_ZERO(&wfds);
- FD_ZERO(&efds);
- if (mask & AE_READABLE) FD_SET(fd,&rfds);
- if (mask & AE_WRITABLE) FD_SET(fd,&wfds);
- if ((retval = select(fd+1, &rfds, &wfds, &efds, &tv)) > 0) {
- if (FD_ISSET(fd,&rfds)) retmask |= AE_READABLE;
- if (FD_ISSET(fd,&wfds)) retmask |= AE_WRITABLE;
- return retmask;
- } else {
- return retval;
- }
- #else
- struct pollfd pfd;
- int retmask = 0, retval;
- memset(&pfd, 0, sizeof(pfd));
- pfd.fd = fd;
- if (mask & AE_READABLE) pfd.events |= POLLIN;
- if (mask & AE_WRITABLE) pfd.events |= POLLOUT;
- if ((retval = poll(&pfd, 1, milliseconds))== 1) {
- if (pfd.revents & POLLIN) retmask |= AE_READABLE;
- if (pfd.revents & POLLOUT) retmask |= AE_WRITABLE;
- if (pfd.revents & POLLERR) retmask |= AE_WRITABLE;
- if (pfd.revents & POLLHUP) retmask |= AE_WRITABLE;
- return retmask;
- } else {
- return retval;
- }
- #endif
- }
- CS_API void aeMain(aeEventLoop *eventLoop) {
- eventLoop->stop = 0;
- while (!eventLoop->stop) {
- if (eventLoop->beforesleep != NULL)
- eventLoop->beforesleep(eventLoop);
- aeProcessEvents(eventLoop, AE_ALL_EVENTS|AE_CALL_AFTER_SLEEP);
- }
- }
- CS_API char *aeGetApiName(void) {
- return aeApiName();
- }
- CS_API void aeSetBeforeSleepProc(
- aeEventLoop *eventLoop, aeBeforeSleepProc *beforesleep) {
- eventLoop->beforesleep = beforesleep;
- }
- CS_API void aeSetAfterSleepProc(
- aeEventLoop *eventLoop, aeBeforeSleepProc *aftersleep) {
- eventLoop->aftersleep = aftersleep;
- }
|