-
Notifications
You must be signed in to change notification settings - Fork 2.9k
/
AbstractClient.java
377 lines (342 loc) · 13.2 KB
/
AbstractClient.java
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio;
import alluxio.exception.AlluxioException;
import alluxio.exception.ConnectionFailedException;
import alluxio.exception.ExceptionMessage;
import alluxio.exception.PreconditionMessage;
import alluxio.exception.status.AlluxioStatusException;
import alluxio.exception.status.ExceptionStatus;
import alluxio.retry.ExponentialBackoffRetry;
import alluxio.retry.RetryPolicy;
import alluxio.security.authentication.TransportProvider;
import alluxio.thrift.AlluxioService;
import alluxio.thrift.AlluxioTException;
import com.google.common.base.Preconditions;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TMultiplexedProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TTransportException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.regex.Pattern;
import javax.annotation.concurrent.ThreadSafe;
import javax.security.auth.Subject;
/**
* The base class for clients.
*/
// TODO(peis): Consolidate this to ThriftClientPool.
@ThreadSafe
public abstract class AbstractClient implements Client {
private static final Logger LOG = LoggerFactory.getLogger(AbstractClient.class);
/** The pattern of exception message when client and server transport frame sizes do not match. */
private static final Pattern FRAME_SIZE_EXCEPTION_PATTERN =
Pattern.compile("Frame size \\((\\d+)\\) larger than max length");
private static final int BASE_SLEEP_MS =
Configuration.getInt(PropertyKey.USER_RPC_RETRY_BASE_SLEEP_MS);
private static final int MAX_SLEEP_MS =
Configuration.getInt(PropertyKey.USER_RPC_RETRY_MAX_SLEEP_MS);
/** The number of times to retry a particular RPC. */
protected static final int RPC_MAX_NUM_RETRY =
Configuration.getInt(PropertyKey.USER_RPC_RETRY_MAX_NUM_RETRY);
protected final String mMode;
protected InetSocketAddress mAddress = null;
protected TProtocol mProtocol = null;
/** Is true if this client is currently connected. */
protected boolean mConnected = false;
/**
* Is true if this client was closed by the user. No further actions are possible after the client
* is closed.
*/
protected boolean mClosed = false;
/**
* Stores the service version; used for detecting incompatible client-server pairs.
*/
protected long mServiceVersion;
/** Handler to the transport provider according to the authentication type. */
protected final TransportProvider mTransportProvider;
private final Subject mParentSubject;
/**
* Creates a new client base.
*
* @param subject the parent subject, set to null if not present
* @param address the address
* @param mode the mode of the client for display
*/
public AbstractClient(Subject subject, InetSocketAddress address, String mode) {
mAddress = Preconditions.checkNotNull(address, "address");
mMode = mode;
mServiceVersion = Constants.UNKNOWN_SERVICE_VERSION;
mTransportProvider = TransportProvider.Factory.create();
mParentSubject = subject;
}
/**
* @return a Thrift service client
*/
protected abstract AlluxioService.Client getClient();
/**
* @return a string representing the specific service
*/
protected abstract String getServiceName();
/**
* @return the client service version
*/
protected abstract long getServiceVersion();
/**
* Checks that the service version is compatible with the client.
*
* @param client the service client
* @param version the client version
*/
protected void checkVersion(AlluxioService.Client client, long version) throws IOException {
if (mServiceVersion == Constants.UNKNOWN_SERVICE_VERSION) {
try {
mServiceVersion = client.getServiceVersion();
} catch (TException e) {
throw new IOException(e);
}
if (mServiceVersion != version) {
throw new IOException(ExceptionMessage.INCOMPATIBLE_VERSION.getMessage(getServiceName(),
version, mServiceVersion));
}
}
}
/**
* This method is called after the connection is made to the remote. Implementations should create
* internal state to finish the connection process.
*/
protected void afterConnect() throws IOException {
// Empty implementation.
}
/**
* This method is called after the connection is disconnected. Implementations should clean up any
* additional state created for the connection.
*/
protected void afterDisconnect() {
// Empty implementation.
}
/**
* This method is called before the connection is disconnected. Implementations should add any
* additional operations before the connection is disconnected.
*/
protected void beforeDisconnect() {
// Empty implementation.
}
/**
* Connects with the remote.
*
* @throws IOException if an I/O error occurs
* @throws ConnectionFailedException if network connection failed
*/
public synchronized void connect() throws IOException, ConnectionFailedException {
if (mConnected) {
return;
}
disconnect();
Preconditions.checkState(!mClosed, "Client is closed, will not try to connect.");
RetryPolicy retryPolicy =
new ExponentialBackoffRetry(BASE_SLEEP_MS, MAX_SLEEP_MS, RPC_MAX_NUM_RETRY);
while (!mClosed) {
mAddress = getAddress();
LOG.info("Alluxio client (version {}) is trying to connect with {} {} @ {}",
RuntimeConstants.VERSION, getServiceName(), mMode, mAddress);
TProtocol binaryProtocol =
new TBinaryProtocol(mTransportProvider.getClientTransport(mParentSubject, mAddress));
mProtocol = new TMultiplexedProtocol(binaryProtocol, getServiceName());
try {
mProtocol.getTransport().open();
LOG.info("Client registered with {} {} @ {}", getServiceName(), mMode, mAddress);
mConnected = true;
afterConnect();
checkVersion(getClient(), getServiceVersion());
return;
} catch (IOException e) {
if (e.getMessage() != null && FRAME_SIZE_EXCEPTION_PATTERN.matcher(e.getMessage()).find()) {
// See an error like "Frame size (67108864) larger than max length (16777216)!",
// pointing to the helper page.
String message = String.format("Failed to connect to %s %s @ %s: %s. "
+ "This exception may be caused by incorrect network configuration. "
+ "Please consult %s for common solutions to address this problem.",
getServiceName(), mMode, mAddress, e.getMessage(),
RuntimeConstants.ALLUXIO_DEBUG_DOCS_URL);
throw new IOException(message, e);
}
throw e;
} catch (TTransportException e) {
LOG.warn("Failed to connect ({}) to {} {} @ {}: {}", retryPolicy.getRetryCount(),
getServiceName(), mMode, mAddress, e.getMessage());
if (e.getCause() instanceof java.net.SocketTimeoutException) {
// Do not retry if socket timeout.
String message = "Thrift transport open times out. Please check whether the "
+ "authentication types match between client and server. Note that NOSASL client "
+ "is not able to connect to servers with SIMPLE security mode.";
throw new IOException(message, e);
}
// TODO(peis): Consider closing the connection here as well.
if (!retryPolicy.attemptRetry()) {
break;
}
}
}
// Reaching here indicates that we did not successfully connect.
throw new ConnectionFailedException("Failed to connect to " + getServiceName() + " " + mMode
+ " @ " + mAddress + " after " + (retryPolicy.getRetryCount()) + " attempts");
}
/**
* Closes the connection with the Alluxio remote and does the necessary cleanup. It should be used
* if the client has not connected with the remote for a while, for example.
*/
public synchronized void disconnect() {
if (mConnected) {
Preconditions.checkNotNull(mProtocol, PreconditionMessage.PROTOCOL_NULL_WHEN_CONNECTED);
LOG.debug("Disconnecting from the {} {} {}", getServiceName(), mMode, mAddress);
beforeDisconnect();
mProtocol.getTransport().close();
mConnected = false;
afterDisconnect();
}
}
/**
* @return true if this client is connected to the remote
*/
public synchronized boolean isConnected() {
return mConnected;
}
/**
* Closes the connection with the remote permanently. This instance should be not be reused after
* closing.
*/
@Override
public synchronized void close() {
disconnect();
mClosed = true;
}
/**
* Closes the connection, then queries and sets current remote address.
*/
public synchronized void resetConnection() {
disconnect();
mAddress = getAddress();
}
/**
* @return the {@link InetSocketAddress} of the remote
*/
public synchronized InetSocketAddress getAddress() {
return mAddress;
}
/**
* The RPC to be executed in {@link #retryRPC(RpcCallable)}.
*
* @param <V> the return value of {@link #call()}
*/
protected interface RpcCallable<V> {
/**
* The task where RPC happens.
*
* @return RPC result
* @throws TException when any exception defined in thrift happens
*/
V call() throws TException;
}
/**
* Same with {@link RpcCallable} except that this RPC call throws {@link AlluxioTException} and
* is to be executed in {@link #retryRPC(RpcCallableThrowsAlluxioTException)}.
*
* @param <V> the return value of {@link #call()}
*/
protected interface RpcCallableThrowsAlluxioTException<V> {
/**
* The task where RPC happens.
*
* @return RPC result
* @throws AlluxioTException when any {@link AlluxioException} happens during RPC and is wrapped
* into {@link AlluxioTException}
* @throws TException when any exception defined in thrift happens
*/
V call() throws AlluxioTException, TException;
}
/**
* Tries to execute an RPC defined as a {@link RpcCallable}.
*
* If a non-Alluxio thrift exception occurs, a reconnection will be tried through
* {@link #connect()} and the action will be re-executed.
*
* @param rpc the RPC call to be executed
* @param <V> type of return value of the RPC call
* @return the return value of the RPC call
* @throws IOException when retries exceeds {@link #RPC_MAX_NUM_RETRY} or {@link #close()} has
* been called before calling this method or during the retry
* @throws ConnectionFailedException if network connection failed
*/
protected synchronized <V> V retryRPC(RpcCallable<V> rpc) throws IOException,
ConnectionFailedException {
RetryPolicy retryPolicy =
new ExponentialBackoffRetry(BASE_SLEEP_MS, MAX_SLEEP_MS, RPC_MAX_NUM_RETRY);
while (!mClosed) {
connect();
try {
return rpc.call();
} catch (AlluxioTException e) {
AlluxioStatusException se = AlluxioStatusException.fromThrift(e);
if (se.getStatus() == ExceptionStatus.UNAVAILABLE) {
throw new IOException(e);
}
throw se;
} catch (TException e) {
LOG.error(e.getMessage(), e);
disconnect();
}
if (!retryPolicy.attemptRetry()) {
break;
}
}
throw new IOException("Failed after " + retryPolicy.getRetryCount() + " retries.");
}
/**
* Similar to {@link #retryRPC(RpcCallable)} except that the RPC call may throw
* {@link AlluxioTException} and once it is thrown, it will be transformed into
* {@link AlluxioException} and be thrown.
*
* @param rpc the RPC call to be executed
* @param <V> type of return value of the RPC call
* @return the return value of the RPC call
* @throws AlluxioException when {@link AlluxioTException} is thrown by the RPC call
* @throws IOException when retries exceeds {@link #RPC_MAX_NUM_RETRY} or {@link #close()} has
* been called before calling this method or during the retry
*/
protected synchronized <V> V retryRPC(RpcCallableThrowsAlluxioTException<V> rpc)
throws AlluxioException, IOException {
RetryPolicy retryPolicy =
new ExponentialBackoffRetry(BASE_SLEEP_MS, MAX_SLEEP_MS, RPC_MAX_NUM_RETRY);
while (!mClosed) {
connect();
try {
return rpc.call();
} catch (AlluxioTException e) {
AlluxioStatusException se = AlluxioStatusException.fromThrift(e);
if (se.getStatus() == ExceptionStatus.UNAVAILABLE) {
throw new IOException(e);
}
throw se;
} catch (TException e) {
LOG.error(e.getMessage(), e);
disconnect();
}
if (!retryPolicy.attemptRetry()) {
break;
}
}
throw new IOException("Failed after " + retryPolicy.getRetryCount() + " retries.");
}
}