001/**
002 *
003 * Licensed to the Apache Software Foundation (ASF) under one
004 * or more contributor license agreements.  See the NOTICE file
005 * distributed with this work for additional information
006 * regarding copyright ownership.  The ASF licenses this file
007 * to you under the Apache License, Version 2.0 (the
008 * "License"); you may not use this file except in compliance
009 * with the License.  You may obtain a copy of the License at
010 *
011 *     http://www.apache.org/licenses/LICENSE-2.0
012 *
013 * Unless required by applicable law or agreed to in writing, software
014 * distributed under the License is distributed on an "AS IS" BASIS,
015 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
016 * See the License for the specific language governing permissions and
017 * limitations under the License.
018 */
019package org.apache.hadoop.hbase.master;
020
021import java.io.FileNotFoundException;
022import java.io.IOException;
023import java.util.Comparator;
024import java.util.HashSet;
025import java.util.Map;
026import java.util.TreeMap;
027import java.util.concurrent.atomic.AtomicBoolean;
028import java.util.concurrent.atomic.AtomicInteger;
029
030import org.apache.hadoop.fs.FileSystem;
031import org.apache.hadoop.fs.Path;
032import org.apache.hadoop.hbase.HConstants;
033import org.apache.hadoop.hbase.MetaTableAccessor;
034import org.apache.hadoop.hbase.ScheduledChore;
035import org.apache.hadoop.hbase.TableName;
036import org.apache.hadoop.hbase.client.ColumnFamilyDescriptor;
037import org.apache.hadoop.hbase.client.Connection;
038import org.apache.hadoop.hbase.client.RegionInfo;
039import org.apache.hadoop.hbase.client.Result;
040import org.apache.hadoop.hbase.client.TableDescriptor;
041import org.apache.hadoop.hbase.master.assignment.AssignmentManager;
042import org.apache.hadoop.hbase.master.assignment.GCMergedRegionsProcedure;
043import org.apache.hadoop.hbase.master.assignment.GCRegionProcedure;
044import org.apache.hadoop.hbase.master.procedure.MasterProcedureEnv;
045import org.apache.hadoop.hbase.procedure2.ProcedureExecutor;
046import org.apache.hadoop.hbase.regionserver.HRegionFileSystem;
047import org.apache.hadoop.hbase.util.Bytes;
048import org.apache.hadoop.hbase.util.FSUtils;
049import org.apache.hadoop.hbase.util.Pair;
050import org.apache.hadoop.hbase.util.PairOfSameType;
051import org.apache.hadoop.hbase.util.Threads;
052import org.apache.hadoop.hbase.util.Triple;
053import org.apache.yetus.audience.InterfaceAudience;
054import org.slf4j.Logger;
055import org.slf4j.LoggerFactory;
056
057/**
058 * A janitor for the catalog tables.  Scans the <code>hbase:meta</code> catalog
059 * table on a period looking for unused regions to garbage collect.
060 */
061@InterfaceAudience.Private
062public class CatalogJanitor extends ScheduledChore {
063  private static final Logger LOG = LoggerFactory.getLogger(CatalogJanitor.class.getName());
064
065  private final AtomicBoolean alreadyRunning = new AtomicBoolean(false);
066  private final AtomicBoolean enabled = new AtomicBoolean(true);
067  private final MasterServices services;
068  private final Connection connection;
069  // PID of the last Procedure launched herein. Keep around for Tests.
070
071  CatalogJanitor(final MasterServices services) {
072    super("CatalogJanitor-" + services.getServerName().toShortString(), services,
073      services.getConfiguration().getInt("hbase.catalogjanitor.interval", 300000));
074    this.services = services;
075    this.connection = services.getConnection();
076  }
077
078  @Override
079  protected boolean initialChore() {
080    try {
081      if (this.enabled.get()) scan();
082    } catch (IOException e) {
083      LOG.warn("Failed initial scan of catalog table", e);
084      return false;
085    }
086    return true;
087  }
088
089  /**
090   * @param enabled
091   */
092  public boolean setEnabled(final boolean enabled) {
093    boolean alreadyEnabled = this.enabled.getAndSet(enabled);
094    // If disabling is requested on an already enabled chore, we could have an active
095    // scan still going on, callers might not be aware of that and do further action thinkng
096    // that no action would be from this chore.  In this case, the right action is to wait for
097    // the active scan to complete before exiting this function.
098    if (!enabled && alreadyEnabled) {
099      while (alreadyRunning.get()) {
100        Threads.sleepWithoutInterrupt(100);
101      }
102    }
103    return alreadyEnabled;
104  }
105
106  boolean getEnabled() {
107    return this.enabled.get();
108  }
109
110  @Override
111  protected void chore() {
112    try {
113      AssignmentManager am = this.services.getAssignmentManager();
114      if (this.enabled.get()
115          && !this.services.isInMaintenanceMode()
116          && am != null
117          && am.isFailoverCleanupDone()
118          && !am.hasRegionsInTransition()) {
119        scan();
120      } else {
121        LOG.warn("CatalogJanitor is disabled! Enabled=" + this.enabled.get() +
122            ", maintenanceMode=" + this.services.isInMaintenanceMode() +
123            ", am=" + am + ", failoverCleanupDone=" + (am != null && am.isFailoverCleanupDone()) +
124            ", hasRIT=" + (am != null && am.hasRegionsInTransition()));
125      }
126    } catch (IOException e) {
127      LOG.warn("Failed scan of catalog table", e);
128    }
129  }
130
131  /**
132   * Scans hbase:meta and returns a number of scanned rows, and a map of merged
133   * regions, and an ordered map of split parents.
134   * @return triple of scanned rows, map of merged regions and map of split
135   *         parent regioninfos
136   * @throws IOException
137   */
138  Triple<Integer, Map<RegionInfo, Result>, Map<RegionInfo, Result>>
139    getMergedRegionsAndSplitParents() throws IOException {
140    return getMergedRegionsAndSplitParents(null);
141  }
142
143  /**
144   * Scans hbase:meta and returns a number of scanned rows, and a map of merged
145   * regions, and an ordered map of split parents. if the given table name is
146   * null, return merged regions and split parents of all tables, else only the
147   * specified table
148   * @param tableName null represents all tables
149   * @return triple of scanned rows, and map of merged regions, and map of split
150   *         parent regioninfos
151   * @throws IOException
152   */
153  Triple<Integer, Map<RegionInfo, Result>, Map<RegionInfo, Result>>
154    getMergedRegionsAndSplitParents(final TableName tableName) throws IOException {
155    final boolean isTableSpecified = (tableName != null);
156    // TODO: Only works with single hbase:meta region currently.  Fix.
157    final AtomicInteger count = new AtomicInteger(0);
158    // Keep Map of found split parents.  There are candidates for cleanup.
159    // Use a comparator that has split parents come before its daughters.
160    final Map<RegionInfo, Result> splitParents = new TreeMap<>(new SplitParentFirstComparator());
161    final Map<RegionInfo, Result> mergedRegions = new TreeMap<>(RegionInfo.COMPARATOR);
162    // This visitor collects split parents and counts rows in the hbase:meta table
163
164    MetaTableAccessor.Visitor visitor = new MetaTableAccessor.Visitor() {
165      @Override
166      public boolean visit(Result r) throws IOException {
167        if (r == null || r.isEmpty()) return true;
168        count.incrementAndGet();
169        RegionInfo info = MetaTableAccessor.getRegionInfo(r);
170        if (info == null) return true; // Keep scanning
171        if (isTableSpecified
172            && info.getTable().compareTo(tableName) > 0) {
173          // Another table, stop scanning
174          return false;
175        }
176        if (LOG.isTraceEnabled()) LOG.trace("" + info + " IS-SPLIT_PARENT=" + info.isSplitParent());
177        if (info.isSplitParent()) splitParents.put(info, r);
178        if (r.getValue(HConstants.CATALOG_FAMILY, HConstants.MERGEA_QUALIFIER) != null) {
179          mergedRegions.put(info, r);
180        }
181        // Returning true means "keep scanning"
182        return true;
183      }
184    };
185
186    // Run full scan of hbase:meta catalog table passing in our custom visitor with
187    // the start row
188    MetaTableAccessor.scanMetaForTableRegions(this.connection, visitor, tableName);
189
190    return new Triple<>(count.get(), mergedRegions, splitParents);
191  }
192
193  /**
194   * If merged region no longer holds reference to the merge regions, archive
195   * merge region on hdfs and perform deleting references in hbase:meta
196   * @param mergedRegion
197   * @return true if we delete references in merged region on hbase:meta and archive
198   *         the files on the file system
199   * @throws IOException
200   */
201  boolean cleanMergeRegion(final RegionInfo mergedRegion,
202      final RegionInfo regionA, final RegionInfo regionB) throws IOException {
203    FileSystem fs = this.services.getMasterFileSystem().getFileSystem();
204    Path rootdir = this.services.getMasterFileSystem().getRootDir();
205    Path tabledir = FSUtils.getTableDir(rootdir, mergedRegion.getTable());
206    TableDescriptor htd = getTableDescriptor(mergedRegion.getTable());
207    HRegionFileSystem regionFs = null;
208    try {
209      regionFs = HRegionFileSystem.openRegionFromFileSystem(
210          this.services.getConfiguration(), fs, tabledir, mergedRegion, true);
211    } catch (IOException e) {
212      LOG.warn("Merged region does not exist: " + mergedRegion.getEncodedName());
213    }
214    if (regionFs == null || !regionFs.hasReferences(htd)) {
215      LOG.debug("Deleting region " + regionA.getShortNameToLog() + " and "
216          + regionB.getShortNameToLog()
217          + " from fs because merged region no longer holds references");
218      ProcedureExecutor<MasterProcedureEnv> pe = this.services.getMasterProcedureExecutor();
219      pe.submitProcedure(new GCMergedRegionsProcedure(pe.getEnvironment(),
220          mergedRegion, regionA, regionB));
221      // Remove from in-memory states
222      this.services.getAssignmentManager().getRegionStates().deleteRegion(regionA);
223      this.services.getAssignmentManager().getRegionStates().deleteRegion(regionB);
224      this.services.getServerManager().removeRegion(regionA);
225      this.services.getServerManager().removeRegion(regionB);
226      return true;
227    }
228    return false;
229  }
230
231  /**
232   * Run janitorial scan of catalog <code>hbase:meta</code> table looking for
233   * garbage to collect.
234   * @return number of archiving jobs started.
235   * @throws IOException
236   */
237  int scan() throws IOException {
238    int result = 0;
239
240    try {
241      if (!alreadyRunning.compareAndSet(false, true)) {
242        LOG.debug("CatalogJanitor already running");
243        return result;
244      }
245      Triple<Integer, Map<RegionInfo, Result>, Map<RegionInfo, Result>> scanTriple =
246        getMergedRegionsAndSplitParents();
247      /**
248       * clean merge regions first
249       */
250      Map<RegionInfo, Result> mergedRegions = scanTriple.getSecond();
251      for (Map.Entry<RegionInfo, Result> e : mergedRegions.entrySet()) {
252        if (this.services.isInMaintenanceMode()) {
253          // Stop cleaning if the master is in maintenance mode
254          break;
255        }
256
257        PairOfSameType<RegionInfo> p = MetaTableAccessor.getMergeRegions(e.getValue());
258        RegionInfo regionA = p.getFirst();
259        RegionInfo regionB = p.getSecond();
260        if (regionA == null || regionB == null) {
261          LOG.warn("Unexpected references regionA="
262              + (regionA == null ? "null" : regionA.getShortNameToLog())
263              + ",regionB="
264              + (regionB == null ? "null" : regionB.getShortNameToLog())
265              + " in merged region " + e.getKey().getShortNameToLog());
266        } else {
267          if (cleanMergeRegion(e.getKey(), regionA, regionB)) {
268            result++;
269          }
270        }
271      }
272      /**
273       * clean split parents
274       */
275      Map<RegionInfo, Result> splitParents = scanTriple.getThird();
276
277      // Now work on our list of found parents. See if any we can clean up.
278      // regions whose parents are still around
279      HashSet<String> parentNotCleaned = new HashSet<>();
280      for (Map.Entry<RegionInfo, Result> e : splitParents.entrySet()) {
281        if (this.services.isInMaintenanceMode()) {
282          // Stop cleaning if the master is in maintenance mode
283          break;
284        }
285
286        if (!parentNotCleaned.contains(e.getKey().getEncodedName()) &&
287            cleanParent(e.getKey(), e.getValue())) {
288          result++;
289        } else {
290          // We could not clean the parent, so it's daughters should not be
291          // cleaned either (HBASE-6160)
292          PairOfSameType<RegionInfo> daughters =
293              MetaTableAccessor.getDaughterRegions(e.getValue());
294          parentNotCleaned.add(daughters.getFirst().getEncodedName());
295          parentNotCleaned.add(daughters.getSecond().getEncodedName());
296        }
297      }
298      return result;
299    } finally {
300      alreadyRunning.set(false);
301    }
302  }
303
304  /**
305   * Compare HRegionInfos in a way that has split parents sort BEFORE their
306   * daughters.
307   */
308  static class SplitParentFirstComparator implements Comparator<RegionInfo> {
309    Comparator<byte[]> rowEndKeyComparator = new Bytes.RowEndKeyComparator();
310    @Override
311    public int compare(RegionInfo left, RegionInfo right) {
312      // This comparator differs from the one RegionInfo in that it sorts
313      // parent before daughters.
314      if (left == null) return -1;
315      if (right == null) return 1;
316      // Same table name.
317      int result = left.getTable().compareTo(right.getTable());
318      if (result != 0) return result;
319      // Compare start keys.
320      result = Bytes.compareTo(left.getStartKey(), right.getStartKey());
321      if (result != 0) return result;
322      // Compare end keys, but flip the operands so parent comes first
323      result = rowEndKeyComparator.compare(right.getEndKey(), left.getEndKey());
324
325      return result;
326    }
327  }
328
329  /**
330   * If daughters no longer hold reference to the parents, delete the parent.
331   * @param parent RegionInfo of split offlined parent
332   * @param rowContent Content of <code>parent</code> row in
333   * <code>metaRegionName</code>
334   * @return True if we removed <code>parent</code> from meta table and from
335   * the filesystem.
336   * @throws IOException
337   */
338  boolean cleanParent(final RegionInfo parent, Result rowContent)
339  throws IOException {
340    // Check whether it is a merged region and not clean reference
341    // No necessary to check MERGEB_QUALIFIER because these two qualifiers will
342    // be inserted/deleted together
343    if (rowContent.getValue(HConstants.CATALOG_FAMILY, HConstants.MERGEA_QUALIFIER) != null) {
344      // wait cleaning merge region first
345      return false;
346    }
347    // Run checks on each daughter split.
348    PairOfSameType<RegionInfo> daughters = MetaTableAccessor.getDaughterRegions(rowContent);
349    Pair<Boolean, Boolean> a = checkDaughterInFs(parent, daughters.getFirst());
350    Pair<Boolean, Boolean> b = checkDaughterInFs(parent, daughters.getSecond());
351    if (hasNoReferences(a) && hasNoReferences(b)) {
352      String daughterA = daughters.getFirst() != null?
353          daughters.getFirst().getShortNameToLog(): "null";
354      String daughterB = daughters.getSecond() != null?
355          daughters.getSecond().getShortNameToLog(): "null";
356      LOG.debug("Deleting region " + parent.getShortNameToLog() +
357        " because daughters -- " + daughterA + ", " + daughterB +
358        " -- no longer hold references");
359      ProcedureExecutor<MasterProcedureEnv> pe = this.services.getMasterProcedureExecutor();
360      pe.submitProcedure(new GCRegionProcedure(pe.getEnvironment(), parent));
361      // Remove from in-memory states
362      this.services.getAssignmentManager().getRegionStates().deleteRegion(parent);
363      this.services.getServerManager().removeRegion(parent);
364      return true;
365    }
366    return false;
367  }
368
369  /**
370   * @param p A pair where the first boolean says whether or not the daughter
371   * region directory exists in the filesystem and then the second boolean says
372   * whether the daughter has references to the parent.
373   * @return True the passed <code>p</code> signifies no references.
374   */
375  private boolean hasNoReferences(final Pair<Boolean, Boolean> p) {
376    return !p.getFirst() || !p.getSecond();
377  }
378
379  /**
380   * Checks if a daughter region -- either splitA or splitB -- still holds
381   * references to parent.
382   * @param parent Parent region
383   * @param daughter Daughter region
384   * @return A pair where the first boolean says whether or not the daughter
385   * region directory exists in the filesystem and then the second boolean says
386   * whether the daughter has references to the parent.
387   * @throws IOException
388   */
389  Pair<Boolean, Boolean> checkDaughterInFs(final RegionInfo parent, final RegionInfo daughter)
390  throws IOException {
391    if (daughter == null)  {
392      return new Pair<>(Boolean.FALSE, Boolean.FALSE);
393    }
394
395    FileSystem fs = this.services.getMasterFileSystem().getFileSystem();
396    Path rootdir = this.services.getMasterFileSystem().getRootDir();
397    Path tabledir = FSUtils.getTableDir(rootdir, daughter.getTable());
398
399    Path daughterRegionDir = new Path(tabledir, daughter.getEncodedName());
400
401    HRegionFileSystem regionFs = null;
402
403    try {
404      if (!FSUtils.isExists(fs, daughterRegionDir)) {
405        return new Pair<>(Boolean.FALSE, Boolean.FALSE);
406      }
407    } catch (IOException ioe) {
408      LOG.error("Error trying to determine if daughter region exists, " +
409               "assuming exists and has references", ioe);
410      return new Pair<>(Boolean.TRUE, Boolean.TRUE);
411    }
412
413    boolean references = false;
414    TableDescriptor parentDescriptor = getTableDescriptor(parent.getTable());
415    try {
416      regionFs = HRegionFileSystem.openRegionFromFileSystem(
417          this.services.getConfiguration(), fs, tabledir, daughter, true);
418
419      for (ColumnFamilyDescriptor family: parentDescriptor.getColumnFamilies()) {
420        if ((references = regionFs.hasReferences(family.getNameAsString()))) {
421          break;
422        }
423      }
424    } catch (IOException e) {
425      LOG.error("Error trying to determine referenced files from : " + daughter.getEncodedName()
426          + ", to: " + parent.getEncodedName() + " assuming has references", e);
427      return new Pair<>(Boolean.TRUE, Boolean.TRUE);
428    }
429    return new Pair<>(Boolean.TRUE, Boolean.valueOf(references));
430  }
431
432  private TableDescriptor getTableDescriptor(final TableName tableName)
433      throws FileNotFoundException, IOException {
434    return this.services.getTableDescriptors().get(tableName);
435  }
436
437  /**
438   * Checks if the specified region has merge qualifiers, if so, try to clean
439   * them
440   * @param region
441   * @return true if the specified region doesn't have merge qualifier now
442   * @throws IOException
443   */
444  public boolean cleanMergeQualifier(final RegionInfo region)
445      throws IOException {
446    // Get merge regions if it is a merged region and already has merge
447    // qualifier
448    Pair<RegionInfo, RegionInfo> mergeRegions = MetaTableAccessor
449        .getRegionsFromMergeQualifier(this.services.getConnection(),
450          region.getRegionName());
451    if (mergeRegions == null
452        || (mergeRegions.getFirst() == null && mergeRegions.getSecond() == null)) {
453      // It doesn't have merge qualifier, no need to clean
454      return true;
455    }
456    // It shouldn't happen, we must insert/delete these two qualifiers together
457    if (mergeRegions.getFirst() == null || mergeRegions.getSecond() == null) {
458      LOG.error("Merged region " + region.getRegionNameAsString()
459          + " has only one merge qualifier in META.");
460      return false;
461    }
462    return cleanMergeRegion(region, mergeRegions.getFirst(),
463        mergeRegions.getSecond());
464  }
465}