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.namespace;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertFalse;
022import static org.junit.Assert.assertNotNull;
023import static org.junit.Assert.assertNull;
024import static org.junit.Assert.assertTrue;
025import static org.junit.Assert.fail;
026
027import java.io.IOException;
028import java.util.Collections;
029import java.util.List;
030import java.util.Optional;
031import java.util.concurrent.CountDownLatch;
032import java.util.concurrent.ExecutionException;
033import java.util.concurrent.Future;
034import java.util.concurrent.TimeUnit;
035import org.apache.commons.lang3.StringUtils;
036import org.apache.hadoop.conf.Configuration;
037import org.apache.hadoop.fs.FileSystem;
038import org.apache.hadoop.fs.Path;
039import org.apache.hadoop.hbase.Coprocessor;
040import org.apache.hadoop.hbase.CoprocessorEnvironment;
041import org.apache.hadoop.hbase.HBaseClassTestRule;
042import org.apache.hadoop.hbase.HBaseTestingUtility;
043import org.apache.hadoop.hbase.HColumnDescriptor;
044import org.apache.hadoop.hbase.HConstants;
045import org.apache.hadoop.hbase.HRegionInfo;
046import org.apache.hadoop.hbase.HTableDescriptor;
047import org.apache.hadoop.hbase.MiniHBaseCluster;
048import org.apache.hadoop.hbase.NamespaceDescriptor;
049import org.apache.hadoop.hbase.TableName;
050import org.apache.hadoop.hbase.Waiter;
051import org.apache.hadoop.hbase.client.Admin;
052import org.apache.hadoop.hbase.client.Connection;
053import org.apache.hadoop.hbase.client.ConnectionFactory;
054import org.apache.hadoop.hbase.client.DoNotRetryRegionException;
055import org.apache.hadoop.hbase.client.RegionInfo;
056import org.apache.hadoop.hbase.client.RegionLocator;
057import org.apache.hadoop.hbase.client.Table;
058import org.apache.hadoop.hbase.client.TableDescriptor;
059import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
060import org.apache.hadoop.hbase.coprocessor.MasterCoprocessor;
061import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment;
062import org.apache.hadoop.hbase.coprocessor.MasterObserver;
063import org.apache.hadoop.hbase.coprocessor.ObserverContext;
064import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor;
065import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
066import org.apache.hadoop.hbase.coprocessor.RegionObserver;
067import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessor;
068import org.apache.hadoop.hbase.coprocessor.RegionServerObserver;
069import org.apache.hadoop.hbase.master.HMaster;
070import org.apache.hadoop.hbase.master.MasterCoprocessorHost;
071import org.apache.hadoop.hbase.master.TableNamespaceManager;
072import org.apache.hadoop.hbase.quotas.MasterQuotaManager;
073import org.apache.hadoop.hbase.quotas.QuotaExceededException;
074import org.apache.hadoop.hbase.quotas.QuotaUtil;
075import org.apache.hadoop.hbase.regionserver.HRegion;
076import org.apache.hadoop.hbase.regionserver.Store;
077import org.apache.hadoop.hbase.regionserver.StoreFile;
078import org.apache.hadoop.hbase.regionserver.compactions.CompactionLifeCycleTracker;
079import org.apache.hadoop.hbase.regionserver.compactions.CompactionRequest;
080import org.apache.hadoop.hbase.snapshot.RestoreSnapshotException;
081import org.apache.hadoop.hbase.testclassification.MediumTests;
082import org.apache.hadoop.hbase.util.Bytes;
083import org.apache.hadoop.hbase.util.FSUtils;
084import org.apache.hadoop.hbase.util.Threads;
085import org.apache.zookeeper.KeeperException;
086import org.junit.After;
087import org.junit.AfterClass;
088import org.junit.BeforeClass;
089import org.junit.ClassRule;
090import org.junit.Test;
091import org.junit.experimental.categories.Category;
092import org.slf4j.Logger;
093import org.slf4j.LoggerFactory;
094
095@Category(MediumTests.class)
096public class TestNamespaceAuditor {
097
098  @ClassRule
099  public static final HBaseClassTestRule CLASS_RULE =
100      HBaseClassTestRule.forClass(TestNamespaceAuditor.class);
101
102  private static final Logger LOG = LoggerFactory.getLogger(TestNamespaceAuditor.class);
103  private static final HBaseTestingUtility UTIL = new HBaseTestingUtility();
104  private static Admin ADMIN;
105  private String prefix = "TestNamespaceAuditor";
106
107  @BeforeClass
108  public static void before() throws Exception {
109    Configuration conf = UTIL.getConfiguration();
110    conf.set(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY, CustomObserver.class.getName());
111    conf.setStrings(
112      CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY,
113      MasterSyncObserver.class.getName(), CPMasterObserver.class.getName());
114    conf.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 5);
115    conf.setBoolean(QuotaUtil.QUOTA_CONF_KEY, true);
116    conf.setClass("hbase.coprocessor.regionserver.classes", CPRegionServerObserver.class,
117      RegionServerObserver.class);
118    UTIL.startMiniCluster(1, 1);
119    waitForQuotaInitialize(UTIL);
120    ADMIN = UTIL.getAdmin();
121  }
122
123  @AfterClass
124  public static void tearDown() throws Exception {
125    UTIL.shutdownMiniCluster();
126  }
127
128  @After
129  public void cleanup() throws Exception, KeeperException {
130    for (HTableDescriptor table : ADMIN.listTables()) {
131      ADMIN.disableTable(table.getTableName());
132      deleteTable(table.getTableName());
133    }
134    for (NamespaceDescriptor ns : ADMIN.listNamespaceDescriptors()) {
135      if (ns.getName().startsWith(prefix)) {
136        ADMIN.deleteNamespace(ns.getName());
137      }
138    }
139    assertTrue("Quota manager not initialized", UTIL.getHBaseCluster().getMaster()
140        .getMasterQuotaManager().isQuotaInitialized());
141  }
142
143  @Test
144  public void testTableOperations() throws Exception {
145    String nsp = prefix + "_np2";
146    NamespaceDescriptor nspDesc =
147        NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "5")
148            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build();
149    ADMIN.createNamespace(nspDesc);
150    assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp));
151    assertEquals(3, ADMIN.listNamespaceDescriptors().length);
152    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
153
154    HTableDescriptor tableDescOne =
155        new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1"));
156    tableDescOne.addFamily(fam1);
157    HTableDescriptor tableDescTwo =
158        new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2"));
159    tableDescTwo.addFamily(fam1);
160    HTableDescriptor tableDescThree =
161        new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table3"));
162    tableDescThree.addFamily(fam1);
163    ADMIN.createTable(tableDescOne);
164    boolean constraintViolated = false;
165    try {
166      ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 5);
167    } catch (Exception exp) {
168      assertTrue(exp instanceof IOException);
169      constraintViolated = true;
170    } finally {
171      assertTrue("Constraint not violated for table " + tableDescTwo.getTableName(),
172        constraintViolated);
173    }
174    ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4);
175    NamespaceTableAndRegionInfo nspState = getQuotaManager().getState(nsp);
176    assertNotNull(nspState);
177    assertTrue(nspState.getTables().size() == 2);
178    assertTrue(nspState.getRegionCount() == 5);
179    constraintViolated = false;
180    try {
181      ADMIN.createTable(tableDescThree);
182    } catch (Exception exp) {
183      assertTrue(exp instanceof IOException);
184      constraintViolated = true;
185    } finally {
186      assertTrue("Constraint not violated for table " + tableDescThree.getTableName(),
187        constraintViolated);
188    }
189  }
190
191  @Test
192  public void testValidQuotas() throws Exception {
193    boolean exceptionCaught = false;
194    FileSystem fs = UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getFileSystem();
195    Path rootDir = UTIL.getHBaseCluster().getMaster().getMasterFileSystem().getRootDir();
196    NamespaceDescriptor nspDesc =
197        NamespaceDescriptor.create(prefix + "vq1")
198            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "hihdufh")
199            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build();
200    try {
201      ADMIN.createNamespace(nspDesc);
202    } catch (Exception exp) {
203      LOG.warn(exp.toString(), exp);
204      exceptionCaught = true;
205    } finally {
206      assertTrue(exceptionCaught);
207      assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName())));
208    }
209    nspDesc =
210        NamespaceDescriptor.create(prefix + "vq2")
211            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "-456")
212            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build();
213    try {
214      ADMIN.createNamespace(nspDesc);
215    } catch (Exception exp) {
216      LOG.warn(exp.toString(), exp);
217      exceptionCaught = true;
218    } finally {
219      assertTrue(exceptionCaught);
220      assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName())));
221    }
222    nspDesc =
223        NamespaceDescriptor.create(prefix + "vq3")
224            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10")
225            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "sciigd").build();
226    try {
227      ADMIN.createNamespace(nspDesc);
228    } catch (Exception exp) {
229      LOG.warn(exp.toString(), exp);
230      exceptionCaught = true;
231    } finally {
232      assertTrue(exceptionCaught);
233      assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName())));
234    }
235    nspDesc =
236        NamespaceDescriptor.create(prefix + "vq4")
237            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10")
238            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "-1500").build();
239    try {
240      ADMIN.createNamespace(nspDesc);
241    } catch (Exception exp) {
242      LOG.warn(exp.toString(), exp);
243      exceptionCaught = true;
244    } finally {
245      assertTrue(exceptionCaught);
246      assertFalse(fs.exists(FSUtils.getNamespaceDir(rootDir, nspDesc.getName())));
247    }
248  }
249
250  @Test
251  public void testDeleteTable() throws Exception {
252    String namespace = prefix + "_dummy";
253    NamespaceDescriptor nspDesc =
254        NamespaceDescriptor.create(namespace)
255            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "100")
256            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "3").build();
257    ADMIN.createNamespace(nspDesc);
258    assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(namespace));
259    NamespaceTableAndRegionInfo stateInfo = getNamespaceState(nspDesc.getName());
260    assertNotNull("Namespace state found null for " + namespace, stateInfo);
261    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
262    HTableDescriptor tableDescOne =
263        new HTableDescriptor(TableName.valueOf(namespace + TableName.NAMESPACE_DELIM + "table1"));
264    tableDescOne.addFamily(fam1);
265    HTableDescriptor tableDescTwo =
266        new HTableDescriptor(TableName.valueOf(namespace + TableName.NAMESPACE_DELIM + "table2"));
267    tableDescTwo.addFamily(fam1);
268    ADMIN.createTable(tableDescOne);
269    ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 5);
270    stateInfo = getNamespaceState(nspDesc.getName());
271    assertNotNull("Namespace state found to be null.", stateInfo);
272    assertEquals(2, stateInfo.getTables().size());
273    assertEquals(5, stateInfo.getRegionCountOfTable(tableDescTwo.getTableName()));
274    assertEquals(6, stateInfo.getRegionCount());
275    ADMIN.disableTable(tableDescOne.getTableName());
276    deleteTable(tableDescOne.getTableName());
277    stateInfo = getNamespaceState(nspDesc.getName());
278    assertNotNull("Namespace state found to be null.", stateInfo);
279    assertEquals(5, stateInfo.getRegionCount());
280    assertEquals(1, stateInfo.getTables().size());
281    ADMIN.disableTable(tableDescTwo.getTableName());
282    deleteTable(tableDescTwo.getTableName());
283    ADMIN.deleteNamespace(namespace);
284    stateInfo = getNamespaceState(namespace);
285    assertNull("Namespace state not found to be null.", stateInfo);
286  }
287
288  public static class CPRegionServerObserver
289      implements RegionServerCoprocessor, RegionServerObserver {
290    private volatile boolean shouldFailMerge = false;
291
292    public void failMerge(boolean fail) {
293      shouldFailMerge = fail;
294    }
295
296    private boolean triggered = false;
297
298    public synchronized void waitUtilTriggered() throws InterruptedException {
299      while (!triggered) {
300        wait();
301      }
302    }
303
304    @Override
305    public Optional<RegionServerObserver> getRegionServerObserver() {
306      return Optional.of(this);
307    }
308  }
309
310  public static class CPMasterObserver implements MasterCoprocessor, MasterObserver {
311    private volatile boolean shouldFailMerge = false;
312
313    public void failMerge(boolean fail) {
314      shouldFailMerge = fail;
315    }
316
317    @Override
318    public Optional<MasterObserver> getMasterObserver() {
319      return Optional.of(this);
320    }
321
322    @Override
323    public synchronized void preMergeRegionsAction(
324        final ObserverContext<MasterCoprocessorEnvironment> ctx,
325        final RegionInfo[] regionsToMerge) throws IOException {
326      notifyAll();
327      if (shouldFailMerge) {
328        throw new IOException("fail merge");
329      }
330    }
331  }
332
333  @Test
334  public void testRegionMerge() throws Exception {
335    String nsp1 = prefix + "_regiontest";
336    final int initialRegions = 3;
337    NamespaceDescriptor nspDesc =
338        NamespaceDescriptor.create(nsp1)
339            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "" + initialRegions)
340            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2").build();
341    ADMIN.createNamespace(nspDesc);
342    final TableName tableTwo = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table2");
343    byte[] columnFamily = Bytes.toBytes("info");
344    HTableDescriptor tableDescOne = new HTableDescriptor(tableTwo);
345    tableDescOne.addFamily(new HColumnDescriptor(columnFamily));
346    ADMIN.createTable(tableDescOne, Bytes.toBytes("0"), Bytes.toBytes("9"), initialRegions);
347    Connection connection = ConnectionFactory.createConnection(UTIL.getConfiguration());
348    try (Table table = connection.getTable(tableTwo)) {
349      UTIL.loadNumericRows(table, Bytes.toBytes("info"), 1000, 1999);
350    }
351    ADMIN.flush(tableTwo);
352    List<RegionInfo> hris = ADMIN.getRegions(tableTwo);
353    assertEquals(initialRegions, hris.size());
354    Collections.sort(hris, RegionInfo.COMPARATOR);
355    Future<?> f = ADMIN.mergeRegionsAsync(
356      hris.get(0).getEncodedNameAsBytes(),
357      hris.get(1).getEncodedNameAsBytes(),
358      false);
359    f.get(10, TimeUnit.SECONDS);
360
361    hris = ADMIN.getRegions(tableTwo);
362    assertEquals(initialRegions - 1, hris.size());
363    Collections.sort(hris, RegionInfo.COMPARATOR);
364    byte[] splitKey = Bytes.toBytes("3");
365    HRegion regionToSplit = UTIL.getMiniHBaseCluster().getRegions(tableTwo).stream()
366      .filter(r -> r.getRegionInfo().containsRow(splitKey)).findFirst().get();
367    regionToSplit.compact(true);
368    // the above compact may quit immediately if there is a compaction ongoing, so here we need to
369    // wait a while to let the ongoing compaction finish.
370    UTIL.waitFor(10000, regionToSplit::isSplittable);
371    ADMIN.splitRegionAsync(regionToSplit.getRegionInfo().getRegionName(), splitKey).get(10,
372      TimeUnit.SECONDS);
373    hris = ADMIN.getRegions(tableTwo);
374    assertEquals(initialRegions, hris.size());
375    Collections.sort(hris, RegionInfo.COMPARATOR);
376
377    // Fail region merge through Coprocessor hook
378    MiniHBaseCluster cluster = UTIL.getHBaseCluster();
379    MasterCoprocessorHost cpHost = cluster.getMaster().getMasterCoprocessorHost();
380    Coprocessor coprocessor = cpHost.findCoprocessor(CPMasterObserver.class);
381    CPMasterObserver masterObserver = (CPMasterObserver) coprocessor;
382    masterObserver.failMerge(true);
383
384    f = ADMIN.mergeRegionsAsync(
385      hris.get(1).getEncodedNameAsBytes(),
386      hris.get(2).getEncodedNameAsBytes(),
387      false);
388    try {
389      f.get(10, TimeUnit.SECONDS);
390      fail("Merge was supposed to fail!");
391    } catch (ExecutionException ee) {
392      // Expected.
393    }
394    hris = ADMIN.getRegions(tableTwo);
395    assertEquals(initialRegions, hris.size());
396    Collections.sort(hris, RegionInfo.COMPARATOR);
397    // verify that we cannot split
398    try {
399      ADMIN.split(tableTwo, Bytes.toBytes("6"));
400      fail();
401    } catch (DoNotRetryRegionException e) {
402      // Expected
403    }
404    Thread.sleep(2000);
405    assertEquals(initialRegions, ADMIN.getRegions(tableTwo).size());
406  }
407
408  /*
409   * Create a table and make sure that the table creation fails after adding this table entry into
410   * namespace quota cache. Now correct the failure and recreate the table with same name.
411   * HBASE-13394
412   */
413  @Test
414  public void testRecreateTableWithSameNameAfterFirstTimeFailure() throws Exception {
415    String nsp1 = prefix + "_testRecreateTable";
416    NamespaceDescriptor nspDesc =
417        NamespaceDescriptor.create(nsp1)
418            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "20")
419            .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "1").build();
420    ADMIN.createNamespace(nspDesc);
421    final TableName tableOne = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table1");
422    byte[] columnFamily = Bytes.toBytes("info");
423    HTableDescriptor tableDescOne = new HTableDescriptor(tableOne);
424    tableDescOne.addFamily(new HColumnDescriptor(columnFamily));
425    MasterSyncObserver.throwExceptionInPreCreateTableAction = true;
426    try {
427      try {
428        ADMIN.createTable(tableDescOne);
429        fail("Table " + tableOne.toString() + "creation should fail.");
430      } catch (Exception exp) {
431        LOG.error(exp.toString(), exp);
432      }
433      assertFalse(ADMIN.tableExists(tableOne));
434
435      NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp1);
436      assertEquals("First table creation failed in namespace so number of tables in namespace "
437          + "should be 0.", 0, nstate.getTables().size());
438
439      MasterSyncObserver.throwExceptionInPreCreateTableAction = false;
440      try {
441        ADMIN.createTable(tableDescOne);
442      } catch (Exception e) {
443        fail("Table " + tableOne.toString() + "creation should succeed.");
444        LOG.error(e.toString(), e);
445      }
446      assertTrue(ADMIN.tableExists(tableOne));
447      nstate = getNamespaceState(nsp1);
448      assertEquals("First table was created successfully so table size in namespace should "
449          + "be one now.", 1, nstate.getTables().size());
450    } finally {
451      MasterSyncObserver.throwExceptionInPreCreateTableAction = false;
452      if (ADMIN.tableExists(tableOne)) {
453        ADMIN.disableTable(tableOne);
454        deleteTable(tableOne);
455      }
456      ADMIN.deleteNamespace(nsp1);
457    }
458  }
459
460  private NamespaceTableAndRegionInfo getNamespaceState(String namespace) throws KeeperException,
461      IOException {
462    return getQuotaManager().getState(namespace);
463  }
464
465  byte[] getSplitKey(byte[] startKey, byte[] endKey) {
466    String skey = Bytes.toString(startKey);
467    int key;
468    if (StringUtils.isBlank(skey)) {
469      key = Integer.parseInt(Bytes.toString(endKey))/2 ;
470    } else {
471      key = (int) (Integer.parseInt(skey) * 1.5);
472    }
473    return Bytes.toBytes("" + key);
474  }
475
476  public static class CustomObserver implements RegionCoprocessor, RegionObserver {
477    volatile CountDownLatch postCompact;
478
479    @Override
480    public void postCompact(ObserverContext<RegionCoprocessorEnvironment> e, Store store,
481        StoreFile resultFile, CompactionLifeCycleTracker tracker, CompactionRequest request)
482        throws IOException {
483      postCompact.countDown();
484    }
485
486    @Override
487    public void start(CoprocessorEnvironment e) throws IOException {
488      postCompact = new CountDownLatch(1);
489    }
490
491    @Override
492    public Optional<RegionObserver> getRegionObserver() {
493      return Optional.of(this);
494    }
495  }
496
497  @Test
498  public void testStatePreserve() throws Exception {
499    final String nsp1 = prefix + "_testStatePreserve";
500    NamespaceDescriptor nspDesc = NamespaceDescriptor.create(nsp1)
501        .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "20")
502        .addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "10").build();
503    ADMIN.createNamespace(nspDesc);
504    TableName tableOne = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table1");
505    TableName tableTwo = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table2");
506    TableName tableThree = TableName.valueOf(nsp1 + TableName.NAMESPACE_DELIM + "table3");
507    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
508    HTableDescriptor tableDescOne = new HTableDescriptor(tableOne);
509    tableDescOne.addFamily(fam1);
510    HTableDescriptor tableDescTwo = new HTableDescriptor(tableTwo);
511    tableDescTwo.addFamily(fam1);
512    HTableDescriptor tableDescThree = new HTableDescriptor(tableThree);
513    tableDescThree.addFamily(fam1);
514    ADMIN.createTable(tableDescOne, Bytes.toBytes("1"), Bytes.toBytes("1000"), 3);
515    ADMIN.createTable(tableDescTwo, Bytes.toBytes("1"), Bytes.toBytes("1000"), 3);
516    ADMIN.createTable(tableDescThree, Bytes.toBytes("1"), Bytes.toBytes("1000"), 4);
517    ADMIN.disableTable(tableThree);
518    deleteTable(tableThree);
519    // wait for chore to complete
520    UTIL.waitFor(1000, new Waiter.Predicate<Exception>() {
521      @Override
522      public boolean evaluate() throws Exception {
523       return (getNamespaceState(nsp1).getTables().size() == 2);
524      }
525    });
526    NamespaceTableAndRegionInfo before = getNamespaceState(nsp1);
527    restartMaster();
528    NamespaceTableAndRegionInfo after = getNamespaceState(nsp1);
529    assertEquals("Expected: " + before.getTables() + " Found: " + after.getTables(), before
530        .getTables().size(), after.getTables().size());
531  }
532
533  public static void waitForQuotaInitialize(final HBaseTestingUtility util) throws Exception {
534    util.waitFor(60000, new Waiter.Predicate<Exception>() {
535      @Override
536      public boolean evaluate() throws Exception {
537        HMaster master = util.getHBaseCluster().getMaster();
538        if (master == null) {
539          return false;
540        }
541        MasterQuotaManager quotaManager = master.getMasterQuotaManager();
542        return quotaManager != null && quotaManager.isQuotaInitialized();
543      }
544    });
545  }
546
547  private void restartMaster() throws Exception {
548    UTIL.getHBaseCluster().getMaster(0).stop("Stopping to start again");
549    UTIL.getHBaseCluster().waitOnMaster(0);
550    UTIL.getHBaseCluster().startMaster();
551    waitForQuotaInitialize(UTIL);
552  }
553
554  private NamespaceAuditor getQuotaManager() {
555    return UTIL.getHBaseCluster().getMaster()
556        .getMasterQuotaManager().getNamespaceQuotaManager();
557  }
558
559  public static class MasterSyncObserver implements MasterCoprocessor, MasterObserver {
560    volatile CountDownLatch tableDeletionLatch;
561    static boolean throwExceptionInPreCreateTableAction;
562
563    @Override
564    public Optional<MasterObserver> getMasterObserver() {
565      return Optional.of(this);
566    }
567
568    @Override
569    public void preDeleteTable(ObserverContext<MasterCoprocessorEnvironment> ctx,
570        TableName tableName) throws IOException {
571      tableDeletionLatch = new CountDownLatch(1);
572    }
573
574    @Override
575    public void postCompletedDeleteTableAction(
576        final ObserverContext<MasterCoprocessorEnvironment> ctx,
577        final TableName tableName) throws IOException {
578      tableDeletionLatch.countDown();
579    }
580
581    @Override
582    public void preCreateTableAction(ObserverContext<MasterCoprocessorEnvironment> ctx,
583        TableDescriptor desc, RegionInfo[] regions) throws IOException {
584      if (throwExceptionInPreCreateTableAction) {
585        throw new IOException("Throw exception as it is demanded.");
586      }
587    }
588  }
589
590  private void deleteTable(final TableName tableName) throws Exception {
591    // NOTE: We need a latch because admin is not sync,
592    // so the postOp coprocessor method may be called after the admin operation returned.
593    MasterSyncObserver observer = UTIL.getHBaseCluster().getMaster()
594      .getMasterCoprocessorHost().findCoprocessor(MasterSyncObserver.class);
595    ADMIN.deleteTable(tableName);
596    observer.tableDeletionLatch.await();
597  }
598
599  @Test(expected = QuotaExceededException.class)
600  public void testExceedTableQuotaInNamespace() throws Exception {
601    String nsp = prefix + "_testExceedTableQuotaInNamespace";
602    NamespaceDescriptor nspDesc =
603        NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "1")
604            .build();
605    ADMIN.createNamespace(nspDesc);
606    assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp));
607    assertEquals(3, ADMIN.listNamespaceDescriptors().length);
608    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
609    HTableDescriptor tableDescOne =
610        new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1"));
611    tableDescOne.addFamily(fam1);
612    HTableDescriptor tableDescTwo =
613        new HTableDescriptor(TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2"));
614    tableDescTwo.addFamily(fam1);
615    ADMIN.createTable(tableDescOne);
616    ADMIN.createTable(tableDescTwo, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4);
617  }
618
619  @Test(expected = QuotaExceededException.class)
620  public void testCloneSnapshotQuotaExceed() throws Exception {
621    String nsp = prefix + "_testTableQuotaExceedWithCloneSnapshot";
622    NamespaceDescriptor nspDesc =
623        NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "1")
624            .build();
625    ADMIN.createNamespace(nspDesc);
626    assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp));
627    TableName tableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1");
628    TableName cloneTableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2");
629    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
630    HTableDescriptor tableDescOne = new HTableDescriptor(tableName);
631    tableDescOne.addFamily(fam1);
632    ADMIN.createTable(tableDescOne);
633    String snapshot = "snapshot_testTableQuotaExceedWithCloneSnapshot";
634    ADMIN.snapshot(snapshot, tableName);
635    ADMIN.cloneSnapshot(snapshot, cloneTableName);
636    ADMIN.deleteSnapshot(snapshot);
637  }
638
639  @Test
640  public void testCloneSnapshot() throws Exception {
641    String nsp = prefix + "_testCloneSnapshot";
642    NamespaceDescriptor nspDesc =
643        NamespaceDescriptor.create(nsp).addConfiguration(TableNamespaceManager.KEY_MAX_TABLES, "2")
644            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "20").build();
645    ADMIN.createNamespace(nspDesc);
646    assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp));
647    TableName tableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1");
648    TableName cloneTableName = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table2");
649
650    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
651    HTableDescriptor tableDescOne = new HTableDescriptor(tableName);
652    tableDescOne.addFamily(fam1);
653
654    ADMIN.createTable(tableDescOne, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4);
655    String snapshot = "snapshot_testCloneSnapshot";
656    ADMIN.snapshot(snapshot, tableName);
657    ADMIN.cloneSnapshot(snapshot, cloneTableName);
658
659    int tableLength;
660    try (RegionLocator locator = ADMIN.getConnection().getRegionLocator(tableName)) {
661      tableLength = locator.getStartKeys().length;
662    }
663    assertEquals(tableName.getNameAsString() + " should have four regions.", 4, tableLength);
664
665    try (RegionLocator locator = ADMIN.getConnection().getRegionLocator(cloneTableName)) {
666      tableLength = locator.getStartKeys().length;
667    }
668    assertEquals(cloneTableName.getNameAsString() + " should have four regions.", 4, tableLength);
669
670    NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp);
671    assertEquals("Total tables count should be 2.", 2, nstate.getTables().size());
672    assertEquals("Total regions count should be.", 8, nstate.getRegionCount());
673
674    ADMIN.deleteSnapshot(snapshot);
675  }
676
677  @Test
678  public void testRestoreSnapshot() throws Exception {
679    String nsp = prefix + "_testRestoreSnapshot";
680    NamespaceDescriptor nspDesc =
681        NamespaceDescriptor.create(nsp)
682            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10").build();
683    ADMIN.createNamespace(nspDesc);
684    assertNotNull("Namespace descriptor found null.", ADMIN.getNamespaceDescriptor(nsp));
685    TableName tableName1 = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1");
686    HTableDescriptor tableDescOne = new HTableDescriptor(tableName1);
687    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
688    tableDescOne.addFamily(fam1);
689    ADMIN.createTable(tableDescOne, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4);
690
691    NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp);
692    assertEquals("Intial region count should be 4.", 4, nstate.getRegionCount());
693
694    String snapshot = "snapshot_testRestoreSnapshot";
695    ADMIN.snapshot(snapshot, tableName1);
696
697    List<HRegionInfo> regions = ADMIN.getTableRegions(tableName1);
698    Collections.sort(regions);
699
700    ADMIN.split(tableName1, Bytes.toBytes("JJJ"));
701    Thread.sleep(2000);
702    assertEquals("Total regions count should be 5.", 5, nstate.getRegionCount());
703
704    ADMIN.disableTable(tableName1);
705    ADMIN.restoreSnapshot(snapshot);
706
707    assertEquals("Total regions count should be 4 after restore.", 4, nstate.getRegionCount());
708
709    ADMIN.enableTable(tableName1);
710    ADMIN.deleteSnapshot(snapshot);
711  }
712
713  @Test
714  public void testRestoreSnapshotQuotaExceed() throws Exception {
715    String nsp = prefix + "_testRestoreSnapshotQuotaExceed";
716    NamespaceDescriptor nspDesc =
717        NamespaceDescriptor.create(nsp)
718            .addConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "10").build();
719    ADMIN.createNamespace(nspDesc);
720    NamespaceDescriptor ndesc = ADMIN.getNamespaceDescriptor(nsp);
721    assertNotNull("Namespace descriptor found null.", ndesc);
722    TableName tableName1 = TableName.valueOf(nsp + TableName.NAMESPACE_DELIM + "table1");
723    HTableDescriptor tableDescOne = new HTableDescriptor(tableName1);
724    HColumnDescriptor fam1 = new HColumnDescriptor("fam1");
725    tableDescOne.addFamily(fam1);
726
727    ADMIN.createTable(tableDescOne, Bytes.toBytes("AAA"), Bytes.toBytes("ZZZ"), 4);
728
729    NamespaceTableAndRegionInfo nstate = getNamespaceState(nsp);
730    assertEquals("Intial region count should be 4.", 4, nstate.getRegionCount());
731
732    String snapshot = "snapshot_testRestoreSnapshotQuotaExceed";
733    // snapshot has 4 regions
734    ADMIN.snapshot(snapshot, tableName1);
735    // recreate table with 1 region and set max regions to 3 for namespace
736    ADMIN.disableTable(tableName1);
737    ADMIN.deleteTable(tableName1);
738    ADMIN.createTable(tableDescOne);
739    ndesc.setConfiguration(TableNamespaceManager.KEY_MAX_REGIONS, "3");
740    ADMIN.modifyNamespace(ndesc);
741
742    ADMIN.disableTable(tableName1);
743    try {
744      ADMIN.restoreSnapshot(snapshot);
745      fail("Region quota is exceeded so QuotaExceededException should be thrown but HBaseAdmin"
746          + " wraps IOException into RestoreSnapshotException");
747    } catch (RestoreSnapshotException ignore) {
748      assertTrue(ignore.getCause() instanceof QuotaExceededException);
749    }
750    assertEquals(1, getNamespaceState(nsp).getRegionCount());
751    ADMIN.enableTable(tableName1);
752    ADMIN.deleteSnapshot(snapshot);
753  }
754}