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