View Javadoc

1   /**
2    *
3    * Licensed to the Apache Software Foundation (ASF) under one
4    * or more contributor license agreements.  See the NOTICE file
5    * distributed with this work for additional information
6    * regarding copyright ownership.  The ASF licenses this file
7    * to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance
9    * with the License.  You may obtain a copy of the License at
10   *
11   *     http://www.apache.org/licenses/LICENSE-2.0
12   *
13   * Unless required by applicable law or agreed to in writing, software
14   * distributed under the License is distributed on an "AS IS" BASIS,
15   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16   * See the License for the specific language governing permissions and
17   * limitations under the License.
18   */
19  package org.apache.hadoop.hbase.master;
20  
21  import java.io.FileNotFoundException;
22  import java.io.IOException;
23  import java.util.Comparator;
24  import java.util.HashSet;
25  import java.util.Map;
26  import java.util.TreeMap;
27  import java.util.concurrent.atomic.AtomicBoolean;
28  import java.util.concurrent.atomic.AtomicInteger;
29  
30  import org.apache.commons.logging.Log;
31  import org.apache.commons.logging.LogFactory;
32  import org.apache.hadoop.fs.FileSystem;
33  import org.apache.hadoop.fs.Path;
34  import org.apache.hadoop.hbase.HColumnDescriptor;
35  import org.apache.hadoop.hbase.HConstants;
36  import org.apache.hadoop.hbase.HRegionInfo;
37  import org.apache.hadoop.hbase.HTableDescriptor;
38  import org.apache.hadoop.hbase.MetaTableAccessor;
39  import org.apache.hadoop.hbase.ScheduledChore;
40  import org.apache.hadoop.hbase.Server;
41  import org.apache.hadoop.hbase.TableName;
42  import org.apache.hadoop.hbase.backup.HFileArchiver;
43  import org.apache.hadoop.hbase.classification.InterfaceAudience;
44  import org.apache.hadoop.hbase.client.Connection;
45  import org.apache.hadoop.hbase.client.MetaScanner;
46  import org.apache.hadoop.hbase.client.MetaScanner.MetaScannerVisitor;
47  import org.apache.hadoop.hbase.client.Result;
48  import org.apache.hadoop.hbase.regionserver.HRegionFileSystem;
49  import org.apache.hadoop.hbase.util.Bytes;
50  import org.apache.hadoop.hbase.util.FSUtils;
51  import org.apache.hadoop.hbase.util.Pair;
52  import org.apache.hadoop.hbase.util.PairOfSameType;
53  import org.apache.hadoop.hbase.util.Triple;
54  
55  /**
56   * A janitor for the catalog tables.  Scans the <code>hbase:meta</code> catalog
57   * table on a period looking for unused regions to garbage collect.
58   */
59  @InterfaceAudience.Private
60  public class CatalogJanitor extends ScheduledChore {
61    private static final Log LOG = LogFactory.getLog(CatalogJanitor.class.getName());
62    private final Server server;
63    private final MasterServices services;
64    private AtomicBoolean enabled = new AtomicBoolean(true);
65    private AtomicBoolean alreadyRunning = new AtomicBoolean(false);
66    private final Connection connection;
67  
68    CatalogJanitor(final Server server, final MasterServices services) {
69      super("CatalogJanitor-" + server.getServerName().toShortString(), server, server
70          .getConfiguration().getInt("hbase.catalogjanitor.interval", 300000));
71      this.server = server;
72      this.services = services;
73      this.connection = server.getConnection();
74    }
75  
76    @Override
77    protected boolean initialChore() {
78      try {
79        if (this.enabled.get()) scan();
80      } catch (IOException e) {
81        LOG.warn("Failed initial scan of catalog table", e);
82        return false;
83      }
84      return true;
85    }
86  
87    /**
88     * @param enabled
89     */
90    public boolean setEnabled(final boolean enabled) {
91      return this.enabled.getAndSet(enabled);
92    }
93  
94    boolean getEnabled() {
95      return this.enabled.get();
96    }
97  
98    @Override
99    protected void chore() {
100     try {
101       if (this.enabled.get()) {
102         scan();
103       } else {
104         LOG.warn("CatalogJanitor disabled! Not running scan.");
105       }
106     } catch (IOException e) {
107       LOG.warn("Failed scan of catalog table", e);
108     }
109   }
110 
111   /**
112    * Scans hbase:meta and returns a number of scanned rows, and a map of merged
113    * regions, and an ordered map of split parents.
114    * @return triple of scanned rows, map of merged regions and map of split
115    *         parent regioninfos
116    * @throws IOException
117    */
118   Triple<Integer, Map<HRegionInfo, Result>, Map<HRegionInfo, Result>> getMergedRegionsAndSplitParents()
119       throws IOException {
120     return getMergedRegionsAndSplitParents(null);
121   }
122 
123   /**
124    * Scans hbase:meta and returns a number of scanned rows, and a map of merged
125    * regions, and an ordered map of split parents. if the given table name is
126    * null, return merged regions and split parents of all tables, else only the
127    * specified table
128    * @param tableName null represents all tables
129    * @return triple of scanned rows, and map of merged regions, and map of split
130    *         parent regioninfos
131    * @throws IOException
132    */
133   Triple<Integer, Map<HRegionInfo, Result>, Map<HRegionInfo, Result>> getMergedRegionsAndSplitParents(
134       final TableName tableName) throws IOException {
135     final boolean isTableSpecified = (tableName != null);
136     // TODO: Only works with single hbase:meta region currently.  Fix.
137     final AtomicInteger count = new AtomicInteger(0);
138     // Keep Map of found split parents.  There are candidates for cleanup.
139     // Use a comparator that has split parents come before its daughters.
140     final Map<HRegionInfo, Result> splitParents =
141       new TreeMap<HRegionInfo, Result>(new SplitParentFirstComparator());
142     final Map<HRegionInfo, Result> mergedRegions = new TreeMap<HRegionInfo, Result>();
143     // This visitor collects split parents and counts rows in the hbase:meta table
144 
145     MetaScannerVisitor visitor = new MetaScanner.MetaScannerVisitorBase() {
146       @Override
147       public boolean processRow(Result r) throws IOException {
148         if (r == null || r.isEmpty()) return true;
149         count.incrementAndGet();
150         HRegionInfo info = HRegionInfo.getHRegionInfo(r);
151         if (info == null) return true; // Keep scanning
152         if (isTableSpecified
153             && info.getTable().compareTo(tableName) > 0) {
154           // Another table, stop scanning
155           return false;
156         }
157         if (info.isSplitParent()) splitParents.put(info, r);
158         if (r.getValue(HConstants.CATALOG_FAMILY, HConstants.MERGEA_QUALIFIER) != null) {
159           mergedRegions.put(info, r);
160         }
161         // Returning true means "keep scanning"
162         return true;
163       }
164     };
165 
166     // Run full scan of hbase:meta catalog table passing in our custom visitor with
167     // the start row
168     MetaScanner.metaScan(this.connection, visitor, tableName);
169 
170     return new Triple<Integer, Map<HRegionInfo, Result>, Map<HRegionInfo, Result>>(
171         count.get(), mergedRegions, splitParents);
172   }
173 
174   /**
175    * If merged region no longer holds reference to the merge regions, archive
176    * merge region on hdfs and perform deleting references in hbase:meta
177    * @param mergedRegion
178    * @param regionA
179    * @param regionB
180    * @return true if we delete references in merged region on hbase:meta and archive
181    *         the files on the file system
182    * @throws IOException
183    */
184   boolean cleanMergeRegion(final HRegionInfo mergedRegion,
185       final HRegionInfo regionA, final HRegionInfo regionB) throws IOException {
186     FileSystem fs = this.services.getMasterFileSystem().getFileSystem();
187     Path rootdir = this.services.getMasterFileSystem().getRootDir();
188     Path tabledir = FSUtils.getTableDir(rootdir, mergedRegion.getTable());
189     HTableDescriptor htd = getTableDescriptor(mergedRegion.getTable());
190     HRegionFileSystem regionFs = null;
191     try {
192       regionFs = HRegionFileSystem.openRegionFromFileSystem(
193           this.services.getConfiguration(), fs, tabledir, mergedRegion, true);
194     } catch (IOException e) {
195       LOG.warn("Merged region does not exist: " + mergedRegion.getEncodedName());
196     }
197     if (regionFs == null || !regionFs.hasReferences(htd)) {
198       LOG.debug("Deleting region " + regionA.getRegionNameAsString() + " and "
199           + regionB.getRegionNameAsString()
200           + " from fs because merged region no longer holds references");
201       HFileArchiver.archiveRegion(this.services.getConfiguration(), fs, regionA);
202       HFileArchiver.archiveRegion(this.services.getConfiguration(), fs, regionB);
203       MetaTableAccessor.deleteMergeQualifiers(server.getConnection(),
204         mergedRegion);
205       return true;
206     }
207     return false;
208   }
209 
210   /**
211    * Run janitorial scan of catalog <code>hbase:meta</code> table looking for
212    * garbage to collect.
213    * @return number of cleaned regions
214    * @throws IOException
215    */
216   int scan() throws IOException {
217     try {
218       if (!alreadyRunning.compareAndSet(false, true)) {
219         return 0;
220       }
221       Triple<Integer, Map<HRegionInfo, Result>, Map<HRegionInfo, Result>> scanTriple =
222         getMergedRegionsAndSplitParents();
223       int count = scanTriple.getFirst();
224       /**
225        * clean merge regions first
226        */
227       int mergeCleaned = 0;
228       Map<HRegionInfo, Result> mergedRegions = scanTriple.getSecond();
229       for (Map.Entry<HRegionInfo, Result> e : mergedRegions.entrySet()) {
230         HRegionInfo regionA = HRegionInfo.getHRegionInfo(e.getValue(),
231             HConstants.MERGEA_QUALIFIER);
232         HRegionInfo regionB = HRegionInfo.getHRegionInfo(e.getValue(),
233             HConstants.MERGEB_QUALIFIER);
234         if (regionA == null || regionB == null) {
235           LOG.warn("Unexpected references regionA="
236               + (regionA == null ? "null" : regionA.getRegionNameAsString())
237               + ",regionB="
238               + (regionB == null ? "null" : regionB.getRegionNameAsString())
239               + " in merged region " + e.getKey().getRegionNameAsString());
240         } else {
241           if (cleanMergeRegion(e.getKey(), regionA, regionB)) {
242             mergeCleaned++;
243           }
244         }
245       }
246       /**
247        * clean split parents
248        */
249       Map<HRegionInfo, Result> splitParents = scanTriple.getThird();
250 
251       // Now work on our list of found parents. See if any we can clean up.
252       int splitCleaned = 0;
253       // regions whose parents are still around
254       HashSet<String> parentNotCleaned = new HashSet<String>();
255       for (Map.Entry<HRegionInfo, Result> e : splitParents.entrySet()) {
256         if (!parentNotCleaned.contains(e.getKey().getEncodedName()) &&
257             cleanParent(e.getKey(), e.getValue())) {
258           splitCleaned++;
259         } else {
260           // We could not clean the parent, so it's daughters should not be cleaned either (HBASE-6160)
261           PairOfSameType<HRegionInfo> daughters = HRegionInfo.getDaughterRegions(e.getValue());
262           parentNotCleaned.add(daughters.getFirst().getEncodedName());
263           parentNotCleaned.add(daughters.getSecond().getEncodedName());
264         }
265       }
266       if ((mergeCleaned + splitCleaned) != 0) {
267         LOG.info("Scanned " + count + " catalog row(s), gc'd " + mergeCleaned
268             + " unreferenced merged region(s) and " + splitCleaned
269             + " unreferenced parent region(s)");
270       } else if (LOG.isTraceEnabled()) {
271         LOG.trace("Scanned " + count + " catalog row(s), gc'd " + mergeCleaned
272             + " unreferenced merged region(s) and " + splitCleaned
273             + " unreferenced parent region(s)");
274       }
275       return mergeCleaned + splitCleaned;
276     } finally {
277       alreadyRunning.set(false);
278     }
279   }
280 
281   /**
282    * Compare HRegionInfos in a way that has split parents sort BEFORE their
283    * daughters.
284    */
285   static class SplitParentFirstComparator implements Comparator<HRegionInfo> {
286     Comparator<byte[]> rowEndKeyComparator = new Bytes.RowEndKeyComparator();
287     @Override
288     public int compare(HRegionInfo left, HRegionInfo right) {
289       // This comparator differs from the one HRegionInfo in that it sorts
290       // parent before daughters.
291       if (left == null) return -1;
292       if (right == null) return 1;
293       // Same table name.
294       int result = left.getTable().compareTo(right.getTable());
295       if (result != 0) return result;
296       // Compare start keys.
297       result = Bytes.compareTo(left.getStartKey(), right.getStartKey());
298       if (result != 0) return result;
299       // Compare end keys, but flip the operands so parent comes first
300       result = rowEndKeyComparator.compare(right.getEndKey(), left.getEndKey());
301 
302       return result;
303     }
304   }
305 
306   /**
307    * If daughters no longer hold reference to the parents, delete the parent.
308    * @param parent HRegionInfo of split offlined parent
309    * @param rowContent Content of <code>parent</code> row in
310    * <code>metaRegionName</code>
311    * @return True if we removed <code>parent</code> from meta table and from
312    * the filesystem.
313    * @throws IOException
314    */
315   boolean cleanParent(final HRegionInfo parent, Result rowContent)
316   throws IOException {
317     boolean result = false;
318     // Check whether it is a merged region and not clean reference
319     // No necessary to check MERGEB_QUALIFIER because these two qualifiers will
320     // be inserted/deleted together
321     if (rowContent.getValue(HConstants.CATALOG_FAMILY,
322         HConstants.MERGEA_QUALIFIER) != null) {
323       // wait cleaning merge region first
324       return result;
325     }
326     // Run checks on each daughter split.
327     PairOfSameType<HRegionInfo> daughters = HRegionInfo.getDaughterRegions(rowContent);
328     Pair<Boolean, Boolean> a = checkDaughterInFs(parent, daughters.getFirst());
329     Pair<Boolean, Boolean> b = checkDaughterInFs(parent, daughters.getSecond());
330     if (hasNoReferences(a) && hasNoReferences(b)) {
331       LOG.debug("Deleting region " + parent.getRegionNameAsString() +
332         " because daughter splits no longer hold references");
333       FileSystem fs = this.services.getMasterFileSystem().getFileSystem();
334       if (LOG.isTraceEnabled()) LOG.trace("Archiving parent region: " + parent);
335       HFileArchiver.archiveRegion(this.services.getConfiguration(), fs, parent);
336       MetaTableAccessor.deleteRegion(this.connection, parent);
337       result = true;
338     }
339     return result;
340   }
341 
342   /**
343    * @param p A pair where the first boolean says whether or not the daughter
344    * region directory exists in the filesystem and then the second boolean says
345    * whether the daughter has references to the parent.
346    * @return True the passed <code>p</code> signifies no references.
347    */
348   private boolean hasNoReferences(final Pair<Boolean, Boolean> p) {
349     return !p.getFirst() || !p.getSecond();
350   }
351 
352   /**
353    * Checks if a daughter region -- either splitA or splitB -- still holds
354    * references to parent.
355    * @param parent Parent region
356    * @param daughter Daughter region
357    * @return A pair where the first boolean says whether or not the daughter
358    * region directory exists in the filesystem and then the second boolean says
359    * whether the daughter has references to the parent.
360    * @throws IOException
361    */
362   Pair<Boolean, Boolean> checkDaughterInFs(final HRegionInfo parent, final HRegionInfo daughter)
363   throws IOException {
364     if (daughter == null)  {
365       return new Pair<Boolean, Boolean>(Boolean.FALSE, Boolean.FALSE);
366     }
367 
368     FileSystem fs = this.services.getMasterFileSystem().getFileSystem();
369     Path rootdir = this.services.getMasterFileSystem().getRootDir();
370     Path tabledir = FSUtils.getTableDir(rootdir, daughter.getTable());
371 
372     HRegionFileSystem regionFs = null;
373     try {
374       regionFs = HRegionFileSystem.openRegionFromFileSystem(
375           this.services.getConfiguration(), fs, tabledir, daughter, true);
376     } catch (IOException e) {
377       LOG.warn("Daughter region does not exist: " + daughter.getEncodedName()
378         + ", parent is: " + parent.getEncodedName());
379       return new Pair<Boolean, Boolean>(Boolean.FALSE, Boolean.FALSE);
380     }
381 
382     boolean references = false;
383     HTableDescriptor parentDescriptor = getTableDescriptor(parent.getTable());
384     for (HColumnDescriptor family: parentDescriptor.getFamilies()) {
385       if ((references = regionFs.hasReferences(family.getNameAsString()))) {
386         break;
387       }
388     }
389     return new Pair<Boolean, Boolean>(Boolean.TRUE, Boolean.valueOf(references));
390   }
391 
392   private HTableDescriptor getTableDescriptor(final TableName tableName)
393       throws FileNotFoundException, IOException {
394     return this.services.getTableDescriptors().get(tableName);
395   }
396 
397   /**
398    * Checks if the specified region has merge qualifiers, if so, try to clean
399    * them
400    * @param region
401    * @return true if the specified region doesn't have merge qualifier now
402    * @throws IOException
403    */
404   public boolean cleanMergeQualifier(final HRegionInfo region)
405       throws IOException {
406     // Get merge regions if it is a merged region and already has merge
407     // qualifier
408     Pair<HRegionInfo, HRegionInfo> mergeRegions = MetaTableAccessor
409         .getRegionsFromMergeQualifier(this.services.getConnection(),
410           region.getRegionName());
411     if (mergeRegions == null
412         || (mergeRegions.getFirst() == null && mergeRegions.getSecond() == null)) {
413       // It doesn't have merge qualifier, no need to clean
414       return true;
415     }
416     // It shouldn't happen, we must insert/delete these two qualifiers together
417     if (mergeRegions.getFirst() == null || mergeRegions.getSecond() == null) {
418       LOG.error("Merged region " + region.getRegionNameAsString()
419           + " has only one merge qualifier in META.");
420       return false;
421     }
422     return cleanMergeRegion(region, mergeRegions.getFirst(),
423         mergeRegions.getSecond());
424   }
425 }