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.hbck; 019 020import java.io.IOException; 021import java.time.Instant; 022import java.util.HashMap; 023import java.util.HashSet; 024import java.util.LinkedList; 025import java.util.List; 026import java.util.Map; 027import java.util.Set; 028import java.util.concurrent.atomic.AtomicBoolean; 029import org.apache.hadoop.fs.FileSystem; 030import org.apache.hadoop.fs.Path; 031import org.apache.hadoop.hbase.CatalogFamilyFormat; 032import org.apache.hadoop.hbase.MetaTableAccessor; 033import org.apache.hadoop.hbase.ScheduledChore; 034import org.apache.hadoop.hbase.ServerName; 035import org.apache.hadoop.hbase.client.RegionInfo; 036import org.apache.hadoop.hbase.client.TableState; 037import org.apache.hadoop.hbase.master.MasterServices; 038import org.apache.hadoop.hbase.master.RegionState; 039import org.apache.hadoop.hbase.util.EnvironmentEdgeManager; 040import org.apache.hadoop.hbase.util.FSUtils; 041import org.apache.hadoop.hbase.util.HbckRegionInfo; 042import org.apache.hadoop.hbase.util.Pair; 043import org.apache.yetus.audience.InterfaceAudience; 044import org.apache.yetus.audience.InterfaceStability; 045import org.slf4j.Logger; 046import org.slf4j.LoggerFactory; 047 048/** 049 * Used to do the hbck checking job at master side. 050 */ 051@InterfaceAudience.Private 052@InterfaceStability.Evolving 053public class HbckChore extends ScheduledChore { 054 private static final Logger LOG = LoggerFactory.getLogger(HbckChore.class.getName()); 055 056 private static final String HBCK_CHORE_INTERVAL = "hbase.master.hbck.chore.interval"; 057 private static final int DEFAULT_HBCK_CHORE_INTERVAL = 60 * 60 * 1000; 058 059 private final MasterServices master; 060 061 /** 062 * Saved report from last time this chore ran. Check its date. 063 */ 064 private volatile HbckReport lastReport = null; 065 066 /** 067 * When running, the "snapshot" may be changed when this round's checking finish. 068 */ 069 private final AtomicBoolean running = new AtomicBoolean(false); 070 071 private boolean disabled = false; 072 073 public HbckChore(MasterServices master) { 074 super("HbckChore-", master, 075 master.getConfiguration().getInt(HBCK_CHORE_INTERVAL, DEFAULT_HBCK_CHORE_INTERVAL)); 076 this.master = master; 077 int interval = 078 master.getConfiguration().getInt(HBCK_CHORE_INTERVAL, DEFAULT_HBCK_CHORE_INTERVAL); 079 if (interval <= 0) { 080 LOG.warn(HBCK_CHORE_INTERVAL + " is <=0 hence disabling hbck chore"); 081 disableChore(); 082 } 083 } 084 085 /** 086 * Returns Returns last published Report that comes of last successful execution of this chore. 087 */ 088 public HbckReport getLastReport() { 089 return lastReport; 090 } 091 092 @Override 093 protected void chore() { 094 runChore(); 095 } 096 097 /** 098 * Request execution of this chore's action. 099 * @return {@code true} if the chore was executed, {@code false} if the chore is disabled or 100 * already running. 101 */ 102 public boolean runChore() { 103 if (isDisabled()) { 104 LOG.warn("hbck chore is disabled! Set " + HBCK_CHORE_INTERVAL + " > 0 to enable it."); 105 return false; 106 } 107 if (!running.compareAndSet(false, true)) { 108 LOG.warn("hbck chore already running. Can't run till it finishes."); 109 return false; 110 } 111 try { 112 final HbckReport report = new HbckReport(); 113 report.setCheckingStartTimestamp(Instant.ofEpochMilli(EnvironmentEdgeManager.currentTime())); 114 try { 115 loadRegionsFromInMemoryState(report); 116 loadRegionsFromRSReport(report); 117 try { 118 loadRegionsFromFS(scanForMergedParentRegions(), report); 119 } catch (IOException e) { 120 LOG.warn("Failed to load the regions from filesystem", e); 121 } 122 } catch (Throwable t) { 123 LOG.warn("Unexpected", t); 124 } 125 report.setCheckingEndTimestamp(Instant.ofEpochMilli(EnvironmentEdgeManager.currentTime())); 126 this.lastReport = report; 127 updateAssignmentManagerMetrics(report); 128 return true; 129 } finally { 130 running.set(false); 131 } 132 } 133 134 private void disableChore() { 135 this.disabled = true; 136 } 137 138 public boolean isDisabled() { 139 return this.disabled; 140 } 141 142 /** 143 * Scan hbase:meta to get set of merged parent regions, this is a very heavy scan. 144 * @return Return generated {@link HashSet} 145 */ 146 private HashSet<String> scanForMergedParentRegions() throws IOException { 147 HashSet<String> mergedParentRegions = new HashSet<>(); 148 // Null tablename means scan all of meta. 149 MetaTableAccessor.scanMetaForTableRegions(this.master.getConnection(), r -> { 150 List<RegionInfo> mergeParents = CatalogFamilyFormat.getMergeRegions(r.rawCells()); 151 if (mergeParents != null) { 152 for (RegionInfo mergeRegion : mergeParents) { 153 if (mergeRegion != null) { 154 // This region is already being merged 155 mergedParentRegions.add(mergeRegion.getEncodedName()); 156 } 157 } 158 } 159 return true; 160 }, null); 161 return mergedParentRegions; 162 } 163 164 private void loadRegionsFromInMemoryState(final HbckReport report) { 165 List<RegionState> regionStates = 166 master.getAssignmentManager().getRegionStates().getRegionStates(); 167 for (RegionState regionState : regionStates) { 168 RegionInfo regionInfo = regionState.getRegion(); 169 if ( 170 master.getTableStateManager().isTableState(regionInfo.getTable(), TableState.State.DISABLED) 171 ) { 172 report.getDisabledTableRegions().add(regionInfo.getRegionNameAsString()); 173 } 174 // Check both state and regioninfo for split status, see HBASE-26383 175 if (regionState.isSplit() || regionInfo.isSplit()) { 176 report.getSplitParentRegions().add(regionInfo.getRegionNameAsString()); 177 } 178 HbckRegionInfo.MetaEntry metaEntry = new HbckRegionInfo.MetaEntry(regionInfo, 179 regionState.getServerName(), regionState.getStamp()); 180 report.getRegionInfoMap().put(regionInfo.getEncodedName(), new HbckRegionInfo(metaEntry)); 181 } 182 LOG.info("Loaded {} regions ({} disabled, {} split parents) from in-memory state", 183 regionStates.size(), report.getDisabledTableRegions().size(), 184 report.getSplitParentRegions().size()); 185 if (LOG.isDebugEnabled()) { 186 Map<RegionState.State, Integer> stateCountMap = new HashMap<>(); 187 for (RegionState regionState : regionStates) { 188 stateCountMap.compute(regionState.getState(), (k, v) -> (v == null) ? 1 : v + 1); 189 } 190 StringBuffer sb = new StringBuffer(); 191 sb.append("Regions by state: "); 192 stateCountMap.entrySet().forEach(e -> { 193 sb.append(e.getKey()); 194 sb.append('='); 195 sb.append(e.getValue()); 196 sb.append(' '); 197 }); 198 LOG.debug(sb.toString()); 199 } 200 if (LOG.isTraceEnabled()) { 201 for (RegionState regionState : regionStates) { 202 LOG.trace("{}: {}, serverName={}", regionState.getRegion(), regionState.getState(), 203 regionState.getServerName()); 204 } 205 } 206 } 207 208 private void loadRegionsFromRSReport(final HbckReport report) { 209 int numRegions = 0; 210 Map<ServerName, Set<byte[]>> rsReports = master.getAssignmentManager().getRSReports(); 211 for (Map.Entry<ServerName, Set<byte[]>> entry : rsReports.entrySet()) { 212 ServerName serverName = entry.getKey(); 213 for (byte[] regionName : entry.getValue()) { 214 String encodedRegionName = RegionInfo.encodeRegionName(regionName); 215 HbckRegionInfo hri = report.getRegionInfoMap().get(encodedRegionName); 216 if (hri == null) { 217 report.getOrphanRegionsOnRS().put(RegionInfo.getRegionNameAsString(regionName), 218 serverName); 219 continue; 220 } 221 hri.addServer(hri.getMetaEntry().getRegionInfo(), serverName); 222 } 223 numRegions += entry.getValue().size(); 224 } 225 LOG.info("Loaded {} regions from {} regionservers' reports and found {} orphan regions", 226 numRegions, rsReports.size(), report.getOrphanRegionsOnRS().size()); 227 228 for (Map.Entry<String, HbckRegionInfo> entry : report.getRegionInfoMap().entrySet()) { 229 HbckRegionInfo hri = entry.getValue(); 230 ServerName locationInMeta = hri.getMetaEntry().getRegionServer(); // can be null 231 if (hri.getDeployedOn().size() == 0) { 232 // skip the offline region which belong to disabled table. 233 if (report.getDisabledTableRegions().contains(hri.getRegionNameAsString())) { 234 continue; 235 } 236 // skip the split parent regions 237 if (report.getSplitParentRegions().contains(hri.getRegionNameAsString())) { 238 continue; 239 } 240 // Master thought this region opened, but no regionserver reported it. 241 report.getInconsistentRegions().put(hri.getRegionNameAsString(), 242 new Pair<>(locationInMeta, new LinkedList<>())); 243 } else if (hri.getDeployedOn().size() > 1) { 244 // More than one regionserver reported opened this region 245 report.getInconsistentRegions().put(hri.getRegionNameAsString(), 246 new Pair<>(locationInMeta, hri.getDeployedOn())); 247 } else if (!hri.getDeployedOn().get(0).equals(locationInMeta)) { 248 // Master thought this region opened on Server1, but regionserver reported Server2 249 report.getInconsistentRegions().put(hri.getRegionNameAsString(), 250 new Pair<>(locationInMeta, hri.getDeployedOn())); 251 } 252 } 253 } 254 255 private void loadRegionsFromFS(final HashSet<String> mergedParentRegions, final HbckReport report) 256 throws IOException { 257 Path rootDir = master.getMasterFileSystem().getRootDir(); 258 FileSystem fs = master.getMasterFileSystem().getFileSystem(); 259 260 int numRegions = 0; 261 List<Path> tableDirs = 262 FSUtils.getTableDirs(fs, rootDir).stream().filter(FSUtils::isLocalMetaTable).toList(); 263 for (Path tableDir : tableDirs) { 264 List<Path> regionDirs = FSUtils.getRegionDirs(fs, tableDir); 265 for (Path regionDir : regionDirs) { 266 String encodedRegionName = regionDir.getName(); 267 if (encodedRegionName == null) { 268 LOG.warn("Failed get of encoded name from {}", regionDir); 269 continue; 270 } 271 HbckRegionInfo hri = report.getRegionInfoMap().get(encodedRegionName); 272 // If it is not in in-memory database and not a merged region, 273 // report it as an orphan region. 274 if (hri == null && !mergedParentRegions.contains(encodedRegionName)) { 275 report.getOrphanRegionsOnFS().put(encodedRegionName, regionDir); 276 continue; 277 } 278 } 279 numRegions += regionDirs.size(); 280 } 281 LOG.info("Loaded {} tables {} regions from filesystem and found {} orphan regions", 282 tableDirs.size(), numRegions, report.getOrphanRegionsOnFS().size()); 283 } 284 285 private void updateAssignmentManagerMetrics(final HbckReport report) { 286 master.getAssignmentManager().getAssignmentManagerMetrics() 287 .updateOrphanRegionsOnRs(report.getOrphanRegionsOnRS().size()); 288 master.getAssignmentManager().getAssignmentManagerMetrics() 289 .updateOrphanRegionsOnFs(report.getOrphanRegionsOnFS().size()); 290 master.getAssignmentManager().getAssignmentManagerMetrics() 291 .updateInconsistentRegions(report.getInconsistentRegions().size()); 292 } 293}