Repository navigation
Expand file tree
/
Copy pathem.cpp
More file actions
2382 lines (1998 loc) · 64.8 KB
/
Copy pathem.cpp
File metadata and controls
2382 lines (1998 loc) · 64.8 KB
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
#if defined(__NetBSD__)
#include <sys/param.h>
#endif
#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;
/* The number of accept() done at once in a single tick when the acceptor
* socket becomes readable.
*/
static unsigned int SimultaneousAcceptCount = 10;
/* Internal helper to create a socket with SOCK_CLOEXEC set, and fall
* back to fcntl'ing it if the headers/runtime don't support it.
*/
SOCKET EmSocket (int domain, int type, int protocol)
{
SOCKET sd;
#ifdef HAVE_SOCKET_CLOEXEC
sd = socket (domain, type | SOCK_CLOEXEC, protocol);
if (sd == INVALID_SOCKET) {
sd = socket (domain, type, protocol);
if (sd < 0) {
return sd;
}
SetFdCloexec(sd);
}
#else
sd = socket (domain, type, protocol);
if (sd == INVALID_SOCKET) {
return sd;
}
SetFdCloexec(sd);
#endif
return sd;
}
/***************************************
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;
}
int EventMachine_t::GetSimultaneousAcceptCount()
{
return SimultaneousAcceptCount;
}
void EventMachine_t::SetSimultaneousAcceptCount (int count)
{
if (count < 1)
count = 1;
SimultaneousAcceptCount = count;
}
/******************************
EventMachine_t::EventMachine_t
******************************/
EventMachine_t::EventMachine_t (EMCallback event_callback, Poller_t poller):
NumCloseScheduled (0),
HeartbeatInterval(2000000),
EventCallback (event_callback),
LoopBreakerReader (INVALID_SOCKET),
LoopBreakerWriter (INVALID_SOCKET),
bTerminateSignalReceived (false),
Poller (poller),
epfd (-1),
kqfd (-1)
#ifdef HAVE_INOTIFY
, inotify (NULL)
#endif
{
// Default time-slice is just smaller than one hundred mills.
Quantum.tv_sec = 0;
Quantum.tv_usec = 90000;
// Override the requested poller back to default if needed.
#if !defined(HAVE_EPOLL) && !defined(HAVE_KQUEUE)
Poller = Poller_Default;
#endif
/* Initialize monotonic timekeeping on OS X before the first call to GetRealTime */
#ifdef OS_DARWIN
(void) mach_timebase_info(&mach_timebase);
#endif
#ifdef OS_WIN32
TickCountTickover = 0;
LastTickCount = 0;
#endif
// 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();
SelectData = new SelectData_t();
}
/*******************************
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()) {
std::map<int, Bindable_t*>::iterator f = Files.begin();
UnwatchFile (f->first);
}
if (epfd != -1)
close (epfd);
if (kqfd != -1)
close (kqfd);
delete SelectData;
}
/****************************
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;
/* Signal the loopbreaker so we break out of long-running select/epoll/kqueue and
* notice the halt boolean is set. Signalling the loopbreaker also uses a single
* signal-safe syscall.
*/
SignalLoopBreaker();
}
bool EventMachine_t::Stopping()
{
return bTerminateSignalReceived;
}
/*******************************
EventMachine_t::GetTimerQuantum
*******************************/
uint64_t EventMachine_t::GetTimerQuantum()
{
/* Convert timer-quantum to microseconds */
return (Quantum.tv_sec * 1000 + (Quantum.tv_usec + 500) / 1000) * 1000;
}
/*******************************
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
*************************************/
#ifdef OS_UNIX
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.
*/
if (!username || !*username)
throw std::runtime_error ("setuid_string failed: no username specified");
errno = 0;
struct passwd *p = getpwnam (username);
if (!p) {
if (errno) {
char buf[200];
snprintf (buf, sizeof(buf)-1, "setuid_string failed: %s", strerror(errno));
throw std::runtime_error (buf);
} else {
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.
}
#else
void EventMachine_t::SetuidString (const char *username UNUSED) { }
#endif
/****************************************
(STATIC) EventMachine_t::SetRlimitNofile
****************************************/
#ifdef OS_UNIX
int EventMachine_t::SetRlimitNofile (int nofiles)
{
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;
}
#else
int EventMachine_t::SetRlimitNofile (int nofiles UNUSED) { return 0; }
#endif
/*********************************
EventMachine_t::SignalLoopBreaker
*********************************/
void EventMachine_t::SignalLoopBreaker()
{
#ifdef OS_UNIX
(void)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 defined (HAVE_CLOEXEC) && defined (HAVE_PIPE2)
int pipestatus = pipe2(fd, O_CLOEXEC);
if (pipestatus < 0) {
if (pipe(fd))
throw std::runtime_error (strerror(errno));
}
#else
if (pipe (fd))
throw std::runtime_error (strerror(errno));
#endif
if (!SetFdCloexec(fd[0]) || !SetFdCloexec(fd[1]))
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
SOCKET sd = EmSocket (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
#ifdef HAVE_EPOLL
if (Poller == Poller_Epoll) {
epfd = epoll_create1(EPOLL_CLOEXEC);
if (epfd == -1) {
char buf[200];
snprintf (buf, sizeof(buf)-1, "unable to create epoll descriptor: %s", strerror(errno));
throw std::runtime_error (buf);
}
assert (LoopBreakerReader >= 0);
LoopbreakDescriptor *ld = new LoopbreakDescriptor (LoopBreakerReader, this);
assert (ld);
Add (ld);
}
#endif
#ifdef HAVE_KQUEUE
if (Poller == Poller_Kqueue) {
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
}
/***************************
EventMachine_t::_UpdateTime
***************************/
void EventMachine_t::_UpdateTime()
{
MyCurrentLoopTime = GetRealTime();
}
/***************************
EventMachine_t::GetRealTime
***************************/
// Two great writeups of cross-platform monotonic time are at:
// http://www.python.org/dev/peps/pep-0418
// http://nadeausoftware.com/articles/2012/04/c_c_tip_how_measure_elapsed_real_time_benchmarking
// Uncomment the #pragma messages to confirm which compile-time option was used
uint64_t EventMachine_t::GetRealTime()
{
uint64_t current_time;
#if defined(HAVE_CONST_CLOCK_MONOTONIC_RAW)
// #pragma message "GetRealTime: clock_gettime CLOCK_MONOTONIC_RAW"
// Linux 2.6.28 and above
struct timespec tv;
clock_gettime (CLOCK_MONOTONIC_RAW, &tv);
current_time = (((uint64_t)(tv.tv_sec)) * 1000000LL) + ((uint64_t)((tv.tv_nsec)/1000));
#elif defined(HAVE_CONST_CLOCK_MONOTONIC)
// #pragma message "GetRealTime: clock_gettime CLOCK_MONOTONIC"
// Linux, FreeBSD 5.0 and above, Solaris 8 and above, OpenBSD, NetBSD, DragonflyBSD
struct timespec tv;
clock_gettime (CLOCK_MONOTONIC, &tv);
current_time = (((uint64_t)(tv.tv_sec)) * 1000000LL) + ((uint64_t)((tv.tv_nsec)/1000));
#elif defined(HAVE_GETHRTIME)
// #pragma message "GetRealTime: gethrtime"
// Solaris and HP-UX
current_time = (uint64_t)gethrtime() / 1000;
#elif defined(OS_DARWIN)
// #pragma message "GetRealTime: mach_absolute_time"
// Mac OS X
// https://developer.apple.com/library/mac/qa/qa1398/_index.html
current_time = mach_absolute_time() * mach_timebase.numer / mach_timebase.denom / 1000;
#elif defined(OS_UNIX)
// #pragma message "GetRealTime: gettimeofday"
// Unix fallback
struct timeval tv;
gettimeofday (&tv, NULL);
current_time = (((uint64_t)(tv.tv_sec)) * 1000000LL) + ((uint64_t)(tv.tv_usec));
#elif defined(OS_WIN32)
// #pragma message "GetRealTime: GetTickCount"
// Future improvement: use GetTickCount64 in Windows Vista / Server 2008
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
// #pragma message "GetRealTime: time"
// Universal fallback
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) {
std::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 (std::multimap<uint64_t,EventableDescriptor*>::value_type (heartbeat, ed));
#else
Heartbeats.insert (std::make_pair (heartbeat, ed));
#endif
}
}
/******************************
EventMachine_t::ClearHeartbeat
******************************/
void EventMachine_t::ClearHeartbeat(uint64_t key, EventableDescriptor* ed)
{
std::multimap<uint64_t,EventableDescriptor*>::iterator it;
std::pair<std::multimap<uint64_t,EventableDescriptor*>::iterator,std::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()
{
while (RunOnce()) ;
}
/***********************
EventMachine_t::RunOnce
***********************/
bool EventMachine_t::RunOnce()
{
_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();
switch (Poller) {
case Poller_Epoll:
_RunEpollOnce();
break;
case Poller_Kqueue:
_RunKqueueOnce();
break;
case Poller_Default:
_RunSelectOnce();
break;
}
_DispatchHeartbeats();
_CleanupSockets();
if (bTerminateSignalReceived)
return false;
return true;
}
#ifdef HAVE_EPOLL
typedef struct {
int epfd;
struct epoll_event *events;
int maxevents;
int timeout;
} epoll_args_t;
static void *nogvl_epoll_wait(void *args)
{
epoll_args_t *a = (epoll_args_t *)args;
return (void *) (uintptr_t) epoll_wait (a->epfd, a->events, a->maxevents, a->timeout);
}
#endif
/*****************************
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;
if ((ret = rb_wait_for_single_fd(epfd, RB_WAITFD_IN|RB_WAITFD_PRI, &tv)) < 1) {
if (ret == -1) {
assert(errno != EINVAL);
assert(errno != EBADF);
}
return;
}
epoll_args_t epoll_args = { epfd, epoll_events, MaxEvents, 0 };
s = (uintptr_t) rb_thread_call_without_gvl (nogvl_epoll_wait, &epoll_args, RUBY_UBF_IO, 0);
#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
}
#ifdef HAVE_KQUEUE
typedef struct {
int kqfd;
const struct kevent *changelist;
int nchanges;
struct kevent *eventlist;
int nevents;
const struct timespec *timeout;
} kevent_args_t;
static void *nogvl_kevent(void *args)
{
kevent_args_t *a = (kevent_args_t *)args;
return (void *) (uintptr_t) kevent (a->kqfd, a->changelist, a->nchanges, a->eventlist, a->nevents, a->timeout);
}
#endif
/******************************
EventMachine_t::_RunKqueueOnce
******************************/
#ifdef HAVE_KQUEUE
void EventMachine_t::_RunKqueueOnce()
{
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;
if ((ret = rb_wait_for_single_fd(kqfd, RB_WAITFD_IN|RB_WAITFD_PRI, &tv)) < 1) {
if (ret == -1) {
assert(errno != EINVAL);
assert(errno != EBADF);
}
return;
}
ts.tv_sec = ts.tv_nsec = 0;
kevent_args_t kevent_args = { kqfd, NULL, 0, Karray, MaxEvents, &ts };
k = (uintptr_t) rb_thread_call_without_gvl (nogvl_kevent, &kevent_args, RUBY_UBF_IO, 0);
#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
std::cerr << "Discarding unknown kqueue event " << ke->filter << std::endl;
break;
}
--k;
++ke;
}
#ifdef BUILD_FOR_RUBY
if (!rb_thread_alone()) {
rb_thread_schedule();
}
#endif
}
#else
void EventMachine_t::_RunKqueueOnce()
{
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()) {
std::multimap<uint64_t,EventableDescriptor*>::iterator heartbeats = Heartbeats.begin();
next_event = heartbeats->first;
}
if (!Timers.empty()) {
std::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 (Poller == Poller_Epoll) {
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
*********************************/
#ifdef HAVE_EPOLL
void EventMachine_t::_ModifyEpollEvent (EventableDescriptor *ed)
{
if (Poller == Poller_Epoll) {
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);
}
}
}
#else
void EventMachine_t::_ModifyEpollEvent (EventableDescriptor *ed UNUSED) { }
#endif
/**************************
SelectData_t::SelectData_t
**************************/
SelectData_t::SelectData_t()
{
maxsocket = 0;
rb_fd_init (&fdreads);
rb_fd_init (&fdwrites);
rb_fd_init (&fderrors);
}
SelectData_t::~SelectData_t()
{
rb_fd_term (&fdreads);
rb_fd_term (&fdwrites);
rb_fd_term (&fderrors);
}
/*********************
SelectData_t::_Select
*********************/
int SelectData_t::_Select()
{
return EmSelect (maxsocket + 1, &fdreads, &fdwrites, &fderrors, &tv);
}
void SelectData_t::_Clear()
{
maxsocket = 0;
rb_fd_zero (&fdreads);
rb_fd_zero (&fdwrites);
rb_fd_zero (&fderrors);
}
/******************************
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.
// Get ready for select()
SelectData->_Clear();
// 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.
rb_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);
SOCKET sd = ed->GetSocket();
if (ed->IsWatchOnly() && sd == INVALID_SOCKET)
continue;
assert (sd != INVALID_SOCKET);
if (ed->SelectForRead())
rb_fd_set (sd, &(SelectData->fdreads));
if (ed->SelectForWrite())
rb_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
*/
if (ed->IsConnectPending())
rb_fd_set (sd, &(SelectData->fderrors));
#endif
if (SelectData->maxsocket < sd)
SelectData->maxsocket = sd;
}