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