eventmachine 1.0.0.beta.2-x86-mingw32
Sign up to get free protection for your applications and to get access to all the features.
- data/.gitignore +16 -0
- data/Gemfile +1 -0
- data/README +81 -0
- data/Rakefile +11 -0
- data/docs/COPYING +60 -0
- data/docs/ChangeLog +211 -0
- data/docs/DEFERRABLES +246 -0
- data/docs/EPOLL +141 -0
- data/docs/GNU +281 -0
- data/docs/INSTALL +13 -0
- data/docs/KEYBOARD +42 -0
- data/docs/LEGAL +25 -0
- data/docs/LIGHTWEIGHT_CONCURRENCY +130 -0
- data/docs/PURE_RUBY +75 -0
- data/docs/RELEASE_NOTES +94 -0
- data/docs/SMTP +4 -0
- data/docs/SPAWNED_PROCESSES +148 -0
- data/docs/TODO +8 -0
- data/eventmachine.gemspec +33 -0
- data/examples/ex_channel.rb +43 -0
- data/examples/ex_queue.rb +2 -0
- data/examples/ex_tick_loop_array.rb +15 -0
- data/examples/ex_tick_loop_counter.rb +32 -0
- data/examples/helper.rb +2 -0
- data/ext/binder.cpp +124 -0
- data/ext/binder.h +46 -0
- data/ext/cmain.cpp +838 -0
- data/ext/ed.cpp +1884 -0
- data/ext/ed.h +418 -0
- data/ext/em.cpp +2348 -0
- data/ext/em.h +228 -0
- data/ext/eventmachine.h +123 -0
- data/ext/extconf.rb +157 -0
- data/ext/fastfilereader/extconf.rb +85 -0
- data/ext/fastfilereader/mapper.cpp +214 -0
- data/ext/fastfilereader/mapper.h +59 -0
- data/ext/fastfilereader/rubymain.cpp +127 -0
- data/ext/kb.cpp +79 -0
- data/ext/page.cpp +107 -0
- data/ext/page.h +51 -0
- data/ext/pipe.cpp +347 -0
- data/ext/project.h +155 -0
- data/ext/rubymain.cpp +1200 -0
- data/ext/ssl.cpp +460 -0
- data/ext/ssl.h +94 -0
- data/java/.classpath +8 -0
- data/java/.project +17 -0
- data/java/src/com/rubyeventmachine/EmReactor.java +571 -0
- data/java/src/com/rubyeventmachine/EmReactorException.java +40 -0
- data/java/src/com/rubyeventmachine/EventableChannel.java +69 -0
- data/java/src/com/rubyeventmachine/EventableDatagramChannel.java +189 -0
- data/java/src/com/rubyeventmachine/EventableSocketChannel.java +364 -0
- data/lib/em/buftok.rb +138 -0
- data/lib/em/callback.rb +26 -0
- data/lib/em/channel.rb +57 -0
- data/lib/em/connection.rb +569 -0
- data/lib/em/deferrable.rb +206 -0
- data/lib/em/file_watch.rb +54 -0
- data/lib/em/future.rb +61 -0
- data/lib/em/iterator.rb +270 -0
- data/lib/em/messages.rb +66 -0
- data/lib/em/process_watch.rb +44 -0
- data/lib/em/processes.rb +119 -0
- data/lib/em/protocols.rb +36 -0
- data/lib/em/protocols/header_and_content.rb +138 -0
- data/lib/em/protocols/httpclient.rb +268 -0
- data/lib/em/protocols/httpclient2.rb +590 -0
- data/lib/em/protocols/line_and_text.rb +125 -0
- data/lib/em/protocols/line_protocol.rb +28 -0
- data/lib/em/protocols/linetext2.rb +161 -0
- data/lib/em/protocols/memcache.rb +323 -0
- data/lib/em/protocols/object_protocol.rb +45 -0
- data/lib/em/protocols/postgres3.rb +247 -0
- data/lib/em/protocols/saslauth.rb +175 -0
- data/lib/em/protocols/smtpclient.rb +357 -0
- data/lib/em/protocols/smtpserver.rb +640 -0
- data/lib/em/protocols/socks4.rb +66 -0
- data/lib/em/protocols/stomp.rb +200 -0
- data/lib/em/protocols/tcptest.rb +53 -0
- data/lib/em/pure_ruby.rb +1013 -0
- data/lib/em/queue.rb +62 -0
- data/lib/em/spawnable.rb +85 -0
- data/lib/em/streamer.rb +130 -0
- data/lib/em/tick_loop.rb +85 -0
- data/lib/em/timers.rb +57 -0
- data/lib/em/version.rb +3 -0
- data/lib/eventmachine.rb +1548 -0
- data/lib/jeventmachine.rb +258 -0
- data/lib/rubyeventmachine.rb +2 -0
- data/setup.rb +1585 -0
- data/tasks/cpp.rake_example +77 -0
- data/tasks/doc.rake +30 -0
- data/tasks/package.rake +85 -0
- data/tasks/test.rake +6 -0
- data/tests/client.crt +31 -0
- data/tests/client.key +51 -0
- data/tests/test_attach.rb +136 -0
- data/tests/test_basic.rb +249 -0
- data/tests/test_channel.rb +64 -0
- data/tests/test_connection_count.rb +35 -0
- data/tests/test_defer.rb +49 -0
- data/tests/test_deferrable.rb +35 -0
- data/tests/test_epoll.rb +160 -0
- data/tests/test_error_handler.rb +35 -0
- data/tests/test_errors.rb +82 -0
- data/tests/test_exc.rb +55 -0
- data/tests/test_file_watch.rb +49 -0
- data/tests/test_futures.rb +198 -0
- data/tests/test_get_sock_opt.rb +30 -0
- data/tests/test_handler_check.rb +37 -0
- data/tests/test_hc.rb +190 -0
- data/tests/test_httpclient.rb +227 -0
- data/tests/test_httpclient2.rb +154 -0
- data/tests/test_inactivity_timeout.rb +50 -0
- data/tests/test_kb.rb +60 -0
- data/tests/test_ltp.rb +190 -0
- data/tests/test_ltp2.rb +317 -0
- data/tests/test_next_tick.rb +133 -0
- data/tests/test_object_protocol.rb +37 -0
- data/tests/test_pause.rb +70 -0
- data/tests/test_pending_connect_timeout.rb +48 -0
- data/tests/test_process_watch.rb +50 -0
- data/tests/test_processes.rb +128 -0
- data/tests/test_proxy_connection.rb +144 -0
- data/tests/test_pure.rb +134 -0
- data/tests/test_queue.rb +44 -0
- data/tests/test_running.rb +42 -0
- data/tests/test_sasl.rb +72 -0
- data/tests/test_send_file.rb +251 -0
- data/tests/test_servers.rb +76 -0
- data/tests/test_smtpclient.rb +83 -0
- data/tests/test_smtpserver.rb +85 -0
- data/tests/test_spawn.rb +322 -0
- data/tests/test_ssl_args.rb +79 -0
- data/tests/test_ssl_methods.rb +50 -0
- data/tests/test_ssl_verify.rb +82 -0
- data/tests/test_tick_loop.rb +59 -0
- data/tests/test_timers.rb +160 -0
- data/tests/test_ud.rb +36 -0
- data/tests/testem.rb +31 -0
- metadata +240 -0
data/lib/em/queue.rb
ADDED
@@ -0,0 +1,62 @@
|
|
1
|
+
module EventMachine
|
2
|
+
# A cross thread, reactor scheduled, linear queue.
|
3
|
+
#
|
4
|
+
# This class provides a simple "Queue" like abstraction on top of the reactor
|
5
|
+
# scheduler. It services two primary purposes:
|
6
|
+
# * API sugar for stateful protocols
|
7
|
+
# * Pushing processing onto the same thread as the reactor
|
8
|
+
#
|
9
|
+
# See examples/ex_queue.rb for a detailed example.
|
10
|
+
#
|
11
|
+
# q = EM::Queue.new
|
12
|
+
# q.push('one', 'two', 'three')
|
13
|
+
# 3.times do
|
14
|
+
# q.pop{ |msg| puts(msg) }
|
15
|
+
# end
|
16
|
+
#
|
17
|
+
class Queue
|
18
|
+
# Create a new queue
|
19
|
+
def initialize
|
20
|
+
@items = []
|
21
|
+
@popq = []
|
22
|
+
end
|
23
|
+
|
24
|
+
# Pop items off the queue, running the block on the reactor thread. The pop
|
25
|
+
# will not happen immediately, but at some point in the future, either in
|
26
|
+
# the next tick, if the queue has data, or when the queue is populated.
|
27
|
+
def pop(*a, &b)
|
28
|
+
cb = EM::Callback(*a, &b)
|
29
|
+
EM.schedule do
|
30
|
+
if @items.empty?
|
31
|
+
@popq << cb
|
32
|
+
else
|
33
|
+
cb.call @items.shift
|
34
|
+
end
|
35
|
+
end
|
36
|
+
nil # Always returns nil
|
37
|
+
end
|
38
|
+
|
39
|
+
# Push items onto the queue in the reactor thread. The items will not appear
|
40
|
+
# in the queue immediately, but will be scheduled for addition during the
|
41
|
+
# next reactor tick.
|
42
|
+
def push(*items)
|
43
|
+
EM.schedule do
|
44
|
+
@items.push(*items)
|
45
|
+
@popq.shift.call @items.shift until @items.empty? || @popq.empty?
|
46
|
+
end
|
47
|
+
end
|
48
|
+
alias :<< :push
|
49
|
+
|
50
|
+
# N.B. This is a peek, it's not thread safe, and may only tend toward
|
51
|
+
# accuracy.
|
52
|
+
def empty?
|
53
|
+
@items.empty?
|
54
|
+
end
|
55
|
+
|
56
|
+
# N.B. This is a peek, it's not thread safe, and may only tend toward
|
57
|
+
# accuracy.
|
58
|
+
def size
|
59
|
+
@items.size
|
60
|
+
end
|
61
|
+
end
|
62
|
+
end
|
data/lib/em/spawnable.rb
ADDED
@@ -0,0 +1,85 @@
|
|
1
|
+
#--
|
2
|
+
#
|
3
|
+
# Author:: Francis Cianfrocca (gmail: blackhedd)
|
4
|
+
# Homepage:: http://rubyeventmachine.com
|
5
|
+
# Date:: 25 Aug 2007
|
6
|
+
#
|
7
|
+
# See EventMachine and EventMachine::Connection for documentation and
|
8
|
+
# usage examples.
|
9
|
+
#
|
10
|
+
#----------------------------------------------------------------------------
|
11
|
+
#
|
12
|
+
# Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
|
13
|
+
# Gmail: blackhedd
|
14
|
+
#
|
15
|
+
# This program is free software; you can redistribute it and/or modify
|
16
|
+
# it under the terms of either: 1) the GNU General Public License
|
17
|
+
# as published by the Free Software Foundation; either version 2 of the
|
18
|
+
# License, or (at your option) any later version; or 2) Ruby's License.
|
19
|
+
#
|
20
|
+
# See the file COPYING for complete licensing information.
|
21
|
+
#
|
22
|
+
#---------------------------------------------------------------------------
|
23
|
+
#
|
24
|
+
#
|
25
|
+
|
26
|
+
module EventMachine
|
27
|
+
# Support for Erlang-style processes.
|
28
|
+
#
|
29
|
+
class SpawnedProcess
|
30
|
+
# Send a message to the spawned process
|
31
|
+
def notify *x
|
32
|
+
me = self
|
33
|
+
EM.next_tick {
|
34
|
+
# A notification executes in the context of this
|
35
|
+
# SpawnedProcess object. That makes self and notify
|
36
|
+
# work as one would expect.
|
37
|
+
#
|
38
|
+
y = me.call(*x)
|
39
|
+
if y and y.respond_to?(:pull_out_yield_block)
|
40
|
+
a,b = y.pull_out_yield_block
|
41
|
+
set_receiver a
|
42
|
+
self.notify if b
|
43
|
+
end
|
44
|
+
}
|
45
|
+
end
|
46
|
+
alias_method :resume, :notify
|
47
|
+
alias_method :run, :notify # for formulations like (EM.spawn {xxx}).run
|
48
|
+
#attr_accessor :receiver
|
49
|
+
|
50
|
+
#--
|
51
|
+
# I know I'm missing something stupid, but the inside of class << s
|
52
|
+
# can't see locally-bound values. It can see globals, though.
|
53
|
+
def set_receiver blk
|
54
|
+
$em______tmpglobal = blk
|
55
|
+
class << self
|
56
|
+
define_method :call, $em______tmpglobal.dup
|
57
|
+
end
|
58
|
+
end
|
59
|
+
|
60
|
+
end
|
61
|
+
|
62
|
+
class YieldBlockFromSpawnedProcess # :nodoc:
|
63
|
+
def initialize block, notify
|
64
|
+
@block = [block,notify]
|
65
|
+
end
|
66
|
+
def pull_out_yield_block
|
67
|
+
@block
|
68
|
+
end
|
69
|
+
end
|
70
|
+
|
71
|
+
# Spawn an erlang-style process
|
72
|
+
def self.spawn &block
|
73
|
+
s = SpawnedProcess.new
|
74
|
+
s.set_receiver block
|
75
|
+
s
|
76
|
+
end
|
77
|
+
|
78
|
+
def self.yield &block # :nodoc:
|
79
|
+
return YieldBlockFromSpawnedProcess.new( block, false )
|
80
|
+
end
|
81
|
+
|
82
|
+
def self.yield_and_notify &block # :nodoc:
|
83
|
+
return YieldBlockFromSpawnedProcess.new( block, true )
|
84
|
+
end
|
85
|
+
end
|
data/lib/em/streamer.rb
ADDED
@@ -0,0 +1,130 @@
|
|
1
|
+
#--
|
2
|
+
#
|
3
|
+
# Author:: Francis Cianfrocca (gmail: blackhedd)
|
4
|
+
# Homepage:: http://rubyeventmachine.com
|
5
|
+
# Date:: 16 Jul 2006
|
6
|
+
#
|
7
|
+
# See EventMachine and EventMachine::Connection for documentation and
|
8
|
+
# usage examples.
|
9
|
+
#
|
10
|
+
#----------------------------------------------------------------------------
|
11
|
+
#
|
12
|
+
# Copyright (C) 2006-07 by Francis Cianfrocca. All Rights Reserved.
|
13
|
+
# Gmail: blackhedd
|
14
|
+
#
|
15
|
+
# This program is free software; you can redistribute it and/or modify
|
16
|
+
# it under the terms of either: 1) the GNU General Public License
|
17
|
+
# as published by the Free Software Foundation; either version 2 of the
|
18
|
+
# License, or (at your option) any later version; or 2) Ruby's License.
|
19
|
+
#
|
20
|
+
# See the file COPYING for complete licensing information.
|
21
|
+
#
|
22
|
+
#---------------------------------------------------------------------------
|
23
|
+
#
|
24
|
+
#
|
25
|
+
|
26
|
+
|
27
|
+
module EventMachine
|
28
|
+
class FileStreamer
|
29
|
+
include Deferrable
|
30
|
+
|
31
|
+
# Use mapped streamer for files bigger than 16k
|
32
|
+
MappingThreshold = 16384
|
33
|
+
# Wait until next tick to send more data when 50k is still in the outgoing buffer
|
34
|
+
BackpressureLevel = 50000
|
35
|
+
# Send 16k chunks at a time
|
36
|
+
ChunkSize = 16384
|
37
|
+
|
38
|
+
# Stream a file over a given connection. An optional :http_chunks => true argument will
|
39
|
+
# use HTTP 1.1 style chunked-encoding semantics.
|
40
|
+
#
|
41
|
+
# module FileSender
|
42
|
+
# def post_init
|
43
|
+
# streamer = EventMachine::FileStreamer.new(self, '/tmp/bigfile.tar')
|
44
|
+
# streamer.callback{
|
45
|
+
# # file was sent successfully
|
46
|
+
# close_connection_after_writing
|
47
|
+
# }
|
48
|
+
# end
|
49
|
+
# end
|
50
|
+
#
|
51
|
+
def initialize connection, filename, args = {}
|
52
|
+
@connection = connection
|
53
|
+
@http_chunks = args[:http_chunks]
|
54
|
+
|
55
|
+
if File.exist?(filename)
|
56
|
+
@size = File.size(filename)
|
57
|
+
if @size <= MappingThreshold
|
58
|
+
stream_without_mapping filename
|
59
|
+
else
|
60
|
+
stream_with_mapping filename
|
61
|
+
end
|
62
|
+
else
|
63
|
+
fail "file not found"
|
64
|
+
end
|
65
|
+
end
|
66
|
+
|
67
|
+
def stream_without_mapping filename # :nodoc:
|
68
|
+
if @http_chunks
|
69
|
+
@connection.send_data "#{@size.to_s(16)}\r\n"
|
70
|
+
@connection.send_file_data filename
|
71
|
+
@connection.send_data "\r\n0\r\n\r\n"
|
72
|
+
else
|
73
|
+
@connection.send_file_data filename
|
74
|
+
end
|
75
|
+
succeed
|
76
|
+
end
|
77
|
+
private :stream_without_mapping
|
78
|
+
|
79
|
+
def stream_with_mapping filename # :nodoc:
|
80
|
+
ensure_mapping_extension_is_present
|
81
|
+
|
82
|
+
@position = 0
|
83
|
+
@mapping = EventMachine::FastFileReader::Mapper.new filename
|
84
|
+
stream_one_chunk
|
85
|
+
end
|
86
|
+
private :stream_with_mapping
|
87
|
+
|
88
|
+
# Used internally to stream one chunk at a time over multiple reactor ticks
|
89
|
+
def stream_one_chunk
|
90
|
+
loop {
|
91
|
+
if @position < @size
|
92
|
+
if @connection.get_outbound_data_size > BackpressureLevel
|
93
|
+
EventMachine::next_tick {stream_one_chunk}
|
94
|
+
break
|
95
|
+
else
|
96
|
+
len = @size - @position
|
97
|
+
len = ChunkSize if (len > ChunkSize)
|
98
|
+
|
99
|
+
@connection.send_data( "#{len.to_s(16)}\r\n" ) if @http_chunks
|
100
|
+
@connection.send_data( @mapping.get_chunk( @position, len ))
|
101
|
+
@connection.send_data("\r\n") if @http_chunks
|
102
|
+
|
103
|
+
@position += len
|
104
|
+
end
|
105
|
+
else
|
106
|
+
@connection.send_data "0\r\n\r\n" if @http_chunks
|
107
|
+
@mapping.close
|
108
|
+
succeed
|
109
|
+
break
|
110
|
+
end
|
111
|
+
}
|
112
|
+
end
|
113
|
+
|
114
|
+
#--
|
115
|
+
# We use an outboard extension class to get memory-mapped files.
|
116
|
+
# It's outboard to avoid polluting the core distro, but that means
|
117
|
+
# there's a "hidden" dependency on it. The first time we get here in
|
118
|
+
# any run, try to load up the dependency extension. User code will see
|
119
|
+
# a LoadError if it's not available, but code that doesn't require
|
120
|
+
# mapped files will work fine without it. This is a somewhat difficult
|
121
|
+
# compromise between usability and proper modularization.
|
122
|
+
#
|
123
|
+
def ensure_mapping_extension_is_present # :nodoc:
|
124
|
+
@@fastfilereader ||= (require 'fastfilereaderext')
|
125
|
+
end
|
126
|
+
private :ensure_mapping_extension_is_present
|
127
|
+
|
128
|
+
end
|
129
|
+
end
|
130
|
+
|
data/lib/em/tick_loop.rb
ADDED
@@ -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
|
data/lib/em/timers.rb
ADDED
@@ -0,0 +1,57 @@
|
|
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
|
+
# n = 0
|
24
|
+
# timer = EventMachine::PeriodicTimer.new(5) do
|
25
|
+
# puts "the time is #{Time.now}"
|
26
|
+
# timer.cancel if (n+=1) > 5
|
27
|
+
# end
|
28
|
+
#
|
29
|
+
class PeriodicTimer
|
30
|
+
# Create a new periodic timer that executes every interval seconds
|
31
|
+
def initialize interval, callback=nil, &block
|
32
|
+
@interval = interval
|
33
|
+
@code = callback || block
|
34
|
+
@cancelled = false
|
35
|
+
@work = method(:fire)
|
36
|
+
schedule
|
37
|
+
end
|
38
|
+
|
39
|
+
# Cancel the periodic timer
|
40
|
+
def cancel
|
41
|
+
@cancelled = true
|
42
|
+
end
|
43
|
+
|
44
|
+
# Fire the timer every interval seconds
|
45
|
+
attr_accessor :interval
|
46
|
+
|
47
|
+
def schedule # :nodoc:
|
48
|
+
EventMachine::add_timer @interval, @work
|
49
|
+
end
|
50
|
+
def fire # :nodoc:
|
51
|
+
unless @cancelled
|
52
|
+
@code.call
|
53
|
+
schedule
|
54
|
+
end
|
55
|
+
end
|
56
|
+
end
|
57
|
+
end
|
data/lib/em/version.rb
ADDED
data/lib/eventmachine.rb
ADDED
@@ -0,0 +1,1548 @@
|
|
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/deferrable'
|
17
|
+
require 'em/future'
|
18
|
+
require 'em/streamer'
|
19
|
+
require 'em/spawnable'
|
20
|
+
require 'em/processes'
|
21
|
+
require 'em/iterator'
|
22
|
+
require 'em/buftok'
|
23
|
+
require 'em/timers'
|
24
|
+
require 'em/protocols'
|
25
|
+
require 'em/connection'
|
26
|
+
require 'em/callback'
|
27
|
+
require 'em/queue'
|
28
|
+
require 'em/channel'
|
29
|
+
require 'em/file_watch'
|
30
|
+
require 'em/process_watch'
|
31
|
+
require 'em/tick_loop'
|
32
|
+
|
33
|
+
require 'shellwords'
|
34
|
+
require 'thread'
|
35
|
+
|
36
|
+
# == Introduction
|
37
|
+
# EventMachine provides a fast, lightweight framework for implementing
|
38
|
+
# Ruby programs that can use the network to communicate with other
|
39
|
+
# processes. Using EventMachine, Ruby programmers can easily connect
|
40
|
+
# to remote servers and act as servers themselves. EventMachine does not
|
41
|
+
# supplant the Ruby IP libraries. It does provide an alternate technique
|
42
|
+
# for those applications requiring better performance, scalability,
|
43
|
+
# and discipline over the behavior of network sockets, than is easily
|
44
|
+
# obtainable using the built-in libraries, especially in applications
|
45
|
+
# which are structurally well-suited for the event-driven programming model.
|
46
|
+
#
|
47
|
+
# EventMachine provides a perpetual event-loop which your programs can
|
48
|
+
# start and stop. Within the event loop, TCP network connections are
|
49
|
+
# initiated and accepted, based on EventMachine methods called by your
|
50
|
+
# program. You also define callback methods which are called by EventMachine
|
51
|
+
# when events of interest occur within the event-loop.
|
52
|
+
#
|
53
|
+
# User programs will be called back when the following events occur:
|
54
|
+
# * When the event loop accepts network connections from remote peers
|
55
|
+
# * When data is received from network connections
|
56
|
+
# * When connections are closed, either by the local or the remote side
|
57
|
+
# * When user-defined timers expire
|
58
|
+
#
|
59
|
+
# == Usage example
|
60
|
+
#
|
61
|
+
# Here's a fully-functional echo server implemented in EventMachine:
|
62
|
+
#
|
63
|
+
# require 'eventmachine'
|
64
|
+
#
|
65
|
+
# module EchoServer
|
66
|
+
# def post_init
|
67
|
+
# puts "-- someone connected to the echo server!"
|
68
|
+
# end
|
69
|
+
#
|
70
|
+
# def receive_data data
|
71
|
+
# send_data ">>>you sent: #{data}"
|
72
|
+
# close_connection if data =~ /quit/i
|
73
|
+
# end
|
74
|
+
#
|
75
|
+
# def unbind
|
76
|
+
# puts "-- someone disconnected from the echo server!"
|
77
|
+
# end
|
78
|
+
# end
|
79
|
+
#
|
80
|
+
# EventMachine::run {
|
81
|
+
# EventMachine::start_server "127.0.0.1", 8081, EchoServer
|
82
|
+
# }
|
83
|
+
#
|
84
|
+
# What's going on here? Well, we have defined the module EchoServer to
|
85
|
+
# implement the semantics of the echo protocol (more about that shortly).
|
86
|
+
# The last three lines invoke the event-machine itself, which runs forever
|
87
|
+
# unless one of your callbacks terminates it. The block that you supply
|
88
|
+
# to EventMachine::run contains code that runs immediately after the event
|
89
|
+
# machine is initialized and before it starts looping. This is the place
|
90
|
+
# to open up a TCP server by specifying the address and port it will listen
|
91
|
+
# on, together with the module that will process the data.
|
92
|
+
#
|
93
|
+
# Our EchoServer is extremely simple as the echo protocol doesn't require
|
94
|
+
# much work. Basically you want to send back to the remote peer whatever
|
95
|
+
# data it sends you. We'll dress it up with a little extra text to make it
|
96
|
+
# interesting. Also, we'll close the connection in case the received data
|
97
|
+
# contains the word "quit."
|
98
|
+
#
|
99
|
+
# So what about this module EchoServer? Well, whenever a network connection
|
100
|
+
# (either a client or a server) starts up, EventMachine instantiates an anonymous
|
101
|
+
# class, that your module has been mixed into. Exactly one of these class
|
102
|
+
# instances is created for each connection. Whenever an event occurs on a
|
103
|
+
# given connection, its corresponding object automatically calls specific
|
104
|
+
# instance methods which your module may redefine. The code in your module
|
105
|
+
# always runs in the context of a class instance, so you can create instance
|
106
|
+
# variables as you wish and they will be carried over to other callbacks
|
107
|
+
# made on that same connection.
|
108
|
+
#
|
109
|
+
# Looking back up at EchoServer, you can see that we've defined the method
|
110
|
+
# receive_data which (big surprise) is called whenever data has been received
|
111
|
+
# from the remote end of the connection. Very simple. We get the data
|
112
|
+
# (a String object) and can do whatever we wish with it. In this case,
|
113
|
+
# we use the method send_data to return the received data to the caller,
|
114
|
+
# with some extra text added in. And if the user sends the word "quit,"
|
115
|
+
# we'll close the connection with (naturally) close_connection.
|
116
|
+
# (Notice that closing the connection doesn't terminate the processing loop,
|
117
|
+
# or change the fact that your echo server is still accepting connections!)
|
118
|
+
#
|
119
|
+
# == Questions and Futures
|
120
|
+
# Would it be useful for EventMachine to incorporate the Observer pattern
|
121
|
+
# and make use of the corresponding Ruby <tt>observer</tt> package?
|
122
|
+
# Interesting thought.
|
123
|
+
#
|
124
|
+
module EventMachine
|
125
|
+
class <<self
|
126
|
+
# Exposed to allow joining on the thread, when run in a multithreaded
|
127
|
+
# environment. Performing other actions on the thread has undefined
|
128
|
+
# semantics.
|
129
|
+
attr_reader :reactor_thread
|
130
|
+
end
|
131
|
+
@next_tick_mutex = Mutex.new
|
132
|
+
@reactor_running = false
|
133
|
+
@next_tick_queue = []
|
134
|
+
@threadpool = nil
|
135
|
+
|
136
|
+
|
137
|
+
# EventMachine::run initializes and runs an event loop.
|
138
|
+
# This method only returns if user-callback code calls stop_event_loop.
|
139
|
+
# Use the supplied block to define your clients and servers.
|
140
|
+
# The block is called by EventMachine::run immediately after initializing
|
141
|
+
# its internal event loop but <i>before</i> running the loop.
|
142
|
+
# Therefore this block is the right place to call start_server if you
|
143
|
+
# want to accept connections from remote clients.
|
144
|
+
#
|
145
|
+
# For programs that are structured as servers, it's usually appropriate
|
146
|
+
# to start an event loop by calling EventMachine::run, and let it
|
147
|
+
# run forever. It's also possible to use EventMachine::run to make a single
|
148
|
+
# client-connection to a remote server, process the data flow from that
|
149
|
+
# single connection, and then call stop_event_loop to force EventMachine::run
|
150
|
+
# to return. Your program will then continue from the point immediately
|
151
|
+
# following the call to EventMachine::run.
|
152
|
+
#
|
153
|
+
# You can of course do both client and servers simultaneously in the same program.
|
154
|
+
# One of the strengths of the event-driven programming model is that the
|
155
|
+
# handling of network events on many different connections will be interleaved,
|
156
|
+
# and scheduled according to the actual events themselves. This maximizes
|
157
|
+
# efficiency.
|
158
|
+
#
|
159
|
+
# === Server usage example
|
160
|
+
#
|
161
|
+
# See EventMachine.start_server
|
162
|
+
#
|
163
|
+
# === Client usage example
|
164
|
+
#
|
165
|
+
# See EventMachine.connect
|
166
|
+
#
|
167
|
+
#--
|
168
|
+
# Obsoleted the use_threads mechanism.
|
169
|
+
# 25Nov06: Added the begin/ensure block. We need to be sure that release_machine
|
170
|
+
# gets called even if an exception gets thrown within any of the user code
|
171
|
+
# that the event loop runs. The best way to see this is to run a unit
|
172
|
+
# test with two functions, each of which calls EventMachine#run and each of
|
173
|
+
# which throws something inside of #run. Without the ensure, the second test
|
174
|
+
# will start without release_machine being called and will immediately throw
|
175
|
+
# a C++ runtime error.
|
176
|
+
#
|
177
|
+
def self.run blk=nil, tail=nil, &block
|
178
|
+
@tails ||= []
|
179
|
+
tail and @tails.unshift(tail)
|
180
|
+
|
181
|
+
if reactor_running?
|
182
|
+
(b = blk || block) and b.call # next_tick(b)
|
183
|
+
else
|
184
|
+
@conns = {}
|
185
|
+
@acceptors = {}
|
186
|
+
@timers = {}
|
187
|
+
@wrapped_exception = nil
|
188
|
+
@next_tick_queue ||= []
|
189
|
+
begin
|
190
|
+
@reactor_running = true
|
191
|
+
initialize_event_machine
|
192
|
+
(b = blk || block) and add_timer(0, b)
|
193
|
+
if @next_tick_queue && !@next_tick_queue.empty?
|
194
|
+
add_timer(0) { signal_loopbreak }
|
195
|
+
end
|
196
|
+
@reactor_thread = Thread.current
|
197
|
+
run_machine
|
198
|
+
ensure
|
199
|
+
until @tails.empty?
|
200
|
+
@tails.pop.call
|
201
|
+
end
|
202
|
+
|
203
|
+
begin
|
204
|
+
release_machine
|
205
|
+
ensure
|
206
|
+
if @threadpool
|
207
|
+
@threadpool.each { |t| t.exit }
|
208
|
+
@threadpool.each do |t|
|
209
|
+
next unless t.alive?
|
210
|
+
begin
|
211
|
+
# Thread#kill! does not exist on 1.9 or rbx, and raises
|
212
|
+
# NotImplemented on jruby
|
213
|
+
t.kill!
|
214
|
+
rescue NoMethodError, NotImplementedError
|
215
|
+
t.kill
|
216
|
+
# XXX t.join here?
|
217
|
+
end
|
218
|
+
end
|
219
|
+
@threadqueue = nil
|
220
|
+
@resultqueue = nil
|
221
|
+
@threadpool = nil
|
222
|
+
end
|
223
|
+
|
224
|
+
@next_tick_queue = []
|
225
|
+
end
|
226
|
+
@reactor_running = false
|
227
|
+
@reactor_thread = nil
|
228
|
+
end
|
229
|
+
|
230
|
+
raise @wrapped_exception if @wrapped_exception
|
231
|
+
end
|
232
|
+
end
|
233
|
+
|
234
|
+
# Sugars a common use case. Will pass the given block to #run, but will terminate
|
235
|
+
# the reactor loop and exit the function as soon as the code in the block completes.
|
236
|
+
# (Normally, #run keeps running indefinitely, even after the block supplied to it
|
237
|
+
# finishes running, until user code calls #stop.)
|
238
|
+
#
|
239
|
+
def self.run_block &block
|
240
|
+
pr = proc {
|
241
|
+
block.call
|
242
|
+
EventMachine::stop
|
243
|
+
}
|
244
|
+
run(&pr)
|
245
|
+
end
|
246
|
+
|
247
|
+
# Returns true if the calling thread is the same thread as the reactor.
|
248
|
+
def self.reactor_thread?
|
249
|
+
Thread.current == @reactor_thread
|
250
|
+
end
|
251
|
+
|
252
|
+
# Runs the given callback on the reactor thread, or immediately if called
|
253
|
+
# from the reactor thread. Accepts the same arguments as EM::Callback
|
254
|
+
def self.schedule(*a, &b)
|
255
|
+
cb = Callback(*a, &b)
|
256
|
+
if reactor_running? && reactor_thread?
|
257
|
+
cb.call
|
258
|
+
else
|
259
|
+
next_tick { cb.call }
|
260
|
+
end
|
261
|
+
end
|
262
|
+
|
263
|
+
# fork_reactor forks a new process and calls EM#run inside of it, passing your block.
|
264
|
+
#--
|
265
|
+
# This implementation is subject to change, especially if we clean up the relationship
|
266
|
+
# of EM#run to @reactor_running.
|
267
|
+
# Original patch by Aman Gupta.
|
268
|
+
#
|
269
|
+
def self.fork_reactor &block
|
270
|
+
Kernel.fork do
|
271
|
+
if self.reactor_running?
|
272
|
+
self.stop_event_loop
|
273
|
+
self.release_machine
|
274
|
+
self.instance_variable_set( '@reactor_running', false )
|
275
|
+
end
|
276
|
+
self.run block
|
277
|
+
end
|
278
|
+
end
|
279
|
+
|
280
|
+
# EventMachine#add_timer adds a one-shot timer to the event loop.
|
281
|
+
# Call it with one or two parameters. The first parameters is a delay-time
|
282
|
+
# expressed in <i>seconds</i> (not milliseconds). The second parameter, if
|
283
|
+
# present, must be a proc object. If a proc object is not given, then you
|
284
|
+
# can also simply pass a block to the method call.
|
285
|
+
#
|
286
|
+
# EventMachine#add_timer may be called from the block passed to EventMachine#run
|
287
|
+
# or from any callback method. It schedules execution of the proc or block
|
288
|
+
# passed to add_timer, after the passage of an interval of time equal to
|
289
|
+
# <i>at least</i> the number of seconds specified in the first parameter to
|
290
|
+
# the call.
|
291
|
+
#
|
292
|
+
# EventMachine#add_timer is a <i>non-blocking</i> call. Callbacks can and will
|
293
|
+
# be called during the interval of time that the timer is in effect.
|
294
|
+
# There is no built-in limit to the number of timers that can be outstanding at
|
295
|
+
# any given time.
|
296
|
+
#
|
297
|
+
# === Usage example
|
298
|
+
#
|
299
|
+
# This example shows how easy timers are to use. Observe that two timers are
|
300
|
+
# initiated simultaneously. Also, notice that the event loop will continue
|
301
|
+
# to run even after the second timer event is processed, since there was
|
302
|
+
# no call to EventMachine#stop_event_loop. There will be no activity, of
|
303
|
+
# course, since no network clients or servers are defined. Stop the program
|
304
|
+
# with Ctrl-C.
|
305
|
+
#
|
306
|
+
# EventMachine::run {
|
307
|
+
# puts "Starting the run now: #{Time.now}"
|
308
|
+
# EventMachine::add_timer 5, proc { puts "Executing timer event: #{Time.now}" }
|
309
|
+
# EventMachine::add_timer( 10 ) { puts "Executing timer event: #{Time.now}" }
|
310
|
+
# }
|
311
|
+
#
|
312
|
+
#
|
313
|
+
# Also see EventMachine::Timer
|
314
|
+
#--
|
315
|
+
# Changed 04Oct06: We now pass the interval as an integer number of milliseconds.
|
316
|
+
#
|
317
|
+
def self.add_timer *args, &block
|
318
|
+
interval = args.shift
|
319
|
+
code = args.shift || block
|
320
|
+
if code
|
321
|
+
# check too many timers!
|
322
|
+
s = add_oneshot_timer((interval.to_f * 1000).to_i)
|
323
|
+
@timers[s] = code
|
324
|
+
s
|
325
|
+
end
|
326
|
+
end
|
327
|
+
|
328
|
+
# EventMachine#add_periodic_timer adds a periodic timer to the event loop.
|
329
|
+
# It takes the same parameters as the one-shot timer method, EventMachine#add_timer.
|
330
|
+
# This method schedules execution of the given block repeatedly, at intervals
|
331
|
+
# of time <i>at least</i> as great as the number of seconds given in the first
|
332
|
+
# parameter to the call.
|
333
|
+
#
|
334
|
+
# === Usage example
|
335
|
+
#
|
336
|
+
# The following sample program will write a dollar-sign to stderr every five seconds.
|
337
|
+
# (Of course if the program defined network clients and/or servers, they would
|
338
|
+
# be doing their work while the periodic timer is counting off.)
|
339
|
+
#
|
340
|
+
# EventMachine::run {
|
341
|
+
# EventMachine::add_periodic_timer( 5 ) { $stderr.write "$" }
|
342
|
+
# }
|
343
|
+
#
|
344
|
+
#
|
345
|
+
# Also see EventMachine::PeriodicTimer
|
346
|
+
#
|
347
|
+
def self.add_periodic_timer *args, &block
|
348
|
+
interval = args.shift
|
349
|
+
code = args.shift || block
|
350
|
+
|
351
|
+
EventMachine::PeriodicTimer.new(interval, code)
|
352
|
+
end
|
353
|
+
|
354
|
+
# Cancel a timer using its signature. You can also use EventMachine::Timer#cancel
|
355
|
+
#
|
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
|
+
# stop_event_loop may called from within a callback method
|
366
|
+
# while EventMachine's processing loop is running.
|
367
|
+
# It causes the processing loop to stop executing, which
|
368
|
+
# will cause all open connections and accepting servers
|
369
|
+
# to be run down and closed. <i>Callbacks for connection-termination
|
370
|
+
# will be called</i> as part of the processing of stop_event_loop.
|
371
|
+
# (There currently is no option to panic-stop the loop without
|
372
|
+
# closing connections.) When all of this processing is complete,
|
373
|
+
# the call to EventMachine::run which started the processing loop
|
374
|
+
# will return and program flow will resume from the statement
|
375
|
+
# following EventMachine::run call.
|
376
|
+
#
|
377
|
+
# === Usage example
|
378
|
+
#
|
379
|
+
# require 'rubygems'
|
380
|
+
# require 'eventmachine'
|
381
|
+
#
|
382
|
+
# module Redmond
|
383
|
+
# def post_init
|
384
|
+
# puts "We're sending a dumb HTTP request to the remote peer."
|
385
|
+
# send_data "GET / HTTP/1.1\r\nHost: www.microsoft.com\r\n\r\n"
|
386
|
+
# end
|
387
|
+
#
|
388
|
+
# def receive_data data
|
389
|
+
# puts "We received #{data.length} bytes from the remote peer."
|
390
|
+
# puts "We're going to stop the event loop now."
|
391
|
+
# EventMachine::stop_event_loop
|
392
|
+
# end
|
393
|
+
#
|
394
|
+
# def unbind
|
395
|
+
# puts "A connection has terminated."
|
396
|
+
# end
|
397
|
+
# end
|
398
|
+
#
|
399
|
+
# puts "We're starting the event loop now."
|
400
|
+
# EventMachine::run {
|
401
|
+
# EventMachine::connect "www.microsoft.com", 80, Redmond
|
402
|
+
# }
|
403
|
+
# puts "The event loop has stopped."
|
404
|
+
#
|
405
|
+
# This program will produce approximately the following output:
|
406
|
+
#
|
407
|
+
# We're starting the event loop now.
|
408
|
+
# We're sending a dumb HTTP request to the remote peer.
|
409
|
+
# We received 1440 bytes from the remote peer.
|
410
|
+
# We're going to stop the event loop now.
|
411
|
+
# A connection has terminated.
|
412
|
+
# The event loop has stopped.
|
413
|
+
#
|
414
|
+
#
|
415
|
+
def self.stop_event_loop
|
416
|
+
EventMachine::stop
|
417
|
+
end
|
418
|
+
|
419
|
+
# EventMachine::start_server initiates a TCP server (socket
|
420
|
+
# acceptor) on the specified IP address and port.
|
421
|
+
# The IP address must be valid on the machine where the program
|
422
|
+
# runs, and the process must be privileged enough to listen
|
423
|
+
# on the specified port (on Unix-like systems, superuser privileges
|
424
|
+
# are usually required to listen on any port lower than 1024).
|
425
|
+
# Only one listener may be running on any given address/port
|
426
|
+
# combination. start_server will fail if the given address and port
|
427
|
+
# are already listening on the machine, either because of a prior call
|
428
|
+
# to start_server or some unrelated process running on the machine.
|
429
|
+
# If start_server succeeds, the new network listener becomes active
|
430
|
+
# immediately and starts accepting connections from remote peers,
|
431
|
+
# and these connections generate callback events that are processed
|
432
|
+
# by the code specified in the handler parameter to start_server.
|
433
|
+
#
|
434
|
+
# The optional handler which is passed to start_server is the key
|
435
|
+
# to EventMachine's ability to handle particular network protocols.
|
436
|
+
# The handler parameter passed to start_server must be a Ruby Module
|
437
|
+
# that you must define. When the network server that is started by
|
438
|
+
# start_server accepts a new connection, it instantiates a new
|
439
|
+
# object of an anonymous class that is inherited from EventMachine::Connection,
|
440
|
+
# <i>into which the methods from your handler have been mixed.</i>
|
441
|
+
# Your handler module may redefine any of the methods in EventMachine::Connection
|
442
|
+
# in order to implement the specific behavior of the network protocol.
|
443
|
+
#
|
444
|
+
# Callbacks invoked in response to network events <i>always</i> take place
|
445
|
+
# within the execution context of the object derived from EventMachine::Connection
|
446
|
+
# extended by your handler module. There is one object per connection, and
|
447
|
+
# all of the callbacks invoked for a particular connection take the form
|
448
|
+
# of instance methods called against the corresponding EventMachine::Connection
|
449
|
+
# object. Therefore, you are free to define whatever instance variables you
|
450
|
+
# wish, in order to contain the per-connection state required by the network protocol you are
|
451
|
+
# implementing.
|
452
|
+
#
|
453
|
+
# start_server is often called inside the block passed to EventMachine::run,
|
454
|
+
# but it can be called from any EventMachine callback. start_server will fail
|
455
|
+
# unless the EventMachine event loop is currently running (which is why
|
456
|
+
# it's often called in the block suppled to EventMachine::run).
|
457
|
+
#
|
458
|
+
# You may call start_server any number of times to start up network
|
459
|
+
# listeners on different address/port combinations. The servers will
|
460
|
+
# all run simultaneously. More interestingly, each individual call to start_server
|
461
|
+
# can specify a different handler module and thus implement a different
|
462
|
+
# network protocol from all the others.
|
463
|
+
#
|
464
|
+
# === Usage example
|
465
|
+
# Here is an example of a server that counts lines of input from the remote
|
466
|
+
# peer and sends back the total number of lines received, after each line.
|
467
|
+
# Try the example with more than one client connection opened via telnet,
|
468
|
+
# and you will see that the line count increments independently on each
|
469
|
+
# of the client connections. Also very important to note, is that the
|
470
|
+
# handler for the receive_data function, which our handler redefines, may
|
471
|
+
# not assume that the data it receives observes any kind of message boundaries.
|
472
|
+
# Also, to use this example, be sure to change the server and port parameters
|
473
|
+
# to the start_server call to values appropriate for your environment.
|
474
|
+
#
|
475
|
+
# require 'rubygems'
|
476
|
+
# require 'eventmachine'
|
477
|
+
#
|
478
|
+
# module LineCounter
|
479
|
+
# MaxLinesPerConnection = 10
|
480
|
+
#
|
481
|
+
# def post_init
|
482
|
+
# puts "Received a new connection"
|
483
|
+
# @data_received = ""
|
484
|
+
# @line_count = 0
|
485
|
+
# end
|
486
|
+
#
|
487
|
+
# def receive_data data
|
488
|
+
# @data_received << data
|
489
|
+
# while @data_received.slice!( /^[^\n]*[\n]/m )
|
490
|
+
# @line_count += 1
|
491
|
+
# send_data "received #{@line_count} lines so far\r\n"
|
492
|
+
# @line_count == MaxLinesPerConnection and close_connection_after_writing
|
493
|
+
# end
|
494
|
+
# end
|
495
|
+
# end
|
496
|
+
#
|
497
|
+
# EventMachine::run {
|
498
|
+
# host,port = "192.168.0.100", 8090
|
499
|
+
# EventMachine::start_server host, port, LineCounter
|
500
|
+
# puts "Now accepting connections on address #{host}, port #{port}..."
|
501
|
+
# EventMachine::add_periodic_timer( 10 ) { $stderr.write "*" }
|
502
|
+
# }
|
503
|
+
#
|
504
|
+
#
|
505
|
+
def self.start_server server, port=nil, handler=nil, *args, &block
|
506
|
+
begin
|
507
|
+
port = Integer(port)
|
508
|
+
rescue ArgumentError, TypeError
|
509
|
+
# there was no port, so server must be a unix domain socket
|
510
|
+
# the port argument is actually the handler, and the handler is one of the args
|
511
|
+
args.unshift handler if handler
|
512
|
+
handler = port
|
513
|
+
port = nil
|
514
|
+
end if port
|
515
|
+
|
516
|
+
klass = klass_from_handler(Connection, handler, *args)
|
517
|
+
|
518
|
+
s = if port
|
519
|
+
start_tcp_server server, port
|
520
|
+
else
|
521
|
+
start_unix_server server
|
522
|
+
end
|
523
|
+
@acceptors[s] = [klass,args,block]
|
524
|
+
s
|
525
|
+
end
|
526
|
+
|
527
|
+
|
528
|
+
# Stop a TCP server socket that was started with EventMachine#start_server.
|
529
|
+
#--
|
530
|
+
# Requested by Kirk Haines. TODO, this isn't OOP enough. We ought somehow
|
531
|
+
# to have #start_server return an object that has a close or a stop method on it.
|
532
|
+
#
|
533
|
+
def self.stop_server signature
|
534
|
+
EventMachine::stop_tcp_server signature
|
535
|
+
end
|
536
|
+
|
537
|
+
# Start a Unix-domain server
|
538
|
+
#
|
539
|
+
# Note that this is an alias for EventMachine::start_server, which can be used to start both
|
540
|
+
# TCP and Unix-domain servers
|
541
|
+
def self.start_unix_domain_server filename, *args, &block
|
542
|
+
start_server filename, *args, &block
|
543
|
+
end
|
544
|
+
|
545
|
+
# EventMachine#connect initiates a TCP connection to a remote
|
546
|
+
# server and sets up event-handling for the connection.
|
547
|
+
# You can call EventMachine#connect in the block supplied
|
548
|
+
# to EventMachine#run or in any callback method.
|
549
|
+
#
|
550
|
+
# EventMachine#connect takes the IP address (or hostname) and
|
551
|
+
# port of the remote server you want to connect to.
|
552
|
+
# It also takes an optional handler Module which you must define, that
|
553
|
+
# contains the callbacks that will be invoked by the event loop
|
554
|
+
# on behalf of the connection.
|
555
|
+
#
|
556
|
+
# See the description of EventMachine#start_server for a discussion
|
557
|
+
# of the handler Module. All of the details given in that description
|
558
|
+
# apply for connections created with EventMachine#connect.
|
559
|
+
#
|
560
|
+
# === Usage 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
|
+
#
|
567
|
+
# module DumbHttpClient
|
568
|
+
# def post_init
|
569
|
+
# send_data "GET / HTTP/1.1\r\nHost: _\r\n\r\n"
|
570
|
+
# @data = ""
|
571
|
+
# @parsed = false
|
572
|
+
# end
|
573
|
+
#
|
574
|
+
# def receive_data data
|
575
|
+
# @data << data
|
576
|
+
# if !@parsed and @data =~ /[\n][\r]*[\n]/m
|
577
|
+
# @parsed = true
|
578
|
+
# puts "RECEIVED HTTP HEADER:"
|
579
|
+
# $`.each {|line| puts ">>> #{line}" }
|
580
|
+
#
|
581
|
+
# puts "Now we'll terminate the loop, which will also close the connection"
|
582
|
+
# EventMachine::stop_event_loop
|
583
|
+
# end
|
584
|
+
# end
|
585
|
+
#
|
586
|
+
# def unbind
|
587
|
+
# puts "A connection has terminated"
|
588
|
+
# end
|
589
|
+
# end
|
590
|
+
#
|
591
|
+
# EventMachine::run {
|
592
|
+
# EventMachine::connect "www.bayshorenetworks.com", 80, DumbHttpClient
|
593
|
+
# }
|
594
|
+
# puts "The event loop has ended"
|
595
|
+
#
|
596
|
+
#
|
597
|
+
# There are times when it's more convenient to define a protocol handler
|
598
|
+
# as a Class rather than a Module. Here's how to do this:
|
599
|
+
#
|
600
|
+
# class MyProtocolHandler < EventMachine::Connection
|
601
|
+
# def initialize *args
|
602
|
+
# super
|
603
|
+
# # whatever else you want to do here
|
604
|
+
# end
|
605
|
+
#
|
606
|
+
# #.......your other class code
|
607
|
+
# end
|
608
|
+
#
|
609
|
+
# If you do this, then an instance of your class will be instantiated to handle
|
610
|
+
# every network connection created by your code or accepted by servers that you
|
611
|
+
# create. If you redefine #post_init in your protocol-handler class, your
|
612
|
+
# #post_init method will be called _inside_ the call to #super that you will
|
613
|
+
# make in your #initialize method (if you provide one).
|
614
|
+
#
|
615
|
+
#--
|
616
|
+
# EventMachine::connect initiates a TCP connection to a remote
|
617
|
+
# server and sets up event-handling for the connection.
|
618
|
+
# It internally creates an object that should not be handled
|
619
|
+
# by the caller. HOWEVER, it's often convenient to get the
|
620
|
+
# object to set up interfacing to other objects in the system.
|
621
|
+
# We return the newly-created anonymous-class object to the caller.
|
622
|
+
# It's expected that a considerable amount of code will depend
|
623
|
+
# on this behavior, so don't change it.
|
624
|
+
#
|
625
|
+
# Ok, added support for a user-defined block, 13Apr06.
|
626
|
+
# This leads us to an interesting choice because of the
|
627
|
+
# presence of the post_init call, which happens in the
|
628
|
+
# initialize method of the new object. We call the user's
|
629
|
+
# block and pass the new object to it. This is a great
|
630
|
+
# way to do protocol-specific initiation. It happens
|
631
|
+
# AFTER post_init has been called on the object, which I
|
632
|
+
# certainly hope is the right choice.
|
633
|
+
# Don't change this lightly, because accepted connections
|
634
|
+
# are different from connected ones and we don't want
|
635
|
+
# to have them behave differently with respect to post_init
|
636
|
+
# if at all possible.
|
637
|
+
#
|
638
|
+
def self.connect server, port=nil, handler=nil, *args, &blk
|
639
|
+
bind_connect nil, nil, server, port, handler, *args, &blk
|
640
|
+
end
|
641
|
+
|
642
|
+
# EventMachine::bind_connect is like EventMachine::connect, but allows for a local address/port
|
643
|
+
# to bind the connection to.
|
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
|
+
# === Usage 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
|
+
# EM.run{
|
707
|
+
# $sock = TCPSocket.new('site.com', 80)
|
708
|
+
# $sock.write("GET / HTTP/1.0\r\n\r\n")
|
709
|
+
# conn = EM.watch $sock, SimpleHttpClient
|
710
|
+
# conn.notify_readable = true
|
711
|
+
# }
|
712
|
+
#
|
713
|
+
#--
|
714
|
+
# Thanks to Riham Aldakkak (eSpace Technologies) for the initial patch
|
715
|
+
def EventMachine::watch io, handler=nil, *args, &blk
|
716
|
+
attach_io io, true, handler, *args, &blk
|
717
|
+
end
|
718
|
+
|
719
|
+
# Attaches an IO object or file descriptor to the eventloop as a regular connection.
|
720
|
+
# The file descriptor will be set as non-blocking, and EventMachine will process
|
721
|
+
# receive_data and send_data events on it as it would for any other connection.
|
722
|
+
#
|
723
|
+
# To watch a fd instead, use EventMachine::watch, which will not alter the state of the socket
|
724
|
+
# and fire notify_readable and notify_writable events instead.
|
725
|
+
def EventMachine::attach io, handler=nil, *args, &blk
|
726
|
+
attach_io io, false, handler, *args, &blk
|
727
|
+
end
|
728
|
+
|
729
|
+
def EventMachine::attach_io io, watch_mode, handler=nil, *args # :nodoc:
|
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(:@fd, fd)
|
747
|
+
|
748
|
+
@conns[s] = c
|
749
|
+
block_given? and yield c
|
750
|
+
c
|
751
|
+
end
|
752
|
+
|
753
|
+
|
754
|
+
# Connect to a given host/port and re-use the provided EventMachine::Connection instance
|
755
|
+
#--
|
756
|
+
# Observe, the test for already-connected FAILS if we call a reconnect inside post_init,
|
757
|
+
# because we haven't set up the connection in @conns by that point.
|
758
|
+
# RESIST THE TEMPTATION to "fix" this problem by redefining the behavior of post_init.
|
759
|
+
#
|
760
|
+
# Changed 22Nov06: if called on an already-connected handler, just return the
|
761
|
+
# handler and do nothing more. Originally this condition raised an exception.
|
762
|
+
# We may want to change it yet again and call the block, if any.
|
763
|
+
#
|
764
|
+
def self.reconnect server, port, handler # :nodoc:
|
765
|
+
raise "invalid handler" unless handler.respond_to?(:connection_completed)
|
766
|
+
#raise "still connected" if @conns.has_key?(handler.signature)
|
767
|
+
return handler if @conns.has_key?(handler.signature)
|
768
|
+
|
769
|
+
s = connect_server server, port
|
770
|
+
handler.signature = s
|
771
|
+
@conns[s] = handler
|
772
|
+
block_given? and yield handler
|
773
|
+
handler
|
774
|
+
end
|
775
|
+
|
776
|
+
|
777
|
+
# Make a connection to a Unix-domain socket. This is not implemented on Windows platforms.
|
778
|
+
# The parameter socketname is a String which identifies the Unix-domain socket you want
|
779
|
+
# to connect to. socketname is the name of a file on your local system, and in most cases
|
780
|
+
# is a fully-qualified path name. Make sure that your process has enough local permissions
|
781
|
+
# to open the Unix-domain socket.
|
782
|
+
# See also the documentation for #connect. This method behaves like #connect
|
783
|
+
# in all respects except for the fact that it connects to a local Unix-domain
|
784
|
+
# socket rather than a TCP socket.
|
785
|
+
#
|
786
|
+
# Note that this method is simply an alias for #connect, which can connect to both TCP
|
787
|
+
# and Unix-domain sockets
|
788
|
+
#--
|
789
|
+
# For making connections to Unix-domain sockets.
|
790
|
+
# Eventually this has to get properly documented and unified with the TCP-connect methods.
|
791
|
+
# Note how nearly identical this is to EventMachine#connect
|
792
|
+
def self.connect_unix_domain socketname, *args, &blk
|
793
|
+
connect socketname, *args, &blk
|
794
|
+
end
|
795
|
+
|
796
|
+
|
797
|
+
# EventMachine#open_datagram_socket is for support of UDP-based
|
798
|
+
# protocols. Its usage is similar to that of EventMachine#start_server.
|
799
|
+
# It takes three parameters: an IP address (which must be valid
|
800
|
+
# on the machine which executes the method), a port number,
|
801
|
+
# and an optional Module name which will handle the data.
|
802
|
+
# This method will create a new UDP (datagram) socket and
|
803
|
+
# bind it to the address and port that you specify.
|
804
|
+
# The normal callbacks (see EventMachine#start_server) will
|
805
|
+
# be called as events of interest occur on the newly-created
|
806
|
+
# socket, but there are some differences in how they behave.
|
807
|
+
#
|
808
|
+
# Connection#receive_data will be called when a datagram packet
|
809
|
+
# is received on the socket, but unlike TCP sockets, the message
|
810
|
+
# boundaries of the received data will be respected. In other words,
|
811
|
+
# if the remote peer sent you a datagram of a particular size,
|
812
|
+
# you may rely on Connection#receive_data to give you the
|
813
|
+
# exact data in the packet, with the original data length.
|
814
|
+
# Also observe that Connection#receive_data may be called with a
|
815
|
+
# <i>zero-length</i> data payload, since empty datagrams are permitted
|
816
|
+
# in UDP.
|
817
|
+
#
|
818
|
+
# Connection#send_data is available with UDP packets as with TCP,
|
819
|
+
# but there is an important difference. Because UDP communications
|
820
|
+
# are <i>connectionless,</i> there is no implicit recipient for the packets you
|
821
|
+
# send. Ordinarily you must specify the recipient for each packet you send.
|
822
|
+
# However, EventMachine
|
823
|
+
# provides for the typical pattern of receiving a UDP datagram
|
824
|
+
# from a remote peer, performing some operation, and then sending
|
825
|
+
# one or more packets in response to the same remote peer.
|
826
|
+
# To support this model easily, just use Connection#send_data
|
827
|
+
# in the code that you supply for Connection:receive_data.
|
828
|
+
# EventMachine will
|
829
|
+
# provide an implicit return address for any messages sent to
|
830
|
+
# Connection#send_data within the context of a Connection#receive_data callback,
|
831
|
+
# and your response will automatically go to the correct remote peer.
|
832
|
+
# (TODO: Example-code needed!)
|
833
|
+
#
|
834
|
+
# Observe that the port number that you supply to EventMachine#open_datagram_socket
|
835
|
+
# may be zero. In this case, EventMachine will create a UDP socket
|
836
|
+
# that is bound to an <i>ephemeral</i> (not well-known) port.
|
837
|
+
# This is not appropriate for servers that must publish a well-known
|
838
|
+
# port to which remote peers may send datagrams. But it can be useful
|
839
|
+
# for clients that send datagrams to other servers.
|
840
|
+
# If you do this, you will receive any responses from the remote
|
841
|
+
# servers through the normal Connection#receive_data callback.
|
842
|
+
# Observe that you will probably have issues with firewalls blocking
|
843
|
+
# the ephemeral port numbers, so this technique is most appropriate for LANs.
|
844
|
+
# (TODO: Need an example!)
|
845
|
+
#
|
846
|
+
# If you wish to send datagrams to arbitrary remote peers (not
|
847
|
+
# necessarily ones that have sent data to which you are responding),
|
848
|
+
# then see Connection#send_datagram.
|
849
|
+
#
|
850
|
+
# DO NOT call send_data from a datagram socket
|
851
|
+
# outside of a #receive_data method. Use #send_datagram. If you do use #send_data
|
852
|
+
# outside of a #receive_data method, you'll get a confusing error
|
853
|
+
# because there is no "peer," as #send_data requires. (Inside of #receive_data,
|
854
|
+
# #send_data "fakes" the peer as described above.)
|
855
|
+
#
|
856
|
+
#--
|
857
|
+
# Replaced the implementation on 01Oct06. Thanks to Tobias Gustafsson for pointing
|
858
|
+
# out that this originally did not take a class but only a module.
|
859
|
+
#
|
860
|
+
def self.open_datagram_socket address, port, handler=nil, *args
|
861
|
+
klass = klass_from_handler(Connection, handler, *args)
|
862
|
+
s = open_udp_socket address, port.to_i
|
863
|
+
c = klass.new s, *args
|
864
|
+
@conns[s] = c
|
865
|
+
block_given? and yield c
|
866
|
+
c
|
867
|
+
end
|
868
|
+
|
869
|
+
|
870
|
+
# For advanced users. This function sets the default timer granularity, which by default is
|
871
|
+
# slightly smaller than 100 milliseconds. Call this function to set a higher or lower granularity.
|
872
|
+
# The function affects the behavior of #add_timer and #add_periodic_timer. Most applications
|
873
|
+
# will not need to call this function.
|
874
|
+
#
|
875
|
+
# The argument is a number of milliseconds. Avoid setting the quantum to very low values because
|
876
|
+
# that may reduce performance under some extreme conditions. We recommend that you not set a quantum
|
877
|
+
# lower than 10.
|
878
|
+
#
|
879
|
+
# You may only call this function while an EventMachine loop is running (that is, after a call to
|
880
|
+
# EventMachine#run and before a subsequent call to EventMachine#stop).
|
881
|
+
#
|
882
|
+
def self.set_quantum mills
|
883
|
+
set_timer_quantum mills.to_i
|
884
|
+
end
|
885
|
+
|
886
|
+
# Sets the maximum number of timers and periodic timers that may be outstanding at any
|
887
|
+
# given time. You only need to call #set_max_timers if you need more than the default
|
888
|
+
# number of timers, which on most platforms is 1000.
|
889
|
+
# Call this method before calling EventMachine#run.
|
890
|
+
#
|
891
|
+
def self.set_max_timers ct
|
892
|
+
set_max_timer_count ct
|
893
|
+
end
|
894
|
+
|
895
|
+
# Gets the current maximum number of allowed timers
|
896
|
+
#
|
897
|
+
def self.get_max_timers
|
898
|
+
get_max_timer_count
|
899
|
+
end
|
900
|
+
|
901
|
+
# Returns the total number of connections (file descriptors) currently held by the reactor.
|
902
|
+
# Note that a tick must pass after the 'initiation' of a connection for this number to increment.
|
903
|
+
# It's usually accurate, but don't rely on the exact precision of this number unless you really know EM internals.
|
904
|
+
#
|
905
|
+
# For example, $count will be 0 in this case:
|
906
|
+
#
|
907
|
+
# EM.run {
|
908
|
+
# EM.connect("rubyeventmachine.com", 80)
|
909
|
+
# $count = EM.connection_count
|
910
|
+
# }
|
911
|
+
#
|
912
|
+
# In this example, $count will be 1 since the connection has been established in the next loop of the reactor.
|
913
|
+
#
|
914
|
+
# EM.run {
|
915
|
+
# EM.connect("rubyeventmachine.com", 80)
|
916
|
+
# EM.next_tick {
|
917
|
+
# $count = EM.connection_count
|
918
|
+
# }
|
919
|
+
# }
|
920
|
+
#
|
921
|
+
def self.connection_count
|
922
|
+
self.get_connection_count
|
923
|
+
end
|
924
|
+
|
925
|
+
#--
|
926
|
+
# The is the responder for the loopback-signalled event.
|
927
|
+
# It can be fired either by code running on a separate thread (EM#defer) or on
|
928
|
+
# the main thread (EM#next_tick).
|
929
|
+
# It will often happen that a next_tick handler will reschedule itself. We
|
930
|
+
# consume a copy of the tick queue so that tick events scheduled by tick events
|
931
|
+
# have to wait for the next pass through the reactor core.
|
932
|
+
#
|
933
|
+
def self.run_deferred_callbacks # :nodoc:
|
934
|
+
until (@resultqueue ||= []).empty?
|
935
|
+
result,cback = @resultqueue.pop
|
936
|
+
cback.call result if cback
|
937
|
+
end
|
938
|
+
|
939
|
+
@next_tick_mutex.synchronize do
|
940
|
+
jobs, @next_tick_queue = @next_tick_queue, []
|
941
|
+
jobs
|
942
|
+
end.each { |j| j.call }
|
943
|
+
end
|
944
|
+
|
945
|
+
|
946
|
+
# #defer is for integrating blocking operations into EventMachine's control flow.
|
947
|
+
# Call #defer with one or two blocks, as shown below (the second block is <i>optional</i>):
|
948
|
+
#
|
949
|
+
# operation = proc {
|
950
|
+
# # perform a long-running operation here, such as a database query.
|
951
|
+
# "result" # as usual, the last expression evaluated in the block will be the return value.
|
952
|
+
# }
|
953
|
+
# callback = proc {|result|
|
954
|
+
# # do something with result here, such as send it back to a network client.
|
955
|
+
# }
|
956
|
+
#
|
957
|
+
# EventMachine.defer( operation, callback )
|
958
|
+
#
|
959
|
+
# The action of #defer is to take the block specified in the first parameter (the "operation")
|
960
|
+
# and schedule it for asynchronous execution on an internal thread pool maintained by EventMachine.
|
961
|
+
# When the operation completes, it will pass the result computed by the block (if any)
|
962
|
+
# back to the EventMachine reactor. Then, EventMachine calls the block specified in the
|
963
|
+
# second parameter to #defer (the "callback"), as part of its normal, synchronous
|
964
|
+
# event handling loop. The result computed by the operation block is passed as a parameter
|
965
|
+
# to the callback. You may omit the callback parameter if you don't need to execute any code
|
966
|
+
# after the operation completes.
|
967
|
+
#
|
968
|
+
# == Caveats
|
969
|
+
# Note carefully that the code in your deferred operation will be executed on a separate
|
970
|
+
# thread from the main EventMachine processing and all other Ruby threads that may exist in
|
971
|
+
# your program. Also, multiple deferred operations may be running at once! Therefore, you
|
972
|
+
# are responsible for ensuring that your operation code is threadsafe. [Need more explanation
|
973
|
+
# and examples.]
|
974
|
+
# Don't write a deferred operation that will block forever. If so, the current implementation will
|
975
|
+
# not detect the problem, and the thread will never be returned to the pool. EventMachine limits
|
976
|
+
# the number of threads in its pool, so if you do this enough times, your subsequent deferred
|
977
|
+
# operations won't get a chance to run. [We might put in a timer to detect this problem.]
|
978
|
+
#
|
979
|
+
#--
|
980
|
+
# OBSERVE that #next_tick hacks into this mechanism, so don't make any changes here
|
981
|
+
# without syncing there.
|
982
|
+
#
|
983
|
+
# Running with $VERBOSE set to true gives a warning unless all ivars are defined when
|
984
|
+
# they appear in rvalues. But we DON'T ever want to initialize @threadqueue unless we
|
985
|
+
# need it, because the Ruby threads are so heavyweight. We end up with this bizarre
|
986
|
+
# way of initializing @threadqueue because EventMachine is a Module, not a Class, and
|
987
|
+
# has no constructor.
|
988
|
+
#
|
989
|
+
def self.defer op = nil, callback = nil, &blk
|
990
|
+
unless @threadpool
|
991
|
+
require 'thread'
|
992
|
+
@threadpool = []
|
993
|
+
@threadqueue = ::Queue.new
|
994
|
+
@resultqueue = ::Queue.new
|
995
|
+
spawn_threadpool
|
996
|
+
end
|
997
|
+
|
998
|
+
@threadqueue << [op||blk,callback]
|
999
|
+
end
|
1000
|
+
|
1001
|
+
def self.spawn_threadpool # :nodoc:
|
1002
|
+
until @threadpool.size == @threadpool_size.to_i
|
1003
|
+
thread = Thread.new do
|
1004
|
+
Thread.current.abort_on_exception = true
|
1005
|
+
while true
|
1006
|
+
op, cback = *@threadqueue.pop
|
1007
|
+
result = op.call
|
1008
|
+
@resultqueue << [result, cback]
|
1009
|
+
EventMachine.signal_loopbreak
|
1010
|
+
end
|
1011
|
+
end
|
1012
|
+
@threadpool << thread
|
1013
|
+
end
|
1014
|
+
end
|
1015
|
+
|
1016
|
+
class << self
|
1017
|
+
attr_reader :threadpool # :nodoc:
|
1018
|
+
|
1019
|
+
# Size of the EventMachine.defer threadpool (defaults to 20)
|
1020
|
+
attr_accessor :threadpool_size
|
1021
|
+
EventMachine.threadpool_size = 20
|
1022
|
+
end
|
1023
|
+
|
1024
|
+
# Schedules a proc for execution immediately after the next "turn" through the reactor
|
1025
|
+
# core. An advanced technique, this can be useful for improving memory management and/or
|
1026
|
+
# application responsiveness, especially when scheduling large amounts of data for
|
1027
|
+
# writing to a network connection. TODO, we need a FAQ entry on this subject.
|
1028
|
+
#
|
1029
|
+
# #next_tick takes either a single argument (which must be a Proc) or a block.
|
1030
|
+
#--
|
1031
|
+
# This works by adding to the @resultqueue that's used for #defer.
|
1032
|
+
# The general idea is that next_tick is used when we want to give the reactor a chance
|
1033
|
+
# to let other operations run, either to balance the load out more evenly, or to let
|
1034
|
+
# outbound network buffers drain, or both. So we probably do NOT want to block, and
|
1035
|
+
# we probably do NOT want to be spinning any threads. A program that uses next_tick
|
1036
|
+
# but not #defer shouldn't suffer the penalty of having Ruby threads running. They're
|
1037
|
+
# extremely expensive even if they're just sleeping.
|
1038
|
+
#
|
1039
|
+
def self.next_tick pr=nil, &block
|
1040
|
+
raise ArgumentError, "no proc or block given" unless ((pr && pr.respond_to?(:call)) or block)
|
1041
|
+
@next_tick_mutex.synchronize do
|
1042
|
+
@next_tick_queue << ( pr || block )
|
1043
|
+
end
|
1044
|
+
signal_loopbreak if reactor_running?
|
1045
|
+
end
|
1046
|
+
|
1047
|
+
# A wrapper over the setuid system call. Particularly useful when opening a network
|
1048
|
+
# server on a privileged port because you can use this call to drop privileges
|
1049
|
+
# after opening the port. Also very useful after a call to #set_descriptor_table_size,
|
1050
|
+
# which generally requires that you start your process with root privileges.
|
1051
|
+
#
|
1052
|
+
# This method has no effective implementation on Windows or in the pure-Ruby
|
1053
|
+
# implementation of EventMachine.
|
1054
|
+
# Call #set_effective_user by passing it a string containing the effective name
|
1055
|
+
# of the user whose privilege-level your process should attain.
|
1056
|
+
# This method is intended for use in enforcing security requirements, consequently
|
1057
|
+
# it will throw a fatal error and end your program if it fails.
|
1058
|
+
#
|
1059
|
+
def self.set_effective_user username
|
1060
|
+
EventMachine::setuid_string username
|
1061
|
+
end
|
1062
|
+
|
1063
|
+
|
1064
|
+
# Sets the maximum number of file or socket descriptors that your process may open.
|
1065
|
+
# You can pass this method an integer specifying the new size of the descriptor table.
|
1066
|
+
# Returns the new descriptor-table size, which may be less than the number you
|
1067
|
+
# requested. If you call this method with no arguments, it will simply return
|
1068
|
+
# the current size of the descriptor table without attempting to change it.
|
1069
|
+
#
|
1070
|
+
# The new limit on open descriptors ONLY applies to sockets and other descriptors
|
1071
|
+
# that belong to EventMachine. It has NO EFFECT on the number of descriptors
|
1072
|
+
# you can create in ordinary Ruby code.
|
1073
|
+
#
|
1074
|
+
# Not available on all platforms. Increasing the number of descriptors beyond its
|
1075
|
+
# default limit usually requires superuser privileges. (See #set_effective_user
|
1076
|
+
# for a way to drop superuser privileges while your program is running.)
|
1077
|
+
#
|
1078
|
+
def self.set_descriptor_table_size n_descriptors=nil
|
1079
|
+
EventMachine::set_rlimit_nofile n_descriptors
|
1080
|
+
end
|
1081
|
+
|
1082
|
+
|
1083
|
+
|
1084
|
+
# Run an external process. This does not currently work on Windows.
|
1085
|
+
#
|
1086
|
+
# module RubyCounter
|
1087
|
+
# def post_init
|
1088
|
+
# # count up to 5
|
1089
|
+
# send_data "5\n"
|
1090
|
+
# end
|
1091
|
+
# def receive_data data
|
1092
|
+
# puts "ruby sent me: #{data}"
|
1093
|
+
# end
|
1094
|
+
# def unbind
|
1095
|
+
# puts "ruby died with exit status: #{get_status.exitstatus}"
|
1096
|
+
# end
|
1097
|
+
# end
|
1098
|
+
#
|
1099
|
+
# EM.run{
|
1100
|
+
# EM.popen("ruby -e' $stdout.sync = true; gets.to_i.times{ |i| puts i+1; sleep 1 } '", RubyCounter)
|
1101
|
+
# }
|
1102
|
+
#
|
1103
|
+
# Also see EventMachine::DeferrableChildProcess and EventMachine.system
|
1104
|
+
#--
|
1105
|
+
# At this moment, it's only available on Unix.
|
1106
|
+
# Perhaps misnamed since the underlying function uses socketpair and is full-duplex.
|
1107
|
+
#
|
1108
|
+
def self.popen cmd, handler=nil, *args
|
1109
|
+
klass = klass_from_handler(Connection, handler, *args)
|
1110
|
+
w = Shellwords::shellwords( cmd )
|
1111
|
+
w.unshift( w.first ) if w.first
|
1112
|
+
s = invoke_popen( w )
|
1113
|
+
c = klass.new s, *args
|
1114
|
+
@conns[s] = c
|
1115
|
+
yield(c) if block_given?
|
1116
|
+
c
|
1117
|
+
end
|
1118
|
+
|
1119
|
+
|
1120
|
+
# Tells you whether the EventMachine reactor loop is currently running. Returns true or
|
1121
|
+
# false. Useful when writing libraries that want to run event-driven code, but may
|
1122
|
+
# be running in programs that are already event-driven. In such cases, if EventMachine#reactor_running?
|
1123
|
+
# returns false, your code can invoke EventMachine#run and run your application code inside
|
1124
|
+
# the block passed to that method. If EventMachine#reactor_running? returns true, just
|
1125
|
+
# execute your event-aware code.
|
1126
|
+
#
|
1127
|
+
# This method is necessary because calling EventMachine#run inside of another call to
|
1128
|
+
# EventMachine#run generates a fatal error.
|
1129
|
+
#
|
1130
|
+
def self.reactor_running?
|
1131
|
+
(@reactor_running || false)
|
1132
|
+
end
|
1133
|
+
|
1134
|
+
|
1135
|
+
# (Experimental)
|
1136
|
+
#
|
1137
|
+
#
|
1138
|
+
def self.open_keyboard handler=nil, *args
|
1139
|
+
klass = klass_from_handler(Connection, handler, *args)
|
1140
|
+
|
1141
|
+
s = read_keyboard
|
1142
|
+
c = klass.new s, *args
|
1143
|
+
@conns[s] = c
|
1144
|
+
block_given? and yield c
|
1145
|
+
c
|
1146
|
+
end
|
1147
|
+
|
1148
|
+
# EventMachine's file monitoring API. Currently supported are the following events
|
1149
|
+
# on individual files, using inotify on Linux systems, and kqueue for OSX/BSD:
|
1150
|
+
#
|
1151
|
+
# * File modified (written to)
|
1152
|
+
# * File moved/renamed
|
1153
|
+
# * File deleted
|
1154
|
+
#
|
1155
|
+
# EventMachine::watch_file takes a filename and a handler Module containing your custom callback methods.
|
1156
|
+
# This will setup the low level monitoring on the specified file, and create a new EventMachine::FileWatch
|
1157
|
+
# object with your Module mixed in. FileWatch is a subclass of EM::Connection, so callbacks on this object
|
1158
|
+
# work in the familiar way. The callbacks that will be fired by EventMachine are:
|
1159
|
+
#
|
1160
|
+
# * file_modified
|
1161
|
+
# * file_moved
|
1162
|
+
# * file_deleted
|
1163
|
+
#
|
1164
|
+
# You can access the filename being monitored from within this object using FileWatch#path.
|
1165
|
+
#
|
1166
|
+
# When a file is deleted, FileWatch#stop_watching will be called after your file_deleted callback,
|
1167
|
+
# to clean up the underlying monitoring and remove EventMachine's reference to the now-useless FileWatch.
|
1168
|
+
# This will in turn call unbind, if you wish to use it.
|
1169
|
+
#
|
1170
|
+
# The corresponding system-level Errno will be raised when attempting to monitor non-existent files,
|
1171
|
+
# files with wrong permissions, or if an error occurs dealing with inotify/kqueue.
|
1172
|
+
#
|
1173
|
+
# === Usage example:
|
1174
|
+
#
|
1175
|
+
# Make sure we have a file to monitor:
|
1176
|
+
# $ echo "bar" > /tmp/foo
|
1177
|
+
#
|
1178
|
+
# module Handler
|
1179
|
+
# def file_modified
|
1180
|
+
# puts "#{path} modified"
|
1181
|
+
# end
|
1182
|
+
#
|
1183
|
+
# def file_moved
|
1184
|
+
# puts "#{path} moved"
|
1185
|
+
# end
|
1186
|
+
#
|
1187
|
+
# def file_deleted
|
1188
|
+
# puts "#{path} deleted"
|
1189
|
+
# end
|
1190
|
+
#
|
1191
|
+
# def unbind
|
1192
|
+
# puts "#{path} monitoring ceased"
|
1193
|
+
# end
|
1194
|
+
# end
|
1195
|
+
#
|
1196
|
+
# EM.kqueue = true if EM.kqueue? # file watching requires kqueue on OSX
|
1197
|
+
#
|
1198
|
+
# EM.run {
|
1199
|
+
# EM.watch_file("/tmp/foo", Handler)
|
1200
|
+
# }
|
1201
|
+
#
|
1202
|
+
# $ echo "baz" >> /tmp/foo => "/tmp/foo modified"
|
1203
|
+
# $ mv /tmp/foo /tmp/oof => "/tmp/foo moved"
|
1204
|
+
# $ rm /tmp/oof => "/tmp/foo deleted"
|
1205
|
+
# => "/tmp/foo monitoring ceased"
|
1206
|
+
#
|
1207
|
+
# Note that we have not implemented the ability to pick up on the new filename after a rename.
|
1208
|
+
# Calling #path will always return the filename you originally used.
|
1209
|
+
#
|
1210
|
+
def self.watch_file(filename, handler=nil, *args)
|
1211
|
+
klass = klass_from_handler(FileWatch, handler, *args)
|
1212
|
+
|
1213
|
+
s = EM::watch_filename(filename)
|
1214
|
+
c = klass.new s, *args
|
1215
|
+
# we have to set the path like this because of how Connection.new works
|
1216
|
+
c.instance_variable_set("@path", filename)
|
1217
|
+
@conns[s] = c
|
1218
|
+
block_given? and yield c
|
1219
|
+
c
|
1220
|
+
end
|
1221
|
+
|
1222
|
+
# EventMachine's process monitoring API. Currently supported using kqueue for OSX/BSD.
|
1223
|
+
#
|
1224
|
+
# === Usage example:
|
1225
|
+
#
|
1226
|
+
# module ProcessWatcher
|
1227
|
+
# def process_exited
|
1228
|
+
# put 'the forked child died!'
|
1229
|
+
# end
|
1230
|
+
# end
|
1231
|
+
#
|
1232
|
+
# pid = fork{ sleep }
|
1233
|
+
#
|
1234
|
+
# EM.run{
|
1235
|
+
# EM.watch_process(pid, ProcessWatcher)
|
1236
|
+
# EM.add_timer(1){ Process.kill('TERM', pid) }
|
1237
|
+
# }
|
1238
|
+
#
|
1239
|
+
def self.watch_process(pid, handler=nil, *args)
|
1240
|
+
pid = pid.to_i
|
1241
|
+
|
1242
|
+
klass = klass_from_handler(ProcessWatch, handler, *args)
|
1243
|
+
|
1244
|
+
s = EM::watch_pid(pid)
|
1245
|
+
c = klass.new s, *args
|
1246
|
+
# we have to set the path like this because of how Connection.new works
|
1247
|
+
c.instance_variable_set("@pid", pid)
|
1248
|
+
@conns[s] = c
|
1249
|
+
block_given? and yield c
|
1250
|
+
c
|
1251
|
+
end
|
1252
|
+
|
1253
|
+
# Catch-all for errors raised during event loop callbacks.
|
1254
|
+
#
|
1255
|
+
# EM.error_handler{ |e|
|
1256
|
+
# puts "Error raised during event loop: #{e.message}"
|
1257
|
+
# }
|
1258
|
+
#
|
1259
|
+
def self.error_handler cb = nil, &blk
|
1260
|
+
if cb or blk
|
1261
|
+
@error_handler = cb || blk
|
1262
|
+
elsif instance_variable_defined? :@error_handler
|
1263
|
+
remove_instance_variable :@error_handler
|
1264
|
+
end
|
1265
|
+
end
|
1266
|
+
|
1267
|
+
# enable_proxy allows for direct writing of incoming data back out to another descriptor, at the C++ level in the reactor.
|
1268
|
+
# This is especially useful for proxies where high performance is required. Propogating data from a server response
|
1269
|
+
# all the way up to Ruby, and then back down to the reactor to be sent back to the client, is often unnecessary and
|
1270
|
+
# incurs a significant performance decrease.
|
1271
|
+
#
|
1272
|
+
# The two arguments are Connections, 'from' and 'to'. 'from' is the connection whose inbound data you want
|
1273
|
+
# relayed back out. 'to' is the connection to write it to.
|
1274
|
+
#
|
1275
|
+
# Once you call this method, the 'from' connection will no longer get receive_data callbacks from the reactor,
|
1276
|
+
# except in the case that 'to' connection has already closed when attempting to write to it. You can see
|
1277
|
+
# in the example, that proxy_target_unbound will be called when this occurs. After that, further incoming
|
1278
|
+
# data will be passed into receive_data as normal.
|
1279
|
+
#
|
1280
|
+
# Note also that this feature supports different types of descriptors - TCP, UDP, and pipes. You can relay
|
1281
|
+
# data from one kind to another.
|
1282
|
+
#
|
1283
|
+
# Example:
|
1284
|
+
#
|
1285
|
+
# module ProxyConnection
|
1286
|
+
# def initialize(client, request)
|
1287
|
+
# @client, @request = client, request
|
1288
|
+
# end
|
1289
|
+
#
|
1290
|
+
# def post_init
|
1291
|
+
# EM::enable_proxy(self, @client)
|
1292
|
+
# end
|
1293
|
+
#
|
1294
|
+
# def connection_completed
|
1295
|
+
# send_data @request
|
1296
|
+
# end
|
1297
|
+
#
|
1298
|
+
# def proxy_target_unbound
|
1299
|
+
# close_connection
|
1300
|
+
# end
|
1301
|
+
#
|
1302
|
+
# def unbind
|
1303
|
+
# @client.close_connection_after_writing
|
1304
|
+
# end
|
1305
|
+
# end
|
1306
|
+
#
|
1307
|
+
# module ProxyServer
|
1308
|
+
# def receive_data(data)
|
1309
|
+
# (@buf ||= "") << data
|
1310
|
+
# if @buf =~ /\r\n\r\n/ # all http headers received
|
1311
|
+
# EM.connect("10.0.0.15", 80, ProxyConnection, self, data)
|
1312
|
+
# end
|
1313
|
+
# end
|
1314
|
+
# end
|
1315
|
+
#
|
1316
|
+
# EM.run {
|
1317
|
+
# EM.start_server("127.0.0.1", 8080, ProxyServer)
|
1318
|
+
# }
|
1319
|
+
def self.enable_proxy(from, to, bufsize=0, length=0)
|
1320
|
+
EM::start_proxy(from.signature, to.signature, bufsize, length)
|
1321
|
+
end
|
1322
|
+
|
1323
|
+
# disable_proxy takes just one argument, a Connection that has proxying enabled via enable_proxy.
|
1324
|
+
# Calling this method will remove that functionality and your connection will begin receiving
|
1325
|
+
# data via receive_data again.
|
1326
|
+
def self.disable_proxy(from)
|
1327
|
+
EM::stop_proxy(from.signature)
|
1328
|
+
end
|
1329
|
+
|
1330
|
+
# Retrieve the heartbeat interval. This is how often EventMachine will check for dead connections
|
1331
|
+
# that have had an InactivityTimeout set via Connection#set_comm_inactivity_timeout.
|
1332
|
+
# Default is 2 seconds.
|
1333
|
+
def self.heartbeat_interval
|
1334
|
+
EM::get_heartbeat_interval
|
1335
|
+
end
|
1336
|
+
|
1337
|
+
# Set the heartbeat interval. This is how often EventMachine will check for dead connections
|
1338
|
+
# that have had an InactivityTimeout set via Connection#set_comm_inactivity_timeout.
|
1339
|
+
# Takes a Numeric number of seconds. Default is 2.
|
1340
|
+
def self.heartbeat_interval= (time)
|
1341
|
+
EM::set_heartbeat_interval time.to_f
|
1342
|
+
end
|
1343
|
+
|
1344
|
+
private
|
1345
|
+
|
1346
|
+
def self.event_callback conn_binding, opcode, data # :nodoc:
|
1347
|
+
#
|
1348
|
+
# Changed 27Dec07: Eliminated the hookable error handling.
|
1349
|
+
# No one was using it, and it degraded performance significantly.
|
1350
|
+
# It's in original_event_callback, which is dead code.
|
1351
|
+
#
|
1352
|
+
# Changed 25Jul08: Added a partial solution to the problem of exceptions
|
1353
|
+
# raised in user-written event-handlers. If such exceptions are not caught,
|
1354
|
+
# we must cause the reactor to stop, and then re-raise the exception.
|
1355
|
+
# Otherwise, the reactor doesn't stop and it's left on the call stack.
|
1356
|
+
# This is partial because we only added it to #unbind, where it's critical
|
1357
|
+
# (to keep unbind handlers from being re-entered when a stopping reactor
|
1358
|
+
# runs down open connections). It should go on the other calls to user
|
1359
|
+
# code, but the performance impact may be too large.
|
1360
|
+
#
|
1361
|
+
if opcode == ConnectionUnbound
|
1362
|
+
if c = @conns.delete( conn_binding )
|
1363
|
+
begin
|
1364
|
+
c.unbind
|
1365
|
+
rescue
|
1366
|
+
@wrapped_exception = $!
|
1367
|
+
stop
|
1368
|
+
end
|
1369
|
+
elsif c = @acceptors.delete( conn_binding )
|
1370
|
+
# no-op
|
1371
|
+
else
|
1372
|
+
if $! # Bubble user generated errors.
|
1373
|
+
@wrapped_exception = $!
|
1374
|
+
EM.stop
|
1375
|
+
else
|
1376
|
+
raise ConnectionNotBound, "recieved ConnectionUnbound for an unknown signature: #{conn_binding}"
|
1377
|
+
end
|
1378
|
+
end
|
1379
|
+
elsif opcode == ConnectionAccepted
|
1380
|
+
accep,args,blk = @acceptors[conn_binding]
|
1381
|
+
raise NoHandlerForAcceptedConnection unless accep
|
1382
|
+
c = accep.new data, *args
|
1383
|
+
@conns[data] = c
|
1384
|
+
blk and blk.call(c)
|
1385
|
+
c # (needed?)
|
1386
|
+
##
|
1387
|
+
# The remaining code is a fallback for the pure ruby and java reactors.
|
1388
|
+
# In the C++ reactor, these events are handled in the C event_callback() in rubymain.cpp
|
1389
|
+
elsif opcode == ConnectionCompleted
|
1390
|
+
c = @conns[conn_binding] or raise ConnectionNotBound, "received ConnectionCompleted for unknown signature: #{conn_binding}"
|
1391
|
+
c.connection_completed
|
1392
|
+
elsif opcode == TimerFired
|
1393
|
+
t = @timers.delete( data )
|
1394
|
+
return if t == false # timer cancelled
|
1395
|
+
t or raise UnknownTimerFired, "timer data: #{data}"
|
1396
|
+
t.call
|
1397
|
+
elsif opcode == ConnectionData
|
1398
|
+
c = @conns[conn_binding] or raise ConnectionNotBound, "received data #{data} for unknown signature: #{conn_binding}"
|
1399
|
+
c.receive_data data
|
1400
|
+
elsif opcode == LoopbreakSignalled
|
1401
|
+
run_deferred_callbacks
|
1402
|
+
elsif opcode == ConnectionNotifyReadable
|
1403
|
+
c = @conns[conn_binding] or raise ConnectionNotBound
|
1404
|
+
c.notify_readable
|
1405
|
+
elsif opcode == ConnectionNotifyWritable
|
1406
|
+
c = @conns[conn_binding] or raise ConnectionNotBound
|
1407
|
+
c.notify_writable
|
1408
|
+
end
|
1409
|
+
end
|
1410
|
+
|
1411
|
+
#--
|
1412
|
+
# The original event_callback below handled runtime errors in ruby and degraded performance significantly.
|
1413
|
+
# An optional C-based error handler is now available via EM::error_handler
|
1414
|
+
#
|
1415
|
+
# private
|
1416
|
+
# def EventMachine::original_event_callback conn_binding, opcode, data
|
1417
|
+
# #
|
1418
|
+
# # Added 03Oct07: Any code path that invokes user-written code must
|
1419
|
+
# # wrap itself in a begin/rescue for RuntimeErrors, that calls the
|
1420
|
+
# # user-overridable class method #handle_runtime_error.
|
1421
|
+
# #
|
1422
|
+
# if opcode == ConnectionData
|
1423
|
+
# c = @conns[conn_binding] or raise ConnectionNotBound
|
1424
|
+
# begin
|
1425
|
+
# c.receive_data data
|
1426
|
+
# rescue
|
1427
|
+
# EventMachine.handle_runtime_error
|
1428
|
+
# end
|
1429
|
+
# elsif opcode == ConnectionUnbound
|
1430
|
+
# if c = @conns.delete( conn_binding )
|
1431
|
+
# begin
|
1432
|
+
# c.unbind
|
1433
|
+
# rescue
|
1434
|
+
# EventMachine.handle_runtime_error
|
1435
|
+
# end
|
1436
|
+
# elsif c = @acceptors.delete( conn_binding )
|
1437
|
+
# # no-op
|
1438
|
+
# else
|
1439
|
+
# raise ConnectionNotBound
|
1440
|
+
# end
|
1441
|
+
# elsif opcode == ConnectionAccepted
|
1442
|
+
# accep,args,blk = @acceptors[conn_binding]
|
1443
|
+
# raise NoHandlerForAcceptedConnection unless accep
|
1444
|
+
# c = accep.new data, *args
|
1445
|
+
# @conns[data] = c
|
1446
|
+
# begin
|
1447
|
+
# blk and blk.call(c)
|
1448
|
+
# rescue
|
1449
|
+
# EventMachine.handle_runtime_error
|
1450
|
+
# end
|
1451
|
+
# c # (needed?)
|
1452
|
+
# elsif opcode == TimerFired
|
1453
|
+
# t = @timers.delete( data ) or raise UnknownTimerFired
|
1454
|
+
# begin
|
1455
|
+
# t.call
|
1456
|
+
# rescue
|
1457
|
+
# EventMachine.handle_runtime_error
|
1458
|
+
# end
|
1459
|
+
# elsif opcode == ConnectionCompleted
|
1460
|
+
# c = @conns[conn_binding] or raise ConnectionNotBound
|
1461
|
+
# begin
|
1462
|
+
# c.connection_completed
|
1463
|
+
# rescue
|
1464
|
+
# EventMachine.handle_runtime_error
|
1465
|
+
# end
|
1466
|
+
# elsif opcode == LoopbreakSignalled
|
1467
|
+
# begin
|
1468
|
+
# run_deferred_callbacks
|
1469
|
+
# rescue
|
1470
|
+
# EventMachine.handle_runtime_error
|
1471
|
+
# end
|
1472
|
+
# end
|
1473
|
+
# end
|
1474
|
+
#
|
1475
|
+
#
|
1476
|
+
# # Default handler for RuntimeErrors that are raised in user code.
|
1477
|
+
# # The default behavior is to re-raise the error, which ends your program.
|
1478
|
+
# # To override the default behavior, re-implement this method in your code.
|
1479
|
+
# # For example:
|
1480
|
+
# #
|
1481
|
+
# # module EventMachine
|
1482
|
+
# # def self.handle_runtime_error
|
1483
|
+
# # $>.puts $!
|
1484
|
+
# # end
|
1485
|
+
# # end
|
1486
|
+
# #
|
1487
|
+
# #--
|
1488
|
+
# # We need to ensure that any code path which invokes user code rescues RuntimeError
|
1489
|
+
# # and calls this method. The obvious place to do that is in #event_callback,
|
1490
|
+
# # but, scurrilously, it turns out that we need to be finer grained that that.
|
1491
|
+
# # Periodic timers, in particular, wrap their invocations of user code inside
|
1492
|
+
# # procs that do other stuff we can't not do, like schedule the next invocation.
|
1493
|
+
# # This is a potential non-robustness, since we need to remember to hook in the
|
1494
|
+
# # error handler whenever and wherever we change how user code is invoked.
|
1495
|
+
# #
|
1496
|
+
# def EventMachine::handle_runtime_error
|
1497
|
+
# @runtime_error_hook ? @runtime_error_hook.call : raise
|
1498
|
+
# end
|
1499
|
+
#
|
1500
|
+
# # Sets a handler for RuntimeErrors that are raised in user code.
|
1501
|
+
# # Pass a block with no parameters. You can also call this method without a block,
|
1502
|
+
# # which restores the default behavior (see #handle_runtime_error).
|
1503
|
+
# #
|
1504
|
+
# def EventMachine::set_runtime_error_hook &blk
|
1505
|
+
# @runtime_error_hook = blk
|
1506
|
+
# end
|
1507
|
+
|
1508
|
+
#--
|
1509
|
+
# This is a provisional implementation of a stream-oriented file access object.
|
1510
|
+
# We also experiment with wrapping up some better exception reporting.
|
1511
|
+
def self._open_file_for_writing filename, handler=nil # :nodoc:
|
1512
|
+
klass = klass_from_handler(Connection, handler)
|
1513
|
+
|
1514
|
+
s = _write_file filename
|
1515
|
+
c = klass.new s
|
1516
|
+
@conns[s] = c
|
1517
|
+
block_given? and yield c
|
1518
|
+
c
|
1519
|
+
end
|
1520
|
+
|
1521
|
+
private
|
1522
|
+
def self.klass_from_handler(klass = Connection, handler = nil, *args)
|
1523
|
+
klass = if handler and handler.is_a?(Class)
|
1524
|
+
raise ArgumentError, "must provide module or subclass of #{klass.name}" unless klass >= handler
|
1525
|
+
handler
|
1526
|
+
elsif handler
|
1527
|
+
begin
|
1528
|
+
handler::EM_CONNECTION_CLASS
|
1529
|
+
rescue NameError
|
1530
|
+
handler::const_set(:EM_CONNECTION_CLASS, Class.new(klass) {include handler})
|
1531
|
+
end
|
1532
|
+
else
|
1533
|
+
klass
|
1534
|
+
end
|
1535
|
+
|
1536
|
+
arity = klass.instance_method(:initialize).arity
|
1537
|
+
expected = arity >= 0 ? arity : -(arity + 1)
|
1538
|
+
if (arity >= 0 and args.size != expected) or (arity < 0 and args.size < expected)
|
1539
|
+
raise ArgumentError, "wrong number of arguments for #{klass}#initialize (#{args.size} for #{expected})"
|
1540
|
+
end
|
1541
|
+
|
1542
|
+
klass
|
1543
|
+
end
|
1544
|
+
end # module EventMachine
|
1545
|
+
|
1546
|
+
# Save everyone some typing.
|
1547
|
+
EM = EventMachine
|
1548
|
+
EM::P = EventMachine::Protocols
|