View Javadoc

1   /**
2    * Copyright The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  package org.apache.hadoop.hbase.client;
21  
22  import java.io.IOException;
23  import static org.junit.Assert.assertEquals;
24  import static org.junit.Assert.assertNull;
25  import static org.junit.Assert.assertTrue;
26  import static org.junit.Assert.fail;
27  
28  import java.util.ArrayList;
29  import java.util.Arrays;
30  import java.util.List;
31  import java.util.Random;
32  import java.util.concurrent.CountDownLatch;
33  import java.util.concurrent.ExecutorService;
34  import java.util.concurrent.Executors;
35  import java.util.concurrent.TimeUnit;
36  import static junit.framework.Assert.assertFalse;
37  import org.apache.commons.logging.Log;
38  import org.apache.commons.logging.LogFactory;
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.HColumnDescriptor;
44  import org.apache.hadoop.hbase.HConstants;
45  import org.apache.hadoop.hbase.HRegionLocation;
46  import org.apache.hadoop.hbase.HTableDescriptor;
47  import org.apache.hadoop.hbase.TableName;
48  import org.apache.hadoop.hbase.client.coprocessor.Batch;
49  import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
50  import org.apache.hadoop.hbase.coprocessor.MultiRowMutationEndpoint;
51  import org.apache.hadoop.hbase.coprocessor.ObserverContext;
52  import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
53  import org.apache.hadoop.hbase.coprocessor.RegionObserver;
54  import org.apache.hadoop.hbase.Coprocessor;
55  import org.apache.hadoop.hbase.ipc.BlockingRpcCallback;
56  import org.apache.hadoop.hbase.ipc.ServerRpcController;
57  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
58  import org.apache.hadoop.hbase.protobuf.generated.AdminProtos;
59  import org.apache.hadoop.hbase.protobuf.generated.MultiRowMutationProtos;
60  import org.apache.hadoop.hbase.regionserver.HRegion;
61  import org.apache.hadoop.hbase.regionserver.HRegionServer;
62  import org.apache.hadoop.hbase.regionserver.MiniBatchOperationInProgress;
63  import org.apache.hadoop.hbase.regionserver.Region;
64  import org.apache.hadoop.hbase.testclassification.LargeTests;
65  import org.apache.hadoop.hbase.util.Bytes;
66  import org.apache.hadoop.hbase.util.Pair;
67  import org.junit.After;
68  import org.junit.AfterClass;
69  import org.junit.Before;
70  import org.junit.BeforeClass;
71  import org.junit.Test;
72  import org.junit.experimental.categories.Category;
73  
74  @Category(LargeTests.class)
75  public class TestFromClientSide3 {
76    private static final Log LOG = LogFactory.getLog(TestFromClientSide3.class);
77    private final static HBaseTestingUtility TEST_UTIL
78      = new HBaseTestingUtility();
79    private static byte[] FAMILY = Bytes.toBytes("testFamily");
80    private static Random random = new Random();
81    private static int SLAVES = 3;
82    private static byte [] ROW = Bytes.toBytes("testRow");
83    private static final byte[] ANOTHERROW = Bytes.toBytes("anotherrow");
84    private static byte [] QUALIFIER = Bytes.toBytes("testQualifier");
85    private static byte [] VALUE = Bytes.toBytes("testValue");
86    private final static byte[] COL_QUAL = Bytes.toBytes("f1");
87    private final static byte[] VAL_BYTES = Bytes.toBytes("v1");
88    private final static byte[] ROW_BYTES = Bytes.toBytes("r1");
89  
90    /**
91     * @throws java.lang.Exception
92     */
93    @BeforeClass
94    public static void setUpBeforeClass() throws Exception {
95      TEST_UTIL.getConfiguration().setBoolean(
96          "hbase.online.schema.update.enable", true);
97      TEST_UTIL.startMiniCluster(SLAVES);
98    }
99  
100   /**
101    * @throws java.lang.Exception
102    */
103   @AfterClass
104   public static void tearDownAfterClass() throws Exception {
105     TEST_UTIL.shutdownMiniCluster();
106   }
107 
108   /**
109    * @throws java.lang.Exception
110    */
111   @Before
112   public void setUp() throws Exception {
113     // Nothing to do.
114   }
115 
116   /**
117    * @throws java.lang.Exception
118    */
119   @After
120   public void tearDown() throws Exception {
121     for (HTableDescriptor htd: TEST_UTIL.getHBaseAdmin().listTables()) {
122       LOG.info("Tear down, remove table=" + htd.getTableName());
123       TEST_UTIL.deleteTable(htd.getTableName());
124     }
125   }
126 
127   private void randomCFPuts(Table table, byte[] row, byte[] family, int nPuts)
128       throws Exception {
129     Put put = new Put(row);
130     for (int i = 0; i < nPuts; i++) {
131       byte[] qualifier = Bytes.toBytes(random.nextInt());
132       byte[] value = Bytes.toBytes(random.nextInt());
133       put.add(family, qualifier, value);
134     }
135     table.put(put);
136   }
137 
138   private void performMultiplePutAndFlush(HBaseAdmin admin, HTable table,
139       byte[] row, byte[] family, int nFlushes, int nPuts)
140   throws Exception {
141 
142     // connection needed for poll-wait
143     HRegionLocation loc = table.getRegionLocation(row, true);
144     AdminProtos.AdminService.BlockingInterface server =
145       admin.getConnection().getAdmin(loc.getServerName());
146     byte[] regName = loc.getRegionInfo().getRegionName();
147 
148     for (int i = 0; i < nFlushes; i++) {
149       randomCFPuts(table, row, family, nPuts);
150       List<String> sf = ProtobufUtil.getStoreFiles(server, regName, FAMILY);
151       int sfCount = sf.size();
152 
153       // TODO: replace this api with a synchronous flush after HBASE-2949
154       admin.flush(table.getTableName());
155 
156       // synchronously poll wait for a new storefile to appear (flush happened)
157       while (ProtobufUtil.getStoreFiles(
158           server, regName, FAMILY).size() == sfCount) {
159         Thread.sleep(40);
160       }
161     }
162   }
163 
164   private static List<Cell> toList(ResultScanner scanner) {
165     try {
166       List<Cell> cells = new ArrayList<>();
167       for (Result r : scanner) {
168         cells.addAll(r.listCells());
169       }
170       return cells;
171     } finally {
172       scanner.close();
173     }
174   }
175 
176   @Test
177   public void testScanAfterDeletingSpecifiedRow() throws IOException {
178     TableName tableName = TableName.valueOf("testScanAfterDeletingSpecifiedRow");
179     HTableDescriptor desc = new HTableDescriptor(tableName)
180             .addFamily(new HColumnDescriptor(FAMILY));
181     TEST_UTIL.getHBaseAdmin().createTable(desc);
182     byte[] row = Bytes.toBytes("SpecifiedRow");
183     byte[] value0 = Bytes.toBytes("value_0");
184     byte[] value1 = Bytes.toBytes("value_1");
185     try (Table t = TEST_UTIL.getConnection().getTable(tableName)) {
186       Put put = new Put(row);
187       put.addColumn(FAMILY, QUALIFIER, VALUE);
188       t.put(put);
189       Delete d = new Delete(row);
190       t.delete(d);
191       put = new Put(row);
192       put.addColumn(FAMILY, null, value0);
193       t.put(put);
194       put = new Put(row);
195       put.addColumn(FAMILY, null, value1);
196       t.put(put);
197       List<Cell> cells = toList(t.getScanner(new Scan()));
198       assertEquals(1, cells.size());
199       assertEquals("value_1", Bytes.toString(CellUtil.cloneValue(cells.get(0))));
200 
201       cells = toList(t.getScanner(new Scan().addFamily(FAMILY)));
202       assertEquals(1, cells.size());
203       assertEquals("value_1", Bytes.toString(CellUtil.cloneValue(cells.get(0))));
204 
205       cells = toList(t.getScanner(new Scan().addColumn(FAMILY, QUALIFIER)));
206       assertEquals(0, cells.size());
207 
208       TEST_UTIL.getHBaseAdmin().flush(tableName);
209       cells = toList(t.getScanner(new Scan()));
210       assertEquals(1, cells.size());
211       assertEquals("value_1", Bytes.toString(CellUtil.cloneValue(cells.get(0))));
212 
213       cells = toList(t.getScanner(new Scan().addFamily(FAMILY)));
214       assertEquals(1, cells.size());
215       assertEquals("value_1", Bytes.toString(CellUtil.cloneValue(cells.get(0))));
216 
217       cells = toList(t.getScanner(new Scan().addColumn(FAMILY, QUALIFIER)));
218       assertEquals(0, cells.size());
219     } finally {
220       TEST_UTIL.deleteTable(tableName);
221     }
222   }
223 
224   // override the config settings at the CF level and ensure priority
225   @Test(timeout = 60000)
226   public void testAdvancedConfigOverride() throws Exception {
227     /*
228      * Overall idea: (1) create 3 store files and issue a compaction. config's
229      * compaction.min == 3, so should work. (2) Increase the compaction.min
230      * toggle in the HTD to 5 and modify table. If we use the HTD value instead
231      * of the default config value, adding 3 files and issuing a compaction
232      * SHOULD NOT work (3) Decrease the compaction.min toggle in the HCD to 2
233      * and modify table. The CF schema should override the Table schema and now
234      * cause a minor compaction.
235      */
236     TEST_UTIL.getConfiguration().setInt("hbase.hstore.compaction.min", 3);
237 
238     String tableName = "testAdvancedConfigOverride";
239     TableName TABLE = TableName.valueOf(tableName);
240     HTable hTable = TEST_UTIL.createTable(TABLE, FAMILY, 10);
241     HBaseAdmin admin = TEST_UTIL.getHBaseAdmin();
242     ClusterConnection connection = (ClusterConnection)TEST_UTIL.getConnection();
243 
244     // Create 3 store files.
245     byte[] row = Bytes.toBytes(random.nextInt());
246     performMultiplePutAndFlush(admin, hTable, row, FAMILY, 3, 100);
247 
248     // Verify we have multiple store files.
249     HRegionLocation loc = hTable.getRegionLocation(row, true);
250     byte[] regionName = loc.getRegionInfo().getRegionName();
251     AdminProtos.AdminService.BlockingInterface server =
252       connection.getAdmin(loc.getServerName());
253     assertTrue(ProtobufUtil.getStoreFiles(
254       server, regionName, FAMILY).size() > 1);
255 
256     // Issue a compaction request
257     admin.compact(TABLE.getName());
258 
259     // poll wait for the compactions to happen
260     for (int i = 0; i < 10 * 1000 / 40; ++i) {
261       // The number of store files after compaction should be lesser.
262       loc = hTable.getRegionLocation(row, true);
263       if (!loc.getRegionInfo().isOffline()) {
264         regionName = loc.getRegionInfo().getRegionName();
265         server = connection.getAdmin(loc.getServerName());
266         if (ProtobufUtil.getStoreFiles(
267             server, regionName, FAMILY).size() <= 1) {
268           break;
269         }
270       }
271       Thread.sleep(40);
272     }
273     // verify the compactions took place and that we didn't just time out
274     assertTrue(ProtobufUtil.getStoreFiles(
275       server, regionName, FAMILY).size() <= 1);
276 
277     // change the compaction.min config option for this table to 5
278     LOG.info("hbase.hstore.compaction.min should now be 5");
279     HTableDescriptor htd = new HTableDescriptor(hTable.getTableDescriptor());
280     htd.setValue("hbase.hstore.compaction.min", String.valueOf(5));
281     admin.modifyTable(TABLE, htd);
282     Pair<Integer, Integer> st;
283     while (null != (st = admin.getAlterStatus(TABLE)) && st.getFirst() > 0) {
284       LOG.debug(st.getFirst() + " regions left to update");
285       Thread.sleep(40);
286     }
287     LOG.info("alter status finished");
288 
289     // Create 3 more store files.
290     performMultiplePutAndFlush(admin, hTable, row, FAMILY, 3, 10);
291 
292     // Issue a compaction request
293     admin.compact(TABLE.getName());
294 
295     // This time, the compaction request should not happen
296     Thread.sleep(10 * 1000);
297     loc = hTable.getRegionLocation(row, true);
298     regionName = loc.getRegionInfo().getRegionName();
299     server = connection.getAdmin(loc.getServerName());
300     int sfCount = ProtobufUtil.getStoreFiles(
301       server, regionName, FAMILY).size();
302     assertTrue(sfCount > 1);
303 
304     // change an individual CF's config option to 2 & online schema update
305     LOG.info("hbase.hstore.compaction.min should now be 2");
306     HColumnDescriptor hcd = new HColumnDescriptor(htd.getFamily(FAMILY));
307     hcd.setValue("hbase.hstore.compaction.min", String.valueOf(2));
308     htd.modifyFamily(hcd);
309     admin.modifyTable(TABLE, htd);
310     while (null != (st = admin.getAlterStatus(TABLE)) && st.getFirst() > 0) {
311       LOG.debug(st.getFirst() + " regions left to update");
312       Thread.sleep(40);
313     }
314     LOG.info("alter status finished");
315 
316     // Issue a compaction request
317     admin.compact(TABLE.getName());
318 
319     // poll wait for the compactions to happen
320     for (int i = 0; i < 10 * 1000 / 40; ++i) {
321       loc = hTable.getRegionLocation(row, true);
322       regionName = loc.getRegionInfo().getRegionName();
323       try {
324         server = connection.getAdmin(loc.getServerName());
325         if (ProtobufUtil.getStoreFiles(
326             server, regionName, FAMILY).size() < sfCount) {
327           break;
328         }
329       } catch (Exception e) {
330         LOG.debug("Waiting for region to come online: " + regionName);
331       }
332       Thread.sleep(40);
333     }
334     // verify the compaction took place and that we didn't just time out
335     assertTrue(ProtobufUtil.getStoreFiles(
336       server, regionName, FAMILY).size() < sfCount);
337 
338     // Finally, ensure that we can remove a custom config value after we made it
339     LOG.info("Removing CF config value");
340     LOG.info("hbase.hstore.compaction.min should now be 5");
341     hcd = new HColumnDescriptor(htd.getFamily(FAMILY));
342     hcd.setValue("hbase.hstore.compaction.min", null);
343     htd.modifyFamily(hcd);
344     admin.modifyTable(TABLE, htd);
345     while (null != (st = admin.getAlterStatus(TABLE)) && st.getFirst() > 0) {
346       LOG.debug(st.getFirst() + " regions left to update");
347       Thread.sleep(40);
348     }
349     LOG.info("alter status finished");
350     assertNull(hTable.getTableDescriptor().getFamily(FAMILY).getValue(
351         "hbase.hstore.compaction.min"));
352   }
353 
354   @Test
355   public void testHTableBatchWithEmptyPut() throws Exception {
356     Table table = TEST_UTIL.createTable(
357       Bytes.toBytes("testHTableBatchWithEmptyPut"), new byte[][] { FAMILY });
358     try {
359       List actions = (List) new ArrayList();
360       Object[] results = new Object[2];
361       // create an empty Put
362       Put put1 = new Put(ROW);
363       actions.add(put1);
364 
365       Put put2 = new Put(ANOTHERROW);
366       put2.add(FAMILY, QUALIFIER, VALUE);
367       actions.add(put2);
368 
369       table.batch(actions, results);
370       fail("Empty Put should have failed the batch call");
371     } catch (IllegalArgumentException iae) {
372 
373     } finally {
374       table.close();
375     }
376   }
377 
378   @Test
379   public void testHTableExistsMethodSingleRegionSingleGet() throws Exception {
380 
381     // Test with a single region table.
382 
383     Table table = TEST_UTIL.createTable(
384       Bytes.toBytes("testHTableExistsMethodSingleRegionSingleGet"), new byte[][] { FAMILY });
385 
386     Put put = new Put(ROW);
387     put.add(FAMILY, QUALIFIER, VALUE);
388 
389     Get get = new Get(ROW);
390 
391     boolean exist = table.exists(get);
392     assertEquals(exist, false);
393 
394     table.put(put);
395 
396     exist = table.exists(get);
397     assertEquals(exist, true);
398   }
399 
400   public void testHTableExistsMethodSingleRegionMultipleGets() throws Exception {
401 
402     HTable table = TEST_UTIL.createTable(
403       Bytes.toBytes("testHTableExistsMethodSingleRegionMultipleGets"), new byte[][] { FAMILY });
404 
405     Put put = new Put(ROW);
406     put.add(FAMILY, QUALIFIER, VALUE);
407     table.put(put);
408 
409     List<Get> gets = new ArrayList<Get>();
410     gets.add(new Get(ROW));
411     gets.add(null);
412     gets.add(new Get(ANOTHERROW));
413 
414     Boolean[] results = table.exists(gets);
415     assertEquals(results[0], true);
416     assertEquals(results[1], false);
417     assertEquals(results[2], false);
418   }
419 
420   @Test
421   public void testHTableExistsBeforeGet() throws Exception {
422     Table table = TEST_UTIL.createTable(
423       Bytes.toBytes("testHTableExistsBeforeGet"), new byte[][] { FAMILY });
424     try {
425       Put put = new Put(ROW);
426       put.add(FAMILY, QUALIFIER, VALUE);
427       table.put(put);
428 
429       Get get = new Get(ROW);
430 
431       boolean exist = table.exists(get);
432       assertEquals(true, exist);
433 
434       Result result = table.get(get);
435       assertEquals(false, result.isEmpty());
436       assertTrue(Bytes.equals(VALUE, result.getValue(FAMILY, QUALIFIER)));
437     } finally {
438       table.close();
439     }
440   }
441 
442   @Test
443   public void testHTableExistsAllBeforeGet() throws Exception {
444     final byte[] ROW2 = Bytes.add(ROW, Bytes.toBytes("2"));
445     Table table = TEST_UTIL.createTable(
446       Bytes.toBytes("testHTableExistsAllBeforeGet"), new byte[][] { FAMILY });
447     try {
448       Put put = new Put(ROW);
449       put.add(FAMILY, QUALIFIER, VALUE);
450       table.put(put);
451       put = new Put(ROW2);
452       put.add(FAMILY, QUALIFIER, VALUE);
453       table.put(put);
454 
455       Get get = new Get(ROW);
456       Get get2 = new Get(ROW2);
457       ArrayList<Get> getList = new ArrayList(2);
458       getList.add(get);
459       getList.add(get2);
460 
461       boolean[] exists = table.existsAll(getList);
462       assertEquals(true, exists[0]);
463       assertEquals(true, exists[1]);
464 
465       Result[] result = table.get(getList);
466       assertEquals(false, result[0].isEmpty());
467       assertTrue(Bytes.equals(VALUE, result[0].getValue(FAMILY, QUALIFIER)));
468       assertEquals(false, result[1].isEmpty());
469       assertTrue(Bytes.equals(VALUE, result[1].getValue(FAMILY, QUALIFIER)));
470     } finally {
471       table.close();
472     }
473   }
474 
475   @Test
476   public void testHTableExistsMethodMultipleRegionsSingleGet() throws Exception {
477 
478     Table table = TEST_UTIL.createTable(
479       TableName.valueOf("testHTableExistsMethodMultipleRegionsSingleGet"), new byte[][] { FAMILY },
480       1, new byte[] { 0x00 }, new byte[] { (byte) 0xff }, 255);
481     Put put = new Put(ROW);
482     put.add(FAMILY, QUALIFIER, VALUE);
483 
484     Get get = new Get(ROW);
485 
486     boolean exist = table.exists(get);
487     assertEquals(exist, false);
488 
489     table.put(put);
490 
491     exist = table.exists(get);
492     assertEquals(exist, true);
493   }
494 
495   @Test
496   public void testHTableExistsMethodMultipleRegionsMultipleGets() throws Exception {
497     HTable table = TEST_UTIL.createTable(
498       TableName.valueOf("testHTableExistsMethodMultipleRegionsMultipleGets"),
499       new byte[][] { FAMILY }, 1, new byte[] { 0x00 }, new byte[] { (byte) 0xff }, 255);
500     Put put = new Put(ROW);
501     put.add(FAMILY, QUALIFIER, VALUE);
502     table.put (put);
503 
504     List<Get> gets = new ArrayList<Get>();
505     gets.add(new Get(ANOTHERROW));
506     gets.add(new Get(Bytes.add(ROW, new byte[] { 0x00 })));
507     gets.add(new Get(ROW));
508     gets.add(new Get(Bytes.add(ANOTHERROW, new byte[] { 0x00 })));
509 
510     LOG.info("Calling exists");
511     Boolean[] results = table.exists(gets);
512     assertEquals(results[0], false);
513     assertEquals(results[1], false);
514     assertEquals(results[2], true);
515     assertEquals(results[3], false);
516 
517     // Test with the first region.
518     put = new Put(new byte[] { 0x00 });
519     put.add(FAMILY, QUALIFIER, VALUE);
520     table.put(put);
521 
522     gets = new ArrayList<Get>();
523     gets.add(new Get(new byte[] { 0x00 }));
524     gets.add(new Get(new byte[] { 0x00, 0x00 }));
525     results = table.exists(gets);
526     assertEquals(results[0], true);
527     assertEquals(results[1], false);
528 
529     // Test with the last region
530     put = new Put(new byte[] { (byte) 0xff, (byte) 0xff });
531     put.add(FAMILY, QUALIFIER, VALUE);
532     table.put(put);
533 
534     gets = new ArrayList<Get>();
535     gets.add(new Get(new byte[] { (byte) 0xff }));
536     gets.add(new Get(new byte[] { (byte) 0xff, (byte) 0xff }));
537     gets.add(new Get(new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff }));
538     results = table.exists(gets);
539     assertEquals(results[0], false);
540     assertEquals(results[1], true);
541     assertEquals(results[2], false);
542   }
543 
544   @Test
545   public void testGetEmptyRow() throws Exception {
546     //Create a table and put in 1 row
547     Admin admin = TEST_UTIL.getHBaseAdmin();
548     HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(Bytes.toBytes("test")));
549     desc.addFamily(new HColumnDescriptor(FAMILY));
550     admin.createTable(desc);
551     Table table = new HTable(TEST_UTIL.getConfiguration(), desc.getTableName());
552 
553     Put put = new Put(ROW_BYTES);
554     put.add(FAMILY, COL_QUAL, VAL_BYTES);
555     table.put(put);
556 
557     //Try getting the row with an empty row key
558     Result res = null;
559     try {
560       res = table.get(new Get(new byte[0]));
561       fail();
562     } catch (IllegalArgumentException e) {
563       // Expected.
564     }
565     assertTrue(res == null);
566     res = table.get(new Get(Bytes.toBytes("r1-not-exist")));
567     assertTrue(res.isEmpty() == true);
568     res = table.get(new Get(ROW_BYTES));
569     assertTrue(Arrays.equals(res.getValue(FAMILY, COL_QUAL), VAL_BYTES));
570     table.close();
571   }
572 
573   @Test(timeout = 30000)
574   public void testMultiRowMutations() throws Exception, Throwable {
575     final TableName tableName = TableName.valueOf("testMultiRowMutations");
576     HTableDescriptor desc = new HTableDescriptor(tableName);
577     desc.addCoprocessor(MultiRowMutationEndpoint.class.getName());
578     desc.addCoprocessor(WatiingForMultiMutationsObserver.class.getName());
579     desc.setConfiguration("hbase.rowlock.wait.duration", String.valueOf(5000));
580     desc.addFamily(new HColumnDescriptor(FAMILY));
581     TEST_UTIL.getHBaseAdmin().createTable(desc);
582     // new a connection for lower retry number.
583     Configuration copy = new Configuration(TEST_UTIL.getConfiguration());
584     copy.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 2);
585     try (Connection con = ConnectionFactory.createConnection(copy)) {
586       final byte[] row = Bytes.toBytes("ROW-0");
587       final byte[] rowLocked= Bytes.toBytes("ROW-1");
588       final byte[] value0 = Bytes.toBytes("VALUE-0");
589       final byte[] value1 = Bytes.toBytes("VALUE-1");
590       final byte[] value2 = Bytes.toBytes("VALUE-2");
591       assertNoLocks(tableName);
592       ExecutorService putService = Executors.newSingleThreadExecutor();
593       putService.execute(new Runnable() {
594         @Override
595         public void run() {
596           try (Table table = con.getTable(tableName)) {
597             Put put0 = new Put(rowLocked);
598             put0.addColumn(FAMILY, QUALIFIER, value0);
599             // the put will be blocked by WatiingForMultiMutationsObserver.
600             table.put(put0);
601           } catch (IOException ex) {
602             throw new RuntimeException(ex);
603           }
604         }
605       });
606       ExecutorService cpService = Executors.newSingleThreadExecutor();
607       cpService.execute(new Runnable() {
608         @Override
609         public void run() {
610           Put put1 = new Put(row);
611           Put put2 = new Put(rowLocked);
612           put1.addColumn(FAMILY, QUALIFIER, value1);
613           put2.addColumn(FAMILY, QUALIFIER, value2);
614           try (Table table = con.getTable(tableName)) {
615             final MultiRowMutationProtos.MutateRowsRequest request
616               = MultiRowMutationProtos.MutateRowsRequest.newBuilder()
617                 .addMutationRequest(org.apache.hadoop.hbase.protobuf.ProtobufUtil.toMutation(
618                         org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.MutationType.PUT, put1))
619                 .addMutationRequest(org.apache.hadoop.hbase.protobuf.ProtobufUtil.toMutation(
620                         org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.MutationType.PUT, put2))
621                 .build();
622             table.coprocessorService(MultiRowMutationProtos.MultiRowMutationService.class, ROW, ROW,
623               new Batch.Call<MultiRowMutationProtos.MultiRowMutationService, MultiRowMutationProtos.MutateRowsResponse>() {
624                 public MultiRowMutationProtos.MutateRowsResponse call(MultiRowMutationProtos.MultiRowMutationService instance) throws IOException {
625                   ServerRpcController controller = new ServerRpcController();
626                   BlockingRpcCallback<MultiRowMutationProtos.MutateRowsResponse> rpcCallback = new BlockingRpcCallback<>();
627                   instance.mutateRows(controller, request, rpcCallback);
628                   return rpcCallback.get();
629                 }
630               });
631             fail("This cp should fail because the target lock is blocked by previous put");
632           } catch (Throwable ex) {
633           }
634         }
635       });
636       cpService.shutdown();
637       cpService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
638       WatiingForMultiMutationsObserver observer = find(tableName, WatiingForMultiMutationsObserver.class);
639       observer.latch.countDown();
640       putService.shutdown();
641       putService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
642       try (Table table = con.getTable(tableName)) {
643         Get g0 = new Get(row);
644         Get g1 = new Get(rowLocked);
645         Result r0 = table.get(g0);
646         Result r1 = table.get(g1);
647         assertTrue(r0.isEmpty());
648         assertFalse(r1.isEmpty());
649         assertTrue(Bytes.equals(r1.getValue(FAMILY, QUALIFIER), value0));
650       }
651       assertNoLocks(tableName);
652     }
653   }
654 
655   private static void assertNoLocks(final TableName tableName) throws IOException, InterruptedException {
656     HRegion region = (HRegion) find(tableName);
657     assertEquals(0, region.getLockedRows().size());
658   }
659   private static Region find(final TableName tableName)
660       throws IOException, InterruptedException {
661     HRegionServer rs = TEST_UTIL.getRSForFirstRegionInTable(tableName);
662     List<Region> regions = rs.getOnlineRegions(tableName);
663     assertEquals(1, regions.size());
664     return regions.get(0);
665   }
666 
667   private static <T extends RegionObserver> T find(final TableName tableName,
668           Class<T> clz) throws IOException, InterruptedException {
669     Region region = find(tableName);
670     Coprocessor cp = region.getCoprocessorHost().findCoprocessor(clz.getName());
671     assertTrue("The cp instance should be " + clz.getName()
672             + ", current instance is " + cp.getClass().getName(), clz.isInstance(cp));
673     return clz.cast(cp);
674   }
675 
676   public static class WatiingForMultiMutationsObserver extends BaseRegionObserver {
677     final CountDownLatch latch = new CountDownLatch(1);
678     @Override
679     public void preBatchMutate(final ObserverContext<RegionCoprocessorEnvironment> c,
680             final MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
681       try {
682         latch.await();
683       } catch (InterruptedException ex) {
684         throw new IOException(ex);
685       }
686     }
687   }
688 }