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