Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
…101266_fix
  • Loading branch information
astefan committed Dec 6, 2023
2 parents 495de5f + 7413e41 commit 6abd99f
Show file tree
Hide file tree
Showing 642 changed files with 17,667 additions and 3,734 deletions.
10 changes: 10 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,16 @@ and then run `curl` in another window like this:

curl -u elastic:password localhost:9200

To send requests to this Elasticsearch instance, either use the built-in `elastic`
user and password as above or use the pre-configured `elastic-admin` user:

curl -u elastic-admin:elastic-password localhost:9200

Security can also be disabled altogether:

./gradlew :run -Dtests.es.xpack.security.enabled=false

The definition of this Elasticsearch cluster can be found [here](build-tools-internal/src/main/groovy/elasticsearch.run.gradle).

### Importing the project into IntelliJ IDEA

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
/*
* 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.benchmark.index.mapper;

import org.elasticsearch.common.UUIDs;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.LuceneDocument;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.Mapping;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.mapper.SourceToParse;
import org.elasticsearch.xcontent.XContentType;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.Fork;
import org.openjdk.jmh.annotations.Measurement;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Param;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.Setup;
import org.openjdk.jmh.annotations.State;
import org.openjdk.jmh.annotations.Warmup;

import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.DoubleStream;
import java.util.stream.IntStream;
import java.util.stream.Stream;

@Fork(value = 3)
@Warmup(iterations = 3)
@Measurement(iterations = 5)
@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.MILLISECONDS)
@State(Scope.Benchmark)
public class DynamicMapperBenchmark {

@Param({ "1600172297" })
private long seed;

private Random random;
private SourceToParse[] sources;

@Setup
public void setUp() {
this.random = new Random(seed);
this.sources = generateRandomDocuments(500);
}

private SourceToParse[] generateRandomDocuments(int count) {
var docs = new SourceToParse[count];
for (int i = 0; i < count; i++) {
docs[i] = generateRandomDocument();
}
return docs;
}

private SourceToParse generateRandomDocument() {
int textFields = 50;
int intFields = 50;
int floatFields = 50;
int objFields = 10;
int objFieldDepth = 10;
int fieldValueCountMax = 25;
StringBuilder builder = new StringBuilder();
builder.append("{");
for (int i = 0; i < textFields; i++) {
if (random.nextBoolean()) {
StringBuilder fieldValueBuilder = generateTextField(fieldValueCountMax);
builder.append("\"text_field_").append(i).append("\":").append(fieldValueBuilder).append(",");
}
}
for (int i = 0; i < intFields; i++) {
if (random.nextBoolean()) {
int fieldValueCount = random.nextInt(fieldValueCountMax);
builder.append("\"int_field_")
.append(i)
.append("\":")
.append(Arrays.toString(IntStream.generate(() -> random.nextInt()).limit(fieldValueCount).toArray()))
.append(",");
}
}
for (int i = 0; i < floatFields; i++) {
if (random.nextBoolean()) {
int fieldValueCount = random.nextInt(fieldValueCountMax);
builder.append("\"float_field_")
.append(i)
.append("\":")
.append(Arrays.toString(DoubleStream.generate(() -> random.nextFloat()).limit(fieldValueCount).toArray()))
.append(",");
}
}
for (int i = 0; i < objFields; i++) {
final int idx = i;
if (random.nextBoolean()) {
continue;
}
String objFieldPrefix = Stream.generate(() -> "obj_field_" + idx).limit(objFieldDepth).collect(Collectors.joining("."));
for (int j = 0; j < textFields; j++) {
if (random.nextBoolean()) {
StringBuilder fieldValueBuilder = generateTextField(fieldValueCountMax);
builder.append("\"")
.append(objFieldPrefix)
.append(".text_field_")
.append(j)
.append("\":")
.append(fieldValueBuilder)
.append(",");
}
}
for (int j = 0; j < intFields; j++) {
if (random.nextBoolean()) {
int fieldValueCount = random.nextInt(fieldValueCountMax);
builder.append("\"")
.append(objFieldPrefix)
.append(".int_field_")
.append(j)
.append("\":")
.append(Arrays.toString(IntStream.generate(() -> random.nextInt()).limit(fieldValueCount).toArray()))
.append(",");
}
}
for (int j = 0; j < floatFields; j++) {
if (random.nextBoolean()) {
int fieldValueCount = random.nextInt(fieldValueCountMax);
builder.append("\"")
.append(objFieldPrefix)
.append(".float_field_")
.append(j)
.append("\":")
.append(Arrays.toString(DoubleStream.generate(() -> random.nextFloat()).limit(fieldValueCount).toArray()))
.append(",");
}
}
}
if (builder.charAt(builder.length() - 1) == ',') {
builder.deleteCharAt(builder.length() - 1);
}
builder.append("}");
return new SourceToParse(UUIDs.randomBase64UUID(), new BytesArray(builder.toString()), XContentType.JSON);
}

private StringBuilder generateTextField(int fieldValueCountMax) {
int fieldValueCount = random.nextInt(fieldValueCountMax);
StringBuilder fieldValueBuilder = new StringBuilder();
fieldValueBuilder.append("[");
for (int j = 0; j < fieldValueCount - 1; j++) {
fieldValueBuilder.append("\"").append(randomString(6)).append("\"").append(",");
}
return fieldValueBuilder.append("\"").append(randomString(6)).append("\"").append("]");
}

private String randomString(int maxLength) {
var length = random.nextInt(maxLength);
var builder = new StringBuilder(length);
for (int i = 0; i < length; i++) {
builder.append((byte) (32 + random.nextInt(94)));
}
return builder.toString();
}

@SafeVarargs
@SuppressWarnings("varargs")
private <T> T randomFrom(T... items) {
return items[random.nextInt(items.length)];
}

@Benchmark
public List<LuceneDocument> benchmarkDynamicallyCreatedFields() throws Exception {
MapperService mapperService = MapperServiceFactory.create("{}");
for (int i = 0; i < 25; i++) {
DocumentMapper documentMapper = mapperService.documentMapper();
Mapping mapping = null;
if (documentMapper == null) {
documentMapper = DocumentMapper.createEmpty(mapperService);
mapping = documentMapper.mapping();
}
ParsedDocument doc = documentMapper.parse(randomFrom(sources));
if (mapping != null) {
doc.addDynamicMappingsUpdate(mapping);
}
if (doc.dynamicMappingsUpdate() != null) {
mapperService.merge(
"_doc",
new CompressedXContent(XContentHelper.toXContent(doc.dynamicMappingsUpdate(), XContentType.JSON, false)),
MapperService.MergeReason.MAPPING_UPDATE
);
}
}
return mapperService.documentMapper().parse(randomFrom(sources)).docs();
}
}
6 changes: 6 additions & 0 deletions build-tools-internal/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,10 @@ gradlePlugin {
id = 'elasticsearch.legacy-yaml-rest-test'
implementationClass = 'org.elasticsearch.gradle.internal.test.rest.LegacyYamlRestTestPlugin'
}
cacheTestFixtures {
id = 'elasticsearch.cache-test-fixtures'
implementationClass = 'org.elasticsearch.gradle.internal.packer.CacheTestFixtureResourcesPlugin'
}
yamlRestTest {
id = 'elasticsearch.internal-yaml-rest-test'
implementationClass = 'org.elasticsearch.gradle.internal.test.rest.InternalYamlRestTestPlugin'
Expand Down Expand Up @@ -288,6 +292,8 @@ dependencies {
api buildLibs.httpcore

compileOnly buildLibs.checkstyle
compileOnly buildLibs.reflections

runtimeOnly "org.elasticsearch.gradle:reaper:$version"
testImplementation buildLibs.checkstyle
testImplementation buildLibs.wiremock
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ private List<File> resolveProjectLogs(File projectDir) {
projectDirFiles.include("**/build/testclusters/**");
projectDirFiles.include("**/build/testrun/*/temp/**");
projectDirFiles.include("**/build/**/hs_err_pid*.log");
projectDirFiles.include("**/build/**/replay_pid*.log");
projectDirFiles.exclude("**/build/testclusters/**/data/**");
projectDirFiles.exclude("**/build/testclusters/**/distro/**");
projectDirFiles.exclude("**/build/testclusters/**/repo/**");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ public void apply(Project project) {
File testOutputDir = new File(test.getReports().getJunitXml().getOutputLocation().getAsFile().get(), "output");

ErrorReportingTestListener listener = new ErrorReportingTestListener(test, testOutputDir);
test.getInputs().property(DUMP_OUTPUT_ON_FAILURE_PROP_NAME, true);
test.getExtensions().getExtraProperties().set(DUMP_OUTPUT_ON_FAILURE_PROP_NAME, true);
test.getExtensions().add("errorReportingTestListener", listener);
test.addTestOutputListener(listener);
test.addTestListener(listener);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,6 @@ private static ListMultimap<Class<?>, String> createLegacyRestTestBasePluginUsag
map.put(LegacyRestTestBasePlugin.class, ":x-pack:plugin:ml:qa:native-multi-node-tests");
map.put(LegacyRestTestBasePlugin.class, ":x-pack:plugin:ml:qa:single-node-tests");
map.put(LegacyRestTestBasePlugin.class, ":x-pack:plugin:searchable-snapshots:qa:hdfs");
map.put(LegacyRestTestBasePlugin.class, ":x-pack:plugin:searchable-snapshots:qa:minio");
map.put(LegacyRestTestBasePlugin.class, ":x-pack:plugin:searchable-snapshots:qa:rest");
map.put(LegacyRestTestBasePlugin.class, ":x-pack:plugin:searchable-snapshots:qa:url");
map.put(LegacyRestTestBasePlugin.class, ":x-pack:plugin:security:qa:tls-basic");
Expand All @@ -150,7 +149,6 @@ private static ListMultimap<Class<?>, String> createLegacyRestTestBasePluginUsag
map.put(LegacyRestTestBasePlugin.class, ":x-pack:plugin:snapshot-based-recoveries:qa:fs");
map.put(LegacyRestTestBasePlugin.class, ":x-pack:plugin:snapshot-based-recoveries:qa:license-enforcing");
map.put(LegacyRestTestBasePlugin.class, ":x-pack:plugin:snapshot-repo-test-kit:qa:hdfs");
map.put(LegacyRestTestBasePlugin.class, ":x-pack:plugin:snapshot-repo-test-kit:qa:minio");
map.put(LegacyRestTestBasePlugin.class, ":x-pack:plugin:snapshot-repo-test-kit:qa:rest");
map.put(LegacyRestTestBasePlugin.class, ":x-pack:plugin:sql:qa:jdbc:multi-node");
map.put(LegacyRestTestBasePlugin.class, ":x-pack:plugin:sql:qa:jdbc:no-sql");
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/*
* 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.gradle.internal.packer;

import org.gradle.api.DefaultTask;
import org.gradle.api.InvalidUserDataException;
import org.gradle.api.file.ConfigurableFileCollection;
import org.gradle.api.file.FileCollection;
import org.gradle.api.tasks.CompileClasspath;
import org.gradle.api.tasks.TaskAction;
import org.gradle.workers.WorkAction;
import org.gradle.workers.WorkParameters;
import org.gradle.workers.WorkQueue;
import org.gradle.workers.WorkerExecutor;
import org.reflections.Reflections;
import org.reflections.scanners.SubTypesScanner;
import org.reflections.util.ClasspathHelper;
import org.reflections.util.ConfigurationBuilder;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.LinkedHashSet;
import java.util.Set;

import javax.inject.Inject;

public abstract class CacheCacheableTestFixtures extends DefaultTask {

@CompileClasspath
public abstract ConfigurableFileCollection getClasspath();

@Inject
public abstract WorkerExecutor getWorkerExecutor();

/**
* Executes the forbidden apis task.
*/
@TaskAction
public void checkForbidden() {
WorkQueue workQueue = getWorkerExecutor().classLoaderIsolation(spec -> spec.getClasspath().from(getClasspath()));
workQueue.submit(CacheTestFixtureWorkAction.class, params -> params.getClasspath().setFrom(getClasspath()));
}

interface Parameters extends WorkParameters {
ConfigurableFileCollection getClasspath();
}

abstract static class CacheTestFixtureWorkAction implements WorkAction<Parameters> {

@Inject
@SuppressWarnings("checkstyle:RedundantModifier")
public CacheTestFixtureWorkAction() {}

@Override
public void execute() {
final URLClassLoader urlLoader = createClassLoader(getParameters().getClasspath());
try {
Reflections reflections = new Reflections(
new ConfigurationBuilder().setUrls(ClasspathHelper.forPackage("org.elasticsearch.test.fixtures"))
.setScanners(new SubTypesScanner())
);

Class<?> ifClass = Class.forName("org.elasticsearch.test.fixtures.CacheableTestFixture");
Set<Class<?>> classes = (Set<Class<?>>) reflections.getSubTypesOf(ifClass);

for (Class<?> cacheableTestFixtureClazz : classes) {
Object o = cacheableTestFixtureClazz.getDeclaredConstructor().newInstance();
Method cacheMethod = cacheableTestFixtureClazz.getMethod("cache");
cacheMethod.invoke(o);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
// Close the classloader to free resources:
try {
if (urlLoader != null) urlLoader.close();
} catch (IOException ioe) {
// getLogger().warn("Cannot close classloader: ".concat(ioe.toString()));
}
}
}

private URLClassLoader createClassLoader(FileCollection classpath) {
if (classpath == null) {
throw new InvalidUserDataException("Missing 'classesDirs' or 'classpath' property.");
}

final Set<File> cpElements = new LinkedHashSet<>();
cpElements.addAll(classpath.getFiles());
final URL[] urls = new URL[cpElements.size()];
try {
int i = 0;
for (final File cpElement : cpElements) {
urls[i++] = cpElement.toURI().toURL();
}
assert i == urls.length;
} catch (MalformedURLException mfue) {
throw new InvalidUserDataException("Failed to build classpath URLs.", mfue);
}

return URLClassLoader.newInstance(urls, ClassLoader.getSystemClassLoader());
}

}
}
Loading

0 comments on commit 6abd99f

Please sign in to comment.