b67c8f4a2c6b662497dc950b1bdc67b3c560fc43
[controller.git] / third-party / atomix / storage / src / main / java / io / atomix / storage / journal / BufferCleaner.java
1 /*
2  * Copyright 2019-present Open Networking Foundation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package io.atomix.storage.journal;
17
18 import org.slf4j.Logger;
19 import org.slf4j.LoggerFactory;
20
21 import java.io.IOException;
22 import java.lang.invoke.MethodHandle;
23 import java.lang.invoke.MethodHandles;
24 import java.lang.reflect.Field;
25 import java.lang.reflect.Method;
26 import java.nio.ByteBuffer;
27 import java.security.AccessController;
28 import java.security.PrivilegedAction;
29 import java.util.Objects;
30
31 import static java.lang.invoke.MethodHandles.constant;
32 import static java.lang.invoke.MethodHandles.dropArguments;
33 import static java.lang.invoke.MethodHandles.filterReturnValue;
34 import static java.lang.invoke.MethodHandles.guardWithTest;
35 import static java.lang.invoke.MethodHandles.lookup;
36 import static java.lang.invoke.MethodType.methodType;
37
38 /**
39  * Utility class which allows explicit calls to the DirectByteBuffer cleaner method instead of relying on GC.
40  */
41 public class BufferCleaner {
42
43   private static final Logger LOGGER = LoggerFactory.getLogger(BufferCleaner.class);
44
45   /**
46    * Reference to a Cleaner that does unmapping; no-op if not supported.
47    */
48   private static final Cleaner CLEANER;
49
50   static {
51     final Object hack = AccessController.doPrivileged((PrivilegedAction<Object>) BufferCleaner::unmapHackImpl);
52     if (hack instanceof Cleaner) {
53       CLEANER = (Cleaner) hack;
54       LOGGER.debug("java.nio.DirectByteBuffer.cleaner(): available");
55     } else {
56       CLEANER = (ByteBuffer buffer) -> {
57         // noop
58       };
59       LOGGER.debug("java.nio.DirectByteBuffer.cleaner(): unavailable: {}", hack);
60     }
61   }
62
63   private static Object unmapHackImpl() {
64     final MethodHandles.Lookup lookup = lookup();
65     try {
66       try {
67         // *** sun.misc.Unsafe unmapping (Java 9+) ***
68         final Class<?> unsafeClass = Class.forName("sun.misc.Unsafe");
69         // first check if Unsafe has the right method, otherwise we can give up
70         // without doing any security critical stuff:
71         final MethodHandle unmapper = lookup.findVirtual(unsafeClass, "invokeCleaner",
72             methodType(void.class, ByteBuffer.class));
73         // fetch the unsafe instance and bind it to the virtual MH:
74         final Field f = unsafeClass.getDeclaredField("theUnsafe");
75         f.setAccessible(true);
76         final Object theUnsafe = f.get(null);
77         return newBufferCleaner(ByteBuffer.class, unmapper.bindTo(theUnsafe));
78       } catch (SecurityException se) {
79         // rethrow to report errors correctly (we need to catch it here, as we also catch RuntimeException below!):
80         throw se;
81       } catch (ReflectiveOperationException | RuntimeException e) {
82         // *** sun.misc.Cleaner unmapping (Java 8) ***
83         final Class<?> directBufferClass = Class.forName("java.nio.DirectByteBuffer");
84
85         final Method m = directBufferClass.getMethod("cleaner");
86         m.setAccessible(true);
87         final MethodHandle directBufferCleanerMethod = lookup.unreflect(m);
88         final Class<?> cleanerClass = directBufferCleanerMethod.type().returnType();
89
90         /* "Compile" a MH that basically is equivalent to the following code:
91          * void unmapper(ByteBuffer byteBuffer) {
92          *   sun.misc.Cleaner cleaner = ((java.nio.DirectByteBuffer) byteBuffer).cleaner();
93          *   if (Objects.nonNull(cleaner)) {
94          *     cleaner.clean();
95          *   } else {
96          *     noop(cleaner); // the noop is needed because MethodHandles#guardWithTest always needs ELSE
97          *   }
98          * }
99          */
100         final MethodHandle cleanMethod = lookup.findVirtual(cleanerClass, "clean", methodType(void.class));
101         final MethodHandle nonNullTest = lookup.findStatic(Objects.class, "nonNull", methodType(boolean.class, Object.class))
102             .asType(methodType(boolean.class, cleanerClass));
103         final MethodHandle noop = dropArguments(constant(Void.class, null).asType(methodType(void.class)), 0, cleanerClass);
104         final MethodHandle unmapper = filterReturnValue(directBufferCleanerMethod, guardWithTest(nonNullTest, cleanMethod, noop))
105             .asType(methodType(void.class, ByteBuffer.class));
106         return newBufferCleaner(directBufferClass, unmapper);
107       }
108     } catch (SecurityException se) {
109       return "Unmapping is not supported, because not all required permissions are given to the Lucene JAR file: "
110           + se + " [Please grant at least the following permissions: RuntimePermission(\"accessClassInPackage.sun.misc\") "
111           + " and ReflectPermission(\"suppressAccessChecks\")]";
112     } catch (ReflectiveOperationException | RuntimeException e) {
113       return "Unmapping is not supported on this platform, because internal Java APIs are not compatible with this Atomix version: " + e;
114     }
115   }
116
117   private static Cleaner newBufferCleaner(final Class<?> unmappableBufferClass, final MethodHandle unmapper) {
118     return (ByteBuffer buffer) -> {
119       if (!buffer.isDirect()) {
120         return;
121       }
122       if (!unmappableBufferClass.isInstance(buffer)) {
123         throw new IllegalArgumentException("buffer is not an instance of " + unmappableBufferClass.getName());
124       }
125       final Throwable error = AccessController.doPrivileged((PrivilegedAction<Throwable>) () -> {
126         try {
127           unmapper.invokeExact(buffer);
128           return null;
129         } catch (Throwable t) {
130           return t;
131         }
132       });
133       if (error != null) {
134         throw new IOException("Unable to unmap the mapped buffer", error);
135       }
136     };
137   }
138
139   /**
140    * Free {@link ByteBuffer} if possible.
141    */
142   public static void freeBuffer(ByteBuffer buffer) throws IOException {
143     CLEANER.freeBuffer(buffer);
144   }
145 }