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.IOException;
22 import java.io.RandomAccessFile;
23 import java.nio.ByteBuffer;
24 import java.nio.channels.FileChannel;
25
26 import org.apache.commons.logging.Log;
27 import org.apache.commons.logging.LogFactory;
28 import org.apache.hadoop.classification.InterfaceAudience;
29 import org.apache.hadoop.util.StringUtils;
30
31
32
33
34 @InterfaceAudience.Private
35 public class FileIOEngine implements IOEngine {
36 static final Log LOG = LogFactory.getLog(FileIOEngine.class);
37
38 private FileChannel fileChannel = null;
39 private final String path;
40 private long size;
41
42 public FileIOEngine(String filePath, long fileSize) throws IOException {
43 this.path = filePath;
44 this.size = fileSize;
45 RandomAccessFile raf = null;
46 try {
47 raf = new RandomAccessFile(filePath, "rw");
48 raf.setLength(fileSize);
49 fileChannel = raf.getChannel();
50 LOG.info("Allocating " + StringUtils.byteDesc(fileSize)
51 + ", on the path:" + filePath);
52 } catch (java.io.FileNotFoundException fex) {
53 LOG.error("Can't create bucket cache file " + filePath, fex);
54 throw fex;
55 } catch (IOException ioex) {
56 LOG.error("Can't extend bucket cache file; insufficient space for "
57 + StringUtils.byteDesc(fileSize), ioex);
58 if (raf != null) raf.close();
59 throw ioex;
60 }
61 }
62
63 @Override
64 public String toString() {
65 return "ioengine=" + this.getClass().getSimpleName() + ", path=" + this.path +
66 ", size=" + String.format("%,d", this.size);
67 }
68
69
70
71
72
73 @Override
74 public boolean isPersistent() {
75 return true;
76 }
77
78
79
80
81
82
83
84
85 @Override
86 public int read(ByteBuffer dstBuffer, long offset) throws IOException {
87 return fileChannel.read(dstBuffer, offset);
88 }
89
90
91
92
93
94
95
96 @Override
97 public void write(ByteBuffer srcBuffer, long offset) throws IOException {
98 fileChannel.write(srcBuffer, offset);
99 }
100
101
102
103
104
105 @Override
106 public void sync() throws IOException {
107 fileChannel.force(true);
108 }
109
110
111
112
113 @Override
114 public void shutdown() {
115 try {
116 fileChannel.close();
117 } catch (IOException ex) {
118 LOG.error("Can't shutdown cleanly", ex);
119 }
120 }
121 }