Skip to content

Commit ca11085

Browse files
authored
Add TcpChannel to unify Transport implementations (#27132)
Right now our different transport implementations must duplicate functionality in order to stay compliant with the requirements of TcpTransport. They must all implement common logic to open channels, close channels, keep track of channels for eventual shutdown, etc. Additionally, there is a weird and complicated relationship between Transport and TransportService. We eventually want to start merging some of the functionality between these classes. This commit starts moving towards a world where TransportService retains all the application logic and channel state. Transport implementations in this world will only be tasked with returning a channel when one is requested, calling transport service when a channel is accepted from a server, and starting / stopping itself. Specifically this commit changes how channels are opened and closed. All Transport implementations now return a channel type that must comply with the new TcpChannel interface. This interface has the methods necessary for TcpTransport to completely manage the lifecycle of a channel. This includes setting the channel up, waiting for connection, adding close listeners, and eventually closing.
1 parent 3c9b919 commit ca11085

37 files changed

+794
-975
lines changed

core/src/main/java/org/elasticsearch/action/ActionListener.java

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424

2525
import java.util.ArrayList;
2626
import java.util.List;
27+
import java.util.function.BiConsumer;
2728
import java.util.function.Consumer;
2829

2930
/**
@@ -69,6 +70,42 @@ public void onFailure(Exception e) {
6970
};
7071
}
7172

73+
/**
74+
* Creates a listener that listens for a response (or failure) and executes the
75+
* corresponding runnable when the response (or failure) is received.
76+
*
77+
* @param runnable the runnable that will be called in event of success or failure
78+
* @param <Response> the type of the response
79+
* @return a listener that listens for responses and invokes the runnable when received
80+
*/
81+
static <Response> ActionListener<Response> wrap(Runnable runnable) {
82+
return wrap(r -> runnable.run(), e -> runnable.run());
83+
}
84+
85+
/**
86+
* Converts a listener to a {@link BiConsumer} for compatibility with the {@link java.util.concurrent.CompletableFuture}
87+
* api.
88+
*
89+
* @param listener that will be wrapped
90+
* @param <Response> the type of the response
91+
* @return a bi consumer that will complete the wrapped listener
92+
*/
93+
static <Response> BiConsumer<Response, Throwable> toBiConsumer(ActionListener<Response> listener) {
94+
return (response, throwable) -> {
95+
if (throwable == null) {
96+
listener.onResponse(response);
97+
} else {
98+
if (throwable instanceof Exception) {
99+
listener.onFailure((Exception) throwable);
100+
} else if (throwable instanceof Error) {
101+
throw (Error) throwable;
102+
} else {
103+
throw new AssertionError("Should have been either Error or Exception", throwable);
104+
}
105+
}
106+
};
107+
}
108+
72109
/**
73110
* Notifies every given listener with the response passed to {@link #onResponse(Object)}. If a listener itself throws an exception
74111
* the exception is forwarded to {@link #onFailure(Exception)}. If in turn {@link #onFailure(Exception)} fails all remaining

core/src/main/java/org/elasticsearch/transport/ConnectionProfile.java

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -208,12 +208,12 @@ private ConnectionTypeHandle(int offset, int length, Set<TransportRequestOptions
208208
* Returns one of the channels out configured for this handle. The channel is selected in a round-robin
209209
* fashion.
210210
*/
211-
<T> T getChannel(T[] channels) {
211+
<T> T getChannel(List<T> channels) {
212212
if (length == 0) {
213213
throw new IllegalStateException("can't select channel size is 0 for types: " + types);
214214
}
215-
assert channels.length >= offset + length : "illegal size: " + channels.length + " expected >= " + (offset + length);
216-
return channels[offset + Math.floorMod(counter.incrementAndGet(), length)];
215+
assert channels.size() >= offset + length : "illegal size: " + channels.size() + " expected >= " + (offset + length);
216+
return channels.get(offset + Math.floorMod(counter.incrementAndGet(), length));
217217
}
218218

219219
/**
@@ -223,5 +223,4 @@ Set<TransportRequestOptions.Type> getTypes() {
223223
return types;
224224
}
225225
}
226-
227226
}
Lines changed: 169 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,169 @@
1+
/*
2+
* Licensed to Elasticsearch under one or more contributor
3+
* license agreements. See the NOTICE file distributed with
4+
* this work for additional information regarding copyright
5+
* ownership. Elasticsearch licenses this file to you under
6+
* the Apache License, Version 2.0 (the "License"); you may
7+
* not use this file except in compliance with the License.
8+
* You may obtain a copy of the License at
9+
*
10+
* http://www.apache.org/licenses/LICENSE-2.0
11+
*
12+
* Unless required by applicable law or agreed to in writing,
13+
* software distributed under the License is distributed on an
14+
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+
* KIND, either express or implied. See the License for the
16+
* specific language governing permissions and limitations
17+
* under the License.
18+
*/
19+
20+
package org.elasticsearch.transport;
21+
22+
import org.apache.logging.log4j.Logger;
23+
import org.apache.logging.log4j.message.ParameterizedMessage;
24+
import org.elasticsearch.action.ActionFuture;
25+
import org.elasticsearch.action.ActionListener;
26+
import org.elasticsearch.action.support.PlainActionFuture;
27+
import org.elasticsearch.cluster.node.DiscoveryNode;
28+
import org.elasticsearch.common.lease.Releasable;
29+
import org.elasticsearch.common.lease.Releasables;
30+
import org.elasticsearch.common.unit.TimeValue;
31+
32+
import java.io.IOException;
33+
import java.util.ArrayList;
34+
import java.util.Collection;
35+
import java.util.Collections;
36+
import java.util.List;
37+
import java.util.concurrent.ExecutionException;
38+
import java.util.concurrent.TimeUnit;
39+
import java.util.concurrent.TimeoutException;
40+
41+
42+
/**
43+
* This is a tcp channel representing a single channel connection to another node. It is the base channel
44+
* abstraction used by the {@link TcpTransport} and {@link TransportService}. All tcp transport
45+
* implementations must return channels that adhere to the required method contracts.
46+
*/
47+
public interface TcpChannel extends Releasable {
48+
49+
/**
50+
* Closes the channel. This might be an asynchronous process. There is notguarantee that the channel
51+
* will be closed when this method returns. Use the {@link #addCloseListener(ActionListener)} method
52+
* to implement logic that depends on knowing when the channel is closed.
53+
*/
54+
void close();
55+
56+
/**
57+
* Adds a listener that will be executed when the channel is closed. If the channel is still open when
58+
* this listener is added, the listener will be executed by the thread that eventually closes the
59+
* channel. If the channel is already closed when the listener is added the listener will immediately be
60+
* executed by the thread that is attempting to add the listener.
61+
*
62+
* @param listener to be executed
63+
*/
64+
void addCloseListener(ActionListener<TcpChannel> listener);
65+
66+
67+
/**
68+
* This sets the low level socket option {@link java.net.StandardSocketOptions} SO_LINGER on a channel.
69+
*
70+
* @param value to set for SO_LINGER
71+
* @throws IOException that can be throw by the low level socket implementation
72+
*/
73+
void setSoLinger(int value) throws IOException;
74+
75+
76+
/**
77+
* Indicates whether a channel is currently open
78+
*
79+
* @return boolean indicating if channel is open
80+
*/
81+
boolean isOpen();
82+
83+
/**
84+
* Closes the channel.
85+
*
86+
* @param channel to close
87+
* @param blocking indicates if we should block on channel close
88+
*/
89+
static <C extends TcpChannel> void closeChannel(C channel, boolean blocking) {
90+
closeChannels(Collections.singletonList(channel), blocking);
91+
}
92+
93+
/**
94+
* Closes the channels.
95+
*
96+
* @param channels to close
97+
* @param blocking indicates if we should block on channel close
98+
*/
99+
static <C extends TcpChannel> void closeChannels(List<C> channels, boolean blocking) {
100+
if (blocking) {
101+
ArrayList<ActionFuture<TcpChannel>> futures = new ArrayList<>(channels.size());
102+
for (final C channel : channels) {
103+
if (channel.isOpen()) {
104+
PlainActionFuture<TcpChannel> closeFuture = PlainActionFuture.newFuture();
105+
channel.addCloseListener(closeFuture);
106+
channel.close();
107+
futures.add(closeFuture);
108+
}
109+
}
110+
blockOnFutures(futures);
111+
} else {
112+
Releasables.close(channels);
113+
}
114+
}
115+
116+
/**
117+
* Awaits for all of the pending connections to complete. Will throw an exception if at least one of the
118+
* connections fails.
119+
*
120+
* @param discoveryNode the node for the pending connections
121+
* @param connectionFutures representing the pending connections
122+
* @param connectTimeout to wait for a connection
123+
* @param <C> the type of channel
124+
* @throws ConnectTransportException if one of the connections fails
125+
*/
126+
static <C extends TcpChannel> void awaitConnected(DiscoveryNode discoveryNode, List<ActionFuture<C>> connectionFutures,
127+
TimeValue connectTimeout) throws ConnectTransportException {
128+
Exception connectionException = null;
129+
boolean allConnected = true;
130+
131+
for (ActionFuture<C> connectionFuture : connectionFutures) {
132+
try {
133+
connectionFuture.get(connectTimeout.getMillis(), TimeUnit.MILLISECONDS);
134+
} catch (TimeoutException e) {
135+
allConnected = false;
136+
break;
137+
} catch (InterruptedException e) {
138+
Thread.currentThread().interrupt();
139+
throw new IllegalStateException(e);
140+
} catch (ExecutionException e) {
141+
allConnected = false;
142+
connectionException = (Exception) e.getCause();
143+
break;
144+
}
145+
}
146+
147+
if (allConnected == false) {
148+
if (connectionException == null) {
149+
throw new ConnectTransportException(discoveryNode, "connect_timeout[" + connectTimeout + "]");
150+
} else {
151+
throw new ConnectTransportException(discoveryNode, "connect_exception", connectionException);
152+
}
153+
}
154+
}
155+
156+
static void blockOnFutures(List<ActionFuture<TcpChannel>> futures) {
157+
for (ActionFuture<TcpChannel> future : futures) {
158+
try {
159+
future.get();
160+
} catch (ExecutionException e) {
161+
// Ignore as we are only interested in waiting for the close process to complete. Logging
162+
// close exceptions happens elsewhere.
163+
} catch (InterruptedException e) {
164+
Thread.currentThread().interrupt();
165+
throw new IllegalStateException("Future got interrupted", e);
166+
}
167+
}
168+
}
169+
}

0 commit comments

Comments
 (0)