Class: Mongo::Connection

Inherits:
Object show all
Defined in:
lib/mongo/connection.rb

Overview

Instantiates and manages connections to MongoDB.

Direct Known Subclasses

ReplSetConnection

Constant Summary

TCPSocket =
::TCPSocket
Mutex =
::Mutex
ConditionVariable =
::ConditionVariable
DEFAULT_PORT =
27017
STANDARD_HEADER_SIZE =
16
RESPONSE_HEADER_SIZE =
20
@@current_request_id =

Counter for generating unique request ids.

0

Instance Attribute Summary (collapse)

Class Method Summary (collapse)

Instance Method Summary (collapse)

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 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:

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

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

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

    a customizable set of options

Options Hash (opts):

  • (Boolean, Hash) :safe — 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.

  • (Boolean) :slave_ok — default: false

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

  • (Logger, #debug) :logger — 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.

  • (Integer) :pool_size — default: 1

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

  • (Float) :timeout — default: 5.0

    When all of the 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).

  • (Float) :op_timeout — default: nil

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

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:



92
93
94
95
96
97
98
99
100
101
102
# File 'lib/mongo/connection.rb', line 92

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

  # Host and port of current master.
  @host = @port = nil

  # slave_ok can be true only if one node is specified
  @slave_ok = opts[:slave_ok]

  setup(opts)
end

Instance Attribute Details

- (Object) auths (readonly)

Returns the value of attribute auths



38
39
40
# File 'lib/mongo/connection.rb', line 38

def auths
  @auths
end

- (Object) host_to_try (readonly)

Returns the value of attribute host_to_try



38
39
40
# File 'lib/mongo/connection.rb', line 38

def host_to_try
  @host_to_try
end

- (Object) logger (readonly)

Returns the value of attribute logger



38
39
40
# File 'lib/mongo/connection.rb', line 38

def logger
  @logger
end

- (Object) pool_size (readonly)

Returns the value of attribute pool_size



38
39
40
# File 'lib/mongo/connection.rb', line 38

def pool_size
  @pool_size
end

- (Object) primary (readonly)

Returns the value of attribute primary



38
39
40
# File 'lib/mongo/connection.rb', line 38

def primary
  @primary
end

- (Object) primary_pool (readonly)

Returns the value of attribute primary_pool



38
39
40
# File 'lib/mongo/connection.rb', line 38

def primary_pool
  @primary_pool
end

- (Object) safe (readonly)

Returns the value of attribute safe



38
39
40
# File 'lib/mongo/connection.rb', line 38

def safe
  @safe
end

- (Object) size (readonly)

Returns the value of attribute size



38
39
40
# File 'lib/mongo/connection.rb', line 38

def size
  @size
end

Class Method Details

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

Initialize a connection to MongoDB using the MongoDB URI spec:

Parameters:

  • (String) uri

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

  • opts

    Any of the options available for Connection.new

Returns:



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/mongo/connection.rb', line 145

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:

  • (Array) nodes

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

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

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

Options Hash (opts):

  • (String) :rs_name — 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.

  • (Boolean) :read_secondary — default: false

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

Returns:



130
131
132
133
134
135
# File 'lib/mongo/connection.rb', line 130

def self.multi(nodes, opts={})
  warn "Connection.multi is now deprecated. 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:

  • (String) db_name

    a valid database name.

Returns:

Core docs:



308
309
310
# File 'lib/mongo/connection.rb', line 308

def [](db_name)
  DB.new(db_name, self, :safe => @safe)
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)


540
541
542
543
544
545
546
547
548
# File 'lib/mongo/connection.rb', line 540

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.



230
231
232
233
234
235
236
237
238
# File 'lib/mongo/connection.rb', line 230

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

- (Integer) add_message_headers(message, operation)

Prepares a message for transmission to MongoDB by constructing a valid message header.

Note: this method modifies message by reference.

Returns:

  • (Integer)

    the request id used in the header



807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
# File 'lib/mongo/connection.rb', line 807

def add_message_headers(message, operation)
  headers = [
    # Message size.
    16 + message.size,

    # Unique request id.
    request_id = get_request_id,

    # Response id.
    0,

    # Opcode.
    operation
  ].pack('VVVV')

  message.prepend!(headers)

  request_id
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:



208
209
210
211
212
213
214
215
# File 'lib/mongo/connection.rb', line 208

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



262
263
264
# File 'lib/mongo/connection.rb', line 262

def authenticate_pools
  @primary_pool.authenticate_existing
end

- (Object) build_last_error_message(message, db_name, opts)

Constructs a getlasterror message. This method is used exclusively by Connection#send_message_with_safe_check.

Because it modifies message by reference, we don’t need to return it.



786
787
788
789
790
791
792
793
794
795
796
797
798
799
# File 'lib/mongo/connection.rb', line 786

def build_last_error_message(message, db_name, opts)
  message.put_int(0)
  BSON::BSON_RUBY.serialize_cstr(message, "#{db_name}.$cmd")
  message.put_int(0)
  message.put_int(-1)
  cmd = BSON::OrderedHash.new
  cmd[:getlasterror] = 1
  if opts.is_a?(Hash)
    opts.assert_valid_keys(:w, :wtimeout, :fsync)
    cmd.merge!(opts)
  end
  message.put_binary(BSON::BSON_CODER.serialize(cmd, false).to_s)
  nil
end

- (Object) checkin_reader(socket)

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



591
592
593
594
595
# File 'lib/mongo/connection.rb', line 591

def checkin_reader(socket)
  if @primary_pool
    @primary_pool.checkin(socket)
  end
end

- (Object) checkin_writer(socket)

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



599
600
601
602
603
# File 'lib/mongo/connection.rb', line 599

def checkin_writer(socket)
  if @primary_pool
    @primary_pool.checkin(socket)
  end
end

- (Object) checkout_reader

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



577
578
579
580
# File 'lib/mongo/connection.rb', line 577

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.



584
585
586
587
# File 'lib/mongo/connection.rb', line 584

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.



257
258
259
260
# File 'lib/mongo/connection.rb', line 257

def clear_auths
  @auths = []
  true
end

- (Object) close

Close the connection to the database.



560
561
562
563
564
# File 'lib/mongo/connection.rb', line 560

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:



501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
# File 'lib/mongo/connection.rb', line 501

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

    set_primary(@host_to_try)
  end

  if connected?
    BSON::BSON_CODER.update_max_bson_size(self)
  else
    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)


530
531
532
# File 'lib/mongo/connection.rb', line 530

def connected?
  @primary_pool && @primary_pool.host && @primary_pool.port
end

- (Boolean) connecting?

Returns:

  • (Boolean)


523
524
525
# File 'lib/mongo/connection.rb', line 523

def connecting?
  @nodes_to_try.length > 0
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:

  • (String) from

    name of the database to copy from.

  • (String) to

    name of the database to copy to.

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

    host of the ‘from’ database.

  • (String) username (defaults to: nil)

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

  • (String) password (defaults to: nil)

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



327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
# File 'lib/mongo/connection.rb', line 327

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:



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

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)


284
285
286
# File 'lib/mongo/connection.rb', line 284

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:

  • (String) db_name

    a valid database name.

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

    options to be passed to the DB constructor.

Returns:

Core docs:



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

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

- (Object) drop_database(name)

Drop a database.

Parameters:

  • (String) name

    name of an existing database.



315
316
317
# File 'lib/mongo/connection.rb', line 315

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

- (Object) get_request_id

Increment and return the next available request id.

return [Integer]



830
831
832
833
834
835
836
# File 'lib/mongo/connection.rb', line 830

def get_request_id
  request_id = ''
  @id_lock.synchronize do
    request_id = @@current_request_id += 1
  end
  request_id
end

- (String) host

The host name used for this connection.

Returns:



165
166
167
# File 'lib/mongo/connection.rb', line 165

def host
  @primary_pool.host
end

- (Object) instrument(name, payload = {}, &blk)

Execute the block and log the operation described by name and payload. TODO: Not sure if this should take a block.



608
609
610
611
612
# File 'lib/mongo/connection.rb', line 608

def instrument(name, payload = {}, &blk)
  res = yield
  log_operation(name, payload)
  res
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:



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

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)


190
191
192
# File 'lib/mongo/connection.rb', line 190

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

- (Object) logout_pools(db)



266
267
268
# File 'lib/mongo/connection.rb', line 266

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)


570
571
572
573
# File 'lib/mongo/connection.rb', line 570

def max_bson_size
  config = self['admin'].command({:ismaster => 1})
  config['maxBsonObjectSize'] || Mongo::DEFAULT_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:



352
353
354
# File 'lib/mongo/connection.rb', line 352

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

- (Integer) port

The port used for this connection.

Returns:

  • (Integer)


172
173
174
# File 'lib/mongo/connection.rb', line 172

def port
  @primary_pool.port
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)


554
555
556
# File 'lib/mongo/connection.rb', line 554

def read_primary?
  @read_primary
end

- (Object) receive_data(length, socket)

Raises:



884
885
886
887
888
889
890
891
892
893
894
895
896
897
# File 'lib/mongo/connection.rb', line 884

def receive_data(length, socket)
  message = new_binary_string
  socket.read(length, message)
  raise ConnectionFailure, "connection closed" unless message && message.length > 0
  if message.length < length
    chunk = new_binary_string
    while message.length < length
      socket.read(length - message.length, chunk)
      raise ConnectionFailure, "connection closed" unless chunk.length > 0
      message << chunk
    end
  end
  message
end

- (Array) receive_message(operation, message, log_message = nil, socket = nil, command = false)

Sends a message to the database and waits for the response.

Parameters:

  • (Integer) operation

    a MongoDB opcode.

  • (BSON::ByteBuffer) message

    a message to send to the database.

  • (String) log_message (defaults to: nil)

    this is currently a no-op and will be removed.

  • (Socket) socket (defaults to: nil)

    a socket to use in lieu of checking out a new one.

  • (Boolean) command (defaults to: false)

    (false) indicate whether this is a command. If this is a command, the message will be sent to the primary node.

Returns:

  • (Array)

    An array whose indexes include [0] documents returned, [1] number of document received, and [3] a cursor_id.



469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
# File 'lib/mongo/connection.rb', line 469

def receive_message(operation, message, log_message=nil, socket=nil, command=false)
  request_id = add_message_headers(message, operation)
  packed_message = message.to_s
  begin
    if socket
      sock = socket
      checkin = false
    else
      sock = (command ? checkout_writer : checkout_reader)
      checkin = true
    end

    result = ''
    @safe_mutexes[sock].synchronize do
      send_message_on_socket(packed_message, sock)
      result = receive(sock, request_id)
    end
  ensure
    if checkin
      command ? checkin_writer(sock) : checkin_reader(sock)
    end
  end
  result
end

- (Object) receive_message_on_socket(length, socket)

Low-level method for receiving data from socket. Requires length and an available socket.



862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
# File 'lib/mongo/connection.rb', line 862

def receive_message_on_socket(length, socket)
  begin
    if @op_timeout
      message = nil
      Mongo::TimeoutHandler.timeout(@op_timeout, OperationTimeout) do
        message = receive_data(length, socket)
      end
    else
      message = receive_data(length, socket)
    end
    rescue => ex
      close

      if ex.class == OperationTimeout
        raise OperationTimeout, "Timed out waiting on socket read."
      else
        raise ConnectionFailure, "Operation failed with the following exception: #{ex}"
      end
  end
  message
end

- (Boolean) remove_auth(db_name)

Remove a saved authentication for this connection.

Parameters:

Returns:

  • (Boolean)


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

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

- (Integer) send_message(operation, message, opts = {})

Send a message to MongoDB, adding the necessary headers.

Parameters:

  • (Integer) operation

    a MongoDB opcode.

  • (BSON::ByteBuffer) message

    a message to send to the database.

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

    a customizable set of options

Options Hash (opts):

  • (Symbol) :connection — default: :writer

    The connection to which this message should be sent. Valid options are :writer and :reader.

Returns:

  • (Integer)

    number of bytes sent



388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
# File 'lib/mongo/connection.rb', line 388

def send_message(operation, message, opts={})
  if opts.is_a?(String)
    warn "Connection#send_message no longer takes a string log message. " +
      "Logging is now handled within the Collection and Cursor classes."
    opts = {}
  end

  connection = opts.fetch(:connection, :writer)

  begin
    add_message_headers(message, operation)
    packed_message = message.to_s

    if connection == :writer
      socket = checkout_writer
    else
      socket = checkout_reader
    end

    send_message_on_socket(packed_message, socket)
  ensure
    if connection == :writer
      checkin_writer(socket)
    else
      checkin_reader(socket)
    end
  end
end

- (Integer) send_message_on_socket(packed_message, socket)

Low-level method for sending a message on a socket. Requires a packed message and an available socket,

Returns:

  • (Integer)

    number of bytes sent



842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
# File 'lib/mongo/connection.rb', line 842

def send_message_on_socket(packed_message, socket)
  begin
  total_bytes_sent = socket.send(packed_message, 0)
  if total_bytes_sent != packed_message.size
    packed_message.slice!(0, total_bytes_sent)
    while packed_message.size > 0
      byte_sent = socket.send(packed_message, 0)
      total_bytes_sent += byte_sent
      packed_message.slice!(0, byte_sent)
    end
  end
  total_bytes_sent
  rescue => ex
    close
    raise ConnectionFailure, "Operation failed with the following exception: #{ex}"
  end
end

- (Hash) send_message_with_safe_check(operation, message, db_name, log_message = nil, last_error_params = false)

Sends a message to the database, waits for a response, and raises an exception if the operation has failed.

Parameters:

  • (Integer) operation

    a MongoDB opcode.

  • (BSON::ByteBuffer) message

    a message to send to the database.

  • (String) db_name

    the name of the database. used on call to get_last_error.

  • (Hash) last_error_params (defaults to: false)

    parameters to be sent to getLastError. See DB#error for available options.

Returns:

  • (Hash)

    The document returned by the call to getlasterror.

See Also:



429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
# File 'lib/mongo/connection.rb', line 429

def send_message_with_safe_check(operation, message, db_name, log_message=nil, last_error_params=false)
  docs = num_received = cursor_id = ''
  add_message_headers(message, operation)

  last_error_message = BSON::ByteBuffer.new
  build_last_error_message(last_error_message, db_name, last_error_params)
  last_error_id = add_message_headers(last_error_message, Mongo::Constants::OP_QUERY)

  packed_message = message.append!(last_error_message).to_s
  begin
    sock = checkout_writer
    @safe_mutexes[sock].synchronize do
      send_message_on_socket(packed_message, sock)
      docs, num_received, cursor_id = receive(sock, last_error_id)
    end
  ensure
    checkin_writer(sock)
  end

  if num_received == 1 && (error = docs[0]['err'] || docs[0]['errmsg'])
    close if error == "not master"
    error = "wtimeout" if error == "timeout"
    raise Mongo::OperationFailure, docs[0]['code'].to_s + ': ' + error
  end

  docs[0]
end

- (Hash) server_info

Get the build information for the current connection.

Returns:



359
360
361
# File 'lib/mongo/connection.rb', line 359

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

- (Mongo::ServerVersion) server_version

Get the build version of the current server.

Returns:



368
369
370
# File 'lib/mongo/connection.rb', line 368

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

- (Boolean) slave_ok?

Is it okay to connect to a slave?

Returns:

  • (Boolean)


375
376
377
# File 'lib/mongo/connection.rb', line 375

def slave_ok?
  @slave_ok
end

- (BSON::OrderedHash) unlock!

Unlock a previously fsync-locked mongod process.

Returns:



197
198
199
# File 'lib/mongo/connection.rb', line 197

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