forked from eventmachine/eventmachine
-
Notifications
You must be signed in to change notification settings - Fork 4
/
em.cpp
2351 lines (1946 loc) · 62.4 KB
/
em.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*****************************************************************************
$Id$
File: em.cpp
Date: 06Apr06
Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
Gmail: blackhedd
This program is free software; you can redistribute it and/or modify
it under the terms of either: 1) the GNU General Public License
as published by the Free Software Foundation; either version 2 of the
License, or (at your option) any later version; or 2) Ruby's License.
See the file COPYING for complete licensing information.
*****************************************************************************/
// THIS ENTIRE FILE WILL EVENTUALLY BE FOR UNIX BUILDS ONLY.
//#ifdef OS_UNIX
#include "project.h"
/* The numer of max outstanding timers was once a const enum defined in em.h.
* Now we define it here so that users can change its value if necessary.
*/
static unsigned int MaxOutstandingTimers = 100000;
/* Internal helper to convert strings to internet addresses. IPv6-aware.
* Not reentrant or threadsafe, optimized for speed.
*/
static struct sockaddr *name2address (const char *server, int port, int *family, int *bind_size);
/***************************************
STATIC EventMachine_t::GetMaxTimerCount
***************************************/
int EventMachine_t::GetMaxTimerCount()
{
return MaxOutstandingTimers;
}
/***************************************
STATIC EventMachine_t::SetMaxTimerCount
***************************************/
void EventMachine_t::SetMaxTimerCount (int count)
{
/* Allow a user to increase the maximum number of outstanding timers.
* If this gets "too high" (a metric that is of course platform dependent),
* bad things will happen like performance problems and possible overuse
* of memory.
* The actual timer mechanism is very efficient so it's hard to know what
* the practical max, but 100,000 shouldn't be too problematical.
*/
if (count < 100)
count = 100;
MaxOutstandingTimers = count;
}
/******************************
EventMachine_t::EventMachine_t
******************************/
EventMachine_t::EventMachine_t (EMCallback event_callback):
HeartbeatInterval(2000000),
EventCallback (event_callback),
NextHeartbeatTime (0),
LoopBreakerReader (-1),
LoopBreakerWriter (-1),
NumCloseScheduled (0),
bTerminateSignalReceived (false),
bEpoll (false),
epfd (-1),
bKqueue (false),
kqfd (-1),
inotify (NULL)
{
// Default time-slice is just smaller than one hundred mills.
Quantum.tv_sec = 0;
Quantum.tv_usec = 90000;
// Make sure the current loop time is sane, in case we do any initializations of
// objects before we start running.
_UpdateTime();
/* We initialize the network library here (only on Windows of course)
* and initialize "loop breakers." Our destructor also does some network-level
* cleanup. There's thus an implicit assumption that any given instance of EventMachine_t
* will only call ::Run once. Is that a good assumption? Should we move some of these
* inits and de-inits into ::Run?
*/
#ifdef OS_WIN32
WSADATA w;
WSAStartup (MAKEWORD (1, 1), &w);
#endif
_InitializeLoopBreaker();
}
/*******************************
EventMachine_t::~EventMachine_t
*******************************/
EventMachine_t::~EventMachine_t()
{
// Run down descriptors
size_t i;
for (i = 0; i < NewDescriptors.size(); i++)
delete NewDescriptors[i];
for (i = 0; i < Descriptors.size(); i++)
delete Descriptors[i];
close (LoopBreakerReader);
close (LoopBreakerWriter);
// Remove any file watch descriptors
while(!Files.empty()) {
map<int, Bindable_t*>::iterator f = Files.begin();
UnwatchFile (f->first);
}
if (epfd != -1)
close (epfd);
if (kqfd != -1)
close (kqfd);
}
/*************************
EventMachine_t::_UseEpoll
*************************/
void EventMachine_t::_UseEpoll()
{
/* Temporary.
* Use an internal flag to switch in epoll-based functionality until we determine
* how it should be integrated properly and the extent of the required changes.
* A permanent solution needs to allow the integration of additional technologies,
* like kqueue and Solaris's events.
*/
#ifdef HAVE_EPOLL
bEpoll = true;
#endif
}
/**************************
EventMachine_t::_UseKqueue
**************************/
void EventMachine_t::_UseKqueue()
{
/* Temporary.
* See comments under _UseEpoll.
*/
#ifdef HAVE_KQUEUE
bKqueue = true;
#endif
}
/****************************
EventMachine_t::ScheduleHalt
****************************/
void EventMachine_t::ScheduleHalt()
{
/* This is how we stop the machine.
* This can be called by clients. Signal handlers will probably
* set the global flag.
* For now this means there can only be one EventMachine ever running at a time.
*
* IMPORTANT: keep this light, fast, and async-safe. Don't do anything frisky in here,
* because it may be called from signal handlers invoked from code that we don't
* control. At this writing (20Sep06), EM does NOT install any signal handlers of
* its own.
*
* We need a FAQ. And one of the questions is: how do I stop EM when Ctrl-C happens?
* The answer is to call evma_stop_machine, which calls here, from a SIGINT handler.
*/
bTerminateSignalReceived = true;
}
/*******************************
EventMachine_t::SetTimerQuantum
*******************************/
void EventMachine_t::SetTimerQuantum (int interval)
{
/* We get a timer-quantum expressed in milliseconds.
*/
if ((interval < 5) || (interval > 5*60*1000))
throw std::runtime_error ("invalid timer-quantum");
Quantum.tv_sec = interval / 1000;
Quantum.tv_usec = (interval % 1000) * 1000;
}
/*************************************
(STATIC) EventMachine_t::SetuidString
*************************************/
void EventMachine_t::SetuidString (const char *username)
{
/* This method takes a caller-supplied username and tries to setuid
* to that user. There is no meaningful implementation (and no error)
* on Windows. On Unix, a failure to setuid the caller-supplied string
* causes a fatal abort, because presumably the program is calling here
* in order to fulfill a security requirement. If we fail silently,
* the user may continue to run with too much privilege.
*
* TODO, we need to decide on and document a way of generating C++ level errors
* that can be wrapped in documented Ruby exceptions, so users can catch
* and handle them. And distinguish it from errors that we WON'T let the Ruby
* user catch (like security-violations and resource-overallocation).
* A setuid failure here would be in the latter category.
*/
#ifdef OS_UNIX
if (!username || !*username)
throw std::runtime_error ("setuid_string failed: no username specified");
struct passwd *p = getpwnam (username);
if (!p)
throw std::runtime_error ("setuid_string failed: unknown username");
if (setuid (p->pw_uid) != 0)
throw std::runtime_error ("setuid_string failed: no setuid");
// Success.
#endif
}
/****************************************
(STATIC) EventMachine_t::SetRlimitNofile
****************************************/
int EventMachine_t::SetRlimitNofile (int nofiles)
{
#ifdef OS_UNIX
struct rlimit rlim;
getrlimit (RLIMIT_NOFILE, &rlim);
if (nofiles >= 0) {
rlim.rlim_cur = nofiles;
if ((unsigned int)nofiles > rlim.rlim_max)
rlim.rlim_max = nofiles;
setrlimit (RLIMIT_NOFILE, &rlim);
// ignore the error return, for now at least.
// TODO, emit an error message someday when we have proper debug levels.
}
getrlimit (RLIMIT_NOFILE, &rlim);
return rlim.rlim_cur;
#endif
#ifdef OS_WIN32
// No meaningful implementation on Windows.
return 0;
#endif
}
/*********************************
EventMachine_t::SignalLoopBreaker
*********************************/
void EventMachine_t::SignalLoopBreaker()
{
#ifdef OS_UNIX
write (LoopBreakerWriter, "", 1);
#endif
#ifdef OS_WIN32
sendto (LoopBreakerReader, "", 0, 0, (struct sockaddr*)&(LoopBreakerTarget), sizeof(LoopBreakerTarget));
#endif
}
/**************************************
EventMachine_t::_InitializeLoopBreaker
**************************************/
void EventMachine_t::_InitializeLoopBreaker()
{
/* A "loop-breaker" is a socket-descriptor that we can write to in order
* to break the main select loop. Primarily useful for things running on
* threads other than the main EM thread, so they can trigger processing
* of events that arise exogenously to the EM.
* Keep the loop-breaker pipe out of the main descriptor set, otherwise
* its events will get passed on to user code.
*/
#ifdef OS_UNIX
int fd[2];
if (pipe (fd))
throw std::runtime_error (strerror(errno));
LoopBreakerWriter = fd[1];
LoopBreakerReader = fd[0];
/* 16Jan11: Make sure the pipe is non-blocking, so more than 65k loopbreaks
* in one tick do not fill up the pipe and block the process on write() */
SetSocketNonblocking (LoopBreakerWriter);
#endif
#ifdef OS_WIN32
int sd = socket (AF_INET, SOCK_DGRAM, 0);
if (sd == INVALID_SOCKET)
throw std::runtime_error ("no loop breaker socket");
SetSocketNonblocking (sd);
memset (&LoopBreakerTarget, 0, sizeof(LoopBreakerTarget));
LoopBreakerTarget.sin_family = AF_INET;
LoopBreakerTarget.sin_addr.s_addr = inet_addr ("127.0.0.1");
srand ((int)time(NULL));
int i;
for (i=0; i < 100; i++) {
int r = (rand() % 10000) + 20000;
LoopBreakerTarget.sin_port = htons (r);
if (bind (sd, (struct sockaddr*)&LoopBreakerTarget, sizeof(LoopBreakerTarget)) == 0)
break;
}
if (i == 100)
throw std::runtime_error ("no loop breaker");
LoopBreakerReader = sd;
#endif
}
/***************************
EventMachine_t::_UpdateTime
***************************/
void EventMachine_t::_UpdateTime()
{
MyCurrentLoopTime = GetRealTime();
}
/***************************
EventMachine_t::GetRealTime
***************************/
uint64_t EventMachine_t::GetRealTime()
{
uint64_t current_time;
#if defined(OS_UNIX)
struct timeval tv;
gettimeofday (&tv, NULL);
current_time = (((uint64_t)(tv.tv_sec)) * 1000000LL) + ((uint64_t)(tv.tv_usec));
#elif defined(OS_WIN32)
unsigned tick = GetTickCount();
if (tick < LastTickCount)
TickCountTickover += 1;
LastTickCount = tick;
current_time = ((uint64_t)TickCountTickover << 32) + (uint64_t)tick;
current_time *= 1000; // convert to microseconds
#else
current_time = (uint64_t)time(NULL) * 1000000LL;
#endif
return current_time;
}
/***********************************
EventMachine_t::_DispatchHeartbeats
***********************************/
void EventMachine_t::_DispatchHeartbeats()
{
// Store the first processed heartbeat descriptor and bail out if
// we see it again. This fixes an infinite loop in case the system time
// is changed out from underneath MyCurrentLoopTime.
const EventableDescriptor *head = NULL;
while (true) {
multimap<uint64_t,EventableDescriptor*>::iterator i = Heartbeats.begin();
if (i == Heartbeats.end())
break;
if (i->first > MyCurrentLoopTime)
break;
EventableDescriptor *ed = i->second;
if (ed == head)
break;
ed->Heartbeat();
QueueHeartbeat(ed);
if (head == NULL)
head = ed;
}
}
/******************************
EventMachine_t::QueueHeartbeat
******************************/
void EventMachine_t::QueueHeartbeat(EventableDescriptor *ed)
{
uint64_t heartbeat = ed->GetNextHeartbeat();
if (heartbeat) {
#ifndef HAVE_MAKE_PAIR
Heartbeats.insert (multimap<uint64_t,EventableDescriptor*>::value_type (heartbeat, ed));
#else
Heartbeats.insert (make_pair (heartbeat, ed));
#endif
}
}
/******************************
EventMachine_t::ClearHeartbeat
******************************/
void EventMachine_t::ClearHeartbeat(uint64_t key, EventableDescriptor* ed)
{
multimap<uint64_t,EventableDescriptor*>::iterator it;
pair<multimap<uint64_t,EventableDescriptor*>::iterator,multimap<uint64_t,EventableDescriptor*>::iterator> ret;
ret = Heartbeats.equal_range (key);
for (it = ret.first; it != ret.second; ++it) {
if (it->second == ed) {
Heartbeats.erase (it);
break;
}
}
}
/*******************
EventMachine_t::Run
*******************/
void EventMachine_t::Run()
{
#ifdef HAVE_EPOLL
if (bEpoll) {
epfd = epoll_create (MaxEpollDescriptors);
if (epfd == -1) {
char buf[200];
snprintf (buf, sizeof(buf)-1, "unable to create epoll descriptor: %s", strerror(errno));
throw std::runtime_error (buf);
}
int cloexec = fcntl (epfd, F_GETFD, 0);
assert (cloexec >= 0);
cloexec |= FD_CLOEXEC;
fcntl (epfd, F_SETFD, cloexec);
assert (LoopBreakerReader >= 0);
LoopbreakDescriptor *ld = new LoopbreakDescriptor (LoopBreakerReader, this);
assert (ld);
Add (ld);
}
#endif
#ifdef HAVE_KQUEUE
if (bKqueue) {
kqfd = kqueue();
if (kqfd == -1) {
char buf[200];
snprintf (buf, sizeof(buf)-1, "unable to create kqueue descriptor: %s", strerror(errno));
throw std::runtime_error (buf);
}
// cloexec not needed. By definition, kqueues are not carried across forks.
assert (LoopBreakerReader >= 0);
LoopbreakDescriptor *ld = new LoopbreakDescriptor (LoopBreakerReader, this);
assert (ld);
Add (ld);
}
#endif
while (true) {
_UpdateTime();
_RunTimers();
/* _Add must precede _Modify because the same descriptor might
* be on both lists during the same pass through the machine,
* and to modify a descriptor before adding it would fail.
*/
_AddNewDescriptors();
_ModifyDescriptors();
_RunOnce();
if (bTerminateSignalReceived)
break;
}
}
/************************
EventMachine_t::_RunOnce
************************/
void EventMachine_t::_RunOnce()
{
if (bEpoll)
_RunEpollOnce();
else if (bKqueue)
_RunKqueueOnce();
else
_RunSelectOnce();
_DispatchHeartbeats();
_CleanupSockets();
}
/*****************************
EventMachine_t::_RunEpollOnce
*****************************/
void EventMachine_t::_RunEpollOnce()
{
#ifdef HAVE_EPOLL
assert (epfd != -1);
int s;
timeval tv = _TimeTilNextEvent();
#ifdef BUILD_FOR_RUBY
int ret = 0;
#ifdef HAVE_RB_WAIT_FOR_SINGLE_FD
if ((ret = rb_wait_for_single_fd(epfd, RB_WAITFD_IN|RB_WAITFD_PRI, &tv)) < 1) {
#else
fd_set fdreads;
FD_ZERO(&fdreads);
FD_SET(epfd, &fdreads);
if ((ret = rb_thread_select(epfd + 1, &fdreads, NULL, NULL, &tv)) < 1) {
#endif
if (ret == -1) {
assert(errno != EINVAL);
assert(errno != EBADF);
}
return;
}
TRAP_BEG;
s = epoll_wait (epfd, epoll_events, MaxEvents, 0);
TRAP_END;
#else
int duration = 0;
duration = duration + (tv.tv_sec * 1000);
duration = duration + (tv.tv_usec / 1000);
s = epoll_wait (epfd, epoll_events, MaxEvents, duration);
#endif
if (s > 0) {
for (int i=0; i < s; i++) {
EventableDescriptor *ed = (EventableDescriptor*) epoll_events[i].data.ptr;
if (ed->IsWatchOnly() && ed->GetSocket() == INVALID_SOCKET)
continue;
assert(ed->GetSocket() != INVALID_SOCKET);
if (epoll_events[i].events & EPOLLIN)
ed->Read();
if (epoll_events[i].events & EPOLLOUT)
ed->Write();
if (epoll_events[i].events & (EPOLLERR | EPOLLHUP))
ed->HandleError();
}
}
else if (s < 0) {
// epoll_wait can fail on error in a handful of ways.
// If this happens, then wait for a little while to avoid busy-looping.
// If the error was EINTR, we probably caught SIGCHLD or something,
// so keep the wait short.
timeval tv = {0, ((errno == EINTR) ? 5 : 50) * 1000};
EmSelect (0, NULL, NULL, NULL, &tv);
}
#else
throw std::runtime_error ("epoll is not implemented on this platform");
#endif
}
/******************************
EventMachine_t::_RunKqueueOnce
******************************/
void EventMachine_t::_RunKqueueOnce()
{
#ifdef HAVE_KQUEUE
assert (kqfd != -1);
int k;
timeval tv = _TimeTilNextEvent();
struct timespec ts;
ts.tv_sec = tv.tv_sec;
ts.tv_nsec = tv.tv_usec * 1000;
#ifdef BUILD_FOR_RUBY
int ret = 0;
#ifdef HAVE_RB_WAIT_FOR_SINGLE_FD
if ((ret = rb_wait_for_single_fd(kqfd, RB_WAITFD_IN|RB_WAITFD_PRI, &tv)) < 1) {
#else
fd_set fdreads;
FD_ZERO(&fdreads);
FD_SET(kqfd, &fdreads);
if ((ret = rb_thread_select(kqfd + 1, &fdreads, NULL, NULL, &tv)) < 1) {
#endif
if (ret == -1) {
assert(errno != EINVAL);
assert(errno != EBADF);
}
return;
}
TRAP_BEG;
ts.tv_sec = ts.tv_nsec = 0;
k = kevent (kqfd, NULL, 0, Karray, MaxEvents, &ts);
TRAP_END;
#else
k = kevent (kqfd, NULL, 0, Karray, MaxEvents, &ts);
#endif
struct kevent *ke = Karray;
while (k > 0) {
switch (ke->filter)
{
case EVFILT_VNODE:
_HandleKqueueFileEvent (ke);
break;
case EVFILT_PROC:
_HandleKqueuePidEvent (ke);
break;
case EVFILT_READ:
case EVFILT_WRITE:
EventableDescriptor *ed = (EventableDescriptor*) (ke->udata);
assert (ed);
if (ed->IsWatchOnly() && ed->GetSocket() == INVALID_SOCKET)
break;
if (ke->filter == EVFILT_READ)
ed->Read();
else if (ke->filter == EVFILT_WRITE)
ed->Write();
else
cerr << "Discarding unknown kqueue event " << ke->filter << endl;
break;
}
--k;
++ke;
}
// TODO, replace this with rb_thread_blocking_region for 1.9 builds.
#ifdef BUILD_FOR_RUBY
if (!rb_thread_alone()) {
rb_thread_schedule();
}
#endif
#else
throw std::runtime_error ("kqueue is not implemented on this platform");
#endif
}
/*********************************
EventMachine_t::_TimeTilNextEvent
*********************************/
timeval EventMachine_t::_TimeTilNextEvent()
{
// 29jul11: Changed calculation base from MyCurrentLoopTime to the
// real time. As MyCurrentLoopTime is set at the beginning of an
// iteration and this calculation is done at the end, evenmachine
// will potentially oversleep by the amount of time the iteration
// took to execute.
uint64_t next_event = 0;
uint64_t current_time = GetRealTime();
if (!Heartbeats.empty()) {
multimap<uint64_t,EventableDescriptor*>::iterator heartbeats = Heartbeats.begin();
next_event = heartbeats->first;
}
if (!Timers.empty()) {
multimap<uint64_t,Timer_t>::iterator timers = Timers.begin();
if (next_event == 0 || timers->first < next_event)
next_event = timers->first;
}
if (!NewDescriptors.empty() || !ModifiedDescriptors.empty()) {
next_event = current_time;
}
timeval tv;
if (NumCloseScheduled > 0 || bTerminateSignalReceived) {
tv.tv_sec = tv.tv_usec = 0;
} else if (next_event == 0) {
tv = Quantum;
} else {
if (next_event > current_time) {
uint64_t duration = next_event - current_time;
tv.tv_sec = duration / 1000000;
tv.tv_usec = duration % 1000000;
} else {
tv.tv_sec = tv.tv_usec = 0;
}
}
return tv;
}
/*******************************
EventMachine_t::_CleanupSockets
*******************************/
void EventMachine_t::_CleanupSockets()
{
// TODO, rip this out and only delete the descriptors we know have died,
// rather than traversing the whole list.
// Modified 05Jan08 per suggestions by Chris Heath. It's possible that
// an EventableDescriptor will have a descriptor value of -1. That will
// happen if EventableDescriptor::Close was called on it. In that case,
// don't call epoll_ctl to remove the socket's filters from the epoll set.
// According to the epoll docs, this happens automatically when the
// descriptor is closed anyway. This is different from the case where
// the socket has already been closed but the descriptor in the ED object
// hasn't yet been set to INVALID_SOCKET.
// In kqueue, closing a descriptor automatically removes its event filters.
int i, j;
int nSockets = Descriptors.size();
for (i=0, j=0; i < nSockets; i++) {
EventableDescriptor *ed = Descriptors[i];
assert (ed);
if (ed->ShouldDelete()) {
#ifdef HAVE_EPOLL
if (bEpoll) {
assert (epfd != -1);
if (ed->GetSocket() != INVALID_SOCKET) {
int e = epoll_ctl (epfd, EPOLL_CTL_DEL, ed->GetSocket(), ed->GetEpollEvent());
// ENOENT or EBADF are not errors because the socket may be already closed when we get here.
if (e && (errno != ENOENT) && (errno != EBADF) && (errno != EPERM)) {
char buf [200];
snprintf (buf, sizeof(buf)-1, "unable to delete epoll event: %s", strerror(errno));
throw std::runtime_error (buf);
}
}
ModifiedDescriptors.erase(ed);
}
#endif
delete ed;
}
else
Descriptors [j++] = ed;
}
while ((size_t)j < Descriptors.size())
Descriptors.pop_back();
}
/*********************************
EventMachine_t::_ModifyEpollEvent
*********************************/
void EventMachine_t::_ModifyEpollEvent (EventableDescriptor *ed)
{
#ifdef HAVE_EPOLL
if (bEpoll) {
assert (epfd != -1);
assert (ed);
assert (ed->GetSocket() != INVALID_SOCKET);
int e = epoll_ctl (epfd, EPOLL_CTL_MOD, ed->GetSocket(), ed->GetEpollEvent());
if (e) {
char buf [200];
snprintf (buf, sizeof(buf)-1, "unable to modify epoll event: %s", strerror(errno));
throw std::runtime_error (buf);
}
}
#endif
}
/**************************
SelectData_t::SelectData_t
**************************/
SelectData_t::SelectData_t()
{
maxsocket = 0;
FD_ZERO (&fdreads);
FD_ZERO (&fdwrites);
FD_ZERO (&fderrors);
}
#ifdef BUILD_FOR_RUBY
/*****************
_SelectDataSelect
*****************/
#ifdef HAVE_TBR
static VALUE _SelectDataSelect (void *v)
{
SelectData_t *sd = (SelectData_t*)v;
sd->nSockets = select (sd->maxsocket+1, &(sd->fdreads), &(sd->fdwrites), &(sd->fderrors), &(sd->tv));
return Qnil;
}
#endif
/*********************
SelectData_t::_Select
*********************/
int SelectData_t::_Select()
{
#ifdef HAVE_TBR
rb_thread_blocking_region (_SelectDataSelect, (void*)this, RUBY_UBF_IO, 0);
return nSockets;
#endif
#ifndef HAVE_TBR
return EmSelect (maxsocket+1, &fdreads, &fdwrites, &fderrors, &tv);
#endif
}
#endif
/******************************
EventMachine_t::_RunSelectOnce
******************************/
void EventMachine_t::_RunSelectOnce()
{
// Crank the event machine once.
// If there are no descriptors to process, then sleep
// for a few hundred mills to avoid busy-looping.
// This is based on a select loop. Alternately provide epoll
// if we know we're running on a 2.6 kernel.
// epoll will be effective if we provide it as an alternative,
// however it has the same problem interoperating with Ruby
// threads that select does.
SelectData_t SelectData;
/*
fd_set fdreads, fdwrites;
FD_ZERO (&fdreads);
FD_ZERO (&fdwrites);
int maxsocket = 0;
*/
// Always read the loop-breaker reader.
// Changed 23Aug06, provisionally implemented for Windows with a UDP socket
// running on localhost with a randomly-chosen port. (*Puke*)
// Windows has a version of the Unix pipe() library function, but it doesn't
// give you back descriptors that are selectable.
FD_SET (LoopBreakerReader, &(SelectData.fdreads));
if (SelectData.maxsocket < LoopBreakerReader)
SelectData.maxsocket = LoopBreakerReader;
// prepare the sockets for reading and writing
size_t i;
for (i = 0; i < Descriptors.size(); i++) {
EventableDescriptor *ed = Descriptors[i];
assert (ed);
int sd = ed->GetSocket();
if (ed->IsWatchOnly() && sd == INVALID_SOCKET)
continue;
assert (sd != INVALID_SOCKET);
if (ed->SelectForRead())
FD_SET (sd, &(SelectData.fdreads));
if (ed->SelectForWrite())
FD_SET (sd, &(SelectData.fdwrites));
#ifdef OS_WIN32
/* 21Sep09: on windows, a non-blocking connect() that fails does not come up as writable.
Instead, it is added to the error set. See http://www.mail-archive.com/[email protected]/msg58500.html
*/
FD_SET (sd, &(SelectData.fderrors));
#endif
if (SelectData.maxsocket < sd)
SelectData.maxsocket = sd;
}
{ // read and write the sockets
//timeval tv = {1, 0}; // Solaris fails if the microseconds member is >= 1000000.
//timeval tv = Quantum;
SelectData.tv = _TimeTilNextEvent();
int s = SelectData._Select();
//rb_thread_blocking_region(xxx,(void*)&SelectData,RUBY_UBF_IO,0);
//int s = EmSelect (SelectData.maxsocket+1, &(SelectData.fdreads), &(SelectData.fdwrites), NULL, &(SelectData.tv));
//int s = SelectData.nSockets;
if (s > 0) {
/* Changed 01Jun07. We used to handle the Loop-breaker right here.
* Now we do it AFTER all the regular descriptors. There's an
* incredibly important and subtle reason for this. Code on
* loop breakers is sometimes used to cause the reactor core to
* cycle (for example, to allow outbound network buffers to drain).
* If a loop-breaker handler reschedules itself (say, after determining
* that the write buffers are still too full), then it will execute
* IMMEDIATELY if _ReadLoopBreaker is done here instead of after
* the other descriptors are processed. That defeats the whole purpose.
*/
for (i=0; i < Descriptors.size(); i++) {
EventableDescriptor *ed = Descriptors[i];
assert (ed);
int sd = ed->GetSocket();
if (ed->IsWatchOnly() && sd == INVALID_SOCKET)
continue;
assert (sd != INVALID_SOCKET);
if (FD_ISSET (sd, &(SelectData.fdwrites)))
ed->Write();
if (FD_ISSET (sd, &(SelectData.fdreads)))
ed->Read();
if (FD_ISSET (sd, &(SelectData.fderrors)))
ed->HandleError();
}
if (FD_ISSET (LoopBreakerReader, &(SelectData.fdreads)))
_ReadLoopBreaker();
}
else if (s < 0) {
switch (errno) {
case EBADF:
_CleanBadDescriptors();
break;
case EINVAL:
throw std::runtime_error ("Somehow EM passed an invalid nfds or invalid timeout to select(2), please report this!");
break;
default:
// select can fail on error in a handful of ways.
// If this happens, then wait for a little while to avoid busy-looping.
// If the error was EINTR, we probably caught SIGCHLD or something,
// so keep the wait short.
timeval tv = {0, ((errno == EINTR) ? 5 : 50) * 1000};
EmSelect (0, NULL, NULL, NULL, &tv);
}
}
}
}
void EventMachine_t::_CleanBadDescriptors()
{
size_t i;
for (i = 0; i < Descriptors.size(); i++) {
EventableDescriptor *ed = Descriptors[i];
if (ed->ShouldDelete())
continue;
int sd = ed->GetSocket();
struct timeval tv;
tv.tv_sec = 0;
tv.tv_usec = 0;
fd_set fds;
FD_ZERO(&fds);
FD_SET(sd, &fds);
int ret = select(sd + 1, &fds, NULL, NULL, &tv);
if (ret == -1) {
if (errno == EBADF)
ed->ScheduleClose(false);
}
}
}
/********************************
EventMachine_t::_ReadLoopBreaker
********************************/
void EventMachine_t::_ReadLoopBreaker()
{
/* The loop breaker has selected readable.