forked from eventmachine/eventmachine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventmachine.rb
1602 lines (1499 loc) · 60.5 KB
/
eventmachine.rb
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
if defined?(EventMachine.library_type) and EventMachine.library_type == :pure_ruby
# assume 'em/pure_ruby' was loaded already
elsif RUBY_PLATFORM =~ /java/
require 'java'
require 'jeventmachine'
else
begin
require 'rubyeventmachine'
rescue LoadError
warn "Unable to load the EventMachine C extension; To use the pure-ruby reactor, require 'em/pure_ruby'"
raise
end
end
require 'em/version'
require 'em/pool'
require 'em/deferrable'
require 'em/future'
require 'em/streamer'
require 'em/spawnable'
require 'em/processes'
require 'em/iterator'
require 'em/buftok'
require 'em/timers'
require 'em/protocols'
require 'em/connection'
require 'em/callback'
require 'em/queue'
require 'em/channel'
require 'em/file_watch'
require 'em/process_watch'
require 'em/tick_loop'
require 'em/resolver'
require 'em/completion'
require 'em/threaded_resource'
require 'shellwords'
require 'thread'
require 'resolv'
##
# Top-level EventMachine namespace. If you are looking for EventMachine examples, see {file:docs/GettingStarted.md EventMachine tutorial}.
#
# ## Key methods ##
# ### Starting and stopping the event loop ###
#
# * {EventMachine.run}
# * {EventMachine.stop_event_loop}
#
# ### Implementing clients ###
#
# * {EventMachine.connect}
#
# ### Implementing servers ###
#
# * {EventMachine.start_server}
#
# ### Working with timers ###
#
# * {EventMachine.add_timer}
# * {EventMachine.add_periodic_timer}
# * {EventMachine.cancel_timer}
#
# ### Working with blocking tasks ###
#
# * {EventMachine.defer}
# * {EventMachine.next_tick}
#
# ### Efficient proxying ###
#
# * {EventMachine.enable_proxy}
# * {EventMachine.disable_proxy}
module EventMachine
class << self
# Exposed to allow joining on the thread, when run in a multithreaded
# environment. Performing other actions on the thread has undefined
# semantics (read: a dangerous endevor).
#
# @return [Thread]
attr_reader :reactor_thread
end
@next_tick_mutex = Mutex.new
@reactor_running = false
@next_tick_queue = []
@tails = []
@threadpool = @threadqueue = @resultqueue = nil
@all_threads_spawned = false
# System errnos
# @private
ERRNOS = Errno::constants.grep(/^E/).inject(Hash.new(:unknown)) { |hash, name|
errno = Errno.__send__(:const_get, name)
hash[errno::Errno] = errno
hash
}
# Initializes and runs an event loop. This method only returns if code inside the block passed to this method
# calls {EventMachine.stop_event_loop}. The block is executed after initializing its internal event loop but *before* running the loop,
# therefore this block is the right place to call any code that needs event loop to run, for example, {EventMachine.start_server},
# {EventMachine.connect} or similar methods of libraries that use EventMachine under the hood
# (like `EventMachine::HttpRequest.new` or `AMQP.start`).
#
# Programs that are run for long periods of time (e.g. servers) usually start event loop by calling {EventMachine.run}, and let it
# run "forever". It's also possible to use {EventMachine.run} to make a single client-connection to a remote server,
# process the data flow from that single connection, and then call {EventMachine.stop_event_loop} to stop, in other words,
# to run event loop for a short period of time (necessary to complete some operation) and then shut it down.
#
# Once event loop is running, it is perfectly possible to start multiple servers and clients simultaneously: content-aware
# proxies like [Proxymachine](https://github.com/mojombo/proxymachine) do just that.
#
# ## Using EventMachine with Ruby on Rails and other Web application frameworks
#
# Standalone applications often run event loop on the main thread, thus blocking for their entire lifespan. In case of Web applications,
# if you are running an EventMachine-based app server such as [Thin](http://code.macournoyer.com/thin/) or [Goliath](https://github.com/postrank-labs/goliath/),
# they start event loop for you. Servers like Unicorn, Apache Passenger or Mongrel occupy main Ruby thread to serve HTTP(S) requests. This means
# that calling {EventMachine.run} on the same thread is not an option (it will result in Web server never binding to the socket).
# In that case, start event loop in a separate thread as demonstrated below.
#
#
# @example Starting EventMachine event loop in the current thread to run the "Hello, world"-like Echo server example
#
# #!/usr/bin/env ruby
#
# require 'rubygems' # or use Bundler.setup
# require 'eventmachine'
#
# class EchoServer < EM::Connection
# def receive_data(data)
# send_data(data)
# end
# end
#
# EventMachine.run do
# EventMachine.start_server("0.0.0.0", 10000, EchoServer)
# end
#
#
# @example Starting EventMachine event loop in a separate thread
#
# # doesn't block current thread, can be used with Ruby on Rails, Sinatra, Merb, Rack
# # and any other application server that occupies main Ruby thread.
# Thread.new { EventMachine.run }
#
#
# @note This method blocks calling thread. If you need to start EventMachine event loop from a Web app
# running on a non event-driven server (Unicorn, Apache Passenger, Mongrel), do it in a separate thread like demonstrated
# in one of the examples.
# @see file:docs/GettingStarted.md Getting started with EventMachine
# @see EventMachine.stop_event_loop
def self.run blk=nil, tail=nil, &block
# Obsoleted the use_threads mechanism.
# 25Nov06: Added the begin/ensure block. We need to be sure that release_machine
# gets called even if an exception gets thrown within any of the user code
# that the event loop runs. The best way to see this is to run a unit
# test with two functions, each of which calls {EventMachine.run} and each of
# which throws something inside of #run. Without the ensure, the second test
# will start without release_machine being called and will immediately throw
#
if @reactor_running and @reactor_pid != Process.pid
# Reactor was started in a different parent, meaning we have forked.
# Clean up reactor state so a new reactor boots up in this child.
stop_event_loop
release_machine
cleanup_machine
@reactor_running = false
end
tail and @tails.unshift(tail)
if reactor_running?
(b = blk || block) and b.call # next_tick(b)
else
@conns = {}
@acceptors = {}
@timers = {}
@wrapped_exception = nil
@next_tick_queue ||= []
@tails ||= []
begin
initialize_event_machine
@reactor_pid = Process.pid
@reactor_thread = Thread.current
@reactor_running = true
(b = blk || block) and add_timer(0, b)
if @next_tick_queue && !@next_tick_queue.empty?
add_timer(0) { signal_loopbreak }
end
# Rubinius needs to come back into "Ruby space" for GC to work,
# so we'll crank the machine here.
if defined?(RUBY_ENGINE) && RUBY_ENGINE == "rbx"
while run_machine_once; end
else
run_machine
end
ensure
until @tails.empty?
@tails.pop.call
end
release_machine
cleanup_machine
@reactor_running = false
@reactor_thread = nil
end
raise @wrapped_exception if @wrapped_exception
end
end
# Sugars a common use case. Will pass the given block to #run, but will terminate
# the reactor loop and exit the function as soon as the code in the block completes.
# (Normally, {EventMachine.run} keeps running indefinitely, even after the block supplied to it
# finishes running, until user code calls {EventMachine.stop})
#
def self.run_block &block
pr = proc {
block.call
EventMachine::stop
}
run(&pr)
end
# @return [Boolean] true if the calling thread is the same thread as the reactor.
def self.reactor_thread?
Thread.current == @reactor_thread
end
# Runs the given callback on the reactor thread, or immediately if called
# from the reactor thread. Accepts the same arguments as {EventMachine::Callback}
def self.schedule(*a, &b)
cb = Callback(*a, &b)
if reactor_running? && reactor_thread?
cb.call
else
next_tick { cb.call }
end
end
# Forks a new process, properly stops the reactor and then calls {EventMachine.run} inside of it again, passing your block.
def self.fork_reactor &block
# This implementation is subject to change, especially if we clean up the relationship
# of EM#run to @reactor_running.
# Original patch by Aman Gupta.
#
Kernel.fork do
if reactor_running?
stop_event_loop
release_machine
cleanup_machine
@reactor_running = false
@reactor_thread = nil
end
run block
end
end
# Clean up Ruby space following a release_machine
def self.cleanup_machine
if @threadpool && [email protected]?
# Tell the threads to stop
@threadpool.each { |t| t.exit }
# Join the threads or bump the stragglers one more time
@threadpool.each { |t| t.join 0.01 || t.exit }
end
@threadpool = nil
@threadqueue = nil
@resultqueue = nil
@all_threads_spawned = false
@next_tick_queue = []
end
# Adds a block to call as the reactor is shutting down.
#
# These callbacks are called in the _reverse_ order to which they are added.
#
# @example Scheduling operations to be run when EventMachine event loop is stopped
#
# EventMachine.run do
# EventMachine.add_shutdown_hook { puts "b" }
# EventMachine.add_shutdown_hook { puts "a" }
# EventMachine.stop
# end
#
# # Outputs:
# # a
# # b
#
def self.add_shutdown_hook &block
@tails << block
end
# Adds a one-shot timer to the event loop.
# Call it with one or two parameters. The first parameters is a delay-time
# expressed in *seconds* (not milliseconds). The second parameter, if
# present, must be an object that responds to :call. If 2nd parameter is not given, then you
# can also simply pass a block to the method call.
#
# This method may be called from the block passed to {EventMachine.run}
# or from any callback method. It schedules execution of the proc or block
# passed to it, after the passage of an interval of time equal to
# *at least* the number of seconds specified in the first parameter to
# the call.
#
# {EventMachine.add_timer} is a non-blocking method. Callbacks can and will
# be called during the interval of time that the timer is in effect.
# There is no built-in limit to the number of timers that can be outstanding at
# any given time.
#
# @example Setting a one-shot timer with EventMachine
#
# EventMachine.run {
# puts "Starting the run now: #{Time.now}"
# EventMachine.add_timer 5, proc { puts "Executing timer event: #{Time.now}" }
# EventMachine.add_timer(10) { puts "Executing timer event: #{Time.now}" }
# }
#
# @param [Integer] delay Delay in seconds
# @see EventMachine::Timer
# @see EventMachine.add_periodic_timer
def self.add_timer *args, &block
interval = args.shift
code = args.shift || block
if code
# check too many timers!
s = add_oneshot_timer((interval.to_f * 1000).to_i)
@timers[s] = code
s
end
end
# Adds a periodic timer to the event loop.
# It takes the same parameters as the one-shot timer method, {EventMachine.add_timer}.
# This method schedules execution of the given block repeatedly, at intervals
# of time *at least* as great as the number of seconds given in the first
# parameter to the call.
#
# @example Write a dollar-sign to stderr every five seconds, without blocking
#
# EventMachine.run {
# EventMachine.add_periodic_timer(5) { $stderr.write "$" }
# }
#
# @param [Integer] delay Delay in seconds
#
# @see EventMachine::PeriodicTimer
# @see EventMachine.add_timer
#
def self.add_periodic_timer *args, &block
interval = args.shift
code = args.shift || block
EventMachine::PeriodicTimer.new(interval, code)
end
# Cancel a timer (can be a callback or an {EventMachine::Timer} instance).
#
# @param [#cancel, #call] timer_or_sig A timer to cancel
# @see EventMachine::Timer#cancel
def self.cancel_timer timer_or_sig
if timer_or_sig.respond_to? :cancel
timer_or_sig.cancel
else
@timers[timer_or_sig] = false if @timers.has_key?(timer_or_sig)
end
end
# Causes the processing loop to stop executing, which will cause all open connections and accepting servers
# to be run down and closed. Connection termination callbacks added using {EventMachine.add_shutdown_hook}
# will be called as part of running this method.
#
# When all of this processing is complete, the call to {EventMachine.run} which started the processing loop
# will return and program flow will resume from the statement following {EventMachine.run} call.
#
# @example Stopping a running EventMachine event loop
#
# require 'rubygems'
# require 'eventmachine'
#
# module Redmond
# def post_init
# puts "We're sending a dumb HTTP request to the remote peer."
# send_data "GET / HTTP/1.1\r\nHost: www.microsoft.com\r\n\r\n"
# end
#
# def receive_data data
# puts "We received #{data.length} bytes from the remote peer."
# puts "We're going to stop the event loop now."
# EventMachine::stop_event_loop
# end
#
# def unbind
# puts "A connection has terminated."
# end
# end
#
# puts "We're starting the event loop now."
# EventMachine.run {
# EventMachine.connect "www.microsoft.com", 80, Redmond
# }
# puts "The event loop has stopped."
#
# # This program will produce approximately the following output:
# #
# # We're starting the event loop now.
# # We're sending a dumb HTTP request to the remote peer.
# # We received 1440 bytes from the remote peer.
# # We're going to stop the event loop now.
# # A connection has terminated.
# # The event loop has stopped.
#
#
def self.stop_event_loop
EventMachine::stop
end
# Initiates a TCP server (socket acceptor) on the specified IP address and port.
#
# The IP address must be valid on the machine where the program
# runs, and the process must be privileged enough to listen
# on the specified port (on Unix-like systems, superuser privileges
# are usually required to listen on any port lower than 1024).
# Only one listener may be running on any given address/port
# combination. start_server will fail if the given address and port
# are already listening on the machine, either because of a prior call
# to {.start_server} or some unrelated process running on the machine.
# If {.start_server} succeeds, the new network listener becomes active
# immediately and starts accepting connections from remote peers,
# and these connections generate callback events that are processed
# by the code specified in the handler parameter to {.start_server}.
#
# The optional handler which is passed to this method is the key
# to EventMachine's ability to handle particular network protocols.
# The handler parameter passed to start_server must be a Ruby Module
# that you must define. When the network server that is started by
# start_server accepts a new connection, it instantiates a new
# object of an anonymous class that is inherited from {EventMachine::Connection},
# *into which your handler module have been included*. Arguments passed into start_server
# after the class name are passed into the constructor during the instantiation.
#
# Your handler module may override any of the methods in {EventMachine::Connection},
# such as {EventMachine::Connection#receive_data}, in order to implement the specific behavior
# of the network protocol.
#
# Callbacks invoked in response to network events *always* take place
# within the execution context of the object derived from {EventMachine::Connection}
# extended by your handler module. There is one object per connection, and
# all of the callbacks invoked for a particular connection take the form
# of instance methods called against the corresponding {EventMachine::Connection}
# object. Therefore, you are free to define whatever instance variables you
# wish, in order to contain the per-connection state required by the network protocol you are
# implementing.
#
# {EventMachine.start_server} is usually called inside the block passed to {EventMachine.run},
# but it can be called from any EventMachine callback. {EventMachine.start_server} will fail
# unless the EventMachine event loop is currently running (which is why
# it's often called in the block suppled to {EventMachine.run}).
#
# You may call start_server any number of times to start up network
# listeners on different address/port combinations. The servers will
# all run simultaneously. More interestingly, each individual call to start_server
# can specify a different handler module and thus implement a different
# network protocol from all the others.
#
# @example
#
# require 'rubygems'
# require 'eventmachine'
#
# # Here is an example of a server that counts lines of input from the remote
# # peer and sends back the total number of lines received, after each line.
# # Try the example with more than one client connection opened via telnet,
# # and you will see that the line count increments independently on each
# # of the client connections. Also very important to note, is that the
# # handler for the receive_data function, which our handler redefines, may
# # not assume that the data it receives observes any kind of message boundaries.
# # Also, to use this example, be sure to change the server and port parameters
# # to the start_server call to values appropriate for your environment.
# module LineCounter
# MaxLinesPerConnection = 10
#
# def post_init
# puts "Received a new connection"
# @data_received = ""
# @line_count = 0
# end
#
# def receive_data data
# @data_received << data
# while @data_received.slice!( /^[^\n]*[\n]/m )
# @line_count += 1
# send_data "received #{@line_count} lines so far\r\n"
# @line_count == MaxLinesPerConnection and close_connection_after_writing
# end
# end
# end
#
# EventMachine.run {
# host, port = "192.168.0.100", 8090
# EventMachine.start_server host, port, LineCounter
# puts "Now accepting connections on address #{host}, port #{port}..."
# EventMachine.add_periodic_timer(10) { $stderr.write "*" }
# }
#
# @param [String] server Host to bind to.
# @param [Integer] port Port to bind to.
# @param [Module, Class] handler A module or class that implements connection callbacks
#
# @note Don't forget that in order to bind to ports < 1024 on Linux, *BSD and Mac OS X your process must have superuser privileges.
#
# @see file:docs/GettingStarted.md EventMachine tutorial
# @see EventMachine.stop_server
def self.start_server server, port=nil, handler=nil, *args, &block
begin
port = Integer(port)
rescue ArgumentError, TypeError
# there was no port, so server must be a unix domain socket
# the port argument is actually the handler, and the handler is one of the args
args.unshift handler if handler
handler = port
port = nil
end if port
klass = klass_from_handler(Connection, handler, *args)
s = if port
start_tcp_server server, port
else
start_unix_server server
end
@acceptors[s] = [klass,args,block]
s
end
# Attach to an existing socket's file descriptor. The socket may have been
# started with {EventMachine.start_server}.
def self.attach_server sock, handler=nil, *args, &block
klass = klass_from_handler(Connection, handler, *args)
sd = sock.respond_to?(:fileno) ? sock.fileno : sock
s = attach_sd(sd)
@acceptors[s] = [klass,args,block,sock]
s
end
# Stop a TCP server socket that was started with {EventMachine.start_server}.
# @see EventMachine.start_server
def self.stop_server signature
EventMachine::stop_tcp_server signature
end
# Start a Unix-domain server.
#
# Note that this is an alias for {EventMachine.start_server}, which can be used to start both
# TCP and Unix-domain servers.
#
# @see EventMachine.start_server
def self.start_unix_domain_server filename, *args, &block
start_server filename, *args, &block
end
# Initiates a TCP connection to a remote server and sets up event handling for the connection.
# {EventMachine.connect} requires event loop to be running (see {EventMachine.run}).
#
# {EventMachine.connect} takes the IP address (or hostname) and
# port of the remote server you want to connect to.
# It also takes an optional handler (a module or a subclass of {EventMachine::Connection}) which you must define, that
# contains the callbacks that will be invoked by the event loop on behalf of the connection.
#
# Learn more about connection lifecycle callbacks in the {file:docs/GettingStarted.md EventMachine tutorial} and
# {file:docs/ConnectionLifecycleCallbacks.md Connection lifecycle guide}.
#
#
# @example
#
# # Here's a program which connects to a web server, sends a naive
# # request, parses the HTTP header of the response, and then
# # (antisocially) ends the event loop, which automatically drops the connection
# # (and incidentally calls the connection's unbind method).
# module DumbHttpClient
# def post_init
# send_data "GET / HTTP/1.1\r\nHost: _\r\n\r\n"
# @data = ""
# @parsed = false
# end
#
# def receive_data data
# @data << data
# if !@parsed and @data =~ /[\n][\r]*[\n]/m
# @parsed = true
# puts "RECEIVED HTTP HEADER:"
# $`.each {|line| puts ">>> #{line}" }
#
# puts "Now we'll terminate the loop, which will also close the connection"
# EventMachine::stop_event_loop
# end
# end
#
# def unbind
# puts "A connection has terminated"
# end
# end
#
# EventMachine.run {
# EventMachine.connect "www.bayshorenetworks.com", 80, DumbHttpClient
# }
# puts "The event loop has ended"
#
#
# @example Defining protocol handler as a class
#
# class MyProtocolHandler < EventMachine::Connection
# def initialize *args
# super
# # whatever else you want to do here
# end
#
# # ...
# end
#
#
# @param [String] server Host to connect to
# @param [Integer] port Port to connect to
# @param [Module, Class] handler A module or class that implements connection lifecycle callbacks
#
# @see EventMachine.start_server
# @see file:docs/GettingStarted.md EventMachine tutorial
def self.connect server, port=nil, handler=nil, *args, &blk
# EventMachine::connect initiates a TCP connection to a remote
# server and sets up event-handling for the connection.
# It internally creates an object that should not be handled
# by the caller. HOWEVER, it's often convenient to get the
# object to set up interfacing to other objects in the system.
# We return the newly-created anonymous-class object to the caller.
# It's expected that a considerable amount of code will depend
# on this behavior, so don't change it.
#
# Ok, added support for a user-defined block, 13Apr06.
# This leads us to an interesting choice because of the
# presence of the post_init call, which happens in the
# initialize method of the new object. We call the user's
# block and pass the new object to it. This is a great
# way to do protocol-specific initiation. It happens
# AFTER post_init has been called on the object, which I
# certainly hope is the right choice.
# Don't change this lightly, because accepted connections
# are different from connected ones and we don't want
# to have them behave differently with respect to post_init
# if at all possible.
bind_connect nil, nil, server, port, handler, *args, &blk
end
# This method is like {EventMachine.connect}, but allows for a local address/port
# to bind the connection to.
#
# @see EventMachine.connect
def self.bind_connect bind_addr, bind_port, server, port=nil, handler=nil, *args
begin
port = Integer(port)
rescue ArgumentError, TypeError
# there was no port, so server must be a unix domain socket
# the port argument is actually the handler, and the handler is one of the args
args.unshift handler if handler
handler = port
port = nil
end if port
klass = klass_from_handler(Connection, handler, *args)
s = if port
if bind_addr
bind_connect_server bind_addr, bind_port.to_i, server, port
else
connect_server server, port
end
else
connect_unix_server server
end
c = klass.new s, *args
@conns[s] = c
block_given? and yield c
c
end
# {EventMachine.watch} registers a given file descriptor or IO object with the eventloop. The
# file descriptor will not be modified (it will remain blocking or non-blocking).
#
# The eventloop can be used to process readable and writable events on the file descriptor, using
# {EventMachine::Connection#notify_readable=} and {EventMachine::Connection#notify_writable=}
#
# {EventMachine::Connection#notify_readable?} and {EventMachine::Connection#notify_writable?} can be used
# to check what events are enabled on the connection.
#
# To detach the file descriptor, use {EventMachine::Connection#detach}
#
# @example
#
# module SimpleHttpClient
# def notify_readable
# header = @io.readline
#
# if header == "\r\n"
# # detach returns the file descriptor number (fd == @io.fileno)
# fd = detach
# end
# rescue EOFError
# detach
# end
#
# def unbind
# EM.next_tick do
# # socket is detached from the eventloop, but still open
# data = @io.read
# end
# end
# end
#
# EventMachine.run {
# sock = TCPSocket.new('site.com', 80)
# sock.write("GET / HTTP/1.0\r\n\r\n")
# conn = EventMachine.watch(sock, SimpleHttpClient)
# conn.notify_readable = true
# }
#
# @author Riham Aldakkak (eSpace Technologies)
def EventMachine::watch io, handler=nil, *args, &blk
attach_io io, true, handler, *args, &blk
end
# Attaches an IO object or file descriptor to the eventloop as a regular connection.
# The file descriptor will be set as non-blocking, and EventMachine will process
# receive_data and send_data events on it as it would for any other connection.
#
# To watch a fd instead, use {EventMachine.watch}, which will not alter the state of the socket
# and fire notify_readable and notify_writable events instead.
def EventMachine::attach io, handler=nil, *args, &blk
attach_io io, false, handler, *args, &blk
end
# @private
def EventMachine::attach_io io, watch_mode, handler=nil, *args
klass = klass_from_handler(Connection, handler, *args)
if !watch_mode and klass.public_instance_methods.any?{|m| [:notify_readable, :notify_writable].include? m.to_sym }
raise ArgumentError, "notify_readable/writable with EM.attach is not supported. Use EM.watch(io){ |c| c.notify_readable = true }"
end
if io.respond_to?(:fileno)
# getDescriptorByFileno deprecated in JRuby 1.7.x, removed in JRuby 9000
if defined?(JRuby) && JRuby.runtime.respond_to?(:getDescriptorByFileno)
fd = JRuby.runtime.getDescriptorByFileno(io.fileno).getChannel
else
fd = io.fileno
end
else
fd = io
end
s = attach_fd fd, watch_mode
c = klass.new s, *args
c.instance_variable_set(:@io, io)
c.instance_variable_set(:@watch_mode, watch_mode)
c.instance_variable_set(:@fd, fd)
@conns[s] = c
block_given? and yield c
c
end
# Connect to a given host/port and re-use the provided {EventMachine::Connection} instance.
# Consider also {EventMachine::Connection#reconnect}.
#
# @see EventMachine::Connection#reconnect
def self.reconnect server, port, handler
# Observe, the test for already-connected FAILS if we call a reconnect inside post_init,
# because we haven't set up the connection in @conns by that point.
# RESIST THE TEMPTATION to "fix" this problem by redefining the behavior of post_init.
#
# Changed 22Nov06: if called on an already-connected handler, just return the
# handler and do nothing more. Originally this condition raised an exception.
# We may want to change it yet again and call the block, if any.
raise "invalid handler" unless handler.respond_to?(:connection_completed)
#raise "still connected" if @conns.has_key?(handler.signature)
return handler if @conns.has_key?(handler.signature)
s = if port
connect_server server, port
else
connect_unix_server server
end
handler.signature = s
@conns[s] = handler
block_given? and yield handler
handler
end
# Make a connection to a Unix-domain socket. This method is simply an alias for {.connect},
# which can connect to both TCP and Unix-domain sockets. Make sure that your process has sufficient
# permissions to open the socket it is given.
#
# @param [String] socketname Unix domain socket (local fully-qualified path) you want to connect to.
#
# @note UNIX sockets, as the name suggests, are not available on Microsoft Windows.
def self.connect_unix_domain socketname, *args, &blk
connect socketname, *args, &blk
end
# Used for UDP-based protocols. Its usage is similar to that of {EventMachine.start_server}.
#
# This method will create a new UDP (datagram) socket and
# bind it to the address and port that you specify.
# The normal callbacks (see {EventMachine.start_server}) will
# be called as events of interest occur on the newly-created
# socket, but there are some differences in how they behave.
#
# {Connection#receive_data} will be called when a datagram packet
# is received on the socket, but unlike TCP sockets, the message
# boundaries of the received data will be respected. In other words,
# if the remote peer sent you a datagram of a particular size,
# you may rely on {Connection#receive_data} to give you the
# exact data in the packet, with the original data length.
# Also observe that Connection#receive_data may be called with a
# *zero-length* data payload, since empty datagrams are permitted in UDP.
#
# {Connection#send_data} is available with UDP packets as with TCP,
# but there is an important difference. Because UDP communications
# are *connectionless*, there is no implicit recipient for the packets you
# send. Ordinarily you must specify the recipient for each packet you send.
# However, EventMachine provides for the typical pattern of receiving a UDP datagram
# from a remote peer, performing some operation, and then sending
# one or more packets in response to the same remote peer.
# To support this model easily, just use {Connection#send_data}
# in the code that you supply for {Connection#receive_data}.
#
# EventMachine will provide an implicit return address for any messages sent to
# {Connection#send_data} within the context of a {Connection#receive_data} callback,
# and your response will automatically go to the correct remote peer.
#
# Observe that the port number that you supply to {EventMachine.open_datagram_socket}
# may be zero. In this case, EventMachine will create a UDP socket
# that is bound to an [ephemeral port](http://en.wikipedia.org/wiki/Ephemeral_port).
# This is not appropriate for servers that must publish a well-known
# port to which remote peers may send datagrams. But it can be useful
# for clients that send datagrams to other servers.
# If you do this, you will receive any responses from the remote
# servers through the normal {Connection#receive_data} callback.
# Observe that you will probably have issues with firewalls blocking
# the ephemeral port numbers, so this technique is most appropriate for LANs.
#
# If you wish to send datagrams to arbitrary remote peers (not
# necessarily ones that have sent data to which you are responding),
# then see {Connection#send_datagram}.
#
# DO NOT call send_data from a datagram socket outside of a {Connection#receive_data} method. Use {Connection#send_datagram}.
# If you do use {Connection#send_data} outside of a {Connection#receive_data} method, you'll get a confusing error
# because there is no "peer," as #send_data requires (inside of {EventMachine::Connection#receive_data},
# {EventMachine::Connection#send_data} "fakes" the peer as described above).
#
# @param [String] address IP address
# @param [String] port Port
# @param [Class, Module] handler A class or a module that implements connection lifecycle callbacks.
def self.open_datagram_socket address, port, handler=nil, *args
# Replaced the implementation on 01Oct06. Thanks to Tobias Gustafsson for pointing
# out that this originally did not take a class but only a module.
klass = klass_from_handler(Connection, handler, *args)
s = open_udp_socket address, port.to_i
c = klass.new s, *args
@conns[s] = c
block_given? and yield c
c
end
# For advanced users. This function sets the default timer granularity, which by default is
# slightly smaller than 100 milliseconds. Call this function to set a higher or lower granularity.
# The function affects the behavior of {EventMachine.add_timer} and {EventMachine.add_periodic_timer}.
# Most applications will not need to call this function.
#
# Avoid setting the quantum to very low values because that may reduce performance under some extreme conditions.
# We recommend that you not use values lower than 10.
#
# This method only can be used if event loop is running.
#
# @param [Integer] mills New timer granularity, in milliseconds
#
# @see EventMachine.add_timer
# @see EventMachine.add_periodic_timer
# @see EventMachine::Timer
# @see EventMachine.run
def self.set_quantum mills
set_timer_quantum mills.to_i
end
# Sets the maximum number of timers and periodic timers that may be outstanding at any
# given time. You only need to call {.set_max_timers} if you need more than the default
# number of timers, which on most platforms is 1000.
#
# @note This method has to be used *before* event loop is started.
#
# @param [Integer] ct Maximum number of timers that may be outstanding at any given time
#
# @see EventMachine.add_timer
# @see EventMachine.add_periodic_timer
# @see EventMachine::Timer
def self.set_max_timers ct
set_max_timer_count ct
end
# Gets the current maximum number of allowed timers
#
# @return [Integer] Maximum number of timers that may be outstanding at any given time
def self.get_max_timers
get_max_timer_count
end
# Returns the total number of connections (file descriptors) currently held by the reactor.
# Note that a tick must pass after the 'initiation' of a connection for this number to increment.
# It's usually accurate, but don't rely on the exact precision of this number unless you really know EM internals.
#
# @example
#
# EventMachine.run {
# EventMachine.connect("rubyeventmachine.com", 80)
# # count will be 0 in this case, because connection is not
# # established yet
# count = EventMachine.connection_count
# }
#
#
# @example
#
# EventMachine.run {
# EventMachine.connect("rubyeventmachine.com", 80)
#
# EventMachine.next_tick {
# # In this example, count will be 1 since the connection has been established in
# # the next loop of the reactor.
# count = EventMachine.connection_count
# }
# }
#
# @return [Integer] Number of connections currently held by the reactor.
def self.connection_count
self.get_connection_count
end
# The is the responder for the loopback-signalled event.
# It can be fired either by code running on a separate thread ({EventMachine.defer}) or on
# the main thread ({EventMachine.next_tick}).
# It will often happen that a next_tick handler will reschedule itself. We
# consume a copy of the tick queue so that tick events scheduled by tick events
# have to wait for the next pass through the reactor core.
#
# @private
def self.run_deferred_callbacks
until (@resultqueue ||= []).empty?
result,cback = @resultqueue.pop
cback.call result if cback
end
# Capture the size at the start of this tick...
size = @next_tick_mutex.synchronize { @next_tick_queue.size }
size.times do |i|
callback = @next_tick_mutex.synchronize { @next_tick_queue.shift }
begin
callback.call
rescue
exception_raised = true
raise
ensure
# This is a little nasty. The problem is, if an exception occurs during
# the callback, then we need to send a signal to the reactor to actually
# do some work during the next_tick. The only mechanism we have from the
# ruby side is next_tick itself, although ideally, we'd just drop a byte
# on the loopback descriptor.
next_tick {} if exception_raised
end
end
end
# EventMachine.defer is used for integrating blocking operations into EventMachine's control flow.
# The action of {.defer} is to take the block specified in the first parameter (the "operation")
# and schedule it for asynchronous execution on an internal thread pool maintained by EventMachine.
# When the operation completes, it will pass the result computed by the block (if any) back to the
# EventMachine reactor. Then, EventMachine calls the block specified in the second parameter to
# {.defer} (the "callback"), as part of its normal event handling loop. The result computed by the