-
-
Notifications
You must be signed in to change notification settings - Fork 120
Expand file tree
/
Copy pathLockedFile.java
More file actions
326 lines (275 loc) · 9.93 KB
/
LockedFile.java
File metadata and controls
326 lines (275 loc) · 9.93 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
/* JUG Java Uuid Generator
*
* Copyright (c) 2002- Tatu Saloranta, tatu.saloranta@iki.fi
*
* Licensed under the License specified in the file LICENSE which is
* included with the source code.
* You may not use this file except in compliance with the License.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fasterxml.uuid.ext;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Utility class used by {@link FileBasedTimestampSynchronizer} to do
* actual file access and locking.
*<p>
* Class stores simple timestamp values based on system time accessed
* using <code>System.currentTimeMillis()</code>. A single timestamp
* is stored into a file using {@link RandomAccessFile} in fully
* synchronized mode. Value is written in ISO-Latin (ISO-8859-1)
* encoding (superset of Ascii, 1 byte per char) as 16-digit hexadecimal
* number, surrounded by brackets. As such, file produced should
* always have exact size of 18 bytes. For extra robustness, slight
* variations in number of digits are accepeted, as are white space
* chars before and after bracketed value.
*/
class LockedFile
{
private static final Logger LOGGER = LoggerFactory.getLogger(LockedFile.class);
// Wrapper just to allow test(s) to disable/re-route
static LoggerWrapper logger = new LoggerWrapper(LOGGER);
/**
* Expected file length comes from hex-timestamp (16 digits),
* preamble "[0x",(3 chars) and trailer "]\r\n" (2 chars, linefeed
* to help debugging -- in some environments, missing trailing linefeed
* causes problems: also, 2-char linefeed to be compatible with all
* standard linefeeds on MacOS, Unix and Windows).
*/
final static int DEFAULT_LENGTH = 22;
final static long READ_ERROR = 0L;
// // // Configuration:
final File mFile;
// // // File state
RandomAccessFile mRAFile;
FileChannel mChannel;
FileLock mLock;
ByteBuffer mWriteBuffer = null;
/**
* Flag set if the original file (created before this instance was
* created) had size other than default size and needs to be
* truncated
*/
boolean mWeirdSize;
/**
* Marker used to ensure that the timestamps stored are monotonously
* increasing. Shouldn't really be needed, since caller should take
* care of it, but let's be bit paranoid here.
*/
long mLastTimestamp = 0L;
LockedFile(File f)
throws IOException
{
mFile = f;
RandomAccessFile raf = null;
FileChannel channel = null;
FileLock lock = null;
boolean ok = false;
try { // let's just use a single block to share cleanup code
raf = new RandomAccessFile(f, "rwd");
// Then lock them, if possible; if not, let's err out
channel = raf.getChannel();
if (channel == null) {
throw new IOException("Failed to access channel for '"+f+"'");
}
lock = channel.tryLock();
if (lock == null) {
throw new IOException("Failed to lock '"+f+"' (another JVM running UUIDGenerator?)");
}
ok = true;
} finally {
if (!ok) {
doDeactivate(f, raf, lock);
}
}
mRAFile = raf;
mChannel = channel;
mLock = lock;
}
// @since 5.2 for testing (for `LockedFileTest`)
static void logging(boolean enabled) {
logger = new LoggerWrapper(enabled ? LOGGER : null);
}
public void deactivate()
{
RandomAccessFile raf = mRAFile;
mRAFile = null;
FileLock lock = mLock;
mLock = null;
doDeactivate(mFile, raf, lock);
}
public long readStamp()
{
int size;
try {
size = (int) mChannel.size();
} catch (IOException ioe) {
logger.error(ioe, "Failed to read file size");
return READ_ERROR;
}
mWeirdSize = (size != DEFAULT_LENGTH);
// Let's check specifically empty files though
if (size == 0) {
logger.warn("Missing or empty file, can not read timestamp value");
return READ_ERROR;
}
// Let's also allow some slack... but just a bit
if (size > 100) {
size = 100;
}
byte[] data = new byte[size];
try {
mRAFile.readFully(data);
} catch (IOException ie) {
logger.error(ie, "(file '"+mFile+"') Failed to read "+size+" bytes");
return READ_ERROR;
}
/* Ok, got data. Now, we could just directly parse the bytes (since
* it is single-byte encoding)... but for convenience, let's create
* the String (this is only called once per JVM session)
*/
char[] cdata = new char[size];
for (int i = 0; i < size; ++i) {
cdata[i] = (char) (data[i] & 0xFF);
}
String dataStr = new String(cdata);
// And let's trim leading (and trailing, who cares)
dataStr = dataStr.trim();
long result = -1;
String errMsg = null;
if (!dataStr.startsWith("[0")
|| dataStr.length() < 3
|| Character.toLowerCase(dataStr.charAt(2)) != 'x') {
errMsg = "does not start with '[0x' prefix";
} else {
int ix = dataStr.indexOf(']', 3);
if (ix <= 0) {
errMsg = "does not end with ']' marker";
} else {
String hex = dataStr.substring(3, ix);
if (hex.length() > 16) {
errMsg = "length of the (hex) timestamp too long; expected 16, had "+hex.length()+" ('"+hex+"')";
} else {
try {
result = Long.parseLong(hex, 16);
} catch (NumberFormatException nex) {
errMsg = "does not contain a valid hex timestamp; got '"
+hex+"' (parse error: "+nex+")";
}
}
}
}
// Unsuccesful?
if (result < 0L) {
logger.error("(file '{}') Malformed timestamp file contents: {}", mFile, errMsg);
return READ_ERROR;
}
mLastTimestamp = result;
return result;
}
final static String HEX_DIGITS = "0123456789abcdef";
public void writeStamp(long stamp)
throws IOException
{
// Let's do sanity check first:
if (stamp <= mLastTimestamp) {
// same stamp is not dangerous, but pointless... so warning,
// not an error:
if (stamp == mLastTimestamp) {
logger.warn("(file '{}') Trying to re-write existing timestamp ({})", mFile, stamp);
return;
}
throw new IOException(""+mFile+" trying to overwrite existing value ("+mLastTimestamp+") with an earlier timestamp ("+stamp+")");
}
//System.err.println("!!!! Syncing ["+mFile+"] with "+stamp+" !!!");
// Need to initialize the buffer?
if (mWriteBuffer == null) {
mWriteBuffer = ByteBuffer.allocate(DEFAULT_LENGTH);
mWriteBuffer.put(0, (byte) '[');
mWriteBuffer.put(1, (byte) '0');
mWriteBuffer.put(2, (byte) 'x');
mWriteBuffer.put(19, (byte) ']');
mWriteBuffer.put(20, (byte) '\r');
mWriteBuffer.put(21, (byte) '\n');
}
// Converting to hex is simple
for (int i = 18; i >= 3; --i) {
int val = (((int) stamp) & 0x0F);
mWriteBuffer.put(i, (byte) HEX_DIGITS.charAt(val));
stamp = (stamp >> 4);
}
// and off we go:
mWriteBuffer.position(0); // to make sure we always write it all
mChannel.write(mWriteBuffer, 0L);
if (mWeirdSize) {
mRAFile.setLength(DEFAULT_LENGTH);
mWeirdSize = false;
}
// This is probably not needed (as the random access file is supposedly synced)... but let's be safe:
mChannel.force(false);
// And that's it!
}
/*
//////////////////////////////////////////////////////////////
// Internal methods
//////////////////////////////////////////////////////////////
*/
protected static void doDeactivate(File f, RandomAccessFile raf,
FileLock lock)
{
if (lock != null) {
try {
lock.release();
} catch (Throwable t) {
logger.error(t, "Failed to release lock (for file '"+f+"')");
}
}
if (raf != null) {
try {
raf.close();
} catch (Throwable t) {
logger.error(t, "Failed to close file '{"+f+"}'");
}
}
}
/*
//////////////////////////////////////////////////////////////
// Helper class(es)
//////////////////////////////////////////////////////////////
*/
private static class LoggerWrapper {
private final Logger logger;
public LoggerWrapper(Logger l) {
logger = l;
}
public void error(Throwable t, String msg) {
if (logger != null) {
logger.error(msg, t);
}
}
public void error(String msg, Object arg1, Object arg2) {
if (logger != null) {
logger.error(msg, arg1, arg2);
}
}
public void warn(String msg) {
if (logger != null) {
logger.warn(msg);
}
}
public void warn(String msg, Object arg1, Object arg2) {
if (logger != null) {
logger.warn(msg, arg1, arg2);
}
}
}
}