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.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.HRegion;
35  import org.apache.hadoop.hbase.regionserver.StoreFileInfo;
36  import org.apache.hadoop.hbase.util.FSUtils;
37  import org.apache.hadoop.hbase.util.HFileArchiveUtil;
38  import org.apache.hadoop.hbase.util.Pair;
39  
40  /**
41   * HFileLink describes a link to an hfile.
42   *
43   * An hfile can be served from a region or from the hfile archive directory (/hbase/.archive)
44   * HFileLink allows to access the referenced hfile regardless of the location where it is.
45   *
46   * <p>Searches for hfiles in the following order and locations:
47   * <ul>
48   *  <li>/hbase/table/region/cf/hfile</li>
49   *  <li>/hbase/.archive/table/region/cf/hfile</li>
50   * </ul>
51   *
52   * The link checks first in the original path if it is not present
53   * it fallbacks to the archived path.
54   */
55  @InterfaceAudience.Private
56  public class HFileLink extends FileLink {
57    private static final Log LOG = LogFactory.getLog(HFileLink.class);
58  
59    /**
60     * A non-capture group, for HFileLink, so that this can be embedded.
61     * The HFileLink describe a link to an hfile in a different table/region
62     * and the name is in the form: table=region-hfile.
63     * <p>
64     * Table name is ([a-zA-Z_0-9][a-zA-Z_0-9.-]*), so '=' is an invalid character for the table name.
65     * Region name is ([a-f0-9]+), so '-' is an invalid character for the region name.
66     * HFile is ([0-9a-f]+(?:_SeqId_[0-9]+_)?) covering the plain hfiles (uuid)
67     * and the bulk loaded (_SeqId_[0-9]+_) hfiles.
68     */
69    public static final String LINK_NAME_REGEX =
70      String.format("(?:(?:%s=)?)%s=%s-%s",
71        TableName.VALID_NAMESPACE_REGEX, TableName.VALID_TABLE_QUALIFIER_REGEX,
72        HRegionInfo.ENCODED_REGION_NAME_REGEX, StoreFileInfo.HFILE_NAME_REGEX);
73  
74    /** Define the HFile Link name parser in the form of: table=region-hfile */
75    //made package private for testing
76    static final Pattern LINK_NAME_PATTERN =
77      Pattern.compile(String.format("^(?:(%s)(?:\\=))?(%s)=(%s)-(%s)$",
78        TableName.VALID_NAMESPACE_REGEX, TableName.VALID_TABLE_QUALIFIER_REGEX,
79        HRegionInfo.ENCODED_REGION_NAME_REGEX, StoreFileInfo.HFILE_NAME_REGEX));
80  
81    /**
82     * The pattern should be used for hfile and reference links
83     * that can be found in /hbase/table/region/family/
84     */
85    private static final Pattern REF_OR_HFILE_LINK_PATTERN =
86      Pattern.compile(String.format("^(?:(%s)(?:=))?(%s)=(%s)-(.+)$",
87        TableName.VALID_NAMESPACE_REGEX, TableName.VALID_TABLE_QUALIFIER_REGEX,
88        HRegionInfo.ENCODED_REGION_NAME_REGEX));
89  
90    private final Path archivePath;
91    private final Path originPath;
92    private final Path tempPath;
93  
94    /**
95     * @param conf {@link Configuration} from which to extract specific archive locations
96     * @param path The path of the HFile Link.
97     * @throws IOException on unexpected error.
98     */
99    public HFileLink(Configuration conf, Path path) throws IOException {
100     this(FSUtils.getRootDir(conf), HFileArchiveUtil.getArchivePath(conf), path);
101   }
102 
103   /**
104    * @param rootDir Path to the root directory where hbase files are stored
105    * @param archiveDir Path to the hbase archive directory
106    * @param path The path of the HFile Link.
107    */
108   public HFileLink(final Path rootDir, final Path archiveDir, final Path path) {
109     Path hfilePath = getRelativeTablePath(path);
110     this.tempPath = new Path(new Path(rootDir, HConstants.HBASE_TEMP_DIRECTORY), hfilePath);
111     this.originPath = new Path(rootDir, hfilePath);
112     this.archivePath = new Path(archiveDir, hfilePath);
113     setLocations(originPath, tempPath, archivePath);
114   }
115 
116   /**
117    * @return the origin path of the hfile.
118    */
119   public Path getOriginPath() {
120     return this.originPath;
121   }
122 
123   /**
124    * @return the path of the archived hfile.
125    */
126   public Path getArchivePath() {
127     return this.archivePath;
128   }
129 
130   /**
131    * @param path Path to check.
132    * @return True if the path is a HFileLink.
133    */
134   public static boolean isHFileLink(final Path path) {
135     return isHFileLink(path.getName());
136   }
137 
138 
139   /**
140    * @param fileName File name to check.
141    * @return True if the path is a HFileLink.
142    */
143   public static boolean isHFileLink(String fileName) {
144     Matcher m = LINK_NAME_PATTERN.matcher(fileName);
145     if (!m.matches()) return false;
146     return m.groupCount() > 2 && m.group(4) != null && m.group(3) != null && m.group(2) != null;
147   }
148 
149   /**
150    * Convert a HFileLink path to a table relative path.
151    * e.g. the link: /hbase/test/0123/cf/testtb=4567-abcd
152    *      becomes: /hbase/testtb/4567/cf/abcd
153    *
154    * @param path HFileLink path
155    * @return Relative table path
156    * @throws IOException on unexpected error.
157    */
158   private static Path getRelativeTablePath(final Path path) {
159     // table=region-hfile
160     Matcher m = REF_OR_HFILE_LINK_PATTERN.matcher(path.getName());
161     if (!m.matches()) {
162       throw new IllegalArgumentException(path.getName() + " is not a valid HFileLink name!");
163     }
164 
165     // Convert the HFileLink name into a real table/region/cf/hfile path.
166     TableName tableName = TableName.valueOf(m.group(1), m.group(2));
167     String regionName = m.group(3);
168     String hfileName = m.group(4);
169     String familyName = path.getParent().getName();
170     Path tableDir = FSUtils.getTableDir(new Path("./"), tableName);
171     return new Path(tableDir, new Path(regionName, new Path(familyName,
172         hfileName)));
173   }
174 
175   /**
176    * Get the HFile name of the referenced link
177    *
178    * @param fileName HFileLink file name
179    * @return the name of the referenced HFile
180    */
181   public static String getReferencedHFileName(final String fileName) {
182     Matcher m = REF_OR_HFILE_LINK_PATTERN.matcher(fileName);
183     if (!m.matches()) {
184       throw new IllegalArgumentException(fileName + " is not a valid HFileLink name!");
185     }
186     return(m.group(4));
187   }
188 
189   /**
190    * Get the Region name of the referenced link
191    *
192    * @param fileName HFileLink file name
193    * @return the name of the referenced Region
194    */
195   public static String getReferencedRegionName(final String fileName) {
196     Matcher m = REF_OR_HFILE_LINK_PATTERN.matcher(fileName);
197     if (!m.matches()) {
198       throw new IllegalArgumentException(fileName + " is not a valid HFileLink name!");
199     }
200     return(m.group(3));
201   }
202 
203   /**
204    * Get the Table name of the referenced link
205    *
206    * @param fileName HFileLink file name
207    * @return the name of the referenced Table
208    */
209   public static TableName getReferencedTableName(final String fileName) {
210     Matcher m = REF_OR_HFILE_LINK_PATTERN.matcher(fileName);
211     if (!m.matches()) {
212       throw new IllegalArgumentException(fileName + " is not a valid HFileLink name!");
213     }
214     return(TableName.valueOf(m.group(1), m.group(2)));
215   }
216 
217   /**
218    * Create a new HFileLink name
219    *
220    * @param hfileRegionInfo - Linked HFile Region Info
221    * @param hfileName - Linked HFile name
222    * @return file name of the HFile Link
223    */
224   public static String createHFileLinkName(final HRegionInfo hfileRegionInfo,
225       final String hfileName) {
226     return createHFileLinkName(hfileRegionInfo.getTableName(),
227                       hfileRegionInfo.getEncodedName(), hfileName);
228   }
229 
230   /**
231    * Create a new HFileLink name
232    *
233    * @param tableName - Linked HFile table name
234    * @param regionName - Linked HFile region name
235    * @param hfileName - Linked HFile name
236    * @return file name of the HFile Link
237    */
238   public static String createHFileLinkName(final TableName tableName,
239       final String regionName, final String hfileName) {
240     String s = String.format("%s=%s-%s",
241         tableName.getNameAsString().replace(TableName.NAMESPACE_DELIM, '='),
242         regionName, hfileName);
243     return s;
244   }
245 
246   /**
247    * Create a new HFileLink
248    *
249    * <p>It also adds a back-reference to the hfile back-reference directory
250    * to simplify the reference-count and the cleaning process.
251    *
252    * @param conf {@link Configuration} to read for the archive directory name
253    * @param fs {@link FileSystem} on which to write the HFileLink
254    * @param dstFamilyPath - Destination path (table/region/cf/)
255    * @param hfileRegionInfo - Linked HFile Region Info
256    * @param hfileName - Linked HFile name
257    * @return true if the file is created, otherwise the file exists.
258    * @throws IOException on file or parent directory creation failure
259    */
260   public static boolean create(final Configuration conf, final FileSystem fs,
261       final Path dstFamilyPath, final HRegionInfo hfileRegionInfo,
262       final String hfileName) throws IOException {
263     TableName linkedTable = hfileRegionInfo.getTableName();
264     String linkedRegion = hfileRegionInfo.getEncodedName();
265     return create(conf, fs, dstFamilyPath, linkedTable, linkedRegion, hfileName);
266   }
267 
268   /**
269    * Create a new HFileLink
270    *
271    * <p>It also adds a back-reference to the hfile back-reference directory
272    * to simplify the reference-count and the cleaning process.
273    *
274    * @param conf {@link Configuration} to read for the archive directory name
275    * @param fs {@link FileSystem} on which to write the HFileLink
276    * @param dstFamilyPath - Destination path (table/region/cf/)
277    * @param linkedTable - Linked Table Name
278    * @param linkedRegion - Linked Region Name
279    * @param hfileName - Linked HFile name
280    * @return true if the file is created, otherwise the file exists.
281    * @throws IOException on file or parent directory creation failure
282    */
283   public static boolean create(final Configuration conf, final FileSystem fs,
284       final Path dstFamilyPath, final TableName linkedTable, final String linkedRegion,
285       final String hfileName) throws IOException {
286     String familyName = dstFamilyPath.getName();
287     String regionName = dstFamilyPath.getParent().getName();
288     String tableName = FSUtils.getTableName(dstFamilyPath.getParent().getParent())
289         .getNameAsString();
290 
291     String name = createHFileLinkName(linkedTable, linkedRegion, hfileName);
292     String refName = createBackReferenceName(tableName, regionName);
293 
294     // Make sure the destination directory exists
295     fs.mkdirs(dstFamilyPath);
296 
297     // Make sure the FileLink reference directory exists
298     Path archiveStoreDir = HFileArchiveUtil.getStoreArchivePath(conf,
299           linkedTable, linkedRegion, familyName);
300     Path backRefssDir = getBackReferencesDir(archiveStoreDir, hfileName);
301     fs.mkdirs(backRefssDir);
302 
303     // Create the reference for the link
304     Path backRefPath = new Path(backRefssDir, refName);
305     fs.createNewFile(backRefPath);
306     try {
307       // Create the link
308       return fs.createNewFile(new Path(dstFamilyPath, name));
309     } catch (IOException e) {
310       LOG.error("couldn't create the link=" + name + " for " + dstFamilyPath, e);
311       // Revert the reference if the link creation failed
312       fs.delete(backRefPath, false);
313       throw e;
314     }
315   }
316 
317   /**
318    * Create a new HFileLink starting from a hfileLink name
319    *
320    * <p>It also adds a back-reference to the hfile back-reference directory
321    * to simplify the reference-count and the cleaning process.
322    *
323    * @param conf {@link Configuration} to read for the archive directory name
324    * @param fs {@link FileSystem} on which to write the HFileLink
325    * @param dstFamilyPath - Destination path (table/region/cf/)
326    * @param hfileLinkName - HFileLink name (it contains hfile-region-table)
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 createFromHFileLink(final Configuration conf, final FileSystem fs,
331       final Path dstFamilyPath, final String hfileLinkName) throws IOException {
332     Matcher m = LINK_NAME_PATTERN.matcher(hfileLinkName);
333     if (!m.matches()) {
334       throw new IllegalArgumentException(hfileLinkName + " is not a valid HFileLink name!");
335     }
336     return create(conf, fs, dstFamilyPath, TableName.valueOf(m.group(1), m.group(2)),
337         m.group(3), m.group(4));
338   }
339 
340   /**
341    * Create the back reference name
342    */
343   //package-private for testing
344   static String createBackReferenceName(final String tableNameStr,
345                                         final String regionName) {
346 
347     return regionName + "." + tableNameStr.replace(TableName.NAMESPACE_DELIM, '=');
348   }
349 
350   /**
351    * Get the full path of the HFile referenced by the back reference
352    *
353    * @param rootDir root hbase directory
354    * @param linkRefPath Link Back Reference path
355    * @return full path of the referenced hfile
356    * @throws IOException on unexpected error.
357    */
358   public static Path getHFileFromBackReference(final Path rootDir, final Path linkRefPath) {
359     Pair<TableName, String> p = parseBackReferenceName(linkRefPath.getName());
360     TableName linkTableName = p.getFirst();
361     String linkRegionName = p.getSecond();
362 
363     String hfileName = getBackReferenceFileName(linkRefPath.getParent());
364     Path familyPath = linkRefPath.getParent().getParent();
365     Path regionPath = familyPath.getParent();
366     Path tablePath = regionPath.getParent();
367 
368     String linkName = createHFileLinkName(FSUtils.getTableName(tablePath),
369         regionPath.getName(), hfileName);
370     Path linkTableDir = FSUtils.getTableDir(rootDir, linkTableName);
371     Path regionDir = HRegion.getRegionDir(linkTableDir, linkRegionName);
372     return new Path(new Path(regionDir, familyPath.getName()), linkName);
373   }
374 
375   static Pair<TableName, String> parseBackReferenceName(String name) {
376     int separatorIndex = name.indexOf('.');
377     String linkRegionName = name.substring(0, separatorIndex);
378     String tableSubstr = name.substring(separatorIndex + 1)
379         .replace('=', TableName.NAMESPACE_DELIM);
380     TableName linkTableName = TableName.valueOf(tableSubstr);
381     return new Pair<TableName, String>(linkTableName, linkRegionName);
382   }
383 
384   /**
385    * Get the full path of the HFile referenced by the back reference
386    *
387    * @param conf {@link Configuration} to read for the archive directory name
388    * @param linkRefPath Link Back Reference path
389    * @return full path of the referenced hfile
390    * @throws IOException on unexpected error.
391    */
392   public static Path getHFileFromBackReference(final Configuration conf, final Path linkRefPath)
393       throws IOException {
394     return getHFileFromBackReference(FSUtils.getRootDir(conf), linkRefPath);
395   }
396 
397 }