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.master.janitor;
019
020import static org.junit.Assert.assertFalse;
021import static org.junit.Assert.assertNotNull;
022import static org.junit.Assert.assertTrue;
023
024import java.io.IOException;
025import java.util.ArrayList;
026import java.util.List;
027import java.util.concurrent.ExecutionException;
028import org.apache.hadoop.hbase.HBaseClassTestRule;
029import org.apache.hadoop.hbase.HBaseTestingUtility;
030import org.apache.hadoop.hbase.HRegionLocation;
031import org.apache.hadoop.hbase.MetaMockingUtil;
032import org.apache.hadoop.hbase.MetaTableAccessor;
033import org.apache.hadoop.hbase.TableName;
034import org.apache.hadoop.hbase.TableNameTestRule;
035import org.apache.hadoop.hbase.Waiter;
036import org.apache.hadoop.hbase.client.Admin;
037import org.apache.hadoop.hbase.client.Connection;
038import org.apache.hadoop.hbase.client.ConnectionFactory;
039import org.apache.hadoop.hbase.client.Get;
040import org.apache.hadoop.hbase.client.RegionInfo;
041import org.apache.hadoop.hbase.client.RegionLocator;
042import org.apache.hadoop.hbase.client.Result;
043import org.apache.hadoop.hbase.client.Table;
044import org.apache.hadoop.hbase.master.HMaster;
045import org.apache.hadoop.hbase.master.ServerManager;
046import org.apache.hadoop.hbase.master.assignment.AssignmentManager;
047import org.apache.hadoop.hbase.master.assignment.GCRegionProcedure;
048import org.apache.hadoop.hbase.master.procedure.MasterProcedureEnv;
049import org.apache.hadoop.hbase.procedure2.Procedure;
050import org.apache.hadoop.hbase.procedure2.ProcedureExecutor;
051import org.apache.hadoop.hbase.testclassification.MasterTests;
052import org.apache.hadoop.hbase.testclassification.MediumTests;
053import org.apache.hadoop.hbase.util.Bytes;
054import org.apache.hadoop.hbase.util.EnvironmentEdgeManager;
055import org.apache.hadoop.hbase.util.PairOfSameType;
056import org.apache.hadoop.hbase.util.Threads;
057import org.junit.AfterClass;
058import org.junit.BeforeClass;
059import org.junit.ClassRule;
060import org.junit.Rule;
061import org.junit.Test;
062import org.junit.experimental.categories.Category;
063import org.slf4j.Logger;
064import org.slf4j.LoggerFactory;
065
066@Category({ MasterTests.class, MediumTests.class })
067public class TestCatalogJanitorInMemoryStates {
068
069  @ClassRule
070  public static final HBaseClassTestRule CLASS_RULE =
071    HBaseClassTestRule.forClass(TestCatalogJanitorInMemoryStates.class);
072
073  private static final Logger LOG = LoggerFactory.getLogger(TestCatalogJanitorInMemoryStates.class);
074
075  private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
076
077  private static byte[] FAMILY = Bytes.toBytes("testFamily");
078
079  @Rule
080  public final TableNameTestRule name = new TableNameTestRule();
081
082  @BeforeClass
083  public static void setUpBeforeClass() throws Exception {
084    TEST_UTIL.startMiniCluster(1);
085  }
086
087  @AfterClass
088  public static void tearDownAfterClass() throws Exception {
089    TEST_UTIL.shutdownMiniCluster();
090  }
091
092  /**
093   * Test clearing a split parent from memory.
094   */
095  @Test
096  public void testInMemoryParentCleanup()
097    throws IOException, InterruptedException, ExecutionException {
098    HMaster master = TEST_UTIL.getHBaseCluster().getMaster();
099    final AssignmentManager am = master.getAssignmentManager();
100    final ServerManager sm = master.getServerManager();
101
102    Admin admin = TEST_UTIL.getAdmin();
103    admin.enableCatalogJanitor(false);
104
105    final TableName tableName = name.getTableName();
106    Table t = TEST_UTIL.createTable(tableName, FAMILY);
107    TEST_UTIL.loadTable(t, FAMILY, false);
108
109    RegionLocator locator = TEST_UTIL.getConnection().getRegionLocator(tableName);
110    List<HRegionLocation> allRegionLocations = locator.getAllRegionLocations();
111
112    // We need to create a valid split with daughter regions
113    HRegionLocation parent = allRegionLocations.get(0);
114    List<HRegionLocation> daughters = splitRegion(parent.getRegionInfo());
115    LOG.info("Parent region: " + parent);
116    LOG.info("Daughter regions: " + daughters);
117    assertNotNull("Should have found daughter regions for " + parent, daughters);
118
119    assertTrue("Parent region should exist in RegionStates",
120      am.getRegionStates().isRegionInRegionStates(parent.getRegion()));
121    assertTrue("Parent region should exist in ServerManager",
122      sm.isRegionInServerManagerStates(parent.getRegion()));
123
124    // clean the parent
125    Result r = MetaMockingUtil.getMetaTableRowResult(parent.getRegion(), null,
126      daughters.get(0).getRegion(), daughters.get(1).getRegion());
127    CatalogJanitor.cleanParent(master, parent.getRegion(), r);
128
129    // wait for procedures to complete
130    Waiter.waitFor(TEST_UTIL.getConfiguration(), 10 * 1000, new Waiter.Predicate<Exception>() {
131      @Override
132      public boolean evaluate() throws Exception {
133        ProcedureExecutor<MasterProcedureEnv> pe = master.getMasterProcedureExecutor();
134        for (Procedure<MasterProcedureEnv> proc : pe.getProcedures()) {
135          if (proc.getClass().isAssignableFrom(GCRegionProcedure.class) && proc.isFinished()) {
136            return true;
137          }
138        }
139        return false;
140      }
141    });
142
143    assertFalse("Parent region should have been removed from RegionStates",
144      am.getRegionStates().isRegionInRegionStates(parent.getRegion()));
145    assertFalse("Parent region should have been removed from ServerManager",
146      sm.isRegionInServerManagerStates(parent.getRegion()));
147
148  }
149
150  /**
151   * Splits a region
152   * @param r Region to split.
153   * @return List of region locations
154   */
155  private List<HRegionLocation> splitRegion(final RegionInfo r)
156    throws IOException, InterruptedException, ExecutionException {
157    List<HRegionLocation> locations = new ArrayList<>();
158    // Split this table in two.
159    Admin admin = TEST_UTIL.getAdmin();
160    Connection connection = TEST_UTIL.getConnection();
161    admin.splitRegionAsync(r.getEncodedNameAsBytes()).get();
162    admin.close();
163    PairOfSameType<RegionInfo> regions = waitOnDaughters(r);
164    if (regions != null) {
165      try (RegionLocator rl = connection.getRegionLocator(r.getTable())) {
166        locations.add(rl.getRegionLocation(regions.getFirst().getEncodedNameAsBytes()));
167        locations.add(rl.getRegionLocation(regions.getSecond().getEncodedNameAsBytes()));
168      }
169      return locations;
170    }
171    return locations;
172  }
173
174  /*
175   * Wait on region split. May return because we waited long enough on the split and it didn't
176   * happen. Caller should check. n * @return Daughter regions; caller needs to check table actually
177   * split.
178   */
179  private PairOfSameType<RegionInfo> waitOnDaughters(final RegionInfo r) throws IOException {
180    long start = EnvironmentEdgeManager.currentTime();
181    PairOfSameType<RegionInfo> pair = null;
182    try (Connection conn = ConnectionFactory.createConnection(TEST_UTIL.getConfiguration());
183      Table metaTable = conn.getTable(TableName.META_TABLE_NAME)) {
184      Result result = null;
185      RegionInfo region = null;
186      while ((EnvironmentEdgeManager.currentTime() - start) < 60000) {
187        result = metaTable.get(new Get(r.getRegionName()));
188        if (result == null) {
189          break;
190        }
191        region = MetaTableAccessor.getRegionInfo(result);
192        if (region.isSplitParent()) {
193          LOG.debug(region.toString() + " IS a parent!");
194          pair = MetaTableAccessor.getDaughterRegions(result);
195          break;
196        }
197        Threads.sleep(100);
198      }
199
200      if (pair.getFirst() == null || pair.getSecond() == null) {
201        throw new IOException("Failed to get daughters, for parent region: " + r);
202      }
203      return pair;
204    }
205  }
206}