Class: Mongo::Server

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Event::Publisher, Monitoring::Publishable
Defined in:
lib/mongo/server.rb,
lib/mongo/server/context.rb,
lib/mongo/server/monitor.rb,
lib/mongo/server/connection.rb,
lib/mongo/server/connectable.rb,
lib/mongo/server/description.rb,
lib/mongo/server/app_metadata.rb,
lib/mongo/server/connection_base.rb,
lib/mongo/server/connection_pool.rb,
lib/mongo/server/monitor/connection.rb,
lib/mongo/server/pending_connection.rb,
lib/mongo/server/description/features.rb,
lib/mongo/server/monitor/app_metadata.rb,
lib/mongo/server/connection_pool/queue.rb,
lib/mongo/server/round_trip_time_averager.rb

Overview

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

Since:

  • 2.0.0

Defined Under Namespace

Modules: Connectable Classes: AppMetadata, Connection, ConnectionBase, ConnectionPool, Context, Description, Monitor, PendingConnection, RoundTripTimeAverager

Constant Summary collapse

CONNECT_TIMEOUT =

The default time in seconds to timeout a connection attempt.

Since:

  • 2.4.3

10.freeze

Constants included from Loggable

Loggable::PREFIX

Instance Attribute Summary collapse

Attributes included from Event::Publisher

#event_listeners

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Event::Publisher

#publish

Methods included from Monitoring::Publishable

#publish_event, #publish_sdam_event

Methods included from Loggable

#log_debug, #log_error, #log_fatal, #log_info, #log_warn, #logger

Constructor Details

#initialize(address, cluster, monitoring, event_listeners, options = {}) ⇒ Server

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Note:

Server must never be directly instantiated outside of a Cluster.

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

Examples:

Initialize the server.

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

Parameters:

  • address (Address)

    The host:port address to connect to.

  • cluster (Cluster)

    The cluster the server belongs to.

  • monitoring (Monitoring)

    The monitoring.

  • event_listeners (Event::Listeners)

    The event listeners.

  • options (Hash) (defaults to: {})

    The server options.

Options Hash (options):

  • :monitor (Boolean)

    For internal driver use only: whether to monitor the server after instantiating it.

  • :monitoring_io (true, false)

    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



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# 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
  @monitor = Monitor.new(address, event_listeners, monitoring,
    options.merge(app_metadata: Monitor::AppMetadata.new(cluster.options)))
  unless monitor == false
    start_monitoring
  end
  @connected = true
  @pool_lock = Mutex.new
end

Instance Attribute Details

#addressString (readonly)

Returns The configured address for the server.

Returns:

  • (String)

    The configured address for the server.

Since:

  • 2.0.0



74
75
76
# File 'lib/mongo/server.rb', line 74

def address
  @address
end

#clusterCluster (readonly)

Returns cluster The server cluster.

Returns:

  • (Cluster)

    cluster The server cluster.

Since:

  • 2.0.0



77
78
79
# File 'lib/mongo/server.rb', line 77

def cluster
  @cluster
end

#monitorMonitor (readonly)

Returns monitor The server monitor.

Returns:

  • (Monitor)

    monitor The server monitor.

Since:

  • 2.0.0



80
81
82
# File 'lib/mongo/server.rb', line 80

def monitor
  @monitor
end

#monitoringMonitoring (readonly)

Returns monitoring The monitoring.

Returns:

Since:

  • 2.0.0



86
87
88
# File 'lib/mongo/server.rb', line 86

def monitoring
  @monitoring
end

#optionsHash (readonly)

Returns The options hash.

Returns:

  • (Hash)

    The options hash.

Since:

  • 2.0.0



83
84
85
# File 'lib/mongo/server.rb', line 83

def options
  @options
end

Class Method Details

.finalize(monitor) ⇒ Object

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

Examples:

Finalize the object.

Server.finalize(monitor)

Parameters:

Since:

  • 2.2.0



206
207
208
# File 'lib/mongo/server.rb', line 206

def self.finalize(monitor)
  proc { monitor.stop! }
end

Instance Method Details

#==(other) ⇒ true, false

Is this server equal to another?

Examples:

Is the server equal to the other?

server == other

Parameters:

  • other (Object)

    The object to compare to.

Returns:

  • (true, false)

    If the servers are equal.

Since:

  • 2.0.0



137
138
139
140
# File 'lib/mongo/server.rb', line 137

def ==(other)
  return false unless other.is_a?(Server)
  address == other.address
end

#connectable?true, false

Deprecated.

No longer necessary with Server Selection specification.

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

Examples:

Is the server connectable?

server.connectable?

Returns:

  • (true, false)

    If the server is connectable.

Since:

  • 2.1.0



167
# File 'lib/mongo/server.rb', line 167

def connectable?; end

#connected?true|false

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Whether the server is connected.

Returns:

  • (true|false)

    Whether the server is connected.

Since:

  • 2.7.0



193
194
195
# File 'lib/mongo/server.rb', line 193

def connected?
  @connected
end

#contextMongo::Server::Context

Deprecated.

Will be removed in version 3.0

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

Examples:

Get the server context.

server.context

Returns:

Since:

  • 2.0.0



152
153
154
# File 'lib/mongo/server.rb', line 152

def context
  Context.new(self)
end

#disconnect!(wait = false) ⇒ true

Disconnect the server from the connection.

Examples:

Disconnect the server.

server.disconnect!

Parameters:

  • wait (Boolean) (defaults to: false)

    Whether to wait for background threads to finish running.

Returns:

  • (true)

    Always true with no exception.

Since:

  • 2.0.0



180
181
182
183
184
185
# File 'lib/mongo/server.rb', line 180

def disconnect!(wait=false)
  pool.disconnect!
  monitor.stop!(wait)
  @connected = false
  true
end

#handle_auth_failure!Object

Handle authentication failure.

Examples:

Handle possible authentication failure.

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

Returns:

  • (Object)

    The result of the block execution.

Raises:

Since:

  • 2.3.0



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/mongo/server.rb', line 360

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!
  pool.disconnect!
  raise
rescue Auth::Unauthorized
  # auth error, keep server description and topology as they are
  pool.disconnect!
  raise
end

#handle_handshake_failure!Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Handle handshake failure.

Since:

  • 2.7.0



341
342
343
344
345
346
# File 'lib/mongo/server.rb', line 341

def handle_handshake_failure!
  yield
rescue Mongo::Error::SocketError, Mongo::Error::SocketTimeoutError
  unknown!
  raise
end

#inspectString

Get a pretty printed server inspection.

Examples:

Get the server inspection.

server.inspect

Returns:

  • (String)

    The nice inspection string.

Since:

  • 2.0.0



235
236
237
# File 'lib/mongo/server.rb', line 235

def inspect
  "#<Mongo::Server:0x#{object_id} address=#{address.host}:#{address.port}>"
end

#matches_tag_set?(tag_set) ⇒ true, false

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

Examples:

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

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

Parameters:

  • tag_set (Hash)

    The tag set to compare to the server's tags.

Returns:

  • (true, false)

    If the provided tags are a subset of the server's tags.

Since:

  • 2.0.0



303
304
305
306
307
# File 'lib/mongo/server.rb', line 303

def matches_tag_set?(tag_set)
  tag_set.keys.all? do |k|
    tags[k] && tags[k] == tag_set[k]
  end
end

#poolMongo::Server::ConnectionPool

Get the connection pool for this server.

Examples:

Get the connection pool for the server.

server.pool

Returns:

Since:

  • 2.0.0



283
284
285
286
287
288
289
290
291
# File 'lib/mongo/server.rb', line 283

def pool
  @pool_lock.synchronize do
    @pool ||= begin
      ConnectionPool.new(options) do |generation|
        Connection.new(self, options.merge(generation: generation))
      end
    end
  end
end

#reconnect!true

Restart the server monitor.

Examples:

Restart the server monitor.

server.reconnect!

Returns:

  • (true)

    Always true.

Since:

  • 2.1.0



317
318
319
320
# File 'lib/mongo/server.rb', line 317

def reconnect!
  monitor.restart!
  @connected = true
end

#retry_writes?true, false

Note:

Retryable writes are only available on server versions 3.6+ and with sharded clusters or replica sets.

Will writes sent to this server be retried.

Examples:

Will writes be retried.

server.retry_writes?

Returns:

  • (true, false)

    If writes will be retried.

Since:

  • 2.5.0



387
388
389
# File 'lib/mongo/server.rb', line 387

def retry_writes?
  !!(features.sessions_enabled? && logical_session_timeout && !standalone?)
end

#start_monitoringObject

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

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.

Since:

  • 2.0.0



216
217
218
219
220
221
222
223
224
225
# File 'lib/mongo/server.rb', line 216

def start_monitoring
  publish_sdam_event(
    Monitoring::SERVER_OPENING,
    Monitoring::Event::ServerOpening.new(address, cluster.topology)
  )
  if options[:monitoring_io] != false
    monitor.run!
    ObjectSpace.define_finalizer(self, self.class.finalize(monitor))
  end
end

#summaryObject

Note:

This method is experimental and subject to change.

Since:

  • 2.7.0



243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
# File 'lib/mongo/server.rb', line 243

def summary
  status = case
  when primary?
    'PRIMARY'
  when secondary?
    'SECONDARY'
  when standalone?
    'STANDALONE'
  when arbiter?
    'ARBITER'
  when ghost?
    'GHOST'
  when other?
    'OTHER'
  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
    ''
  end
  if replica_set_name
    status += " replica_set=#{replica_set_name}"
  end
  address_bit = if address
    "#{address.host}:#{address.port}"
  else
    'nil'
  end
  "#<Server address=#{address_bit} #{status}>"
end

#unknown!Object

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

Since:

  • 2.4.0, SDAM events are sent as of version 2.7.0



395
396
397
398
399
400
# File 'lib/mongo/server.rb', line 395

def unknown!
  # Just dispatch the description changed event here, SDAM flow
  # will update description on the server without in-place mutations
  # and invoke SDAM transitions as needed.
  publish(Event::DESCRIPTION_CHANGED, description, Description.new(address))
end

#update_description(description) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Since:

  • 2.0.0



403
404
405
# File 'lib/mongo/server.rb', line 403

def update_description(description)
  monitor.instance_variable_set('@description', description)
end

#with_connection(&block) ⇒ Object

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

Examples:

Send a message with the connection.

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

Returns:

  • (Object)

    The result of the block execution.

Since:

  • 2.3.0



333
334
335
# File 'lib/mongo/server.rb', line 333

def with_connection(&block)
  pool.with_connection(&block)
end