1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.appender;
18
19 import java.io.File;
20 import java.io.IOException;
21 import java.io.OutputStream;
22 import java.io.RandomAccessFile;
23 import java.io.Serializable;
24 import java.lang.reflect.Method;
25 import java.nio.ByteBuffer;
26 import java.nio.ByteOrder;
27 import java.nio.MappedByteBuffer;
28 import java.nio.channels.FileChannel;
29 import java.security.AccessController;
30 import java.security.PrivilegedActionException;
31 import java.security.PrivilegedExceptionAction;
32 import java.util.HashMap;
33 import java.util.Map;
34 import java.util.Objects;
35
36 import org.apache.logging.log4j.core.Layout;
37 import org.apache.logging.log4j.core.util.Closer;
38 import org.apache.logging.log4j.core.util.NullOutputStream;
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58 public class MemoryMappedFileManager extends OutputStreamManager {
59
60
61
62 static final int DEFAULT_REGION_LENGTH = 32 * 1024 * 1024;
63 private static final int MAX_REMAP_COUNT = 10;
64 private static final MemoryMappedFileManagerFactory FACTORY = new MemoryMappedFileManagerFactory();
65 private static final double NANOS_PER_MILLISEC = 1000.0 * 1000.0;
66
67 private final boolean isForce;
68 private final int regionLength;
69 private final String advertiseURI;
70 private final RandomAccessFile randomAccessFile;
71 private final ThreadLocal<Boolean> isEndOfBatch = new ThreadLocal<>();
72 private MappedByteBuffer mappedBuffer;
73 private long mappingOffset;
74
75 protected MemoryMappedFileManager(final RandomAccessFile file, final String fileName, final OutputStream os,
76 final boolean force, final long position, final int regionLength, final String advertiseURI,
77 final Layout<? extends Serializable> layout, final boolean writeHeader) throws IOException {
78 super(os, fileName, layout, writeHeader, ByteBuffer.wrap(new byte[0]));
79 this.isForce = force;
80 this.randomAccessFile = Objects.requireNonNull(file, "RandomAccessFile");
81 this.regionLength = regionLength;
82 this.advertiseURI = advertiseURI;
83 this.isEndOfBatch.set(Boolean.FALSE);
84 this.mappedBuffer = mmap(randomAccessFile.getChannel(), getFileName(), position, regionLength);
85 this.byteBuffer = mappedBuffer;
86 this.mappingOffset = position;
87 }
88
89
90
91
92
93
94
95
96
97
98
99
100 public static MemoryMappedFileManager getFileManager(final String fileName, final boolean append,
101 final boolean isForce, final int regionLength, final String advertiseURI,
102 final Layout<? extends Serializable> layout) {
103 return (MemoryMappedFileManager) getManager(fileName, new FactoryData(append, isForce, regionLength,
104 advertiseURI, layout), FACTORY);
105 }
106
107 public Boolean isEndOfBatch() {
108 return isEndOfBatch.get();
109 }
110
111 public void setEndOfBatch(final boolean endOfBatch) {
112 this.isEndOfBatch.set(Boolean.valueOf(endOfBatch));
113 }
114
115 @Override
116 protected synchronized void write(final byte[] bytes, int offset, int length, final boolean immediateFlush) {
117 while (length > mappedBuffer.remaining()) {
118 final int chunk = mappedBuffer.remaining();
119 mappedBuffer.put(bytes, offset, chunk);
120 offset += chunk;
121 length -= chunk;
122 remap();
123 }
124 mappedBuffer.put(bytes, offset, length);
125
126
127
128 }
129
130 private synchronized void remap() {
131 final long offset = this.mappingOffset + mappedBuffer.position();
132 final int length = mappedBuffer.remaining() + regionLength;
133 try {
134 unsafeUnmap(mappedBuffer);
135 final long fileLength = randomAccessFile.length() + regionLength;
136 LOGGER.debug("{} {} extending {} by {} bytes to {}", getClass().getSimpleName(), getName(), getFileName(),
137 regionLength, fileLength);
138
139 final long startNanos = System.nanoTime();
140 randomAccessFile.setLength(fileLength);
141 final float millis = (float) ((System.nanoTime() - startNanos) / NANOS_PER_MILLISEC);
142 LOGGER.debug("{} {} extended {} OK in {} millis", getClass().getSimpleName(), getName(), getFileName(),
143 millis);
144
145 mappedBuffer = mmap(randomAccessFile.getChannel(), getFileName(), offset, length);
146 this.byteBuffer = mappedBuffer;
147 mappingOffset = offset;
148 } catch (final Exception ex) {
149 logError("unable to remap", ex);
150 }
151 }
152
153 @Override
154 public synchronized void flush() {
155 mappedBuffer.force();
156 }
157
158 @Override
159 public synchronized void close() {
160 final long position = mappedBuffer.position();
161 final long length = mappingOffset + position;
162 try {
163 unsafeUnmap(mappedBuffer);
164 } catch (final Exception ex) {
165 logError("unable to unmap MappedBuffer", ex);
166 }
167 try {
168 LOGGER.debug("MMapAppender closing. Setting {} length to {} (offset {} + position {})", getFileName(),
169 length, mappingOffset, position);
170 randomAccessFile.setLength(length);
171 randomAccessFile.close();
172 } catch (final IOException ex) {
173 logError("unable to close MemoryMappedFile", ex);
174 }
175 }
176
177 public static MappedByteBuffer mmap(final FileChannel fileChannel, final String fileName, final long start,
178 final int size) throws IOException {
179 for (int i = 1;; i++) {
180 try {
181 LOGGER.debug("MMapAppender remapping {} start={}, size={}", fileName, start, size);
182
183 final long startNanos = System.nanoTime();
184 final MappedByteBuffer map = fileChannel.map(FileChannel.MapMode.READ_WRITE, start, size);
185 map.order(ByteOrder.nativeOrder());
186
187 final float millis = (float) ((System.nanoTime() - startNanos) / NANOS_PER_MILLISEC);
188 LOGGER.debug("MMapAppender remapped {} OK in {} millis", fileName, millis);
189
190 return map;
191 } catch (final IOException e) {
192 if (e.getMessage() == null || !e.getMessage().endsWith("user-mapped section open")) {
193 throw e;
194 }
195 LOGGER.debug("Remap attempt {}/{} failed. Retrying...", i, MAX_REMAP_COUNT, e);
196 if (i < MAX_REMAP_COUNT) {
197 Thread.yield();
198 } else {
199 try {
200 Thread.sleep(1);
201 } catch (final InterruptedException ignored) {
202 Thread.currentThread().interrupt();
203 throw e;
204 }
205 }
206 }
207 }
208 }
209
210 private static void unsafeUnmap(final MappedByteBuffer mbb) throws PrivilegedActionException {
211 LOGGER.debug("MMapAppender unmapping old buffer...");
212 final long startNanos = System.nanoTime();
213 AccessController.doPrivileged(new PrivilegedExceptionAction<Object>() {
214 @Override
215 public Object run() throws Exception {
216 final Method getCleanerMethod = mbb.getClass().getMethod("cleaner");
217 getCleanerMethod.setAccessible(true);
218 final Object cleaner = getCleanerMethod.invoke(mbb);
219 final Method cleanMethod = cleaner.getClass().getMethod("clean");
220 cleanMethod.invoke(cleaner);
221 return null;
222 }
223 });
224 final float millis = (float) ((System.nanoTime() - startNanos) / NANOS_PER_MILLISEC);
225 LOGGER.debug("MMapAppender unmapped buffer OK in {} millis", millis);
226 }
227
228
229
230
231
232
233 public String getFileName() {
234 return getName();
235 }
236
237
238
239
240
241
242 public int getRegionLength() {
243 return regionLength;
244 }
245
246
247
248
249
250
251
252 public boolean isImmediateFlush() {
253 return isForce;
254 }
255
256
257
258
259
260
261
262
263
264 @Override
265 public Map<String, String> getContentFormat() {
266 final Map<String, String> result = new HashMap<>(super.getContentFormat());
267 result.put("fileURI", advertiseURI);
268 return result;
269 }
270
271 @Override
272 protected void flushBuffer(final ByteBuffer buffer) {
273
274 }
275
276 @Override
277 public ByteBuffer getByteBuffer() {
278 return mappedBuffer;
279 }
280
281 @Override
282 public ByteBuffer drain(final ByteBuffer buf) {
283 remap();
284 return mappedBuffer;
285 }
286
287
288
289
290 private static class FactoryData {
291 private final boolean append;
292 private final boolean force;
293 private final int regionLength;
294 private final String advertiseURI;
295 private final Layout<? extends Serializable> layout;
296
297
298
299
300
301
302
303
304
305
306 public FactoryData(final boolean append, final boolean force, final int regionLength,
307 final String advertiseURI, final Layout<? extends Serializable> layout) {
308 this.append = append;
309 this.force = force;
310 this.regionLength = regionLength;
311 this.advertiseURI = advertiseURI;
312 this.layout = layout;
313 }
314 }
315
316
317
318
319 private static class MemoryMappedFileManagerFactory
320 implements ManagerFactory<MemoryMappedFileManager, FactoryData> {
321
322
323
324
325
326
327
328
329 @SuppressWarnings("resource")
330 @Override
331 public MemoryMappedFileManager createManager(final String name, final FactoryData data) {
332 final File file = new File(name);
333 final File parent = file.getParentFile();
334 if (null != parent && !parent.exists()) {
335 parent.mkdirs();
336 }
337 if (!data.append) {
338 file.delete();
339 }
340
341 final boolean writeHeader = !data.append || !file.exists();
342 final OutputStream os = NullOutputStream.NULL_OUTPUT_STREAM;
343 RandomAccessFile raf = null;
344 try {
345 raf = new RandomAccessFile(name, "rw");
346 final long position = (data.append) ? raf.length() : 0;
347 raf.setLength(position + data.regionLength);
348 return new MemoryMappedFileManager(raf, name, os, data.force, position, data.regionLength,
349 data.advertiseURI, data.layout, writeHeader);
350 } catch (final Exception ex) {
351 LOGGER.error("MemoryMappedFileManager (" + name + ") " + ex, ex);
352 Closer.closeSilently(raf);
353 }
354 return null;
355 }
356 }
357 }