Class: Mongo::Connection

Inherits:
Object show all
Includes:
Logging, Networking
Defined in:
lib/mongo/connection.rb

Overview

Instantiates and manages self.connections to MongoDB.

Direct Known Subclasses

ReplSetConnection

Constant Summary

TCPSocket =
Mongo::TCPSocket
Mutex =
::Mutex
ConditionVariable =
::ConditionVariable
DEFAULT_PORT =
27017
GENERIC_OPTS =
[:ssl, :auths, :pool_size, :pool_timeout, :timeout, :op_timeout, :connect_timeout, :safe, :logger, :connect]
CONNECTION_OPTS =
[:slave_ok]

Constants included from Networking

Networking::BINARY_ENCODING, Networking::RESPONSE_HEADER_SIZE, Networking::STANDARD_HEADER_SIZE

Constants included from Logging

Logging::DEBUG_LEVEL

Instance Attribute Summary (collapse)

Class Method Summary (collapse)

Instance Method Summary (collapse)

Methods included from Networking

#new_binary_string, #receive_message, #send_message, #send_message_with_safe_check

Methods included from Logging

#instrument, #log, #write_logging_startup_message

Constructor Details

- (Connection) initialize(host = nil, port = nil, opts = {})

Create a connection to single MongoDB instance.

You may specify whether connection to slave is permitted. In all cases, the default host is "localhost" and the default port is 27017.

If you're connecting to a replica set, you'll need to use ReplSetConnection.new instead.

Once connected to a replica set, you can find out which nodes are primary, secondary, and arbiters with the corresponding accessors: Connection#primary, Connection#secondaries, and Connection#arbiters. This is useful if your application needs to connect manually to nodes other than the primary.

Examples:

localhost, 27017

Connection.new

localhost, 27017

Connection.new("localhost")

localhost, 3000, max 5 self.connections, with max 5 seconds of wait time.

Connection.new("localhost", 3000, :pool_size => 5, :timeout => 5)

localhost, 3000, where this node may be a slave

Connection.new("localhost", 3000, :slave_ok => true)

Parameters:

  • host (String, Hash) (defaults to: nil)
  • port (Integer) (defaults to: nil)

    specify a port number here if only one host is being specified.

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

    a customizable set of options

Options Hash (opts):

  • :safe (Boolean, Hash) — default: false

    Set the default safe-mode options propogated to DB objects instantiated off of this Connection. This default can be overridden upon instantiation of any DB by explicity setting a :safe value on initialization.

  • :slave_ok (Boolean) — default: false

    Must be set to true when connecting to a single, slave node.

  • :logger (Logger, #debug) — default: nil

    A Logger instance for debugging driver ops. Note that logging negatively impacts performance; therefore, it should not be used for high-performance apps.

  • :pool_size (Integer) — default: 1

    The maximum number of socket self.connections allowed per connection pool. Note: this setting is relevant only for multi-threaded applications.

  • :timeout (Float) — default: 5.0

    When all of the self.connections a pool are checked out, this is the number of seconds to wait for a new connection to be released before throwing an exception. Note: this setting is relevant only for multi-threaded applications (which in Ruby are rare).

  • :op_timeout (Float) — default: nil

    The number of seconds to wait for a read operation to time out. Disabled by default.

  • :connect_timeout (Float) — default: nil

    The number of seconds to wait before timing out a connection attempt.

  • :ssl (Boolean) — default: false

    If true, create the connection to the server using SSL.

Raises:

  • (ReplicaSetConnectionError)

    This is raised if a replica set name is specified and the driver fails to connect to a replica set with that name.

See Also:

Core docs:



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/mongo/connection.rb', line 97

def initialize(host=nil, port=nil, opts={})
  @host_to_try = format_pair(host, port)

  # Host and port of current master.
  @host = @port = nil
  
  # Default maximum BSON object size
  @max_bson_size = Mongo::DEFAULT_MAX_BSON_SIZE
  
  # Lock for request ids.
  @id_lock = Mutex.new
  
  # Connection pool for primay node
  @primary      = nil
  @primary_pool = nil

  check_opts(opts)
  setup(opts)
end

Instance Attribute Details

- (Object) auths (readonly)

Returns the value of attribute auths



41
42
43
# File 'lib/mongo/connection.rb', line 41

def auths
  @auths
end

- (Object) connect_timeout (readonly)

Returns the value of attribute connect_timeout



41
42
43
# File 'lib/mongo/connection.rb', line 41

def connect_timeout
  @connect_timeout
end

- (Object) host_to_try (readonly)

Returns the value of attribute host_to_try



41
42
43
# File 'lib/mongo/connection.rb', line 41

def host_to_try
  @host_to_try
end

- (Object) logger (readonly)

Returns the value of attribute logger



41
42
43
# File 'lib/mongo/connection.rb', line 41

def logger
  @logger
end

- (Object) op_timeout (readonly)

Returns the value of attribute op_timeout



41
42
43
# File 'lib/mongo/connection.rb', line 41

def op_timeout
  @op_timeout
end

- (Object) pool_size (readonly)

Returns the value of attribute pool_size



41
42
43
# File 'lib/mongo/connection.rb', line 41

def pool_size
  @pool_size
end

- (Object) pool_timeout (readonly)

Returns the value of attribute pool_timeout



41
42
43
# File 'lib/mongo/connection.rb', line 41

def pool_timeout
  @pool_timeout
end

- (Object) primary (readonly)

Returns the value of attribute primary



41
42
43
# File 'lib/mongo/connection.rb', line 41

def primary
  @primary
end

- (Object) primary_pool (readonly)

Returns the value of attribute primary_pool



41
42
43
# File 'lib/mongo/connection.rb', line 41

def primary_pool
  @primary_pool
end

- (Object) safe (readonly)

Returns the value of attribute safe



41
42
43
# File 'lib/mongo/connection.rb', line 41

def safe
  @safe
end

- (Object) size (readonly)

Returns the value of attribute size



41
42
43
# File 'lib/mongo/connection.rb', line 41

def size
  @size
end

- (Object) socket_class (readonly)

Returns the value of attribute socket_class



41
42
43
# File 'lib/mongo/connection.rb', line 41

def socket_class
  @socket_class
end

Class Method Details

+ (Mongo::Connection, Mongo::ReplSetConnection) from_uri(string, extra_opts = {})

Initialize a connection to MongoDB using the MongoDB URI spec:

Parameters:

Returns:



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/mongo/connection.rb', line 158

def self.from_uri(string, extra_opts={})
  uri = URIParser.new(string)
  opts = uri.connection_options
  opts.merge!(extra_opts)

  if uri.nodes.length == 1
    opts.merge!({:auths => uri.auths})
    Connection.new(uri.nodes[0][0], uri.nodes[0][1], opts)
  elsif uri.nodes.length > 1
    nodes = uri.nodes.clone
    nodes_with_opts = nodes << opts
    ReplSetConnection.new(*nodes_with_opts)
  else
    raise MongoArgumentError, "No nodes specified. Please ensure that you've provided at least one node."
  end
end

+ (Mongo::Connection) multi(nodes, opts = {})

Deprecated.

DEPRECATED

Initialize a connection to a MongoDB replica set using an array of seed nodes.

The seed nodes specified will be used on the initial connection to the replica set, but note that this list of nodes will be replced by the list of canonical nodes returned by running the is_master command on the replica set.

Examples:

Connection.multi([["db1.example.com", 27017], ["db2.example.com", 27017]])

This connection will read from a random secondary node.

Connection.multi([["db1.example.com", 27017], ["db2.example.com", 27017], ["db3.example.com", 27017]],
                :read_secondary => true)

Parameters:

  • nodes (Array)

    An array of arrays, each of which specifies a host and port.

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

    Any of the available options that can be passed to Connection.new.

Options Hash (opts):

  • :rs_name (String) — default: nil

    The name of the replica set to connect to. An exception will be raised if unable to connect to a replica set with this name.

  • :read_secondary (Boolean) — default: false

    When true, this connection object will pick a random slave to send reads to.

Returns:



143
144
145
146
147
148
# File 'lib/mongo/connection.rb', line 143

def self.multi(nodes, opts={})
  warn "Connection.multi is now deprecated and will be removed in v2.0. Please use ReplSetConnection.new instead."

  nodes << opts
  ReplSetConnection.new(*nodes)
end

Instance Method Details

- (Mongo::DB) [](db_name)

Shortcut for returning a database. Use DB#db to accept options.

Parameters:

  • db_name (String)

    a valid database name.

Returns:

Core docs:



321
322
323
# File 'lib/mongo/connection.rb', line 321

def [](db_name)
  DB.new(db_name, self)
end

- (Boolean) active?

Determine if the connection is active. In a normal case the server_info operation will be performed without issues, but if the connection was dropped by the server or for some reason the sockets are unsynchronized, a ConnectionFailure will be raised and the return will be false.

Returns:

  • (Boolean)


433
434
435
436
437
438
439
440
441
# File 'lib/mongo/connection.rb', line 433

def active?
  return false unless connected?

  ping
  true

  rescue ConnectionFailure
  false
end

- (Hash) add_auth(db_name, username, password)

Save an authentication to this connection. When connecting, the connection will attempt to re-authenticate on every db specificed in the list of auths. This method is called automatically by DB#authenticate.

Note: this method will not actually issue an authentication command. To do that, either run Connection#apply_saved_authentication or DB#authenticate.

Parameters:

Returns:

  • (Hash)

    a hash representing the authentication just added.



243
244
245
246
247
248
249
250
251
# File 'lib/mongo/connection.rb', line 243

def add_auth(db_name, username, password)
  remove_auth(db_name)
  auth = {}
  auth['db_name']  = db_name
  auth['username'] = username
  auth['password'] = password
  @auths << auth
  auth
end

- (Boolean) apply_saved_authentication(opts = {})

Apply each of the saved database authentications.

Returns:

  • (Boolean)

    returns true if authentications exist and succeeed, false if none exists.

Raises:



221
222
223
224
225
226
227
228
# File 'lib/mongo/connection.rb', line 221

def apply_saved_authentication(opts={})
  return false if @auths.empty?
  @auths.each do |auth|
    self[auth['db_name']].issue_authentication(auth['username'], auth['password'], false,
      :socket => opts[:socket])
  end
  true
end

- (Object) authenticate_pools



275
276
277
# File 'lib/mongo/connection.rb', line 275

def authenticate_pools
  @primary_pool.authenticate_existing
end

- (Object) best_available_socket

Excecutes block with the best available socket



523
524
525
526
527
528
529
530
531
532
533
# File 'lib/mongo/connection.rb', line 523

def best_available_socket
  socket = nil
  begin
    socket = checkout_best
    yield socket
  ensure
    if socket
      socket.pool.checkin(socket)
    end
  end
end

- (Object) checkin(socket)

Check a socket back into its pool.



516
517
518
519
520
# File 'lib/mongo/connection.rb', line 516

def checkin(socket)
  if @primary_pool && socket
    socket.pool.checkin(socket)
  end
end

- (Object) checkin_reader(socket)

Checkin a socket used for reading. Note: this is overridden in ReplSetConnection.



505
506
507
# File 'lib/mongo/connection.rb', line 505

def checkin_reader(socket)
  checkin(socket)
end

- (Object) checkin_writer(socket)

Checkin a socket used for writing. Note: this is overridden in ReplSetConnection.



511
512
513
# File 'lib/mongo/connection.rb', line 511

def checkin_writer(socket)
  checkin(socket)
end

- (Object) checkout_best

Prefer primary pool but fall back to secondary



484
485
486
487
# File 'lib/mongo/connection.rb', line 484

def checkout_best
  connect unless connected?
  @primary_pool.checkout
end

- (Object) checkout_reader

Checkout a socket for reading (i.e., a secondary node). Note: this is overridden in ReplSetConnection.



491
492
493
494
# File 'lib/mongo/connection.rb', line 491

def checkout_reader
  connect unless connected?
  @primary_pool.checkout
end

- (Object) checkout_writer

Checkout a socket for writing (i.e., a primary node). Note: this is overridden in ReplSetConnection.



498
499
500
501
# File 'lib/mongo/connection.rb', line 498

def checkout_writer
  connect unless connected?
  @primary_pool.checkout
end

- (true) clear_auths

Remove all authenication information stored in this connection.

Returns:

  • (true)

    this operation return true because it always succeeds.



270
271
272
273
# File 'lib/mongo/connection.rb', line 270

def clear_auths
  @auths = []
  true
end

- (Object) close

Close the connection to the database.



469
470
471
472
473
# File 'lib/mongo/connection.rb', line 469

def close
  @primary_pool.close if @primary_pool
  @primary_pool = nil
  @primary = nil
end

- (Object) connect Also known as: reconnect

Create a new socket and attempt to connect to master. If successful, sets host and port to master and returns the socket.

If connecting to a replica set, this method will replace the initially-provided seed list with any nodes known to the set.

Raises:



399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/mongo/connection.rb', line 399

def connect
  close

  config = check_is_master(@host_to_try)
  if config
    if config['ismaster'] == 1 || config['ismaster'] == true
      @read_primary = true
    elsif @slave_ok
      @read_primary = false
    end

    @max_bson_size = config['maxBsonObjectSize'] || Mongo::DEFAULT_MAX_BSON_SIZE
    set_primary(@host_to_try)
  end

  if !connected?
    raise ConnectionFailure, "Failed to connect to a master node at #{@host_to_try[0]}:#{@host_to_try[1]}"
  end
end

- (Boolean) connected?

It's possible that we defined connected as all nodes being connected??? NOTE: Do check if this needs to be more stringent. Probably not since if any node raises a connection failure, all nodes will be closed.

Returns:

  • (Boolean)


423
424
425
# File 'lib/mongo/connection.rb', line 423

def connected?
  @primary_pool && !@primary_pool.closed?
end

- (Object) copy_database(from, to, from_host = "localhost", username = nil, password = nil)

Copy the database from to to on localhost. The from database is assumed to be on localhost, but an alternate host can be specified.

Parameters:

  • from (String)

    name of the database to copy from.

  • to (String)

    name of the database to copy to.

  • from_host (String) (defaults to: "localhost")

    host of the ‘from’ database.

  • username (String) (defaults to: nil)

    username for authentication against from_db (>=1.3.x).

  • password (String) (defaults to: nil)

    password for authentication against from_db (>=1.3.x).



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
# File 'lib/mongo/connection.rb', line 340

def copy_database(from, to, from_host="localhost", username=nil, password=nil)
  oh = BSON::OrderedHash.new
  oh[:copydb]   = 1
  oh[:fromhost] = from_host
  oh[:fromdb]   = from
  oh[:todb]     = to
  if username || password
    unless username && password
      raise MongoArgumentError, "Both username and password must be supplied for authentication."
    end
    nonce_cmd = BSON::OrderedHash.new
    nonce_cmd[:copydbgetnonce] = 1
    nonce_cmd[:fromhost] = from_host
    result = self["admin"].command(nonce_cmd)
    oh[:nonce] = result["nonce"]
    oh[:username] = username
    oh[:key] = Mongo::Support.auth_key(username, password, oh[:nonce])
  end
  self["admin"].command(oh)
end

- (Hash) database_info

Return a hash with all database names and their respective sizes on disk.

Returns:



287
288
289
290
291
292
# File 'lib/mongo/connection.rb', line 287

def database_info
  doc = self['admin'].command({:listDatabases => 1})
  doc['databases'].each_with_object({}) do |db, info|
    info[db['name']] = db['sizeOnDisk'].to_i
  end
end

- (Array) database_names

Return an array of database names.

Returns:

  • (Array)


297
298
299
# File 'lib/mongo/connection.rb', line 297

def database_names
  database_info.keys
end

- (Mongo::DB) db(db_name, opts = {})

Return a database with the given name. See DB#new for valid options hash parameters.

Parameters:

  • db_name (String)

    a valid database name.

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

    options to be passed to the DB constructor.

Returns:

Core docs:



310
311
312
# File 'lib/mongo/connection.rb', line 310

def db(db_name, opts={})
  DB.new(db_name, self, opts)
end

- (Object) drop_database(name)

Drop a database.

Parameters:

  • name (String)

    name of an existing database.



328
329
330
# File 'lib/mongo/connection.rb', line 328

def drop_database(name)
  self[name].command(:dropDatabase => 1)
end

- (String) host

The host name used for this connection.

Returns:



178
179
180
# File 'lib/mongo/connection.rb', line 178

def host
  @primary_pool.host
end

- (BSON::OrderedHash) lock!

Fsync, then lock the mongod process against writes. Use this to get the datafiles in a state safe for snapshotting, backing up, etc.

Returns:



193
194
195
196
197
198
# File 'lib/mongo/connection.rb', line 193

def lock!
  cmd = BSON::OrderedHash.new
  cmd[:fsync] = 1
  cmd[:lock]  = true
  self['admin'].command(cmd)
end

- (Boolean) locked?

Is this database locked against writes?

Returns:

  • (Boolean)


203
204
205
# File 'lib/mongo/connection.rb', line 203

def locked?
  self['admin']['$cmd.sys.inprog'].find_one['fsyncLock'] == 1
end

- (Object) logout_pools(db)



279
280
281
# File 'lib/mongo/connection.rb', line 279

def logout_pools(db)
  @primary_pool.logout_existing(db)
end

- (Integer) max_bson_size

Returns the maximum BSON object size as returned by the core server. Use the 4MB default when the server doesn't report this.

Returns:

  • (Integer)


479
480
481
# File 'lib/mongo/connection.rb', line 479

def max_bson_size
  @max_bson_size
end

- (Hash) ping

Checks if a server is alive. This command will return immediately even if the server is in a lock.

Returns:



365
366
367
# File 'lib/mongo/connection.rb', line 365

def ping
  self["admin"].command({:ping => 1})
end

- (Integer) port

The port used for this connection.

Returns:

  • (Integer)


185
186
187
# File 'lib/mongo/connection.rb', line 185

def port
  @primary_pool.port
end

- (Mongo::Pool) read_pool

The socket pool that this connection reads from.

Returns:



455
456
457
# File 'lib/mongo/connection.rb', line 455

def read_pool
  @primary_pool
end

- (Object) read_preference

The value of the read preference.



460
461
462
463
464
465
466
# File 'lib/mongo/connection.rb', line 460

def read_preference
  if slave_ok?
    :secondary
  else
    :primary
  end
end

- (Boolean) read_primary? Also known as: primary?

Determine whether we're reading from a primary node. If false, this connection connects to a secondary node and @slave_ok is true.

Returns:

  • (Boolean)


447
448
449
# File 'lib/mongo/connection.rb', line 447

def read_primary?
  @read_primary
end

- (Boolean) remove_auth(db_name)

Remove a saved authentication for this connection.

Parameters:

Returns:

  • (Boolean)


258
259
260
261
262
263
264
265
# File 'lib/mongo/connection.rb', line 258

def remove_auth(db_name)
  return unless @auths
  if @auths.reject! { |a| a['db_name'] == db_name }
    true
  else
    false
  end
end

- (Hash) server_info

Get the build information for the current connection.

Returns:



372
373
374
# File 'lib/mongo/connection.rb', line 372

def server_info
  self["admin"].command({:buildinfo => 1})
end

- (Mongo::ServerVersion) server_version

Get the build version of the current server.

Returns:



381
382
383
# File 'lib/mongo/connection.rb', line 381

def server_version
  ServerVersion.new(server_info["version"])
end

- (Boolean) slave_ok?

Is it okay to connect to a slave?

Returns:

  • (Boolean)


388
389
390
# File 'lib/mongo/connection.rb', line 388

def slave_ok?
  @slave_ok
end

- (BSON::OrderedHash) unlock!

Unlock a previously fsync-locked mongod process.

Returns:



210
211
212
# File 'lib/mongo/connection.rb', line 210

def unlock!
  self['admin']['$cmd.sys.unlock'].find_one
end