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