View Javadoc

1   /*
2    * Copyright The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one
5    * or more contributor license agreements.  See the NOTICE file
6    * distributed with this work for additional information
7    * regarding copyright ownership.  The ASF licenses this file
8    * to you under the Apache License, Version 2.0 (the
9    * "License"); you may not use this file except in compliance
10   * with the License.  You may obtain a copy of the License at
11   *
12   *     http://www.apache.org/licenses/LICENSE-2.0
13   *
14   * Unless required by applicable law or agreed to in writing, software
15   * distributed under the License is distributed on an "AS IS" BASIS,
16   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17   * See the License for the specific language governing permissions and
18   * limitations under the License.
19   */
20  
21  package org.apache.hadoop.hbase.fs;
22  
23  import java.io.Closeable;
24  import java.io.IOException;
25  import java.lang.reflect.Field;
26  import java.lang.reflect.InvocationHandler;
27  import java.lang.reflect.InvocationTargetException;
28  import java.lang.reflect.Method;
29  import java.lang.reflect.Modifier;
30  import java.lang.reflect.Proxy;
31  import java.lang.reflect.UndeclaredThrowableException;
32  import java.net.URI;
33  
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.hadoop.conf.Configuration;
37  import org.apache.hadoop.fs.FSDataOutputStream;
38  import org.apache.hadoop.fs.FileSystem;
39  import org.apache.hadoop.fs.FilterFileSystem;
40  import org.apache.hadoop.fs.LocalFileSystem;
41  import org.apache.hadoop.fs.Path;
42  import org.apache.hadoop.hbase.ServerName;
43  import org.apache.hadoop.hbase.wal.DefaultWALProvider;
44  import org.apache.hadoop.hdfs.DFSClient;
45  import org.apache.hadoop.hdfs.DistributedFileSystem;
46  import org.apache.hadoop.hdfs.protocol.ClientProtocol;
47  import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
48  import org.apache.hadoop.hdfs.protocol.LocatedBlock;
49  import org.apache.hadoop.hdfs.protocol.LocatedBlocks;
50  import org.apache.hadoop.ipc.RPC;
51  import org.apache.hadoop.util.Progressable;
52  import org.apache.hadoop.util.ReflectionUtils;
53  
54  /**
55   * An encapsulation for the FileSystem object that hbase uses to access
56   * data. This class allows the flexibility of using  
57   * separate filesystem objects for reading and writing hfiles and wals.
58   * In future, if we want to make wals be in a different filesystem,
59   * this is the place to make it happen.
60   */
61  public class HFileSystem extends FilterFileSystem {
62    public static final Log LOG = LogFactory.getLog(HFileSystem.class);
63  
64    private final FileSystem noChecksumFs;   // read hfile data from storage
65    private final boolean useHBaseChecksum;
66  
67    /**
68     * Create a FileSystem object for HBase regionservers.
69     * @param conf The configuration to be used for the filesystem
70     * @param useHBaseChecksum if true, then use
71     *        checksum verfication in hbase, otherwise
72     *        delegate checksum verification to the FileSystem.
73     */
74    public HFileSystem(Configuration conf, boolean useHBaseChecksum)
75      throws IOException {
76  
77      // Create the default filesystem with checksum verification switched on.
78      // By default, any operation to this FilterFileSystem occurs on
79      // the underlying filesystem that has checksums switched on.
80      this.fs = FileSystem.get(conf);
81      this.useHBaseChecksum = useHBaseChecksum;
82      
83      fs.initialize(getDefaultUri(conf), conf);
84      
85      // disable checksum verification for local fileSystem, see HBASE-11218
86      if (fs instanceof LocalFileSystem) {
87        fs.setWriteChecksum(false);
88        fs.setVerifyChecksum(false);
89      }
90  
91      addLocationsOrderInterceptor(conf);
92  
93      // If hbase checksum verification is switched on, then create a new
94      // filesystem object that has cksum verification turned off.
95      // We will avoid verifying checksums in the fs client, instead do it
96      // inside of hbase.
97      // If this is the local file system hadoop has a bug where seeks
98      // do not go to the correct location if setVerifyChecksum(false) is called.
99      // This manifests itself in that incorrect data is read and HFileBlocks won't be able to read
100     // their header magic numbers. See HBASE-5885
101     if (useHBaseChecksum && !(fs instanceof LocalFileSystem)) {
102       conf = new Configuration(conf);
103       conf.setBoolean("dfs.client.read.shortcircuit.skip.checksum", true);
104       this.noChecksumFs = newInstanceFileSystem(conf);
105       this.noChecksumFs.setVerifyChecksum(false);
106     } else {
107       this.noChecksumFs = fs;
108     }
109   }
110 
111   /**
112    * Wrap a FileSystem object within a HFileSystem. The noChecksumFs and
113    * writefs are both set to be the same specified fs. 
114    * Do not verify hbase-checksums while reading data from filesystem.
115    * @param fs Set the noChecksumFs and writeFs to this specified filesystem.
116    */
117   public HFileSystem(FileSystem fs) {
118     this.fs = fs;
119     this.noChecksumFs = fs;
120     this.useHBaseChecksum = false;
121   }
122 
123   /**
124    * Returns the filesystem that is specially setup for 
125    * doing reads from storage. This object avoids doing 
126    * checksum verifications for reads.
127    * @return The FileSystem object that can be used to read data
128    *         from files.
129    */
130   public FileSystem getNoChecksumFs() {
131     return noChecksumFs;
132   }
133 
134   /**
135    * Returns the underlying filesystem
136    * @return The underlying FileSystem for this FilterFileSystem object.
137    */
138   public FileSystem getBackingFs() throws IOException {
139     return fs;
140   }
141 
142   /**
143    * Are we verifying checksums in HBase?
144    * @return True, if hbase is configured to verify checksums,
145    *         otherwise false.
146    */
147   public boolean useHBaseChecksum() {
148     return useHBaseChecksum;
149   }
150 
151   /**
152    * Close this filesystem object
153    */
154   @Override
155   public void close() throws IOException {
156     super.close();
157     if (this.noChecksumFs != fs) {
158       this.noChecksumFs.close();
159     }
160   }
161 
162  /**
163    * Returns a brand new instance of the FileSystem. It does not use
164    * the FileSystem.Cache. In newer versions of HDFS, we can directly
165    * invoke FileSystem.newInstance(Configuration).
166    * 
167    * @param conf Configuration
168    * @return A new instance of the filesystem
169    */
170   private static FileSystem newInstanceFileSystem(Configuration conf)
171     throws IOException {
172     URI uri = FileSystem.getDefaultUri(conf);
173     FileSystem fs = null;
174     Class<?> clazz = conf.getClass("fs." + uri.getScheme() + ".impl", null);
175     if (clazz != null) {
176       // This will be true for Hadoop 1.0, or 0.20.
177       fs = (FileSystem)ReflectionUtils.newInstance(clazz, conf);
178       fs.initialize(uri, conf);
179     } else {
180       // For Hadoop 2.0, we have to go through FileSystem for the filesystem
181       // implementation to be loaded by the service loader in case it has not
182       // been loaded yet.
183       Configuration clone = new Configuration(conf);
184       clone.setBoolean("fs." + uri.getScheme() + ".impl.disable.cache", true);
185       fs = FileSystem.get(uri, clone);
186     }
187     if (fs == null) {
188       throw new IOException("No FileSystem for scheme: " + uri.getScheme());
189     }
190 
191     return fs;
192   }
193 
194   public static boolean addLocationsOrderInterceptor(Configuration conf) throws IOException {
195     return addLocationsOrderInterceptor(conf, new ReorderWALBlocks());
196   }
197 
198   /**
199    * Add an interceptor on the calls to the namenode#getBlockLocations from the DFSClient
200    * linked to this FileSystem. See HBASE-6435 for the background.
201    * <p/>
202    * There should be no reason, except testing, to create a specific ReorderBlocks.
203    *
204    * @return true if the interceptor was added, false otherwise.
205    */
206   static boolean addLocationsOrderInterceptor(Configuration conf, final ReorderBlocks lrb) {
207     if (!conf.getBoolean("hbase.filesystem.reorder.blocks", true)) {  // activated by default
208       LOG.debug("addLocationsOrderInterceptor configured to false");
209       return false;
210     }
211 
212     FileSystem fs;
213     try {
214       fs = FileSystem.get(conf);
215     } catch (IOException e) {
216       LOG.warn("Can't get the file system from the conf.", e);
217       return false;
218     }
219 
220     if (!(fs instanceof DistributedFileSystem)) {
221       LOG.debug("The file system is not a DistributedFileSystem. " +
222           "Skipping on block location reordering");
223       return false;
224     }
225 
226     DistributedFileSystem dfs = (DistributedFileSystem) fs;
227     DFSClient dfsc = dfs.getClient();
228     if (dfsc == null) {
229       LOG.warn("The DistributedFileSystem does not contain a DFSClient. Can't add the location " +
230           "block reordering interceptor. Continuing, but this is unexpected."
231       );
232       return false;
233     }
234 
235     try {
236       Field nf = DFSClient.class.getDeclaredField("namenode");
237       nf.setAccessible(true);
238       Field modifiersField = Field.class.getDeclaredField("modifiers");
239       modifiersField.setAccessible(true);
240       modifiersField.setInt(nf, nf.getModifiers() & ~Modifier.FINAL);
241 
242       ClientProtocol namenode = (ClientProtocol) nf.get(dfsc);
243       if (namenode == null) {
244         LOG.warn("The DFSClient is not linked to a namenode. Can't add the location block" +
245             " reordering interceptor. Continuing, but this is unexpected."
246         );
247         return false;
248       }
249 
250       ClientProtocol cp1 = createReorderingProxy(namenode, lrb, conf);
251       nf.set(dfsc, cp1);
252       LOG.info("Added intercepting call to namenode#getBlockLocations so can do block reordering" +
253         " using class " + lrb.getClass().getName());
254     } catch (NoSuchFieldException e) {
255       LOG.warn("Can't modify the DFSClient#namenode field to add the location reorder.", e);
256       return false;
257     } catch (IllegalAccessException e) {
258       LOG.warn("Can't modify the DFSClient#namenode field to add the location reorder.", e);
259       return false;
260     }
261 
262     return true;
263   }
264 
265   private static ClientProtocol createReorderingProxy(final ClientProtocol cp,
266       final ReorderBlocks lrb, final Configuration conf) {
267     return (ClientProtocol) Proxy.newProxyInstance
268         (cp.getClass().getClassLoader(),
269             new Class[]{ClientProtocol.class, Closeable.class},
270             new InvocationHandler() {
271               public Object invoke(Object proxy, Method method,
272                                    Object[] args) throws Throwable {
273                 try {
274                   if ((args == null || args.length == 0)
275                       && "close".equals(method.getName())) {
276                     RPC.stopProxy(cp);
277                     return null;
278                   } else {
279                     Object res = method.invoke(cp, args);
280                     if (res != null && args != null && args.length == 3
281                         && "getBlockLocations".equals(method.getName())
282                         && res instanceof LocatedBlocks
283                         && args[0] instanceof String
284                         && args[0] != null) {
285                       lrb.reorderBlocks(conf, (LocatedBlocks) res, (String) args[0]);
286                     }
287                     return res;
288                   }
289                 } catch  (InvocationTargetException ite) {
290                   // We will have this for all the exception, checked on not, sent
291                   //  by any layer, including the functional exception
292                   Throwable cause = ite.getCause();
293                   if (cause == null){
294                     throw new RuntimeException(
295                       "Proxy invocation failed and getCause is null", ite);
296                   }
297                   if (cause instanceof UndeclaredThrowableException) {
298                     Throwable causeCause = cause.getCause();
299                     if (causeCause == null) {
300                       throw new RuntimeException("UndeclaredThrowableException had null cause!");
301                     }
302                     cause = cause.getCause();
303                   }
304                   throw cause;
305                 }
306               }
307             });
308   }
309 
310   /**
311    * Interface to implement to add a specific reordering logic in hdfs.
312    */
313   interface ReorderBlocks {
314     /**
315      *
316      * @param conf - the conf to use
317      * @param lbs - the LocatedBlocks to reorder
318      * @param src - the file name currently read
319      * @throws IOException - if something went wrong
320      */
321     void reorderBlocks(Configuration conf, LocatedBlocks lbs, String src) throws IOException;
322   }
323 
324   /**
325    * We're putting at lowest priority the wal files blocks that are on the same datanode
326    * as the original regionserver which created these files. This because we fear that the
327    * datanode is actually dead, so if we use it it will timeout.
328    */
329   static class ReorderWALBlocks implements ReorderBlocks {
330     public void reorderBlocks(Configuration conf, LocatedBlocks lbs, String src)
331         throws IOException {
332 
333       ServerName sn = DefaultWALProvider.getServerNameFromWALDirectoryName(conf, src);
334       if (sn == null) {
335         // It's not an WAL
336         return;
337       }
338 
339       // Ok, so it's an WAL
340       String hostName = sn.getHostname();
341       if (LOG.isTraceEnabled()) {
342         LOG.trace(src +
343             " is an WAL file, so reordering blocks, last hostname will be:" + hostName);
344       }
345 
346       // Just check for all blocks
347       for (LocatedBlock lb : lbs.getLocatedBlocks()) {
348         DatanodeInfo[] dnis = lb.getLocations();
349         if (dnis != null && dnis.length > 1) {
350           boolean found = false;
351           for (int i = 0; i < dnis.length - 1 && !found; i++) {
352             if (hostName.equals(dnis[i].getHostName())) {
353               // advance the other locations by one and put this one at the last place.
354               DatanodeInfo toLast = dnis[i];
355               System.arraycopy(dnis, i + 1, dnis, i, dnis.length - i - 1);
356               dnis[dnis.length - 1] = toLast;
357               found = true;
358             }
359           }
360         }
361       }
362     }
363   }
364 
365   /**
366    * Create a new HFileSystem object, similar to FileSystem.get().
367    * This returns a filesystem object that avoids checksum
368    * verification in the filesystem for hfileblock-reads.
369    * For these blocks, checksum verification is done by HBase.
370    */
371   static public FileSystem get(Configuration conf) throws IOException {
372     return new HFileSystem(conf, true);
373   }
374 
375   /**
376    * Wrap a LocalFileSystem within a HFileSystem.
377    */
378   static public FileSystem getLocalFs(Configuration conf) throws IOException {
379     return new HFileSystem(FileSystem.getLocal(conf));
380   }
381 
382   /**
383    * The org.apache.hadoop.fs.FilterFileSystem does not yet support 
384    * createNonRecursive. This is a hadoop bug and when it is fixed in Hadoop,
385    * this definition will go away.
386    */
387   @SuppressWarnings("deprecation")
388   public FSDataOutputStream createNonRecursive(Path f,
389       boolean overwrite,
390       int bufferSize, short replication, long blockSize,
391       Progressable progress) throws IOException {
392     return fs.createNonRecursive(f, overwrite, bufferSize, replication,
393                                  blockSize, progress);
394   }
395 }