Class: Mongo::Cluster

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
Mongo::ClusterTime::Consumer, Event::Subscriber, Loggable, Monitoring::Publishable
Defined in:
lib/mongo/cluster.rb,
lib/mongo/cluster/topology.rb,
lib/mongo/cluster/topology.rb,
lib/mongo/cluster/sdam_flow.rb,
lib/mongo/cluster/topology/base.rb,
lib/mongo/cluster/topology/single.rb,
lib/mongo/cluster/topology/sharded.rb,
lib/mongo/cluster/topology/unknown.rb,
lib/mongo/cluster/periodic_executor.rb,
lib/mongo/cluster/reapers/cursor_reaper.rb,
lib/mongo/cluster/reapers/socket_reaper.rb,
lib/mongo/cluster/topology/no_replica_set_options.rb,
lib/mongo/cluster/topology/replica_set_no_primary.rb,
lib/mongo/cluster/topology/replica_set_with_primary.rb

Overview

Copyright © 2018-2020 MongoDB Inc.

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Defined Under Namespace

Modules: Topology Classes: CursorReaper, PeriodicExecutor, SdamFlow, SocketReaper

Constant Summary collapse

MAX_READ_RETRIES =

The default number of legacy read retries.

Since:

  • 2.1.1

1
MAX_WRITE_RETRIES =

The default number of legacy write retries.

Since:

  • 2.4.2

1
READ_RETRY_INTERVAL =

The default read retry interval, in seconds, when using legacy read retries.

Since:

  • 2.1.1

5
IDLE_WRITE_PERIOD_SECONDS =

How often an idle primary writes a no-op to the oplog.

Since:

  • 2.4.0

10
CLUSTER_TIME =
Deprecated.

The cluster time key in responses from mongos servers.

Since:

  • 2.5.0

'clusterTime'.freeze

Constants included from Loggable

Loggable::PREFIX

Instance Attribute Summary collapse

Attributes included from Mongo::ClusterTime::Consumer

#cluster_time

Attributes included from Event::Subscriber

#event_listeners

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Mongo::ClusterTime::Consumer

#advance_cluster_time

Methods included from Loggable

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

Methods included from Event::Subscriber

#subscribe_to

Methods included from Monitoring::Publishable

#publish_cmap_event, #publish_event, #publish_sdam_event

Constructor Details

#initialize(seeds, monitoring, options = Options::Redacted.new) ⇒ Cluster

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:

Cluster should never be directly instantiated outside of a Client.

Note:

When connecting to a mongodb+srv:// URI, the client expands such a URI into a list of servers and passes that list to the Cluster constructor. When connecting to a standalone mongod, the Cluster constructor receives the corresponding address as an array of one string.

Instantiate the new cluster.

Examples:

Instantiate the cluster.

Mongo::Cluster.new(["127.0.0.1:27017"], monitoring)

Parameters:

  • seeds (Array<String>)

    The addresses of the configured servers

  • monitoring (Monitoring)

    The monitoring.

  • options (Hash) (defaults to: Options::Redacted.new)

    Options. Client constructor forwards its options to Cluster constructor, although Cluster recognizes only a subset of the options recognized by Client.

Options Hash (options):

  • :direct_connection (true | false)

    Whether to connect directly to the specified seed, bypassing topology discovery. Exactly one seed must be provided.

  • :connect (Symbol)

    Deprecated - use :direct_connection option instead of this option. The connection method to use. This forces the cluster to behave in the specified way instead of auto-discovering. One of :direct, :replica_set, :sharded

  • :replica_set (Symbol)

    The name of the replica set to connect to. Servers not in this replica set will be ignored.

  • :scan (true | false)

    Whether to scan all seeds in constructor. The default in driver version 2.x is to do so; driver version 3.x will not scan seeds in constructor. Opt in to the new behavior by setting this option to false. Note: setting this option to nil enables scanning seeds in constructor in driver version 2.x. Driver version 3.x will recognize this option but will ignore it and will never scan seeds in the constructor.

  • :monitoring_io (true | false)

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

  • :cleanup (true | false)

    For internal driver use only. Set to false to prevent endSessions command being sent to the server to clean up server sessions when the cluster is disconnected, and to to not start the periodic executor. If :monitoring_io is false, :cleanup automatically defaults to false as well.

  • :heartbeat_frequency (Float)

    The interval, in seconds, for the server monitor to refresh its description via ismaster.

  • :resolv_options (Hash)

    For internal driver use only. Options to pass through to Resolv::DNS constructor for SRV lookups.

Since:

  • 2.0.0



112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/mongo/cluster.rb', line 112

def initialize(seeds, monitoring, options = Options::Redacted.new)
  if seeds.nil?
    raise ArgumentError, 'Seeds cannot be nil'
  end

  options = options.dup
  if options[:monitoring_io] == false && !options.key?(:cleanup)
    options[:cleanup] = false
  end
  @options = options.freeze

  # @update_lock covers @servers, @connecting, @connected, @topology and
  # @sessions_supported. Generally instance variables that do not have a
  # designated for them lock should only be modified under the update lock.
  # Note that topology change is locked by @update_lock and not by
  # @sdam_flow_lock.
  @update_lock = Mutex.new
  @servers = []
  @monitoring = monitoring
  @event_listeners = Event::Listeners.new
   = Server::.new(@options)
  @cluster_time_lock = Mutex.new
  @cluster_time = nil
  @srv_monitor_lock = Mutex.new
  @srv_monitor = nil
  @server_selection_semaphore = Semaphore.new
  @topology = Topology.initial(self, monitoring, options)
  # State change lock is similar to the sdam flow lock, but is designed
  # to serialize state changes initated by consumers of Cluster
  # (e.g. application connecting or disconnecting the cluster), so that
  # e.g. an application calling disconnect-connect-disconnect rapidly
  # does not put the cluster into an inconsistent state.
  # Monitoring updates performed internally by the driver do not take
  # the state change lock.
  @state_change_lock = Mutex.new
  # @sdam_flow_lock covers just the sdam flow. Note it does not apply
  # to @topology replacements which are done under @update_lock.
  @sdam_flow_lock = Mutex.new
  Session::SessionPool.create(self)

  # The opening topology is always unknown with no servers.
  # https://github.com/mongodb/specifications/pull/388
  opening_topology = Topology::Unknown.new(options, monitoring, self)

  publish_sdam_event(
    Monitoring::TOPOLOGY_OPENING,
    Monitoring::Event::TopologyOpening.new(opening_topology)
  )

  @seeds = seeds = seeds.uniq
  servers = seeds.map do |seed|
    # Server opening events must be sent after topology change events.
    # Therefore separate server addition, done here before topoolgy change
    # event is published, from starting to monitor the server which is
    # done later.
    add(seed, monitor: false)
  end

  if seeds.size >= 1
    # Recreate the topology to get the current server list into it
    @topology = topology.class.new(topology.options, topology.monitoring, self)
    publish_sdam_event(
      Monitoring::TOPOLOGY_CHANGED,
      Monitoring::Event::TopologyChanged.new(opening_topology, @topology)
    )
  end

  if options[:monitoring_io] == false
    # Omit periodic executor construction, because without servers
    # no commands can be sent to the cluster and there shouldn't ever
    # be anything that needs to be cleaned up.
    #
    # Omit monitoring individual servers and the legacy single round of
    # of SDAM on the main thread, as it would race with tests that mock
    # SDAM responses.
    @connecting = @connected = false
    return
  end

  # Update instance variables prior to starting monitoring threads.
  @connecting = false
  @connected = true

  if options[:cleanup] != false
    @cursor_reaper = CursorReaper.new
    @socket_reaper = SocketReaper.new(self)
    @periodic_executor = PeriodicExecutor.new([
      @cursor_reaper, @socket_reaper,
    ], options)

    ObjectSpace.define_finalizer(self, self.class.finalize(
      {}, @periodic_executor, @session_pool))

    @periodic_executor.run!
  end

  # Need to record start time prior to starting monitoring
  start_time = Time.now

  servers.each do |server|
    server.start_monitoring
  end

  if options[:scan] != false
    server_selection_timeout = options[:server_selection_timeout] || ServerSelector::SERVER_SELECTION_TIMEOUT
    # The server selection timeout can be very short especially in
    # tests, when the client waits for a synchronous scan before
    # starting server selection. Limiting the scan to server selection time
    # then aborts the scan before it can process even local servers.
    # Therefore, allow at least 3 seconds for the scan here.
    if server_selection_timeout < 3
      server_selection_timeout = 3
    end
    deadline = start_time + server_selection_timeout
    # Wait for the first scan of each server to complete, for
    # backwards compatibility.
    # If any servers are discovered during this SDAM round we are going to
    # wait for these servers to also be queried, and so on, up to the
    # server selection timeout or the 3 second minimum.
    loop do
      # Ensure we do not try to read the servers list while SDAM is running
      servers = @sdam_flow_lock.synchronize do
        servers_list.dup
      end
      if servers.all? { |server| server.last_scan && server.last_scan >= start_time }
        break
      end
      if (time_remaining = deadline - Time.now) <= 0
        break
      end
      log_debug("Waiting for up to #{'%.2f' % time_remaining} seconds for servers to be scanned: #{summary}")
      # Since the semaphore may have been signaled between us checking
      # the servers list above and the wait call below, we should not
      # wait for the full remaining time - wait for up to 1 second, then
      # recheck the state.
      server_selection_semaphore.wait([time_remaining, 1].min)
    end
  end

  start_stop_srv_monitor
end

Instance Attribute Details

#app_metadataMongo::Server::AppMetadata (readonly)

Returns The application metadata, used for connection handshakes.

Returns:

Since:

  • 2.4.0



289
290
291
# File 'lib/mongo/cluster.rb', line 289

def 
  
end

#monitoringMonitoring (readonly)

Returns monitoring The monitoring.

Returns:

Since:

  • 2.0.0



280
281
282
# File 'lib/mongo/cluster.rb', line 280

def monitoring
  @monitoring
end

#optionsHash (readonly)

Returns The options hash.

Returns:

  • (Hash)

    The options hash.

Since:

  • 2.0.0



277
278
279
# File 'lib/mongo/cluster.rb', line 277

def options
  @options
end

#seedsArray<String> (readonly)

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.

Returns The addresses of seed servers. Contains addresses that were given to Cluster when it was instantiated, not current addresses that the cluster is using as a result of SDAM.

Returns:

  • (Array<String>)

    The addresses of seed servers. Contains addresses that were given to Cluster when it was instantiated, not current addresses that the cluster is using as a result of SDAM.

Since:

  • 2.7.0



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

def seeds
  @seeds
end

#server_selection_semaphoreObject (readonly)

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



446
447
448
# File 'lib/mongo/cluster.rb', line 446

def server_selection_semaphore
  @server_selection_semaphore
end

#session_poolObject (readonly)

Since:

  • 2.5.1



302
303
304
# File 'lib/mongo/cluster.rb', line 302

def session_pool
  @session_pool
end

#srv_monitorObject (readonly)

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



316
317
318
# File 'lib/mongo/cluster.rb', line 316

def srv_monitor
  @srv_monitor
end

#topologyInteger? (readonly)

The logical session timeout value in minutes.

Examples:

Get the logical session timeout in minutes.

cluster.logical_session_timeout

Returns:

  • (Integer, nil)

    The logical session timeout.

Since:

  • 2.5.0



283
284
285
# File 'lib/mongo/cluster.rb', line 283

def topology
  @topology
end

Class Method Details

.create(client) ⇒ Cluster

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.

Create a cluster for the provided client, for use when we don’t want the client’s original cluster instance to be the same.

Examples:

Create a cluster for the client.

Cluster.create(client)

Parameters:

  • client (Client)

    The client to create on.

Returns:

Since:

  • 2.0.0



267
268
269
270
271
272
273
274
# File 'lib/mongo/cluster.rb', line 267

def self.create(client)
  cluster = Cluster.new(
    client.cluster.addresses.map(&:to_s),
    Monitoring.new,
    client.cluster_options,
  )
  client.instance_variable_set(:@cluster, cluster)
end

.finalize(pools, periodic_executor, session_pool) ⇒ Proc

Finalize the cluster for garbage collection.

Examples:

Finalize the cluster.

Cluster.finalize(pools)

Parameters:

Returns:

  • (Proc)

    The Finalizer.

Since:

  • 2.2.0



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

def self.finalize(pools, periodic_executor, session_pool)
  proc do
    session_pool.end_sessions
    periodic_executor.stop!
  end
end

Instance Method Details

#==(other) ⇒ true, false

Determine if this cluster of servers is equal to another object. Checks the servers currently in the cluster, not what was configured.

Examples:

Is the cluster equal to the object?

cluster == other

Parameters:

  • other (Object)

    The object to compare to.

Returns:

  • (true, false)

    If the objects are equal.

Since:

  • 2.0.0



686
687
688
689
# File 'lib/mongo/cluster.rb', line 686

def ==(other)
  return false unless other.is_a?(Cluster)
  addresses == other.addresses && options == other.options
end

#add(host, add_options = nil) ⇒ Server

Add a server to the cluster with the provided address. Useful in auto-discovery of new servers when an existing server executes an ismaster and potentially non-configured servers were included.

Examples:

Add the server for the address to the cluster.

cluster.add('127.0.0.1:27018')

Parameters:

  • host (String)

    The address of the server to add.

  • options (Hash)

    a customizable set of options

Returns:

  • (Server)

    The newly added server, if not present already.

Since:

  • 2.0.0



784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
# File 'lib/mongo/cluster.rb', line 784

def add(host, add_options=nil)
  address = Address.new(host, options)
  if !addresses.include?(address)
    server = Server.new(address, self, @monitoring, event_listeners, options.merge(
      monitor: false))
    @update_lock.synchronize do
      # Need to recheck whether server is present in @servers, because
      # the previous check was not under a lock.
      # Since we are under the update lock here, we cannot call servers_list.
      return if @servers.map(&:address).include?(address)

      @servers.push(server)
    end
    if add_options.nil? || add_options[:monitor] != false
      server.start_monitoring
    end
    server
  end
end

#addressesArray<Mongo::Address>

The addresses in the cluster.

Examples:

Get the addresses in the cluster.

cluster.addresses

Returns:

Since:

  • 2.0.6



409
410
411
# File 'lib/mongo/cluster.rb', line 409

def addresses
  servers_list.map(&:address)
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 cluster object is connected to its cluster.

Returns:

  • (true|false)

    Whether the cluster is connected.

Since:

  • 2.7.0



382
383
384
385
386
# File 'lib/mongo/cluster.rb', line 382

def connected?
  @update_lock.synchronize do
    !!@connected
  end
end

#connecting?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 cluster object is in the process of connecting to its cluster.

Returns:

  • (true|false)

    Whether the cluster is connecting.

Since:

  • 2.0.0



370
371
372
373
374
# File 'lib/mongo/cluster.rb', line 370

def connecting?
  @update_lock.synchronize do
    !!@connecting
  end
end

#disconnect!true

Note:

Applications should call Client#close to disconnect from

Closes the cluster.

the cluster rather than calling this method. This method is for internal driver use only.

Disconnects all servers in the cluster, publishing appropriate SDAM events in the process. Stops SRV monitoring if it is active. Marks the cluster disconnected.

Returns:

  • (true)

    Always true.

Since:

  • 2.1.0



480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
# File 'lib/mongo/cluster.rb', line 480

def disconnect!
  @state_change_lock.synchronize do
    unless connecting? || connected?
      return true
    end
    if options[:cleanup] != false
      session_pool.end_sessions
      @periodic_executor.stop!
    end
    @srv_monitor_lock.synchronize do
      if @srv_monitor
        @srv_monitor.stop!
      end
    end
    @servers.each do |server|
      if server.connected?
        server.disconnect!
        publish_sdam_event(
          Monitoring::SERVER_CLOSED,
          Monitoring::Event::ServerClosed.new(server.address, topology)
        )
      end
    end
    publish_sdam_event(
      Monitoring::TOPOLOGY_CLOSED,
      Monitoring::Event::TopologyClosed.new(topology)
    )
    @update_lock.synchronize do
      @connecting = @connected = false
    end
  end
  true
end

#disconnect_server_if_connected(server) ⇒ 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



882
883
884
885
886
887
888
889
890
# File 'lib/mongo/cluster.rb', line 882

def disconnect_server_if_connected(server)
  if server.connected?
    server.disconnect!
    publish_sdam_event(
      Monitoring::SERVER_CLOSED,
      Monitoring::Event::ServerClosed.new(server.address, topology)
    )
  end
end

#has_readable_server?(server_selector = nil) ⇒ true, false

Determine if the cluster would select a readable server for the provided read preference.

Examples:

Is a readable server present?

topology.has_readable_server?(server_selector)

Parameters:

  • server_selector (ServerSelector) (defaults to: nil)

    The server selector.

Returns:

  • (true, false)

    If a readable server is present.

Since:

  • 2.4.0



703
704
705
# File 'lib/mongo/cluster.rb', line 703

def has_readable_server?(server_selector = nil)
  topology.has_readable_server?(self, server_selector)
end

#has_writable_server?true, false

Determine if the cluster would select a writable server.

Examples:

Is a writable server present?

topology.has_writable_server?

Returns:

  • (true, false)

    If a writable server is present.

Since:

  • 2.4.0



715
716
717
# File 'lib/mongo/cluster.rb', line 715

def has_writable_server?
  topology.has_writable_server?(self)
end

#heartbeat_intervalFloat

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.

Get the refresh interval for the server. This will be defined via an option or will default to 10.

Returns:

  • (Float)

    The heartbeat interval, in seconds.

Since:

  • 2.10.0



361
362
363
# File 'lib/mongo/cluster.rb', line 361

def heartbeat_interval
  options[:heartbeat_frequency] || Server::Monitor::DEFAULT_HEARTBEAT_INTERVAL
end

#inspectString

Get the nicer formatted string for use in inspection.

Examples:

Inspect the cluster.

cluster.inspect

Returns:

  • (String)

    The cluster inspection.

Since:

  • 2.0.0



431
432
433
# File 'lib/mongo/cluster.rb', line 431

def inspect
  "#<Mongo::Cluster:0x#{object_id} servers=#{servers} topology=#{topology.summary}>"
end

#max_read_retriesInteger

Deprecated.
Note:

max_read_retries should be retrieved from the Client instance, not from a Cluster instance, because clusters may be shared between clients with different values for max read retries.

Get the maximum number of times the client can retry a read operation when using legacy read retries.

Examples:

Get the max read retries.

cluster.max_read_retries

Returns:

  • (Integer)

    The maximum number of retries.

Since:

  • 2.1.1



332
333
334
# File 'lib/mongo/cluster.rb', line 332

def max_read_retries
  options[:max_read_retries] || MAX_READ_RETRIES
end

#next_primary(ping = nil, session = nil) ⇒ Mongo::Server

Get the next primary server we can send an operation to.

Examples:

Get the next primary server.

cluster.next_primary

Parameters:

  • ping (true, false) (defaults to: nil)

    Whether to ping the server before selection. Deprecated and ignored.

  • session (Session | nil) (defaults to: nil)

    Optional session to take into account for mongos pinning.

Returns:

Since:

  • 2.0.0



732
733
734
# File 'lib/mongo/cluster.rb', line 732

def next_primary(ping = nil, session = nil)
  ServerSelector.primary.select_server(self, nil, session)
end

#pool(server) ⇒ Server::ConnectionPool

Deprecated.

Get the connection pool for the server.

Examples:

Get the connection pool.

cluster.pool(server)

Parameters:

  • server (Server)

    The server.

Returns:

Since:

  • 2.2.0



747
748
749
# File 'lib/mongo/cluster.rb', line 747

def pool(server)
  server.pool
end

#read_retry_intervalFloat

Deprecated.
Note:

read_retry_interval should be retrieved from the Client instance, not from a Cluster instance, because clusters may be shared between clients with different values for the read retry interval.

Get the interval, in seconds, in which read retries when using legacy read retries.

Examples:

Get the read retry interval.

cluster.read_retry_interval

Returns:

  • (Float)

    The interval.

Since:

  • 2.1.1



350
351
352
# File 'lib/mongo/cluster.rb', line 350

def read_retry_interval
  options[:read_retry_interval] || READ_RETRY_INTERVAL
end

#reconnect!true

Deprecated.

Use Client#reconnect to reconnect to the cluster instead of calling this method. This method does not send SDAM events.

Reconnect all servers.

Examples:

Reconnect the cluster’s servers.

cluster.reconnect!

Returns:

  • (true)

    Always true.

Since:

  • 2.1.0



524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
# File 'lib/mongo/cluster.rb', line 524

def reconnect!
  @state_change_lock.synchronize do
    @update_lock.synchronize do
      @connecting = true
    end
    scan!
    servers.each do |server|
      server.reconnect!
    end
    @periodic_executor.restart!
    @srv_monitor_lock.synchronize do
      if @srv_monitor
        @srv_monitor.run!
      end
    end
    @update_lock.synchronize do
      @connecting = false
      @connected = true
    end
  end
end

#remove(host, disconnect: true) ⇒ Array<Server> | true | false

Note:

The return value of this method is not part of the driver’s public API.

Remove the server from the cluster for the provided address, if it exists.

Examples:

Remove the server from the cluster.

server.remove('127.0.0.1:27017')

Parameters:

  • host (String)

    The host/port or socket address.

  • disconnect (true | false) (defaults to: true)

    Whether to disconnect the servers being removed. For internal driver use only.

Returns:

  • (Array<Server> | true | false)

    If disconnect is any value other than false, including nil, returns whether any servers were removed. If disconnect is false, returns an array of servers that were removed (and should be disconnected by the caller).

Since:

  • 2.0.0



823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
# File 'lib/mongo/cluster.rb', line 823

def remove(host, disconnect: true)
  address = Address.new(host)
  removed_servers = []
  @update_lock.synchronize do
    @servers.delete_if do |server|
      (server.address == address).tap do |delete|
        if delete
          removed_servers << server
        end
      end
    end
  end
  if disconnect != false
    removed_servers.each do |server|
      disconnect_server_if_connected(server)
    end
  end
  if disconnect != false
    removed_servers.any?
  else
    removed_servers
  end
end

#run_sdam_flow(previous_desc, updated_desc, options = {}) ⇒ 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.

Runs SDAM flow on the cluster.

This method can be invoked to process a new server description returned by the server on a monitoring or non-monitoring connection, and also by the driver when it marks a server unknown as a result of a (network) error.

Parameters:

  • previous_desc (Server::Description)

    Previous server description.

  • updated_desc (Server::Description)

    The changed description.

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

    Options.

  • aptions (Hash)

    a customizable set of options

Options Hash (options):

  • :keep_connection_pool (true | false)

    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.0.0



606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
# File 'lib/mongo/cluster.rb', line 606

def run_sdam_flow(previous_desc, updated_desc, options = {})
  @sdam_flow_lock.synchronize do
    flow = SdamFlow.new(self, previous_desc, updated_desc,
      awaited: options[:awaited])
    flow.server_description_changed

    # SDAM flow may alter the updated description - grab the final
    # version for the purposes of broadcasting if a server is available
    updated_desc = flow.updated_desc

    unless options[:keep_connection_pool]
      if flow.became_unknown?
        servers_list.each do |server|
          if server.address == updated_desc.address
            server.clear_connection_pool
          end
        end
      end
    end

    start_stop_srv_monitor
  end

  # Some updated descriptions, e.g. a mismatched me one, result in the
  # server whose description we are processing being removed from
  # the topology. When this happens, the server's monitoring thread gets
  # killed. As a result, any code after the flow invocation may not run
  # a particular monitor instance, hence there should generally not be
  # any code in this method past the flow invocation.
  #
  # However, this broadcast call can be here because if the monitoring
  # thread got killed the server should have been closed and no client
  # should be currently waiting for it, thus not signaling the semaphore
  # shouldn't cause any problems.
  unless updated_desc.unknown?
    server_selection_semaphore.broadcast
  end
end

#scan!(sync = true) ⇒ true

Note:

In both synchronous and asynchronous scans, each monitor thread maintains a minimum interval between scans, meaning calling this method may not initiate a scan on a particular server the very next instant.

Force a scan of all known servers in the cluster.

If the sync parameter is true which is the default, the scan is performed synchronously in the thread which called this method. Each server in the cluster is checked sequentially. If there are many servers in the cluster or they are slow to respond, this can be a long running operation.

If the sync parameter is false, this method instructs all server monitor threads to perform an immediate scan and returns without waiting for scan results.

Examples:

Force a full cluster scan.

cluster.scan!

Returns:

  • (true)

    Always true.

Since:

  • 2.0.0



569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
# File 'lib/mongo/cluster.rb', line 569

def scan!(sync=true)
  if sync
    servers_list.each do |server|
      if server.monitor
        server.monitor.scan!
      else
        log_warn("Synchronous scan requested on cluster #{summary} but server #{server} has no monitor")
      end
    end
  else
    servers_list.each do |server|
      server.scan_semaphore.signal
    end
  end
  true
end

#serversArray<Server>

Get a list of server candidates from the cluster that can have operations executed on them.

Examples:

Get the server candidates for an operation.

cluster.servers

Returns:

  • (Array<Server>)

    The candidate servers.

Since:

  • 2.0.0



397
398
399
# File 'lib/mongo/cluster.rb', line 397

def servers
  topology.servers(servers_list)
end

#servers_listObject

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



875
876
877
878
879
# File 'lib/mongo/cluster.rb', line 875

def servers_list
  @update_lock.synchronize do
    @servers.dup
  end
end

#set_server_list(server_address_strs) ⇒ 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.

Sets the list of servers to the addresses in the provided list of address strings.

This method is called by the SRV monitor after receiving new DNS records for the monitored hostname.

Removes servers in the cluster whose addresses are not in the passed list of server addresses, and adds servers for any addresses in the argument which are not already in the cluster.

Parameters:

  • server_address_strs (Array<String>)

    List of server addresses to sync the cluster servers to.

Since:

  • 2.0.0



659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
# File 'lib/mongo/cluster.rb', line 659

def set_server_list(server_address_strs)
  @sdam_flow_lock.synchronize do
    server_address_strs.each do |address_str|
      unless servers_list.any? { |server| server.address.seed == address_str }
        add(address_str)
      end
    end

    servers_list.each do |server|
      unless server_address_strs.any? { |address_str| server.address.seed == address_str }
        remove(server.address.seed)
      end
    end
  end
end

#summaryObject

Note:

This method is experimental and subject to change.

Since:

  • 2.7.0



439
440
441
442
443
# File 'lib/mongo/cluster.rb', line 439

def summary
  "#<Cluster " +
  "topology=#{topology.summary} "+
  "servers=[#{servers_list.map(&:summary).join(',')}]>"
end

#update_cluster_time(result) ⇒ Object

Update the max cluster time seen in a response.

Examples:

Update the cluster time.

cluster.update_cluster_time(result)

Parameters:

Returns:

  • (Object)

    The cluster time.

Since:

  • 2.5.0



761
762
763
764
765
766
767
# File 'lib/mongo/cluster.rb', line 761

def update_cluster_time(result)
  if cluster_time_doc = result.cluster_time
    @cluster_time_lock.synchronize do
      advance_cluster_time(cluster_time_doc)
    end
  end
end

#update_topology(new_topology) ⇒ 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



848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
# File 'lib/mongo/cluster.rb', line 848

def update_topology(new_topology)
  old_topology = nil
  @update_lock.synchronize do
    old_topology = topology
    @topology = new_topology
  end

  # If new topology has data bearing servers, we know for sure whether
  # sessions are supported - update our cached value.
  # If new topology has no data bearing servers, leave the old value
  # as it is and sessions_supported? method will perform server selection
  # to try to determine session support accurately, falling back to the
  # last known value.
  if topology.data_bearing_servers?
    sessions_supported = !!topology.logical_session_timeout
    @update_lock.synchronize do
      @sessions_supported = sessions_supported
    end
  end

  publish_sdam_event(
    Monitoring::TOPOLOGY_CHANGED,
    Monitoring::Event::TopologyChanged.new(old_topology, topology)
  )
end

#validate_session_support!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.

Raises Error::SessionsNotAvailable if the deployment that the driver is connected to does not support sessions.

Session support may change over time, for example due to servers in the deployment being upgraded or downgraded. If the client is currently not connected to any data bearing servers, this method considers the state of session support as of when the client was last connected to at least one server. If the client has never connected to any servers, the deployment is considered to not support sessions.

Since:

  • 2.0.0



903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
# File 'lib/mongo/cluster.rb', line 903

def validate_session_support!
  @state_change_lock.synchronize do
    @sdam_flow_lock.synchronize do
      if topology.data_bearing_servers?
        unless topology.logical_session_timeout
          raise_sessions_not_supported
        end
      end
    end
  end

  # No data bearing servers known - perform server selection to try to
  # get a response from at least one of them, to return an accurate
  # assessment of whether sessions are currently supported.
  begin
    ServerSelector.get(mode: :primary_preferred).select_server(self)
    @state_change_lock.synchronize do
      @sdam_flow_lock.synchronize do
        unless topology.logical_session_timeout
          raise_sessions_not_supported
        end
      end
    end
  rescue Error::NoServerAvailable
    # We haven't been able to contact any servers - use last known
    # value for session support.
    @state_change_lock.synchronize do
      @sdam_flow_lock.synchronize do
        @update_lock.synchronize do
          unless @sessions_supported
            raise_sessions_not_supported
          end
        end
      end
    end
  end
end