class Mongo::Server

Represents a single server on the server side that can be standalone, part of a replica set, or a mongos.

@since 2.0.0

Constants

CONNECT_TIMEOUT

The default time in seconds to timeout a connection attempt.

@since 2.4.3

Attributes

address[R]

@return [ String ] The configured address for the server.

cluster[R]

@return [ Cluster ] cluster The server cluster.

description[R]

@return [ Server::Description ] description The server

description the monitor refreshes.
monitor[R]

@return [ nil | Monitor ] monitor The server monitor. nil if the servenr

was created with monitoring_io: false option.
monitoring[R]

@return [ Monitoring ] monitoring The monitoring.

options[R]

@return [ Hash ] The options hash.

round_trip_time_averager[R]

@return [ RoundTripTimeAverager ] Round trip time averager object. @api private

scan_semaphore[R]

@return [ Semaphore ] Semaphore to signal to request an immediate scan

of this server by its monitor, if one is running.

@api private

Public Class Methods

finalize(monitor) click to toggle source

When the server is flagged for garbage collection, stop the monitor thread.

@example Finalize the object.

Server.finalize(monitor)

@param [ Server::Monitor ] monitor The server monitor.

@since 2.2.0

# File lib/mongo/server.rb, line 276
def self.finalize(monitor)
  proc { monitor.stop! }
end
new(address, cluster, monitoring, event_listeners, options = {}) click to toggle source

Instantiate a new server object. Will start the background refresh and subscribe to the appropriate events.

@api private

@example Initialize the server.

Mongo::Server.new('127.0.0.1:27017', cluster, monitoring, listeners)

@note Server must never be directly instantiated outside of a Cluster.

@param [ Address ] address The host:port address to connect to. @param [ Cluster ] cluster The cluster the server belongs to. @param [ Monitoring ] monitoring The monitoring. @param [ Event::Listeners ] event_listeners The event listeners. @param [ Hash ] options The server options.

@option options [ Boolean ] :monitor For internal driver use only:

whether to monitor the server after instantiating it.

@option options [ true, false ] :monitoring_io For internal driver

use only. Set to false to prevent SDAM-related I/O from being
done by this server. Note: setting this option to false will make
the server non-functional. It is intended for use in tests which
manually invoke SDAM state transitions.

@since 2.0.0

# File lib/mongo/server.rb, line 56
def initialize(address, cluster, monitoring, event_listeners, options = {})
  @address = address
  @cluster = cluster
  @monitoring = monitoring
  options = options.dup
  _monitor = options.delete(:monitor)
  @options = options.freeze
  @event_listeners = event_listeners
  @connection_id_gen = Class.new do
    include Id
  end
  @scan_semaphore = Semaphore.new
  @round_trip_time_averager = RoundTripTimeAverager.new
  @description = Description.new(address, {})
  @last_scan = nil
  unless options[:monitoring_io] == false
    @monitor = Monitor.new(self, event_listeners, monitoring,
      options.merge(
        app_metadata: Monitor::AppMetadata.new(cluster.options),
    ))
    unless _monitor == false
      start_monitoring
    end
  end
  @connected = true
  @pool_lock = Mutex.new
end

Public Instance Methods

==(other) click to toggle source

Is this server equal to another?

@example Is the server equal to the other?

server == other

@param [ Object ] other The object to compare to.

@return [ true, false ] If the servers are equal.

@since 2.0.0

# File lib/mongo/server.rb, line 190
def ==(other)
  return false unless other.is_a?(Server)
  address == other.address
end
clear_connection_pool() click to toggle source

@api private

# File lib/mongo/server.rb, line 504
def clear_connection_pool
  @pool_lock.synchronize do
    if @pool
      @pool.disconnect!
    end
  end
end
compressor() click to toggle source

The last compressor discovered by the server monitor.

The compressor state should be determined for each individual connection rather than kept per server. A future version of the driver will change how compressors are tracked and used.

# File lib/mongo/server.rb, line 132
def compressor
  if monitor
    monitor.compressor
  else
    nil
  end
end
connectable?() click to toggle source

Determine if a connection to the server is able to be established and messages can be sent to it.

@example Is the server connectable?

server.connectable?

@return [ true, false ] If the server is connectable.

@since 2.1.0

@deprecated No longer necessary with Server Selection specification.

# File lib/mongo/server.rb, line 220
def connectable?; end
connected?() click to toggle source

Whether the server is connected.

@return [ true|false ] Whether the server is connected.

@api private @since 2.7.0

# File lib/mongo/server.rb, line 263
def connected?
  @connected
end
context() click to toggle source

Get a new context for this server in which to send messages.

@example Get the server context.

server.context

@return [ Mongo::Server::Context ] context The server context.

@since 2.0.0

@deprecated Will be removed in version 3.0

# File lib/mongo/server.rb, line 205
def context
  Context.new(self)
end
disconnect!() click to toggle source

Disconnect the driver from this server.

Disconnects all idle connections to this server in its connection pool, if any exist. Stops the populator of the connection pool, if it is running. Does not immediately close connections which are presently checked out (i.e. in use) - such connections will be closed when they are returned to their respective connection pools. Stop the server's background monitor.

@return [ true ] Always true.

@since 2.0.0

# File lib/mongo/server.rb, line 234
def disconnect!
  if monitor
    monitor.stop!
  end
  _pool = @pool_lock.synchronize do
    @pool
  end
  if _pool
    # For backwards compatibility we disconnect/clear the pool rather
    # than close it here. We also stop the populator which allows the
    # the pool to continue providing connections but stops it from
    # connecting in background on clients/servers that are in fact
    # intended to be closed and no longer used.
    begin
      _pool.disconnect!(stop_populator: true)
    rescue Error::PoolClosedError
      # If the pool was already closed, we don't need to do anything here.
    end
  end
  @connected = false
  true
end
handle_auth_failure!() { || ... } click to toggle source

Handle authentication failure.

@example Handle possible authentication failure.

server.handle_auth_failure! do
  Auth.get(user).login(self)
end

@raise [ Auth::Unauthorized ] If the authentication failed.

@return [ Object ] The result of the block execution.

@since 2.3.0

# File lib/mongo/server.rb, line 443
def handle_auth_failure!
  yield
rescue Mongo::Error::SocketTimeoutError
  # possibly cluster is slow, do not give up on it
  raise
rescue Mongo::Error::SocketError
  # non-timeout network error
  unknown!
  raise
rescue Auth::Unauthorized
  # auth error, keep server description and topology as they are
  pool.disconnect!
  raise
end
handle_handshake_failure!() { || ... } click to toggle source

Handle handshake failure.

@since 2.7.0 @api private

# File lib/mongo/server.rb, line 424
def handle_handshake_failure!
  yield
rescue Mongo::Error::SocketError, Mongo::Error::SocketTimeoutError
  unknown!
  raise
end
heartbeat_frequency() click to toggle source

@deprecated

# File lib/mongo/server.rb, line 117
def heartbeat_frequency
  cluster.heartbeat_interval
end
Also aliased as: heartbeat_frequency_seconds
heartbeat_frequency_seconds()

@deprecated

Alias for: heartbeat_frequency
inspect() click to toggle source

Get a pretty printed server inspection.

@example Get the server inspection.

server.inspect

@return [ String ] The nice inspection string.

@since 2.0.0

# File lib/mongo/server.rb, line 305
def inspect
  "#<Mongo::Server:0x#{object_id} address=#{address.host}:#{address.port}>"
end
last_scan() click to toggle source

@return [ Time | nil ] last_scan The time when the last server scan

completed, or nil if the server has not been scanned yet.

@since 2.4.0

# File lib/mongo/server.rb, line 108
def last_scan
  if description && !description.config.empty?
    description.last_update_time
  else
    @last_scan
  end
end
matches_tag_set?(tag_set) click to toggle source

Determine if the provided tags are a subset of the server's tags.

@example Are the provided tags a subset of the server's tags.

server.matches_tag_set?({ 'rack' => 'a', 'dc' => 'nyc' })

@param [ Hash ] tag_set The tag set to compare to the server's tags.

@return [ true, false ] If the provided tags are a subset of the server's tags.

@since 2.0.0

# File lib/mongo/server.rb, line 384
def matches_tag_set?(tag_set)
  tag_set.keys.all? do |k|
    tags[k] && tags[k] == tag_set[k]
  end
end
next_connection_id() click to toggle source

@api private

# File lib/mongo/server.rb, line 513
def next_connection_id
  @connection_id_gen.next_id
end
pool() click to toggle source

Get the connection pool for this server.

@example Get the connection pool for the server.

server.pool

@return [ Mongo::Server::ConnectionPool ] The connection pool.

@since 2.0.0

# File lib/mongo/server.rb, line 368
def pool
  @pool_lock.synchronize do
    @pool ||= ConnectionPool.new(self, options)
  end
end
reconnect!() click to toggle source

Restart the server monitor.

@example Restart the server monitor.

server.reconnect!

@return [ true ] Always true.

@since 2.1.0

# File lib/mongo/server.rb, line 398
def reconnect!
  if options[:monitoring_io] != false
    monitor.restart!
  end
  @connected = true
end
retry_reads?() click to toggle source

Whether the server supports modern read retries.

@api private

# File lib/mongo/server.rb, line 461
def retry_reads?
  !!(features.sessions_enabled? && logical_session_timeout)
end
retry_writes?() click to toggle source

Will writes sent to this server be retried.

@example Will writes be retried.

server.retry_writes?

@return [ true, false ] If writes will be retried.

@note Retryable writes are only available on server versions 3.6+ and with

sharded clusters or replica sets.

@since 2.5.0

# File lib/mongo/server.rb, line 476
def retry_writes?
  !!(features.sessions_enabled? && logical_session_timeout && !standalone?)
end
start_monitoring() click to toggle source

Start monitoring the server.

Used internally by the driver to add a server to a cluster while delaying monitoring until the server is in the cluster.

@api private

# File lib/mongo/server.rb, line 286
def start_monitoring
  publish_sdam_event(
    Monitoring::SERVER_OPENING,
    Monitoring::Event::ServerOpening.new(address, cluster.topology)
  )
  if options[:monitoring_io] != false
    ObjectSpace.define_finalizer(self, self.class.finalize(monitor))
    monitor.run!
  end
end
status() click to toggle source

@return [ String ] String representing server status (e.g. PRIMARY).

@api private

# File lib/mongo/server.rb, line 312
def status
  case
  when primary?
    'PRIMARY'
  when secondary?
    'SECONDARY'
  when standalone?
    'STANDALONE'
  when arbiter?
    'ARBITER'
  when ghost?
    'GHOST'
  when other?
    'OTHER'
  when mongos?
    'MONGOS'
  when unknown?
    'UNKNOWN'
  else
    # Since the summary method is often used for debugging, do not raise
    # an exception in case none of the expected types matched
    nil
  end
end
summary() click to toggle source

@note This method is experimental and subject to change.

@api experimental @since 2.7.0

# File lib/mongo/server.rb, line 341
def summary
  status = self.status || ''
  if replica_set_name
    status += " replica_set=#{replica_set_name}"
  end

  if @pool
    status += " pool=#{@pool.summary}"
  end

  address_bit = if address
    "#{address.host}:#{address.port}"
  else
    'nil'
  end

  "#<Server address=#{address_bit} #{status}>"
end
unknown!(options = {}) click to toggle source

Marks server unknown and publishes the associated SDAM event (server description changed).

@param [ Hash ] options Options.

@option options [ true | false ] :keep_connection_pool Usually when the

new server description is unknown, the connection pool on the
respective server is cleared. Set this option to true to keep the
existing connection pool (required when handling not master errors
on 4.2+ servers).

@since 2.4.0, SDAM events are sent as of version 2.7.0

# File lib/mongo/server.rb, line 492
def unknown!(options = {})
  # SDAM flow will update description on the server without in-place
  # mutations and invoke SDAM transitions as needed.
  cluster.run_sdam_flow(description, Description.new(address), options)
end
update_description(description) click to toggle source

@api private

# File lib/mongo/server.rb, line 499
def update_description(description)
  @description = description
end
update_last_scan() click to toggle source

@api private

# File lib/mongo/server.rb, line 518
def update_last_scan
  @last_scan = Time.now
end
with_connection(&block) click to toggle source

Execute a block of code with a connection, that is checked out of the server's pool and then checked back in.

@example Send a message with the connection.

server.with_connection do |connection|
  connection.dispatch([ command ])
end

@return [ Object ] The result of the block execution.

@since 2.3.0

# File lib/mongo/server.rb, line 416
def with_connection(&block)
  pool.with_connection(&block)
end