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  
20  package org.apache.hadoop.hbase.client;
21  
22  import java.io.Closeable;
23  import java.io.IOException;
24  import java.util.ArrayList;
25  import java.util.List;
26  import java.util.NavigableMap;
27  import java.util.TreeMap;
28  
29  import org.apache.commons.logging.Log;
30  import org.apache.commons.logging.LogFactory;
31  import org.apache.hadoop.classification.InterfaceAudience;
32  import org.apache.hadoop.conf.Configuration;
33  import org.apache.hadoop.hbase.HConstants;
34  import org.apache.hadoop.hbase.HRegionInfo;
35  import org.apache.hadoop.hbase.HRegionLocation;
36  import org.apache.hadoop.hbase.MetaTableAccessor;
37  import org.apache.hadoop.hbase.RegionLocations;
38  import org.apache.hadoop.hbase.ServerName;
39  import org.apache.hadoop.hbase.TableName;
40  import org.apache.hadoop.hbase.TableNotFoundException;
41  import org.apache.hadoop.hbase.util.Bytes;
42  import org.apache.hadoop.hbase.util.ExceptionUtil;
43  
44  /**
45   * Scanner class that contains the <code>hbase:meta</code> table scanning logic.
46   * Provided visitors will be called for each row.
47   *
48   * Although public visibility, this is not a public-facing API and may evolve in
49   * minor releases.
50   *
51   * <p> Note that during concurrent region splits, the scanner might not see
52   * hbase:meta changes across rows (for parent and daughter entries) consistently.
53   * see HBASE-5986, and {@link DefaultMetaScannerVisitor} for details. </p>
54   */
55  @InterfaceAudience.Private
56  //TODO: merge this to MetaTableAccessor, get rid of it.
57  public class MetaScanner {
58    private static final Log LOG = LogFactory.getLog(MetaScanner.class);
59    /**
60     * Scans the meta table and calls a visitor on each RowResult and uses a empty
61     * start row value as table name.
62     *
63     * @param configuration conf
64     * @param visitor A custom visitor
65     * @throws IOException e
66     */
67    public static void metaScan(Configuration configuration,
68        MetaScannerVisitor visitor)
69    throws IOException {
70      metaScan(configuration, visitor, null, null, Integer.MAX_VALUE);
71    }
72  
73    /**
74     * Scans the meta table and calls a visitor on each RowResult. Uses a table
75     * name to locate meta regions.
76     *
77     * @param configuration config
78     * @param connection connection to use internally (null to use a new instance)
79     * @param visitor visitor object
80     * @param userTableName User table name in meta table to start scan at.  Pass
81     * null if not interested in a particular table.
82     * @throws IOException e
83     */
84    public static void metaScan(Configuration configuration, ClusterConnection connection,
85        MetaScannerVisitor visitor, TableName userTableName) throws IOException {
86      metaScan(configuration, connection, visitor, userTableName, null, Integer.MAX_VALUE,
87          TableName.META_TABLE_NAME);
88    }
89  
90    /**
91     * Scans the meta table and calls a visitor on each RowResult. Uses a table
92     * name and a row name to locate meta regions. And it only scans at most
93     * <code>rowLimit</code> of rows.
94     *
95     * @param configuration HBase configuration.
96     * @param visitor Visitor object.
97     * @param userTableName User table name in meta table to start scan at.  Pass
98     * null if not interested in a particular table.
99     * @param row Name of the row at the user table. The scan will start from
100    * the region row where the row resides.
101    * @param rowLimit Max of processed rows. If it is less than 0, it
102    * will be set to default value <code>Integer.MAX_VALUE</code>.
103    * @throws IOException e
104    */
105   public static void metaScan(Configuration configuration,
106       MetaScannerVisitor visitor, TableName userTableName, byte[] row,
107       int rowLimit)
108   throws IOException {
109     metaScan(configuration, null, visitor, userTableName, row, rowLimit,
110       TableName.META_TABLE_NAME);
111   }
112 
113   /**
114    * Scans the meta table and calls a visitor on each RowResult. Uses a table
115    * name and a row name to locate meta regions. And it only scans at most
116    * <code>rowLimit</code> of rows.
117    *
118    * @param configuration HBase configuration.
119    * @param connection connection to use internally (null to use a new instance)
120    * @param visitor Visitor object. Closes the visitor before returning.
121    * @param tableName User table name in meta table to start scan at.  Pass
122    * null if not interested in a particular table.
123    * @param row Name of the row at the user table. The scan will start from
124    * the region row where the row resides.
125    * @param rowLimit Max of processed rows. If it is less than 0, it
126    * will be set to default value <code>Integer.MAX_VALUE</code>.
127    * @param metaTableName Meta table to scan, root or meta.
128    * @throws IOException e
129    */
130   static void metaScan(Configuration configuration, ClusterConnection connection,
131       final MetaScannerVisitor visitor, final TableName tableName,
132       final byte[] row, final int rowLimit, final TableName metaTableName)
133     throws IOException {
134 
135     if (connection == null){
136       connection = ConnectionManager.getConnectionInternal(configuration);
137     }
138 
139     int rowUpperLimit = rowLimit > 0 ? rowLimit: Integer.MAX_VALUE;
140     // Calculate startrow for scan.
141     byte[] startRow;
142     ResultScanner scanner = null;
143     HTable metaTable = null;
144     try {
145       metaTable = new HTable(TableName.META_TABLE_NAME, connection, null);
146       if (row != null) {
147         // Scan starting at a particular row in a particular table
148         byte[] searchRow = HRegionInfo.createRegionName(tableName, row, HConstants.NINES, false);
149 
150         Result startRowResult = metaTable.getRowOrBefore(searchRow, HConstants.CATALOG_FAMILY);
151 
152         if (startRowResult == null) {
153           throw new TableNotFoundException("Cannot find row in "+ TableName
154               .META_TABLE_NAME.getNameAsString()+" for table: "
155               + tableName + ", row=" + Bytes.toStringBinary(searchRow));
156         }
157         HRegionInfo regionInfo = getHRegionInfo(startRowResult);
158         if (regionInfo == null) {
159           throw new IOException("HRegionInfo was null or empty in Meta for " +
160             tableName + ", row=" + Bytes.toStringBinary(searchRow));
161         }
162         byte[] rowBefore = regionInfo.getStartKey();
163         startRow = HRegionInfo.createRegionName(tableName, rowBefore, HConstants.ZEROES, false);
164       } else if (tableName == null || tableName.getName().length == 0) {
165         // Full hbase:meta scan
166         startRow = HConstants.EMPTY_START_ROW;
167       } else {
168         // Scan hbase:meta for an entire table
169         startRow = HRegionInfo.createRegionName(tableName, HConstants.EMPTY_START_ROW,
170           HConstants.ZEROES, false);
171       }
172       final Scan scan = new Scan(startRow).addFamily(HConstants.CATALOG_FAMILY);
173       int scannerCaching = configuration.getInt(HConstants.HBASE_META_SCANNER_CACHING,
174         HConstants.DEFAULT_HBASE_META_SCANNER_CACHING);
175       if (rowUpperLimit <= scannerCaching) {
176           scan.setSmall(true);
177       }
178       int rows = Math.min(rowLimit, scannerCaching);
179       scan.setCaching(rows);
180       if (LOG.isTraceEnabled()) {
181         LOG.trace("Scanning " + metaTableName.getNameAsString() + " starting at row=" +
182           Bytes.toStringBinary(startRow) + " for max=" + rowUpperLimit + " with caching=" + rows);
183       }
184       // Run the scan
185       scanner = metaTable.getScanner(scan);
186       Result result;
187       int processedRows = 0;
188       while ((result = scanner.next()) != null) {
189         if (visitor != null) {
190           if (!visitor.processRow(result)) break;
191         }
192         processedRows++;
193         if (processedRows >= rowUpperLimit) break;
194       }
195     } finally {
196       if (scanner != null) {
197         try {
198           scanner.close();
199         } catch (Throwable t) {
200           ExceptionUtil.rethrowIfInterrupt(t);
201           LOG.debug("Got exception in closing the result scanner", t);
202         }
203       }
204       if (visitor != null) {
205         try {
206           visitor.close();
207         } catch (Throwable t) {
208           ExceptionUtil.rethrowIfInterrupt(t);
209           LOG.debug("Got exception in closing the meta scanner visitor", t);
210         }
211       }
212       if (metaTable != null) {
213         try {
214           metaTable.close();
215         } catch (Throwable t) {
216           ExceptionUtil.rethrowIfInterrupt(t);
217           LOG.debug("Got exception in closing meta table", t);
218         }
219       }
220 
221     }
222   }
223 
224   /**
225    * Returns HRegionInfo object from the column
226    * HConstants.CATALOG_FAMILY:HConstants.REGIONINFO_QUALIFIER of the catalog
227    * table Result.
228    * @param data a Result object from the catalog table scan
229    * @return HRegionInfo or null
230    * @deprecated Use {@link org.apache.hadoop.hbase.MetaTableAccessor#getRegionLocations(Result)}
231    */
232   @Deprecated
233   public static HRegionInfo getHRegionInfo(Result data) {
234     return HRegionInfo.getHRegionInfo(data);
235   }
236 
237   /**
238    * Lists all of the regions currently in META.
239    * @param conf
240    * @param offlined True if we are to include offlined regions, false and we'll
241    * leave out offlined regions from returned list.
242    * @return List of all user-space regions.
243    * @throws IOException
244    */
245   public static List<HRegionInfo> listAllRegions(Configuration conf, final boolean offlined)
246   throws IOException {
247     final List<HRegionInfo> regions = new ArrayList<HRegionInfo>();
248     MetaScannerVisitor visitor = new MetaScannerVisitorBase() {
249         @Override
250         public boolean processRow(Result result) throws IOException {
251           if (result == null || result.isEmpty()) {
252             return true;
253           }
254 
255           RegionLocations locations = MetaTableAccessor.getRegionLocations(result);
256           if (locations == null) return true;
257           for (HRegionLocation loc : locations.getRegionLocations()) {
258             if (loc != null) {
259               HRegionInfo regionInfo = loc.getRegionInfo();
260               // If region offline AND we are not to include offlined regions, return.
261               if (regionInfo.isOffline() && !offlined) continue;
262               regions.add(regionInfo);
263             }
264           }
265           return true;
266         }
267     };
268     metaScan(conf, visitor);
269     return regions;
270   }
271 
272   /**
273    * Lists all of the table regions currently in META.
274    * @param conf
275    * @param offlined True if we are to include offlined regions, false and we'll
276    * leave out offlined regions from returned list.
277    * @return Map of all user-space regions to servers
278    * @throws IOException
279    */
280   public static NavigableMap<HRegionInfo, ServerName> allTableRegions(Configuration conf,
281       ClusterConnection connection, final TableName tableName,
282       final boolean offlined) throws IOException {
283     final NavigableMap<HRegionInfo, ServerName> regions =
284       new TreeMap<HRegionInfo, ServerName>();
285     MetaScannerVisitor visitor = new TableMetaScannerVisitor(tableName) {
286       @Override
287       public boolean processRowInternal(Result result) throws IOException {
288         RegionLocations locations = MetaTableAccessor.getRegionLocations(result);
289         if (locations == null) return true;
290         for (HRegionLocation loc : locations.getRegionLocations()) {
291           if (loc != null) {
292             HRegionInfo regionInfo = loc.getRegionInfo();
293             regions.put(new UnmodifyableHRegionInfo(regionInfo), loc.getServerName());
294           }
295         }
296         return true;
297       }
298     };
299     metaScan(conf, connection, visitor, tableName);
300     return regions;
301   }
302 
303   /**
304    * Lists table regions and locations grouped by region range from META.
305    */
306   public static List<RegionLocations> listTableRegionLocations(Configuration conf,
307       ClusterConnection connection, final TableName tableName) throws IOException {
308     final List<RegionLocations> regions = new ArrayList<RegionLocations>();
309     MetaScannerVisitor visitor = new TableMetaScannerVisitor(tableName) {
310       @Override
311       public boolean processRowInternal(Result result) throws IOException {
312         RegionLocations locations = MetaTableAccessor.getRegionLocations(result);
313         if (locations == null) return true;
314         regions.add(locations);
315         return true;
316       }
317     };
318     metaScan(conf, connection, visitor, tableName);
319     return regions;
320   }
321 
322   /**
323    * Visitor class called to process each row of the hbase:meta table
324    */
325   public interface MetaScannerVisitor extends Closeable {
326     /**
327      * Visitor method that accepts a RowResult and the meta region location.
328      * Implementations can return false to stop the region's loop if it becomes
329      * unnecessary for some reason.
330      *
331      * @param rowResult result
332      * @return A boolean to know if it should continue to loop in the region
333      * @throws IOException e
334      */
335     boolean processRow(Result rowResult) throws IOException;
336   }
337 
338   public static abstract class MetaScannerVisitorBase implements MetaScannerVisitor {
339     @Override
340     public void close() throws IOException {
341     }
342   }
343 
344   /**
345    * A MetaScannerVisitor that skips offline regions and split parents
346    */
347   public static abstract class DefaultMetaScannerVisitor
348     extends MetaScannerVisitorBase {
349 
350     public DefaultMetaScannerVisitor() {
351       super();
352     }
353 
354     public abstract boolean processRowInternal(Result rowResult) throws IOException;
355 
356     @Override
357     public boolean processRow(Result rowResult) throws IOException {
358       HRegionInfo info = getHRegionInfo(rowResult);
359       if (info == null) {
360         return true;
361       }
362 
363       //skip over offline and split regions
364       if (!(info.isOffline() || info.isSplit())) {
365         return processRowInternal(rowResult);
366       }
367       return true;
368     }
369   }
370 
371   /**
372    * A MetaScannerVisitor for a table. Provides a consistent view of the table's
373    * hbase:meta entries during concurrent splits (see HBASE-5986 for details). This class
374    * does not guarantee ordered traversal of meta entries, and can block until the
375    * hbase:meta entries for daughters are available during splits.
376    */
377   public static abstract class TableMetaScannerVisitor extends DefaultMetaScannerVisitor {
378     private TableName tableName;
379 
380     public TableMetaScannerVisitor(TableName tableName) {
381       super();
382       this.tableName = tableName;
383     }
384 
385     @Override
386     public final boolean processRow(Result rowResult) throws IOException {
387       HRegionInfo info = getHRegionInfo(rowResult);
388       if (info == null) {
389         return true;
390       }
391       if (!(info.getTable().equals(tableName))) {
392         return false;
393       }
394       return super.processRow(rowResult);
395     }
396   }
397 }