1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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
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
75
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
83
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
119
120
121 @Override
122 public boolean isPersistent() {
123 return true;
124 }
125
126
127
128
129
130
131
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
154
155
156
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
168
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
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
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
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
246
247
248
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
278
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
320
321
322
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 }