View Javadoc

1   /**
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.io;
20  
21  import java.io.IOException;
22  import java.util.regex.Matcher;
23  import java.util.regex.Pattern;
24  
25  import org.apache.commons.logging.Log;
26  import org.apache.commons.logging.LogFactory;
27  import org.apache.hadoop.hbase.classification.InterfaceAudience;
28  import org.apache.hadoop.conf.Configuration;
29  import org.apache.hadoop.fs.FileSystem;
30  import org.apache.hadoop.fs.Path;
31  import org.apache.hadoop.hbase.TableName;
32  import org.apache.hadoop.hbase.HConstants;
33  import org.apache.hadoop.hbase.HRegionInfo;
34  import org.apache.hadoop.hbase.regionserver.StoreFileInfo;
35  import org.apache.hadoop.hbase.util.FSUtils;
36  import org.apache.hadoop.hbase.util.HFileArchiveUtil;
37  import org.apache.hadoop.hbase.util.Pair;
38  
39  /**
40   * HFileLink describes a link to an hfile.
41   *
42   * An hfile can be served from a region or from the hfile archive directory (/hbase/.archive)
43   * HFileLink allows to access the referenced hfile regardless of the location where it is.
44   *
45   * <p>Searches for hfiles in the following order and locations:
46   * <ul>
47   *  <li>/hbase/table/region/cf/hfile</li>
48   *  <li>/hbase/.archive/table/region/cf/hfile</li>
49   * </ul>
50   *
51   * The link checks first in the original path if it is not present
52   * it fallbacks to the archived path.
53   */
54  @InterfaceAudience.Private
55  @edu.umd.cs.findbugs.annotations.SuppressWarnings(value="EQ_DOESNT_OVERRIDE_EQUALS",
56    justification="To be fixed but warning suppressed for now")
57  public class HFileLink extends FileLink {
58    private static final Log LOG = LogFactory.getLog(HFileLink.class);
59  
60    /**
61     * A non-capture group, for HFileLink, so that this can be embedded.
62     * The HFileLink describe a link to an hfile in a different table/region
63     * and the name is in the form: table=region-hfile.
64     * <p>
65     * Table name is ([a-zA-Z_0-9][a-zA-Z_0-9.-]*), so '=' is an invalid character for the table name.
66     * Region name is ([a-f0-9]+), so '-' is an invalid character for the region name.
67     * HFile is ([0-9a-f]+(?:_SeqId_[0-9]+_)?) covering the plain hfiles (uuid)
68     * and the bulk loaded (_SeqId_[0-9]+_) hfiles.
69     */
70    public static final String LINK_NAME_REGEX =
71      String.format("(?:(?:%s=)?)%s=%s-%s",
72        TableName.VALID_NAMESPACE_REGEX, TableName.VALID_TABLE_QUALIFIER_REGEX,
73        HRegionInfo.ENCODED_REGION_NAME_REGEX, StoreFileInfo.HFILE_NAME_REGEX);
74  
75    /** Define the HFile Link name parser in the form of: table=region-hfile */
76    //made package private for testing
77    static final Pattern LINK_NAME_PATTERN =
78      Pattern.compile(String.format("^(?:(%s)(?:\\=))?(%s)=(%s)-(%s)$",
79        TableName.VALID_NAMESPACE_REGEX, TableName.VALID_TABLE_QUALIFIER_REGEX,
80        HRegionInfo.ENCODED_REGION_NAME_REGEX, StoreFileInfo.HFILE_NAME_REGEX));
81  
82    /**
83     * The pattern should be used for hfile and reference links
84     * that can be found in /hbase/table/region/family/
85     */
86    private static final Pattern REF_OR_HFILE_LINK_PATTERN =
87      Pattern.compile(String.format("^(?:(%s)(?:=))?(%s)=(%s)-(.+)$",
88        TableName.VALID_NAMESPACE_REGEX, TableName.VALID_TABLE_QUALIFIER_REGEX,
89        HRegionInfo.ENCODED_REGION_NAME_REGEX));
90  
91    private final Path archivePath;
92    private final Path originPath;
93    private final Path tempPath;
94  
95    /**
96     * Dead simple hfile link constructor
97     */
98    public HFileLink(final Path originPath, final Path tempPath,
99                     final Path archivePath) {
100     this.tempPath  = tempPath;
101     this.originPath = originPath;
102     this.archivePath = archivePath;
103 
104     setLocations(originPath, tempPath, archivePath);
105   }
106 
107   /**
108    * @param conf {@link Configuration} from which to extract specific archive locations
109    * @param hFileLinkPattern The path ending with a HFileLink pattern. (table=region-hfile)
110    * @throws IOException on unexpected error.
111    */
112   public static final HFileLink buildFromHFileLinkPattern(Configuration conf, Path hFileLinkPattern)
113           throws IOException {
114     return buildFromHFileLinkPattern(FSUtils.getRootDir(conf),
115             HFileArchiveUtil.getArchivePath(conf), hFileLinkPattern);
116   }
117 
118   /**
119    * @param rootDir Path to the root directory where hbase files are stored
120    * @param archiveDir Path to the hbase archive directory
121    * @param hFileLinkPattern The path of the HFile Link.
122    */
123   public final static HFileLink buildFromHFileLinkPattern(final Path rootDir,
124                                                           final Path archiveDir,
125                                                           final Path hFileLinkPattern) {
126     Path hfilePath = getHFileLinkPatternRelativePath(hFileLinkPattern);
127     Path tempPath = new Path(new Path(rootDir, HConstants.HBASE_TEMP_DIRECTORY), hfilePath);
128     Path originPath = new Path(rootDir, hfilePath);
129     Path archivePath = new Path(archiveDir, hfilePath);
130     return new HFileLink(originPath, tempPath, archivePath);
131   }
132 
133   /**
134    * Create an HFileLink relative path for the table/region/family/hfile location
135    * @param table Table name
136    * @param region Region Name
137    * @param family Family Name
138    * @param hfile HFile Name
139    * @return the relative Path to open the specified table/region/family/hfile link
140    */
141   public static Path createPath(final TableName table, final String region,
142                                 final String family, final String hfile) {
143     if (HFileLink.isHFileLink(hfile)) {
144       return new Path(family, hfile);
145     }
146     return new Path(family, HFileLink.createHFileLinkName(table, region, hfile));
147   }
148 
149   /**
150    * Create an HFileLink instance from table/region/family/hfile location
151    * @param conf {@link Configuration} from which to extract specific archive locations
152    * @param table Table name
153    * @param region Region Name
154    * @param family Family Name
155    * @param hfile HFile Name
156    * @return Link to the file with the specified table/region/family/hfile location
157    * @throws IOException on unexpected error.
158    */
159   public static HFileLink build(final Configuration conf, final TableName table,
160                                  final String region, final String family, final String hfile)
161           throws IOException {
162     return HFileLink.buildFromHFileLinkPattern(conf, createPath(table, region, family, hfile));
163   }
164 
165   /**
166    * @return the origin path of the hfile.
167    */
168   public Path getOriginPath() {
169     return this.originPath;
170   }
171 
172   /**
173    * @return the path of the archived hfile.
174    */
175   public Path getArchivePath() {
176     return this.archivePath;
177   }
178 
179   /**
180    * @param path Path to check.
181    * @return True if the path is a HFileLink.
182    */
183   public static boolean isHFileLink(final Path path) {
184     return isHFileLink(path.getName());
185   }
186 
187 
188   /**
189    * @param fileName File name to check.
190    * @return True if the path is a HFileLink.
191    */
192   public static boolean isHFileLink(String fileName) {
193     Matcher m = LINK_NAME_PATTERN.matcher(fileName);
194     if (!m.matches()) return false;
195     return m.groupCount() > 2 && m.group(4) != null && m.group(3) != null && m.group(2) != null;
196   }
197 
198   /**
199    * Convert a HFileLink path to a table relative path.
200    * e.g. the link: /hbase/test/0123/cf/testtb=4567-abcd
201    *      becomes: /hbase/testtb/4567/cf/abcd
202    *
203    * @param path HFileLink path
204    * @return Relative table path
205    * @throws IOException on unexpected error.
206    */
207   private static Path getHFileLinkPatternRelativePath(final Path path) {
208     // table=region-hfile
209     Matcher m = REF_OR_HFILE_LINK_PATTERN.matcher(path.getName());
210     if (!m.matches()) {
211       throw new IllegalArgumentException(path.getName() + " is not a valid HFileLink pattern!");
212     }
213 
214     // Convert the HFileLink name into a real table/region/cf/hfile path.
215     TableName tableName = TableName.valueOf(m.group(1), m.group(2));
216     String regionName = m.group(3);
217     String hfileName = m.group(4);
218     String familyName = path.getParent().getName();
219     Path tableDir = FSUtils.getTableDir(new Path("./"), tableName);
220     return new Path(tableDir, new Path(regionName, new Path(familyName,
221         hfileName)));
222   }
223 
224   /**
225    * Get the HFile name of the referenced link
226    *
227    * @param fileName HFileLink file name
228    * @return the name of the referenced HFile
229    */
230   public static String getReferencedHFileName(final String fileName) {
231     Matcher m = REF_OR_HFILE_LINK_PATTERN.matcher(fileName);
232     if (!m.matches()) {
233       throw new IllegalArgumentException(fileName + " is not a valid HFileLink name!");
234     }
235     return(m.group(4));
236   }
237 
238   /**
239    * Get the Region name of the referenced link
240    *
241    * @param fileName HFileLink file name
242    * @return the name of the referenced Region
243    */
244   public static String getReferencedRegionName(final String fileName) {
245     Matcher m = REF_OR_HFILE_LINK_PATTERN.matcher(fileName);
246     if (!m.matches()) {
247       throw new IllegalArgumentException(fileName + " is not a valid HFileLink name!");
248     }
249     return(m.group(3));
250   }
251 
252   /**
253    * Get the Table name of the referenced link
254    *
255    * @param fileName HFileLink file name
256    * @return the name of the referenced Table
257    */
258   public static TableName getReferencedTableName(final String fileName) {
259     Matcher m = REF_OR_HFILE_LINK_PATTERN.matcher(fileName);
260     if (!m.matches()) {
261       throw new IllegalArgumentException(fileName + " is not a valid HFileLink name!");
262     }
263     return(TableName.valueOf(m.group(1), m.group(2)));
264   }
265 
266   /**
267    * Create a new HFileLink name
268    *
269    * @param hfileRegionInfo - Linked HFile Region Info
270    * @param hfileName - Linked HFile name
271    * @return file name of the HFile Link
272    */
273   public static String createHFileLinkName(final HRegionInfo hfileRegionInfo,
274       final String hfileName) {
275     return createHFileLinkName(hfileRegionInfo.getTable(),
276             hfileRegionInfo.getEncodedName(), hfileName);
277   }
278 
279   /**
280    * Create a new HFileLink name
281    *
282    * @param tableName - Linked HFile table name
283    * @param regionName - Linked HFile region name
284    * @param hfileName - Linked HFile name
285    * @return file name of the HFile Link
286    */
287   public static String createHFileLinkName(final TableName tableName,
288       final String regionName, final String hfileName) {
289     String s = String.format("%s=%s-%s",
290         tableName.getNameAsString().replace(TableName.NAMESPACE_DELIM, '='),
291         regionName, hfileName);
292     return s;
293   }
294 
295   /**
296    * Create a new HFileLink
297    *
298    * <p>It also adds a back-reference to the hfile back-reference directory
299    * to simplify the reference-count and the cleaning process.
300    *
301    * @param conf {@link Configuration} to read for the archive directory name
302    * @param fs {@link FileSystem} on which to write the HFileLink
303    * @param dstFamilyPath - Destination path (table/region/cf/)
304    * @param hfileRegionInfo - Linked HFile Region Info
305    * @param hfileName - Linked HFile name
306    * @return true if the file is created, otherwise the file exists.
307    * @throws IOException on file or parent directory creation failure
308    */
309   public static boolean create(final Configuration conf, final FileSystem fs,
310       final Path dstFamilyPath, final HRegionInfo hfileRegionInfo,
311       final String hfileName) throws IOException {
312     return create(conf, fs, dstFamilyPath, hfileRegionInfo, hfileName, true);
313   }
314 
315   /**
316    * Create a new HFileLink
317    *
318    * <p>It also adds a back-reference to the hfile back-reference directory
319    * to simplify the reference-count and the cleaning process.
320    *
321    * @param conf {@link Configuration} to read for the archive directory name
322    * @param fs {@link FileSystem} on which to write the HFileLink
323    * @param dstFamilyPath - Destination path (table/region/cf/)
324    * @param hfileRegionInfo - Linked HFile Region Info
325    * @param hfileName - Linked HFile name
326    * @param createBackRef - Whether back reference should be created. Defaults to true.
327    * @return true if the file is created, otherwise the file exists.
328    * @throws IOException on file or parent directory creation failure
329    */
330   public static boolean create(final Configuration conf, final FileSystem fs,
331       final Path dstFamilyPath, final HRegionInfo hfileRegionInfo,
332       final String hfileName, final boolean createBackRef) throws IOException {
333     TableName linkedTable = hfileRegionInfo.getTable();
334     String linkedRegion = hfileRegionInfo.getEncodedName();
335     return create(conf, fs, dstFamilyPath, linkedTable, linkedRegion, hfileName, createBackRef);
336   }
337 
338   /**
339    * Create a new HFileLink
340    *
341    * <p>It also adds a back-reference to the hfile back-reference directory
342    * to simplify the reference-count and the cleaning process.
343    *
344    * @param conf {@link Configuration} to read for the archive directory name
345    * @param fs {@link FileSystem} on which to write the HFileLink
346    * @param dstFamilyPath - Destination path (table/region/cf/)
347    * @param linkedTable - Linked Table Name
348    * @param linkedRegion - Linked Region Name
349    * @param hfileName - Linked HFile name
350    * @return true if the file is created, otherwise the file exists.
351    * @throws IOException on file or parent directory creation failure
352    */
353   public static boolean create(final Configuration conf, final FileSystem fs,
354       final Path dstFamilyPath, final TableName linkedTable, final String linkedRegion,
355       final String hfileName) throws IOException {
356     return create(conf, fs, dstFamilyPath, linkedTable, linkedRegion, hfileName, true);
357   }
358 
359   /**
360    * Create a new HFileLink
361    *
362    * <p>It also adds a back-reference to the hfile back-reference directory
363    * to simplify the reference-count and the cleaning process.
364    *
365    * @param conf {@link Configuration} to read for the archive directory name
366    * @param fs {@link FileSystem} on which to write the HFileLink
367    * @param dstFamilyPath - Destination path (table/region/cf/)
368    * @param linkedTable - Linked Table Name
369    * @param linkedRegion - Linked Region Name
370    * @param hfileName - Linked HFile name
371    * @param createBackRef - Whether back reference should be created. Defaults to true.
372    * @return true if the file is created, otherwise the file exists.
373    * @throws IOException on file or parent directory creation failure
374    */
375   public static boolean create(final Configuration conf, final FileSystem fs,
376       final Path dstFamilyPath, final TableName linkedTable, final String linkedRegion,
377       final String hfileName, final boolean createBackRef) throws IOException {
378     String familyName = dstFamilyPath.getName();
379     String regionName = dstFamilyPath.getParent().getName();
380     String tableName = FSUtils.getTableName(dstFamilyPath.getParent().getParent())
381         .getNameAsString();
382 
383     String name = createHFileLinkName(linkedTable, linkedRegion, hfileName);
384     String refName = createBackReferenceName(tableName, regionName);
385 
386     // Make sure the destination directory exists
387     fs.mkdirs(dstFamilyPath);
388 
389     // Make sure the FileLink reference directory exists
390     Path archiveStoreDir = HFileArchiveUtil.getStoreArchivePath(conf,
391           linkedTable, linkedRegion, familyName);
392     Path backRefPath = null;
393     if (createBackRef) {
394       Path backRefssDir = getBackReferencesDir(archiveStoreDir, hfileName);
395       fs.mkdirs(backRefssDir);
396 
397       // Create the reference for the link
398       backRefPath = new Path(backRefssDir, refName);
399       fs.createNewFile(backRefPath);
400     }
401     try {
402       // Create the link
403       return fs.createNewFile(new Path(dstFamilyPath, name));
404     } catch (IOException e) {
405       LOG.error("couldn't create the link=" + name + " for " + dstFamilyPath, e);
406       // Revert the reference if the link creation failed
407       if (createBackRef) {
408         fs.delete(backRefPath, false);
409       }
410       throw e;
411     }
412   }
413 
414   /**
415    * Create a new HFileLink starting from a hfileLink name
416    *
417    * <p>It also adds a back-reference to the hfile back-reference directory
418    * to simplify the reference-count and the cleaning process.
419    *
420    * @param conf {@link Configuration} to read for the archive directory name
421    * @param fs {@link FileSystem} on which to write the HFileLink
422    * @param dstFamilyPath - Destination path (table/region/cf/)
423    * @param hfileLinkName - HFileLink name (it contains hfile-region-table)
424    * @return true if the file is created, otherwise the file exists.
425    * @throws IOException on file or parent directory creation failure
426    */
427   public static boolean createFromHFileLink(final Configuration conf, final FileSystem fs,
428       final Path dstFamilyPath, final String hfileLinkName)
429           throws IOException {
430     return createFromHFileLink(conf, fs, dstFamilyPath, hfileLinkName, true);
431   }
432 
433   /**
434    * Create a new HFileLink starting from a hfileLink name
435    *
436    * <p>It also adds a back-reference to the hfile back-reference directory
437    * to simplify the reference-count and the cleaning process.
438    *
439    * @param conf {@link Configuration} to read for the archive directory name
440    * @param fs {@link FileSystem} on which to write the HFileLink
441    * @param dstFamilyPath - Destination path (table/region/cf/)
442    * @param hfileLinkName - HFileLink name (it contains hfile-region-table)
443    * @param createBackRef - Whether back reference should be created. Defaults to true.
444    * @return true if the file is created, otherwise the file exists.
445    * @throws IOException on file or parent directory creation failure
446    */
447   public static boolean createFromHFileLink(final Configuration conf, final FileSystem fs,
448       final Path dstFamilyPath, final String hfileLinkName, final boolean createBackRef)
449           throws IOException {
450     Matcher m = LINK_NAME_PATTERN.matcher(hfileLinkName);
451     if (!m.matches()) {
452       throw new IllegalArgumentException(hfileLinkName + " is not a valid HFileLink name!");
453     }
454     return create(conf, fs, dstFamilyPath, TableName.valueOf(m.group(1), m.group(2)),
455         m.group(3), m.group(4), createBackRef);
456   }
457 
458   /**
459    * Create the back reference name
460    */
461   //package-private for testing
462   static String createBackReferenceName(final String tableNameStr,
463                                         final String regionName) {
464 
465     return regionName + "." + tableNameStr.replace(TableName.NAMESPACE_DELIM, '=');
466   }
467 
468   /**
469    * Get the full path of the HFile referenced by the back reference
470    *
471    * @param rootDir root hbase directory
472    * @param linkRefPath Link Back Reference path
473    * @return full path of the referenced hfile
474    */
475   public static Path getHFileFromBackReference(final Path rootDir, final Path linkRefPath) {
476     Pair<TableName, String> p = parseBackReferenceName(linkRefPath.getName());
477     TableName linkTableName = p.getFirst();
478     String linkRegionName = p.getSecond();
479 
480     String hfileName = getBackReferenceFileName(linkRefPath.getParent());
481     Path familyPath = linkRefPath.getParent().getParent();
482     Path regionPath = familyPath.getParent();
483     Path tablePath = regionPath.getParent();
484 
485     String linkName = createHFileLinkName(FSUtils.getTableName(tablePath),
486             regionPath.getName(), hfileName);
487     Path linkTableDir = FSUtils.getTableDir(rootDir, linkTableName);
488     Path regionDir = new Path(linkTableDir, linkRegionName);
489     return new Path(new Path(regionDir, familyPath.getName()), linkName);
490   }
491 
492   static Pair<TableName, String> parseBackReferenceName(String name) {
493     int separatorIndex = name.indexOf('.');
494     String linkRegionName = name.substring(0, separatorIndex);
495     String tableSubstr = name.substring(separatorIndex + 1)
496         .replace('=', TableName.NAMESPACE_DELIM);
497     TableName linkTableName = TableName.valueOf(tableSubstr);
498     return new Pair<TableName, String>(linkTableName, linkRegionName);
499   }
500 
501   /**
502    * Get the full path of the HFile referenced by the back reference
503    *
504    * @param conf {@link Configuration} to read for the archive directory name
505    * @param linkRefPath Link Back Reference path
506    * @return full path of the referenced hfile
507    * @throws IOException on unexpected error.
508    */
509   public static Path getHFileFromBackReference(final Configuration conf, final Path linkRefPath)
510       throws IOException {
511     return getHFileFromBackReference(FSUtils.getRootDir(conf), linkRefPath);
512   }
513 
514 }