Patch ImmutableCollections for tests (#109271)

ImmutableCollections uses a seed, set early during JVM startup, which
affects the iteration order of collections. Although we do not want to
rely on the iteration order of Map and Set collections, bugs do
sometimes occur. In order to reproduce those bugs to fix them, it is
important the test seed for Elasticsearch matches the seed used in
ImmutableCollections.

Unfortunately ImmutableCollections is internal to the JDK, and the seed
used is private and final. This commit works around these limitations by
creating a patched version of ImmutableCollections which allows access
to the seed member. ESTestCase is then able to reflectively set the seed
at runtime based on the Elasticsearch seed.

Note that this only affects tests. ImmutableCollections remains is
unchanged for production code.

relates #94946
This commit is contained in:
Ryan Ernst 2024-06-05 11:13:55 -07:00 committed by GitHub
parent 307cac5648
commit 21ffdac4a7
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
7 changed files with 180 additions and 9 deletions

View File

@ -30,6 +30,7 @@ import org.gradle.api.tasks.SourceSetContainer;
import org.gradle.api.tasks.testing.Test;
import java.io.File;
import java.util.List;
import java.util.Map;
import static org.elasticsearch.gradle.util.FileUtils.mkdirs;
@ -100,6 +101,7 @@ public class ElasticsearchTestBasePlugin implements Plugin<Project> {
"-Xmx" + System.getProperty("tests.heap.size", "512m"),
"-Xms" + System.getProperty("tests.heap.size", "512m"),
"-Djava.security.manager=allow",
"--add-opens=java.base/java.util=ALL-UNNAMED",
// TODO: only open these for mockito when it is modularized
"--add-opens=java.base/java.security.cert=ALL-UNNAMED",
"--add-opens=java.base/java.nio.channels=ALL-UNNAMED",
@ -199,5 +201,29 @@ public class ElasticsearchTestBasePlugin implements Plugin<Project> {
}
});
});
configureImmutableCollectionsPatch(project);
}
private void configureImmutableCollectionsPatch(Project project) {
String patchProject = ":test:immutable-collections-patch";
if (project.findProject(patchProject) == null) {
return; // build tests may not have this project, just skip
}
String configurationName = "immutableCollectionsPatch";
FileCollection patchedFileCollection = project.getConfigurations()
.create(configurationName, config -> config.setCanBeConsumed(false));
var deps = project.getDependencies();
deps.add(configurationName, deps.project(Map.of("path", patchProject, "configuration", "patch")));
project.getTasks().withType(Test.class).matching(task -> task.getName().equals("test")).configureEach(test -> {
test.getInputs().files(patchedFileCollection);
test.systemProperty("tests.hackImmutableCollections", "true");
test.getJvmArgumentProviders()
.add(
() -> List.of(
"--patch-module=java.base=" + patchedFileCollection.getSingleFile() + "/java.base",
"--add-opens=java.base/java.util=ALL-UNNAMED"
)
);
});
}
}

View File

@ -172,7 +172,6 @@ public class MrjarPlugin implements Plugin<Project> {
testTask.getJavaLauncher()
.set(javaToolchains.launcherFor(spec -> spec.getLanguageVersion().set(JavaLanguageVersion.of(javaVersion))));
}
});
project.getTasks().named("check").configure(checkTask -> checkTask.dependsOn(testTaskProvider));

View File

@ -105,7 +105,8 @@ List projects = [
'test:test-clusters',
'test:x-content',
'test:yaml-rest-runner',
'test:metadata-extractor'
'test:metadata-extractor',
'test:immutable-collections-patch'
]
/**

View File

@ -73,6 +73,7 @@ public class BootstrapForTesting {
// without making things complex???
static {
// make sure java.io.tmpdir exists always (in case code uses it in a static initializer)
Path javaTmpDir = PathUtils.get(
Objects.requireNonNull(System.getProperty("java.io.tmpdir"), "please set ${java.io.tmpdir} in pom.xml")

View File

@ -79,6 +79,7 @@ import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.common.util.concurrent.ThreadContext;
import org.elasticsearch.common.xcontent.LoggingDeprecationHandler;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.core.Booleans;
import org.elasticsearch.core.CheckedRunnable;
import org.elasticsearch.core.PathUtils;
import org.elasticsearch.core.PathUtilsForTesting;
@ -145,6 +146,7 @@ import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.invoke.MethodHandles;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
@ -257,8 +259,9 @@ public abstract class ESTestCase extends LuceneTestCase {
private static final SetOnce<Boolean> WARN_SECURE_RANDOM_FIPS_NOT_DETERMINISTIC = new SetOnce<>();
static {
Random random = initTestSeed();
TEST_WORKER_VM_ID = System.getProperty(TEST_WORKER_SYS_PROPERTY, DEFAULT_TEST_WORKER_ID);
setTestSysProps();
setTestSysProps(random);
// TODO: consolidate logging initialization for tests so it all occurs in logconfigurator
LogConfigurator.loadLog4jPlugins();
LogConfigurator.configureESLogging();
@ -359,8 +362,46 @@ public abstract class ESTestCase extends LuceneTestCase {
JAVA_ZONE_IDS = ZoneId.getAvailableZoneIds().stream().filter(unsupportedZoneIdsPredicate.negate()).sorted().toList();
}
static Random initTestSeed() {
String inputSeed = System.getProperty("tests.seed");
long seed;
if (inputSeed == null) {
// when running tests in intellij, we don't have a seed. Setup the seed early here, before getting to RandomizedRunner,
// so that we can use it in ESTestCase static init
seed = System.nanoTime();
setTestSeed(Long.toHexString(seed));
} else {
String[] seedParts = inputSeed.split("[\\:]");
seed = Long.parseUnsignedLong(seedParts[0], 16);
}
if (Booleans.parseBoolean(System.getProperty("tests.hackImmutableCollections", "false"))) {
forceImmutableCollectionsSeed(seed);
}
return new Random(seed);
}
@SuppressForbidden(reason = "set tests.seed for intellij")
static void setTestSeed(String seed) {
System.setProperty("tests.seed", seed);
}
private static void forceImmutableCollectionsSeed(long seed) {
try {
MethodHandles.Lookup lookup = MethodHandles.lookup();
Class<?> collectionsClass = Class.forName("java.util.ImmutableCollections");
var salt32l = lookup.findStaticVarHandle(collectionsClass, "SALT32L", long.class);
var reverse = lookup.findStaticVarHandle(collectionsClass, "REVERSE", boolean.class);
salt32l.set(seed & 0xFFFF_FFFFL);
reverse.set((seed & 1) == 0);
} catch (Exception e) {
throw new AssertionError(e);
}
}
@SuppressForbidden(reason = "force log4j and netty sysprops")
private static void setTestSysProps() {
private static void setTestSysProps(Random random) {
System.setProperty("log4j.shutdownHookEnabled", "false");
System.setProperty("log4j2.disable.jmx", "true");
@ -377,11 +418,7 @@ public abstract class ESTestCase extends LuceneTestCase {
System.setProperty("es.set.netty.runtime.available.processors", "false");
// sometimes use the java.time date formatters
// we can't use randomBoolean here, the random context isn't set properly
// so read it directly from the test seed in an unfortunately hacky way
String testSeed = System.getProperty("tests.seed", "0");
boolean firstBit = (Integer.parseInt(testSeed.substring(testSeed.length() - 1), 16) & 1) == 1;
if (firstBit) {
if (random.nextBoolean()) {
System.setProperty("es.datetime.java_time_parsers", "true");
}
}

View File

@ -0,0 +1,49 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
import org.elasticsearch.gradle.OS
import org.elasticsearch.gradle.VersionProperties
import org.elasticsearch.gradle.internal.info.BuildParams
apply plugin: 'elasticsearch.java'
configurations {
patch
}
dependencies {
implementation 'org.ow2.asm:asm:9.7'
implementation 'org.ow2.asm:asm-tree:9.7'
}
def outputDir = layout.buildDirectory.dir("jdk-patches")
def generatePatch = tasks.register("generatePatch", JavaExec)
generatePatch.configure {
dependsOn tasks.named("compileJava")
inputs.property("java-home-set", BuildParams.getIsRuntimeJavaHomeSet())
inputs.property("java-version", BuildParams.runtimeJavaVersion)
outputs.dir(outputDir)
classpath = sourceSets.main.runtimeClasspath
mainClass = 'org.elasticsearch.jdk.patch.ImmutableCollectionsPatcher'
if (BuildParams.getIsRuntimeJavaHomeSet()) {
executable = "${BuildParams.runtimeJavaHome}/bin/java" + (OS.current() == OS.WINDOWS ? '.exe' : '')
} else {
javaLauncher = javaToolchains.launcherFor {
languageVersion = JavaLanguageVersion.of(BuildParams.runtimeJavaVersion.majorVersion)
vendor = VersionProperties.bundledJdkVendor == "openjdk" ?
JvmVendorSpec.ORACLE :
JvmVendorSpec.matching(VersionProperties.bundledJdkVendor)
}
}
doFirst {
args outputDir.get().getAsFile().toString()
}
}
artifacts.add("patch", generatePatch);

View File

@ -0,0 +1,58 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/
package org.elasticsearch.jdk.patch;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.FieldVisitor;
import org.objectweb.asm.Opcodes;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Loads ImmutableCollections.class from the current jdk and writes it out
* as a public class with SALT32L and REVERSE as public, non-final static fields.
*
* By exposing ImmutableCollections, tests run with this patched version can
* hook in the existing test seed to ensure consistent iteration of immutable collections.
* Note that the consistency is for <i>reproducing</i> dependencies on iteration
* order, so that the code can be fixed.
*/
public class ImmutableCollectionsPatcher {
private static final String CLASSFILE = "java.base/java/util/ImmutableCollections.class";
public static void main(String[] args) throws Exception {
Path outputDir = Paths.get(args[0]);
byte[] originalClassFile = Files.readAllBytes(Paths.get(URI.create("jrt:/" + CLASSFILE)));
ClassReader classReader = new ClassReader(originalClassFile);
ClassWriter classWriter = new ClassWriter(classReader, 0);
classReader.accept(new ClassVisitor(Opcodes.ASM9, classWriter) {
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
super.visit(version, Opcodes.ACC_PUBLIC, name, signature, superName, interfaces);
}
@Override
public FieldVisitor visitField(int access, String name, String descriptor, String signature, Object value) {
if (name.equals("SALT32L") || name.equals("REVERSE")) {
access = Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC;
}
return super.visitField(access, name, descriptor, signature, value);
}
}, 0);
Path outputFile = outputDir.resolve(CLASSFILE);
Files.createDirectories(outputFile.getParent());
Files.write(outputFile, classWriter.toByteArray());
}
}