blob: 71e8cc0baa81f59bc8940a3f2285cdbaab508007 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.search.dispatch.rpc;
import com.google.common.collect.ImmutableMap;
import com.yahoo.search.dispatch.FillInvoker;
import com.yahoo.search.dispatch.rpc.Client.NodeConnection;
import com.yahoo.vespa.config.search.DispatchNodesConfig;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
/**
* RpcResourcePool constructs {@link FillInvoker} objects that communicate with content nodes over RPC. It also contains
* the RPC connection pool.
*
* @author ollivir
*/
public class RpcResourcePool implements RpcConnectionPool, AutoCloseable {
/** Connections to the search nodes this talks to, indexed by node id ("partid") */
private final ImmutableMap<Integer, NodeConnectionPool> nodeConnectionPools;
RpcResourcePool(Map<Integer, NodeConnection> nodeConnections) {
var builder = new ImmutableMap.Builder<Integer, NodeConnectionPool>();
nodeConnections.forEach((key, connection) -> builder.put(key, new NodeConnectionPool(Collections.singletonList(connection))));
this.nodeConnectionPools = builder.build();
}
public RpcResourcePool(RpcClient client, DispatchNodesConfig nodesConfig, int numConnections) {
super();
// Create rpc node connection pools indexed by the node distribution key
var builder = new ImmutableMap.Builder<Integer, NodeConnectionPool>();
for (var node : nodesConfig.node()) {
var connections = new ArrayList<NodeConnection>(numConnections);
for (int i = 0; i < numConnections; i++) {
connections.add(client.createConnection(node.host(), node.port()));
}
builder.put(node.key(), new NodeConnectionPool(connections));
}
this.nodeConnectionPools = builder.build();
}
@Override
public NodeConnection getConnection(int nodeId) {
var pool = nodeConnectionPools.get(nodeId);
if (pool == null) {
return null;
} else {
return pool.nextConnection();
}
}
@Override
public void close() {
nodeConnectionPools.values().forEach(NodeConnectionPool::release);
}
private static class NodeConnectionPool {
private final List<Client.NodeConnection> connections;
NodeConnectionPool(List<NodeConnection> connections) {
this.connections = connections;
}
Client.NodeConnection nextConnection() {
int slot = ThreadLocalRandom.current().nextInt(connections.size());
return connections.get(slot);
}
void release() {
connections.forEach(Client.NodeConnection::close);
}
}
}
|