Skip to content

Commit 348ae18

Browse files
committed
Extract instrumentation initialization to a separate class
1 parent f1f7459 commit 348ae18

File tree

2 files changed

+274
-231
lines changed

2 files changed

+274
-231
lines changed
Lines changed: 270 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,270 @@
1+
/*
2+
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
3+
* or more contributor license agreements. Licensed under the "Elastic License
4+
* 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side
5+
* Public License v 1"; you may not use this file except in compliance with, at
6+
* your election, the "Elastic License 2.0", the "GNU Affero General Public
7+
* License v3.0 only", or the "Server Side Public License, v 1".
8+
*/
9+
10+
package org.elasticsearch.entitlement.initialization;
11+
12+
import org.elasticsearch.core.internal.provider.ProviderLocator;
13+
import org.elasticsearch.entitlement.bridge.EntitlementChecker;
14+
import org.elasticsearch.entitlement.instrumentation.CheckMethod;
15+
import org.elasticsearch.entitlement.instrumentation.InstrumentationService;
16+
import org.elasticsearch.entitlement.instrumentation.Instrumenter;
17+
import org.elasticsearch.entitlement.instrumentation.MethodKey;
18+
import org.elasticsearch.entitlement.instrumentation.Transformer;
19+
import org.elasticsearch.entitlement.runtime.policy.entitlements.Entitlement;
20+
21+
import java.lang.instrument.Instrumentation;
22+
import java.lang.instrument.UnmodifiableClassException;
23+
import java.net.URI;
24+
import java.nio.channels.spi.SelectorProvider;
25+
import java.nio.file.AccessMode;
26+
import java.nio.file.CopyOption;
27+
import java.nio.file.DirectoryStream;
28+
import java.nio.file.FileStore;
29+
import java.nio.file.FileSystems;
30+
import java.nio.file.LinkOption;
31+
import java.nio.file.OpenOption;
32+
import java.nio.file.Path;
33+
import java.nio.file.WatchEvent;
34+
import java.nio.file.WatchService;
35+
import java.nio.file.attribute.FileAttribute;
36+
import java.nio.file.spi.FileSystemProvider;
37+
import java.util.ArrayList;
38+
import java.util.HashMap;
39+
import java.util.List;
40+
import java.util.Map;
41+
import java.util.Set;
42+
import java.util.concurrent.ExecutorService;
43+
import java.util.function.Function;
44+
import java.util.stream.Collectors;
45+
import java.util.stream.Stream;
46+
import java.util.stream.StreamSupport;
47+
48+
class DynamicInstrumentation {
49+
50+
interface InstrumentationInfoFactory {
51+
InstrumentationService.InstrumentationInfo of(String methodName, Class<?>... parameterTypes) throws ClassNotFoundException,
52+
NoSuchMethodException;
53+
}
54+
55+
private static final InstrumentationService INSTRUMENTATION_SERVICE = new ProviderLocator<>(
56+
"entitlement",
57+
InstrumentationService.class,
58+
"org.elasticsearch.entitlement.instrumentation",
59+
Set.of()
60+
).get();
61+
62+
/**
63+
* Initializes the dynamic (agent-based) instrumentation:
64+
* <ol>
65+
* <li>
66+
* Finds the version-specific subclass of {@link EntitlementChecker} to use
67+
* </li>
68+
* <li>
69+
* Builds the set of methods to instrument using {@link InstrumentationService#lookupMethods}
70+
* </li>
71+
* <li>
72+
* Augment this set “dynamically” using {@link InstrumentationService#lookupImplementationMethod}
73+
* </li>
74+
* <li>
75+
* Creates an {@link Instrumenter} via {@link InstrumentationService#newInstrumenter}, and adds a new {@link Transformer} (derived from
76+
* {@link java.lang.instrument.ClassFileTransformer}) that uses it. Transformers are invoked when a class is about to load, after its
77+
* bytes have been deserialized to memory but before the class is initialized.
78+
* </li>
79+
* <li>
80+
* Re-transforms all already loaded classes: we force the {@link Instrumenter} to run on classes that might have been already loaded
81+
* before entitlement initialization by calling the {@link java.lang.instrument.Instrumentation#retransformClasses} method on all
82+
* classes that were already loaded.
83+
* </li>
84+
* </ol>
85+
* <p>
86+
* The third step is needed as the JDK exposes some API through interfaces that have different (internal) implementations
87+
* depending on the JVM host platform. As we cannot instrument an interfaces, we find its concrete implementation.
88+
* A prime example is {@link FileSystemProvider}, which has different implementations (e.g. {@code UnixFileSystemProvider} or
89+
* {@code WindowsFileSystemProvider}). At runtime, we find the implementation class which is currently used by the JVM, and add
90+
* its methods to the set of methods to instrument. See e.g. {@link DynamicInstrumentation#fileSystemProviderChecks}.
91+
* </p>
92+
*
93+
* @param inst the JVM instrumentation class instance
94+
* @param checkerInterface the interface to use to find methods to instrument and to use in the injected instrumentation code
95+
* @param verifyBytecode whether we should perform bytecode verification before and after instrumenting each method
96+
*/
97+
static void initialize(Instrumentation inst, Class<?> checkerInterface, boolean verifyBytecode)
98+
throws ClassNotFoundException, NoSuchMethodException, UnmodifiableClassException {
99+
100+
var checkMethods = getMethodsToInstrument(checkerInterface);
101+
var classesToTransform = checkMethods.keySet().stream().map(MethodKey::className).collect(Collectors.toSet());
102+
103+
Instrumenter instrumenter = INSTRUMENTATION_SERVICE.newInstrumenter(checkerInterface, checkMethods);
104+
var transformer = new Transformer(instrumenter, classesToTransform, verifyBytecode);
105+
inst.addTransformer(transformer, true);
106+
107+
var classesToRetransform = findClassesToRetransform(inst.getAllLoadedClasses(), classesToTransform);
108+
try {
109+
inst.retransformClasses(classesToRetransform);
110+
} catch (VerifyError e) {
111+
// Turn on verification and try to retransform one class at the time to get detailed diagnostic
112+
transformer.enableClassVerification();
113+
114+
for (var classToRetransform : classesToRetransform) {
115+
inst.retransformClasses(classToRetransform);
116+
}
117+
118+
// We should have failed already in the loop above, but just in case we did not, rethrow.
119+
throw e;
120+
}
121+
}
122+
123+
private static Map<MethodKey, CheckMethod> getMethodsToInstrument(Class<?> checkerInterface)
124+
throws ClassNotFoundException, NoSuchMethodException {
125+
Map<MethodKey, CheckMethod> checkMethods = new HashMap<>(INSTRUMENTATION_SERVICE.lookupMethods(checkerInterface));
126+
Stream.of(
127+
fileSystemProviderChecks(),
128+
fileStoreChecks(),
129+
pathChecks(),
130+
Stream.of(
131+
INSTRUMENTATION_SERVICE.lookupImplementationMethod(
132+
SelectorProvider.class,
133+
"inheritedChannel",
134+
SelectorProvider.provider().getClass(),
135+
EntitlementChecker.class,
136+
"checkSelectorProviderInheritedChannel"
137+
)
138+
)
139+
)
140+
.flatMap(Function.identity())
141+
.forEach(instrumentation -> checkMethods.put(instrumentation.targetMethod(), instrumentation.checkMethod()));
142+
143+
return checkMethods;
144+
}
145+
146+
private static Stream<InstrumentationService.InstrumentationInfo> fileSystemProviderChecks() throws ClassNotFoundException,
147+
NoSuchMethodException {
148+
var fileSystemProviderClass = FileSystems.getDefault().provider().getClass();
149+
150+
var instrumentation = new InstrumentationInfoFactory() {
151+
@Override
152+
public InstrumentationService.InstrumentationInfo of(String methodName, Class<?>... parameterTypes)
153+
throws ClassNotFoundException, NoSuchMethodException {
154+
return INSTRUMENTATION_SERVICE.lookupImplementationMethod(
155+
FileSystemProvider.class,
156+
methodName,
157+
fileSystemProviderClass,
158+
EntitlementChecker.class,
159+
"check" + Character.toUpperCase(methodName.charAt(0)) + methodName.substring(1),
160+
parameterTypes
161+
);
162+
}
163+
};
164+
165+
return Stream.of(
166+
instrumentation.of("newFileSystem", URI.class, Map.class),
167+
instrumentation.of("newFileSystem", Path.class, Map.class),
168+
instrumentation.of("newInputStream", Path.class, OpenOption[].class),
169+
instrumentation.of("newOutputStream", Path.class, OpenOption[].class),
170+
instrumentation.of("newFileChannel", Path.class, Set.class, FileAttribute[].class),
171+
instrumentation.of("newAsynchronousFileChannel", Path.class, Set.class, ExecutorService.class, FileAttribute[].class),
172+
instrumentation.of("newByteChannel", Path.class, Set.class, FileAttribute[].class),
173+
instrumentation.of("newDirectoryStream", Path.class, DirectoryStream.Filter.class),
174+
instrumentation.of("createDirectory", Path.class, FileAttribute[].class),
175+
instrumentation.of("createSymbolicLink", Path.class, Path.class, FileAttribute[].class),
176+
instrumentation.of("createLink", Path.class, Path.class),
177+
instrumentation.of("delete", Path.class),
178+
instrumentation.of("deleteIfExists", Path.class),
179+
instrumentation.of("readSymbolicLink", Path.class),
180+
instrumentation.of("copy", Path.class, Path.class, CopyOption[].class),
181+
instrumentation.of("move", Path.class, Path.class, CopyOption[].class),
182+
instrumentation.of("isSameFile", Path.class, Path.class),
183+
instrumentation.of("isHidden", Path.class),
184+
instrumentation.of("getFileStore", Path.class),
185+
instrumentation.of("checkAccess", Path.class, AccessMode[].class),
186+
instrumentation.of("getFileAttributeView", Path.class, Class.class, LinkOption[].class),
187+
instrumentation.of("readAttributes", Path.class, Class.class, LinkOption[].class),
188+
instrumentation.of("readAttributes", Path.class, String.class, LinkOption[].class),
189+
instrumentation.of("readAttributesIfExists", Path.class, Class.class, LinkOption[].class),
190+
instrumentation.of("setAttribute", Path.class, String.class, Object.class, LinkOption[].class),
191+
instrumentation.of("exists", Path.class, LinkOption[].class)
192+
);
193+
}
194+
195+
private static Stream<InstrumentationService.InstrumentationInfo> fileStoreChecks() {
196+
var fileStoreClasses = StreamSupport.stream(FileSystems.getDefault().getFileStores().spliterator(), false)
197+
.map(FileStore::getClass)
198+
.distinct();
199+
return fileStoreClasses.flatMap(fileStoreClass -> {
200+
var instrumentation = new InstrumentationInfoFactory() {
201+
@Override
202+
public InstrumentationService.InstrumentationInfo of(String methodName, Class<?>... parameterTypes)
203+
throws ClassNotFoundException, NoSuchMethodException {
204+
return INSTRUMENTATION_SERVICE.lookupImplementationMethod(
205+
FileStore.class,
206+
methodName,
207+
fileStoreClass,
208+
EntitlementChecker.class,
209+
"check" + Character.toUpperCase(methodName.charAt(0)) + methodName.substring(1),
210+
parameterTypes
211+
);
212+
}
213+
};
214+
215+
try {
216+
return Stream.of(
217+
instrumentation.of("getFileStoreAttributeView", Class.class),
218+
instrumentation.of("getAttribute", String.class),
219+
instrumentation.of("getBlockSize"),
220+
instrumentation.of("getTotalSpace"),
221+
instrumentation.of("getUnallocatedSpace"),
222+
instrumentation.of("getUsableSpace"),
223+
instrumentation.of("isReadOnly"),
224+
instrumentation.of("name"),
225+
instrumentation.of("type")
226+
227+
);
228+
} catch (NoSuchMethodException | ClassNotFoundException e) {
229+
throw new RuntimeException(e);
230+
}
231+
});
232+
}
233+
234+
private static Stream<InstrumentationService.InstrumentationInfo> pathChecks() {
235+
var pathClasses = StreamSupport.stream(FileSystems.getDefault().getRootDirectories().spliterator(), false)
236+
.map(Path::getClass)
237+
.distinct();
238+
return pathClasses.flatMap(pathClass -> {
239+
InstrumentationInfoFactory instrumentation = (String methodName, Class<?>... parameterTypes) -> INSTRUMENTATION_SERVICE
240+
.lookupImplementationMethod(
241+
Path.class,
242+
methodName,
243+
pathClass,
244+
EntitlementChecker.class,
245+
"checkPath" + Character.toUpperCase(methodName.charAt(0)) + methodName.substring(1),
246+
parameterTypes
247+
);
248+
249+
try {
250+
return Stream.of(
251+
instrumentation.of("toRealPath", LinkOption[].class),
252+
instrumentation.of("register", WatchService.class, WatchEvent.Kind[].class),
253+
instrumentation.of("register", WatchService.class, WatchEvent.Kind[].class, WatchEvent.Modifier[].class)
254+
);
255+
} catch (NoSuchMethodException | ClassNotFoundException e) {
256+
throw new RuntimeException(e);
257+
}
258+
});
259+
}
260+
261+
private static Class<?>[] findClassesToRetransform(Class<?>[] loadedClasses, Set<String> classesToTransform) {
262+
List<Class<?>> retransform = new ArrayList<>();
263+
for (Class<?> loadedClass : loadedClasses) {
264+
if (classesToTransform.contains(loadedClass.getName().replace(".", "/"))) {
265+
retransform.add(loadedClass);
266+
}
267+
}
268+
return retransform.toArray(new Class<?>[0]);
269+
}
270+
}

0 commit comments

Comments
 (0)