Class: SSHKit::Backend::ConnectionPool

Inherits:
Object
  • Object
show all
Defined in:
lib/sshkit/backends/connection_pool.rb

Overview

The ConnectionPool caches connections and allows them to be reused, so long as the reuse happens within the `idle_timeout` period. Timed out connections are closed, forcing a new connection to be used in that case.

Additionally, a background thread is started to check for abandoned connections that have timed out without any attempt at being reused. These are eventually closed as well and removed from the cache.

If `idle_timeout` set to `false`, `0`, or `nil`, no caching is performed, and a new connection is created and then immediately closed each time. The default timeout is 30 (seconds).

There is a single public method: `with`. Example usage:

pool = SSHKit::Backend::ConnectionPool.new
pool.with(Net::SSH.method(:start), "host", "username") do |connection|
  # do stuff with connection
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(idle_timeout = 30) ⇒ ConnectionPool

Returns a new instance of ConnectionPool


44
45
46
47
48
49
50
# File 'lib/sshkit/backends/connection_pool.rb', line 44

def initialize(idle_timeout=30)
  @idle_timeout = idle_timeout
  @caches = {}
  @caches.extend(MonitorMixin)
  @timed_out_connections = Queue.new
  Thread.new { run_eviction_loop }
end

Instance Attribute Details

#idle_timeoutObject

Returns the value of attribute idle_timeout


42
43
44
# File 'lib/sshkit/backends/connection_pool.rb', line 42

def idle_timeout
  @idle_timeout
end

Instance Method Details

#close_connectionsObject

Immediately close all cached connections and empty the pool.


76
77
78
79
80
81
82
# File 'lib/sshkit/backends/connection_pool.rb', line 76

def close_connections
  caches.synchronize do
    caches.values.each(&:clear)
    caches.clear
    process_deferred_close
  end
end

#flush_connectionsObject

Immediately remove all cached connections, without closing them. This only exists for unit test purposes.


71
72
73
# File 'lib/sshkit/backends/connection_pool.rb', line 71

def flush_connections
  caches.synchronize { caches.clear }
end

#with(connection_factory, *args) ⇒ Object

Creates a new connection or reuses a cached connection (if possible) and yields the connection to the given block. Connections are created by invoking the `connection_factory` proc with the given `args`. The arguments are used to construct a key used for caching.


56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/sshkit/backends/connection_pool.rb', line 56

def with(connection_factory, *args)
  cache = find_cache(args)
  conn = cache.pop || begin
    connection_factory.call(*args)
  end
  yield(conn)
ensure
  cache.push(conn) unless conn.nil?
  # Sometimes the args mutate as a result of opening a connection. In this
  # case we need to update the cache key to match the new args.
  update_key_if_args_changed(cache, args)
end