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 * http://www.apache.org/licenses/LICENSE-2.0
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.apache.hadoop.hbase.quotas;
017
018import static org.hamcrest.CoreMatchers.instanceOf;
019import static org.hamcrest.MatcherAssert.assertThat;
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertNull;
022import static org.junit.Assert.assertTrue;
023import static org.junit.Assert.fail;
024
025import java.io.IOException;
026import java.util.HashMap;
027import java.util.List;
028import java.util.Map;
029import java.util.concurrent.atomic.AtomicLong;
030import org.apache.hadoop.conf.Configuration;
031import org.apache.hadoop.fs.FileStatus;
032import org.apache.hadoop.fs.FileSystem;
033import org.apache.hadoop.fs.Path;
034import org.apache.hadoop.hbase.HBaseClassTestRule;
035import org.apache.hadoop.hbase.HBaseTestingUtil;
036import org.apache.hadoop.hbase.TableName;
037import org.apache.hadoop.hbase.client.Put;
038import org.apache.hadoop.hbase.client.RegionInfo;
039import org.apache.hadoop.hbase.client.ResultScanner;
040import org.apache.hadoop.hbase.client.Scan;
041import org.apache.hadoop.hbase.client.Table;
042import org.apache.hadoop.hbase.master.HMaster;
043import org.apache.hadoop.hbase.quotas.policies.DefaultViolationPolicyEnforcement;
044import org.apache.hadoop.hbase.regionserver.HRegionServer;
045import org.apache.hadoop.hbase.testclassification.MediumTests;
046import org.apache.hadoop.hbase.tool.BulkLoadHFiles;
047import org.apache.hadoop.hbase.util.Bytes;
048import org.junit.AfterClass;
049import org.junit.Before;
050import org.junit.BeforeClass;
051import org.junit.ClassRule;
052import org.junit.Rule;
053import org.junit.Test;
054import org.junit.experimental.categories.Category;
055import org.junit.rules.TestName;
056import org.slf4j.Logger;
057import org.slf4j.LoggerFactory;
058
059@Category(MediumTests.class)
060public class TestSpaceQuotaOnBulkLoad {
061
062  @ClassRule
063  public static final HBaseClassTestRule CLASS_RULE =
064      HBaseClassTestRule.forClass(TestSpaceQuotaOnBulkLoad.class);
065
066  private static final Logger LOG = LoggerFactory.getLogger(TestSpaceQuotaOnBulkLoad.class);
067  private static final HBaseTestingUtil TEST_UTIL = new HBaseTestingUtil();
068
069  @Rule
070  public TestName testName = new TestName();
071  private SpaceQuotaHelperForTests helper;
072
073  @BeforeClass
074  public static void setUp() throws Exception {
075    Configuration conf = TEST_UTIL.getConfiguration();
076    SpaceQuotaHelperForTests.updateConfigForQuotas(conf);
077    TEST_UTIL.startMiniCluster(1);
078  }
079
080  @AfterClass
081  public static void tearDown() throws Exception {
082    TEST_UTIL.shutdownMiniCluster();
083  }
084
085  @Before
086  public void removeAllQuotas() throws Exception {
087    helper = new SpaceQuotaHelperForTests(TEST_UTIL, testName, new AtomicLong(0));
088    helper.removeAllQuotas();
089  }
090
091  @Test
092  public void testNoBulkLoadsWithNoWrites() throws Exception {
093    Put p = new Put(Bytes.toBytes("to_reject"));
094    p.addColumn(Bytes.toBytes(SpaceQuotaHelperForTests.F1), Bytes.toBytes("to"),
095        Bytes.toBytes("reject"));
096    TableName tableName =
097        helper.writeUntilViolationAndVerifyViolation(SpaceViolationPolicy.NO_WRITES, p);
098
099    // The table is now in violation. Try to do a bulk load
100    Map<byte[], List<Path>> family2Files = helper.generateFileToLoad(tableName, 1, 50);
101    try {
102      BulkLoadHFiles.create(TEST_UTIL.getConfiguration()).bulkLoad(tableName, family2Files);
103      fail("Expected the bulk load call to fail!");
104    } catch (IOException e) {
105      // Pass
106      assertThat(e.getCause(), instanceOf(SpaceLimitingException.class));
107      LOG.trace("Caught expected exception", e);
108    }
109  }
110
111  @Test
112  public void testAtomicBulkLoadUnderQuota() throws Exception {
113    // Need to verify that if the batch of hfiles cannot be loaded, none are loaded.
114    TableName tn = helper.createTableWithRegions(10);
115
116    final long sizeLimit = 50L * SpaceQuotaHelperForTests.ONE_KILOBYTE;
117    QuotaSettings settings =
118        QuotaSettingsFactory.limitTableSpace(tn, sizeLimit, SpaceViolationPolicy.NO_INSERTS);
119    TEST_UTIL.getAdmin().setQuota(settings);
120
121    HRegionServer rs = TEST_UTIL.getMiniHBaseCluster().getRegionServer(0);
122    RegionServerSpaceQuotaManager spaceQuotaManager = rs.getRegionServerSpaceQuotaManager();
123    Map<TableName, SpaceQuotaSnapshot> snapshots = spaceQuotaManager.copyQuotaSnapshots();
124    Map<RegionInfo, Long> regionSizes = getReportedSizesForTable(tn);
125    while (true) {
126      SpaceQuotaSnapshot snapshot = snapshots.get(tn);
127      if (snapshot != null && snapshot.getLimit() > 0) {
128        break;
129      }
130      LOG.debug("Snapshot does not yet realize quota limit: " + snapshots + ", regionsizes: "
131          + regionSizes);
132      Thread.sleep(3000);
133      snapshots = spaceQuotaManager.copyQuotaSnapshots();
134      regionSizes = getReportedSizesForTable(tn);
135    }
136    // Our quota limit should be reflected in the latest snapshot
137    SpaceQuotaSnapshot snapshot = snapshots.get(tn);
138    assertEquals(0L, snapshot.getUsage());
139    assertEquals(sizeLimit, snapshot.getLimit());
140
141    // We would also not have a "real" policy in violation
142    ActivePolicyEnforcement activePolicies = spaceQuotaManager.getActiveEnforcements();
143    SpaceViolationPolicyEnforcement enforcement = activePolicies.getPolicyEnforcement(tn);
144    assertTrue("Expected to find Noop policy, but got " + enforcement.getClass().getSimpleName(),
145        enforcement instanceof DefaultViolationPolicyEnforcement);
146
147    // Should generate two files, each of which is over 25KB each
148    Map<byte[], List<Path>> family2Files = helper.generateFileToLoad(tn, 2, 525);
149    FileSystem fs = TEST_UTIL.getTestFileSystem();
150    FileStatus[] files =
151        fs.listStatus(new Path(fs.getHomeDirectory(), testName.getMethodName() + "_files"));
152    for (FileStatus file : files) {
153      assertTrue(
154          "Expected the file, " + file.getPath() + ",  length to be larger than 25KB, but was "
155              + file.getLen(), file.getLen() > 25 * SpaceQuotaHelperForTests.ONE_KILOBYTE);
156      LOG.debug(file.getPath() + " -> " + file.getLen() + "B");
157    }
158
159    try {
160      BulkLoadHFiles.create(TEST_UTIL.getConfiguration()).bulkLoad(tn, family2Files);
161      fail("Expected the bulk load call to fail!");
162    } catch (IOException e) {
163      // Pass
164      assertThat(e.getCause(), instanceOf(SpaceLimitingException.class));
165      LOG.trace("Caught expected exception", e);
166    }
167    // Verify that we have no data in the table because neither file should have been
168    // loaded even though one of the files could have.
169    Table table = TEST_UTIL.getConnection().getTable(tn);
170    ResultScanner scanner = table.getScanner(new Scan());
171    try {
172      assertNull("Expected no results", scanner.next());
173    } finally {
174      scanner.close();
175    }
176  }
177
178  private Map<RegionInfo, Long> getReportedSizesForTable(TableName tn) {
179    HMaster master = TEST_UTIL.getMiniHBaseCluster().getMaster();
180    MasterQuotaManager quotaManager = master.getMasterQuotaManager();
181    Map<RegionInfo, Long> filteredRegionSizes = new HashMap<>();
182    for (Map.Entry<RegionInfo, Long> entry : quotaManager.snapshotRegionSizes().entrySet()) {
183      if (entry.getKey().getTable().equals(tn)) {
184        filteredRegionSizes.put(entry.getKey(), entry.getValue());
185      }
186    }
187    return filteredRegionSizes;
188  }
189}