Debian Codegraph @

ruby/lib/core/container.rb

raw
1 # Licensed to the Apache Software Foundation (ASF) under one
2 # or more contributor license agreements. See the NOTICE file
3 # distributed with this work for additional information
4 # regarding copyright ownership. The ASF licenses this file
5 # to you under the Apache License, Version 2.0 (the
6 # "License"); you may not use this file except in compliance
7 # with the License. You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing,
12 # software distributed under the License is distributed on an
13 # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14 # KIND, either express or implied. See the License for the
15 # specific language governing permissions and limitations
16 # under the License.
17
18
19 require 'thread'
20 require 'set'
21 require_relative 'listener'
22 require_relative 'work_queue'
23
24 module Qpid::Proton
25 public
26
27 # An AMQP container manages a set of {Listener}s and {Connection}s which
28 # contain {#Sender} and {#Receiver} links to transfer messages. Usually, each
29 # AMQP client or server process has a single container for all of its
30 # connections and links.
31 #
32 # One or more threads can call {#run}, events generated by all the listeners and
33 # connections will be dispatched in the {#run} threads.
34 class Container
35 include TimeCompare
36
37 # Error raised if the container is used after {#stop} has been called.
38 class StoppedError < Qpid::Proton::StoppedError
39 def initialize() super("container has been stopped"); end
40 end
41
42 # Create a new Container
43 # @overload initialize(id=nil)
44 # @param id [String,Symbol] A unique ID for this container, use random UUID if nil.
45 #
46 # @overload initialize(handler=nil, id=nil)
47 # @param id [String,Symbol] A unique ID for this container, use random UUID if nil.
48 # @param handler [MessagingHandler] Optional default handler for connections
49 # that do not have their own handler (see {#connect} and {#listen})
50 #
51 # *Note*: For multi-threaded code, it is recommended to use a separate
52 # handler instance for each connection, as a shared handler may be called
53 # concurrently.
54 #
55 def initialize(*args)
56 @handler, @id = nil
57 case args.size
58 when 2 then @handler, @id = args
59 when 1 then
60 @id = String.try_convert(args[0]) || (args[0].to_s if args[0].is_a? Symbol)
61 @handler = args[0] unless @id
62 when 0 then
63 else raise ArgumentError, "wrong number of arguments (given #{args.size}, expected 0..2"
64 end
65 # Use an empty messaging adapter to give default behaviour if there's no global handler.
66 @adapter = Handler::Adapter.adapt(@handler) || Handler::MessagingAdapter.new(nil)
67 @id = (@id || SecureRandom.uuid).freeze
68
69 # Threading and implementation notes: see comment on #run_one
70 @work = Queue.new
71 @work << :start
72 @work << :select
73 @wake = SelectWaker.new # Wakes #run thread in IO.select
74 @auto_stop = true # Stop when @active drops to 0
75 @work_queue = WorkQueue.new(self) # work scheduled by other threads for :select context
76
77 # Following instance variables protected by lock
78 @lock = Mutex.new
79 @active = 0 # All active tasks, in @selectable, @work or being processed
80 @selectable = Set.new # Tasks ready to block in IO.select
81 @running = 0 # Count of #run threads
82 @stopped = false # #stop called
83 @stop_err = nil # Optional error to pass to tasks, from #stop
84 @panic = nil # Exception caught in a run thread, to be raised by all run threads
85 end
86
87 # @return [MessagingHandler] The container-wide handler
88 attr_reader :handler
89
90 # @return [String] unique identifier for this container
91 attr_reader :id
92
93 def to_s() "#<#{self.class} id=#{id.inspect}>"; end
94 def inspect() to_s; end
95
96 # Auto-stop flag.
97 #
98 # True (the default) means that the container will stop automatically, as if {#stop}
99 # had been called, when the last listener or connection closes.
100 #
101 # False means {#run} will not return unless {#stop} is called.
102 #
103 # @return [Bool] auto-stop state
104 attr_accessor :auto_stop
105
106 # True if the container has been stopped and can no longer be used.
107 # @return [Bool] stopped state
108 attr_accessor :stopped
109
110 # Number of threads in {#run}
111 # @return [Bool] {#run} thread count
112 def running() @lock.synchronize { @running }; end
113
114 # Open an AMQP connection.
115 #
116 # @param url [String, URI] Open a {TCPSocket} to url.host, url.port.
117 # url.scheme must be "amqp" or "amqps", url.scheme.nil? is treated as "amqp"
118 # url.user, url.password are used as defaults if opts[:user], opts[:password] are nil
119 # @option (see Connection#open)
120 # @return [Connection] The new AMQP connection
121 def connect(url, opts=nil)
122 not_stopped
123 url = Qpid::Proton::uri url
124 opts ||= {}
125 if url.user || url.password
126 opts[:user] ||= url.user
127 opts[:password] ||= url.password
128 end
129 opts[:ssl_domain] ||= SSLDomain.new(SSLDomain::MODE_CLIENT) if url.scheme == "amqps"
130 connect_io(TCPSocket.new(url.host, url.port), opts)
131 end
132
133 # Open an AMQP protocol connection on an existing {IO} object
134 # @param io [IO] An existing {IO} object, e.g. a {TCPSocket}
135 # @option (see Connection#open)
136 def connect_io(io, opts=nil)
137 not_stopped
138 cd = connection_driver(io, opts)
139 cd.connection.open()
140 add(cd)
141 cd.connection
142 end
143
144 # Listen for incoming AMQP connections
145 #
146 # @param url [String,URI] Listen on host:port of the AMQP URL
147 # @param handler [Listener::Handler] A {Listener::Handler} object that will be called
148 # with events for this listener and can generate a new set of options for each one.
149 # @return [Listener] The AMQP listener.
150 #
151 def listen(url, handler=Listener::Handler.new)
152 not_stopped
153 url = Qpid::Proton::uri url
154 # TODO aconway 2017-11-01: amqps, SSL
155 listen_io(TCPServer.new(url.host, url.port), handler)
156 end
157
158 # Listen for incoming AMQP connections on an existing server socket.
159 # @param io A server socket, for example a {TCPServer}
160 # @param handler [Listener::Handler] Handler for events from this listener
161 #
162 def listen_io(io, handler=Listener::Handler.new)
163 not_stopped
164 l = ListenTask.new(io, handler, self)
165 add(l)
166 l.listener
167 end
168
169 # Run the container: wait for IO activity, dispatch events to handlers.
170 #
171 # *Multi-threaading* : More than one thread can call {#run} concurrently,
172 # the container will use all {#run} threads as a thread pool. Calls to
173 # {MessagingHandler} or {Listener::Handler} methods are serialized for each
174 # connection or listener. See {WorkQueue} for coordinating with other
175 # threads.
176 #
177 # *Exceptions*: If any handler method raises an exception it will stop the
178 # container, and the exception will be raised by all calls to {#run}. For
179 # single threaded code this is often desirable. Multi-threaded server
180 # applications should normally rescue exceptions in the handler and deal
181 # with them in another way: logging, closing the connection with an error
182 # condition, signalling another thread etc.
183 #
184 # @return [void] Returns when the container stops, see {#stop} and {#auto_stop}
185 #
186 # @raise [StoppedError] If the container has already been stopped when {#run} was called.
187 #
188 # @raise [Exception] If any {MessagingHandler} or {Listener::Handler} managed by
189 # the container raises an exception, that exception will be raised by {#run}
190 #
191 def run
192 @lock.synchronize do
193 @running += 1 # Note: ensure clause below will decrement @running
194 raise StoppedError if @stopped
195 end
196 while task = @work.pop
197 run_one(task, Time.now)
198 end
199 @lock.synchronize { raise @panic if @panic }
200 ensure
201 @lock.synchronize do
202 if (@running -= 1) > 0
203 work_wake nil # Signal the next thread
204 else
205 # This is the last thread, no need to do maybe_panic around this final handler call.
206 @adapter.on_container_stop(self) if @adapter.respond_to? :on_container_stop
207 end
208 end
209 end
210
211 # Stop the container.
212 #
213 # Close all listeners and abort all connections without doing AMQP protocol close.
214 #
215 # {#stop} returns immediately, calls to {#run} will return when all activity
216 # is finished.
217 #
218 # The container can no longer be used, using a stopped container raises
219 # {StoppedError}. Create a new container if you want to resume activity.
220 #
221 # @param error [Condition] Optional error condition passed to
222 # {MessagingHandler#on_transport_error} for each connection and
223 # {Listener::Handler::on_error} for each listener.
224 #
225 # @param panic [Exception] Optional exception to raise from all calls to run()
226 #
227 def stop(error=nil, panic=nil)
228 @lock.synchronize do
229 return if @stopped
230 @stop_err = Condition.convert(error)
231 @panic = panic
232 @stopped = true
233 check_stop_lh
234 # NOTE: @stopped =>
235 # - no new run threads can join
236 # - no more select calls after next wakeup
237 # - once @active == 0, all threads will be stopped with nil
238 end
239 wake
240 end
241
242 # Get the {WorkQueue} that can be used to schedule code to be run by the container.
243 #
244 # Note: to run code that affects a {Connection} or it's associated objects,
245 # use {Connection#work_queue}
246 def work_queue() @work_queue; end
247
248 # (see WorkQueue#schedule)
249 def schedule(at, &block) @work_queue.schedule(at, &block) end
250
251 private
252
253 def wake() @wake.wake; end
254
255 class ConnectionTask < Qpid::Proton::HandlerDriver
256 include TimeCompare
257
258 def initialize container, io, opts, server=false
259 super io, opts[:handler]
260 transport.set_server if server
261 transport.apply opts
262 connection.apply opts
263 @work_queue = WorkQueue.new(container)
264 connection.instance_variable_set(:@work_queue, @work_queue)
265 end
266 def next_tick() earliest(super, @work_queue.next_tick); end
267 def process(now) @work_queue.process(now); super(); end
268
269 def dispatch # Intercept dispatch to close work_queue
270 super
271 @work_queue.close if read_closed? && write_closed?
272 end
273 end
274
275 class ListenTask < Listener
276
277 def initialize(io, handler, container)
278 @io, @handler = io, handler
279 @listener = Listener.new(io, container)
280 env = ENV['PN_TRACE_EVT']
281 if env && ["true", "1", "yes", "on"].include?(env.downcase)
282 @log_prefix = "[0x#{object_id.to_s(16)}](PN_LISTENER_"
283 else
284 @log_prefix = nil
285 end
286 dispatch(:on_open);
287 end
288
289 attr_reader :listener
290 def closing?() @listener.instance_variable_get(:@closing); end
291 def condition() @listener.instance_variable_get(:@condition); end
292 def closed?() @io.closed?; end
293
294 def process
295 return if closed?
296 unless closing?
297 begin
298 return @io.accept, dispatch(:on_accept)
299 rescue IO::WaitReadable, Errno::EINTR
300 rescue StandardError => e
301 @listener.close(e)
302 end
303 end
304 ensure
305 if closing?
306 @io.close rescue nil
307 @listener.instance_variable_set(:@closed, true)
308 dispatch(:on_error, condition) if condition
309 dispatch(:on_close)
310 end
311 end
312
313 def can_read?() !finished?; end
314 def can_write?() false; end
315 def finished?() closed?; end
316
317 def dispatch(method, *args)
318 # TODO aconway 2017-11-27: better logging
319 STDERR.puts "#{@log_prefix}#{([method[3..-1].upcase]+args).join ', '})" if @log_prefix
320 @handler.__send__(method, self, *args) if @handler && @handler.respond_to?(method)
321 end
322
323 def next_tick() nil; end
324
325 # Close listener and force immediate close of socket
326 def close(e=nil)
327 @listener.close(e)
328 @io.close rescue nil
329 end
330 end
331
332 # Selectable object that can be used to wake IO.select from another thread
333 class SelectWaker
334 def initialize
335 @rd, @wr = IO.pipe
336 @lock = Mutex.new
337 @set = false
338 end
339
340 def to_io() @rd; end
341
342 def wake
343 @lock.synchronize do
344 return if @set # Don't write if already has data
345 @set = true
346 @wr.write_nonblock('x') rescue nil
347 end
348 end
349
350 def reset
351 @lock.synchronize do
352 return unless @set
353 @rd.read_nonblock(1) rescue nil
354 @set = false
355 end
356 end
357
358 def close
359 @rd.close
360 @wr.close
361 end
362 end
363
364 # Handle a single item from the @work queue, this is the heart of the #run loop.
365 # Take one task from @work, process it, and rearm for select
366 # Tasks are: ConnectionTask, ListenTask, :start, :select
367 # - ConnectionTask/ListenTask have #can_read, #can_write, #next_tick to set up IO.select
368 # and #process to run handlers and process relevant work_queue
369 # - nil means exit from the #run thread exit (handled by #run)
370 # - :select does IO.select and processes Container#work_queue
371 def run_one(task, now)
372 case task
373
374 when :start
375 maybe_panic { @adapter.on_container_start(self) } if @adapter.respond_to? :on_container_start
376
377 when :select
378 # Compute read/write select sets and minimum next_tick for select timeout
379 r, w = [@wake], []
380 next_tick = @work_queue.next_tick
381 @lock.synchronize do
382 @selectable.each do |s|
383 r << s if s.can_read?
384 w << s if s.can_write?
385 next_tick = earliest(s.next_tick, next_tick)
386 end
387 end
388
389 timeout = ((next_tick > now) ? next_tick - now : 0) if next_tick
390 r, w = IO.select(r, w, nil, timeout)
391 @wake.reset if r && r.delete(@wake)
392 now = Time.now unless timeout == 0 # Update now if we may have blocked
393
394 # selected is a Set to eliminate duplicates between r, w and next_tick due.
395 selected = Set.new
396 selected.merge(r) if r
397 selected.merge(w) if w
398 stopped = @lock.synchronize do
399 if @stopped # close everything
400 @selectable.each { |s| s.close @stop_err; @work << s }
401 @selectable.clear
402 @work_queue.close
403 @wake.close
404 else
405 @selectable -= selected # Remove already-selected tasks from @selectable
406 # Also select and remove items with next_tick before now
407 @selectable.delete_if { |s| before_eq(s.next_tick, now) and selected << s }
408 end
409 @stopped
410 end
411 selected.each { |s| @work << s } # Queue up tasks needing #process
412 maybe_panic { @work_queue.process(now) } # Process current work queue items
413 @work_queue.clear if stopped
414 @lock.synchronize { check_stop_lh } if @work_queue.empty?
415
416 @work << :select unless stopped # Enable next select
417
418 when ConnectionTask then
419 maybe_panic { task.process now }
420 rearm task
421
422 when ListenTask then
423 io, opts = maybe_panic { task.process }
424 add(connection_driver(io, opts, true)) if io
425 rearm task
426 end
427 end
428
429 # Rescue any exception raised by the block and stop the container.
430 def maybe_panic
431 begin
432 yield
433 rescue Exception => e
434 stop(nil, e)
435 nil
436 end
437 end
438
439 # Normally if we add work we need to set a wakeup to ensure a single #run
440 # thread doesn't get stuck in select while there is other work on the queue.
441 def work_wake(task)
442 @work << task
443 @wake.wake
444 end
445
446 def connection_driver(io, opts=nil, server=false)
447 opts ||= {}
448 opts[:container] = self
449 opts[:handler] ||= @adapter
450 ConnectionTask.new(self, io, opts, server)
451 end
452
453 # All new tasks are added here
454 def add task
455 @lock.synchronize do
456 @active += 1
457 task.close @stop_err if @stopped
458 end
459 work_wake task
460 end
461
462 def rearm task
463 @lock.synchronize do
464 if task.finished?
465 @active -= 1
466 check_stop_lh
467 elsif @stopped
468 task.close @stop_err
469 work_wake task
470 else
471 @selectable << task
472 end
473 end
474 @wake.wake
475 end
476
477 def check_stop_lh
478 if @active.zero? && (@auto_stop || @stopped) && @work_queue.empty?
479 @stopped = true
480 work_wake nil # Signal threads to stop
481 true
482 end
483 end
484
485 def not_stopped() raise StoppedError if @lock.synchronize { @stopped }; end
486
487 end
488 end