class Mongo::MongoClient

Instantiates and manages self.connections to MongoDB.

Constants

CLIENT_ONLY_OPTS
ConditionVariable
DEFAULT_DB_NAME
DEFAULT_HOST
DEFAULT_PORT
GENERIC_OPTS
Mutex
POOL_OPTS
READ_PREFERENCE_OPTS
SSL_OPTS
TIMEOUT_OPTS
WRITE_CONCERN_OPTS

Attributes

acceptable_latency[R]
auths[R]
connect_timeout[R]
host_to_try[R]
logger[R]
op_timeout[R]
pool_size[R]
pool_timeout[R]
primary[R]
primary_pool[R]
read[R]
size[R]
socket_class[R]
socket_opts[R]
tag_sets[R]
write_concern[R]

Public Class Methods

from_uri(uri = ENV['MONGODB_URI'], extra_opts={}) click to toggle source

Initialize a connection to MongoDB using the MongoDB URI spec.

Since ::new cannot be used with any ENV["MONGODB_URI"] that has multiple hosts (implying a replicaset), you may use this when the type of your connection varies by environment and should be determined solely from ENV["MONGODB_URI"].

@param uri [String]

A string of the format mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/database]

@param opts Any of the options available for ::new

@return [Mongo::MongoClient, Mongo::MongoReplicaSetClient]

# File lib/mongo/mongo_client.rb, line 201
def self.from_uri(uri = ENV['MONGODB_URI'], extra_opts={})
  parser = URIParser.new(uri)
  parser.connection(extra_opts)
end
multi(nodes, opts={}) click to toggle source

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 replaced by the list of canonical nodes returned by running the is_master command on the replica set.

@param nodes [Array] An array of arrays, each of which specifies a host and port. @param opts [Hash] Any of the available options that can be passed to ::new.

@option opts [String] :rs_name (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.

@option opts [Boolean] :read_secondary (false) When true, this connection object will pick a random slave

to send reads to.

@example

Mongo::MongoClient.multi([["db1.example.com", 27017], ["db2.example.com", 27017]])

@example This connection will read from a random secondary node.

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

@return [Mongo::MongoClient]

@deprecated

# File lib/mongo/mongo_client.rb, line 184
def self.multi(nodes, opts={})
  warn "MongoClient.multi is now deprecated and will be removed in v2.0. Please use MongoReplicaSetClient.new instead."

  MongoReplicaSetClient.new(nodes, opts)
end
new(*args) click to toggle source

Create a connection to single MongoDB instance.

If no args are provided, it will check ENV["MONGODB_URI"].

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 Mongo::MongoReplicaSetClient.new instead.

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

@overload initialize(host, port, opts={})

@param [String] host hostname for the target MongoDB server.
@param [Integer] port specify a port number here if only one host is being specified.
@param [Hash] opts hash of optional settings and configuration values.

@option opts [String, Integer, Symbol] :w (1) Set default number of nodes to which a write
  should be acknowledged
@option opts [Boolean] :j (false) Set journal acknowledgement
@option opts [Integer] :wtimeout (nil) Set replica set acknowledgement timeout
@option opts [Boolean] :fsync (false) Set fsync acknowledgement.

Notes about Write-Concern Options:
 Write concern options are propagated to objects instantiated from this MongoClient.
 These defaults can be overridden upon instantiation of any object by explicitly setting an options hash
 on initialization.

@option opts [Boolean] :ssl (false) If true, create the connection to the server using SSL.
@option opts [String] :ssl_cert (nil) The certificate file used to identify the local connection against MongoDB.
@option opts [String] :ssl_key (nil) The private keyfile used to identify the local connection against MongoDB.
  If included with the :ssl_cert then only :ssl_cert is needed.
@option opts [Boolean] :ssl_verify (nil) Specifies whether or not peer certification validation should occur.
@option opts [String] :ssl_ca_cert (nil) The ca_certs file contains a set of concatenated "certification authority"
  certificates, which are used to validate certificates passed from the other end of the connection.
  Required for :ssl_verify.
@option opts [Boolean] :slave_ok (false) Must be set to +true+ when connecting
  to a single, slave node.
@option opts [Logger, #debug] :logger (nil) A Logger instance for debugging driver ops. Note that
  logging negatively impacts performance; therefore, it should not be used for high-performance apps.
@option opts [Integer] :pool_size (1) The maximum number of socket self.connections allowed per
  connection pool. Note: this setting is relevant only for multi-threaded applications.
@option opts [Float] :pool_timeout (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.
@option opts [Float] :op_timeout (nil) The number of seconds to wait for a read operation to time out.
  Disabled by default.
@option opts [Float] :connect_timeout (nil) The number of seconds to wait before timing out a
  connection attempt.

@example localhost, 27017 (or ENV["MONGODB_URI"] if available)

MongoClient.new

@example localhost, 27017

MongoClient.new("localhost")

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

MongoClient.new("localhost", 3000, :pool_size => 5, :pool_timeout => 5)

@example localhost, 3000, where this node may be a slave

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

@example Unix Domain Socket

MongoClient.new("/var/run/mongodb.sock")

@see api.mongodb.org/ruby/current/file.REPLICA_SETS.html Replica sets in Ruby

@raise [ReplicaSetConnectionError] This is raised if a replica set name is specified and the

driver fails to connect to a replica set with that name.

@raise [MongoArgumentError] If called with no arguments and ENV["MONGODB_URI"] implies a replica set.

@core self.connections

# File lib/mongo/mongo_client.rb, line 135
def initialize(*args)
  opts = args.last.is_a?(Hash) ? args.pop : {}
  @host, @port = parse_init(args[0], args[1], opts)

  # Lock for request ids.
  @id_lock = Mutex.new

  # Connection pool for primary node
  @primary      = nil
  @primary_pool = nil
  @mongos       = false

  # Not set for direct connection
  @tag_sets = []
  @acceptable_latency = 15

  @max_message_size = nil
  @max_bson_size = nil

  check_opts(opts)
  setup(opts.dup)
end

Public Instance Methods

[](db_name) click to toggle source

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

@param [String] db_name a valid database name.

@return [Mongo::DB]

@core databases []-instance_method

# File lib/mongo/mongo_client.rb, line 372
def [](db_name)
  DB.new(db_name, self)
end
active?() click to toggle source

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.

@return [Boolean]

# File lib/mongo/mongo_client.rb, line 505
def active?
  return false unless connected?

  ping
  true

  rescue ConnectionFailure
  false
end
add_auth(db_name, username, password, source) click to toggle source

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

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

@param [String] db_name @param [String] username @param [String] password

@return [Hash] a hash representing the authentication just added.

# File lib/mongo/mongo_client.rb, line 292
def add_auth(db_name, username, password, source)
  if @auths.any? {|a| a[:db_name] == db_name}
    raise MongoArgumentError, "Cannot apply multiple authentications to database '#{db_name}'"
  end

  auth = {
    :db_name  => db_name,
    :username => username,
    :password => password,
    :source => source
  }
  @auths << auth
  auth
end
apply_saved_authentication(opts={}) click to toggle source

Apply each of the saved database authentications.

@return [Boolean] returns true if authentications exist and succeeds, false

if none exists.

@raise [AuthenticationError] raises an exception if any one

authentication fails.
# File lib/mongo/mongo_client.rb, line 270
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,
      :source => auth[:source], :socket => opts[:socket])
  end
  true
end
authenticate_pools() click to toggle source
# File lib/mongo/mongo_client.rb, line 325
def authenticate_pools
  @primary_pool.authenticate_existing
end
check_is_master(node) click to toggle source

Internal method for checking isMaster() on a given node.

@param node [Array] Port and host for the target node @return [Hash] Response from isMaster()

@private

# File lib/mongo/mongo_client.rb, line 578
def check_is_master(node)
  begin
    host, port = *node
    config = nil
    socket = @socket_class.new(host, port, @op_timeout, @connect_timeout, @socket_opts)
    if @connect_timeout
      Timeout::timeout(@connect_timeout, OperationTimeout) do
        config = self['admin'].command({:ismaster => 1}, :socket => socket)
      end
    else
      config = self['admin'].command({:ismaster => 1}, :socket => socket)
    end
  rescue OperationFailure, SocketError, SystemCallError, IOError
    close
  ensure
    socket.close unless socket.nil? || socket.closed?
  end
  config
end
checkin(socket) click to toggle source

Check a socket back into its pool. Note: this is overridden in MongoReplicaSetClient.

# File lib/mongo/mongo_client.rb, line 566
def checkin(socket)
  if @primary_pool && socket && socket.pool
    socket.checkin
  end
end
checkout_reader(read_preference) click to toggle source

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

# File lib/mongo/mongo_client.rb, line 552
def checkout_reader(read_preference)
  connect unless connected?
  @primary_pool.checkout
end
checkout_writer() click to toggle source

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

# File lib/mongo/mongo_client.rb, line 559
def checkout_writer
  connect unless connected?
  @primary_pool.checkout
end
clear_auths() click to toggle source

Remove all authentication information stored in this connection.

@return [true] this operation return true because it always succeeds.

# File lib/mongo/mongo_client.rb, line 320
def clear_auths
  @auths = []
  true
end
close() click to toggle source

Close the connection to the database.

# File lib/mongo/mongo_client.rb, line 532
def close
  @primary_pool.close if @primary_pool
  @primary_pool = nil
  @primary = nil
end
connect() click to toggle source

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.

@raise [ConnectionFailure] if unable to connect to any host or port.

# File lib/mongo/mongo_client.rb, line 466
def connect
  close
  config = check_is_master(host_port)
  if config
    if config['ismaster'] == 1 || config['ismaster'] == true
      @read_primary = true
    elsif @slave_ok
      @read_primary = false
    end

    if config.has_key?('msg') && config['msg'] == 'isdbgrid'
      @mongos = true
    end

    @max_bson_size = config['maxBsonObjectSize']
    @max_message_size = config['maxMessageSizeBytes']
    set_primary(host_port)
  end

  if !connected?
    raise ConnectionFailure, "Failed to connect to a master node at #{host_port.join(":")}"
  end
  true
end
Also aliased as: reconnect
connected?() click to toggle source

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.

# File lib/mongo/mongo_client.rb, line 495
def connected?
  !!(@primary_pool && !@primary_pool.closed?)
end
copy_database(from, to, from_host=DEFAULT_HOST, username=nil, password=nil) click to toggle source

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

@param [String] from name of the database to copy from. @param [String] to name of the database to copy to. @param [String] from_host host of the 'from' database. @param [String] username username for authentication against from_db (>=1.3.x). @param [String] password password for authentication against from_db (>=1.3.x).

# File lib/mongo/mongo_client.rb, line 404
def copy_database(from, to, from_host=DEFAULT_HOST, 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
database_info() click to toggle source

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

@return [Hash]

# File lib/mongo/mongo_client.rb, line 337
def database_info
  doc = self['admin'].command({:listDatabases => 1})
  doc['databases'].inject({}) do |info, db|
    info[db['name']] = db['sizeOnDisk'].to_i
    info
  end
end
database_names() click to toggle source

Return an array of database names.

@return [Array]

# File lib/mongo/mongo_client.rb, line 348
def database_names
  database_info.keys
end
db(db_name = @default_db, opts = {}) click to toggle source

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

@param [String] db_name a valid database name. @param [Hash] opts options to be passed to the DB constructor.

@return [Mongo::DB]

@core databases db-instance_method

# File lib/mongo/mongo_client.rb, line 361
def db(db_name = @default_db, opts = {})
  DB.new(db_name, self, opts)
end
drop_database(name) click to toggle source

Drop a database.

@param [String] name name of an existing database.

# File lib/mongo/mongo_client.rb, line 392
def drop_database(name)
  self[name].command(:dropDatabase => 1)
end
host() click to toggle source

The host name used for this connection.

@return [String]

# File lib/mongo/mongo_client.rb, line 223
def host
  @primary_pool.host
end
host_port() click to toggle source
# File lib/mongo/mongo_client.rb, line 234
def host_port
  [@host, @port]
end
lock!() click to toggle source

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

@return [BSON::OrderedHash] the command response

# File lib/mongo/mongo_client.rb, line 242
def lock!
  cmd = BSON::OrderedHash.new
  cmd[:fsync] = 1
  cmd[:lock]  = true
  self['admin'].command(cmd)
end
locked?() click to toggle source

Is this database locked against writes?

@return [Boolean]

# File lib/mongo/mongo_client.rb, line 252
def locked?
  [1, true].include? self['admin']['$cmd.sys.inprog'].find_one['fsyncLock']
end
logout_pools(db) click to toggle source
# File lib/mongo/mongo_client.rb, line 329
def logout_pools(db)
  @primary_pool.logout_existing(db)
end
max_bson_size() click to toggle source

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

@return [Integer]

# File lib/mongo/mongo_client.rb, line 542
def max_bson_size
  @max_bson_size || DEFAULT_MAX_BSON_SIZE
end
max_message_size() click to toggle source
# File lib/mongo/mongo_client.rb, line 546
def max_message_size
  @max_message_size || max_bson_size * MESSAGE_SIZE_FACTOR
end
mongos?() click to toggle source
# File lib/mongo/mongo_client.rb, line 455
def mongos?
  @mongos
end
parse_init(host, port, opts) click to toggle source
# File lib/mongo/mongo_client.rb, line 206
def parse_init(host, port, opts)
  if host.nil? && port.nil? && ENV.has_key?('MONGODB_URI')
    parser = URIParser.new(ENV['MONGODB_URI'])
    if parser.replicaset?
      raise MongoArgumentError,
        "ENV['MONGODB_URI'] implies a replica set."
    end
    opts.merge!(parser.connection_options)
    [parser.host, parser.port]
  else
    [host || DEFAULT_HOST, port || DEFAULT_PORT]
  end
end
pin_pool(pool, read_prefs) click to toggle source
# File lib/mongo/mongo_client.rb, line 383
def pin_pool(pool, read_prefs)
end
ping() click to toggle source

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

@return [Hash]

# File lib/mongo/mongo_client.rb, line 429
def ping
  self["admin"].command({:ping => 1})
end
pinned_pool() click to toggle source
# File lib/mongo/mongo_client.rb, line 379
def pinned_pool
  @primary_pool
end
port() click to toggle source

The port used for this connection.

@return [Integer]

# File lib/mongo/mongo_client.rb, line 230
def port
  @primary_pool.port
end
primary?()
Alias for: read_primary?
read_pool() click to toggle source

The socket pool that this connection reads from.

@return [Mongo::Pool]

# File lib/mongo/mongo_client.rb, line 527
def read_pool
  @primary_pool
end
read_primary?() click to toggle source

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

@return [Boolean]

# File lib/mongo/mongo_client.rb, line 519
def read_primary?
  @read_primary
end
Also aliased as: primary?
reconnect()
Alias for: connect
refresh() click to toggle source
# File lib/mongo/mongo_client.rb, line 376
def refresh
end
remove_auth(db_name) click to toggle source

Remove a saved authentication for this connection.

@param [String] db_name

@return [Boolean]

# File lib/mongo/mongo_client.rb, line 312
def remove_auth(db_name)
  return unless @auths
  @auths.reject! { |a| a[:db_name] == db_name } ? true : false
end
server_info() click to toggle source

Get the build information for the current connection.

@return [Hash]

# File lib/mongo/mongo_client.rb, line 436
def server_info
  self["admin"].command({:buildinfo => 1})
end
server_version() click to toggle source

Get the build version of the current server.

@return [Mongo::ServerVersion]

object allowing easy comparability of version.
# File lib/mongo/mongo_client.rb, line 444
def server_version
  ServerVersion.new(server_info["version"])
end
slave_ok?() click to toggle source

Is it okay to connect to a slave?

@return [Boolean]

# File lib/mongo/mongo_client.rb, line 451
def slave_ok?
  @slave_ok
end
unlock!() click to toggle source

Unlock a previously fsync-locked mongod process.

@return [BSON::OrderedHash] command response

# File lib/mongo/mongo_client.rb, line 259
def unlock!
  self['admin']['$cmd.sys.unlock'].find_one
end
unpin_pool() click to toggle source
# File lib/mongo/mongo_client.rb, line 386
def unpin_pool
end

Protected Instance Methods

check_opts(opts) click to toggle source
# File lib/mongo/mongo_client.rb, line 610
def check_opts(opts)
  bad_opts = opts.keys.reject { |opt| valid_opts.include?(opt) }

  unless bad_opts.empty?
    bad_opts.each {|opt| warn "#{opt} is not a valid option for #{self.class}"}
  end
end
setup(opts) click to toggle source

Parse option hash

# File lib/mongo/mongo_client.rb, line 619
def setup(opts)
  @slave_ok = opts.delete(:slave_ok)
  @ssl      = opts.delete(:ssl)
  @unix     = @host ? @host.end_with?('.sock') : false

  # if ssl options are present, but ssl is nil/false raise for misconfig
  ssl_opts = opts.keys.select { |k| k.to_s.start_with?('ssl') }
  if ssl_opts.size > 0 && !@ssl
    raise MongoArgumentError, "SSL has not been enabled (:ssl=false) " +
      "but the following  SSL related options were " +
      "specified: #{ssl_opts.join(', ')}"
  end

  @socket_opts = {}
  if @ssl
    # construct ssl socket opts
    @socket_opts[:key]     = opts.delete(:ssl_key)
    @socket_opts[:cert]    = opts.delete(:ssl_cert)
    @socket_opts[:verify]  = opts.delete(:ssl_verify)
    @socket_opts[:ca_cert] = opts.delete(:ssl_ca_cert)

    # verify peer requires ca_cert, raise if only one is present
    if @socket_opts[:verify] && !@socket_opts[:ca_cert]
      raise MongoArgumentError,
        "If :ssl_verify_mode has been specified, then you must include " +
        ":ssl_ca_cert in order to perform server validation."
    end

    @socket_class = Mongo::SSLSocket
  elsif @unix
    @socket_class = Mongo::UNIXSocket
  else
    @socket_class = Mongo::TCPSocket
  end

  # Authentication objects
  @auths = opts.delete(:auths) || []

  # Pool size and timeout.
  @pool_size = opts.delete(:pool_size) || 1
  if opts[:timeout]
    warn "The :timeout option has been deprecated " +
         "and will be removed in the 2.0 release. " +
         "Use :pool_timeout instead."
  end
  @pool_timeout = opts.delete(:pool_timeout) || opts.delete(:timeout) || 5.0

  # Timeout on socket read operation.
  @op_timeout = opts.delete(:op_timeout) || nil

  # Timeout on socket connect.
  @connect_timeout = opts.delete(:connect_timeout) || 30

  @logger = opts.delete(:logger) || nil

  if @logger
    write_logging_startup_message
  end

  # Determine read preference
  if defined?(@slave_ok) && (@slave_ok) || defined?(@read_secondary) && @read_secondary
    @read = :secondary_preferred
  else
    @read = opts.delete(:read) || :primary
  end
  Mongo::ReadPreference::validate(@read)

  @default_db = opts.delete(:default_db) || DEFAULT_DB_NAME
  @tag_sets = opts.delete(:tag_sets) || []
  @acceptable_latency = opts.delete(:secondary_acceptable_latency_ms) || 15

  # Connection level write concern options.
  @write_concern = get_write_concern(opts)

  connect if opts.fetch(:connect, true)
end
valid_opts() click to toggle source
# File lib/mongo/mongo_client.rb, line 600
def valid_opts
  GENERIC_OPTS +
  CLIENT_ONLY_OPTS +
  POOL_OPTS +
  READ_PREFERENCE_OPTS +
  WRITE_CONCERN_OPTS +
  TIMEOUT_OPTS +
  SSL_OPTS
end

Private Instance Methods

set_primary(node) click to toggle source

Set the specified node as primary.

# File lib/mongo/mongo_client.rb, line 699
def set_primary(node)
  host, port = *node
  @primary = [host, port]
  @primary_pool = Pool.new(self, host, port, :size => @pool_size, :timeout => @pool_timeout)
end