Debian Codegraph @

src/main/org/h2/mvstore/SingleFileStore.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.mvstore;
7
8 import java.io.IOException;
9 import java.nio.ByteBuffer;
10 import java.nio.channels.FileChannel;
11 import java.nio.channels.FileLock;
12 import java.nio.channels.OverlappingFileLockException;
13 import java.util.Map;
14 import java.util.function.Function;
15 import java.util.zip.ZipEntry;
16 import java.util.zip.ZipOutputStream;
17 import org.h2.mvstore.cache.FilePathCache;
18 import org.h2.store.fs.FilePath;
19 import org.h2.store.fs.encrypt.FileEncrypt;
20 import org.h2.store.fs.encrypt.FilePathEncrypt;
21 import org.h2.util.IOUtils;
22
23 /**
24 * The default storage mechanism of the MVStore. This implementation persists
25 * data to a file. The file store is responsible to persist data and for free
26 * space management.
27 */
28 public class SingleFileStore extends RandomAccessStore {
29
30 /**
31 * The file.
32 */
33 private FileChannel fileChannel;
34
35 /**
36 * The encrypted file (if encryption is used).
37 */
38 private FileChannel originalFileChannel;
39
40 /**
41 * The file lock.
42 */
43 private FileLock fileLock;
44
45 private final Map<String, Object> config;
46
47
48 public SingleFileStore(Map<String, Object> config) {
49 super(config);
50 this.config = config;
51 }
52
53 @Override
54 public String toString() {
55 return getFileName();
56 }
57
58 @Override
59 public ByteBuffer readFully(SFChunk chunk, long pos, int len) {
60 return readFully(fileChannel, pos, len);
61 }
62
63 @Override
64 protected void writeFully(SFChunk chunk, long pos, ByteBuffer src) {
65 int len = src.remaining();
66 setSize(Math.max(super.size(), pos + len));
67 DataUtils.writeFully(fileChannel, pos, src);
68 writeCount.incrementAndGet();
69 writeBytes.addAndGet(len);
70 }
71
72 /**
73 * Try to open the file.
74 * @param fileName the file name
75 * @param readOnly whether the file should only be opened in read-only mode,
76 * even if the file is writable
77 * @param encryptionKey the encryption key, or null if encryption is not
78 */
79 @Override
80 public void open(String fileName, boolean readOnly, char[] encryptionKey) {
81 open(fileName, readOnly,
82 encryptionKey == null ? null
83 : fileChannel -> new FileEncrypt(fileName, FilePathEncrypt.getPasswordBytes(encryptionKey),
84 fileChannel));
85 }
86
87 @Override
88 public SingleFileStore open(String fileName, boolean readOnly) {
89 SingleFileStore result = new SingleFileStore(config);
90 result.open(fileName, readOnly, originalFileChannel == null ? null :
91 fileChannel -> new FileEncrypt(fileName, (FileEncrypt)this.fileChannel, fileChannel));
92 return result;
93 }
94
95 private void open(String fileName, boolean readOnly, Function<FileChannel,FileChannel> encryptionTransformer) {
96 if (fileChannel != null && fileChannel.isOpen()) {
97 return;
98 }
99 // ensure the Cache file system is registered
100 FilePathCache.INSTANCE.getScheme();
101 FilePath f = FilePath.get(fileName);
102 FilePath parent = f.getParent();
103 if (parent != null && !parent.exists()) {
104 throw DataUtils.newIllegalArgumentException(
105 "Directory does not exist: {0}", parent);
106 }
107 if (f.exists() && !f.canWrite()) {
108 readOnly = true;
109 }
110 init(fileName, readOnly);
111 try {
112 fileChannel = f.open(readOnly ? "r" : "rw");
113 if (encryptionTransformer != null) {
114 originalFileChannel = fileChannel;
115 fileChannel = encryptionTransformer.apply(fileChannel);
116 }
117 fileLock = lockFileChannel(fileChannel, readOnly, fileName);
118 saveChunkLock.lock();
119 try {
120 setSize(fileChannel.size());
121 } finally {
122 saveChunkLock.unlock();
123 }
124 } catch (IOException e) {
125 try { close(); } catch (Exception ignore) {}
126 throw DataUtils.newMVStoreException(
127 DataUtils.ERROR_READING_FAILED,
128 "Could not open file {0}", fileName, e);
129 }
130 }
131
132 private FileLock lockFileChannel(FileChannel fileChannel, boolean readOnly, String fileName) throws IOException {
133 FileLock fileLock;
134 try {
135 fileLock = fileChannel.tryLock(0L, Long.MAX_VALUE, readOnly);
136 } catch (OverlappingFileLockException e) {
137 throw DataUtils.newMVStoreException(
138 DataUtils.ERROR_FILE_LOCKED,
139 "The file is locked: {0}", fileName, e);
140 }
141 if (fileLock == null) {
142 try { close(); } catch (Exception ignore) {}
143 throw DataUtils.newMVStoreException(
144 DataUtils.ERROR_FILE_LOCKED,
145 "The file is locked: {0}", fileName);
146 }
147 return fileLock;
148 }
149
150 /**
151 * Close this store.
152 */
153 @Override
154 public void close() {
155 try {
156 if(fileChannel.isOpen()) {
157 if (fileLock != null) {
158 fileLock.release();
159 }
160 fileChannel.close();
161 }
162 } catch (Exception e) {
163 throw DataUtils.newMVStoreException(
164 DataUtils.ERROR_WRITING_FAILED,
165 "Closing failed for file {0}", getFileName(), e);
166 } finally {
167 fileLock = null;
168 super.close();
169 }
170 }
171
172 /**
173 * Flush all changes.
174 */
175 @Override
176 public void sync() {
177 if (fileChannel.isOpen()) {
178 try {
179 fileChannel.force(true);
180 } catch (IOException e) {
181 throw DataUtils.newMVStoreException(
182 DataUtils.ERROR_WRITING_FAILED,
183 "Could not sync file {0}", getFileName(), e);
184 }
185 }
186 }
187
188 /**
189 * Truncate the file.
190 *
191 * @param size the new file size
192 */
193 @Override
194 @SuppressWarnings("ThreadPriorityCheck")
195 public void truncate(long size) {
196 int attemptCount = 0;
197 while (true) {
198 try {
199 writeCount.incrementAndGet();
200 fileChannel.truncate(size);
201 setSize(Math.min(super.size(), size));
202 return;
203 } catch (IOException e) {
204 if (++attemptCount == 10) {
205 throw DataUtils.newMVStoreException(
206 DataUtils.ERROR_WRITING_FAILED,
207 "Could not truncate file {0} to size {1}",
208 getFileName(), size, e);
209 }
210 System.gc();
211 Thread.yield();
212 }
213 }
214 }
215
216 /**
217 * Calculates relative "priority" for chunk to be moved.
218 *
219 * @param block where chunk starts
220 * @return priority, bigger number indicate that chunk need to be moved sooner
221 */
222 @Override
223 public int getMovePriority(int block) {
224 return freeSpace.getMovePriority(block);
225 }
226
227 @Override
228 protected long getAfterLastBlock_() {
229 return freeSpace.getAfterLastBlock();
230 }
231
232 @Override
233 public void backup(ZipOutputStream out) throws IOException {
234 boolean before = isSpaceReused();
235 setReuseSpace(false);
236 try {
237 backupFile(out, getFileName(), originalFileChannel != null ? originalFileChannel : fileChannel);
238 } finally {
239 setReuseSpace(before);
240 }
241 }
242
243 private static void backupFile(ZipOutputStream out, String fileName, FileChannel in) throws IOException {
244 String f = FilePath.get(fileName).toRealPath().getName();
245 f = correctFileName(f);
246 out.putNextEntry(new ZipEntry(f));
247 IOUtils.copy(in, out);
248 out.closeEntry();
249 }
250
251 /**
252 * Fix the file name, replacing backslash with slash.
253 *
254 * @param f the file name
255 * @return the corrected file name
256 */
257 public static String correctFileName(String f) {
258 f = f.replace('\\', '/');
259 if (f.startsWith("/")) {
260 f = f.substring(1);
261 }
262 return f;
263 }
264 }