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 final byte [] ROW = Bytes.toBytes("testRow");
83    private static final byte[] ANOTHERROW = Bytes.toBytes("anotherrow");
84    private static final byte [] QUALIFIER = Bytes.toBytes("testQualifier");
85    private static final byte [] VALUE = Bytes.toBytes("testValue");
86    private static final byte[] COL_QUAL = Bytes.toBytes("f1");
87    private static final byte[] VAL_BYTES = Bytes.toBytes("v1");
88    private static final 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     desc.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     }
220   }
221 
222   @Test
223   public void testScanAfterDeletingSpecifiedRowV2() throws IOException {
224     TableName tableName = TableName.valueOf("testScanAfterDeletingSpecifiedRowV2");
225     HTableDescriptor desc = new HTableDescriptor(tableName);
226     desc.addFamily(new HColumnDescriptor(FAMILY));
227     TEST_UTIL.getHBaseAdmin().createTable(desc);
228     byte[] row = Bytes.toBytes("SpecifiedRow");
229     byte[] qual0 = Bytes.toBytes("qual0");
230     byte[] qual1 = Bytes.toBytes("qual1");
231     try (Table t = TEST_UTIL.getConnection().getTable(tableName)) {
232       Delete d = new Delete(row);
233       t.delete(d);
234 
235       Put put = new Put(row);
236       put.addColumn(FAMILY, null, VALUE);
237       t.put(put);
238 
239       put = new Put(row);
240       put.addColumn(FAMILY, qual1, qual1);
241       t.put(put);
242 
243       put = new Put(row);
244       put.addColumn(FAMILY, qual0, qual0);
245       t.put(put);
246 
247       Result r = t.get(new Get(row));
248       assertEquals(3, r.size());
249       assertEquals("testValue", Bytes.toString(CellUtil.cloneValue(r.rawCells()[0])));
250       assertEquals("qual0", Bytes.toString(CellUtil.cloneValue(r.rawCells()[1])));
251       assertEquals("qual1", Bytes.toString(CellUtil.cloneValue(r.rawCells()[2])));
252 
253       TEST_UTIL.getHBaseAdmin().flush(tableName);
254       r = t.get(new Get(row));
255       assertEquals(3, r.size());
256       assertEquals("testValue", Bytes.toString(CellUtil.cloneValue(r.rawCells()[0])));
257       assertEquals("qual0", Bytes.toString(CellUtil.cloneValue(r.rawCells()[1])));
258       assertEquals("qual1", Bytes.toString(CellUtil.cloneValue(r.rawCells()[2])));
259     }
260   }
261 
262   // override the config settings at the CF level and ensure priority
263   @Test(timeout = 60000)
264   public void testAdvancedConfigOverride() throws Exception {
265     /*
266      * Overall idea: (1) create 3 store files and issue a compaction. config's
267      * compaction.min == 3, so should work. (2) Increase the compaction.min
268      * toggle in the HTD to 5 and modify table. If we use the HTD value instead
269      * of the default config value, adding 3 files and issuing a compaction
270      * SHOULD NOT work (3) Decrease the compaction.min toggle in the HCD to 2
271      * and modify table. The CF schema should override the Table schema and now
272      * cause a minor compaction.
273      */
274     TEST_UTIL.getConfiguration().setInt("hbase.hstore.compaction.min", 3);
275 
276     String tableName = "testAdvancedConfigOverride";
277     TableName TABLE = TableName.valueOf(tableName);
278     HTable hTable = TEST_UTIL.createTable(TABLE, FAMILY, 10);
279     HBaseAdmin admin = TEST_UTIL.getHBaseAdmin();
280     ClusterConnection connection = (ClusterConnection)TEST_UTIL.getConnection();
281 
282     // Create 3 store files.
283     byte[] row = Bytes.toBytes(random.nextInt());
284     performMultiplePutAndFlush(admin, hTable, row, FAMILY, 3, 100);
285 
286     // Verify we have multiple store files.
287     HRegionLocation loc = hTable.getRegionLocation(row, true);
288     byte[] regionName = loc.getRegionInfo().getRegionName();
289     AdminProtos.AdminService.BlockingInterface server =
290       connection.getAdmin(loc.getServerName());
291     assertTrue(ProtobufUtil.getStoreFiles(
292       server, regionName, FAMILY).size() > 1);
293 
294     // Issue a compaction request
295     admin.compact(TABLE.getName());
296 
297     // poll wait for the compactions to happen
298     for (int i = 0; i < 10 * 1000 / 40; ++i) {
299       // The number of store files after compaction should be lesser.
300       loc = hTable.getRegionLocation(row, true);
301       if (!loc.getRegionInfo().isOffline()) {
302         regionName = loc.getRegionInfo().getRegionName();
303         server = connection.getAdmin(loc.getServerName());
304         if (ProtobufUtil.getStoreFiles(
305             server, regionName, FAMILY).size() <= 1) {
306           break;
307         }
308       }
309       Thread.sleep(40);
310     }
311     // verify the compactions took place and that we didn't just time out
312     assertTrue(ProtobufUtil.getStoreFiles(
313       server, regionName, FAMILY).size() <= 1);
314 
315     // change the compaction.min config option for this table to 5
316     LOG.info("hbase.hstore.compaction.min should now be 5");
317     HTableDescriptor htd = new HTableDescriptor(hTable.getTableDescriptor());
318     htd.setValue("hbase.hstore.compaction.min", String.valueOf(5));
319     admin.modifyTable(TABLE, htd);
320     Pair<Integer, Integer> st;
321     while (null != (st = admin.getAlterStatus(TABLE)) && st.getFirst() > 0) {
322       LOG.debug(st.getFirst() + " regions left to update");
323       Thread.sleep(40);
324     }
325     LOG.info("alter status finished");
326 
327     // Create 3 more store files.
328     performMultiplePutAndFlush(admin, hTable, row, FAMILY, 3, 10);
329 
330     // Issue a compaction request
331     admin.compact(TABLE.getName());
332 
333     // This time, the compaction request should not happen
334     Thread.sleep(10 * 1000);
335     loc = hTable.getRegionLocation(row, true);
336     regionName = loc.getRegionInfo().getRegionName();
337     server = connection.getAdmin(loc.getServerName());
338     int sfCount = ProtobufUtil.getStoreFiles(
339       server, regionName, FAMILY).size();
340     assertTrue(sfCount > 1);
341 
342     // change an individual CF's config option to 2 & online schema update
343     LOG.info("hbase.hstore.compaction.min should now be 2");
344     HColumnDescriptor hcd = new HColumnDescriptor(htd.getFamily(FAMILY));
345     hcd.setValue("hbase.hstore.compaction.min", String.valueOf(2));
346     htd.modifyFamily(hcd);
347     admin.modifyTable(TABLE, htd);
348     while (null != (st = admin.getAlterStatus(TABLE)) && st.getFirst() > 0) {
349       LOG.debug(st.getFirst() + " regions left to update");
350       Thread.sleep(40);
351     }
352     LOG.info("alter status finished");
353 
354     // Issue a compaction request
355     admin.compact(TABLE.getName());
356 
357     // poll wait for the compactions to happen
358     for (int i = 0; i < 10 * 1000 / 40; ++i) {
359       loc = hTable.getRegionLocation(row, true);
360       regionName = loc.getRegionInfo().getRegionName();
361       try {
362         server = connection.getAdmin(loc.getServerName());
363         if (ProtobufUtil.getStoreFiles(
364             server, regionName, FAMILY).size() < sfCount) {
365           break;
366         }
367       } catch (Exception e) {
368         LOG.debug("Waiting for region to come online: " + Bytes.toString(regionName));
369       }
370       Thread.sleep(40);
371     }
372     // verify the compaction took place and that we didn't just time out
373     assertTrue(ProtobufUtil.getStoreFiles(
374       server, regionName, FAMILY).size() < sfCount);
375 
376     // Finally, ensure that we can remove a custom config value after we made it
377     LOG.info("Removing CF config value");
378     LOG.info("hbase.hstore.compaction.min should now be 5");
379     hcd = new HColumnDescriptor(htd.getFamily(FAMILY));
380     hcd.setValue("hbase.hstore.compaction.min", null);
381     htd.modifyFamily(hcd);
382     admin.modifyTable(TABLE, htd);
383     while (null != (st = admin.getAlterStatus(TABLE)) && st.getFirst() > 0) {
384       LOG.debug(st.getFirst() + " regions left to update");
385       Thread.sleep(40);
386     }
387     LOG.info("alter status finished");
388     assertNull(hTable.getTableDescriptor().getFamily(FAMILY).getValue(
389         "hbase.hstore.compaction.min"));
390   }
391 
392   @Test
393   public void testHTableBatchWithEmptyPut() throws Exception {
394     Table table = TEST_UTIL.createTable(
395       Bytes.toBytes("testHTableBatchWithEmptyPut"), new byte[][] { FAMILY });
396     try {
397       List actions = (List) new ArrayList();
398       Object[] results = new Object[2];
399       // create an empty Put
400       Put put1 = new Put(ROW);
401       actions.add(put1);
402 
403       Put put2 = new Put(ANOTHERROW);
404       put2.add(FAMILY, QUALIFIER, VALUE);
405       actions.add(put2);
406 
407       table.batch(actions, results);
408       fail("Empty Put should have failed the batch call");
409     } catch (IllegalArgumentException iae) {
410 
411     } finally {
412       table.close();
413     }
414   }
415 
416   // Test Table.batch with large amount of mutations against the same key.
417   // It used to trigger read lock's "Maximum lock count exceeded" Error.
418   @Test
419   public void testHTableWithLargeBatch() throws Exception {
420     Table table = TEST_UTIL.createTable(TableName.valueOf("testHTableWithLargeBatch"),
421         new byte[][] { FAMILY });
422     int sixtyFourK = 64 * 1024;
423     try {
424       List actions = new ArrayList();
425       Object[] results = new Object[(sixtyFourK + 1) * 2];
426 
427       for (int i = 0; i < sixtyFourK + 1; i ++) {
428         Put put1 = new Put(ROW);
429         put1.addColumn(FAMILY, QUALIFIER, VALUE);
430         actions.add(put1);
431 
432         Put put2 = new Put(ANOTHERROW);
433         put2.addColumn(FAMILY, QUALIFIER, VALUE);
434         actions.add(put2);
435       }
436 
437       table.batch(actions, results);
438     } finally {
439       table.close();
440     }
441   }
442 
443   @Test
444   public void testBatchWithRowMutation() throws Exception {
445     LOG.info("Starting testBatchWithRowMutation");
446     final TableName TABLENAME = TableName.valueOf("testBatchWithRowMutation");
447     try (Table t = TEST_UTIL.createTable(TABLENAME, FAMILY)) {
448       byte [][] QUALIFIERS = new byte [][] {
449         Bytes.toBytes("a"), Bytes.toBytes("b")
450       };
451       RowMutations arm = new RowMutations(ROW);
452       Put p = new Put(ROW);
453       p.addColumn(FAMILY, QUALIFIERS[0], VALUE);
454       arm.add(p);
455       Object[] batchResult = new Object[1];
456       t.batch(Arrays.asList(arm), batchResult);
457 
458       Get g = new Get(ROW);
459       Result r = t.get(g);
460       assertEquals(0, Bytes.compareTo(VALUE, r.getValue(FAMILY, QUALIFIERS[0])));
461 
462       arm = new RowMutations(ROW);
463       p = new Put(ROW);
464       p.addColumn(FAMILY, QUALIFIERS[1], VALUE);
465       arm.add(p);
466       Delete d = new Delete(ROW);
467       d.addColumns(FAMILY, QUALIFIERS[0]);
468       arm.add(d);
469       t.batch(Arrays.asList(arm), batchResult);
470       r = t.get(g);
471       assertEquals(0, Bytes.compareTo(VALUE, r.getValue(FAMILY, QUALIFIERS[1])));
472       assertNull(r.getValue(FAMILY, QUALIFIERS[0]));
473 
474       // Test that we get the correct remote exception for RowMutations from batch()
475       try {
476         arm = new RowMutations(ROW);
477         p = new Put(ROW);
478         p.addColumn(new byte[]{'b', 'o', 'g', 'u', 's'}, QUALIFIERS[0], VALUE);
479         arm.add(p);
480         t.batch(Arrays.asList(arm), batchResult);
481         fail("Expected RetriesExhaustedWithDetailsException with NoSuchColumnFamilyException");
482       } catch (RetriesExhaustedWithDetailsException e) {
483         String msg = e.getMessage();
484         assertTrue(msg.contains("NoSuchColumnFamilyException"));
485       }
486     }
487   }
488 
489   @Test
490   public void testHTableExistsMethodSingleRegionSingleGet() throws Exception {
491 
492     // Test with a single region table.
493 
494     Table table = TEST_UTIL.createTable(
495       Bytes.toBytes("testHTableExistsMethodSingleRegionSingleGet"), new byte[][] { FAMILY });
496 
497     Put put = new Put(ROW);
498     put.add(FAMILY, QUALIFIER, VALUE);
499 
500     Get get = new Get(ROW);
501 
502     boolean exist = table.exists(get);
503     assertEquals(exist, false);
504 
505     table.put(put);
506 
507     exist = table.exists(get);
508     assertEquals(exist, true);
509   }
510 
511   @Test
512   public void testHTableExistsMethodSingleRegionMultipleGets() throws Exception {
513 
514     HTable table = TEST_UTIL.createTable(
515       Bytes.toBytes("testHTableExistsMethodSingleRegionMultipleGets"), new byte[][] { FAMILY });
516 
517     Put put = new Put(ROW);
518     put.add(FAMILY, QUALIFIER, VALUE);
519     table.put(put);
520 
521     List<Get> gets = new ArrayList<Get>();
522     gets.add(new Get(ROW));
523     gets.add(new Get(ANOTHERROW));
524 
525     Boolean[] results = table.exists(gets);
526     assertTrue(results[0]);
527     assertFalse(results[1]);
528   }
529 
530   @Test
531   public void testHTableExistsBeforeGet() throws Exception {
532     Table table = TEST_UTIL.createTable(
533       Bytes.toBytes("testHTableExistsBeforeGet"), new byte[][] { FAMILY });
534     try {
535       Put put = new Put(ROW);
536       put.add(FAMILY, QUALIFIER, VALUE);
537       table.put(put);
538 
539       Get get = new Get(ROW);
540 
541       boolean exist = table.exists(get);
542       assertEquals(true, exist);
543 
544       Result result = table.get(get);
545       assertEquals(false, result.isEmpty());
546       assertTrue(Bytes.equals(VALUE, result.getValue(FAMILY, QUALIFIER)));
547     } finally {
548       table.close();
549     }
550   }
551 
552   @Test
553   public void testHTableExistsAllBeforeGet() throws Exception {
554     final byte[] ROW2 = Bytes.add(ROW, Bytes.toBytes("2"));
555     Table table = TEST_UTIL.createTable(
556       Bytes.toBytes("testHTableExistsAllBeforeGet"), new byte[][] { FAMILY });
557     try {
558       Put put = new Put(ROW);
559       put.add(FAMILY, QUALIFIER, VALUE);
560       table.put(put);
561       put = new Put(ROW2);
562       put.add(FAMILY, QUALIFIER, VALUE);
563       table.put(put);
564 
565       Get get = new Get(ROW);
566       Get get2 = new Get(ROW2);
567       ArrayList<Get> getList = new ArrayList(2);
568       getList.add(get);
569       getList.add(get2);
570 
571       boolean[] exists = table.existsAll(getList);
572       assertEquals(true, exists[0]);
573       assertEquals(true, exists[1]);
574 
575       Result[] result = table.get(getList);
576       assertEquals(false, result[0].isEmpty());
577       assertTrue(Bytes.equals(VALUE, result[0].getValue(FAMILY, QUALIFIER)));
578       assertEquals(false, result[1].isEmpty());
579       assertTrue(Bytes.equals(VALUE, result[1].getValue(FAMILY, QUALIFIER)));
580     } finally {
581       table.close();
582     }
583   }
584 
585   @Test
586   public void testHTableExistsMethodMultipleRegionsSingleGet() throws Exception {
587 
588     Table table = TEST_UTIL.createTable(
589       TableName.valueOf("testHTableExistsMethodMultipleRegionsSingleGet"), new byte[][] { FAMILY },
590       1, new byte[] { 0x00 }, new byte[] { (byte) 0xff }, 255);
591     Put put = new Put(ROW);
592     put.add(FAMILY, QUALIFIER, VALUE);
593 
594     Get get = new Get(ROW);
595 
596     boolean exist = table.exists(get);
597     assertEquals(exist, false);
598 
599     table.put(put);
600 
601     exist = table.exists(get);
602     assertEquals(exist, true);
603   }
604 
605   @Test
606   public void testHTableExistsMethodMultipleRegionsMultipleGets() throws Exception {
607     HTable table = TEST_UTIL.createTable(
608       TableName.valueOf("testHTableExistsMethodMultipleRegionsMultipleGets"),
609       new byte[][] { FAMILY }, 1, new byte[] { 0x00 }, new byte[] { (byte) 0xff }, 255);
610     Put put = new Put(ROW);
611     put.add(FAMILY, QUALIFIER, VALUE);
612     table.put (put);
613 
614     List<Get> gets = new ArrayList<Get>();
615     gets.add(new Get(ANOTHERROW));
616     gets.add(new Get(Bytes.add(ROW, new byte[] { 0x00 })));
617     gets.add(new Get(ROW));
618     gets.add(new Get(Bytes.add(ANOTHERROW, new byte[] { 0x00 })));
619 
620     LOG.info("Calling exists");
621     Boolean[] results = table.exists(gets);
622     assertEquals(results[0], false);
623     assertEquals(results[1], false);
624     assertEquals(results[2], true);
625     assertEquals(results[3], false);
626 
627     // Test with the first region.
628     put = new Put(new byte[] { 0x00 });
629     put.add(FAMILY, QUALIFIER, VALUE);
630     table.put(put);
631 
632     gets = new ArrayList<Get>();
633     gets.add(new Get(new byte[] { 0x00 }));
634     gets.add(new Get(new byte[] { 0x00, 0x00 }));
635     results = table.exists(gets);
636     assertEquals(results[0], true);
637     assertEquals(results[1], false);
638 
639     // Test with the last region
640     put = new Put(new byte[] { (byte) 0xff, (byte) 0xff });
641     put.add(FAMILY, QUALIFIER, VALUE);
642     table.put(put);
643 
644     gets = new ArrayList<Get>();
645     gets.add(new Get(new byte[] { (byte) 0xff }));
646     gets.add(new Get(new byte[] { (byte) 0xff, (byte) 0xff }));
647     gets.add(new Get(new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff }));
648     results = table.exists(gets);
649     assertEquals(results[0], false);
650     assertEquals(results[1], true);
651     assertEquals(results[2], false);
652   }
653 
654   @Test
655   public void testGetEmptyRow() throws Exception {
656     //Create a table and put in 1 row
657     Admin admin = TEST_UTIL.getHBaseAdmin();
658     HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(Bytes.toBytes("test")));
659     desc.addFamily(new HColumnDescriptor(FAMILY));
660     admin.createTable(desc);
661     Table table = new HTable(TEST_UTIL.getConfiguration(), desc.getTableName());
662 
663     Put put = new Put(ROW_BYTES);
664     put.add(FAMILY, COL_QUAL, VAL_BYTES);
665     table.put(put);
666 
667     //Try getting the row with an empty row key
668     Result res = null;
669     try {
670       res = table.get(new Get(new byte[0]));
671       fail();
672     } catch (IllegalArgumentException e) {
673       // Expected.
674     }
675     assertTrue(res == null);
676     res = table.get(new Get(Bytes.toBytes("r1-not-exist")));
677     assertTrue(res.isEmpty() == true);
678     res = table.get(new Get(ROW_BYTES));
679     assertTrue(Arrays.equals(res.getValue(FAMILY, COL_QUAL), VAL_BYTES));
680     table.close();
681   }
682 
683   @Test(timeout = 30000)
684   public void testMultiRowMutations() throws Exception, Throwable {
685     final TableName tableName = TableName.valueOf("testMultiRowMutations");
686     HTableDescriptor desc = new HTableDescriptor(tableName);
687     desc.addCoprocessor(MultiRowMutationEndpoint.class.getName());
688     desc.addCoprocessor(WatiingForMultiMutationsObserver.class.getName());
689     desc.setConfiguration("hbase.rowlock.wait.duration", String.valueOf(5000));
690     desc.addFamily(new HColumnDescriptor(FAMILY));
691     TEST_UTIL.getHBaseAdmin().createTable(desc);
692     // new a connection for lower retry number.
693     Configuration copy = new Configuration(TEST_UTIL.getConfiguration());
694     copy.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 2);
695     try (Connection con = ConnectionFactory.createConnection(copy)) {
696       final byte[] row = Bytes.toBytes("ROW-0");
697       final byte[] rowLocked= Bytes.toBytes("ROW-1");
698       final byte[] value0 = Bytes.toBytes("VALUE-0");
699       final byte[] value1 = Bytes.toBytes("VALUE-1");
700       final byte[] value2 = Bytes.toBytes("VALUE-2");
701       assertNoLocks(tableName);
702       ExecutorService putService = Executors.newSingleThreadExecutor();
703       putService.execute(new Runnable() {
704         @Override
705         public void run() {
706           try (Table table = con.getTable(tableName)) {
707             Put put0 = new Put(rowLocked);
708             put0.addColumn(FAMILY, QUALIFIER, value0);
709             // the put will be blocked by WatiingForMultiMutationsObserver.
710             table.put(put0);
711           } catch (IOException ex) {
712             throw new RuntimeException(ex);
713           }
714         }
715       });
716       ExecutorService cpService = Executors.newSingleThreadExecutor();
717       cpService.execute(new Runnable() {
718         @Override
719         public void run() {
720           boolean threw;
721           Put put1 = new Put(row);
722           Put put2 = new Put(rowLocked);
723           put1.addColumn(FAMILY, QUALIFIER, value1);
724           put2.addColumn(FAMILY, QUALIFIER, value2);
725           try (Table table = con.getTable(tableName)) {
726             final MultiRowMutationProtos.MutateRowsRequest request
727               = MultiRowMutationProtos.MutateRowsRequest.newBuilder()
728                 .addMutationRequest(org.apache.hadoop.hbase.protobuf.ProtobufUtil.toMutation(
729                         org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.MutationType.PUT, put1))
730                 .addMutationRequest(org.apache.hadoop.hbase.protobuf.ProtobufUtil.toMutation(
731                         org.apache.hadoop.hbase.protobuf.generated.ClientProtos.MutationProto.MutationType.PUT, put2))
732                 .build();
733             table.coprocessorService(MultiRowMutationProtos.MultiRowMutationService.class, ROW, ROW,
734               new Batch.Call<MultiRowMutationProtos.MultiRowMutationService, MultiRowMutationProtos.MutateRowsResponse>() {
735                 public MultiRowMutationProtos.MutateRowsResponse call(MultiRowMutationProtos.MultiRowMutationService instance) throws IOException {
736                   ServerRpcController controller = new ServerRpcController();
737                   BlockingRpcCallback<MultiRowMutationProtos.MutateRowsResponse> rpcCallback = new BlockingRpcCallback<>();
738                   instance.mutateRows(controller, request, rpcCallback);
739                   return rpcCallback.get();
740                 }
741               });
742             threw = false;
743           } catch (Throwable ex) {
744             threw = true;
745           }
746           if (!threw) {
747             // Can't call fail() earlier because the catch would eat it.
748             fail("This cp should fail because the target lock is blocked by previous put");
749           }
750         }
751       });
752       cpService.shutdown();
753       cpService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
754       WatiingForMultiMutationsObserver observer = find(tableName, WatiingForMultiMutationsObserver.class);
755       observer.latch.countDown();
756       putService.shutdown();
757       putService.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS);
758       try (Table table = con.getTable(tableName)) {
759         Get g0 = new Get(row);
760         Get g1 = new Get(rowLocked);
761         Result r0 = table.get(g0);
762         Result r1 = table.get(g1);
763         assertTrue(r0.isEmpty());
764         assertFalse(r1.isEmpty());
765         assertTrue(Bytes.equals(r1.getValue(FAMILY, QUALIFIER), value0));
766       }
767       assertNoLocks(tableName);
768     }
769   }
770 
771   private static void assertNoLocks(final TableName tableName) throws IOException, InterruptedException {
772     HRegion region = (HRegion) find(tableName);
773     assertEquals(0, region.getLockedRows().size());
774   }
775   private static Region find(final TableName tableName)
776       throws IOException, InterruptedException {
777     HRegionServer rs = TEST_UTIL.getRSForFirstRegionInTable(tableName);
778     List<Region> regions = rs.getOnlineRegions(tableName);
779     assertEquals(1, regions.size());
780     return regions.get(0);
781   }
782 
783   private static <T extends RegionObserver> T find(final TableName tableName,
784           Class<T> clz) throws IOException, InterruptedException {
785     Region region = find(tableName);
786     Coprocessor cp = region.getCoprocessorHost().findCoprocessor(clz.getName());
787     assertTrue("The cp instance should be " + clz.getName()
788             + ", current instance is " + cp.getClass().getName(), clz.isInstance(cp));
789     return clz.cast(cp);
790   }
791 
792   public static class WatiingForMultiMutationsObserver extends BaseRegionObserver {
793     final CountDownLatch latch = new CountDownLatch(1);
794     @Override
795     public void preBatchMutate(final ObserverContext<RegionCoprocessorEnvironment> c,
796             final MiniBatchOperationInProgress<Mutation> miniBatchOp) throws IOException {
797       try {
798         latch.await();
799       } catch (InterruptedException ex) {
800         throw new IOException(ex);
801       }
802     }
803   }
804 }