001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.client;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertFalse;
022import static org.junit.Assert.assertNotNull;
023import static org.junit.Assert.assertTrue;
024import static org.junit.Assert.fail;
025
026import java.io.IOException;
027import java.util.ArrayList;
028import java.util.HashMap;
029import java.util.Iterator;
030import java.util.List;
031import java.util.Map;
032import java.util.concurrent.TimeUnit;
033import java.util.concurrent.atomic.AtomicInteger;
034
035import org.apache.hadoop.hbase.HBaseClassTestRule;
036import org.apache.hadoop.hbase.HBaseTestingUtility;
037import org.apache.hadoop.hbase.HColumnDescriptor;
038import org.apache.hadoop.hbase.HConstants;
039import org.apache.hadoop.hbase.HRegionLocation;
040import org.apache.hadoop.hbase.HTableDescriptor;
041import org.apache.hadoop.hbase.InvalidFamilyOperationException;
042import org.apache.hadoop.hbase.MetaTableAccessor;
043import org.apache.hadoop.hbase.ServerName;
044import org.apache.hadoop.hbase.TableName;
045import org.apache.hadoop.hbase.TableNotDisabledException;
046import org.apache.hadoop.hbase.TableNotEnabledException;
047import org.apache.hadoop.hbase.TableNotFoundException;
048import org.apache.hadoop.hbase.exceptions.MergeRegionException;
049import org.apache.hadoop.hbase.master.LoadBalancer;
050import org.apache.hadoop.hbase.regionserver.DisabledRegionSplitPolicy;
051import org.apache.hadoop.hbase.regionserver.HRegion;
052import org.apache.hadoop.hbase.regionserver.HStore;
053import org.apache.hadoop.hbase.regionserver.HStoreFile;
054import org.apache.hadoop.hbase.testclassification.ClientTests;
055import org.apache.hadoop.hbase.testclassification.LargeTests;
056import org.apache.hadoop.hbase.util.Bytes;
057import org.apache.hadoop.hbase.util.FSUtils;
058import org.apache.hadoop.hbase.util.Pair;
059import org.apache.hadoop.hbase.util.Threads;
060import org.junit.After;
061import org.junit.AfterClass;
062import org.junit.Before;
063import org.junit.BeforeClass;
064import org.junit.ClassRule;
065import org.junit.Rule;
066import org.junit.Test;
067import org.junit.experimental.categories.Category;
068import org.junit.rules.TestName;
069import org.slf4j.Logger;
070import org.slf4j.LoggerFactory;
071import org.apache.hadoop.hbase.shaded.protobuf.RequestConverter;
072import org.apache.hadoop.hbase.shaded.protobuf.generated.MasterProtos.MergeTableRegionsRequest;
073
074/**
075 * Class to test HBaseAdmin.
076 * Spins up the minicluster once at test start and then takes it down afterward.
077 * Add any testing of HBaseAdmin functionality here.
078 */
079@Category({LargeTests.class, ClientTests.class})
080public class TestAdmin1 {
081
082  @ClassRule
083  public static final HBaseClassTestRule CLASS_RULE =
084      HBaseClassTestRule.forClass(TestAdmin1.class);
085
086  private static final Logger LOG = LoggerFactory.getLogger(TestAdmin1.class);
087  private final static HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
088  private Admin admin;
089
090  @Rule
091  public TestName name = new TestName();
092
093  @BeforeClass
094  public static void setUpBeforeClass() throws Exception {
095    TEST_UTIL.getConfiguration().setInt("hbase.regionserver.msginterval", 100);
096    TEST_UTIL.getConfiguration().setInt("hbase.client.pause", 250);
097    TEST_UTIL.getConfiguration().setInt("hbase.client.retries.number", 6);
098    TEST_UTIL.getConfiguration().setBoolean("hbase.master.enabletable.roundrobin", true);
099    TEST_UTIL.startMiniCluster(3);
100  }
101
102  @AfterClass
103  public static void tearDownAfterClass() throws Exception {
104    TEST_UTIL.shutdownMiniCluster();
105  }
106
107  @Before
108  public void setUp() throws Exception {
109    this.admin = TEST_UTIL.getAdmin();
110  }
111
112  @After
113  public void tearDown() throws Exception {
114    for (HTableDescriptor htd : this.admin.listTables()) {
115      TEST_UTIL.deleteTable(htd.getTableName());
116    }
117  }
118
119  @Test
120  public void testSplitFlushCompactUnknownTable() throws InterruptedException {
121    final TableName unknowntable = TableName.valueOf(name.getMethodName());
122    Exception exception = null;
123    try {
124      this.admin.compact(unknowntable);
125    } catch (IOException e) {
126      exception = e;
127    }
128    assertTrue(exception instanceof TableNotFoundException);
129
130    exception = null;
131    try {
132      this.admin.flush(unknowntable);
133    } catch (IOException e) {
134      exception = e;
135    }
136    assertTrue(exception instanceof TableNotFoundException);
137
138    exception = null;
139    try {
140      this.admin.split(unknowntable);
141    } catch (IOException e) {
142      exception = e;
143    }
144    assertTrue(exception instanceof TableNotFoundException);
145  }
146
147  @Test
148  public void testDeleteEditUnknownColumnFamilyAndOrTable() throws IOException {
149    // Test we get exception if we try to
150    final TableName nonexistentTable = TableName.valueOf("nonexistent");
151    final byte[] nonexistentColumn = Bytes.toBytes("nonexistent");
152    HColumnDescriptor nonexistentHcd = new HColumnDescriptor(nonexistentColumn);
153    Exception exception = null;
154    try {
155      this.admin.addColumnFamily(nonexistentTable, nonexistentHcd);
156    } catch (IOException e) {
157      exception = e;
158    }
159    assertTrue(exception instanceof TableNotFoundException);
160
161    exception = null;
162    try {
163      this.admin.deleteTable(nonexistentTable);
164    } catch (IOException e) {
165      exception = e;
166    }
167    assertTrue(exception instanceof TableNotFoundException);
168
169    exception = null;
170    try {
171      this.admin.deleteColumnFamily(nonexistentTable, nonexistentColumn);
172    } catch (IOException e) {
173      exception = e;
174    }
175    assertTrue(exception instanceof TableNotFoundException);
176
177    exception = null;
178    try {
179      this.admin.disableTable(nonexistentTable);
180    } catch (IOException e) {
181      exception = e;
182    }
183    assertTrue(exception instanceof TableNotFoundException);
184
185    exception = null;
186    try {
187      this.admin.enableTable(nonexistentTable);
188    } catch (IOException e) {
189      exception = e;
190    }
191    assertTrue(exception instanceof TableNotFoundException);
192
193    exception = null;
194    try {
195      this.admin.modifyColumnFamily(nonexistentTable, nonexistentHcd);
196    } catch (IOException e) {
197      exception = e;
198    }
199    assertTrue(exception instanceof TableNotFoundException);
200
201    exception = null;
202    try {
203      HTableDescriptor htd = new HTableDescriptor(nonexistentTable);
204      htd.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
205      this.admin.modifyTable(htd.getTableName(), htd);
206    } catch (IOException e) {
207      exception = e;
208    }
209    assertTrue(exception instanceof TableNotFoundException);
210
211    // Now make it so at least the table exists and then do tests against a
212    // nonexistent column family -- see if we get right exceptions.
213    final TableName tableName = TableName.valueOf(name.getMethodName() + System.currentTimeMillis());
214    HTableDescriptor htd = new HTableDescriptor(tableName);
215    htd.addFamily(new HColumnDescriptor("cf"));
216    this.admin.createTable(htd);
217    try {
218      exception = null;
219      try {
220        this.admin.deleteColumnFamily(htd.getTableName(), nonexistentHcd.getName());
221      } catch (IOException e) {
222        exception = e;
223      }
224      assertTrue("found=" + exception.getClass().getName(),
225          exception instanceof InvalidFamilyOperationException);
226
227      exception = null;
228      try {
229        this.admin.modifyColumnFamily(htd.getTableName(), nonexistentHcd);
230      } catch (IOException e) {
231        exception = e;
232      }
233      assertTrue("found=" + exception.getClass().getName(),
234          exception instanceof InvalidFamilyOperationException);
235    } finally {
236      this.admin.disableTable(tableName);
237      this.admin.deleteTable(tableName);
238    }
239  }
240
241  @Test
242  public void testDisableAndEnableTable() throws IOException {
243    final byte [] row = Bytes.toBytes("row");
244    final byte [] qualifier = Bytes.toBytes("qualifier");
245    final byte [] value = Bytes.toBytes("value");
246    final TableName table = TableName.valueOf(name.getMethodName());
247    Table ht = TEST_UTIL.createTable(table, HConstants.CATALOG_FAMILY);
248    Put put = new Put(row);
249    put.addColumn(HConstants.CATALOG_FAMILY, qualifier, value);
250    ht.put(put);
251    Get get = new Get(row);
252    get.addColumn(HConstants.CATALOG_FAMILY, qualifier);
253    ht.get(get);
254
255    this.admin.disableTable(ht.getName());
256    assertTrue("Table must be disabled.", TEST_UTIL.getHBaseCluster()
257        .getMaster().getTableStateManager().isTableState(
258            ht.getName(), TableState.State.DISABLED));
259    assertEquals(TableState.State.DISABLED, getStateFromMeta(table));
260
261    // Test that table is disabled
262    get = new Get(row);
263    get.addColumn(HConstants.CATALOG_FAMILY, qualifier);
264    boolean ok = false;
265    try {
266      ht.get(get);
267    } catch (TableNotEnabledException e) {
268      ok = true;
269    }
270    ok = false;
271    // verify that scan encounters correct exception
272    Scan scan = new Scan();
273    try {
274      ResultScanner scanner = ht.getScanner(scan);
275      Result res = null;
276      do {
277        res = scanner.next();
278      } while (res != null);
279    } catch (TableNotEnabledException e) {
280      ok = true;
281    }
282    assertTrue(ok);
283    this.admin.enableTable(table);
284    assertTrue("Table must be enabled.", TEST_UTIL.getHBaseCluster()
285        .getMaster().getTableStateManager().isTableState(
286            ht.getName(), TableState.State.ENABLED));
287    assertEquals(TableState.State.ENABLED, getStateFromMeta(table));
288
289    // Test that table is enabled
290    try {
291      ht.get(get);
292    } catch (RetriesExhaustedException e) {
293      ok = false;
294    }
295    assertTrue(ok);
296    ht.close();
297  }
298
299  private TableState.State getStateFromMeta(TableName table) throws IOException {
300    TableState state =
301        MetaTableAccessor.getTableState(TEST_UTIL.getConnection(), table);
302    assertNotNull(state);
303    return state.getState();
304  }
305
306  @Test
307  public void testDisableAndEnableTables() throws IOException {
308    final byte [] row = Bytes.toBytes("row");
309    final byte [] qualifier = Bytes.toBytes("qualifier");
310    final byte [] value = Bytes.toBytes("value");
311    final TableName table1 = TableName.valueOf(name.getMethodName() + "1");
312    final TableName table2 = TableName.valueOf(name.getMethodName() + "2");
313    Table ht1 = TEST_UTIL.createTable(table1, HConstants.CATALOG_FAMILY);
314    Table ht2 = TEST_UTIL.createTable(table2, HConstants.CATALOG_FAMILY);
315    Put put = new Put(row);
316    put.addColumn(HConstants.CATALOG_FAMILY, qualifier, value);
317    ht1.put(put);
318    ht2.put(put);
319    Get get = new Get(row);
320    get.addColumn(HConstants.CATALOG_FAMILY, qualifier);
321    ht1.get(get);
322    ht2.get(get);
323
324    this.admin.disableTables("testDisableAndEnableTable.*");
325
326    // Test that tables are disabled
327    get = new Get(row);
328    get.addColumn(HConstants.CATALOG_FAMILY, qualifier);
329    boolean ok = false;
330    try {
331      ht1.get(get);
332      ht2.get(get);
333    } catch (org.apache.hadoop.hbase.DoNotRetryIOException e) {
334      ok = true;
335    }
336
337    assertEquals(TableState.State.DISABLED, getStateFromMeta(table1));
338    assertEquals(TableState.State.DISABLED, getStateFromMeta(table2));
339
340
341    assertTrue(ok);
342    this.admin.enableTables("testDisableAndEnableTable.*");
343
344    // Test that tables are enabled
345    try {
346      ht1.get(get);
347    } catch (IOException e) {
348      ok = false;
349    }
350    try {
351      ht2.get(get);
352    } catch (IOException e) {
353      ok = false;
354    }
355    assertTrue(ok);
356
357    ht1.close();
358    ht2.close();
359
360    assertEquals(TableState.State.ENABLED, getStateFromMeta(table1));
361    assertEquals(TableState.State.ENABLED, getStateFromMeta(table2));
362  }
363
364  @Test
365  public void testCreateTable() throws IOException {
366    HTableDescriptor [] tables = admin.listTables();
367    int numTables = tables.length;
368    final TableName tableName = TableName.valueOf(name.getMethodName());
369    TEST_UTIL.createTable(tableName, HConstants.CATALOG_FAMILY).close();
370    tables = this.admin.listTables();
371    assertEquals(numTables + 1, tables.length);
372    assertTrue("Table must be enabled.",
373        TEST_UTIL.getHBaseCluster().getMaster().getTableStateManager()
374            .isTableState(tableName, TableState.State.ENABLED));
375    assertEquals(TableState.State.ENABLED, getStateFromMeta(tableName));
376  }
377
378  @Test
379  public void testTruncateTable() throws IOException {
380    testTruncateTable(TableName.valueOf(name.getMethodName()), false);
381  }
382
383  @Test
384  public void testTruncateTablePreservingSplits() throws IOException {
385    testTruncateTable(TableName.valueOf(name.getMethodName()), true);
386  }
387
388  private void testTruncateTable(final TableName tableName, boolean preserveSplits)
389      throws IOException {
390    byte[][] splitKeys = new byte[2][];
391    splitKeys[0] = Bytes.toBytes(4);
392    splitKeys[1] = Bytes.toBytes(8);
393
394    // Create & Fill the table
395    Table table = TEST_UTIL.createTable(tableName, HConstants.CATALOG_FAMILY, splitKeys);
396    try {
397      TEST_UTIL.loadNumericRows(table, HConstants.CATALOG_FAMILY, 0, 10);
398      assertEquals(10, TEST_UTIL.countRows(table));
399    } finally {
400      table.close();
401    }
402    assertEquals(3, TEST_UTIL.getHBaseCluster().getRegions(tableName).size());
403
404    // Truncate & Verify
405    this.admin.disableTable(tableName);
406    this.admin.truncateTable(tableName, preserveSplits);
407    table = TEST_UTIL.getConnection().getTable(tableName);
408    try {
409      assertEquals(0, TEST_UTIL.countRows(table));
410    } finally {
411      table.close();
412    }
413    if (preserveSplits) {
414      assertEquals(3, TEST_UTIL.getHBaseCluster().getRegions(tableName).size());
415    } else {
416      assertEquals(1, TEST_UTIL.getHBaseCluster().getRegions(tableName).size());
417    }
418  }
419
420  @Test
421  public void testGetTableDescriptor() throws IOException {
422    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
423    HColumnDescriptor fam2 = new HColumnDescriptor("fam2");
424    HColumnDescriptor fam3 = new HColumnDescriptor("fam3");
425    HTableDescriptor htd = new HTableDescriptor(TableName.valueOf(name.getMethodName()));
426    htd.addFamily(fam1);
427    htd.addFamily(fam2);
428    htd.addFamily(fam3);
429    this.admin.createTable(htd);
430    Table table = TEST_UTIL.getConnection().getTable(htd.getTableName());
431    TableDescriptor confirmedHtd = table.getDescriptor();
432    assertEquals(0, TableDescriptor.COMPARATOR.compare(htd, confirmedHtd));
433    MetaTableAccessor.fullScanMetaAndPrint(TEST_UTIL.getConnection());
434    table.close();
435  }
436
437  @Test
438  public void testCompactionTimestamps() throws Exception {
439    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
440    final TableName tableName = TableName.valueOf(name.getMethodName());
441    HTableDescriptor htd = new HTableDescriptor(tableName);
442    htd.addFamily(fam1);
443    this.admin.createTable(htd);
444    Table table = TEST_UTIL.getConnection().getTable(htd.getTableName());
445    long ts = this.admin.getLastMajorCompactionTimestamp(tableName);
446    assertEquals(0, ts);
447    Put p = new Put(Bytes.toBytes("row1"));
448    p.addColumn(Bytes.toBytes("fam1"), Bytes.toBytes("fam1"), Bytes.toBytes("fam1"));
449    table.put(p);
450    ts = this.admin.getLastMajorCompactionTimestamp(tableName);
451    // no files written -> no data
452    assertEquals(0, ts);
453
454    this.admin.flush(tableName);
455    ts = this.admin.getLastMajorCompactionTimestamp(tableName);
456    // still 0, we flushed a file, but no major compaction happened
457    assertEquals(0, ts);
458
459    byte[] regionName;
460    try (RegionLocator l = TEST_UTIL.getConnection().getRegionLocator(tableName)) {
461      regionName = l.getAllRegionLocations().get(0).getRegionInfo().getRegionName();
462    }
463    long ts1 = this.admin.getLastMajorCompactionTimestampForRegion(regionName);
464    assertEquals(ts, ts1);
465    p = new Put(Bytes.toBytes("row2"));
466    p.addColumn(Bytes.toBytes("fam1"), Bytes.toBytes("fam1"), Bytes.toBytes("fam1"));
467    table.put(p);
468    this.admin.flush(tableName);
469    ts = this.admin.getLastMajorCompactionTimestamp(tableName);
470    // make sure the region API returns the same value, as the old file is still around
471    assertEquals(ts1, ts);
472
473    TEST_UTIL.compact(tableName, true);
474    table.put(p);
475    // forces a wait for the compaction
476    this.admin.flush(tableName);
477    ts = this.admin.getLastMajorCompactionTimestamp(tableName);
478    // after a compaction our earliest timestamp will have progressed forward
479    assertTrue(ts > ts1);
480
481    // region api still the same
482    ts1 = this.admin.getLastMajorCompactionTimestampForRegion(regionName);
483    assertEquals(ts, ts1);
484    table.put(p);
485    this.admin.flush(tableName);
486    ts = this.admin.getLastMajorCompactionTimestamp(tableName);
487    assertEquals(ts, ts1);
488    table.close();
489  }
490
491  @Test
492  public void testHColumnValidName() {
493       boolean exceptionThrown;
494       try {
495         new HColumnDescriptor("\\test\\abc");
496       } catch(IllegalArgumentException iae) {
497           exceptionThrown = true;
498           assertTrue(exceptionThrown);
499       }
500   }
501
502  /**
503   * Verify schema modification takes.
504   * @throws IOException
505   * @throws InterruptedException
506   */
507  @Test
508  public void testOnlineChangeTableSchema() throws IOException, InterruptedException {
509    final TableName tableName = TableName.valueOf(name.getMethodName());
510    HTableDescriptor [] tables = admin.listTables();
511    int numTables = tables.length;
512    TEST_UTIL.createTable(tableName, HConstants.CATALOG_FAMILY).close();
513    tables = this.admin.listTables();
514    assertEquals(numTables + 1, tables.length);
515
516    // FIRST, do htabledescriptor changes.
517    HTableDescriptor htd = this.admin.getTableDescriptor(tableName);
518    // Make a copy and assert copy is good.
519    HTableDescriptor copy = new HTableDescriptor(htd);
520    assertTrue(htd.equals(copy));
521    // Now amend the copy. Introduce differences.
522    long newFlushSize = htd.getMemStoreFlushSize() / 2;
523    if (newFlushSize <=0) {
524      newFlushSize = HTableDescriptor.DEFAULT_MEMSTORE_FLUSH_SIZE / 2;
525    }
526    copy.setMemStoreFlushSize(newFlushSize);
527    final String key = "anyoldkey";
528    assertTrue(htd.getValue(key) == null);
529    copy.setValue(key, key);
530    boolean expectedException = false;
531    try {
532      admin.modifyTable(tableName, copy);
533    } catch (TableNotDisabledException re) {
534      expectedException = true;
535    }
536    assertFalse(expectedException);
537    HTableDescriptor modifiedHtd = new HTableDescriptor(this.admin.getTableDescriptor(tableName));
538    assertFalse(htd.equals(modifiedHtd));
539    assertTrue(copy.equals(modifiedHtd));
540    assertEquals(newFlushSize, modifiedHtd.getMemStoreFlushSize());
541    assertEquals(key, modifiedHtd.getValue(key));
542
543    // Now work on column family changes.
544    int countOfFamilies = modifiedHtd.getFamilies().size();
545    assertTrue(countOfFamilies > 0);
546    HColumnDescriptor hcd = modifiedHtd.getFamilies().iterator().next();
547    int maxversions = hcd.getMaxVersions();
548    final int newMaxVersions = maxversions + 1;
549    hcd.setMaxVersions(newMaxVersions);
550    final byte [] hcdName = hcd.getName();
551    expectedException = false;
552    try {
553      this.admin.modifyColumnFamily(tableName, hcd);
554    } catch (TableNotDisabledException re) {
555      expectedException = true;
556    }
557    assertFalse(expectedException);
558    modifiedHtd = this.admin.getTableDescriptor(tableName);
559    HColumnDescriptor modifiedHcd = modifiedHtd.getFamily(hcdName);
560    assertEquals(newMaxVersions, modifiedHcd.getMaxVersions());
561
562    // Try adding a column
563    assertFalse(this.admin.isTableDisabled(tableName));
564    final String xtracolName = "xtracol";
565    HColumnDescriptor xtracol = new HColumnDescriptor(xtracolName);
566    xtracol.setValue(xtracolName, xtracolName);
567    expectedException = false;
568    try {
569      this.admin.addColumnFamily(tableName, xtracol);
570    } catch (TableNotDisabledException re) {
571      expectedException = true;
572    }
573    // Add column should work even if the table is enabled
574    assertFalse(expectedException);
575    modifiedHtd = this.admin.getTableDescriptor(tableName);
576    hcd = modifiedHtd.getFamily(xtracol.getName());
577    assertTrue(hcd != null);
578    assertTrue(hcd.getValue(xtracolName).equals(xtracolName));
579
580    // Delete the just-added column.
581    this.admin.deleteColumnFamily(tableName, xtracol.getName());
582    modifiedHtd = this.admin.getTableDescriptor(tableName);
583    hcd = modifiedHtd.getFamily(xtracol.getName());
584    assertTrue(hcd == null);
585
586    // Delete the table
587    this.admin.disableTable(tableName);
588    this.admin.deleteTable(tableName);
589    this.admin.listTables();
590    assertFalse(this.admin.tableExists(tableName));
591  }
592
593  protected void verifyRoundRobinDistribution(ClusterConnection c, RegionLocator regionLocator, int
594      expectedRegions) throws IOException {
595    int numRS = c.getCurrentNrHRS();
596    List<HRegionLocation> regions = regionLocator.getAllRegionLocations();
597    Map<ServerName, List<RegionInfo>> server2Regions = new HashMap<>();
598    for (HRegionLocation loc : regions) {
599      ServerName server = loc.getServerName();
600      List<RegionInfo> regs = server2Regions.get(server);
601      if (regs == null) {
602        regs = new ArrayList<>();
603        server2Regions.put(server, regs);
604      }
605      regs.add(loc.getRegionInfo());
606    }
607    boolean tablesOnMaster = LoadBalancer.isTablesOnMaster(TEST_UTIL.getConfiguration());
608    if (tablesOnMaster) {
609      // Ignore the master region server,
610      // which contains less regions by intention.
611      numRS--;
612    }
613    float average = (float) expectedRegions/numRS;
614    int min = (int)Math.floor(average);
615    int max = (int)Math.ceil(average);
616    for (List<RegionInfo> regionList : server2Regions.values()) {
617      assertTrue("numRS=" + numRS + ", min=" + min + ", max=" + max +
618        ", size=" + regionList.size() + ", tablesOnMaster=" + tablesOnMaster,
619      regionList.size() == min || regionList.size() == max);
620    }
621  }
622
623  @Test
624  public void testCreateTableNumberOfRegions() throws IOException, InterruptedException {
625    final TableName tableName = TableName.valueOf(name.getMethodName());
626    HTableDescriptor desc = new HTableDescriptor(tableName);
627    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
628    admin.createTable(desc);
629    List<HRegionLocation> regions;
630    try (RegionLocator l = TEST_UTIL.getConnection().getRegionLocator(tableName)) {
631      regions = l.getAllRegionLocations();
632      assertEquals("Table should have only 1 region", 1, regions.size());
633    }
634
635    TableName TABLE_2 = TableName.valueOf(tableName.getNameAsString() + "_2");
636    desc = new HTableDescriptor(TABLE_2);
637    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
638    admin.createTable(desc, new byte[][]{new byte[]{42}});
639    try (RegionLocator l = TEST_UTIL.getConnection().getRegionLocator(TABLE_2)) {
640      regions = l.getAllRegionLocations();
641      assertEquals("Table should have only 2 region", 2, regions.size());
642    }
643
644    TableName TABLE_3 = TableName.valueOf(tableName.getNameAsString() + "_3");
645    desc = new HTableDescriptor(TABLE_3);
646    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
647    admin.createTable(desc, "a".getBytes(), "z".getBytes(), 3);
648    try (RegionLocator l = TEST_UTIL.getConnection().getRegionLocator(TABLE_3)) {
649      regions = l.getAllRegionLocations();
650      assertEquals("Table should have only 3 region", 3, regions.size());
651    }
652
653    TableName TABLE_4 = TableName.valueOf(tableName.getNameAsString() + "_4");
654    desc = new HTableDescriptor(TABLE_4);
655    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
656    try {
657      admin.createTable(desc, "a".getBytes(), "z".getBytes(), 2);
658      fail("Should not be able to create a table with only 2 regions using this API.");
659    } catch (IllegalArgumentException eae) {
660    // Expected
661    }
662
663    TableName TABLE_5 = TableName.valueOf(tableName.getNameAsString() + "_5");
664    desc = new HTableDescriptor(TABLE_5);
665    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
666    admin.createTable(desc, new byte[] { 1 }, new byte[] { 127 }, 16);
667    try (RegionLocator l = TEST_UTIL.getConnection().getRegionLocator(TABLE_5)) {
668      regions = l.getAllRegionLocations();
669      assertEquals("Table should have 16 region", 16, regions.size());
670    }
671  }
672
673  @Test
674  public void testCreateTableWithRegions() throws IOException, InterruptedException {
675    final TableName tableName = TableName.valueOf(name.getMethodName());
676
677    byte [][] splitKeys = {
678        new byte [] { 1, 1, 1 },
679        new byte [] { 2, 2, 2 },
680        new byte [] { 3, 3, 3 },
681        new byte [] { 4, 4, 4 },
682        new byte [] { 5, 5, 5 },
683        new byte [] { 6, 6, 6 },
684        new byte [] { 7, 7, 7 },
685        new byte [] { 8, 8, 8 },
686        new byte [] { 9, 9, 9 },
687    };
688    int expectedRegions = splitKeys.length + 1;
689
690    HTableDescriptor desc = new HTableDescriptor(tableName);
691    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
692    admin.createTable(desc, splitKeys);
693
694    boolean tableAvailable = admin.isTableAvailable(tableName, splitKeys);
695    assertTrue("Table should be created with splitKyes + 1 rows in META", tableAvailable);
696
697    List<HRegionLocation> regions;
698    Iterator<HRegionLocation> hris;
699    RegionInfo hri;
700    ClusterConnection conn = (ClusterConnection) TEST_UTIL.getConnection();
701    try (RegionLocator l = TEST_UTIL.getConnection().getRegionLocator(tableName)) {
702      regions = l.getAllRegionLocations();
703
704      assertEquals("Tried to create " + expectedRegions + " regions " +
705              "but only found " + regions.size(), expectedRegions, regions.size());
706      System.err.println("Found " + regions.size() + " regions");
707
708      hris = regions.iterator();
709      hri = hris.next().getRegionInfo();
710      assertTrue(hri.getStartKey() == null || hri.getStartKey().length == 0);
711      assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[0]));
712      hri = hris.next().getRegionInfo();
713      assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[0]));
714      assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[1]));
715      hri = hris.next().getRegionInfo();
716      assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[1]));
717      assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[2]));
718      hri = hris.next().getRegionInfo();
719      assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[2]));
720      assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[3]));
721      hri = hris.next().getRegionInfo();
722      assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[3]));
723      assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[4]));
724      hri = hris.next().getRegionInfo();
725      assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[4]));
726      assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[5]));
727      hri = hris.next().getRegionInfo();
728      assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[5]));
729      assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[6]));
730      hri = hris.next().getRegionInfo();
731      assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[6]));
732      assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[7]));
733      hri = hris.next().getRegionInfo();
734      assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[7]));
735      assertTrue(Bytes.equals(hri.getEndKey(), splitKeys[8]));
736      hri = hris.next().getRegionInfo();
737      assertTrue(Bytes.equals(hri.getStartKey(), splitKeys[8]));
738      assertTrue(hri.getEndKey() == null || hri.getEndKey().length == 0);
739
740      verifyRoundRobinDistribution(conn, l, expectedRegions);
741    }
742
743
744
745    // Now test using start/end with a number of regions
746
747    // Use 80 bit numbers to make sure we aren't limited
748    byte [] startKey = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
749    byte [] endKey =   { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 };
750
751    // Splitting into 10 regions, we expect (null,1) ... (9, null)
752    // with (1,2) (2,3) (3,4) (4,5) (5,6) (6,7) (7,8) (8,9) in the middle
753
754    expectedRegions = 10;
755
756    TableName TABLE_2 = TableName.valueOf(tableName.getNameAsString() + "_2");
757
758    desc = new HTableDescriptor(TABLE_2);
759    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
760    admin = TEST_UTIL.getAdmin();
761    admin.createTable(desc, startKey, endKey, expectedRegions);
762
763    try (RegionLocator l = TEST_UTIL.getConnection().getRegionLocator(TABLE_2)) {
764      regions = l.getAllRegionLocations();
765      assertEquals("Tried to create " + expectedRegions + " regions " +
766          "but only found " + regions.size(), expectedRegions, regions.size());
767      System.err.println("Found " + regions.size() + " regions");
768
769      hris = regions.iterator();
770      hri = hris.next().getRegionInfo();
771      assertTrue(hri.getStartKey() == null || hri.getStartKey().length == 0);
772      assertTrue(Bytes.equals(hri.getEndKey(), new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }));
773      hri = hris.next().getRegionInfo();
774      assertTrue(Bytes.equals(hri.getStartKey(), new byte[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }));
775      assertTrue(Bytes.equals(hri.getEndKey(), new byte[] { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }));
776      hri = hris.next().getRegionInfo();
777      assertTrue(Bytes.equals(hri.getStartKey(), new byte[] { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2 }));
778      assertTrue(Bytes.equals(hri.getEndKey(), new byte[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }));
779      hri = hris.next().getRegionInfo();
780      assertTrue(Bytes.equals(hri.getStartKey(), new byte[] { 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 }));
781      assertTrue(Bytes.equals(hri.getEndKey(), new byte[] { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }));
782      hri = hris.next().getRegionInfo();
783      assertTrue(Bytes.equals(hri.getStartKey(), new byte[] { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }));
784      assertTrue(Bytes.equals(hri.getEndKey(), new byte[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }));
785      hri = hris.next().getRegionInfo();
786      assertTrue(Bytes.equals(hri.getStartKey(), new byte[] { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }));
787      assertTrue(Bytes.equals(hri.getEndKey(), new byte[] { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 }));
788      hri = hris.next().getRegionInfo();
789      assertTrue(Bytes.equals(hri.getStartKey(), new byte[] { 6, 6, 6, 6, 6, 6, 6, 6, 6, 6 }));
790      assertTrue(Bytes.equals(hri.getEndKey(), new byte[] { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }));
791      hri = hris.next().getRegionInfo();
792      assertTrue(Bytes.equals(hri.getStartKey(), new byte[] { 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 }));
793      assertTrue(Bytes.equals(hri.getEndKey(), new byte[] { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }));
794      hri = hris.next().getRegionInfo();
795      assertTrue(Bytes.equals(hri.getStartKey(), new byte[] { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }));
796      assertTrue(Bytes.equals(hri.getEndKey(), new byte[] { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }));
797      hri = hris.next().getRegionInfo();
798      assertTrue(Bytes.equals(hri.getStartKey(), new byte[] { 9, 9, 9, 9, 9, 9, 9, 9, 9, 9 }));
799      assertTrue(hri.getEndKey() == null || hri.getEndKey().length == 0);
800
801      verifyRoundRobinDistribution(conn, l, expectedRegions);
802    }
803
804    // Try once more with something that divides into something infinite
805
806    startKey = new byte [] { 0, 0, 0, 0, 0, 0 };
807    endKey = new byte [] { 1, 0, 0, 0, 0, 0 };
808
809    expectedRegions = 5;
810
811    TableName TABLE_3 = TableName.valueOf(tableName.getNameAsString() + "_3");
812
813    desc = new HTableDescriptor(TABLE_3);
814    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
815    admin = TEST_UTIL.getAdmin();
816    admin.createTable(desc, startKey, endKey, expectedRegions);
817
818
819    try (RegionLocator l = TEST_UTIL.getConnection().getRegionLocator(TABLE_3)) {
820      regions = l.getAllRegionLocations();
821      assertEquals("Tried to create " + expectedRegions + " regions " +
822          "but only found " + regions.size(), expectedRegions, regions.size());
823      System.err.println("Found " + regions.size() + " regions");
824
825      verifyRoundRobinDistribution(conn, l, expectedRegions);
826    }
827
828
829    // Try an invalid case where there are duplicate split keys
830    splitKeys = new byte [][] {
831        new byte [] { 1, 1, 1 },
832        new byte [] { 2, 2, 2 },
833        new byte [] { 3, 3, 3 },
834        new byte [] { 2, 2, 2 }
835    };
836
837    TableName TABLE_4 = TableName.valueOf(tableName.getNameAsString() + "_4");
838    desc = new HTableDescriptor(TABLE_4);
839    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
840    try {
841      admin.createTable(desc, splitKeys);
842      assertTrue("Should not be able to create this table because of " +
843          "duplicate split keys", false);
844    } catch(IllegalArgumentException iae) {
845      // Expected
846    }
847  }
848
849  @Test
850  public void testTableAvailableWithRandomSplitKeys() throws Exception {
851    final TableName tableName = TableName.valueOf(name.getMethodName());
852    HTableDescriptor desc = new HTableDescriptor(tableName);
853    desc.addFamily(new HColumnDescriptor("col"));
854    byte[][] splitKeys = new byte[1][];
855    splitKeys = new byte [][] {
856        new byte [] { 1, 1, 1 },
857        new byte [] { 2, 2, 2 }
858    };
859    admin.createTable(desc);
860    boolean tableAvailable = admin.isTableAvailable(tableName, splitKeys);
861    assertFalse("Table should be created with 1 row in META", tableAvailable);
862  }
863
864  @Test
865  public void testCreateTableWithOnlyEmptyStartRow() throws IOException {
866    final byte[] tableName = Bytes.toBytes(name.getMethodName());
867    byte[][] splitKeys = new byte[1][];
868    splitKeys[0] = HConstants.EMPTY_BYTE_ARRAY;
869    HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
870    desc.addFamily(new HColumnDescriptor("col"));
871    try {
872      admin.createTable(desc, splitKeys);
873      fail("Test case should fail as empty split key is passed.");
874    } catch (IllegalArgumentException e) {
875    }
876  }
877
878  @Test
879  public void testCreateTableWithEmptyRowInTheSplitKeys() throws IOException{
880    final byte[] tableName = Bytes.toBytes(name.getMethodName());
881    byte[][] splitKeys = new byte[3][];
882    splitKeys[0] = "region1".getBytes();
883    splitKeys[1] = HConstants.EMPTY_BYTE_ARRAY;
884    splitKeys[2] = "region2".getBytes();
885    HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(tableName));
886    desc.addFamily(new HColumnDescriptor("col"));
887    try {
888      admin.createTable(desc, splitKeys);
889      fail("Test case should fail as empty split key is passed.");
890    } catch (IllegalArgumentException e) {
891      LOG.info("Expected ", e);
892    }
893  }
894
895  @Test
896  public void testTableExist() throws IOException {
897    final TableName table = TableName.valueOf(name.getMethodName());
898    boolean exist;
899    exist = this.admin.tableExists(table);
900    assertEquals(false, exist);
901    TEST_UTIL.createTable(table, HConstants.CATALOG_FAMILY);
902    exist = this.admin.tableExists(table);
903    assertEquals(true, exist);
904  }
905
906  /**
907   * Tests forcing split from client and having scanners successfully ride over split.
908   * @throws Exception
909   * @throws IOException
910   */
911  @Test
912  public void testForceSplit() throws Exception {
913    byte[][] familyNames = new byte[][] { Bytes.toBytes("cf") };
914    int[] rowCounts = new int[] { 6000 };
915    int numVersions = HColumnDescriptor.DEFAULT_VERSIONS;
916    int blockSize = 256;
917    splitTest(null, familyNames, rowCounts, numVersions, blockSize, true);
918
919    byte[] splitKey = Bytes.toBytes(3500);
920    splitTest(splitKey, familyNames, rowCounts, numVersions, blockSize, true);
921    // test regionSplitSync
922    splitTest(splitKey, familyNames, rowCounts, numVersions, blockSize, false);
923  }
924
925  /**
926   * Test retain assignment on enableTable.
927   *
928   * @throws IOException
929   */
930  @Test
931  public void testEnableTableRetainAssignment() throws IOException {
932    final TableName tableName = TableName.valueOf(name.getMethodName());
933    byte[][] splitKeys = { new byte[] { 1, 1, 1 }, new byte[] { 2, 2, 2 },
934        new byte[] { 3, 3, 3 }, new byte[] { 4, 4, 4 }, new byte[] { 5, 5, 5 },
935        new byte[] { 6, 6, 6 }, new byte[] { 7, 7, 7 }, new byte[] { 8, 8, 8 },
936        new byte[] { 9, 9, 9 } };
937    int expectedRegions = splitKeys.length + 1;
938    HTableDescriptor desc = new HTableDescriptor(tableName);
939    desc.addFamily(new HColumnDescriptor(HConstants.CATALOG_FAMILY));
940    admin.createTable(desc, splitKeys);
941
942    try (RegionLocator l = TEST_UTIL.getConnection().getRegionLocator(tableName)) {
943      List<HRegionLocation> regions = l.getAllRegionLocations();
944
945      assertEquals(
946          "Tried to create " + expectedRegions + " regions " + "but only found " + regions.size(),
947          expectedRegions, regions.size());
948      // Disable table.
949      admin.disableTable(tableName);
950      // Enable table, use retain assignment to assign regions.
951      admin.enableTable(tableName);
952      List<HRegionLocation> regions2 = l.getAllRegionLocations();
953
954      // Check the assignment.
955      assertEquals(regions.size(), regions2.size());
956      assertTrue(regions2.containsAll(regions));
957    }
958  }
959
960  /**
961   * Multi-family scenario. Tests forcing split from client and
962   * having scanners successfully ride over split.
963   * @throws Exception
964   * @throws IOException
965   */
966  @Test
967  public void testForceSplitMultiFamily() throws Exception {
968    int numVersions = HColumnDescriptor.DEFAULT_VERSIONS;
969
970    // use small HFile block size so that we can have lots of blocks in HFile
971    // Otherwise, if there is only one block,
972    // HFileBlockIndex.midKey()'s value == startKey
973    int blockSize = 256;
974    byte[][] familyNames = new byte[][] { Bytes.toBytes("cf1"),
975      Bytes.toBytes("cf2") };
976
977    // one of the column families isn't splittable
978    int[] rowCounts = new int[] { 6000, 1 };
979    splitTest(null, familyNames, rowCounts, numVersions, blockSize, true);
980
981    rowCounts = new int[] { 1, 6000 };
982    splitTest(null, familyNames, rowCounts, numVersions, blockSize, true);
983
984    // one column family has much smaller data than the other
985    // the split key should be based on the largest column family
986    rowCounts = new int[] { 6000, 300 };
987    splitTest(null, familyNames, rowCounts, numVersions, blockSize, true);
988
989    rowCounts = new int[] { 300, 6000 };
990    splitTest(null, familyNames, rowCounts, numVersions, blockSize, true);
991
992  }
993
994  void splitTest(byte[] splitPoint, byte[][] familyNames, int[] rowCounts,
995    int numVersions, int blockSize, boolean async) throws Exception {
996    TableName tableName = TableName.valueOf("testForceSplit");
997    StringBuilder sb = new StringBuilder();
998    // Add tail to String so can see better in logs where a test is running.
999    for (int i = 0; i < rowCounts.length; i++) {
1000      sb.append("_").append(Integer.toString(rowCounts[i]));
1001    }
1002    assertFalse(admin.tableExists(tableName));
1003    try (final Table table = TEST_UTIL.createTable(tableName, familyNames,
1004      numVersions, blockSize);
1005      final RegionLocator locator = TEST_UTIL.getConnection().getRegionLocator(tableName)) {
1006
1007      int rowCount = 0;
1008      byte[] q = new byte[0];
1009
1010      // insert rows into column families. The number of rows that have values
1011      // in a specific column family is decided by rowCounts[familyIndex]
1012      for (int index = 0; index < familyNames.length; index++) {
1013        ArrayList<Put> puts = new ArrayList<>(rowCounts[index]);
1014        for (int i = 0; i < rowCounts[index]; i++) {
1015          byte[] k = Bytes.toBytes(i);
1016          Put put = new Put(k);
1017          put.addColumn(familyNames[index], q, k);
1018          puts.add(put);
1019        }
1020        table.put(puts);
1021
1022        if (rowCount < rowCounts[index]) {
1023          rowCount = rowCounts[index];
1024        }
1025      }
1026
1027      // get the initial layout (should just be one region)
1028      List<HRegionLocation> m = locator.getAllRegionLocations();
1029      LOG.info("Initial regions (" + m.size() + "): " + m);
1030      assertTrue(m.size() == 1);
1031
1032      // Verify row count
1033      Scan scan = new Scan();
1034      ResultScanner scanner = table.getScanner(scan);
1035      int rows = 0;
1036      for (@SuppressWarnings("unused") Result result : scanner) {
1037        rows++;
1038      }
1039      scanner.close();
1040      assertEquals(rowCount, rows);
1041
1042      // Have an outstanding scan going on to make sure we can scan over splits.
1043      scan = new Scan();
1044      scanner = table.getScanner(scan);
1045      // Scan first row so we are into first region before split happens.
1046      scanner.next();
1047
1048      // Split the table
1049      if (async) {
1050        this.admin.split(tableName, splitPoint);
1051        final AtomicInteger count = new AtomicInteger(0);
1052        Thread t = new Thread("CheckForSplit") {
1053          @Override public void run() {
1054            for (int i = 0; i < 45; i++) {
1055              try {
1056                sleep(1000);
1057              } catch (InterruptedException e) {
1058                continue;
1059              }
1060              // check again
1061              List<HRegionLocation> regions = null;
1062              try {
1063                regions = locator.getAllRegionLocations();
1064              } catch (IOException e) {
1065                e.printStackTrace();
1066              }
1067              if (regions == null) continue;
1068              count.set(regions.size());
1069              if (count.get() >= 2) {
1070                LOG.info("Found: " + regions);
1071                break;
1072              }
1073              LOG.debug("Cycle waiting on split");
1074            }
1075            LOG.debug("CheckForSplit thread exited, current region count: " + count.get());
1076          }
1077        };
1078        t.setPriority(Thread.NORM_PRIORITY - 2);
1079        t.start();
1080        t.join();
1081      } else {
1082        // Sync split region, no need to create a thread to check
1083        ((HBaseAdmin)admin).splitRegionSync(m.get(0).getRegionInfo().getRegionName(), splitPoint);
1084      }
1085
1086      // Verify row count
1087      rows = 1; // We counted one row above.
1088      for (@SuppressWarnings("unused") Result result : scanner) {
1089        rows++;
1090        if (rows > rowCount) {
1091          scanner.close();
1092          assertTrue("Scanned more than expected (" + rowCount + ")", false);
1093        }
1094      }
1095      scanner.close();
1096      assertEquals(rowCount, rows);
1097
1098      List<HRegionLocation> regions = null;
1099      try {
1100        regions = locator.getAllRegionLocations();
1101      } catch (IOException e) {
1102        e.printStackTrace();
1103      }
1104      assertEquals(2, regions.size());
1105      if (splitPoint != null) {
1106        // make sure the split point matches our explicit configuration
1107        assertEquals(Bytes.toString(splitPoint),
1108            Bytes.toString(regions.get(0).getRegionInfo().getEndKey()));
1109        assertEquals(Bytes.toString(splitPoint),
1110            Bytes.toString(regions.get(1).getRegionInfo().getStartKey()));
1111        LOG.debug("Properly split on " + Bytes.toString(splitPoint));
1112      } else {
1113        if (familyNames.length > 1) {
1114          int splitKey = Bytes.toInt(regions.get(0).getRegionInfo().getEndKey());
1115          // check if splitKey is based on the largest column family
1116          // in terms of it store size
1117          int deltaForLargestFamily = Math.abs(rowCount / 2 - splitKey);
1118          LOG.debug("SplitKey=" + splitKey + "&deltaForLargestFamily=" + deltaForLargestFamily +
1119              ", r=" + regions.get(0).getRegionInfo());
1120          for (int index = 0; index < familyNames.length; index++) {
1121            int delta = Math.abs(rowCounts[index] / 2 - splitKey);
1122            if (delta < deltaForLargestFamily) {
1123              assertTrue("Delta " + delta + " for family " + index + " should be at least "
1124                      + "deltaForLargestFamily " + deltaForLargestFamily, false);
1125            }
1126          }
1127        }
1128      }
1129      TEST_UTIL.deleteTable(tableName);
1130    }
1131  }
1132
1133  @Test
1134  public void testSplitAndMergeWithReplicaTable() throws Exception {
1135    // The test tries to directly split replica regions and directly merge replica regions. These
1136    // are not allowed. The test validates that. Then the test does a valid split/merge of allowed
1137    // regions.
1138    // Set up a table with 3 regions and replication set to 3
1139    final TableName tableName = TableName.valueOf(name.getMethodName());
1140    HTableDescriptor desc = new HTableDescriptor(tableName);
1141    desc.setRegionReplication(3);
1142    byte[] cf = "f".getBytes();
1143    HColumnDescriptor hcd = new HColumnDescriptor(cf);
1144    desc.addFamily(hcd);
1145    byte[][] splitRows = new byte[2][];
1146    splitRows[0] = new byte[]{(byte)'4'};
1147    splitRows[1] = new byte[]{(byte)'7'};
1148    TEST_UTIL.getAdmin().createTable(desc, splitRows);
1149    List<HRegion> oldRegions;
1150    do {
1151      oldRegions = TEST_UTIL.getHBaseCluster().getRegions(tableName);
1152      Thread.sleep(10);
1153    } while (oldRegions.size() != 9); //3 regions * 3 replicas
1154    // write some data to the table
1155    Table ht = TEST_UTIL.getConnection().getTable(tableName);
1156    List<Put> puts = new ArrayList<>();
1157    byte[] qualifier = "c".getBytes();
1158    Put put = new Put(new byte[]{(byte)'1'});
1159    put.addColumn(cf, qualifier, "100".getBytes());
1160    puts.add(put);
1161    put = new Put(new byte[]{(byte)'6'});
1162    put.addColumn(cf, qualifier, "100".getBytes());
1163    puts.add(put);
1164    put = new Put(new byte[]{(byte)'8'});
1165    put.addColumn(cf, qualifier, "100".getBytes());
1166    puts.add(put);
1167    ht.put(puts);
1168    ht.close();
1169    List<Pair<RegionInfo, ServerName>> regions =
1170        MetaTableAccessor.getTableRegionsAndLocations(TEST_UTIL.getConnection(), tableName);
1171    boolean gotException = false;
1172    // the element at index 1 would be a replica (since the metareader gives us ordered
1173    // regions). Try splitting that region via the split API . Should fail
1174    try {
1175      TEST_UTIL.getAdmin().splitRegion(regions.get(1).getFirst().getRegionName());
1176    } catch (IllegalArgumentException ex) {
1177      gotException = true;
1178    }
1179    assertTrue(gotException);
1180    gotException = false;
1181    // the element at index 1 would be a replica (since the metareader gives us ordered
1182    // regions). Try splitting that region via a different split API (the difference is
1183    // this API goes direct to the regionserver skipping any checks in the admin). Should fail
1184    try {
1185      TEST_UTIL.getHBaseAdmin().splitRegionAsync(regions.get(1).getFirst(),
1186          new byte[]{(byte)'1'});
1187    } catch (IOException ex) {
1188      gotException = true;
1189    }
1190    assertTrue(gotException);
1191
1192    gotException = false;
1193    //testing Sync split operation
1194    try {
1195      TEST_UTIL.getHBaseAdmin().splitRegionSync(regions.get(1).getFirst().getRegionName(),
1196          new byte[]{(byte)'1'});
1197    } catch (IllegalArgumentException ex) {
1198      gotException = true;
1199    }
1200    assertTrue(gotException);
1201
1202    gotException = false;
1203    // Try merging a replica with another. Should fail.
1204    try {
1205      TEST_UTIL.getHBaseAdmin().mergeRegionsSync(
1206        regions.get(1).getFirst().getEncodedNameAsBytes(),
1207        regions.get(2).getFirst().getEncodedNameAsBytes(),
1208        true);
1209    } catch (IllegalArgumentException m) {
1210      gotException = true;
1211    }
1212    assertTrue(gotException);
1213    // Try going to the master directly (that will skip the check in admin)
1214    try {
1215      byte[][] nameofRegionsToMerge = new byte[2][];
1216      nameofRegionsToMerge[0] =  regions.get(1).getFirst().getEncodedNameAsBytes();
1217      nameofRegionsToMerge[1] = regions.get(2).getFirst().getEncodedNameAsBytes();
1218      MergeTableRegionsRequest request = RequestConverter
1219          .buildMergeTableRegionsRequest(
1220            nameofRegionsToMerge,
1221            true,
1222            HConstants.NO_NONCE,
1223            HConstants.NO_NONCE);
1224      ((ClusterConnection) TEST_UTIL.getAdmin().getConnection()).getMaster()
1225        .mergeTableRegions(null, request);
1226    } catch (org.apache.hbase.thirdparty.com.google.protobuf.ServiceException m) {
1227      Throwable t = m.getCause();
1228      do {
1229        if (t instanceof MergeRegionException) {
1230          gotException = true;
1231          break;
1232        }
1233        t = t.getCause();
1234      } while (t != null);
1235    }
1236    assertTrue(gotException);
1237  }
1238
1239  @Test (expected=IllegalArgumentException.class)
1240  public void testInvalidHColumnDescriptor() throws IOException {
1241     new HColumnDescriptor("/cfamily/name");
1242  }
1243
1244  @Test
1245  public void testEnableDisableAddColumnDeleteColumn() throws Exception {
1246    final TableName tableName = TableName.valueOf(name.getMethodName());
1247    TEST_UTIL.createTable(tableName, HConstants.CATALOG_FAMILY).close();
1248    while (!this.admin.isTableEnabled(TableName.valueOf(name.getMethodName()))) {
1249      Thread.sleep(10);
1250    }
1251    this.admin.disableTable(tableName);
1252    try {
1253      TEST_UTIL.getConnection().getTable(tableName);
1254    } catch (org.apache.hadoop.hbase.DoNotRetryIOException e) {
1255      //expected
1256    }
1257
1258    this.admin.addColumnFamily(tableName, new HColumnDescriptor("col2"));
1259    this.admin.enableTable(tableName);
1260    try {
1261      this.admin.deleteColumnFamily(tableName, Bytes.toBytes("col2"));
1262    } catch (TableNotDisabledException e) {
1263      LOG.info(e.toString(), e);
1264    }
1265    this.admin.disableTable(tableName);
1266    this.admin.deleteTable(tableName);
1267  }
1268
1269  @Test
1270  public void testDeleteLastColumnFamily() throws Exception {
1271    final TableName tableName = TableName.valueOf(name.getMethodName());
1272    TEST_UTIL.createTable(tableName, HConstants.CATALOG_FAMILY).close();
1273    while (!this.admin.isTableEnabled(TableName.valueOf(name.getMethodName()))) {
1274      Thread.sleep(10);
1275    }
1276
1277    // test for enabled table
1278    try {
1279      this.admin.deleteColumnFamily(tableName, HConstants.CATALOG_FAMILY);
1280      fail("Should have failed to delete the only column family of a table");
1281    } catch (InvalidFamilyOperationException ex) {
1282      // expected
1283    }
1284
1285    // test for disabled table
1286    this.admin.disableTable(tableName);
1287
1288    try {
1289      this.admin.deleteColumnFamily(tableName, HConstants.CATALOG_FAMILY);
1290      fail("Should have failed to delete the only column family of a table");
1291    } catch (InvalidFamilyOperationException ex) {
1292      // expected
1293    }
1294
1295    this.admin.deleteTable(tableName);
1296  }
1297
1298  /*
1299   * Test DFS replication for column families, where one CF has default replication(3) and the other
1300   * is set to 1.
1301   */
1302  @Test
1303  public void testHFileReplication() throws Exception {
1304    final TableName tableName = TableName.valueOf(this.name.getMethodName());
1305    String fn1 = "rep1";
1306    HColumnDescriptor hcd1 = new HColumnDescriptor(fn1);
1307    hcd1.setDFSReplication((short) 1);
1308    String fn = "defaultRep";
1309    HColumnDescriptor hcd = new HColumnDescriptor(fn);
1310    HTableDescriptor htd = new HTableDescriptor(tableName);
1311    htd.addFamily(hcd);
1312    htd.addFamily(hcd1);
1313    Table table = TEST_UTIL.createTable(htd, null);
1314    TEST_UTIL.waitTableAvailable(tableName);
1315    Put p = new Put(Bytes.toBytes("defaultRep_rk"));
1316    byte[] q1 = Bytes.toBytes("q1");
1317    byte[] v1 = Bytes.toBytes("v1");
1318    p.addColumn(Bytes.toBytes(fn), q1, v1);
1319    List<Put> puts = new ArrayList<>(2);
1320    puts.add(p);
1321    p = new Put(Bytes.toBytes("rep1_rk"));
1322    p.addColumn(Bytes.toBytes(fn1), q1, v1);
1323    puts.add(p);
1324    try {
1325      table.put(puts);
1326      admin.flush(tableName);
1327
1328      List<HRegion> regions = TEST_UTIL.getMiniHBaseCluster().getRegions(tableName);
1329      for (HRegion r : regions) {
1330        HStore store = r.getStore(Bytes.toBytes(fn));
1331        for (HStoreFile sf : store.getStorefiles()) {
1332          assertTrue(sf.toString().contains(fn));
1333          assertTrue("Column family " + fn + " should have 3 copies",
1334            FSUtils.getDefaultReplication(TEST_UTIL.getTestFileSystem(), sf.getPath()) == (sf
1335                .getFileInfo().getFileStatus().getReplication()));
1336        }
1337
1338        store = r.getStore(Bytes.toBytes(fn1));
1339        for (HStoreFile sf : store.getStorefiles()) {
1340          assertTrue(sf.toString().contains(fn1));
1341          assertTrue("Column family " + fn1 + " should have only 1 copy", 1 == sf.getFileInfo()
1342              .getFileStatus().getReplication());
1343        }
1344      }
1345    } finally {
1346      if (admin.isTableEnabled(tableName)) {
1347        this.admin.disableTable(tableName);
1348        this.admin.deleteTable(tableName);
1349      }
1350    }
1351  }
1352
1353  @Test
1354  public void testMergeRegions() throws Exception {
1355    final TableName tableName = TableName.valueOf(name.getMethodName());
1356    HColumnDescriptor cd = new HColumnDescriptor("d");
1357    HTableDescriptor td = new HTableDescriptor(tableName);
1358    td.addFamily(cd);
1359    byte[][] splitRows = new byte[2][];
1360    splitRows[0] = new byte[]{(byte)'3'};
1361    splitRows[1] = new byte[]{(byte)'6'};
1362    try {
1363      TEST_UTIL.createTable(td, splitRows);
1364      TEST_UTIL.waitTableAvailable(tableName);
1365
1366      List<RegionInfo> tableRegions;
1367      RegionInfo regionA;
1368      RegionInfo regionB;
1369
1370      // merge with full name
1371      tableRegions = admin.getRegions(tableName);
1372      assertEquals(3, admin.getTableRegions(tableName).size());
1373      regionA = tableRegions.get(0);
1374      regionB = tableRegions.get(1);
1375      // TODO convert this to version that is synchronous (See HBASE-16668)
1376      admin.mergeRegionsAsync(regionA.getRegionName(), regionB.getRegionName(), false)
1377          .get(60, TimeUnit.SECONDS);
1378
1379      assertEquals(2, admin.getTableRegions(tableName).size());
1380
1381      // merge with encoded name
1382      tableRegions = admin.getRegions(tableName);
1383      regionA = tableRegions.get(0);
1384      regionB = tableRegions.get(1);
1385      // TODO convert this to version that is synchronous (See HBASE-16668)
1386      admin.mergeRegionsAsync(
1387        regionA.getEncodedNameAsBytes(), regionB.getEncodedNameAsBytes(), false)
1388          .get(60, TimeUnit.SECONDS);
1389
1390      assertEquals(1, admin.getTableRegions(tableName).size());
1391    } finally {
1392      this.admin.disableTable(tableName);
1393      this.admin.deleteTable(tableName);
1394    }
1395  }
1396
1397  @Test
1398  public void testSplitShouldNotHappenIfSplitIsDisabledForTable()
1399      throws Exception {
1400    final TableName tableName = TableName.valueOf(name.getMethodName());
1401    HTableDescriptor htd = new HTableDescriptor(tableName);
1402    htd.addFamily(new HColumnDescriptor("f"));
1403    htd.setRegionSplitPolicyClassName(DisabledRegionSplitPolicy.class.getName());
1404    Table table = TEST_UTIL.createTable(htd, null);
1405    for(int i = 0; i < 10; i++) {
1406      Put p = new Put(Bytes.toBytes("row"+i));
1407      byte[] q1 = Bytes.toBytes("q1");
1408      byte[] v1 = Bytes.toBytes("v1");
1409      p.addColumn(Bytes.toBytes("f"), q1, v1);
1410      table.put(p);
1411    }
1412    this.admin.flush(tableName);
1413    try {
1414      this.admin.split(tableName, Bytes.toBytes("row5"));
1415      Threads.sleep(10000);
1416    } catch (Exception e) {
1417      // Nothing to do.
1418    }
1419    // Split should not happen.
1420    List<RegionInfo> allRegions = MetaTableAccessor.getTableRegions(
1421        this.admin.getConnection(), tableName, true);
1422    assertEquals(1, allRegions.size());
1423  }
1424}