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.Threads;
54  import org.apache.hadoop.hbase.util.Triple;
55  
56  /**
57   * A janitor for the catalog tables.  Scans the <code>hbase:meta</code> catalog
58   * table on a period looking for unused regions to garbage collect.
59   */
60  @InterfaceAudience.Private
61  public class CatalogJanitor extends ScheduledChore {
62    private static final Log LOG = LogFactory.getLog(CatalogJanitor.class.getName());
63    private final Server server;
64    private final MasterServices services;
65    private AtomicBoolean enabled = new AtomicBoolean(true);
66    private AtomicBoolean alreadyRunning = new AtomicBoolean(false);
67    private final Connection connection;
68  
69    CatalogJanitor(final Server server, final MasterServices services) {
70      super("CatalogJanitor-" + server.getServerName().toShortString(), server, server
71          .getConfiguration().getInt("hbase.catalogjanitor.interval", 300000));
72      this.server = server;
73      this.services = services;
74      this.connection = server.getConnection();
75    }
76  
77    @Override
78    protected boolean initialChore() {
79      try {
80        if (this.enabled.get()) scan();
81      } catch (IOException e) {
82        LOG.warn("Failed initial scan of catalog table", e);
83        return false;
84      }
85      return true;
86    }
87  
88    /**
89     * @param enabled
90     */
91    public boolean setEnabled(final boolean enabled) {
92      boolean alreadyEnabled = this.enabled.getAndSet(enabled);
93      // If disabling is requested on an already enabled chore, we could have an active
94      // scan still going on, callers might not be aware of that and do further action thinkng
95      // that no action would be from this chore.  In this case, the right action is to wait for
96      // the active scan to complete before exiting this function.
97      if (!enabled && alreadyEnabled) {
98        while (alreadyRunning.get()) {
99          Threads.sleepWithoutInterrupt(100);
100       }
101     }
102     return alreadyEnabled;
103   }
104 
105   boolean getEnabled() {
106     return this.enabled.get();
107   }
108 
109   @Override
110   protected void chore() {
111     try {
112       AssignmentManager am = this.services.getAssignmentManager();
113       if (this.enabled.get()
114           && !this.services.isInMaintenanceMode()
115           && am != null
116           && am.isFailoverCleanupDone()
117           && am.getRegionStates().getRegionsInTransition().size() == 0) {
118         scan();
119       } else {
120         LOG.warn("CatalogJanitor disabled! Not running scan.");
121       }
122     } catch (IOException e) {
123       LOG.warn("Failed scan of catalog table", e);
124     }
125   }
126 
127   /**
128    * Scans hbase:meta and returns a number of scanned rows, and a map of merged
129    * regions, and an ordered map of split parents.
130    * @return triple of scanned rows, map of merged regions and map of split
131    *         parent regioninfos
132    * @throws IOException
133    */
134   Triple<Integer, Map<HRegionInfo, Result>, Map<HRegionInfo, Result>> getMergedRegionsAndSplitParents()
135       throws IOException {
136     return getMergedRegionsAndSplitParents(null);
137   }
138 
139   /**
140    * Scans hbase:meta and returns a number of scanned rows, and a map of merged
141    * regions, and an ordered map of split parents. if the given table name is
142    * null, return merged regions and split parents of all tables, else only the
143    * specified table
144    * @param tableName null represents all tables
145    * @return triple of scanned rows, and map of merged regions, and map of split
146    *         parent regioninfos
147    * @throws IOException
148    */
149   Triple<Integer, Map<HRegionInfo, Result>, Map<HRegionInfo, Result>> getMergedRegionsAndSplitParents(
150       final TableName tableName) throws IOException {
151     final boolean isTableSpecified = (tableName != null);
152     // TODO: Only works with single hbase:meta region currently.  Fix.
153     final AtomicInteger count = new AtomicInteger(0);
154     // Keep Map of found split parents.  There are candidates for cleanup.
155     // Use a comparator that has split parents come before its daughters.
156     final Map<HRegionInfo, Result> splitParents =
157       new TreeMap<HRegionInfo, Result>(new SplitParentFirstComparator());
158     final Map<HRegionInfo, Result> mergedRegions = new TreeMap<HRegionInfo, Result>();
159     // This visitor collects split parents and counts rows in the hbase:meta table
160 
161     MetaScannerVisitor visitor = new MetaScanner.MetaScannerVisitorBase() {
162       @Override
163       public boolean processRow(Result r) throws IOException {
164         if (r == null || r.isEmpty()) return true;
165         count.incrementAndGet();
166         HRegionInfo info = HRegionInfo.getHRegionInfo(r);
167         if (info == null) return true; // Keep scanning
168         if (isTableSpecified
169             && info.getTable().compareTo(tableName) > 0) {
170           // Another table, stop scanning
171           return false;
172         }
173         if (info.isSplitParent()) splitParents.put(info, r);
174         if (r.getValue(HConstants.CATALOG_FAMILY, HConstants.MERGEA_QUALIFIER) != null) {
175           mergedRegions.put(info, r);
176         }
177         // Returning true means "keep scanning"
178         return true;
179       }
180     };
181 
182     // Run full scan of hbase:meta catalog table passing in our custom visitor with
183     // the start row
184     MetaScanner.metaScan(this.connection, visitor, tableName);
185 
186     return new Triple<Integer, Map<HRegionInfo, Result>, Map<HRegionInfo, Result>>(
187         count.get(), mergedRegions, splitParents);
188   }
189 
190   /**
191    * If merged region no longer holds reference to the merge regions, archive
192    * merge region on hdfs and perform deleting references in hbase:meta
193    * @param mergedRegion
194    * @param regionA
195    * @param regionB
196    * @return true if we delete references in merged region on hbase:meta and archive
197    *         the files on the file system
198    * @throws IOException
199    */
200   boolean cleanMergeRegion(final HRegionInfo mergedRegion,
201       final HRegionInfo regionA, final HRegionInfo regionB) throws IOException {
202     FileSystem fs = this.services.getMasterFileSystem().getFileSystem();
203     Path rootdir = this.services.getMasterFileSystem().getRootDir();
204     Path tabledir = FSUtils.getTableDir(rootdir, mergedRegion.getTable());
205     HTableDescriptor htd = getTableDescriptor(mergedRegion.getTable());
206     HRegionFileSystem regionFs = null;
207     try {
208       regionFs = HRegionFileSystem.openRegionFromFileSystem(
209           this.services.getConfiguration(), fs, tabledir, mergedRegion, true);
210     } catch (IOException e) {
211       LOG.warn("Merged region does not exist: " + mergedRegion.getEncodedName());
212     }
213     if (regionFs == null || !regionFs.hasReferences(htd)) {
214       LOG.debug("Deleting region " + regionA.getRegionNameAsString() + " and "
215           + regionB.getRegionNameAsString()
216           + " from fs because merged region no longer holds references");
217       HFileArchiver.archiveRegion(this.services.getConfiguration(), fs, regionA);
218       HFileArchiver.archiveRegion(this.services.getConfiguration(), fs, regionB);
219       MetaTableAccessor.deleteMergeQualifiers(services.getConnection(), mergedRegion);
220       services.getServerManager().removeRegion(regionA);
221       services.getServerManager().removeRegion(regionB);
222       return true;
223     }
224     return false;
225   }
226 
227   /**
228    * Run janitorial scan of catalog <code>hbase:meta</code> table looking for
229    * garbage to collect.
230    * @return number of cleaned regions
231    * @throws IOException
232    */
233   int scan() throws IOException {
234     try {
235       if (!alreadyRunning.compareAndSet(false, true)) {
236         return 0;
237       }
238       Triple<Integer, Map<HRegionInfo, Result>, Map<HRegionInfo, Result>> scanTriple =
239         getMergedRegionsAndSplitParents();
240       int count = scanTriple.getFirst();
241       /**
242        * clean merge regions first
243        */
244       int mergeCleaned = 0;
245       Map<HRegionInfo, Result> mergedRegions = scanTriple.getSecond();
246       for (Map.Entry<HRegionInfo, Result> e : mergedRegions.entrySet()) {
247         if (this.services.isInMaintenanceMode()) {
248           // Stop cleaning if the master is in maintenance mode
249           break;
250         }
251 
252         HRegionInfo regionA = HRegionInfo.getHRegionInfo(e.getValue(),
253             HConstants.MERGEA_QUALIFIER);
254         HRegionInfo regionB = HRegionInfo.getHRegionInfo(e.getValue(),
255             HConstants.MERGEB_QUALIFIER);
256         if (regionA == null || regionB == null) {
257           LOG.warn("Unexpected references regionA="
258               + (regionA == null ? "null" : regionA.getRegionNameAsString())
259               + ",regionB="
260               + (regionB == null ? "null" : regionB.getRegionNameAsString())
261               + " in merged region " + e.getKey().getRegionNameAsString());
262         } else {
263           if (cleanMergeRegion(e.getKey(), regionA, regionB)) {
264             mergeCleaned++;
265           }
266         }
267       }
268       /**
269        * clean split parents
270        */
271       Map<HRegionInfo, Result> splitParents = scanTriple.getThird();
272 
273       // Now work on our list of found parents. See if any we can clean up.
274       int splitCleaned = 0;
275       // regions whose parents are still around
276       HashSet<String> parentNotCleaned = new HashSet<String>();
277       for (Map.Entry<HRegionInfo, Result> e : splitParents.entrySet()) {
278         if (this.services.isInMaintenanceMode()) {
279           // Stop cleaning if the master is in maintenance mode
280           break;
281         }
282 
283         if (!parentNotCleaned.contains(e.getKey().getEncodedName()) &&
284             cleanParent(e.getKey(), e.getValue())) {
285           splitCleaned++;
286         } else {
287           // We could not clean the parent, so it's daughters should not be cleaned either (HBASE-6160)
288           PairOfSameType<HRegionInfo> daughters = HRegionInfo.getDaughterRegions(e.getValue());
289           parentNotCleaned.add(daughters.getFirst().getEncodedName());
290           parentNotCleaned.add(daughters.getSecond().getEncodedName());
291         }
292       }
293       if ((mergeCleaned + splitCleaned) != 0) {
294         LOG.info("Scanned " + count + " catalog row(s), gc'd " + mergeCleaned
295             + " unreferenced merged region(s) and " + splitCleaned
296             + " unreferenced parent region(s)");
297       } else if (LOG.isTraceEnabled()) {
298         LOG.trace("Scanned " + count + " catalog row(s), gc'd " + mergeCleaned
299             + " unreferenced merged region(s) and " + splitCleaned
300             + " unreferenced parent region(s)");
301       }
302       return mergeCleaned + splitCleaned;
303     } finally {
304       alreadyRunning.set(false);
305     }
306   }
307 
308   /**
309    * Compare HRegionInfos in a way that has split parents sort BEFORE their
310    * daughters.
311    */
312   static class SplitParentFirstComparator implements Comparator<HRegionInfo> {
313     Comparator<byte[]> rowEndKeyComparator = new Bytes.RowEndKeyComparator();
314     @Override
315     public int compare(HRegionInfo left, HRegionInfo right) {
316       // This comparator differs from the one HRegionInfo in that it sorts
317       // parent before daughters.
318       if (left == null) return -1;
319       if (right == null) return 1;
320       // Same table name.
321       int result = left.getTable().compareTo(right.getTable());
322       if (result != 0) return result;
323       // Compare start keys.
324       result = Bytes.compareTo(left.getStartKey(), right.getStartKey());
325       if (result != 0) return result;
326       // Compare end keys, but flip the operands so parent comes first
327       result = rowEndKeyComparator.compare(right.getEndKey(), left.getEndKey());
328 
329       return result;
330     }
331   }
332 
333   /**
334    * If daughters no longer hold reference to the parents, delete the parent.
335    * @param parent HRegionInfo of split offlined parent
336    * @param rowContent Content of <code>parent</code> row in
337    * <code>metaRegionName</code>
338    * @return True if we removed <code>parent</code> from meta table and from
339    * the filesystem.
340    * @throws IOException
341    */
342   boolean cleanParent(final HRegionInfo parent, Result rowContent)
343   throws IOException {
344     boolean result = false;
345     // Check whether it is a merged region and not clean reference
346     // No necessary to check MERGEB_QUALIFIER because these two qualifiers will
347     // be inserted/deleted together
348     if (rowContent.getValue(HConstants.CATALOG_FAMILY,
349         HConstants.MERGEA_QUALIFIER) != null) {
350       // wait cleaning merge region first
351       return result;
352     }
353     // Run checks on each daughter split.
354     PairOfSameType<HRegionInfo> daughters = HRegionInfo.getDaughterRegions(rowContent);
355     Pair<Boolean, Boolean> a = checkDaughterInFs(parent, daughters.getFirst());
356     Pair<Boolean, Boolean> b = checkDaughterInFs(parent, daughters.getSecond());
357     if (hasNoReferences(a) && hasNoReferences(b)) {
358       LOG.debug("Deleting region " + parent.getRegionNameAsString() +
359         " because daughter splits no longer hold references");
360       FileSystem fs = this.services.getMasterFileSystem().getFileSystem();
361       if (LOG.isTraceEnabled()) LOG.trace("Archiving parent region: " + parent);
362       HFileArchiver.archiveRegion(this.services.getConfiguration(), fs, parent);
363       MetaTableAccessor.deleteRegion(this.connection, parent);
364       services.getServerManager().removeRegion(parent);
365       result = true;
366     }
367     return result;
368   }
369 
370   /**
371    * @param p A pair where the first boolean says whether or not the daughter
372    * region directory exists in the filesystem and then the second boolean says
373    * whether the daughter has references to the parent.
374    * @return True the passed <code>p</code> signifies no references.
375    */
376   private boolean hasNoReferences(final Pair<Boolean, Boolean> p) {
377     return !p.getFirst() || !p.getSecond();
378   }
379 
380   /**
381    * Checks if a daughter region -- either splitA or splitB -- still holds
382    * references to parent.
383    * @param parent Parent region
384    * @param daughter Daughter region
385    * @return A pair where the first boolean says whether or not the daughter
386    * region directory exists in the filesystem and then the second boolean says
387    * whether the daughter has references to the parent.
388    * @throws IOException
389    */
390   Pair<Boolean, Boolean> checkDaughterInFs(final HRegionInfo parent, final HRegionInfo daughter)
391   throws IOException {
392     if (daughter == null)  {
393       return new Pair<Boolean, Boolean>(Boolean.FALSE, Boolean.FALSE);
394     }
395 
396     FileSystem fs = this.services.getMasterFileSystem().getFileSystem();
397     Path rootdir = this.services.getMasterFileSystem().getRootDir();
398     Path tabledir = FSUtils.getTableDir(rootdir, daughter.getTable());
399 
400     Path daughterRegionDir = new Path(tabledir, daughter.getEncodedName());
401 
402     HRegionFileSystem regionFs = null;
403 
404     try {
405       if (!FSUtils.isExists(fs, daughterRegionDir)) {
406         return new Pair<Boolean, Boolean>(Boolean.FALSE, Boolean.FALSE);
407       }
408     } catch (IOException ioe) {
409       LOG.warn("Error trying to determine if daughter region exists, " +
410                "assuming exists and has references", ioe);
411       return new Pair<Boolean, Boolean>(Boolean.TRUE, Boolean.TRUE);
412     }
413 
414     try {
415       regionFs = HRegionFileSystem.openRegionFromFileSystem(
416           this.services.getConfiguration(), fs, tabledir, daughter, true);
417     } catch (IOException e) {
418       LOG.warn("Error trying to determine referenced files from : " + daughter.getEncodedName()
419           + ", to: " + parent.getEncodedName() + " assuming has references", e);
420       return new Pair<Boolean, Boolean>(Boolean.TRUE, Boolean.TRUE);
421     }
422 
423     boolean references = false;
424     HTableDescriptor parentDescriptor = getTableDescriptor(parent.getTable());
425     for (HColumnDescriptor family: parentDescriptor.getFamilies()) {
426       if ((references = regionFs.hasReferences(family.getNameAsString()))) {
427         break;
428       }
429     }
430     return new Pair<Boolean, Boolean>(Boolean.TRUE, Boolean.valueOf(references));
431   }
432 
433   private HTableDescriptor getTableDescriptor(final TableName tableName)
434       throws FileNotFoundException, IOException {
435     return this.services.getTableDescriptors().get(tableName);
436   }
437 
438   /**
439    * Checks if the specified region has merge qualifiers, if so, try to clean
440    * them
441    * @param region
442    * @return true if the specified region doesn't have merge qualifier now
443    * @throws IOException
444    */
445   public boolean cleanMergeQualifier(final HRegionInfo region)
446       throws IOException {
447     // Get merge regions if it is a merged region and already has merge
448     // qualifier
449     Pair<HRegionInfo, HRegionInfo> mergeRegions = MetaTableAccessor
450         .getRegionsFromMergeQualifier(this.services.getConnection(),
451           region.getRegionName());
452     if (mergeRegions == null
453         || (mergeRegions.getFirst() == null && mergeRegions.getSecond() == null)) {
454       // It doesn't have merge qualifier, no need to clean
455       return true;
456     }
457     // It shouldn't happen, we must insert/delete these two qualifiers together
458     if (mergeRegions.getFirst() == null || mergeRegions.getSecond() == null) {
459       LOG.error("Merged region " + region.getRegionNameAsString()
460           + " has only one merge qualifier in META.");
461       return false;
462     }
463     return cleanMergeRegion(region, mergeRegions.getFirst(),
464         mergeRegions.getSecond());
465   }
466 }