1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.hadoop.hbase.coprocessor;
20
21 import static org.junit.Assert.assertEquals;
22 import static org.junit.Assert.assertTrue;
23
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.Arrays;
27 import java.util.Collection;
28 import java.util.Collections;
29 import java.util.HashSet;
30 import java.util.List;
31 import java.util.Set;
32 import java.util.concurrent.CountDownLatch;
33 import java.util.concurrent.atomic.AtomicInteger;
34 import java.util.concurrent.atomic.AtomicLong;
35
36 import org.apache.hadoop.hbase.TableName;
37 import org.apache.hadoop.hbase.client.Table;
38 import org.apache.hadoop.hbase.util.ByteStringer;
39 import org.apache.hadoop.conf.Configuration;
40 import org.apache.hadoop.hbase.Cell;
41 import org.apache.hadoop.hbase.CellUtil;
42 import org.apache.hadoop.hbase.HBaseTestingUtility;
43 import org.apache.hadoop.hbase.HConstants;
44 import org.apache.hadoop.hbase.KeyValue;
45 import org.apache.hadoop.hbase.testclassification.MediumTests;
46 import org.apache.hadoop.hbase.client.Delete;
47 import org.apache.hadoop.hbase.client.Get;
48 import org.apache.hadoop.hbase.client.IsolationLevel;
49 import org.apache.hadoop.hbase.client.Mutation;
50 import org.apache.hadoop.hbase.client.Put;
51 import org.apache.hadoop.hbase.client.Scan;
52 import org.apache.hadoop.hbase.client.coprocessor.RowProcessorClient;
53 import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos;
54 import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.FriendsOfFriendsProcessorRequest;
55 import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.FriendsOfFriendsProcessorResponse;
56 import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.IncCounterProcessorRequest;
57 import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.IncCounterProcessorResponse;
58 import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.RowSwapProcessorRequest;
59 import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.RowSwapProcessorResponse;
60 import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.TimeoutProcessorRequest;
61 import org.apache.hadoop.hbase.coprocessor.protobuf.generated.IncrementCounterProcessorTestProtos.TimeoutProcessorResponse;
62 import org.apache.hadoop.hbase.ipc.CoprocessorRpcChannel;
63 import org.apache.hadoop.hbase.protobuf.generated.RowProcessorProtos.ProcessRequest;
64 import org.apache.hadoop.hbase.protobuf.generated.RowProcessorProtos.ProcessResponse;
65 import org.apache.hadoop.hbase.protobuf.generated.RowProcessorProtos.RowProcessorService;
66 import org.apache.hadoop.hbase.regionserver.BaseRowProcessor;
67 import org.apache.hadoop.hbase.regionserver.HRegion;
68 import org.apache.hadoop.hbase.regionserver.InternalScanner;
69 import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
70 import org.apache.hadoop.hbase.util.Bytes;
71 import org.junit.AfterClass;
72 import org.junit.BeforeClass;
73 import org.junit.Test;
74 import org.junit.experimental.categories.Category;
75
76 import com.google.protobuf.Message;
77 import org.apache.commons.logging.Log;
78 import org.apache.commons.logging.LogFactory;
79
80
81
82
83
84 @Category(MediumTests.class)
85 public class TestRowProcessorEndpoint {
86
87 private static final Log LOG = LogFactory.getLog(TestRowProcessorEndpoint.class);
88
89 private static final TableName TABLE = TableName.valueOf("testtable");
90 private final static byte[] ROW = Bytes.toBytes("testrow");
91 private final static byte[] ROW2 = Bytes.toBytes("testrow2");
92 private final static byte[] FAM = Bytes.toBytes("friendlist");
93
94
95 private final static byte[] A = Bytes.toBytes("a");
96 private final static byte[] B = Bytes.toBytes("b");
97 private final static byte[] C = Bytes.toBytes("c");
98 private final static byte[] D = Bytes.toBytes("d");
99 private final static byte[] E = Bytes.toBytes("e");
100 private final static byte[] F = Bytes.toBytes("f");
101 private final static byte[] G = Bytes.toBytes("g");
102 private final static byte[] COUNTER = Bytes.toBytes("counter");
103 private final static AtomicLong myTimer = new AtomicLong(0);
104 private final AtomicInteger failures = new AtomicInteger(0);
105
106 private static HBaseTestingUtility util = new HBaseTestingUtility();
107 private static volatile int expectedCounter = 0;
108 private static int rowSize, row2Size;
109
110 private volatile static Table table = null;
111 private volatile static boolean swapped = false;
112 private volatile CountDownLatch startSignal;
113 private volatile CountDownLatch doneSignal;
114
115 @BeforeClass
116 public static void setupBeforeClass() throws Exception {
117 Configuration conf = util.getConfiguration();
118 conf.setStrings(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY,
119 RowProcessorEndpoint.class.getName());
120 conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 2);
121 conf.setLong("hbase.hregion.row.processor.timeout", 1000L);
122 util.startMiniCluster();
123 }
124
125 @AfterClass
126 public static void tearDownAfterClass() throws Exception {
127 util.shutdownMiniCluster();
128 }
129
130 public void prepareTestData() throws Exception {
131 try {
132 util.getHBaseAdmin().disableTable(TABLE);
133 util.getHBaseAdmin().deleteTable(TABLE);
134 } catch (Exception e) {
135
136 }
137 table = util.createTable(TABLE, FAM);
138 {
139 Put put = new Put(ROW);
140 put.add(FAM, A, Bytes.add(B, C));
141 put.add(FAM, B, Bytes.add(D, E, F));
142 put.add(FAM, C, G);
143 table.put(put);
144 rowSize = put.size();
145 }
146 Put put = new Put(ROW2);
147 put.add(FAM, D, E);
148 put.add(FAM, F, G);
149 table.put(put);
150 row2Size = put.size();
151 }
152
153 @Test
154 public void testDoubleScan() throws Throwable {
155 prepareTestData();
156
157 CoprocessorRpcChannel channel = table.coprocessorService(ROW);
158 RowProcessorEndpoint.FriendsOfFriendsProcessor processor =
159 new RowProcessorEndpoint.FriendsOfFriendsProcessor(ROW, A);
160 RowProcessorService.BlockingInterface service =
161 RowProcessorService.newBlockingStub(channel);
162 ProcessRequest request = RowProcessorClient.getRowProcessorPB(processor);
163 ProcessResponse protoResult = service.process(null, request);
164 FriendsOfFriendsProcessorResponse response =
165 FriendsOfFriendsProcessorResponse.parseFrom(protoResult.getRowProcessorResult());
166 Set<String> result = new HashSet<String>();
167 result.addAll(response.getResultList());
168 Set<String> expected =
169 new HashSet<String>(Arrays.asList(new String[]{"d", "e", "f", "g"}));
170 Get get = new Get(ROW);
171 LOG.debug("row keyvalues:" + stringifyKvs(table.get(get).listCells()));
172 assertEquals(expected, result);
173 }
174
175 @Test
176 public void testReadModifyWrite() throws Throwable {
177 prepareTestData();
178 failures.set(0);
179 int numThreads = 100;
180 concurrentExec(new IncrementRunner(), numThreads);
181 Get get = new Get(ROW);
182 LOG.debug("row keyvalues:" + stringifyKvs(table.get(get).listCells()));
183 int finalCounter = incrementCounter(table);
184 int failureNumber = failures.get();
185 if (failureNumber > 0) {
186 LOG.debug("We failed " + failureNumber + " times during test");
187 }
188 assertEquals(numThreads + 1 - failureNumber, finalCounter);
189 }
190
191 class IncrementRunner implements Runnable {
192 @Override
193 public void run() {
194 try {
195 incrementCounter(table);
196 } catch (Throwable e) {
197 failures.incrementAndGet();
198 e.printStackTrace();
199 }
200 }
201 }
202
203 private int incrementCounter(Table table) throws Throwable {
204 CoprocessorRpcChannel channel = table.coprocessorService(ROW);
205 RowProcessorEndpoint.IncrementCounterProcessor processor =
206 new RowProcessorEndpoint.IncrementCounterProcessor(ROW);
207 RowProcessorService.BlockingInterface service =
208 RowProcessorService.newBlockingStub(channel);
209 ProcessRequest request = RowProcessorClient.getRowProcessorPB(processor);
210 ProcessResponse protoResult = service.process(null, request);
211 IncCounterProcessorResponse response = IncCounterProcessorResponse
212 .parseFrom(protoResult.getRowProcessorResult());
213 Integer result = response.getResponse();
214 return result;
215 }
216
217 private void concurrentExec(
218 final Runnable task, final int numThreads) throws Throwable {
219 startSignal = new CountDownLatch(numThreads);
220 doneSignal = new CountDownLatch(numThreads);
221 for (int i = 0; i < numThreads; ++i) {
222 new Thread(new Runnable() {
223 @Override
224 public void run() {
225 try {
226 startSignal.countDown();
227 startSignal.await();
228 task.run();
229 } catch (Throwable e) {
230 failures.incrementAndGet();
231 e.printStackTrace();
232 }
233 doneSignal.countDown();
234 }
235 }).start();
236 }
237 doneSignal.await();
238 }
239
240 @Test
241 public void testMultipleRows() throws Throwable {
242 prepareTestData();
243 failures.set(0);
244 int numThreads = 100;
245 concurrentExec(new SwapRowsRunner(), numThreads);
246 LOG.debug("row keyvalues:" +
247 stringifyKvs(table.get(new Get(ROW)).listCells()));
248 LOG.debug("row2 keyvalues:" +
249 stringifyKvs(table.get(new Get(ROW2)).listCells()));
250 int failureNumber = failures.get();
251 if (failureNumber > 0) {
252 LOG.debug("We failed " + failureNumber + " times during test");
253 }
254 if (!swapped) {
255 assertEquals(rowSize, table.get(new Get(ROW)).listCells().size());
256 assertEquals(row2Size, table.get(new Get(ROW2)).listCells().size());
257 } else {
258 assertEquals(rowSize, table.get(new Get(ROW2)).listCells().size());
259 assertEquals(row2Size, table.get(new Get(ROW)).listCells().size());
260 }
261 }
262
263 class SwapRowsRunner implements Runnable {
264 @Override
265 public void run() {
266 try {
267 swapRows(table);
268 } catch (Throwable e) {
269 failures.incrementAndGet();
270 e.printStackTrace();
271 }
272 }
273 }
274
275 private void swapRows(Table table) throws Throwable {
276 CoprocessorRpcChannel channel = table.coprocessorService(ROW);
277 RowProcessorEndpoint.RowSwapProcessor processor =
278 new RowProcessorEndpoint.RowSwapProcessor(ROW, ROW2);
279 RowProcessorService.BlockingInterface service =
280 RowProcessorService.newBlockingStub(channel);
281 ProcessRequest request = RowProcessorClient.getRowProcessorPB(processor);
282 service.process(null, request);
283 }
284
285 @Test
286 public void testTimeout() throws Throwable {
287 prepareTestData();
288 CoprocessorRpcChannel channel = table.coprocessorService(ROW);
289 RowProcessorEndpoint.TimeoutProcessor processor =
290 new RowProcessorEndpoint.TimeoutProcessor(ROW);
291 RowProcessorService.BlockingInterface service =
292 RowProcessorService.newBlockingStub(channel);
293 ProcessRequest request = RowProcessorClient.getRowProcessorPB(processor);
294 boolean exceptionCaught = false;
295 try {
296 service.process(null, request);
297 } catch (Exception e) {
298 exceptionCaught = true;
299 }
300 assertTrue(exceptionCaught);
301 }
302
303
304
305
306
307
308
309
310 public static class RowProcessorEndpoint<S extends Message,T extends Message>
311 extends BaseRowProcessorEndpoint<S,T> implements CoprocessorService {
312 public static class IncrementCounterProcessor extends
313 BaseRowProcessor<IncrementCounterProcessorTestProtos.IncCounterProcessorRequest,
314 IncrementCounterProcessorTestProtos.IncCounterProcessorResponse> {
315 int counter = 0;
316 byte[] row = new byte[0];
317
318
319
320
321 IncrementCounterProcessor() {
322 }
323
324 IncrementCounterProcessor(byte[] row) {
325 this.row = row;
326 }
327
328 @Override
329 public Collection<byte[]> getRowsToLock() {
330 return Collections.singleton(row);
331 }
332
333 @Override
334 public IncCounterProcessorResponse getResult() {
335 IncCounterProcessorResponse.Builder i = IncCounterProcessorResponse.newBuilder();
336 i.setResponse(counter);
337 return i.build();
338 }
339
340 @Override
341 public boolean readOnly() {
342 return false;
343 }
344
345 @Override
346 public void process(long now, HRegion region,
347 List<Mutation> mutations, WALEdit walEdit) throws IOException {
348
349 List<Cell> kvs = new ArrayList<Cell>();
350 Scan scan = new Scan(row, row);
351 scan.addColumn(FAM, COUNTER);
352 doScan(region, scan, kvs);
353 counter = kvs.size() == 0 ? 0 :
354 Bytes.toInt(CellUtil.cloneValue(kvs.iterator().next()));
355
356
357 assertEquals(expectedCounter, counter);
358
359
360 counter += 1;
361 expectedCounter += 1;
362
363
364 Put p = new Put(row);
365 KeyValue kv =
366 new KeyValue(row, FAM, COUNTER, now, Bytes.toBytes(counter));
367 p.add(kv);
368 mutations.add(p);
369 walEdit.add(kv);
370
371
372 KeyValue metaKv = new KeyValue(
373 row, WALEdit.METAFAMILY,
374 Bytes.toBytes("I just increment counter"),
375 Bytes.toBytes(counter));
376 walEdit.add(metaKv);
377 }
378
379 @Override
380 public IncCounterProcessorRequest getRequestData() throws IOException {
381 IncCounterProcessorRequest.Builder builder = IncCounterProcessorRequest.newBuilder();
382 builder.setCounter(counter);
383 builder.setRow(ByteStringer.wrap(row));
384 return builder.build();
385 }
386
387 @Override
388 public void initialize(IncCounterProcessorRequest msg) {
389 this.row = msg.getRow().toByteArray();
390 this.counter = msg.getCounter();
391 }
392 }
393
394 public static class FriendsOfFriendsProcessor extends
395 BaseRowProcessor<FriendsOfFriendsProcessorRequest, FriendsOfFriendsProcessorResponse> {
396 byte[] row = null;
397 byte[] person = null;
398 final Set<String> result = new HashSet<String>();
399
400
401
402
403 FriendsOfFriendsProcessor() {
404 }
405
406 FriendsOfFriendsProcessor(byte[] row, byte[] person) {
407 this.row = row;
408 this.person = person;
409 }
410
411 @Override
412 public Collection<byte[]> getRowsToLock() {
413 return Collections.singleton(row);
414 }
415
416 @Override
417 public FriendsOfFriendsProcessorResponse getResult() {
418 FriendsOfFriendsProcessorResponse.Builder builder =
419 FriendsOfFriendsProcessorResponse.newBuilder();
420 builder.addAllResult(result);
421 return builder.build();
422 }
423
424 @Override
425 public boolean readOnly() {
426 return true;
427 }
428
429 @Override
430 public void process(long now, HRegion region,
431 List<Mutation> mutations, WALEdit walEdit) throws IOException {
432 List<Cell> kvs = new ArrayList<Cell>();
433 {
434 Scan scan = new Scan(row, row);
435 scan.addColumn(FAM, person);
436 doScan(region, scan, kvs);
437 }
438
439
440 Scan scan = new Scan(row, row);
441 for (Cell kv : kvs) {
442 byte[] friends = CellUtil.cloneValue(kv);
443 for (byte f : friends) {
444 scan.addColumn(FAM, new byte[]{f});
445 }
446 }
447 doScan(region, scan, kvs);
448
449
450 result.clear();
451 for (Cell kv : kvs) {
452 for (byte b : CellUtil.cloneValue(kv)) {
453 result.add((char)b + "");
454 }
455 }
456 }
457
458 @Override
459 public FriendsOfFriendsProcessorRequest getRequestData() throws IOException {
460 FriendsOfFriendsProcessorRequest.Builder builder =
461 FriendsOfFriendsProcessorRequest.newBuilder();
462 builder.setPerson(ByteStringer.wrap(person));
463 builder.setRow(ByteStringer.wrap(row));
464 builder.addAllResult(result);
465 FriendsOfFriendsProcessorRequest f = builder.build();
466 return f;
467 }
468
469 @Override
470 public void initialize(FriendsOfFriendsProcessorRequest request)
471 throws IOException {
472 this.person = request.getPerson().toByteArray();
473 this.row = request.getRow().toByteArray();
474 result.clear();
475 result.addAll(request.getResultList());
476 }
477 }
478
479 public static class RowSwapProcessor extends
480 BaseRowProcessor<RowSwapProcessorRequest, RowSwapProcessorResponse> {
481 byte[] row1 = new byte[0];
482 byte[] row2 = new byte[0];
483
484
485
486
487 RowSwapProcessor() {
488 }
489
490 RowSwapProcessor(byte[] row1, byte[] row2) {
491 this.row1 = row1;
492 this.row2 = row2;
493 }
494
495 @Override
496 public Collection<byte[]> getRowsToLock() {
497 List<byte[]> rows = new ArrayList<byte[]>();
498 rows.add(row1);
499 rows.add(row2);
500 return rows;
501 }
502
503 @Override
504 public boolean readOnly() {
505 return false;
506 }
507
508 @Override
509 public RowSwapProcessorResponse getResult() {
510 return RowSwapProcessorResponse.getDefaultInstance();
511 }
512
513 @Override
514 public void process(long now, HRegion region,
515 List<Mutation> mutations, WALEdit walEdit) throws IOException {
516
517
518
519 now = myTimer.getAndIncrement();
520
521
522 List<Cell> kvs1 = new ArrayList<Cell>();
523 List<Cell> kvs2 = new ArrayList<Cell>();
524 doScan(region, new Scan(row1, row1), kvs1);
525 doScan(region, new Scan(row2, row2), kvs2);
526
527
528 if (swapped) {
529 assertEquals(rowSize, kvs2.size());
530 assertEquals(row2Size, kvs1.size());
531 } else {
532 assertEquals(rowSize, kvs1.size());
533 assertEquals(row2Size, kvs2.size());
534 }
535 swapped = !swapped;
536
537
538 List<List<Cell>> kvs = new ArrayList<List<Cell>>();
539 kvs.add(kvs1);
540 kvs.add(kvs2);
541 byte[][] rows = new byte[][]{row1, row2};
542 for (int i = 0; i < kvs.size(); ++i) {
543 for (Cell kv : kvs.get(i)) {
544
545 Delete d = new Delete(rows[i]);
546 KeyValue kvDelete =
547 new KeyValue(rows[i], CellUtil.cloneFamily(kv), CellUtil.cloneQualifier(kv),
548 kv.getTimestamp(), KeyValue.Type.Delete);
549 d.addDeleteMarker(kvDelete);
550 Put p = new Put(rows[1 - i]);
551 KeyValue kvAdd =
552 new KeyValue(rows[1 - i], CellUtil.cloneFamily(kv), CellUtil.cloneQualifier(kv),
553 now, CellUtil.cloneValue(kv));
554 p.add(kvAdd);
555 mutations.add(d);
556 walEdit.add(kvDelete);
557 mutations.add(p);
558 walEdit.add(kvAdd);
559 }
560 }
561 }
562
563 @Override
564 public String getName() {
565 return "swap";
566 }
567
568 @Override
569 public RowSwapProcessorRequest getRequestData() throws IOException {
570 RowSwapProcessorRequest.Builder builder = RowSwapProcessorRequest.newBuilder();
571 builder.setRow1(ByteStringer.wrap(row1));
572 builder.setRow2(ByteStringer.wrap(row2));
573 return builder.build();
574 }
575
576 @Override
577 public void initialize(RowSwapProcessorRequest msg) {
578 this.row1 = msg.getRow1().toByteArray();
579 this.row2 = msg.getRow2().toByteArray();
580 }
581 }
582
583 public static class TimeoutProcessor extends
584 BaseRowProcessor<TimeoutProcessorRequest, TimeoutProcessorResponse> {
585
586 byte[] row = new byte[0];
587
588
589
590
591 public TimeoutProcessor() {
592 }
593
594 public TimeoutProcessor(byte[] row) {
595 this.row = row;
596 }
597
598 public Collection<byte[]> getRowsToLock() {
599 return Collections.singleton(row);
600 }
601
602 @Override
603 public TimeoutProcessorResponse getResult() {
604 return TimeoutProcessorResponse.getDefaultInstance();
605 }
606
607 @Override
608 public void process(long now, HRegion region,
609 List<Mutation> mutations, WALEdit walEdit) throws IOException {
610 try {
611
612 Thread.sleep(100 * 1000L);
613 } catch (Exception e) {
614 throw new IOException(e);
615 }
616 }
617
618 @Override
619 public boolean readOnly() {
620 return true;
621 }
622
623 @Override
624 public String getName() {
625 return "timeout";
626 }
627
628 @Override
629 public TimeoutProcessorRequest getRequestData() throws IOException {
630 TimeoutProcessorRequest.Builder builder = TimeoutProcessorRequest.newBuilder();
631 builder.setRow(ByteStringer.wrap(row));
632 return builder.build();
633 }
634
635 @Override
636 public void initialize(TimeoutProcessorRequest msg) throws IOException {
637 this.row = msg.getRow().toByteArray();
638 }
639 }
640
641 public static void doScan(
642 HRegion region, Scan scan, List<Cell> result) throws IOException {
643 InternalScanner scanner = null;
644 try {
645 scan.setIsolationLevel(IsolationLevel.READ_UNCOMMITTED);
646 scanner = region.getScanner(scan);
647 result.clear();
648 scanner.next(result);
649 } finally {
650 if (scanner != null) scanner.close();
651 }
652 }
653 }
654
655 static String stringifyKvs(Collection<Cell> kvs) {
656 StringBuilder out = new StringBuilder();
657 out.append("[");
658 if (kvs != null) {
659 for (Cell kv : kvs) {
660 byte[] col = CellUtil.cloneQualifier(kv);
661 byte[] val = CellUtil.cloneValue(kv);
662 if (Bytes.equals(col, COUNTER)) {
663 out.append(Bytes.toStringBinary(col) + ":" +
664 Bytes.toInt(val) + " ");
665 } else {
666 out.append(Bytes.toStringBinary(col) + ":" +
667 Bytes.toStringBinary(val) + " ");
668 }
669 }
670 }
671 out.append("]");
672 return out.toString();
673 }
674
675 }