forked from voldemort/voldemort
/
SocketStore.java
505 lines (443 loc) · 23.1 KB
/
SocketStore.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
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
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
/*
* Copyright 2008-2010 LinkedIn, 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.
*/
package voldemort.store.socket;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import voldemort.VoldemortException;
import voldemort.client.protocol.RequestFormat;
import voldemort.client.protocol.RequestFormatFactory;
import voldemort.server.RequestRoutingType;
import voldemort.store.NoSuchCapabilityException;
import voldemort.store.Store;
import voldemort.store.StoreCapabilityType;
import voldemort.store.StoreTimeoutException;
import voldemort.store.StoreUtils;
import voldemort.store.UnreachableStoreException;
import voldemort.store.nonblockingstore.NonblockingStore;
import voldemort.store.nonblockingstore.NonblockingStoreCallback;
import voldemort.store.socket.clientrequest.BlockingClientRequest;
import voldemort.store.socket.clientrequest.ClientRequest;
import voldemort.store.socket.clientrequest.ClientRequestExecutor;
import voldemort.store.socket.clientrequest.ClientRequestExecutorPool;
import voldemort.store.socket.clientrequest.DeleteClientRequest;
import voldemort.store.socket.clientrequest.GetAllClientRequest;
import voldemort.store.socket.clientrequest.GetClientRequest;
import voldemort.store.socket.clientrequest.GetVersionsClientRequest;
import voldemort.store.socket.clientrequest.PutClientRequest;
import voldemort.utils.ByteArray;
import voldemort.utils.Time;
import voldemort.utils.Utils;
import voldemort.versioning.Version;
import voldemort.versioning.Versioned;
/**
* The client implementation of a socket store--translates each request into a
* network operation to be handled by the socket server on the other side.
*
* <p/>
*
* SocketStore handles both <i>blocking</i> and <i>non-blocking</i> styles of
* requesting. For non-blocking requests, SocketStore checks out a
* {@link ClientRequestExecutor} instance from the
* {@link ClientRequestExecutorPool pool} and adds an appropriate
* {@link ClientRequest request} to be processed by the NIO thread.
*/
public class SocketStore implements Store<ByteArray, byte[], byte[]>, NonblockingStore {
private final RequestFormatFactory requestFormatFactory = new RequestFormatFactory();
private final String storeName;
private final long timeoutMs;
private final ClientRequestExecutorPool pool;
private final SocketDestination destination;
private final RequestFormat requestFormat;
private final RequestRoutingType requestRoutingType;
private final Logger logger = Logger.getLogger(SocketStore.class);
public SocketStore(String storeName,
long timeoutMs,
SocketDestination dest,
ClientRequestExecutorPool pool,
RequestRoutingType requestRoutingType) {
this.storeName = Utils.notNull(storeName);
this.timeoutMs = timeoutMs;
this.pool = Utils.notNull(pool);
this.destination = dest;
this.requestFormat = requestFormatFactory.getRequestFormat(dest.getRequestFormatType());
this.requestRoutingType = requestRoutingType;
}
public void submitDeleteRequest(ByteArray key,
Version version,
NonblockingStoreCallback callback,
long timeoutMs) {
StoreUtils.assertValidKey(key);
DeleteClientRequest clientRequest = new DeleteClientRequest(storeName,
requestFormat,
requestRoutingType,
key,
version);
if(logger.isDebugEnabled())
logger.debug("DELETE keyRef: " + System.identityHashCode(key) + " requestRef: "
+ System.identityHashCode(clientRequest));
requestAsync(clientRequest, callback, timeoutMs, "delete");
}
public void submitGetRequest(ByteArray key,
byte[] transforms,
NonblockingStoreCallback callback,
long timeoutMs) {
StoreUtils.assertValidKey(key);
GetClientRequest clientRequest = new GetClientRequest(storeName,
requestFormat,
requestRoutingType,
key,
transforms);
if(logger.isDebugEnabled())
logger.debug("GET keyRef: " + System.identityHashCode(key) + " requestRef: "
+ System.identityHashCode(clientRequest));
requestAsync(clientRequest, callback, timeoutMs, "get");
}
public void submitGetAllRequest(Iterable<ByteArray> keys,
Map<ByteArray, byte[]> transforms,
NonblockingStoreCallback callback,
long timeoutMs) {
StoreUtils.assertValidKeys(keys);
GetAllClientRequest clientRequest = new GetAllClientRequest(storeName,
requestFormat,
requestRoutingType,
keys,
transforms);
if(logger.isDebugEnabled())
logger.debug("GETALL keyRef: " + System.identityHashCode(keys) + " requestRef: "
+ System.identityHashCode(clientRequest));
requestAsync(clientRequest, callback, timeoutMs, "get all");
}
public void submitGetVersionsRequest(ByteArray key,
NonblockingStoreCallback callback,
long timeoutMs) {
StoreUtils.assertValidKey(key);
GetVersionsClientRequest clientRequest = new GetVersionsClientRequest(storeName,
requestFormat,
requestRoutingType,
key);
if(logger.isDebugEnabled())
logger.debug("GETVERSIONS keyRef: " + System.identityHashCode(key) + " requestRef: "
+ System.identityHashCode(clientRequest));
requestAsync(clientRequest, callback, timeoutMs, "get versions");
}
public void submitPutRequest(ByteArray key,
Versioned<byte[]> value,
byte[] transforms,
NonblockingStoreCallback callback,
long timeoutMs) {
StoreUtils.assertValidKey(key);
PutClientRequest clientRequest = new PutClientRequest(storeName,
requestFormat,
requestRoutingType,
key,
value,
transforms);
if(logger.isDebugEnabled())
logger.debug("PUT keyRef: " + System.identityHashCode(key) + " requestRef: "
+ System.identityHashCode(clientRequest));
requestAsync(clientRequest, callback, timeoutMs, "put");
}
public boolean delete(ByteArray key, Version version) throws VoldemortException {
StoreUtils.assertValidKey(key);
DeleteClientRequest clientRequest = new DeleteClientRequest(storeName,
requestFormat,
requestRoutingType,
key,
version);
if(logger.isDebugEnabled())
logger.debug("DELETE keyRef: " + System.identityHashCode(key) + " requestRef: "
+ System.identityHashCode(clientRequest));
return request(clientRequest, "delete");
}
public List<Versioned<byte[]>> get(ByteArray key, byte[] transforms) throws VoldemortException {
StoreUtils.assertValidKey(key);
GetClientRequest clientRequest = new GetClientRequest(storeName,
requestFormat,
requestRoutingType,
key,
transforms);
if(logger.isDebugEnabled())
logger.debug("GET keyRef: " + System.identityHashCode(key) + " requestRef: "
+ System.identityHashCode(clientRequest));
return request(clientRequest, "get");
}
public Map<ByteArray, List<Versioned<byte[]>>> getAll(Iterable<ByteArray> keys,
Map<ByteArray, byte[]> transforms)
throws VoldemortException {
StoreUtils.assertValidKeys(keys);
GetAllClientRequest clientRequest = new GetAllClientRequest(storeName,
requestFormat,
requestRoutingType,
keys,
transforms);
if(logger.isDebugEnabled())
logger.debug("GETALL keyRef: " + System.identityHashCode(keys) + " requestRef: "
+ System.identityHashCode(clientRequest));
return request(clientRequest, "getAll");
}
public List<Version> getVersions(ByteArray key) {
StoreUtils.assertValidKey(key);
GetVersionsClientRequest clientRequest = new GetVersionsClientRequest(storeName,
requestFormat,
requestRoutingType,
key);
if(logger.isDebugEnabled())
logger.debug("GETVERSIONS keyRef: " + System.identityHashCode(key) + " requestRef: "
+ System.identityHashCode(clientRequest));
return request(clientRequest, "getVersions");
}
public void put(ByteArray key, Versioned<byte[]> versioned, byte[] transforms)
throws VoldemortException {
StoreUtils.assertValidKey(key);
PutClientRequest clientRequest = new PutClientRequest(storeName,
requestFormat,
requestRoutingType,
key,
versioned,
transforms);
if(logger.isDebugEnabled())
logger.debug("PUT keyRef: " + System.identityHashCode(key) + " requestRef: "
+ System.identityHashCode(clientRequest));
request(clientRequest, "put");
}
public Object getCapability(StoreCapabilityType capability) {
if(StoreCapabilityType.SOCKET_POOL.equals(capability))
return this.pool;
else
throw new NoSuchCapabilityException(capability, getName());
}
public String getName() {
return storeName;
}
public void close() throws VoldemortException {
// don't close the socket pool, it is shared
}
/**
* This method handles submitting and then waiting for the request from the
* server. It uses the ClientRequest API to actually write the request and
* then read back the response. This implementation will block for a
* response from the server.
*
* @param <T> Return type
*
* @param clientRequest ClientRequest implementation used to write the
* request and read the response
* @param operationName Simple string representing the type of request
*
* @return Data returned by the individual requests
*/
private <T> T request(ClientRequest<T> delegate, String operationName) {
ClientRequestExecutor clientRequestExecutor = pool.checkout(destination);
long startTimeMs = -1;
long startTimeNs = -1;
if(logger.isDebugEnabled()) {
startTimeMs = System.currentTimeMillis();
startTimeNs = System.nanoTime();
}
String debugMsgStr = "";
BlockingClientRequest<T> blockingClientRequest = null;
try {
blockingClientRequest = new BlockingClientRequest<T>(delegate, timeoutMs);
clientRequestExecutor.addClientRequest(blockingClientRequest, timeoutMs);
blockingClientRequest.await();
if(logger.isDebugEnabled())
debugMsgStr += "success";
return blockingClientRequest.getResult();
} catch(InterruptedException e) {
if(logger.isDebugEnabled())
debugMsgStr += "unreachable: " + e.getMessage();
throw new UnreachableStoreException("Failure in " + operationName + " on "
+ destination + ": " + e.getMessage(), e);
} catch(IOException e) {
clientRequestExecutor.close();
if(logger.isDebugEnabled())
debugMsgStr += "failure: " + e.getMessage();
throw new UnreachableStoreException("Failure in " + operationName + " on "
+ destination + ": " + e.getMessage(), e);
} finally {
if(blockingClientRequest != null && !blockingClientRequest.isComplete()) {
// close the executor if we timed out
clientRequestExecutor.close();
}
if(logger.isDebugEnabled()) {
logger.debug("Sync request end, type: "
+ operationName
+ " requestRef: "
+ System.identityHashCode(delegate)
+ " totalTimeNs: "
+ (System.nanoTime() - startTimeNs)
+ " start time: "
+ startTimeMs
+ " end time: "
+ System.currentTimeMillis()
+ " client:"
+ clientRequestExecutor.getSocketChannel().socket().getLocalAddress()
+ ":"
+ clientRequestExecutor.getSocketChannel().socket().getLocalPort()
+ " server: "
+ clientRequestExecutor.getSocketChannel()
.socket()
.getRemoteSocketAddress() + " outcome: "
+ debugMsgStr);
}
pool.checkin(destination, clientRequestExecutor);
}
}
/**
* This method handles submitting and then waiting for the request from the
* server. It uses the ClientRequest API to actually write the request and
* then read back the response. This implementation will not block for a
* response from the server.
*
* @param <T> Return type
*
* @param clientRequest ClientRequest implementation used to write the
* request and read the response
* @param operationName Simple string representing the type of request
*
* @return Data returned by the individual requests
*/
private <T> void requestAsync(ClientRequest<T> delegate,
NonblockingStoreCallback callback,
long timeoutMs,
String operationName) {
ClientRequestExecutor clientRequestExecutor = null;
try {
clientRequestExecutor = pool.checkout(destination);
if(logger.isDebugEnabled()) {
logger.debug("Async request start; type: "
+ operationName
+ " requestRef: "
+ System.identityHashCode(delegate)
+ " time: "
+ System.currentTimeMillis()
+ " server: "
+ clientRequestExecutor.getSocketChannel()
.socket()
.getRemoteSocketAddress() + " local socket: "
+ clientRequestExecutor.getSocketChannel().socket().getLocalAddress()
+ ":"
+ clientRequestExecutor.getSocketChannel().socket().getLocalPort());
}
} catch(Exception e) {
// If we can't check out a socket from the pool, we'll usually get
// either an IOException (subclass) or an UnreachableStoreException
// error. However, in the case of asynchronous calls, we want the
// error to be reported via our callback, not returned to the caller
// directly.
if(!(e instanceof UnreachableStoreException))
e = new UnreachableStoreException("Failure in " + operationName + ": "
+ e.getMessage(), e);
try {
callback.requestComplete(e, 0);
} catch(Exception ex) {
if(logger.isEnabledFor(Level.WARN))
logger.warn(ex, ex);
}
return;
}
NonblockingStoreCallbackClientRequest<T> clientRequest = new NonblockingStoreCallbackClientRequest<T>(delegate,
clientRequestExecutor,
callback);
clientRequestExecutor.addClientRequest(clientRequest, timeoutMs);
}
private class NonblockingStoreCallbackClientRequest<T> implements ClientRequest<T> {
private final ClientRequest<T> clientRequest;
private final ClientRequestExecutor clientRequestExecutor;
private final NonblockingStoreCallback callback;
private final long startNs;
private volatile boolean isComplete;
public NonblockingStoreCallbackClientRequest(ClientRequest<T> clientRequest,
ClientRequestExecutor clientRequestExecutor,
NonblockingStoreCallback callback) {
this.clientRequest = clientRequest;
this.clientRequestExecutor = clientRequestExecutor;
this.callback = callback;
this.startNs = System.nanoTime();
}
private void invokeCallback(Object o, long requestTime) {
if(callback != null) {
try {
if(logger.isDebugEnabled()) {
logger.debug("Async request end; requestRef: "
+ System.identityHashCode(clientRequest)
+ " time: "
+ System.currentTimeMillis()
+ " server: "
+ clientRequestExecutor.getSocketChannel()
.socket()
.getRemoteSocketAddress()
+ " local socket: "
+ clientRequestExecutor.getSocketChannel()
.socket()
.getLocalAddress()
+ ":"
+ clientRequestExecutor.getSocketChannel()
.socket()
.getLocalPort() + " result: "
+ o);
}
callback.requestComplete(o, requestTime);
} catch(Exception e) {
if(logger.isEnabledFor(Level.WARN))
logger.warn(e, e);
}
}
}
public void complete() {
try {
clientRequest.complete();
Object result = clientRequest.getResult();
invokeCallback(result, (System.nanoTime() - startNs) / Time.NS_PER_MS);
} catch(Exception e) {
invokeCallback(e, (System.nanoTime() - startNs) / Time.NS_PER_MS);
} finally {
pool.checkin(destination, clientRequestExecutor);
isComplete = true;
}
}
public boolean isComplete() {
return isComplete;
}
public boolean formatRequest(DataOutputStream outputStream) {
return clientRequest.formatRequest(outputStream);
}
public T getResult() throws VoldemortException, IOException {
return clientRequest.getResult();
}
public boolean isCompleteResponse(ByteBuffer buffer) {
return clientRequest.isCompleteResponse(buffer);
}
public void parseResponse(DataInputStream inputStream) {
clientRequest.parseResponse(inputStream);
}
public void timeOut() {
clientRequest.timeOut();
invokeCallback(new StoreTimeoutException("ClientRequestExecutor timed out. Cannot complete request."),
(System.nanoTime() - startNs) / Time.NS_PER_MS);
pool.checkin(destination, clientRequestExecutor);
}
public boolean isTimedOut() {
return clientRequest.isTimedOut();
}
}
}