Class: Moped::Cluster

Inherits:
Object show all
Defined in:
lib/moped/cluster.rb

Overview

The cluster represents a cluster of MongoDB server nodes, either a single node, a replica set, or a mongos server.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(hosts, options) ⇒ Cluster

Initialize the new cluster.

Examples:

Initialize the cluster.

Cluster.new([ "localhost:27017" ], down_interval: 20)

Parameters:

  • options (Hash)

    The cluster options.

Options Hash (options):

  • :down_interval (Object)

    number of seconds to wait before attempting to reconnect to a down node. (30)

  • :refresh_interval (Object)

    number of seconds to cache information about a node. (300)

Since:

  • 1.0.0



46
47
48
49
50
51
52
53
54
# File 'lib/moped/cluster.rb', line 46

def initialize(hosts, options)
  @options = {
    down_interval: 30,
    refresh_interval: 300
  }.merge(options)

  @seeds = hosts
  @nodes = hosts.map { |host| Node.new(host) }
end

Instance Attribute Details

#seedsObject (readonly)

Returns the value of attribute seeds.



8
9
10
# File 'lib/moped/cluster.rb', line 8

def seeds
  @seeds
end

#seeds The seeds the cluster was initialized with.(Theseedstheclusterwasinitializedwith.) ⇒ Object (readonly)



8
# File 'lib/moped/cluster.rb', line 8

attr_reader :seeds

Instance Method Details

#authHash

Get the authentication details for the cluster.

Examples:

Get the authentication details.

cluster.auth

Returns:

  • (Hash)

    the cached authentication credentials for this cluster.

Since:

  • 1.0.0



18
19
20
# File 'lib/moped/cluster.rb', line 18

def auth
  @auth ||= {}
end

#disconnecttrue

Disconnects all nodes in the cluster. This should only be used in cases where you know you’re not going to use the cluster on the thread anymore and need to force the connections to close.

Returns:

  • (true)

    True if the disconnect succeeded.

Since:

  • 1.2.0



29
30
31
# File 'lib/moped/cluster.rb', line 29

def disconnect
  nodes.each { |node| node.disconnect } and true
end

#inspectObject



211
212
213
# File 'lib/moped/cluster.rb', line 211

def inspect
  "<#{self.class.name} nodes=#{@nodes.inspect}>"
end

#nodesArray<Node>

Returns the list of available nodes, refreshing 1) any nodes which were down and ready to be checked again and 2) any nodes whose information is out of date. Arbiter nodes are not returned.

Examples:

Get the available nodes.

cluster.nodes

Returns:

  • (Array<Node>)

    the list of available nodes.

Since:

  • 1.0.0



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/moped/cluster.rb', line 66

def nodes
  current_time = Time.new
  down_boundary = current_time - @options[:down_interval]
  refresh_boundary = current_time - @options[:refresh_interval]

  # Find the nodes that were down but are ready to be refreshed, or those
  # with stale connection information.
  needs_refresh, available = @nodes.partition do |node|
    (node.down? && node.down_at < down_boundary) || node.needs_refresh?(refresh_boundary)
  end

  # Refresh those nodes.
  available.concat refresh(needs_refresh)

  # Now return all the nodes that are available and participating in the
  # replica set.
  available.reject { |node| node.down? || node.arbiter? }
end

#refresh(nodes_to_refresh = @nodes) ⇒ Array<Node>

Refreshes information for each of the nodes provided. The node list defaults to the list of all known nodes.

If a node is successfully refreshed, any newly discovered peers will also be refreshed.

Examples:

Refresh the nodes.

cluster.refresh

Parameters:

  • nodes_to_refresh (Array<Node>) (defaults to: @nodes)

    The nodes to refresh.

Returns:

Since:

  • 1.0.0



99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'lib/moped/cluster.rb', line 99

def refresh(nodes_to_refresh = @nodes)
  refreshed_nodes = []
  seen = {}

  # Set up a recursive lambda function for refreshing a node and it's peers.
  refresh_node = ->(node) do
    unless seen[node]
      seen[node] = true

      # Add the node to the global list of known nodes.
      @nodes << node unless @nodes.include?(node)

      begin
        node.refresh

        # This node is good, so add it to the list of nodes to return.
        refreshed_nodes << node unless refreshed_nodes.include?(node)

        # Now refresh any newly discovered peer nodes.
        (node.peers - @nodes).each(&refresh_node)
      rescue Errors::ConnectionFailure
        # We couldn't connect to the node, so don't do anything with it.
      end
    end
  end

  nodes_to_refresh.each(&refresh_node)
  refreshed_nodes.to_a
end

#with_primary(retry_on_failure = true, &block) ⇒ Object

Yields the replica set’s primary node to the provided block. This method will retry the block in case of connection errors or replica set reconfiguration.

Examples:

Yield the primary to the block.

cluster.with_primary do |node|
  # ...
end

Parameters:

  • retry_on_failure (true, false) (defaults to: true)

    Whether to retry if an error was raised.

Returns:

  • (Object)

    The result of the yield.

Since:

  • 1.0.0



146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
# File 'lib/moped/cluster.rb', line 146

def with_primary(retry_on_failure = true, &block)
  if node = nodes.find(&:primary?)
    begin
      node.ensure_primary do
        return yield node.apply_auth(auth)
      end
    rescue Errors::ConnectionFailure, Errors::ReplicaSetReconfigured
      # Fall through to the code below if our connection was dropped or the
      # node is no longer the primary.
    end
  end

  if retry_on_failure
    # We couldn't find a primary node, so refresh the list and try again.
    refresh
    with_primary(false, &block)
  else
    raise(
      Errors::ConnectionFailure,
      "Could not connect to a primary node for replica set #{inspect}"
    )
  end
end

#with_secondary(retry_on_failure = true, &block) ⇒ Object

Yields a secondary node if available, otherwise the primary node. This method will retry the block in case of connection errors.

Examples:

Yield the secondary to the block.

cluster.with_secondary do |node|
  # ...
end

Parameters:

  • retry_on_failure (true, false) (defaults to: true)

    Whether to retry if an error was raised.

Returns:

  • (Object)

    The result of the yield.

Since:

  • 1.0.0



186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
# File 'lib/moped/cluster.rb', line 186

def with_secondary(retry_on_failure = true, &block)
  available_nodes = nodes.shuffle!.partition(&:secondary?).flatten

  while node = available_nodes.shift
    begin
      return yield node.apply_auth(auth)
    rescue Errors::ConnectionFailure
      # That node's no good, so let's try the next one.
      next
    end
  end

  if retry_on_failure
    # We couldn't find a secondary or primary node, so refresh the list and
    # try again.
    refresh
    with_secondary(false, &block)
  else
    raise(
      Errors::ConnectionFailure,
      "Could not connect to any secondary or primary nodes for replica set #{inspect}"
    )
  end
end