eventmachine-with-ipv6 1.0.0.beta.4.ipv6.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (164) hide show
  1. data/.gitignore +21 -0
  2. data/.yardopts +7 -0
  3. data/FORK.md +47 -0
  4. data/GNU +281 -0
  5. data/Gemfile +3 -0
  6. data/LICENSE +60 -0
  7. data/README.md +109 -0
  8. data/Rakefile +20 -0
  9. data/docs/DocumentationGuidesIndex.md +27 -0
  10. data/docs/GettingStarted.md +521 -0
  11. data/docs/old/ChangeLog +211 -0
  12. data/docs/old/DEFERRABLES +246 -0
  13. data/docs/old/EPOLL +141 -0
  14. data/docs/old/INSTALL +13 -0
  15. data/docs/old/KEYBOARD +42 -0
  16. data/docs/old/LEGAL +25 -0
  17. data/docs/old/LIGHTWEIGHT_CONCURRENCY +130 -0
  18. data/docs/old/PURE_RUBY +75 -0
  19. data/docs/old/RELEASE_NOTES +94 -0
  20. data/docs/old/SMTP +4 -0
  21. data/docs/old/SPAWNED_PROCESSES +148 -0
  22. data/docs/old/TODO +8 -0
  23. data/eventmachine.gemspec +50 -0
  24. data/examples/guides/getting_started/01_eventmachine_echo_server.rb +18 -0
  25. data/examples/guides/getting_started/02_eventmachine_echo_server_that_recognizes_exit_command.rb +22 -0
  26. data/examples/guides/getting_started/03_simple_chat_server.rb +149 -0
  27. data/examples/guides/getting_started/04_simple_chat_server_step_one.rb +27 -0
  28. data/examples/guides/getting_started/05_simple_chat_server_step_two.rb +43 -0
  29. data/examples/guides/getting_started/06_simple_chat_server_step_three.rb +98 -0
  30. data/examples/guides/getting_started/07_simple_chat_server_step_four.rb +121 -0
  31. data/examples/guides/getting_started/08_simple_chat_server_step_five.rb +141 -0
  32. data/examples/old/ex_channel.rb +43 -0
  33. data/examples/old/ex_queue.rb +2 -0
  34. data/examples/old/ex_tick_loop_array.rb +15 -0
  35. data/examples/old/ex_tick_loop_counter.rb +32 -0
  36. data/examples/old/helper.rb +2 -0
  37. data/ext/binder.cpp +124 -0
  38. data/ext/binder.h +46 -0
  39. data/ext/cmain.cpp +858 -0
  40. data/ext/ed.cpp +1992 -0
  41. data/ext/ed.h +423 -0
  42. data/ext/em.cpp +2358 -0
  43. data/ext/em.h +245 -0
  44. data/ext/eventmachine.h +127 -0
  45. data/ext/extconf.rb +166 -0
  46. data/ext/fastfilereader/extconf.rb +94 -0
  47. data/ext/fastfilereader/mapper.cpp +214 -0
  48. data/ext/fastfilereader/mapper.h +59 -0
  49. data/ext/fastfilereader/rubymain.cpp +127 -0
  50. data/ext/kb.cpp +79 -0
  51. data/ext/page.cpp +107 -0
  52. data/ext/page.h +51 -0
  53. data/ext/pipe.cpp +347 -0
  54. data/ext/project.h +155 -0
  55. data/ext/rubymain.cpp +1280 -0
  56. data/ext/ssl.cpp +468 -0
  57. data/ext/ssl.h +94 -0
  58. data/java/.classpath +8 -0
  59. data/java/.project +17 -0
  60. data/java/src/com/rubyeventmachine/EmReactor.java +571 -0
  61. data/java/src/com/rubyeventmachine/EmReactorException.java +40 -0
  62. data/java/src/com/rubyeventmachine/EventableChannel.java +69 -0
  63. data/java/src/com/rubyeventmachine/EventableDatagramChannel.java +189 -0
  64. data/java/src/com/rubyeventmachine/EventableSocketChannel.java +364 -0
  65. data/lib/em/buftok.rb +110 -0
  66. data/lib/em/callback.rb +58 -0
  67. data/lib/em/channel.rb +64 -0
  68. data/lib/em/completion.rb +304 -0
  69. data/lib/em/connection.rb +728 -0
  70. data/lib/em/deferrable.rb +210 -0
  71. data/lib/em/deferrable/pool.rb +2 -0
  72. data/lib/em/file_watch.rb +73 -0
  73. data/lib/em/future.rb +61 -0
  74. data/lib/em/iterator.rb +270 -0
  75. data/lib/em/messages.rb +66 -0
  76. data/lib/em/pool.rb +151 -0
  77. data/lib/em/process_watch.rb +45 -0
  78. data/lib/em/processes.rb +123 -0
  79. data/lib/em/protocols.rb +36 -0
  80. data/lib/em/protocols/header_and_content.rb +138 -0
  81. data/lib/em/protocols/httpclient.rb +279 -0
  82. data/lib/em/protocols/httpclient2.rb +600 -0
  83. data/lib/em/protocols/line_and_text.rb +125 -0
  84. data/lib/em/protocols/line_protocol.rb +29 -0
  85. data/lib/em/protocols/linetext2.rb +161 -0
  86. data/lib/em/protocols/memcache.rb +331 -0
  87. data/lib/em/protocols/object_protocol.rb +46 -0
  88. data/lib/em/protocols/postgres3.rb +246 -0
  89. data/lib/em/protocols/saslauth.rb +175 -0
  90. data/lib/em/protocols/smtpclient.rb +365 -0
  91. data/lib/em/protocols/smtpserver.rb +640 -0
  92. data/lib/em/protocols/socks4.rb +66 -0
  93. data/lib/em/protocols/stomp.rb +202 -0
  94. data/lib/em/protocols/tcptest.rb +54 -0
  95. data/lib/em/pure_ruby.rb +1017 -0
  96. data/lib/em/queue.rb +71 -0
  97. data/lib/em/resolver.rb +195 -0
  98. data/lib/em/spawnable.rb +84 -0
  99. data/lib/em/streamer.rb +118 -0
  100. data/lib/em/threaded_resource.rb +90 -0
  101. data/lib/em/tick_loop.rb +85 -0
  102. data/lib/em/timers.rb +61 -0
  103. data/lib/em/version.rb +3 -0
  104. data/lib/eventmachine.rb +1517 -0
  105. data/lib/jeventmachine.rb +279 -0
  106. data/rakelib/cpp.rake_example +77 -0
  107. data/rakelib/package.rake +98 -0
  108. data/rakelib/test.rake +8 -0
  109. data/tests/client.crt +31 -0
  110. data/tests/client.key +51 -0
  111. data/tests/em_test_helper.rb +64 -0
  112. data/tests/test_attach.rb +126 -0
  113. data/tests/test_basic.rb +294 -0
  114. data/tests/test_channel.rb +62 -0
  115. data/tests/test_completion.rb +177 -0
  116. data/tests/test_connection_count.rb +33 -0
  117. data/tests/test_defer.rb +18 -0
  118. data/tests/test_deferrable.rb +35 -0
  119. data/tests/test_epoll.rb +134 -0
  120. data/tests/test_error_handler.rb +38 -0
  121. data/tests/test_exc.rb +28 -0
  122. data/tests/test_file_watch.rb +65 -0
  123. data/tests/test_futures.rb +170 -0
  124. data/tests/test_get_sock_opt.rb +37 -0
  125. data/tests/test_handler_check.rb +35 -0
  126. data/tests/test_hc.rb +155 -0
  127. data/tests/test_httpclient.rb +190 -0
  128. data/tests/test_httpclient2.rb +128 -0
  129. data/tests/test_inactivity_timeout.rb +54 -0
  130. data/tests/test_ipv4.rb +128 -0
  131. data/tests/test_ipv6.rb +135 -0
  132. data/tests/test_kb.rb +34 -0
  133. data/tests/test_ltp.rb +138 -0
  134. data/tests/test_ltp2.rb +288 -0
  135. data/tests/test_next_tick.rb +104 -0
  136. data/tests/test_object_protocol.rb +36 -0
  137. data/tests/test_pause.rb +78 -0
  138. data/tests/test_pending_connect_timeout.rb +52 -0
  139. data/tests/test_pool.rb +194 -0
  140. data/tests/test_process_watch.rb +48 -0
  141. data/tests/test_processes.rb +133 -0
  142. data/tests/test_proxy_connection.rb +168 -0
  143. data/tests/test_pure.rb +88 -0
  144. data/tests/test_queue.rb +50 -0
  145. data/tests/test_resolver.rb +55 -0
  146. data/tests/test_running.rb +14 -0
  147. data/tests/test_sasl.rb +47 -0
  148. data/tests/test_send_file.rb +217 -0
  149. data/tests/test_servers.rb +33 -0
  150. data/tests/test_set_sock_opt.rb +41 -0
  151. data/tests/test_shutdown_hooks.rb +23 -0
  152. data/tests/test_smtpclient.rb +55 -0
  153. data/tests/test_smtpserver.rb +57 -0
  154. data/tests/test_spawn.rb +293 -0
  155. data/tests/test_ssl_args.rb +78 -0
  156. data/tests/test_ssl_methods.rb +48 -0
  157. data/tests/test_ssl_verify.rb +82 -0
  158. data/tests/test_threaded_resource.rb +53 -0
  159. data/tests/test_tick_loop.rb +59 -0
  160. data/tests/test_timers.rb +123 -0
  161. data/tests/test_ud.rb +8 -0
  162. data/tests/test_udp46.rb +54 -0
  163. data/tests/test_unbind_reason.rb +48 -0
  164. metadata +319 -0
@@ -0,0 +1,90 @@
1
+ module EventMachine
2
+ # = EventMachine::ThreadedResource
3
+ #
4
+ # A threaded resource is a "quick and dirty" wrapper around the concept of
5
+ # wiring up synchronous code into a standard EM::Pool. This is useful to keep
6
+ # interfaces coherent and provide a simple approach at "making an interface
7
+ # async-ish".
8
+ #
9
+ # General usage is to wrap libraries that do not support EventMachine, or to
10
+ # have a specific number of dedicated high-cpu worker resources.
11
+ #
12
+ # == Basic Usage example
13
+ #
14
+ # This example requires the cassandra gem. The cassandra gem contains an
15
+ # EventMachine interface, but it's sadly Fiber based and thus only works on
16
+ # 1.9. It also requires (potentially) complex stack switching logic to reach
17
+ # completion of nested operations. By contrast this approach provides a block
18
+ # in which normal synchronous code can occur, but makes no attempt to wire the
19
+ # IO into EventMachines C++ IO implementations, instead relying on the reactor
20
+ # pattern in rb_thread_select.
21
+ #
22
+ # cassandra_dispatcher = ThreadedResource.new do
23
+ # Cassandra.new('allthethings', '127.0.0.1:9160')
24
+ # end
25
+ #
26
+ # pool = EM::Pool.new
27
+ #
28
+ # pool.add cassandra_dispatcher
29
+ #
30
+ # # If we don't care about the result:
31
+ # pool.perform do |dispatcher|
32
+ # # The following blcok executes inside a dedicated thread, and should not
33
+ # # access EventMachine things:
34
+ # dispatcher.dispatch do |cassandra|
35
+ # cassandra.insert(:Things, '10', 'stuff' => 'things')
36
+ # end
37
+ # end
38
+ #
39
+ # # Example where we care about the result:
40
+ # pool.perform do |dispatcher|
41
+ # # The dispatch block is executed in the resources thread.
42
+ # completion = dispatcher.dispatch do |cassandra|
43
+ # cassandra.get(:Things, '10', 'stuff')
44
+ # end
45
+ #
46
+ # # This block will be yielded on the EM thread:
47
+ # completion.callback do |result|
48
+ # EM.do_something_with(result)
49
+ # end
50
+ #
51
+ # completion
52
+ # end
53
+ class ThreadedResource
54
+
55
+ # The block should return the resource that will be yielded in a dispatch.
56
+ def initialize
57
+ @resource = yield
58
+
59
+ @running = true
60
+ @queue = ::Queue.new
61
+ @thread = Thread.new do
62
+ @queue.pop.call while @running
63
+ end
64
+ end
65
+
66
+ # Called on the EM thread, generally in a perform block to return a
67
+ # completion for the work.
68
+ def dispatch
69
+ completion = EM::Completion.new
70
+ @queue << lambda do
71
+ begin
72
+ result = yield @resource
73
+ completion.succeed result
74
+ rescue Exception => e
75
+ completion.fail e
76
+ end
77
+ end
78
+ completion
79
+ end
80
+
81
+ # Kill the internal thread. should only be used to cleanup - generally
82
+ # only required for tests.
83
+ def shutdown
84
+ @running = false
85
+ @queue << lambda {}
86
+ @thread.join
87
+ end
88
+
89
+ end
90
+ end
@@ -0,0 +1,85 @@
1
+ module EventMachine
2
+ # Creates and immediately starts an EventMachine::TickLoop
3
+ def self.tick_loop(*a, &b)
4
+ TickLoop.new(*a, &b).start
5
+ end
6
+
7
+ # A TickLoop is useful when one needs to distribute amounts of work
8
+ # throughout ticks in order to maintain response times. It is also useful for
9
+ # simple repeated checks and metrics.
10
+ #
11
+ # # Here we run through an array one item per tick until it is empty,
12
+ # # printing each element.
13
+ # # When the array is empty, we return :stop from the callback, and the
14
+ # # loop will terminate.
15
+ # # When the loop terminates, the on_stop callbacks will be called.
16
+ # EM.run do
17
+ # array = (1..100).to_a
18
+ #
19
+ # tickloop = EM.tick_loop do
20
+ # if array.empty?
21
+ # :stop
22
+ # else
23
+ # puts array.shift
24
+ # end
25
+ # end
26
+ #
27
+ # tickloop.on_stop { EM.stop }
28
+ # end
29
+ #
30
+ class TickLoop
31
+
32
+ # Arguments: A callback (EM::Callback) to call each tick. If the call
33
+ # returns +:stop+ then the loop will be stopped. Any other value is
34
+ # ignored.
35
+ def initialize(*a, &b)
36
+ @work = EM::Callback(*a, &b)
37
+ @stops = []
38
+ @stopped = true
39
+ end
40
+
41
+ # Arguments: A callback (EM::Callback) to call once on the next stop (or
42
+ # immediately if already stopped).
43
+ def on_stop(*a, &b)
44
+ if @stopped
45
+ EM::Callback(*a, &b).call
46
+ else
47
+ @stops << EM::Callback(*a, &b)
48
+ end
49
+ end
50
+
51
+ # Stop the tick loop immediately, and call it's on_stop callbacks.
52
+ def stop
53
+ @stopped = true
54
+ until @stops.empty?
55
+ @stops.shift.call
56
+ end
57
+ end
58
+
59
+ # Query if the loop is stopped.
60
+ def stopped?
61
+ @stopped
62
+ end
63
+
64
+ # Start the tick loop, will raise argument error if the loop is already
65
+ # running.
66
+ def start
67
+ raise ArgumentError, "double start" unless @stopped
68
+ @stopped = false
69
+ schedule
70
+ end
71
+
72
+ private
73
+ def schedule
74
+ EM.next_tick do
75
+ next if @stopped
76
+ if @work.call == :stop
77
+ stop
78
+ else
79
+ schedule
80
+ end
81
+ end
82
+ self
83
+ end
84
+ end
85
+ end
@@ -0,0 +1,61 @@
1
+ module EventMachine
2
+ # Creates a one-time timer
3
+ #
4
+ # timer = EventMachine::Timer.new(5) do
5
+ # # this will never fire because we cancel it
6
+ # end
7
+ # timer.cancel
8
+ #
9
+ class Timer
10
+ # Create a new timer that fires after a given number of seconds
11
+ def initialize interval, callback=nil, &block
12
+ @signature = EventMachine::add_timer(interval, callback || block)
13
+ end
14
+
15
+ # Cancel the timer
16
+ def cancel
17
+ EventMachine.send :cancel_timer, @signature
18
+ end
19
+ end
20
+
21
+ # Creates a periodic timer
22
+ #
23
+ # @example
24
+ # n = 0
25
+ # timer = EventMachine::PeriodicTimer.new(5) do
26
+ # puts "the time is #{Time.now}"
27
+ # timer.cancel if (n+=1) > 5
28
+ # end
29
+ #
30
+ class PeriodicTimer
31
+ # Create a new periodic timer that executes every interval seconds
32
+ def initialize interval, callback=nil, &block
33
+ @interval = interval
34
+ @code = callback || block
35
+ @cancelled = false
36
+ @work = method(:fire)
37
+ schedule
38
+ end
39
+
40
+ # Cancel the periodic timer
41
+ def cancel
42
+ @cancelled = true
43
+ end
44
+
45
+ # Fire the timer every interval seconds
46
+ attr_accessor :interval
47
+
48
+ # @private
49
+ def schedule
50
+ EventMachine::add_timer @interval, @work
51
+ end
52
+
53
+ # @private
54
+ def fire
55
+ unless @cancelled
56
+ @code.call
57
+ schedule
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,3 @@
1
+ module EventMachine
2
+ VERSION = "1.0.0.beta.4.ipv6.0"
3
+ end
@@ -0,0 +1,1517 @@
1
+ if RUBY_PLATFORM =~ /java/
2
+ require 'java'
3
+ require 'jeventmachine'
4
+ elsif defined?(EventMachine.library_type) and EventMachine.library_type == :pure_ruby
5
+ # assume 'em/pure_ruby' was loaded already
6
+ else
7
+ begin
8
+ require 'rubyeventmachine'
9
+ rescue LoadError
10
+ warn "Unable to load the EventMachine C extension; To use the pure-ruby reactor, require 'em/pure_ruby'"
11
+ raise
12
+ end
13
+ end
14
+
15
+ require 'em/version'
16
+ require 'em/pool'
17
+ require 'em/deferrable'
18
+ require 'em/future'
19
+ require 'em/streamer'
20
+ require 'em/spawnable'
21
+ require 'em/processes'
22
+ require 'em/iterator'
23
+ require 'em/buftok'
24
+ require 'em/timers'
25
+ require 'em/protocols'
26
+ require 'em/connection'
27
+ require 'em/callback'
28
+ require 'em/queue'
29
+ require 'em/channel'
30
+ require 'em/file_watch'
31
+ require 'em/process_watch'
32
+ require 'em/tick_loop'
33
+ require 'em/resolver'
34
+ require 'em/completion'
35
+ require 'em/threaded_resource'
36
+
37
+ require 'shellwords'
38
+ require 'thread'
39
+ require 'resolv'
40
+
41
+ # Top-level EventMachine namespace. If you are looking for EventMachine examples, see {file:docs/GettingStarted.md EventMachine tutorial}.
42
+ #
43
+ # ## Key methods ##
44
+ # ### Starting and stopping the event loop ###
45
+ #
46
+ # * {EventMachine.run}
47
+ # * {EventMachine.stop_event_loop}
48
+ #
49
+ # ### Implementing clients ###
50
+ #
51
+ # * {EventMachine.connect}
52
+ #
53
+ # ### Implementing servers ###
54
+ #
55
+ # * {EventMachine.start_server}
56
+ #
57
+ # ### Working with timers ###
58
+ #
59
+ # * {EventMachine.add_timer}
60
+ # * {EventMachine.add_periodic_timer}
61
+ # * {EventMachine.cancel_timer}
62
+ #
63
+ # ### Working with blocking tasks ###
64
+ #
65
+ # * {EventMachine.defer}
66
+ # * {EventMachine.next_tick}
67
+ #
68
+ # ### Efficient proxying ###
69
+ #
70
+ # * {EventMachine.enable_proxy}
71
+ # * {EventMachine.disable_proxy}
72
+ module EventMachine
73
+ class << self
74
+ # Exposed to allow joining on the thread, when run in a multithreaded
75
+ # environment. Performing other actions on the thread has undefined
76
+ # semantics (read: a dangerous endevor).
77
+ #
78
+ # @return [Thread]
79
+ attr_reader :reactor_thread
80
+ end
81
+ @next_tick_mutex = Mutex.new
82
+ @reactor_running = false
83
+ @next_tick_queue = []
84
+ @tails = []
85
+ @threadpool = nil
86
+
87
+ # System errnos
88
+ # @private
89
+ ERRNOS = Errno::constants.grep(/^E/).inject(Hash.new(:unknown)) { |hash, name|
90
+ errno = Errno.__send__(:const_get, name)
91
+ hash[errno::Errno] = errno
92
+ hash
93
+ }
94
+
95
+ # Initializes and runs an event loop. This method only returns if code inside the block passed to this method
96
+ # calls {EventMachine.stop_event_loop}. The block is executed after initializing its internal event loop but *before* running the loop,
97
+ # therefore this block is the right place to call any code that needs event loop to run, for example, {EventMachine.start_server},
98
+ # {EventMachine.connect} or similar methods of libraries that use EventMachine under the hood
99
+ # (like `EventMachine::HttpRequest.new` or `AMQP.start`).
100
+ #
101
+ # Programs that are run for long periods of time (e.g. servers) usually start event loop by calling {EventMachine.run}, and let it
102
+ # run "forever". It's also possible to use {EventMachine.run} to make a single client-connection to a remote server,
103
+ # process the data flow from that single connection, and then call {EventMachine.stop_event_loop} to stop, in other words,
104
+ # to run event loop for a short period of time (necessary to complete some operation) and then shut it down.
105
+ #
106
+ # Once event loop is running, it is perfectly possible to start multiple servers and clients simultaneously: content-aware
107
+ # proxies like [Proxymachine](https://github.com/mojombo/proxymachine) do just that.
108
+ #
109
+ # ## Using EventMachine with Ruby on Rails and other Web application frameworks ##
110
+ #
111
+ # Standalone applications often run event loop on the main thread, thus blocking for their entire lifespan. In case of Web applications,
112
+ # 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/),
113
+ # they start event loop for you. Servers like Unicorn, Apache Passenger or Mongrel occupy main Ruby thread to serve HTTP(S) requests. This means
114
+ # that calling {EventMachine.run} on the same thread is not an option (it will result in Web server never binding to the socket).
115
+ # In that case, start event loop in a separate thread as demonstrated below.
116
+ #
117
+ #
118
+ # @example Starting EventMachine event loop in the current thread to run the "Hello, world"-like Echo server example
119
+ #
120
+ # #!/usr/bin/env ruby
121
+ #
122
+ # require 'rubygems' # or use Bundler.setup
123
+ # require 'eventmachine'
124
+ #
125
+ # class EchoServer < EM::Connection
126
+ # def receive_data(data)
127
+ # send_data(data)
128
+ # end
129
+ # end
130
+ #
131
+ # EventMachine.run do
132
+ # EventMachine.start_server("0.0.0.0", 10000, EchoServer)
133
+ # end
134
+ #
135
+ #
136
+ # @example Starting EventMachine event loop in a separate thread
137
+ #
138
+ # # doesn't block current thread, can be used with Ruby on Rails, Sinatra, Merb, Rack
139
+ # # and any other application server that occupies main Ruby thread.
140
+ # Thread.new { EventMachine.run }
141
+ #
142
+ #
143
+ # @note This method blocks calling thread. If you need to start EventMachine event loop from a Web app
144
+ # running on a non event-driven server (Unicorn, Apache Passenger, Mongrel), do it in a separate thread like demonstrated
145
+ # in one of the examples.
146
+ # @see file:docs/GettingStarted.md Getting started with EventMachine
147
+ # @see EventMachine.stop_event_loop
148
+ def self.run blk=nil, tail=nil, &block
149
+ # Obsoleted the use_threads mechanism.
150
+ # 25Nov06: Added the begin/ensure block. We need to be sure that release_machine
151
+ # gets called even if an exception gets thrown within any of the user code
152
+ # that the event loop runs. The best way to see this is to run a unit
153
+ # test with two functions, each of which calls {EventMachine.run} and each of
154
+ # which throws something inside of #run. Without the ensure, the second test
155
+ # will start without release_machine being called and will immediately throw
156
+
157
+ #
158
+ if reactor_running? and @reactor_pid != Process.pid
159
+ # Reactor was started in a different parent, meaning we have forked.
160
+ # Clean up reactor state so a new reactor boots up in this child.
161
+ stop_event_loop
162
+ release_machine
163
+ @reactor_running = false
164
+ end
165
+
166
+ tail and @tails.unshift(tail)
167
+
168
+ if reactor_running?
169
+ (b = blk || block) and b.call # next_tick(b)
170
+ else
171
+ @conns = {}
172
+ @acceptors = {}
173
+ @timers = {}
174
+ @wrapped_exception = nil
175
+ @next_tick_queue ||= []
176
+ @tails ||= []
177
+ begin
178
+ @reactor_pid = Process.pid
179
+ @reactor_running = true
180
+ initialize_event_machine
181
+ (b = blk || block) and add_timer(0, b)
182
+ if @next_tick_queue && !@next_tick_queue.empty?
183
+ add_timer(0) { signal_loopbreak }
184
+ end
185
+ @reactor_thread = Thread.current
186
+ run_machine
187
+ ensure
188
+ until @tails.empty?
189
+ @tails.pop.call
190
+ end
191
+
192
+ begin
193
+ release_machine
194
+ ensure
195
+ if @threadpool
196
+ @threadpool.each { |t| t.exit }
197
+ @threadpool.each do |t|
198
+ next unless t.alive?
199
+ begin
200
+ # Thread#kill! does not exist on 1.9 or rbx, and raises
201
+ # NotImplemented on jruby
202
+ t.kill!
203
+ rescue NoMethodError, NotImplementedError
204
+ t.kill
205
+ # XXX t.join here?
206
+ end
207
+ end
208
+ @threadqueue = nil
209
+ @resultqueue = nil
210
+ @threadpool = nil
211
+ end
212
+
213
+ @next_tick_queue = []
214
+ end
215
+ @reactor_running = false
216
+ @reactor_thread = nil
217
+ end
218
+
219
+ raise @wrapped_exception if @wrapped_exception
220
+ end
221
+ end
222
+
223
+ # Sugars a common use case. Will pass the given block to #run, but will terminate
224
+ # the reactor loop and exit the function as soon as the code in the block completes.
225
+ # (Normally, {EventMachine.run} keeps running indefinitely, even after the block supplied to it
226
+ # finishes running, until user code calls {EventMachine.stop})
227
+ #
228
+ def self.run_block &block
229
+ pr = proc {
230
+ block.call
231
+ EventMachine::stop
232
+ }
233
+ run(&pr)
234
+ end
235
+
236
+ # @return [Boolean] true if the calling thread is the same thread as the reactor.
237
+ def self.reactor_thread?
238
+ Thread.current == @reactor_thread
239
+ end
240
+
241
+ # Runs the given callback on the reactor thread, or immediately if called
242
+ # from the reactor thread. Accepts the same arguments as {EventMachine::Callback}
243
+ def self.schedule(*a, &b)
244
+ cb = Callback(*a, &b)
245
+ if reactor_running? && reactor_thread?
246
+ cb.call
247
+ else
248
+ next_tick { cb.call }
249
+ end
250
+ end
251
+
252
+ # Forks a new process, properly stops the reactor and then calls {EventMachine.run} inside of it again, passing your block.
253
+ def self.fork_reactor &block
254
+ # This implementation is subject to change, especially if we clean up the relationship
255
+ # of EM#run to @reactor_running.
256
+ # Original patch by Aman Gupta.
257
+ #
258
+ Kernel.fork do
259
+ if self.reactor_running?
260
+ self.stop_event_loop
261
+ self.release_machine
262
+ @reactor_running = false
263
+ end
264
+ self.run block
265
+ end
266
+ end
267
+
268
+ # Adds a block to call as the reactor is shutting down.
269
+ #
270
+ # These callbacks are called in the _reverse_ order to which they are added.
271
+ #
272
+ # @example Scheduling operations to be run when EventMachine event loop is stopped
273
+ #
274
+ # EventMachine.run do
275
+ # EventMachine.add_shutdown_hook { puts "b" }
276
+ # EventMachine.add_shutdown_hook { puts "a" }
277
+ # EventMachine.stop
278
+ # end
279
+ #
280
+ # # Outputs:
281
+ # # a
282
+ # # b
283
+ #
284
+ def self.add_shutdown_hook &block
285
+ @tails << block
286
+ end
287
+
288
+ # Adds a one-shot timer to the event loop.
289
+ # Call it with one or two parameters. The first parameters is a delay-time
290
+ # expressed in *seconds* (not milliseconds). The second parameter, if
291
+ # present, must be an object that responds to :call. If 2nd parameter is not given, then you
292
+ # can also simply pass a block to the method call.
293
+ #
294
+ # This method may be called from the block passed to {EventMachine.run}
295
+ # or from any callback method. It schedules execution of the proc or block
296
+ # passed to it, after the passage of an interval of time equal to
297
+ # *at least* the number of seconds specified in the first parameter to
298
+ # the call.
299
+ #
300
+ # {EventMachine.add_timer} is a non-blocking method. Callbacks can and will
301
+ # be called during the interval of time that the timer is in effect.
302
+ # There is no built-in limit to the number of timers that can be outstanding at
303
+ # any given time.
304
+ #
305
+ # @example Setting a one-shot timer with EventMachine
306
+ #
307
+ # EventMachine.run {
308
+ # puts "Starting the run now: #{Time.now}"
309
+ # EventMachine.add_timer 5, proc { puts "Executing timer event: #{Time.now}" }
310
+ # EventMachine.add_timer(10) { puts "Executing timer event: #{Time.now}" }
311
+ # }
312
+ #
313
+ # @param [Integer] delay Delay in seconds
314
+ # @see EventMachine::Timer
315
+ # @see EventMachine.add_periodic_timer
316
+ def self.add_timer *args, &block
317
+ interval = args.shift
318
+ code = args.shift || block
319
+ if code
320
+ # check too many timers!
321
+ s = add_oneshot_timer((interval.to_f * 1000).to_i)
322
+ @timers[s] = code
323
+ s
324
+ end
325
+ end
326
+
327
+ # Adds a periodic timer to the event loop.
328
+ # It takes the same parameters as the one-shot timer method, {EventMachine.add_timer}.
329
+ # This method schedules execution of the given block repeatedly, at intervals
330
+ # of time *at least* as great as the number of seconds given in the first
331
+ # parameter to the call.
332
+ #
333
+ # @example Write a dollar-sign to stderr every five seconds, without blocking
334
+ #
335
+ # EventMachine.run {
336
+ # EventMachine.add_periodic_timer( 5 ) { $stderr.write "$" }
337
+ # }
338
+ #
339
+ # @param [Integer] delay Delay in seconds
340
+ #
341
+ # @see EventMachine::PeriodicTimer
342
+ # @see EventMachine.add_timer
343
+ #
344
+ def self.add_periodic_timer *args, &block
345
+ interval = args.shift
346
+ code = args.shift || block
347
+
348
+ EventMachine::PeriodicTimer.new(interval, code)
349
+ end
350
+
351
+
352
+ # Cancel a timer (can be a callback or an {EventMachine::Timer} instance).
353
+ #
354
+ # @param [#cancel, #call] timer_or_sig A timer to cancel
355
+ # @see EventMachine::Timer#cancel
356
+ def self.cancel_timer timer_or_sig
357
+ if timer_or_sig.respond_to? :cancel
358
+ timer_or_sig.cancel
359
+ else
360
+ @timers[timer_or_sig] = false if @timers.has_key?(timer_or_sig)
361
+ end
362
+ end
363
+
364
+
365
+ # Causes the processing loop to stop executing, which will cause all open connections and accepting servers
366
+ # to be run down and closed. Connection termination callbacks added using {EventMachine.add_shutdown_hook}
367
+ # will be called as part of running this method.
368
+ #
369
+ # When all of this processing is complete, the call to {EventMachine.run} which started the processing loop
370
+ # will return and program flow will resume from the statement following {EventMachine.run} call.
371
+ #
372
+ # @example Stopping a running EventMachine event loop
373
+ #
374
+ # require 'rubygems'
375
+ # require 'eventmachine'
376
+ #
377
+ # module Redmond
378
+ # def post_init
379
+ # puts "We're sending a dumb HTTP request to the remote peer."
380
+ # send_data "GET / HTTP/1.1\r\nHost: www.microsoft.com\r\n\r\n"
381
+ # end
382
+ #
383
+ # def receive_data data
384
+ # puts "We received #{data.length} bytes from the remote peer."
385
+ # puts "We're going to stop the event loop now."
386
+ # EventMachine::stop_event_loop
387
+ # end
388
+ #
389
+ # def unbind
390
+ # puts "A connection has terminated."
391
+ # end
392
+ # end
393
+ #
394
+ # puts "We're starting the event loop now."
395
+ # EventMachine.run {
396
+ # EventMachine.connect "www.microsoft.com", 80, Redmond
397
+ # }
398
+ # puts "The event loop has stopped."
399
+ #
400
+ # # This program will produce approximately the following output:
401
+ # #
402
+ # # We're starting the event loop now.
403
+ # # We're sending a dumb HTTP request to the remote peer.
404
+ # # We received 1440 bytes from the remote peer.
405
+ # # We're going to stop the event loop now.
406
+ # # A connection has terminated.
407
+ # # The event loop has stopped.
408
+ #
409
+ #
410
+ def self.stop_event_loop
411
+ EventMachine::stop
412
+ end
413
+
414
+ # Initiates a TCP server (socket acceptor) on the specified IP address and port.
415
+ #
416
+ # The IP address must be valid on the machine where the program
417
+ # runs, and the process must be privileged enough to listen
418
+ # on the specified port (on Unix-like systems, superuser privileges
419
+ # are usually required to listen on any port lower than 1024).
420
+ # Only one listener may be running on any given address/port
421
+ # combination. start_server will fail if the given address and port
422
+ # are already listening on the machine, either because of a prior call
423
+ # to {.start_server} or some unrelated process running on the machine.
424
+ # If {.start_server} succeeds, the new network listener becomes active
425
+ # immediately and starts accepting connections from remote peers,
426
+ # and these connections generate callback events that are processed
427
+ # by the code specified in the handler parameter to {.start_server}.
428
+ #
429
+ # The optional handler which is passed to this method is the key
430
+ # to EventMachine's ability to handle particular network protocols.
431
+ # The handler parameter passed to start_server must be a Ruby Module
432
+ # that you must define. When the network server that is started by
433
+ # start_server accepts a new connection, it instantiates a new
434
+ # object of an anonymous class that is inherited from {EventMachine::Connection},
435
+ # *into which your handler module have been included*.
436
+ #
437
+ # Your handler module may override any of the methods in {EventMachine::Connection},
438
+ # such as {EventMachine::Connection#receive_data}, in order to implement the specific behavior
439
+ # of the network protocol.
440
+ #
441
+ # Callbacks invoked in response to network events *always* take place
442
+ # within the execution context of the object derived from {EventMachine::Connection}
443
+ # extended by your handler module. There is one object per connection, and
444
+ # all of the callbacks invoked for a particular connection take the form
445
+ # of instance methods called against the corresponding {EventMachine::Connection}
446
+ # object. Therefore, you are free to define whatever instance variables you
447
+ # wish, in order to contain the per-connection state required by the network protocol you are
448
+ # implementing.
449
+ #
450
+ # {EventMachine.start_server} is usually called inside the block passed to {EventMachine.run},
451
+ # but it can be called from any EventMachine callback. {EventMachine.start_server} will fail
452
+ # unless the EventMachine event loop is currently running (which is why
453
+ # it's often called in the block suppled to {EventMachine.run}).
454
+ #
455
+ # You may call start_server any number of times to start up network
456
+ # listeners on different address/port combinations. The servers will
457
+ # all run simultaneously. More interestingly, each individual call to start_server
458
+ # can specify a different handler module and thus implement a different
459
+ # network protocol from all the others.
460
+ #
461
+ # @example
462
+ #
463
+ # require 'rubygems'
464
+ # require 'eventmachine'
465
+ #
466
+ # # Here is an example of a server that counts lines of input from the remote
467
+ # # peer and sends back the total number of lines received, after each line.
468
+ # # Try the example with more than one client connection opened via telnet,
469
+ # # and you will see that the line count increments independently on each
470
+ # # of the client connections. Also very important to note, is that the
471
+ # # handler for the receive_data function, which our handler redefines, may
472
+ # # not assume that the data it receives observes any kind of message boundaries.
473
+ # # Also, to use this example, be sure to change the server and port parameters
474
+ # # to the start_server call to values appropriate for your environment.
475
+ # module LineCounter
476
+ # MaxLinesPerConnection = 10
477
+ #
478
+ # def post_init
479
+ # puts "Received a new connection"
480
+ # @data_received = ""
481
+ # @line_count = 0
482
+ # end
483
+ #
484
+ # def receive_data data
485
+ # @data_received << data
486
+ # while @data_received.slice!( /^[^\n]*[\n]/m )
487
+ # @line_count += 1
488
+ # send_data "received #{@line_count} lines so far\r\n"
489
+ # @line_count == MaxLinesPerConnection and close_connection_after_writing
490
+ # end
491
+ # end
492
+ # end
493
+ #
494
+ # EventMachine.run {
495
+ # host, port = "192.168.0.100", 8090
496
+ # EventMachine.start_server host, port, LineCounter
497
+ # puts "Now accepting connections on address #{host}, port #{port}..."
498
+ # EventMachine.add_periodic_timer(10) { $stderr.write "*" }
499
+ # }
500
+ #
501
+ # @param [String] server Host to bind to.
502
+ # @param [Integer] port Port to bind to.
503
+ # @param [Module, Class] handler A module or class that implements connection callbacks
504
+ #
505
+ # @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.
506
+ #
507
+ # @see file:docs/GettingStarted.md EventMachine tutorial
508
+ # @see EventMachine.stop_server
509
+ def self.start_server server, port=nil, handler=nil, *args, &block
510
+ begin
511
+ port = Integer(port)
512
+ rescue ArgumentError, TypeError
513
+ # there was no port, so server must be a unix domain socket
514
+ # the port argument is actually the handler, and the handler is one of the args
515
+ args.unshift handler if handler
516
+ handler = port
517
+ port = nil
518
+ end if port
519
+
520
+ klass = klass_from_handler(Connection, handler, *args)
521
+
522
+ s = if port
523
+ start_tcp_server server, port
524
+ else
525
+ start_unix_server server
526
+ end
527
+ @acceptors[s] = [klass,args,block]
528
+ s
529
+ end
530
+
531
+
532
+ # Stop a TCP server socket that was started with {EventMachine.start_server}.
533
+ # @see EventMachine.start_server
534
+ def self.stop_server signature
535
+ EventMachine::stop_tcp_server signature
536
+ end
537
+
538
+ # Start a Unix-domain server.
539
+ #
540
+ # Note that this is an alias for {EventMachine.start_server}, which can be used to start both
541
+ # TCP and Unix-domain servers.
542
+ #
543
+ # @see EventMachine.start_server
544
+ def self.start_unix_domain_server filename, *args, &block
545
+ start_server filename, *args, &block
546
+ end
547
+
548
+ # Initiates a TCP connection to a remote server and sets up event handling for the connection.
549
+ # {EventMachine.connect} requires event loop to be running (see {EventMachine.run}).
550
+ #
551
+ # {EventMachine.connect} takes the IP address (or hostname) and
552
+ # port of the remote server you want to connect to.
553
+ # It also takes an optional handler (a module or a subclass of {EventMachine::Connection}) which you must define, that
554
+ # contains the callbacks that will be invoked by the event loop on behalf of the connection.
555
+ #
556
+ # Learn more about connection lifecycle callbacks in the {file:docs/GettingStarted.md EventMachine tutorial} and
557
+ # {file:docs/ConnectionLifecycleCallbacks.md Connection lifecycle guide}.
558
+ #
559
+ #
560
+ # @example
561
+ #
562
+ # # Here's a program which connects to a web server, sends a naive
563
+ # # request, parses the HTTP header of the response, and then
564
+ # # (antisocially) ends the event loop, which automatically drops the connection
565
+ # # (and incidentally calls the connection's unbind method).
566
+ # module DumbHttpClient
567
+ # def post_init
568
+ # send_data "GET / HTTP/1.1\r\nHost: _\r\n\r\n"
569
+ # @data = ""
570
+ # @parsed = false
571
+ # end
572
+ #
573
+ # def receive_data data
574
+ # @data << data
575
+ # if !@parsed and @data =~ /[\n][\r]*[\n]/m
576
+ # @parsed = true
577
+ # puts "RECEIVED HTTP HEADER:"
578
+ # $`.each {|line| puts ">>> #{line}" }
579
+ #
580
+ # puts "Now we'll terminate the loop, which will also close the connection"
581
+ # EventMachine::stop_event_loop
582
+ # end
583
+ # end
584
+ #
585
+ # def unbind
586
+ # puts "A connection has terminated"
587
+ # end
588
+ # end
589
+ #
590
+ # EventMachine.run {
591
+ # EventMachine.connect "www.bayshorenetworks.com", 80, DumbHttpClient
592
+ # }
593
+ # puts "The event loop has ended"
594
+ #
595
+ #
596
+ # @example Defining protocol handler as a class
597
+ #
598
+ # class MyProtocolHandler < EventMachine::Connection
599
+ # def initialize *args
600
+ # super
601
+ # # whatever else you want to do here
602
+ # end
603
+ #
604
+ # # ...
605
+ # end
606
+ #
607
+ #
608
+ # @param [String] server Host to connect to
609
+ # @param [Integer] port Port to connect to
610
+ # @param [Module, Class] handler A module or class that implements connection lifecycle callbacks
611
+ #
612
+ # @see EventMachine.start_server
613
+ # @see file:docs/GettingStarted.md EventMachine tutorial
614
+ def self.connect server, port=nil, handler=nil, *args, &blk
615
+ # EventMachine::connect initiates a TCP connection to a remote
616
+ # server and sets up event-handling for the connection.
617
+ # It internally creates an object that should not be handled
618
+ # by the caller. HOWEVER, it's often convenient to get the
619
+ # object to set up interfacing to other objects in the system.
620
+ # We return the newly-created anonymous-class object to the caller.
621
+ # It's expected that a considerable amount of code will depend
622
+ # on this behavior, so don't change it.
623
+ #
624
+ # Ok, added support for a user-defined block, 13Apr06.
625
+ # This leads us to an interesting choice because of the
626
+ # presence of the post_init call, which happens in the
627
+ # initialize method of the new object. We call the user's
628
+ # block and pass the new object to it. This is a great
629
+ # way to do protocol-specific initiation. It happens
630
+ # AFTER post_init has been called on the object, which I
631
+ # certainly hope is the right choice.
632
+ # Don't change this lightly, because accepted connections
633
+ # are different from connected ones and we don't want
634
+ # to have them behave differently with respect to post_init
635
+ # if at all possible.
636
+
637
+ bind_connect nil, nil, server, port, handler, *args, &blk
638
+ end
639
+
640
+ # This method is like {EventMachine.connect}, but allows for a local address/port
641
+ # to bind the connection to.
642
+ #
643
+ # @see EventMachine.connect
644
+ def self.bind_connect bind_addr, bind_port, server, port=nil, handler=nil, *args
645
+ begin
646
+ port = Integer(port)
647
+ rescue ArgumentError, TypeError
648
+ # there was no port, so server must be a unix domain socket
649
+ # the port argument is actually the handler, and the handler is one of the args
650
+ args.unshift handler if handler
651
+ handler = port
652
+ port = nil
653
+ end if port
654
+
655
+ klass = klass_from_handler(Connection, handler, *args)
656
+
657
+ s = if port
658
+ if bind_addr
659
+ bind_connect_server bind_addr, bind_port.to_i, server, port
660
+ else
661
+ connect_server server, port
662
+ end
663
+ else
664
+ connect_unix_server server
665
+ end
666
+
667
+ c = klass.new s, *args
668
+ @conns[s] = c
669
+ block_given? and yield c
670
+ c
671
+ end
672
+
673
+ # {EventMachine.watch} registers a given file descriptor or IO object with the eventloop. The
674
+ # file descriptor will not be modified (it will remain blocking or non-blocking).
675
+ #
676
+ # The eventloop can be used to process readable and writable events on the file descriptor, using
677
+ # {EventMachine::Connection#notify_readable=} and {EventMachine::Connection#notify_writable=}
678
+ #
679
+ # {EventMachine::Connection#notify_readable?} and {EventMachine::Connection#notify_writable?} can be used
680
+ # to check what events are enabled on the connection.
681
+ #
682
+ # To detach the file descriptor, use {EventMachine::Connection#detach}
683
+ #
684
+ # @example
685
+ #
686
+ # module SimpleHttpClient
687
+ # def notify_readable
688
+ # header = @io.readline
689
+ #
690
+ # if header == "\r\n"
691
+ # # detach returns the file descriptor number (fd == @io.fileno)
692
+ # fd = detach
693
+ # end
694
+ # rescue EOFError
695
+ # detach
696
+ # end
697
+ #
698
+ # def unbind
699
+ # EM.next_tick do
700
+ # # socket is detached from the eventloop, but still open
701
+ # data = @io.read
702
+ # end
703
+ # end
704
+ # end
705
+ #
706
+ # EventMachine.run {
707
+ # sock = TCPSocket.new('site.com', 80)
708
+ # sock.write("GET / HTTP/1.0\r\n\r\n")
709
+ # conn = EventMachine.watch(sock, SimpleHttpClient)
710
+ # conn.notify_readable = true
711
+ # }
712
+ #
713
+ # @author Riham Aldakkak (eSpace Technologies)
714
+ def EventMachine::watch io, handler=nil, *args, &blk
715
+ attach_io io, true, handler, *args, &blk
716
+ end
717
+
718
+ # Attaches an IO object or file descriptor to the eventloop as a regular connection.
719
+ # The file descriptor will be set as non-blocking, and EventMachine will process
720
+ # receive_data and send_data events on it as it would for any other connection.
721
+ #
722
+ # To watch a fd instead, use {EventMachine.watch}, which will not alter the state of the socket
723
+ # and fire notify_readable and notify_writable events instead.
724
+ def EventMachine::attach io, handler=nil, *args, &blk
725
+ attach_io io, false, handler, *args, &blk
726
+ end
727
+
728
+ # @private
729
+ def EventMachine::attach_io io, watch_mode, handler=nil, *args
730
+ klass = klass_from_handler(Connection, handler, *args)
731
+
732
+ if !watch_mode and klass.public_instance_methods.any?{|m| [:notify_readable, :notify_writable].include? m.to_sym }
733
+ raise ArgumentError, "notify_readable/writable with EM.attach is not supported. Use EM.watch(io){ |c| c.notify_readable = true }"
734
+ end
735
+
736
+ if io.respond_to?(:fileno)
737
+ fd = defined?(JRuby) ? JRuby.runtime.getDescriptorByFileno(io.fileno).getChannel : io.fileno
738
+ else
739
+ fd = io
740
+ end
741
+
742
+ s = attach_fd fd, watch_mode
743
+ c = klass.new s, *args
744
+
745
+ c.instance_variable_set(:@io, io)
746
+ c.instance_variable_set(:@watch_mode, watch_mode)
747
+ c.instance_variable_set(:@fd, fd)
748
+
749
+ @conns[s] = c
750
+ block_given? and yield c
751
+ c
752
+ end
753
+
754
+
755
+ # Connect to a given host/port and re-use the provided {EventMachine::Connection} instance.
756
+ # Consider also {EventMachine::Connection#reconnect}.
757
+ #
758
+ # @see EventMachine::Connection#reconnect
759
+ def self.reconnect server, port, handler
760
+ # Observe, the test for already-connected FAILS if we call a reconnect inside post_init,
761
+ # because we haven't set up the connection in @conns by that point.
762
+ # RESIST THE TEMPTATION to "fix" this problem by redefining the behavior of post_init.
763
+ #
764
+ # Changed 22Nov06: if called on an already-connected handler, just return the
765
+ # handler and do nothing more. Originally this condition raised an exception.
766
+ # We may want to change it yet again and call the block, if any.
767
+
768
+ raise "invalid handler" unless handler.respond_to?(:connection_completed)
769
+ #raise "still connected" if @conns.has_key?(handler.signature)
770
+ return handler if @conns.has_key?(handler.signature)
771
+
772
+ s = if port
773
+ connect_server server, port
774
+ else
775
+ connect_unix_server server
776
+ end
777
+ handler.signature = s
778
+ @conns[s] = handler
779
+ block_given? and yield handler
780
+ handler
781
+ end
782
+
783
+
784
+ # Make a connection to a Unix-domain socket. This method is simply an alias for {.connect},
785
+ # which can connect to both TCP and Unix-domain sockets. Make sure that your process has sufficient
786
+ # permissions to open the socket it is given.
787
+ #
788
+ # @param [String] socketname Unix domain socket (local fully-qualified path) you want to connect to.
789
+ #
790
+ # @note UNIX sockets, as the name suggests, are not available on Microsoft Windows.
791
+ def self.connect_unix_domain socketname, *args, &blk
792
+ connect socketname, *args, &blk
793
+ end
794
+
795
+
796
+ # Used for UDP-based protocols. Its usage is similar to that of {EventMachine.start_server}.
797
+ #
798
+ # This method will create a new UDP (datagram) socket and
799
+ # bind it to the address and port that you specify.
800
+ # The normal callbacks (see {EventMachine.start_server}) will
801
+ # be called as events of interest occur on the newly-created
802
+ # socket, but there are some differences in how they behave.
803
+ #
804
+ # {Connection#receive_data} will be called when a datagram packet
805
+ # is received on the socket, but unlike TCP sockets, the message
806
+ # boundaries of the received data will be respected. In other words,
807
+ # if the remote peer sent you a datagram of a particular size,
808
+ # you may rely on {Connection#receive_data} to give you the
809
+ # exact data in the packet, with the original data length.
810
+ # Also observe that Connection#receive_data may be called with a
811
+ # *zero-length* data payload, since empty datagrams are permitted in UDP.
812
+ #
813
+ # {Connection#send_data} is available with UDP packets as with TCP,
814
+ # but there is an important difference. Because UDP communications
815
+ # are *connectionless*, there is no implicit recipient for the packets you
816
+ # send. Ordinarily you must specify the recipient for each packet you send.
817
+ # However, EventMachine provides for the typical pattern of receiving a UDP datagram
818
+ # from a remote peer, performing some operation, and then sending
819
+ # one or more packets in response to the same remote peer.
820
+ # To support this model easily, just use {Connection#send_data}
821
+ # in the code that you supply for {Connection#receive_data}.
822
+ #
823
+ # EventMachine will provide an implicit return address for any messages sent to
824
+ # {Connection#send_data} within the context of a {Connection#receive_data} callback,
825
+ # and your response will automatically go to the correct remote peer.
826
+ #
827
+ # Observe that the port number that you supply to {EventMachine.open_datagram_socket}
828
+ # may be zero. In this case, EventMachine will create a UDP socket
829
+ # that is bound to an [ephemeral port](http://en.wikipedia.org/wiki/Ephemeral_port).
830
+ # This is not appropriate for servers that must publish a well-known
831
+ # port to which remote peers may send datagrams. But it can be useful
832
+ # for clients that send datagrams to other servers.
833
+ # If you do this, you will receive any responses from the remote
834
+ # servers through the normal {Connection#receive_data} callback.
835
+ # Observe that you will probably have issues with firewalls blocking
836
+ # the ephemeral port numbers, so this technique is most appropriate for LANs.
837
+ #
838
+ # If you wish to send datagrams to arbitrary remote peers (not
839
+ # necessarily ones that have sent data to which you are responding),
840
+ # then see {Connection#send_datagram}.
841
+ #
842
+ # DO NOT call send_data from a datagram socket outside of a {Connection#receive_data} method. Use {Connection#send_datagram}.
843
+ # If you do use {Connection#send_data} outside of a {Connection#receive_data} method, you'll get a confusing error
844
+ # because there is no "peer," as #send_data requires (inside of {EventMachine::Connection#receive_data},
845
+ # {EventMachine::Connection#send_data} "fakes" the peer as described above).
846
+ #
847
+ # @param [String] address IP address
848
+ # @param [String] port Port
849
+ # @param [Class, Module] handler A class or a module that implements connection lifecycle callbacks.
850
+ def self.open_datagram_socket address, port, handler=nil, *args
851
+ # Replaced the implementation on 01Oct06. Thanks to Tobias Gustafsson for pointing
852
+ # out that this originally did not take a class but only a module.
853
+
854
+
855
+ klass = klass_from_handler(Connection, handler, *args)
856
+ s = open_udp_socket address, port.to_i
857
+ c = klass.new s, *args
858
+ @conns[s] = c
859
+ block_given? and yield c
860
+ c
861
+ end
862
+
863
+
864
+ # For advanced users. This function sets the default timer granularity, which by default is
865
+ # slightly smaller than 100 milliseconds. Call this function to set a higher or lower granularity.
866
+ # The function affects the behavior of {EventMachine.add_timer} and {EventMachine.add_periodic_timer}.
867
+ # Most applications will not need to call this function.
868
+ #
869
+ # Avoid setting the quantum to very low values because that may reduce performance under some extreme conditions.
870
+ # We recommend that you not use values lower than 10.
871
+ #
872
+ # This method only can be used if event loop is running.
873
+ #
874
+ # @param [Integer] mills New timer granularity, in milliseconds
875
+ #
876
+ # @see EventMachine.add_timer
877
+ # @see EventMachine.add_periodic_timer
878
+ # @see EventMachine::Timer
879
+ # @see EventMachine.run
880
+ def self.set_quantum mills
881
+ set_timer_quantum mills.to_i
882
+ end
883
+
884
+ # Sets the maximum number of timers and periodic timers that may be outstanding at any
885
+ # given time. You only need to call {.set_max_timers} if you need more than the default
886
+ # number of timers, which on most platforms is 1000.
887
+ #
888
+ # @note This method has to be used *before* event loop is started.
889
+ #
890
+ # @param [Integer] ct Maximum number of timers that may be outstanding at any given time
891
+ #
892
+ # @see EventMachine.add_timer
893
+ # @see EventMachine.add_periodic_timer
894
+ # @see EventMachine::Timer
895
+ def self.set_max_timers ct
896
+ set_max_timer_count ct
897
+ end
898
+
899
+ # Gets the current maximum number of allowed timers
900
+ #
901
+ # @return [Integer] Maximum number of timers that may be outstanding at any given time
902
+ def self.get_max_timers
903
+ get_max_timer_count
904
+ end
905
+
906
+ # Returns the total number of connections (file descriptors) currently held by the reactor.
907
+ # Note that a tick must pass after the 'initiation' of a connection for this number to increment.
908
+ # It's usually accurate, but don't rely on the exact precision of this number unless you really know EM internals.
909
+ #
910
+ # @example
911
+ #
912
+ # EventMachine.run {
913
+ # EventMachine.connect("rubyeventmachine.com", 80)
914
+ # # count will be 0 in this case, because connection is not
915
+ # # established yet
916
+ # count = EventMachine.connection_count
917
+ # }
918
+ #
919
+ #
920
+ # @example
921
+ #
922
+ # EventMachine.run {
923
+ # EventMachine.connect("rubyeventmachine.com", 80)
924
+ #
925
+ # EventMachine.next_tick {
926
+ # # In this example, count will be 1 since the connection has been established in
927
+ # # the next loop of the reactor.
928
+ # count = EventMachine.connection_count
929
+ # }
930
+ # }
931
+ #
932
+ # @return [Integer] Number of connections currently held by the reactor.
933
+ def self.connection_count
934
+ self.get_connection_count
935
+ end
936
+
937
+ # The is the responder for the loopback-signalled event.
938
+ # It can be fired either by code running on a separate thread ({EventMachine.defer}) or on
939
+ # the main thread ({EventMachine.next_tick}).
940
+ # It will often happen that a next_tick handler will reschedule itself. We
941
+ # consume a copy of the tick queue so that tick events scheduled by tick events
942
+ # have to wait for the next pass through the reactor core.
943
+ #
944
+ # @private
945
+ def self.run_deferred_callbacks
946
+ until (@resultqueue ||= []).empty?
947
+ result,cback = @resultqueue.pop
948
+ cback.call result if cback
949
+ end
950
+
951
+ # Capture the size at the start of this tick...
952
+ size = @next_tick_mutex.synchronize { @next_tick_queue.size }
953
+ size.times do |i|
954
+ callback = @next_tick_mutex.synchronize { @next_tick_queue.shift }
955
+ begin
956
+ callback.call
957
+ ensure
958
+ # This is a little nasty. The problem is, if an exception occurs during
959
+ # the callback, then we need to send a signal to the reactor to actually
960
+ # do some work during the next_tick. The only mechanism we have from the
961
+ # ruby side is next_tick itself, although ideally, we'd just drop a byte
962
+ # on the loopback descriptor.
963
+ EM.next_tick {} if $!
964
+ end
965
+ end
966
+ end
967
+
968
+
969
+ # EventMachine.defer is used for integrating blocking operations into EventMachine's control flow.
970
+ # The action of {.defer} is to take the block specified in the first parameter (the "operation")
971
+ # and schedule it for asynchronous execution on an internal thread pool maintained by EventMachine.
972
+ # When the operation completes, it will pass the result computed by the block (if any)
973
+ # back to the EventMachine reactor. Then, EventMachine calls the block specified in the
974
+ # second parameter to {.defer} (the "callback"), as part of its normal event handling loop.
975
+ # The result computed by the operation block is passed as a parameter to the callback.
976
+ # You may omit the callback parameter if you don't need to execute any code after the operation completes.
977
+ #
978
+ # ## Caveats ##
979
+ #
980
+ # Note carefully that the code in your deferred operation will be executed on a separate
981
+ # thread from the main EventMachine processing and all other Ruby threads that may exist in
982
+ # your program. Also, multiple deferred operations may be running at once! Therefore, you
983
+ # are responsible for ensuring that your operation code is threadsafe.
984
+ #
985
+ # Don't write a deferred operation that will block forever. If so, the current implementation will
986
+ # not detect the problem, and the thread will never be returned to the pool. EventMachine limits
987
+ # the number of threads in its pool, so if you do this enough times, your subsequent deferred
988
+ # operations won't get a chance to run.
989
+ #
990
+ # @example
991
+ #
992
+ # operation = proc {
993
+ # # perform a long-running operation here, such as a database query.
994
+ # "result" # as usual, the last expression evaluated in the block will be the return value.
995
+ # }
996
+ # callback = proc {|result|
997
+ # # do something with result here, such as send it back to a network client.
998
+ # }
999
+ #
1000
+ # EventMachine.defer(operation, callback)
1001
+ #
1002
+ # @param [#call] op An operation you want to offload to EventMachine thread pool
1003
+ # @param [#call] callback A callback that will be run on the event loop thread after `operation` finishes.
1004
+ #
1005
+ # @see EventMachine.threadpool_size
1006
+ def self.defer op = nil, callback = nil, &blk
1007
+ # OBSERVE that #next_tick hacks into this mechanism, so don't make any changes here
1008
+ # without syncing there.
1009
+ #
1010
+ # Running with $VERBOSE set to true gives a warning unless all ivars are defined when
1011
+ # they appear in rvalues. But we DON'T ever want to initialize @threadqueue unless we
1012
+ # need it, because the Ruby threads are so heavyweight. We end up with this bizarre
1013
+ # way of initializing @threadqueue because EventMachine is a Module, not a Class, and
1014
+ # has no constructor.
1015
+
1016
+ unless @threadpool
1017
+ require 'thread'
1018
+ @threadpool = []
1019
+ @threadqueue = ::Queue.new
1020
+ @resultqueue = ::Queue.new
1021
+ spawn_threadpool
1022
+ end
1023
+
1024
+ @threadqueue << [op||blk,callback]
1025
+ end
1026
+
1027
+
1028
+ # @private
1029
+ def self.spawn_threadpool
1030
+ until @threadpool.size == @threadpool_size.to_i
1031
+ thread = Thread.new do
1032
+ Thread.current.abort_on_exception = true
1033
+ while true
1034
+ op, cback = *@threadqueue.pop
1035
+ result = op.call
1036
+ @resultqueue << [result, cback]
1037
+ EventMachine.signal_loopbreak
1038
+ end
1039
+ end
1040
+ @threadpool << thread
1041
+ end
1042
+ end
1043
+
1044
+ class << self
1045
+ # @private
1046
+ attr_reader :threadpool
1047
+
1048
+ # Size of the EventMachine.defer threadpool (defaults to 20)
1049
+ # @return [Number]
1050
+ attr_accessor :threadpool_size
1051
+ EventMachine.threadpool_size = 20
1052
+ end
1053
+
1054
+ # Schedules a proc for execution immediately after the next "turn" through the reactor
1055
+ # core. An advanced technique, this can be useful for improving memory management and/or
1056
+ # application responsiveness, especially when scheduling large amounts of data for
1057
+ # writing to a network connection.
1058
+ #
1059
+ # This method takes either a single argument (which must be a callable object) or a block.
1060
+ #
1061
+ # @param [#call] pr A callable object to run
1062
+ def self.next_tick pr=nil, &block
1063
+ # This works by adding to the @resultqueue that's used for #defer.
1064
+ # The general idea is that next_tick is used when we want to give the reactor a chance
1065
+ # to let other operations run, either to balance the load out more evenly, or to let
1066
+ # outbound network buffers drain, or both. So we probably do NOT want to block, and
1067
+ # we probably do NOT want to be spinning any threads. A program that uses next_tick
1068
+ # but not #defer shouldn't suffer the penalty of having Ruby threads running. They're
1069
+ # extremely expensive even if they're just sleeping.
1070
+
1071
+ raise ArgumentError, "no proc or block given" unless ((pr && pr.respond_to?(:call)) or block)
1072
+ @next_tick_mutex.synchronize do
1073
+ @next_tick_queue << ( pr || block )
1074
+ end
1075
+ signal_loopbreak if reactor_running?
1076
+ end
1077
+
1078
+ # A wrapper over the setuid system call. Particularly useful when opening a network
1079
+ # server on a privileged port because you can use this call to drop privileges
1080
+ # after opening the port. Also very useful after a call to {.set_descriptor_table_size},
1081
+ # which generally requires that you start your process with root privileges.
1082
+ #
1083
+ # This method is intended for use in enforcing security requirements, consequently
1084
+ # it will throw a fatal error and end your program if it fails.
1085
+ #
1086
+ # @param [String] username The effective name of the user whose privilege-level your process should attain.
1087
+ #
1088
+ # @note This method has no effective implementation on Windows or in the pure-Ruby
1089
+ # implementation of EventMachine
1090
+ def self.set_effective_user username
1091
+ EventMachine::setuid_string username
1092
+ end
1093
+
1094
+
1095
+ # Sets the maximum number of file or socket descriptors that your process may open.
1096
+ # If you call this method with no arguments, it will simply return
1097
+ # the current size of the descriptor table without attempting to change it.
1098
+ #
1099
+ # The new limit on open descriptors **only** applies to sockets and other descriptors
1100
+ # that belong to EventMachine. It has **no effect** on the number of descriptors
1101
+ # you can create in ordinary Ruby code.
1102
+ #
1103
+ # Not available on all platforms. Increasing the number of descriptors beyond its
1104
+ # default limit usually requires superuser privileges. (See {.set_effective_user}
1105
+ # for a way to drop superuser privileges while your program is running.)
1106
+ #
1107
+ # @param [Integer] n_descriptors The maximum number of file or socket descriptors that your process may open
1108
+ # @return [Integer] The new descriptor table size.
1109
+ def self.set_descriptor_table_size n_descriptors=nil
1110
+ EventMachine::set_rlimit_nofile n_descriptors
1111
+ end
1112
+
1113
+
1114
+
1115
+ # Runs an external process.
1116
+ #
1117
+ # @example
1118
+ #
1119
+ # module RubyCounter
1120
+ # def post_init
1121
+ # # count up to 5
1122
+ # send_data "5\n"
1123
+ # end
1124
+ # def receive_data data
1125
+ # puts "ruby sent me: #{data}"
1126
+ # end
1127
+ # def unbind
1128
+ # puts "ruby died with exit status: #{get_status.exitstatus}"
1129
+ # end
1130
+ # end
1131
+ #
1132
+ # EventMachine.run {
1133
+ # EventMachine.popen("ruby -e' $stdout.sync = true; gets.to_i.times{ |i| puts i+1; sleep 1 } '", RubyCounter)
1134
+ # }
1135
+ #
1136
+ # @note This method is not supported on Microsoft Windows
1137
+ # @see EventMachine::DeferrableChildProcess
1138
+ # @see EventMachine.system
1139
+ def self.popen cmd, handler=nil, *args
1140
+ # At this moment, it's only available on Unix.
1141
+ # Perhaps misnamed since the underlying function uses socketpair and is full-duplex.
1142
+
1143
+ klass = klass_from_handler(Connection, handler, *args)
1144
+ w = Shellwords::shellwords( cmd )
1145
+ w.unshift( w.first ) if w.first
1146
+ s = invoke_popen( w )
1147
+ c = klass.new s, *args
1148
+ @conns[s] = c
1149
+ yield(c) if block_given?
1150
+ c
1151
+ end
1152
+
1153
+
1154
+ # Tells you whether the EventMachine reactor loop is currently running.
1155
+ #
1156
+ # Useful when writing libraries that want to run event-driven code, but may
1157
+ # be running in programs that are already event-driven. In such cases, if {EventMachine.reactor_running?}
1158
+ # returns false, your code can invoke {EventMachine.run} and run your application code inside
1159
+ # the block passed to that method. If this method returns true, just
1160
+ # execute your event-aware code.
1161
+ #
1162
+ # @return [Boolean] true if the EventMachine reactor loop is currently running
1163
+ def self.reactor_running?
1164
+ (@reactor_running || false)
1165
+ end
1166
+
1167
+
1168
+ # (Experimental)
1169
+ #
1170
+ # @private
1171
+ def self.open_keyboard handler=nil, *args
1172
+ klass = klass_from_handler(Connection, handler, *args)
1173
+
1174
+ s = read_keyboard
1175
+ c = klass.new s, *args
1176
+ @conns[s] = c
1177
+ block_given? and yield c
1178
+ c
1179
+ end
1180
+
1181
+ # EventMachine's file monitoring API. Currently supported are the following events
1182
+ # on individual files, using inotify on Linux systems, and kqueue for *BSD and Mac OS X:
1183
+ #
1184
+ # * File modified (written to)
1185
+ # * File moved/renamed
1186
+ # * File deleted
1187
+ #
1188
+ # EventMachine::watch_file takes a filename and a handler Module containing your custom callback methods.
1189
+ # This will setup the low level monitoring on the specified file, and create a new EventMachine::FileWatch
1190
+ # object with your Module mixed in. FileWatch is a subclass of {EventMachine::Connection}, so callbacks on this object
1191
+ # work in the familiar way. The callbacks that will be fired by EventMachine are:
1192
+ #
1193
+ # * file_modified
1194
+ # * file_moved
1195
+ # * file_deleted
1196
+ #
1197
+ # You can access the filename being monitored from within this object using {FileWatch#path}.
1198
+ #
1199
+ # When a file is deleted, {FileWatch#stop_watching} will be called after your file_deleted callback,
1200
+ # to clean up the underlying monitoring and remove EventMachine's reference to the now-useless {FileWatch} instance.
1201
+ # This will in turn call unbind, if you wish to use it.
1202
+ #
1203
+ # The corresponding system-level Errno will be raised when attempting to monitor non-existent files,
1204
+ # files with wrong permissions, or if an error occurs dealing with inotify/kqueue.
1205
+ #
1206
+ # @example
1207
+ #
1208
+ # # Before running this example, make sure we have a file to monitor:
1209
+ # # $ echo "bar" > /tmp/foo
1210
+ #
1211
+ # module Handler
1212
+ # def file_modified
1213
+ # puts "#{path} modified"
1214
+ # end
1215
+ #
1216
+ # def file_moved
1217
+ # puts "#{path} moved"
1218
+ # end
1219
+ #
1220
+ # def file_deleted
1221
+ # puts "#{path} deleted"
1222
+ # end
1223
+ #
1224
+ # def unbind
1225
+ # puts "#{path} monitoring ceased"
1226
+ # end
1227
+ # end
1228
+ #
1229
+ # # for efficient file watching, use kqueue on Mac OS X
1230
+ # EventMachine.kqueue = true if EventMachine.kqueue?
1231
+ #
1232
+ # EventMachine.run {
1233
+ # EventMachine.watch_file("/tmp/foo", Handler)
1234
+ # }
1235
+ #
1236
+ # # $ echo "baz" >> /tmp/foo => "/tmp/foo modified"
1237
+ # # $ mv /tmp/foo /tmp/oof => "/tmp/foo moved"
1238
+ # # $ rm /tmp/oof => "/tmp/foo deleted"
1239
+ #
1240
+ # @note The ability to pick up on the new filename after a rename is not yet supported.
1241
+ # Calling #path will always return the filename you originally used.
1242
+ #
1243
+ # @param [String] filename Local path to the file to watch.
1244
+ # @param [Class, Module] handler A class or module that implements event handlers associated with the file.
1245
+ def self.watch_file(filename, handler=nil, *args)
1246
+ klass = klass_from_handler(FileWatch, handler, *args)
1247
+
1248
+ s = EM::watch_filename(filename)
1249
+ c = klass.new s, *args
1250
+ # we have to set the path like this because of how Connection.new works
1251
+ c.instance_variable_set("@path", filename)
1252
+ @conns[s] = c
1253
+ block_given? and yield c
1254
+ c
1255
+ end
1256
+
1257
+ # EventMachine's process monitoring API. On Mac OS X and *BSD this method is implemented using kqueue.
1258
+ #
1259
+ # @example
1260
+ #
1261
+ # module ProcessWatcher
1262
+ # def process_exited
1263
+ # put 'the forked child died!'
1264
+ # end
1265
+ # end
1266
+ #
1267
+ # pid = fork{ sleep }
1268
+ #
1269
+ # EventMachine.run {
1270
+ # EventMachine.watch_process(pid, ProcessWatcher)
1271
+ # EventMachine.add_timer(1){ Process.kill('TERM', pid) }
1272
+ # }
1273
+ #
1274
+ # @param [Integer] pid PID of the process to watch.
1275
+ # @param [Class, Module] handler A class or module that implements event handlers associated with the file.
1276
+ def self.watch_process(pid, handler=nil, *args)
1277
+ pid = pid.to_i
1278
+
1279
+ klass = klass_from_handler(ProcessWatch, handler, *args)
1280
+
1281
+ s = EM::watch_pid(pid)
1282
+ c = klass.new s, *args
1283
+ # we have to set the path like this because of how Connection.new works
1284
+ c.instance_variable_set("@pid", pid)
1285
+ @conns[s] = c
1286
+ block_given? and yield c
1287
+ c
1288
+ end
1289
+
1290
+ # Catch-all for errors raised during event loop callbacks.
1291
+ #
1292
+ # @example
1293
+ #
1294
+ # EventMachine.error_handler{ |e|
1295
+ # puts "Error raised during event loop: #{e.message}"
1296
+ # }
1297
+ #
1298
+ # @param [#call] cb Global catch-all errback
1299
+ def self.error_handler cb = nil, &blk
1300
+ if cb or blk
1301
+ @error_handler = cb || blk
1302
+ elsif instance_variable_defined? :@error_handler
1303
+ remove_instance_variable :@error_handler
1304
+ end
1305
+ end
1306
+
1307
+ # This method allows for direct writing of incoming data back out to another descriptor, at the C++ level in the reactor.
1308
+ # This is very efficient and especially useful for proxies where high performance is required. Propogating data from a server response
1309
+ # all the way up to Ruby, and then back down to the reactor to be sent back to the client, is often unnecessary and
1310
+ # incurs a significant performance decrease.
1311
+ #
1312
+ # The two arguments are instance of {EventMachine::Connection} subclasses, 'from' and 'to'. 'from' is the connection whose inbound data you want
1313
+ # relayed back out. 'to' is the connection to write it to.
1314
+ #
1315
+ # Once you call this method, the 'from' connection will no longer get receive_data callbacks from the reactor,
1316
+ # except in the case that 'to' connection has already closed when attempting to write to it. You can see
1317
+ # in the example, that proxy_target_unbound will be called when this occurs. After that, further incoming
1318
+ # data will be passed into receive_data as normal.
1319
+ #
1320
+ # Note also that this feature supports different types of descriptors: TCP, UDP, and pipes. You can relay
1321
+ # data from one kind to another, for example, feed a pipe from a UDP stream.
1322
+ #
1323
+ # @example
1324
+ #
1325
+ # module ProxyConnection
1326
+ # def initialize(client, request)
1327
+ # @client, @request = client, request
1328
+ # end
1329
+ #
1330
+ # def post_init
1331
+ # EM::enable_proxy(self, @client)
1332
+ # end
1333
+ #
1334
+ # def connection_completed
1335
+ # send_data @request
1336
+ # end
1337
+ #
1338
+ # def proxy_target_unbound
1339
+ # close_connection
1340
+ # end
1341
+ #
1342
+ # def unbind
1343
+ # @client.close_connection_after_writing
1344
+ # end
1345
+ # end
1346
+ #
1347
+ # module ProxyServer
1348
+ # def receive_data(data)
1349
+ # (@buf ||= "") << data
1350
+ # if @buf =~ /\r\n\r\n/ # all http headers received
1351
+ # EventMachine.connect("10.0.0.15", 80, ProxyConnection, self, data)
1352
+ # end
1353
+ # end
1354
+ # end
1355
+ #
1356
+ # EventMachine.run {
1357
+ # EventMachine.start_server("127.0.0.1", 8080, ProxyServer)
1358
+ # }
1359
+ #
1360
+ # @param [EventMachine::Connection] from Source of data to be proxies/streamed.
1361
+ # @param [EventMachine::Connection] to Destination of data to be proxies/streamed.
1362
+ # @param [Integer] bufsize Buffer size to use
1363
+ # @param [Integer] length Maximum number of bytes to proxy.
1364
+ #
1365
+ # @see EventMachine.disable_proxy
1366
+ def self.enable_proxy(from, to, bufsize=0, length=0)
1367
+ EM::start_proxy(from.signature, to.signature, bufsize, length)
1368
+ end
1369
+
1370
+ # Takes just one argument, a {Connection} that has proxying enabled via {EventMachine.enable_proxy}.
1371
+ # Calling this method will remove that functionality and your connection will begin receiving
1372
+ # data via {Connection#receive_data} again.
1373
+ #
1374
+ # @param [EventMachine::Connection] from Source of data that is being proxied
1375
+ # @see EventMachine.enable_proxy
1376
+ def self.disable_proxy(from)
1377
+ EM::stop_proxy(from.signature)
1378
+ end
1379
+
1380
+ # Retrieve the heartbeat interval. This is how often EventMachine will check for dead connections
1381
+ # that have had an inactivity timeout set via {Connection#set_comm_inactivity_timeout}.
1382
+ # Default is 2 seconds.
1383
+ #
1384
+ # @return [Integer] Heartbeat interval, in seconds
1385
+ def self.heartbeat_interval
1386
+ EM::get_heartbeat_interval
1387
+ end
1388
+
1389
+ # Set the heartbeat interval. This is how often EventMachine will check for dead connections
1390
+ # that have had an inactivity timeout set via {Connection#set_comm_inactivity_timeout}.
1391
+ # Takes a Numeric number of seconds. Default is 2.
1392
+ #
1393
+ # @param [Integer] time Heartbeat interval, in seconds
1394
+ def self.heartbeat_interval=(time)
1395
+ EM::set_heartbeat_interval time.to_f
1396
+ end
1397
+
1398
+ # @private
1399
+ def self.event_callback conn_binding, opcode, data
1400
+ #
1401
+ # Changed 27Dec07: Eliminated the hookable error handling.
1402
+ # No one was using it, and it degraded performance significantly.
1403
+ # It's in original_event_callback, which is dead code.
1404
+ #
1405
+ # Changed 25Jul08: Added a partial solution to the problem of exceptions
1406
+ # raised in user-written event-handlers. If such exceptions are not caught,
1407
+ # we must cause the reactor to stop, and then re-raise the exception.
1408
+ # Otherwise, the reactor doesn't stop and it's left on the call stack.
1409
+ # This is partial because we only added it to #unbind, where it's critical
1410
+ # (to keep unbind handlers from being re-entered when a stopping reactor
1411
+ # runs down open connections). It should go on the other calls to user
1412
+ # code, but the performance impact may be too large.
1413
+ #
1414
+ if opcode == ConnectionUnbound
1415
+ if c = @conns.delete( conn_binding )
1416
+ begin
1417
+ if c.original_method(:unbind).arity != 0
1418
+ c.unbind(data == 0 ? nil : EventMachine::ERRNOS[data])
1419
+ else
1420
+ c.unbind
1421
+ end
1422
+ # If this is an attached (but not watched) connection, close the underlying io object.
1423
+ if c.instance_variable_defined?(:@io) and !c.instance_variable_get(:@watch_mode)
1424
+ io = c.instance_variable_get(:@io)
1425
+ begin
1426
+ io.close
1427
+ rescue Errno::EBADF, IOError
1428
+ end
1429
+ end
1430
+ rescue
1431
+ @wrapped_exception = $!
1432
+ stop
1433
+ end
1434
+ elsif c = @acceptors.delete( conn_binding )
1435
+ # no-op
1436
+ else
1437
+ if $! # Bubble user generated errors.
1438
+ @wrapped_exception = $!
1439
+ EM.stop
1440
+ else
1441
+ raise ConnectionNotBound, "received ConnectionUnbound for an unknown signature: #{conn_binding}"
1442
+ end
1443
+ end
1444
+ elsif opcode == ConnectionAccepted
1445
+ accep,args,blk = @acceptors[conn_binding]
1446
+ raise NoHandlerForAcceptedConnection unless accep
1447
+ c = accep.new data, *args
1448
+ @conns[data] = c
1449
+ blk and blk.call(c)
1450
+ c # (needed?)
1451
+ ##
1452
+ # The remaining code is a fallback for the pure ruby and java reactors.
1453
+ # In the C++ reactor, these events are handled in the C event_callback() in rubymain.cpp
1454
+ elsif opcode == ConnectionCompleted
1455
+ c = @conns[conn_binding] or raise ConnectionNotBound, "received ConnectionCompleted for unknown signature: #{conn_binding}"
1456
+ c.connection_completed
1457
+ elsif opcode == TimerFired
1458
+ t = @timers.delete( data )
1459
+ return if t == false # timer cancelled
1460
+ t or raise UnknownTimerFired, "timer data: #{data}"
1461
+ t.call
1462
+ elsif opcode == ConnectionData
1463
+ c = @conns[conn_binding] or raise ConnectionNotBound, "received data #{data} for unknown signature: #{conn_binding}"
1464
+ c.receive_data data
1465
+ elsif opcode == LoopbreakSignalled
1466
+ run_deferred_callbacks
1467
+ elsif opcode == ConnectionNotifyReadable
1468
+ c = @conns[conn_binding] or raise ConnectionNotBound
1469
+ c.notify_readable
1470
+ elsif opcode == ConnectionNotifyWritable
1471
+ c = @conns[conn_binding] or raise ConnectionNotBound
1472
+ c.notify_writable
1473
+ end
1474
+ end
1475
+
1476
+ #
1477
+ #
1478
+ # @private
1479
+ def self._open_file_for_writing filename, handler=nil
1480
+ klass = klass_from_handler(Connection, handler)
1481
+
1482
+ s = _write_file filename
1483
+ c = klass.new s
1484
+ @conns[s] = c
1485
+ block_given? and yield c
1486
+ c
1487
+ end
1488
+
1489
+ # @private
1490
+ def self.klass_from_handler(klass = Connection, handler = nil, *args)
1491
+ klass = if handler and handler.is_a?(Class)
1492
+ raise ArgumentError, "must provide module or subclass of #{klass.name}" unless klass >= handler
1493
+ handler
1494
+ elsif handler
1495
+ begin
1496
+ handler::EM_CONNECTION_CLASS
1497
+ rescue NameError
1498
+ handler::const_set(:EM_CONNECTION_CLASS, Class.new(klass) {include handler})
1499
+ end
1500
+ else
1501
+ klass
1502
+ end
1503
+
1504
+ arity = klass.instance_method(:initialize).arity
1505
+ expected = arity >= 0 ? arity : -(arity + 1)
1506
+ if (arity >= 0 and args.size != expected) or (arity < 0 and args.size < expected)
1507
+ raise ArgumentError, "wrong number of arguments for #{klass}#initialize (#{args.size} for #{expected})"
1508
+ end
1509
+
1510
+ klass
1511
+ end
1512
+ end # module EventMachine
1513
+
1514
+ # Alias for {EventMachine}
1515
+ EM = EventMachine
1516
+ # Alias for {EventMachine::Protocols}
1517
+ EM::P = EventMachine::Protocols