View Javadoc

1   /**
2    * Copyright The Apache Software Foundation
3    *
4    * Licensed to the Apache Software Foundation (ASF) under one or more
5    * contributor license agreements. See the NOTICE file distributed with this
6    * work for additional information regarding copyright ownership. The ASF
7    * licenses this file to you under the Apache License, Version 2.0 (the
8    * "License"); you may not use this file except in compliance with the License.
9    * 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, WITHOUT
15   * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
16   * License for the specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.apache.hadoop.hbase.io.hfile.bucket;
20  
21  import java.io.File;
22  import java.io.IOException;
23  import java.io.RandomAccessFile;
24  import java.nio.ByteBuffer;
25  import java.nio.channels.ClosedByInterruptException;
26  import java.nio.channels.ClosedChannelException;
27  import java.nio.channels.FileChannel;
28  import java.security.MessageDigest;
29  import java.security.NoSuchAlgorithmException;
30  import java.util.Arrays;
31  import java.util.concurrent.locks.ReentrantLock;
32  
33  import com.google.common.annotations.VisibleForTesting;
34  import org.apache.commons.logging.Log;
35  import org.apache.commons.logging.LogFactory;
36  import org.apache.hadoop.hbase.classification.InterfaceAudience;
37  import org.apache.hadoop.hbase.util.Bytes;
38  import org.apache.hadoop.util.Shell;
39  import org.apache.hadoop.util.StringUtils;
40  
41  /**
42   * IO engine that stores data to a file on the local file system.
43   */
44  @InterfaceAudience.Private
45  public class FileIOEngine implements PersistentIOEngine {
46    private static final Log LOG = LogFactory.getLog(FileIOEngine.class);
47    public static final String FILE_DELIMITER = ",";
48    private static final DuFileCommand DU = new DuFileCommand(new String[] {"du", ""});
49  
50    private final String[] filePaths;
51    private final FileChannel[] fileChannels;
52    private final RandomAccessFile[] rafs;
53    private final ReentrantLock[] channelLocks;
54  
55    private final long sizePerFile;
56    private final long capacity;
57  
58    private FileReadAccessor readAccessor = new FileReadAccessor();
59    private FileWriteAccessor writeAccessor = new FileWriteAccessor();
60  
61    public FileIOEngine(long capacity, String... filePaths) throws IOException {
62      this.sizePerFile = capacity / filePaths.length;
63      this.capacity = this.sizePerFile * filePaths.length;
64      this.filePaths = filePaths;
65      this.fileChannels = new FileChannel[filePaths.length];
66      this.rafs = new RandomAccessFile[filePaths.length];
67      this.channelLocks = new ReentrantLock[filePaths.length];
68      for (int i = 0; i < filePaths.length; i++) {
69        String filePath = filePaths[i];
70        try {
71          rafs[i] = new RandomAccessFile(filePath, "rw");
72          long totalSpace = new File(filePath).getTotalSpace();
73          if (totalSpace < sizePerFile) {
74            // The next setting length will throw exception,logging this message
75            // is just used for the detail reason of exception,
76            String msg = "Only " + StringUtils.byteDesc(totalSpace)
77              + " total space under " + filePath + ", not enough for requested "
78              + StringUtils.byteDesc(sizePerFile);
79            LOG.warn(msg);
80          }
81          File file = new File(filePath);
82          // setLength() method will change file's last modified time. So if don't do
83          // this check, wrong time will be used when calculating checksum.
84          if (file.length() != sizePerFile) {
85            rafs[i].setLength(sizePerFile);
86          }
87          fileChannels[i] = rafs[i].getChannel();
88          channelLocks[i] = new ReentrantLock();
89          LOG.info("Allocating cache " + StringUtils.byteDesc(sizePerFile)
90            + ", on the path: " + filePath);
91        } catch (IOException fex) {
92          LOG.error("Failed allocating cache on " + filePath, fex);
93          shutdown();
94          throw fex;
95        }
96      }
97    }
98  
99    @Override
100   public boolean verifyFileIntegrity(byte[] persistentChecksum, String algorithm) {
101     byte[] calculateChecksum = calculateChecksum(algorithm);
102     if (!Bytes.equals(persistentChecksum, calculateChecksum)) {
103       LOG.error("Mismatch of checksum! The persistent checksum is " +
104         Bytes.toString(persistentChecksum) + ", but the calculate checksum is " +
105         Bytes.toString(calculateChecksum));
106       return false;
107     }
108     return true;
109   }
110 
111   @Override
112   public String toString() {
113     return "ioengine=" + this.getClass().getSimpleName() + ", paths="
114         + Arrays.asList(filePaths) + ", capacity=" + String.format("%,d", this.capacity);
115   }
116 
117   /**
118    * File IO engine is always able to support persistent storage for the cache
119    * @return true
120    */
121   @Override
122   public boolean isPersistent() {
123     return true;
124   }
125 
126   /**
127    * Transfers data from file to the given byte buffer
128    * @param dstBuffer the given byte buffer into which bytes are to be written
129    * @param offset The offset in the file where the first byte to be read
130    * @return number of bytes read
131    * @throws IOException
132    */
133   @Override
134   public int read(ByteBuffer dstBuffer, long offset) throws IOException {
135     if (dstBuffer.remaining() != 0) {
136       return accessFile(readAccessor, dstBuffer, offset);
137     }
138     return 0;
139   }
140 
141   @VisibleForTesting
142   void closeFileChannels() {
143     for (FileChannel fileChannel: fileChannels) {
144       try {
145         fileChannel.close();
146       } catch (IOException e) {
147         LOG.warn("Failed to close FileChannel", e);
148       }
149     }
150   }
151 
152   /**
153    * Transfers data from the given byte buffer to file
154    * @param srcBuffer the given byte buffer from which bytes are to be read
155    * @param offset The offset in the file where the first byte to be written
156    * @throws IOException
157    */
158   @Override
159   public void write(ByteBuffer srcBuffer, long offset) throws IOException {
160     if (!srcBuffer.hasRemaining()) {
161       return;
162     }
163     accessFile(writeAccessor, srcBuffer, offset);
164   }
165 
166   /**
167    * Sync the data to file after writing
168    * @throws IOException
169    */
170   @Override
171   public void sync() throws IOException {
172     for (int i = 0; i < fileChannels.length; i++) {
173       try {
174         if (fileChannels[i] != null) {
175           fileChannels[i].force(true);
176         }
177       } catch (IOException ie) {
178         LOG.warn("Failed syncing data to " + this.filePaths[i]);
179         throw ie;
180       }
181     }
182   }
183 
184   /**
185    * Close the file
186    */
187   @Override
188   public void shutdown() {
189     for (int i = 0; i < filePaths.length; i++) {
190       try {
191         if (fileChannels[i] != null) {
192           fileChannels[i].close();
193         }
194         if (rafs[i] != null) {
195           rafs[i].close();
196         }
197       } catch (IOException ex) {
198         LOG.error("Failed closing " + filePaths[i] + " when shudown the IOEngine", ex);
199       }
200     }
201   }
202 
203   private int accessFile(FileAccessor accessor, ByteBuffer buffer, long globalOffset)
204       throws IOException {
205     int startFileNum = getFileNum(globalOffset);
206     int remainingAccessDataLen = buffer.remaining();
207     int endFileNum = getFileNum(globalOffset + remainingAccessDataLen - 1);
208     int accessFileNum = startFileNum;
209     long accessOffset = getAbsoluteOffsetInFile(accessFileNum, globalOffset);
210     int bufLimit = buffer.limit();
211     while (true) {
212       FileChannel fileChannel = fileChannels[accessFileNum];
213       int accessLen = 0;
214       if (endFileNum > accessFileNum) {
215         // short the limit;
216         buffer.limit((int) (buffer.limit() - remainingAccessDataLen + sizePerFile - accessOffset));
217       }
218       try {
219         accessLen = accessor.access(fileChannel, buffer, accessOffset);
220       } catch (ClosedByInterruptException e) {
221         throw e;
222       } catch (ClosedChannelException e) {
223         refreshFileConnection(accessFileNum, e);
224         continue;
225       }
226       // recover the limit
227       buffer.limit(bufLimit);
228       if (accessLen < remainingAccessDataLen) {
229         remainingAccessDataLen -= accessLen;
230         accessFileNum++;
231         accessOffset = 0;
232       } else {
233         break;
234       }
235       if (accessFileNum >= fileChannels.length) {
236         throw new IOException("Required data len " + StringUtils.byteDesc(buffer.remaining())
237             + " exceed the engine's capacity " + StringUtils.byteDesc(capacity) + " where offset="
238             + globalOffset);
239       }
240     }
241     return bufLimit;
242   }
243 
244   /**
245    * Get the absolute offset in given file with the relative global offset.
246    * @param fileNum
247    * @param globalOffset
248    * @return the absolute offset
249    */
250   private long getAbsoluteOffsetInFile(int fileNum, long globalOffset) {
251     return globalOffset - fileNum * sizePerFile;
252   }
253 
254   private int getFileNum(long offset) {
255     if (offset < 0) {
256       throw new IllegalArgumentException("Unexpected offset " + offset);
257     }
258     int fileNum = (int) (offset / sizePerFile);
259     if (fileNum >= fileChannels.length) {
260       throw new RuntimeException("Not expected offset " + offset + " where capacity=" + capacity);
261     }
262     return fileNum;
263   }
264 
265   @VisibleForTesting
266   FileChannel[] getFileChannels() {
267     return fileChannels;
268   }
269 
270   @VisibleForTesting
271   void refreshFileConnection(int accessFileNum, IOException ioe) throws IOException {
272     ReentrantLock channelLock = channelLocks[accessFileNum];
273     channelLock.lock();
274     try {
275       FileChannel fileChannel = fileChannels[accessFileNum];
276       if (fileChannel != null) {
277         // Don't re-open a channel if we were waiting on another
278         // thread to re-open the channel and it is now open.
279         if (fileChannel.isOpen()) {
280           return;
281         }
282         fileChannel.close();
283       }
284       LOG.warn("Caught ClosedChannelException accessing BucketCache, reopening file: "
285           + filePaths[accessFileNum], ioe);
286       rafs[accessFileNum] = new RandomAccessFile(filePaths[accessFileNum], "rw");
287       fileChannels[accessFileNum] = rafs[accessFileNum].getChannel();
288     } finally{
289       channelLock.unlock();
290     }
291   }
292 
293   @Override
294   public byte[] calculateChecksum(String algorithm) {
295     if (filePaths == null) {
296       return null;
297     }
298     try {
299       StringBuilder sb = new StringBuilder();
300       for (String filePath : filePaths){
301         File file = new File(filePath);
302         sb.append(filePath);
303         sb.append(getFileSize(filePath));
304         sb.append(file.lastModified());
305       }
306       MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
307       messageDigest.update(Bytes.toBytes(sb.toString()));
308       return messageDigest.digest();
309     } catch (IOException ioex) {
310       LOG.error("Calculating checksum failed.", ioex);
311       return null;
312     } catch (NoSuchAlgorithmException e) {
313       LOG.error("No such algorithm : " + algorithm + "!");
314       return null;
315     }
316   }
317 
318   /**
319    * Using Linux command du to get file's real size
320    * @param filePath the file
321    * @return file's real size
322    * @throws IOException something happened like file not exists
323    */
324   private static long getFileSize(String filePath) throws IOException {
325     DU.setExecCommand(filePath);
326     DU.execute();
327     return Long.parseLong(DU.getOutput().split("\t")[0]);
328   }
329 
330   private static class DuFileCommand extends Shell.ShellCommandExecutor {
331     private String[] execCommand;
332 
333     DuFileCommand(String[] execString) {
334       super(execString);
335       execCommand = execString;
336     }
337 
338     void setExecCommand(String filePath) {
339       this.execCommand[1] = filePath;
340     }
341 
342     @Override
343     public String[] getExecString() {
344       return this.execCommand;
345     }
346   }
347 
348   private static interface FileAccessor {
349     int access(FileChannel fileChannel, ByteBuffer byteBuffer, long accessOffset)
350         throws IOException;
351   }
352 
353   private static class FileReadAccessor implements FileAccessor {
354     @Override
355     public int access(FileChannel fileChannel, ByteBuffer byteBuffer, long accessOffset)
356         throws IOException {
357       return fileChannel.read(byteBuffer, accessOffset);
358     }
359   }
360 
361   private static class FileWriteAccessor implements FileAccessor {
362     @Override
363     public int access(FileChannel fileChannel, ByteBuffer byteBuffer, long accessOffset)
364         throws IOException {
365       return fileChannel.write(byteBuffer, accessOffset);
366     }
367   }
368 
369 }