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