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