Debian Codegraph @

src/main/org/h2/store/FileLock.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.store;
7
8 import java.io.IOException;
9 import java.io.OutputStream;
10 import java.net.BindException;
11 import java.net.ConnectException;
12 import java.net.InetAddress;
13 import java.net.ServerSocket;
14 import java.net.Socket;
15 import java.net.UnknownHostException;
16 import java.nio.ByteBuffer;
17 import java.nio.channels.FileChannel;
18 import java.util.Properties;
19 import org.h2.Driver;
20 import org.h2.api.ErrorCode;
21 import org.h2.engine.Constants;
22 import org.h2.engine.SessionRemote;
23 import org.h2.message.DbException;
24 import org.h2.message.Trace;
25 import org.h2.message.TraceSystem;
26 import org.h2.store.fs.FilePath;
27 import org.h2.store.fs.FileUtils;
28 import org.h2.util.MathUtils;
29 import org.h2.util.NetUtils;
30 import org.h2.util.SortedProperties;
31 import org.h2.util.StringUtils;
32 import org.h2.value.Transfer;
33
34 /**
35 * The file lock is used to lock a database so that only one process can write
36 * to it. It uses a cooperative locking protocol. Usually a .lock.db file is
37 * used, but locking by creating a socket is supported as well.
38 */
39 public class FileLock implements Runnable {
40
41 private static final String MAGIC = "FileLock";
42 private static final String FILE = "file";
43 private static final String SOCKET = "socket";
44 private static final int RANDOM_BYTES = 16;
45 private static final int SLEEP_GAP = 25;
46 private static final int TIME_GRANULARITY = 2000;
47
48 /**
49 * The lock file name.
50 */
51 private volatile String fileName;
52
53 /**
54 * The server socket (only used when using the SOCKET mode).
55 */
56 private volatile ServerSocket serverSocket;
57
58 /**
59 * Whether the file is locked.
60 */
61 private volatile boolean locked;
62
63 /**
64 * The number of milliseconds to sleep after checking a file.
65 */
66 private final int sleep;
67
68 /**
69 * The trace object.
70 */
71 private final Trace trace;
72
73 /**
74 * The last time the lock file was written.
75 */
76 private long lastWrite;
77
78 private String method;
79 private Properties properties;
80 private String uniqueId;
81 private Thread watchdog;
82
83 /**
84 * Create a new file locking object.
85 *
86 * @param traceSystem the trace system to use
87 * @param fileName the file name
88 * @param sleep the number of milliseconds to sleep
89 */
90 public FileLock(TraceSystem traceSystem, String fileName, int sleep) {
91 this.trace = traceSystem == null ?
92 null : traceSystem.getTrace(Trace.FILE_LOCK);
93 this.fileName = fileName;
94 this.sleep = sleep;
95 }
96
97 /**
98 * Lock the file if possible. A file may only be locked once.
99 *
100 * @param fileLockMethod the file locking method to use
101 * @throws DbException if locking was not successful
102 */
103 public synchronized void lock(FileLockMethod fileLockMethod) {
104 checkServer();
105 if (locked) {
106 throw DbException.getInternalError("already locked");
107 }
108 switch (fileLockMethod) {
109 case FILE:
110 lockFile();
111 break;
112 case SOCKET:
113 lockSocket();
114 break;
115 case FS:
116 case NO:
117 break;
118 }
119 locked = true;
120 }
121
122 /**
123 * Unlock the file. The watchdog thread is stopped. This method does nothing
124 * if the file is already unlocked.
125 */
126 public synchronized void unlock() {
127 if (!locked) {
128 return;
129 }
130 locked = false;
131 try {
132 if (watchdog != null) {
133 watchdog.interrupt();
134 }
135 } catch (Exception e) {
136 trace.debug(e, "unlock");
137 }
138 try {
139 if (fileName != null) {
140 if (load().equals(properties)) {
141 FileUtils.delete(fileName);
142 }
143 }
144 if (serverSocket != null) {
145 serverSocket.close();
146 }
147 } catch (Exception e) {
148 trace.debug(e, "unlock");
149 } finally {
150 fileName = null;
151 serverSocket = null;
152 }
153 try {
154 if (watchdog != null) {
155 watchdog.join();
156 }
157 } catch (Exception e) {
158 trace.debug(e, "unlock");
159 } finally {
160 watchdog = null;
161 }
162 }
163
164 /**
165 * Add or change a setting to the properties. This call does not save the
166 * file.
167 *
168 * @param key the key
169 * @param value the value
170 */
171 public void setProperty(String key, String value) {
172 if (value == null) {
173 properties.remove(key);
174 } else {
175 properties.put(key, value);
176 }
177 }
178
179 /**
180 * Save the lock file.
181 *
182 * @return the saved properties
183 */
184 public Properties save() {
185 try {
186 try (OutputStream out = FileUtils.newOutputStream(fileName, false)) {
187 properties.store(out, MAGIC);
188 }
189 lastWrite = aggressiveLastModified(fileName);
190 if (trace.isDebugEnabled()) {
191 trace.debug("save " + properties);
192 }
193 return properties;
194 } catch (IOException e) {
195 throw getExceptionFatal("Could not save properties " + fileName, e);
196 }
197 }
198
199 /**
200 * Aggressively read last modified time, to work-around remote filesystems.
201 *
202 * @param fileName file name to check
203 * @return last modified date/time in milliseconds UTC
204 */
205 private static long aggressiveLastModified(String fileName) {
206 /*
207 * Some remote filesystem, e.g. SMB on Windows, can cache metadata for
208 * 5-10 seconds. To work around that, do a one-byte read from the
209 * underlying file, which has the effect of invalidating the metadata
210 * cache.
211 */
212 try {
213 try (FileChannel f = FilePath.get(fileName).open("rws")) {
214 ByteBuffer b = ByteBuffer.wrap(new byte[1]);
215 f.read(b);
216 }
217 } catch (IOException ignoreEx) {}
218 return FileUtils.lastModified(fileName);
219 }
220
221 private void checkServer() {
222 Properties prop = load();
223 String server = prop.getProperty("server");
224 if (server == null) {
225 return;
226 }
227 boolean running = false;
228 String id = prop.getProperty("id");
229 try {
230 Socket socket = NetUtils.createSocket(server,
231 Constants.DEFAULT_TCP_PORT, false);
232 Transfer transfer = new Transfer(null, socket);
233 transfer.init();
234 transfer.writeInt(Constants.TCP_PROTOCOL_VERSION_MIN_SUPPORTED);
235 transfer.writeInt(Constants.TCP_PROTOCOL_VERSION_MAX_SUPPORTED);
236 transfer.writeString(null);
237 transfer.writeString(null);
238 transfer.writeString(id);
239 transfer.writeInt(SessionRemote.SESSION_CHECK_KEY);
240 transfer.flush();
241 int state = transfer.readInt();
242 if (state == SessionRemote.STATUS_OK) {
243 running = true;
244 }
245 transfer.close();
246 socket.close();
247 } catch (IOException e) {
248 return;
249 }
250 if (running) {
251 DbException e = DbException.get(
252 ErrorCode.DATABASE_ALREADY_OPEN_1, "Server is running");
253 throw e.addSQL(server + "/" + id);
254 }
255 }
256
257 /**
258 * Load the properties file.
259 *
260 * @return the properties
261 */
262 public Properties load() {
263 IOException lastException = null;
264 for (int i = 0; i < 5; i++) {
265 try {
266 Properties p2 = SortedProperties.loadProperties(fileName);
267 if (trace.isDebugEnabled()) {
268 trace.debug("load " + p2);
269 }
270 return p2;
271 } catch (IOException e) {
272 lastException = e;
273 }
274 }
275 throw getExceptionFatal(
276 "Could not load properties " + fileName, lastException);
277 }
278
279 private void waitUntilOld() {
280 for (int i = 0; i < 2 * TIME_GRANULARITY / SLEEP_GAP; i++) {
281 long last = aggressiveLastModified(fileName);
282 long dist = System.currentTimeMillis() - last;
283 if (dist < -TIME_GRANULARITY) {
284 // lock file modified in the future -
285 // wait for a bit longer than usual
286 try {
287 Thread.sleep(2 * (long) sleep);
288 } catch (Exception e) {
289 trace.debug(e, "sleep");
290 }
291 return;
292 } else if (dist > TIME_GRANULARITY) {
293 return;
294 }
295 try {
296 Thread.sleep(SLEEP_GAP);
297 } catch (Exception e) {
298 trace.debug(e, "sleep");
299 }
300 }
301 throw getExceptionFatal("Lock file recently modified", null);
302 }
303
304 private void setUniqueId() {
305 byte[] bytes = MathUtils.secureRandomBytes(RANDOM_BYTES);
306 String random = StringUtils.convertBytesToHex(bytes);
307 uniqueId = Long.toHexString(System.currentTimeMillis()) + random;
308 properties.setProperty("id", uniqueId);
309 }
310
311 private void lockFile() {
312 method = FILE;
313 properties = new SortedProperties();
314 properties.setProperty("method", String.valueOf(method));
315 setUniqueId();
316 FileUtils.createDirectories(FileUtils.getParent(fileName));
317 if (!FileUtils.createFile(fileName)) {
318 waitUntilOld();
319 String m2 = load().getProperty("method", FILE);
320 if (!m2.equals(FILE)) {
321 throw getExceptionFatal("Unsupported lock method " + m2, null);
322 }
323 save();
324 sleep(2 * sleep);
325 if (!load().equals(properties)) {
326 throw getExceptionAlreadyInUse("Locked by another process: " + fileName);
327 }
328 FileUtils.delete(fileName);
329 if (!FileUtils.createFile(fileName)) {
330 throw getExceptionFatal("Another process was faster", null);
331 }
332 }
333 save();
334 sleep(SLEEP_GAP);
335 if (!load().equals(properties)) {
336 fileName = null;
337 throw getExceptionFatal("Concurrent update", null);
338 }
339 locked = true;
340 watchdog = new Thread(this, "H2 File Lock Watchdog " + fileName);
341 Driver.setThreadContextClassLoader(watchdog);
342 watchdog.setDaemon(true);
343 watchdog.setPriority(Thread.MAX_PRIORITY - 1);
344 watchdog.start();
345 }
346
347 private void lockSocket() {
348 method = SOCKET;
349 properties = new SortedProperties();
350 properties.setProperty("method", String.valueOf(method));
351 setUniqueId();
352 // if this returns 127.0.0.1,
353 // the computer is probably not networked
354 String ipAddress = NetUtils.getLocalAddress();
355 FileUtils.createDirectories(FileUtils.getParent(fileName));
356 if (!FileUtils.createFile(fileName)) {
357 waitUntilOld();
358 long read = aggressiveLastModified(fileName);
359 Properties p2 = load();
360 String m2 = p2.getProperty("method", SOCKET);
361 if (m2.equals(FILE)) {
362 lockFile();
363 return;
364 } else if (!m2.equals(SOCKET)) {
365 throw getExceptionFatal("Unsupported lock method " + m2, null);
366 }
367 String ip = p2.getProperty("ipAddress", ipAddress);
368 if (!ipAddress.equals(ip)) {
369 throw getExceptionAlreadyInUse("Locked by another computer: " + ip);
370 }
371 String port = p2.getProperty("port", "0");
372 int portId = Integer.parseInt(port);
373 InetAddress address;
374 try {
375 address = InetAddress.getByName(ip);
376 } catch (UnknownHostException e) {
377 throw getExceptionFatal("Unknown host " + ip, e);
378 }
379 for (int i = 0; i < 3; i++) {
380 try {
381 Socket s = new Socket(address, portId);
382 s.close();
383 throw getExceptionAlreadyInUse("Locked by another process");
384 } catch (BindException e) {
385 throw getExceptionFatal("Bind Exception", null);
386 } catch (ConnectException e) {
387 trace.debug(e, "socket not connected to port " + port);
388 } catch (IOException e) {
389 throw getExceptionFatal("IOException", null);
390 }
391 }
392 if (read != aggressiveLastModified(fileName)) {
393 throw getExceptionFatal("Concurrent update", null);
394 }
395 FileUtils.delete(fileName);
396 if (!FileUtils.createFile(fileName)) {
397 throw getExceptionFatal("Another process was faster", null);
398 }
399 }
400 try {
401 // 0 to use any free port
402 serverSocket = NetUtils.createServerSocket(0, false);
403 int port = serverSocket.getLocalPort();
404 properties.setProperty("ipAddress", ipAddress);
405 properties.setProperty("port", Integer.toString(port));
406 } catch (Exception e) {
407 trace.debug(e, "lock");
408 serverSocket = null;
409 lockFile();
410 return;
411 }
412 save();
413 locked = true;
414 watchdog = new Thread(this,
415 "H2 File Lock Watchdog (Socket) " + fileName);
416 watchdog.setDaemon(true);
417 watchdog.start();
418 }
419
420 private static void sleep(int time) {
421 try {
422 Thread.sleep(time);
423 } catch (InterruptedException e) {
424 throw getExceptionFatal("Sleep interrupted", e);
425 }
426 }
427
428 private static DbException getExceptionFatal(String reason, Throwable t) {
429 return DbException.get(
430 ErrorCode.ERROR_OPENING_DATABASE_1, t, reason);
431 }
432
433 private DbException getExceptionAlreadyInUse(String reason) {
434 DbException e = DbException.get(
435 ErrorCode.DATABASE_ALREADY_OPEN_1, reason);
436 if (fileName != null) {
437 try {
438 Properties prop = load();
439 String server = prop.getProperty("server");
440 if (server != null) {
441 String serverId = server + "/" + prop.getProperty("id");
442 e = e.addSQL(serverId);
443 }
444 } catch (DbException e2) {
445 // ignore
446 }
447 }
448 return e;
449 }
450
451 /**
452 * Get the file locking method type given a method name.
453 *
454 * @param method the method name
455 * @return the method type
456 * @throws DbException if the method name is unknown
457 */
458 public static FileLockMethod getFileLockMethod(String method) {
459 if (method == null || method.equalsIgnoreCase("FILE")) {
460 return FileLockMethod.FILE;
461 } else if (method.equalsIgnoreCase("NO")) {
462 return FileLockMethod.NO;
463 } else if (method.equalsIgnoreCase("SOCKET")) {
464 return FileLockMethod.SOCKET;
465 } else if (method.equalsIgnoreCase("FS")) {
466 return FileLockMethod.FS;
467 } else {
468 throw DbException.get(ErrorCode.UNSUPPORTED_LOCK_METHOD_1, method);
469 }
470 }
471
472 public String getUniqueId() {
473 return uniqueId;
474 }
475
476 @Override
477 public void run() {
478 try {
479 while (locked && fileName != null) {
480 // trace.debug("watchdog check");
481 try {
482 if (!FileUtils.exists(fileName) ||
483 aggressiveLastModified(fileName) != lastWrite) {
484 save();
485 }
486 Thread.sleep(sleep);
487 } catch (OutOfMemoryError | NullPointerException | InterruptedException e) {
488 // ignore
489 } catch (Exception e) {
490 trace.debug(e, "watchdog");
491 }
492 }
493 while (true) {
494 // take a copy so we don't get an NPE between checking it and using it
495 ServerSocket local = serverSocket;
496 if (local == null) {
497 break;
498 }
499 try {
500 trace.debug("watchdog accept");
501 Socket s = local.accept();
502 s.close();
503 } catch (Exception e) {
504 trace.debug(e, "watchdog");
505 }
506 }
507 } catch (Exception e) {
508 trace.debug(e, "watchdog");
509 }
510 trace.debug("watchdog end");
511 }
512
513 }