1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45 package org.eclipse.jgit.internal.storage.file;
46
47 import static org.eclipse.jgit.lib.Constants.LOCK_SUFFIX;
48
49 import java.io.File;
50 import java.io.FileInputStream;
51 import java.io.FileNotFoundException;
52 import java.io.FileOutputStream;
53 import java.io.FilenameFilter;
54 import java.io.IOException;
55 import java.io.OutputStream;
56 import java.nio.ByteBuffer;
57 import java.nio.channels.Channels;
58 import java.nio.channels.FileChannel;
59 import java.nio.file.Files;
60 import java.nio.file.StandardCopyOption;
61 import java.nio.file.attribute.FileTime;
62 import java.text.MessageFormat;
63 import java.time.Instant;
64 import java.util.concurrent.TimeUnit;
65
66 import org.eclipse.jgit.internal.JGitText;
67 import org.eclipse.jgit.lib.Constants;
68 import org.eclipse.jgit.lib.ObjectId;
69 import org.eclipse.jgit.util.FS;
70 import org.eclipse.jgit.util.FS.LockToken;
71 import org.eclipse.jgit.util.FileUtils;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74
75
76
77
78
79
80
81
82
83
84
85 public class LockFile {
86 private final static Logger LOG = LoggerFactory.getLogger(LockFile.class);
87
88
89
90
91
92
93
94
95
96
97
98
99
100 public static boolean unlock(File file) {
101 final File lockFile = getLockFile(file);
102 final int flags = FileUtils.RETRY | FileUtils.SKIP_MISSING;
103 try {
104 FileUtils.delete(lockFile, flags);
105 } catch (IOException ignored) {
106
107 }
108 return !lockFile.exists();
109 }
110
111
112
113
114
115
116
117 static File getLockFile(File file) {
118 return new File(file.getParentFile(),
119 file.getName() + LOCK_SUFFIX);
120 }
121
122
123 static final FilenameFilter FILTER = (File dir,
124 String name) -> !name.endsWith(LOCK_SUFFIX);
125
126 private final File ref;
127
128 private final File lck;
129
130 private boolean haveLck;
131
132 FileOutputStream os;
133
134 private boolean needSnapshot;
135
136 boolean fsync;
137
138 private FileSnapshot commitSnapshot;
139
140 private LockToken token;
141
142
143
144
145
146
147
148 public LockFile(File f) {
149 ref = f;
150 lck = getLockFile(ref);
151 }
152
153
154
155
156
157
158
159
160
161
162 public boolean lock() throws IOException {
163 FileUtils.mkdirs(lck.getParentFile(), true);
164 try {
165 token = FS.DETECTED.createNewFileAtomic(lck);
166 } catch (IOException e) {
167 LOG.error(JGitText.get().failedCreateLockFile, lck, e);
168 throw e;
169 }
170 if (token.isCreated()) {
171 haveLck = true;
172 try {
173 os = new FileOutputStream(lck);
174 } catch (IOException ioe) {
175 unlock();
176 throw ioe;
177 }
178 } else {
179 closeToken();
180 }
181 return haveLck;
182 }
183
184
185
186
187
188
189
190
191
192
193 public boolean lockForAppend() throws IOException {
194 if (!lock())
195 return false;
196 copyCurrentContent();
197 return true;
198 }
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219 public void copyCurrentContent() throws IOException {
220 requireLock();
221 try {
222 try (FileInputStream fis = new FileInputStream(ref)) {
223 if (fsync) {
224 FileChannel in = fis.getChannel();
225 long pos = 0;
226 long cnt = in.size();
227 while (0 < cnt) {
228 long r = os.getChannel().transferFrom(in, pos, cnt);
229 pos += r;
230 cnt -= r;
231 }
232 } else {
233 final byte[] buf = new byte[2048];
234 int r;
235 while ((r = fis.read(buf)) >= 0)
236 os.write(buf, 0, r);
237 }
238 }
239 } catch (FileNotFoundException fnfe) {
240 if (ref.exists()) {
241 unlock();
242 throw fnfe;
243 }
244
245
246
247 } catch (IOException | RuntimeException | Error ioe) {
248 unlock();
249 throw ioe;
250 }
251 }
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266 public void write(ObjectId id) throws IOException {
267 byte[] buf = new byte[Constants.OBJECT_ID_STRING_LENGTH + 1];
268 id.copyTo(buf, 0);
269 buf[Constants.OBJECT_ID_STRING_LENGTH] = '\n';
270 write(buf);
271 }
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287 public void write(byte[] content) throws IOException {
288 requireLock();
289 try {
290 if (fsync) {
291 FileChannel fc = os.getChannel();
292 ByteBuffer buf = ByteBuffer.wrap(content);
293 while (0 < buf.remaining())
294 fc.write(buf);
295 fc.force(true);
296 } else {
297 os.write(content);
298 }
299 os.close();
300 os = null;
301 } catch (IOException | RuntimeException | Error ioe) {
302 unlock();
303 throw ioe;
304 }
305 }
306
307
308
309
310
311
312
313
314
315
316 public OutputStream getOutputStream() {
317 requireLock();
318
319 final OutputStream out;
320 if (fsync)
321 out = Channels.newOutputStream(os.getChannel());
322 else
323 out = os;
324
325 return new OutputStream() {
326 @Override
327 public void write(byte[] b, int o, int n)
328 throws IOException {
329 out.write(b, o, n);
330 }
331
332 @Override
333 public void write(byte[] b) throws IOException {
334 out.write(b);
335 }
336
337 @Override
338 public void write(int b) throws IOException {
339 out.write(b);
340 }
341
342 @Override
343 public void close() throws IOException {
344 try {
345 if (fsync)
346 os.getChannel().force(true);
347 out.close();
348 os = null;
349 } catch (IOException | RuntimeException | Error ioe) {
350 unlock();
351 throw ioe;
352 }
353 }
354 };
355 }
356
357 void requireLock() {
358 if (os == null) {
359 unlock();
360 throw new IllegalStateException(MessageFormat.format(JGitText.get().lockOnNotHeld, ref));
361 }
362 }
363
364
365
366
367
368
369
370
371
372 public void setNeedStatInformation(boolean on) {
373 setNeedSnapshot(on);
374 }
375
376
377
378
379
380
381
382
383 public void setNeedSnapshot(boolean on) {
384 needSnapshot = on;
385 }
386
387
388
389
390
391
392
393 public void setFSync(boolean on) {
394 fsync = on;
395 }
396
397
398
399
400
401
402
403
404
405
406
407
408
409 public void waitForStatChange() throws InterruptedException {
410 FileSnapshot o = FileSnapshot.save(ref);
411 FileSnapshot n = FileSnapshot.save(lck);
412 long fsTimeResolution = FS.getFileStoreAttributes(lck.toPath())
413 .getFsTimestampResolution().toNanos();
414 while (o.equals(n)) {
415 TimeUnit.NANOSECONDS.sleep(fsTimeResolution);
416 try {
417 Files.setLastModifiedTime(lck.toPath(),
418 FileTime.from(Instant.now()));
419 } catch (IOException e) {
420 n.waitUntilNotRacy();
421 }
422 n = FileSnapshot.save(lck);
423 }
424 }
425
426
427
428
429
430
431
432
433
434
435
436
437 public boolean commit() {
438 if (os != null) {
439 unlock();
440 throw new IllegalStateException(MessageFormat.format(JGitText.get().lockOnNotClosed, ref));
441 }
442
443 saveStatInformation();
444 try {
445 FileUtils.rename(lck, ref, StandardCopyOption.ATOMIC_MOVE);
446 haveLck = false;
447 closeToken();
448 return true;
449 } catch (IOException e) {
450 unlock();
451 return false;
452 }
453 }
454
455 private void closeToken() {
456 if (token != null) {
457 token.close();
458 token = null;
459 }
460 }
461
462 private void saveStatInformation() {
463 if (needSnapshot)
464 commitSnapshot = FileSnapshot.save(lck);
465 }
466
467
468
469
470
471
472
473 @Deprecated
474 public long getCommitLastModified() {
475 return commitSnapshot.lastModified();
476 }
477
478
479
480
481
482
483 public Instant getCommitLastModifiedInstant() {
484 return commitSnapshot.lastModifiedInstant();
485 }
486
487
488
489
490
491
492 public FileSnapshot getCommitSnapshot() {
493 return commitSnapshot;
494 }
495
496
497
498
499
500
501
502 public void createCommitSnapshot() {
503 saveStatInformation();
504 }
505
506
507
508
509
510
511 public void unlock() {
512 if (os != null) {
513 try {
514 os.close();
515 } catch (IOException e) {
516 LOG.error(MessageFormat
517 .format(JGitText.get().unlockLockFileFailed, lck), e);
518 }
519 os = null;
520 }
521
522 if (haveLck) {
523 haveLck = false;
524 try {
525 FileUtils.delete(lck, FileUtils.RETRY);
526 } catch (IOException e) {
527 LOG.error(MessageFormat
528 .format(JGitText.get().unlockLockFileFailed, lck), e);
529 } finally {
530 closeToken();
531 }
532 }
533 }
534
535
536 @SuppressWarnings("nls")
537 @Override
538 public String toString() {
539 return "LockFile[" + lck + ", haveLck=" + haveLck + "]";
540 }
541 }