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.assignment; 019 020import static org.junit.jupiter.api.Assertions.assertEquals; 021import static org.junit.jupiter.api.Assertions.assertFalse; 022import static org.junit.jupiter.api.Assertions.assertNotEquals; 023import static org.junit.jupiter.api.Assertions.assertNotNull; 024import static org.junit.jupiter.api.Assertions.assertNull; 025import static org.junit.jupiter.api.Assertions.assertSame; 026import static org.junit.jupiter.api.Assertions.assertThrows; 027import static org.junit.jupiter.api.Assertions.assertTrue; 028 029import java.lang.management.ManagementFactory; 030import java.lang.management.ThreadInfo; 031import java.time.Instant; 032import java.util.Collections; 033import java.util.List; 034import java.util.Map; 035import java.util.Optional; 036import java.util.concurrent.CopyOnWriteArrayList; 037import java.util.concurrent.CountDownLatch; 038import java.util.concurrent.ExecutorService; 039import java.util.concurrent.Executors; 040import java.util.concurrent.Future; 041import java.util.concurrent.TimeUnit; 042import org.apache.hadoop.conf.Configuration; 043import org.apache.hadoop.fs.FileSystem; 044import org.apache.hadoop.fs.Path; 045import org.apache.hadoop.hbase.HConstants; 046import org.apache.hadoop.hbase.ServerName; 047import org.apache.hadoop.hbase.TableName; 048import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder; 049import org.apache.hadoop.hbase.client.RegionInfo; 050import org.apache.hadoop.hbase.client.RegionInfoBuilder; 051import org.apache.hadoop.hbase.client.TableDescriptor; 052import org.apache.hadoop.hbase.client.TableDescriptorBuilder; 053import org.apache.hadoop.hbase.client.TableState; 054import org.apache.hadoop.hbase.master.MetricsAssignmentManager; 055import org.apache.hadoop.hbase.master.TableStateManager; 056import org.apache.hadoop.hbase.master.hbck.HbckChore; 057import org.apache.hadoop.hbase.master.hbck.HbckReport; 058import org.apache.hadoop.hbase.regionserver.BloomType; 059import org.apache.hadoop.hbase.regionserver.HRegion; 060import org.apache.hadoop.hbase.testclassification.MasterTests; 061import org.apache.hadoop.hbase.testclassification.MediumTests; 062import org.apache.hadoop.hbase.util.Bytes; 063import org.apache.hadoop.hbase.util.CommonFSUtils; 064import org.apache.hadoop.hbase.util.FSTableDescriptors; 065import org.apache.hadoop.hbase.util.FSUtils; 066import org.apache.hadoop.hbase.util.Pair; 067import org.junit.jupiter.api.BeforeEach; 068import org.junit.jupiter.api.Tag; 069import org.junit.jupiter.api.Test; 070import org.mockito.Mockito; 071 072@Tag(MasterTests.TAG) 073@Tag(MediumTests.TAG) 074public class TestHbckChore extends TestAssignmentManagerBase { 075 076 private HbckChore hbckChore; 077 078 @BeforeEach 079 public void setUp() throws Exception { 080 super.setUp(); 081 hbckChore = new HbckChore(master); 082 } 083 084 @Test 085 public void testForMeta() { 086 byte[] metaRegionNameAsBytes = RegionInfoBuilder.FIRST_META_REGIONINFO.getRegionName(); 087 String metaRegionName = RegionInfoBuilder.FIRST_META_REGIONINFO.getRegionNameAsString(); 088 List<ServerName> serverNames = master.getServerManager().getOnlineServersList(); 089 assertEquals(NSERVERS, serverNames.size()); 090 091 hbckChore.choreForTesting(); 092 Map<String, Pair<ServerName, List<ServerName>>> inconsistentRegions = 093 hbckChore.getLastReport().getInconsistentRegions(); 094 095 // Test for case1: Master thought this region opened, but no regionserver reported it. 096 assertTrue(inconsistentRegions.containsKey(metaRegionName)); 097 Pair<ServerName, List<ServerName>> pair = inconsistentRegions.get(metaRegionName); 098 ServerName locationInMeta = pair.getFirst(); 099 List<ServerName> reportedRegionServers = pair.getSecond(); 100 assertTrue(serverNames.contains(locationInMeta)); 101 assertEquals(0, reportedRegionServers.size()); 102 103 // Reported right region location. Then not in problematic regions. 104 am.reportOnlineRegions(locationInMeta, Collections.singleton(metaRegionNameAsBytes)); 105 hbckChore.choreForTesting(); 106 inconsistentRegions = hbckChore.getLastReport().getInconsistentRegions(); 107 assertFalse(inconsistentRegions.containsKey(metaRegionName)); 108 } 109 110 @Test 111 public void testForUserTable() throws Exception { 112 TableName tableName = TableName.valueOf("testForUserTable"); 113 RegionInfo hri = createRegionInfo(tableName, 1); 114 String regionName = hri.getRegionNameAsString(); 115 rsDispatcher.setMockRsExecutor(new GoodRsExecutor()); 116 Future<byte[]> future = submitProcedure(createAssignProcedure(hri)); 117 waitOnFuture(future); 118 119 List<ServerName> serverNames = master.getServerManager().getOnlineServersList(); 120 assertEquals(NSERVERS, serverNames.size()); 121 122 // Test for case1: Master thought this region opened, but no regionserver reported it. 123 hbckChore.choreForTesting(); 124 Map<String, Pair<ServerName, List<ServerName>>> inconsistentRegions = 125 hbckChore.getLastReport().getInconsistentRegions(); 126 assertTrue(inconsistentRegions.containsKey(regionName)); 127 Pair<ServerName, List<ServerName>> pair = inconsistentRegions.get(regionName); 128 ServerName locationInMeta = pair.getFirst(); 129 List<ServerName> reportedRegionServers = pair.getSecond(); 130 assertTrue(serverNames.contains(locationInMeta)); 131 assertEquals(0, reportedRegionServers.size()); 132 133 // Test for case2: Master thought this region opened on Server1, but regionserver reported 134 // Server2 135 final ServerName tempLocationInMeta = locationInMeta; 136 final ServerName anotherServer = 137 serverNames.stream().filter(s -> !s.equals(tempLocationInMeta)).findFirst().get(); 138 am.reportOnlineRegions(anotherServer, Collections.singleton(hri.getRegionName())); 139 hbckChore.choreForTesting(); 140 inconsistentRegions = hbckChore.getLastReport().getInconsistentRegions(); 141 assertTrue(inconsistentRegions.containsKey(regionName)); 142 pair = inconsistentRegions.get(regionName); 143 locationInMeta = pair.getFirst(); 144 reportedRegionServers = pair.getSecond(); 145 assertEquals(1, reportedRegionServers.size()); 146 assertFalse(reportedRegionServers.contains(locationInMeta)); 147 assertTrue(reportedRegionServers.contains(anotherServer)); 148 149 // Test for case3: More than one regionservers reported opened this region. 150 am.reportOnlineRegions(locationInMeta, Collections.singleton(hri.getRegionName())); 151 hbckChore.choreForTesting(); 152 inconsistentRegions = hbckChore.getLastReport().getInconsistentRegions(); 153 assertTrue(inconsistentRegions.containsKey(regionName)); 154 pair = inconsistentRegions.get(regionName); 155 locationInMeta = pair.getFirst(); 156 reportedRegionServers = pair.getSecond(); 157 assertEquals(2, reportedRegionServers.size()); 158 assertTrue(reportedRegionServers.contains(locationInMeta)); 159 assertTrue(reportedRegionServers.contains(anotherServer)); 160 161 // Reported right region location, then not in inconsistent regions. 162 am.reportOnlineRegions(anotherServer, Collections.emptySet()); 163 hbckChore.choreForTesting(); 164 inconsistentRegions = hbckChore.getLastReport().getInconsistentRegions(); 165 assertFalse(inconsistentRegions.containsKey(regionName)); 166 167 // Test for case4: No region location for a previously reported region. Probably due to 168 // TRSP bug or bypass. 169 am.offlineRegion(hri); 170 hbckChore.choreForTesting(); 171 inconsistentRegions = hbckChore.getLastReport().getInconsistentRegions(); 172 assertTrue(inconsistentRegions.containsKey(regionName)); 173 } 174 175 @Test 176 public void testForDisabledTable() throws Exception { 177 TableName tableName = TableName.valueOf("testForDisabledTable"); 178 RegionInfo hri = createRegionInfo(tableName, 1); 179 String regionName = hri.getRegionNameAsString(); 180 rsDispatcher.setMockRsExecutor(new GoodRsExecutor()); 181 Future<byte[]> future = submitProcedure(createAssignProcedure(hri)); 182 waitOnFuture(future); 183 184 List<ServerName> serverNames = master.getServerManager().getOnlineServersList(); 185 assertEquals(NSERVERS, serverNames.size()); 186 187 hbckChore.choreForTesting(); 188 Map<String, Pair<ServerName, List<ServerName>>> inconsistentRegions = 189 hbckChore.getLastReport().getInconsistentRegions(); 190 assertTrue(inconsistentRegions.containsKey(regionName)); 191 Pair<ServerName, List<ServerName>> pair = inconsistentRegions.get(regionName); 192 ServerName locationInMeta = pair.getFirst(); 193 List<ServerName> reportedRegionServers = pair.getSecond(); 194 assertTrue(serverNames.contains(locationInMeta)); 195 assertEquals(0, reportedRegionServers.size()); 196 197 // Set table state to disabled, then not in inconsistent regions. 198 TableStateManager tableStateManager = master.getTableStateManager(); 199 Mockito.when(tableStateManager.isTableState(tableName, TableState.State.DISABLED)) 200 .thenReturn(true); 201 hbckChore.choreForTesting(); 202 inconsistentRegions = hbckChore.getLastReport().getInconsistentRegions(); 203 assertFalse(inconsistentRegions.containsKey(regionName)); 204 } 205 206 @Test 207 public void testForSplitParent() throws Exception { 208 TableName tableName = TableName.valueOf("testForSplitParent"); 209 RegionInfo hri = RegionInfoBuilder.newBuilder(tableName).setStartKey(Bytes.toBytes(0)) 210 .setEndKey(Bytes.toBytes(1)).setSplit(true).setOffline(true).setRegionId(0).build(); 211 String regionName = hri.getEncodedName(); 212 rsDispatcher.setMockRsExecutor(new GoodRsExecutor()); 213 Future<byte[]> future = submitProcedure(createAssignProcedure(hri)); 214 waitOnFuture(future); 215 216 List<ServerName> serverNames = master.getServerManager().getOnlineServersList(); 217 assertEquals(NSERVERS, serverNames.size()); 218 219 hbckChore.choreForTesting(); 220 Map<String, Pair<ServerName, List<ServerName>>> inconsistentRegions = 221 hbckChore.getLastReport().getInconsistentRegions(); 222 assertFalse(inconsistentRegions.containsKey(regionName)); 223 } 224 225 @Test 226 public void testOrphanRegionsOnFS() throws Exception { 227 TableName tableName = TableName.valueOf("testOrphanRegionsOnFS"); 228 RegionInfo regionInfo = RegionInfoBuilder.newBuilder(tableName).build(); 229 Configuration conf = util.getConfiguration(); 230 231 hbckChore.choreForTesting(); 232 assertEquals(0, hbckChore.getLastReport().getOrphanRegionsOnFS().size()); 233 234 HRegion.createRegionDir(conf, regionInfo, CommonFSUtils.getRootDir(conf)); 235 hbckChore.choreForTesting(); 236 assertEquals(1, hbckChore.getLastReport().getOrphanRegionsOnFS().size()); 237 assertTrue( 238 hbckChore.getLastReport().getOrphanRegionsOnFS().containsKey(regionInfo.getEncodedName())); 239 240 FSUtils.deleteRegionDir(conf, regionInfo); 241 hbckChore.choreForTesting(); 242 assertEquals(0, hbckChore.getLastReport().getOrphanRegionsOnFS().size()); 243 } 244 245 @Test 246 public void testChoreDisable() { 247 // The way to disable to chore is to set hbase.master.hbck.chore.interval <= 0 248 // When the interval is > 0, the chore should run. 249 Instant lastRunTime = Optional.ofNullable(hbckChore.getLastReport()) 250 .map(HbckReport::getCheckingEndTimestamp).orElse(null); 251 hbckChore.choreForTesting(); 252 Instant thisRunTime = Optional.ofNullable(hbckChore.getLastReport()) 253 .map(HbckReport::getCheckingEndTimestamp).orElse(null); 254 assertNotNull(thisRunTime); 255 assertNotEquals(lastRunTime, thisRunTime); 256 257 // When the interval <= 0, the chore shouldn't run 258 master.getConfiguration().setInt("hbase.master.hbck.chore.interval", 0); 259 HbckChore hbckChoreWithChangedConf = new HbckChore(master); 260 hbckChoreWithChangedConf.choreForTesting(); 261 assertNull(hbckChoreWithChangedConf.getLastReport()); 262 } 263 264 @Test 265 public void testConcurrentTriggersAreRejected() throws Exception { 266 final CountDownLatch scanStarted = new CountDownLatch(1); 267 final CountDownLatch resumeScan = new CountDownLatch(1); 268 final MockMasterServices blockingMaster = Mockito.spy(master); 269 Mockito.doAnswer(invocation -> { 270 scanStarted.countDown(); 271 assertTrue(resumeScan.await(30, TimeUnit.SECONDS), "Timed out waiting to resume the scan"); 272 return am; 273 }).when(blockingMaster).getAssignmentManager(); 274 final HbckChore chore = new HbckChore(blockingMaster); 275 final ExecutorService concurrentExecutor = Executors.newFixedThreadPool(2); 276 try { 277 // Wait until the first scan is running and paused. 278 final Future<Boolean> first = concurrentExecutor.submit(chore::runChore); 279 assertTrue(scanStarted.await(10, TimeUnit.SECONDS), "The first scan did not start"); 280 281 // The second invocation is rejected before the first scan finishes; no report is published. 282 final Future<Boolean> second = concurrentExecutor.submit(chore::runChore); 283 assertFalse(second.get(10, TimeUnit.SECONDS)); 284 assertNull(chore.getLastReport()); 285 286 // Resume the first scan and verify that it completes and publishes a report. 287 resumeScan.countDown(); 288 assertTrue(first.get(10, TimeUnit.SECONDS)); 289 assertNotNull(chore.getLastReport()); 290 } finally { 291 resumeScan.countDown(); 292 concurrentExecutor.shutdownNow(); 293 concurrentExecutor.awaitTermination(30, TimeUnit.SECONDS); 294 } 295 } 296 297 @Test 298 public void testConcurrentTriggersBeforeRunningStateIsSet() throws Exception { 299 final CountDownLatch latch = new CountDownLatch(1); 300 final MockMasterServices blockingMaster = Mockito.spy(master); 301 Mockito.doAnswer(invocation -> { 302 latch.await(); 303 return am; 304 }).when(blockingMaster).getAssignmentManager(); 305 final HbckChore chore = new HbckChore(blockingMaster); 306 final List<Thread> callers = new CopyOnWriteArrayList<>(); 307 final ExecutorService concurrentExecutor = Executors.newFixedThreadPool(2, task -> { 308 final Thread thread = new Thread(task); 309 callers.add(thread); 310 return thread; 311 }); 312 try { 313 final Future<Boolean> first; 314 final Future<Boolean> second; 315 synchronized (chore) { 316 first = concurrentExecutor.submit(chore::runChore); 317 second = concurrentExecutor.submit(chore::runChore); 318 // Wait until both legacy callers pass the running check and wait for this monitor. 319 // With an atomic guard, the rejected invocation completes instead. 320 util.waitFor(10000, () -> first.isDone() || second.isDone() || (callers.size() == 2 321 && callers.stream().allMatch(thread -> isBlockedOnChore(thread, chore)))); 322 } 323 324 latch.countDown(); 325 // One invocation must return true and the other false, regardless of which starts first. 326 assertNotEquals(first.get(10, TimeUnit.SECONDS), second.get(10, TimeUnit.SECONDS), 327 "Exactly one concurrent invocation must execute"); 328 assertNotNull(chore.getLastReport()); 329 } finally { 330 latch.countDown(); 331 concurrentExecutor.shutdownNow(); 332 concurrentExecutor.awaitTermination(30, TimeUnit.SECONDS); 333 } 334 } 335 336 /** 337 * Checks whether the worker is waiting for the chore monitor held by the current test thread. 338 */ 339 private static boolean isBlockedOnChore(Thread thread, HbckChore chore) { 340 final ThreadInfo info = ManagementFactory.getThreadMXBean().getThreadInfo(thread.getId()); 341 return info != null && info.getThreadState() == Thread.State.BLOCKED 342 && info.getLockOwnerId() == Thread.currentThread().getId() && info.getLockInfo() != null 343 && info.getLockInfo().getIdentityHashCode() == System.identityHashCode(chore); 344 } 345 346 @Test 347 public void testRunningStateIsClearedAfterMetricsFailure() { 348 final MockMasterServices failingMaster = Mockito.spy(master); 349 final AssignmentManager assignmentManager = Mockito.spy(am); 350 final MetricsAssignmentManager metrics = Mockito.spy(am.getAssignmentManagerMetrics()); 351 Mockito.doReturn(assignmentManager).when(failingMaster).getAssignmentManager(); 352 Mockito.doReturn(metrics).when(assignmentManager).getAssignmentManagerMetrics(); 353 final HbckChore chore = new HbckChore(failingMaster); 354 355 // Fail the metrics update on the first run. 356 final IllegalStateException failure = new IllegalStateException("Metrics update failed"); 357 Mockito.doThrow(failure).when(metrics).updateOrphanRegionsOnRs(Mockito.anyInt()); 358 assertSame(failure, assertThrows(IllegalStateException.class, chore::runChore)); 359 360 // Replace the throwing stub so a second run can verify that the running state was cleared. 361 Mockito.doNothing().when(metrics).updateOrphanRegionsOnRs(Mockito.anyInt()); 362 assertTrue(chore.runChore()); 363 } 364 365 @Test 366 public void testChoreSkipsForeignMetaTables() throws Exception { 367 FileSystem fs = master.getMasterFileSystem().getFileSystem(); 368 Path rootDir = master.getMasterFileSystem().getRootDir(); 369 String[] metaTables = { "meta_replica1", "meta" }; 370 Path hbaseNamespaceDir = new Path(rootDir, HConstants.BASE_NAMESPACE_DIR + "/hbase"); 371 fs.mkdirs(hbaseNamespaceDir); 372 373 for (String metaTable : metaTables) { 374 TableName tableName = TableName.valueOf("hbase", metaTable); 375 Path metaTableDir = new Path(hbaseNamespaceDir, metaTable); 376 fs.mkdirs(metaTableDir); 377 fs.mkdirs(new Path(metaTableDir, FSTableDescriptors.TABLEINFO_DIR)); 378 fs.mkdirs(new Path(metaTableDir, "abcdef0123456789")); 379 380 TableDescriptor tableDescriptor = TableDescriptorBuilder.newBuilder(tableName) 381 .setColumnFamily(ColumnFamilyDescriptorBuilder.newBuilder(HConstants.CATALOG_FAMILY) 382 .setMaxVersions(HConstants.DEFAULT_HBASE_META_VERSIONS).setInMemory(true) 383 .setBlocksize(HConstants.DEFAULT_HBASE_META_BLOCK_SIZE) 384 .setBloomFilterType(BloomType.ROWCOL).build()) 385 .build(); 386 387 Path tableDir = CommonFSUtils.getTableDir(rootDir, tableName); 388 FSTableDescriptors.createTableDescriptorForTableDirectory(fs, tableDir, tableDescriptor, 389 false); 390 } 391 392 assertTrue(hbckChore.runChore(), "HbckChore should run successfully"); 393 HbckReport report = hbckChore.getLastReport(); 394 assertNotNull(report, "HbckReport should not be null"); 395 boolean hasForeignMetaOrphan = report.getOrphanRegionsOnFS().values().stream() 396 .anyMatch(path -> path.toString().contains("meta_replica1")); 397 assertFalse(hasForeignMetaOrphan, "HbckChore should not report foreign meta tables as orphans"); 398 } 399}