/
TestBinaryClient.java
651 lines (519 loc) · 19.7 KB
/
TestBinaryClient.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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 org.apache.ignite.internal.processors.rest;
import org.apache.ignite.*;
import org.apache.ignite.internal.client.marshaller.*;
import org.apache.ignite.internal.client.marshaller.optimized.*;
import org.apache.ignite.internal.util.*;
import org.apache.ignite.logger.java.*;
import org.apache.ignite.internal.processors.rest.client.message.*;
import org.apache.ignite.internal.util.typedef.*;
import org.apache.ignite.internal.util.typedef.internal.*;
import org.jetbrains.annotations.*;
import java.io.*;
import java.net.*;
import java.nio.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
import static org.apache.ignite.internal.processors.rest.client.message.GridClientCacheRequest.GridCacheOperation.*;
/**
* Test client.
*/
final class TestBinaryClient {
/** Logger. */
private final IgniteLogger log = new IgniteJavaLogger();
/** Marshaller. */
private final GridClientMarshaller marsh = new GridClientOptimizedMarshaller();
/** Socket. */
private final Socket sock;
/** Socket input stream. */
private final InputStream input;
/** Opaque counter. */
private final AtomicInteger idCntr = new AtomicInteger(0);
/** Response queue. */
private final BlockingQueue<Response> queue = new LinkedBlockingQueue<>();
/** Socket reader. */
private final Thread rdr;
/** Quit response. */
private static final Response QUIT_RESP = new Response(0, GridRestResponse.STATUS_FAILED, null, null);
/** Random client id. */
private UUID id = UUID.randomUUID();
/**
* Creates client.
*
* @param host Hostname.
* @param port Port number.
* @throws IgniteCheckedException In case of error.
*/
TestBinaryClient(String host, int port) throws IgniteCheckedException {
assert host != null;
assert port > 0;
try {
sock = new Socket(host, port);
input = sock.getInputStream();
GridClientHandshakeRequest req = new GridClientHandshakeRequest();
req.marshallerId(GridClientOptimizedMarshaller.ID);
// Write handshake.
sock.getOutputStream().write(GridClientHandshakeRequestWrapper.HANDSHAKE_HEADER);
sock.getOutputStream().write(req.rawBytes());
byte[] buf = new byte[1];
// Wait for handshake response.
int read = input.read(buf);
assert read == 1 : read;
assert buf[0] == GridClientHandshakeResponse.OK.resultCode() :
"Client handshake failed [code=" + buf[0] + ']';
}
catch (IOException e) {
throw new IgniteCheckedException("Failed to establish connection.", e);
}
// Start socket reader thread.
rdr = new Thread(new Runnable() {
@SuppressWarnings("InfiniteLoopStatement")
@Override public void run() {
try {
ByteArrayOutputStream buf = new ByteArrayOutputStream();
int len = 0;
boolean running = true;
while (running) {
// Header.
int symbol = input.read();
if (symbol == -1)
break;
if ((byte)symbol != (byte)0x90) {
if (log.isDebugEnabled())
log.debug("Failed to parse incoming packet (invalid packet start): " +
Integer.toHexString(symbol & 0xFF));
break;
}
// Packet.
while (true) {
symbol = input.read();
if (symbol == -1) {
running = false;
break;
}
byte b = (byte)symbol;
buf.write(b);
if (len == 0) {
if (buf.size() == 4) {
len = U.bytesToInt(buf.toByteArray(), 0);
if (log.isInfoEnabled())
log.info("Read length: " + len);
buf.reset();
}
}
else {
if (buf.size() == len) {
byte[] bytes = buf.toByteArray();
byte[] hdrBytes = Arrays.copyOfRange(bytes, 0, 40);
byte[] msgBytes = Arrays.copyOfRange(bytes, 40, bytes.length);
GridClientResponse msg = marsh.unmarshal(msgBytes);
long reqId = GridClientByteUtils.bytesToLong(hdrBytes, 0);
UUID clientId = GridClientByteUtils.bytesToUuid(hdrBytes, 8);
UUID destId = GridClientByteUtils.bytesToUuid(hdrBytes, 24);
msg.requestId(reqId);
msg.clientId(clientId);
msg.destinationId(destId);
buf.reset();
len = 0;
queue.offer(new Response(msg.requestId(), msg.successStatus(), msg.result(),
msg.errorMessage()));
break;
}
}
}
}
}
catch (IOException e) {
if (!Thread.currentThread().isInterrupted())
U.error(log, e);
}
finally {
U.closeQuiet(sock);
queue.add(QUIT_RESP);
}
}
});
rdr.start();
}
/** {@inheritDoc} */
public void shutdown() throws IgniteCheckedException {
try {
if (rdr != null) {
rdr.interrupt();
U.closeQuiet(sock);
rdr.join();
}
}
catch (InterruptedException e) {
throw new IgniteCheckedException(e);
}
}
/**
* Makes request to server and waits for response.
*
* @param msg Message to request,
* @return Response object.
* @throws IgniteCheckedException If request failed.
*/
private Response makeRequest(GridClientMessage msg) throws IgniteCheckedException {
assert msg != null;
// Send request
try {
sock.getOutputStream().write(createPacket(msg));
}
catch (IOException e) {
throw new IgniteCheckedException("Failed to send packet.", e);
}
// Wait for response.
while (true) {
try {
// Take response from queue.
Response res = queue.take();
if (res == QUIT_RESP)
return res;
// Check opaque value.
if (res.opaque() == msg.requestId()) {
if (!res.isSuccess() && res.error() != null)
throw new IgniteCheckedException(res.error());
else
return res;
}
else
// Return response to queue if opaque is incorrect.
queue.add(res);
}
catch (InterruptedException e) {
throw new IgniteCheckedException("Interrupted while waiting for response.", e);
}
}
}
/**
* Creates hessian packet from client message.
*
* @param msg Message to be sent.
* @return Raw packet.
* @throws IOException If serialization failed.
*/
private byte[] createPacket(GridClientMessage msg) throws IOException {
msg.clientId(id);
ByteBuffer res = marsh.marshal(msg, 45);
ByteBuffer slice = res.slice();
slice.put((byte)0x90);
slice.putInt(res.remaining() - 5);
slice.putLong(msg.requestId());
slice.put(U.uuidToBytes(msg.clientId()));
slice.put(U.uuidToBytes(msg.destinationId()));
byte[] arr = new byte[res.remaining()];
res.get(arr);
return arr;
}
/**
* @param cacheName Cache name.
* @param key Key.
* @param val Value.
* @return If value was actually put.
* @throws IgniteCheckedException In case of error.
*/
public <K, V> boolean cachePut(@Nullable String cacheName, K key, V val)
throws IgniteCheckedException {
return cachePutAll(cacheName, Collections.singletonMap(key, val));
}
/**
* @param cacheName Cache name.
* @param entries Entries.
* @return {@code True} if map contained more then one entry or if put succeeded in case of one entry,
* {@code false} otherwise
* @throws IgniteCheckedException In case of error.
*/
public <K, V> boolean cachePutAll(@Nullable String cacheName, Map<K, V> entries)
throws IgniteCheckedException {
assert entries != null;
GridClientCacheRequest req = new GridClientCacheRequest(PUT_ALL);
req.requestId(idCntr.incrementAndGet());
req.cacheName(cacheName);
req.values((Map<Object, Object>)entries);
return makeRequest(req).<Boolean>getObject();
}
/**
* @param cacheName Cache name.
* @param key Key.
* @return Value.
* @throws IgniteCheckedException In case of error.
*/
public <K, V> V cacheGet(@Nullable String cacheName, K key)
throws IgniteCheckedException {
assert key != null;
GridClientCacheRequest req = new GridClientCacheRequest(GET);
req.requestId(idCntr.getAndIncrement());
req.cacheName(cacheName);
req.key(key);
return makeRequest(req).getObject();
}
/**
* @param cacheName Cache name.
* @param keys Keys.
* @return Entries.
* @throws IgniteCheckedException In case of error.
*/
public <K, V> Map<K, V> cacheGetAll(@Nullable String cacheName, K... keys)
throws IgniteCheckedException {
assert keys != null;
GridClientCacheRequest req = new GridClientCacheRequest(GET_ALL);
req.requestId(idCntr.getAndIncrement());
req.cacheName(cacheName);
req.keys((Iterable<Object>)Arrays.asList(keys));
return makeRequest(req).getObject();
}
/**
* @param cacheName Cache name.
* @param key Key.
* @return Whether entry was actually removed.
* @throws IgniteCheckedException In case of error.
*/
@SuppressWarnings("unchecked")
public <K> boolean cacheRemove(@Nullable String cacheName, K key) throws IgniteCheckedException {
assert key != null;
GridClientCacheRequest req = new GridClientCacheRequest(RMV);
req.requestId(idCntr.getAndIncrement());
req.cacheName(cacheName);
req.key(key);
return makeRequest(req).<Boolean>getObject();
}
/**
* @param cacheName Cache name.
* @param keys Keys.
* @return Whether entries were actually removed
* @throws IgniteCheckedException In case of error.
*/
public <K> boolean cacheRemoveAll(@Nullable String cacheName, K... keys)
throws IgniteCheckedException {
assert keys != null;
GridClientCacheRequest req = new GridClientCacheRequest(RMV_ALL);
req.requestId(idCntr.getAndIncrement());
req.cacheName(cacheName);
req.keys((Iterable<Object>)Arrays.asList(keys));
return makeRequest(req).isSuccess();
}
/**
* @param cacheName Cache name.
* @param key Key.
* @param val Value.
* @return Whether value was actually replaced.
* @throws IgniteCheckedException In case of error.
*/
public <K, V> boolean cacheReplace(@Nullable String cacheName, K key, V val)
throws IgniteCheckedException {
assert key != null;
assert val != null;
GridClientCacheRequest replace = new GridClientCacheRequest(REPLACE);
replace.requestId(idCntr.getAndIncrement());
replace.cacheName(cacheName);
replace.key(key);
replace.value(val);
return makeRequest(replace).<Boolean>getObject();
}
/**
* @param cacheName Cache name.
* @param key Key.
* @param val1 Value 1.
* @param val2 Value 2.
* @return Whether new value was actually set.
* @throws IgniteCheckedException In case of error.
*/
public <K, V> boolean cacheCompareAndSet(@Nullable String cacheName, K key, @Nullable V val1, @Nullable V val2)
throws IgniteCheckedException {
assert key != null;
GridClientCacheRequest msg = new GridClientCacheRequest(CAS);
msg.requestId(idCntr.getAndIncrement());
msg.cacheName(cacheName);
msg.key(key);
msg.value(val1);
msg.value2(val2);
return makeRequest(msg).<Boolean>getObject();
}
/**
* @param cacheName Cache name.
* @return Metrics.
* @throws IgniteCheckedException In case of error.
*/
public <K> Map<String, Long> cacheMetrics(@Nullable String cacheName) throws IgniteCheckedException {
GridClientCacheRequest metrics = new GridClientCacheRequest(METRICS);
metrics.requestId(idCntr.getAndIncrement());
metrics.cacheName(cacheName);
return makeRequest(metrics).getObject();
}
/**
* @param cacheName Cache name.
* @param key Key.
* @param val Value.
* @return Whether entry was appended.
* @throws IgniteCheckedException In case of error.
*/
public <K, V> boolean cacheAppend(@Nullable String cacheName, K key, V val)
throws IgniteCheckedException {
assert key != null;
assert val != null;
GridClientCacheRequest add = new GridClientCacheRequest(APPEND);
add.requestId(idCntr.getAndIncrement());
add.cacheName(cacheName);
add.key(key);
add.value(val);
return makeRequest(add).<Boolean>getObject();
}
/**
* @param cacheName Cache name.
* @param key Key.
* @param val Value.
* @return Whether entry was prepended.
* @throws IgniteCheckedException In case of error.
*/
public <K, V> boolean cachePrepend(@Nullable String cacheName, K key, V val)
throws IgniteCheckedException {
assert key != null;
assert val != null;
GridClientCacheRequest add = new GridClientCacheRequest(PREPEND);
add.requestId(idCntr.getAndIncrement());
add.cacheName(cacheName);
add.key(key);
add.value(val);
return makeRequest(add).<Boolean>getObject();
}
/**
* @param taskName Task name.
* @param arg Task arguments.
* @return Task execution result.
* @throws IgniteCheckedException In case of error.
*/
public GridClientTaskResultBean execute(String taskName, @Nullable Object arg) throws IgniteCheckedException {
assert !F.isEmpty(taskName);
GridClientTaskRequest msg = new GridClientTaskRequest();
msg.taskName(taskName);
msg.argument(arg);
return makeRequest(msg).getObject();
}
/**
* @param id Node ID.
* @param includeAttrs Whether to include attributes.
* @param includeMetrics Whether to include metrics.
* @return Node.
* @throws IgniteCheckedException In case of error.
*/
public GridClientNodeBean node(UUID id, boolean includeAttrs, boolean includeMetrics)
throws IgniteCheckedException {
assert id != null;
GridClientTopologyRequest msg = new GridClientTopologyRequest();
msg.nodeId(id);
msg.includeAttributes(includeAttrs);
msg.includeMetrics(includeMetrics);
return makeRequest(msg).getObject();
}
/**
* @param ipAddr IP address.
* @param includeAttrs Whether to include attributes.
* @param includeMetrics Whether to include metrics.
* @return Node.
* @throws IgniteCheckedException In case of error.
*/
public GridClientNodeBean node(String ipAddr, boolean includeAttrs, boolean includeMetrics)
throws IgniteCheckedException {
assert !F.isEmpty(ipAddr);
GridClientTopologyRequest msg = new GridClientTopologyRequest();
msg.nodeIp(ipAddr);
msg.includeAttributes(includeAttrs);
msg.includeMetrics(includeMetrics);
return makeRequest(msg).getObject();
}
/**
* @param includeAttrs Whether to include attributes.
* @param includeMetrics Whether to include metrics.
* @return Nodes.
* @throws IgniteCheckedException In case of error.
*/
public List<GridClientNodeBean> topology(boolean includeAttrs, boolean includeMetrics)
throws IgniteCheckedException {
GridClientTopologyRequest msg = new GridClientTopologyRequest();
msg.includeAttributes(includeAttrs);
msg.includeMetrics(includeMetrics);
return makeRequest(msg).getObject();
}
/**
* @param path Log file path.
* @return Log file contents.
* @throws IgniteCheckedException In case of error.
*/
public List<String> log(@Nullable String path, int from, int to) throws IgniteCheckedException {
GridClientLogRequest msg = new GridClientLogRequest();
msg.requestId(idCntr.getAndIncrement());
msg.path(path);
msg.from(from);
msg.to(to);
return makeRequest(msg).getObject();
}
/**
* Response data.
*/
private static class Response {
/** Opaque. */
private final long opaque;
/** Success flag. */
private final int success;
/** Response object. */
private final Object obj;
/** Error message, if any */
private final String error;
/**
* @param opaque Opaque.
* @param success Success flag.
* @param obj Response object.
* @param error Error message, if any.
*/
Response(long opaque, int success, @Nullable Object obj, @Nullable String error) {
assert opaque >= 0;
this.opaque = opaque;
this.success = success;
this.obj = obj;
this.error = error;
}
/**
* @return Opaque.
*/
long opaque() {
return opaque;
}
/**
* @return Success flag.
*/
boolean isSuccess() {
return success == GridRestResponse.STATUS_SUCCESS;
}
/**
* @return Response object.
*/
@SuppressWarnings("unchecked")
<T> T getObject() {
return (T)obj;
}
/**
* @return Error message in case if error occurred.
*/
String error() {
return error;
}
}
}