Skip to content

Commit

Permalink
Create gradle plugin for ES stable plugins
Browse files Browse the repository at this point in the history
New ES stable plugins when built should have a stable-plugin-descriptor.properties file
instead of plugin-descriptor.properties.
New plugins also do not use classname property in the plugin descriptor

relates elastic#88980
  • Loading branch information
pgomulka committed Sep 26, 2022
1 parent 84956c2 commit f135b63
Show file tree
Hide file tree
Showing 14 changed files with 509 additions and 294 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import java.util.concurrent.Callable;
import java.util.regex.Pattern;

import static org.elasticsearch.gradle.plugin.PluginBuildPlugin.EXPLODED_BUNDLE_CONFIG;
import static org.elasticsearch.gradle.plugin.BasePluginBuildPlugin.EXPLODED_BUNDLE_CONFIG;

public class ElasticsearchDistributionExtension {
private static final Pattern CONFIG_BIN_REGEX_PATTERN = Pattern.compile("([^\\/]+\\/)?(config|bin)\\/.*");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,8 @@

import javax.inject.Inject;

import static org.elasticsearch.gradle.plugin.PluginBuildPlugin.BUNDLE_PLUGIN_TASK_NAME;
import static org.elasticsearch.gradle.plugin.PluginBuildPlugin.EXPLODED_BUNDLE_PLUGIN_TASK_NAME;
import static org.elasticsearch.gradle.plugin.BasePluginBuildPlugin.BUNDLE_PLUGIN_TASK_NAME;
import static org.elasticsearch.gradle.plugin.BasePluginBuildPlugin.EXPLODED_BUNDLE_PLUGIN_TASK_NAME;

public class RestTestBasePlugin implements Plugin<Project> {
private static final String TESTS_REST_CLUSTER = "tests.rest.cluster";
Expand Down
4 changes: 4 additions & 0 deletions build-tools/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ gradlePlugin {
id = 'elasticsearch.esplugin'
implementationClass = 'org.elasticsearch.gradle.plugin.PluginBuildPlugin'
}
stableEsPlugin {
id = 'elasticsearch.stable_esplugin'
implementationClass = 'org.elasticsearch.gradle.plugin.StableBuildPlugin'
}
javaRestTest {
id = 'elasticsearch.java-rest-test'
implementationClass = 'org.elasticsearch.gradle.test.JavaRestTestPlugin'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ class PluginBuildPluginFuncTest extends AbstractGradleFuncTest {
}
dependencies {
consume project(path:':', configuration:'${PluginBuildPlugin.EXPLODED_BUNDLE_CONFIG}')
consume project(path:':', configuration:'${BasePluginBuildPlugin.EXPLODED_BUNDLE_CONFIG}')
}
tasks.register("resolveModule", Copy) {
Expand Down Expand Up @@ -127,6 +127,38 @@ class PluginBuildPluginFuncTest extends AbstractGradleFuncTest {
props.size() == 9
}

def "can build stable plugin properties"() {
given:
buildFile << """plugins {
id 'elasticsearch.stable_esplugin'
}
version = '1.2.3'
esplugin {
name = 'myplugin'
description = 'test plugin'
}
"""

when:
def result = gradleRunner(":pluginProperties").build()
def props = getPluginProperties("build/generated-descriptor/stable-plugin-descriptor.properties")

then:
result.task(":pluginProperties").outcome == TaskOutcome.SUCCESS
props.get("name") == "myplugin"
props.get("version") == "1.2.3"
props.get("description") == "test plugin"
props.get("modulename") == ""
props.get("java.version") == Integer.toString(Runtime.version().feature())
props.get("elasticsearch.version") == VersionProperties.elasticsearchVersion.toString()
props.get("extended.plugins") == ""
props.get("has.native.controller") == "false"
props.get("stable") == "true"
props.size() == 9
}

def "module name is inferred by plugin properties"() {
given:
buildFile << """plugins {
Expand Down Expand Up @@ -157,7 +189,11 @@ class PluginBuildPluginFuncTest extends AbstractGradleFuncTest {
}

Map<String, String> getPluginProperties() {
Path propsFile = file("build/generated-descriptor/plugin-descriptor.properties").toPath();
return getPluginProperties("build/generated-descriptor/plugin-descriptor.properties")
}

Map<String, String> getPluginProperties(String fileName) {
Path propsFile = file(fileName).toPath();
Properties rawProps = new Properties()
try (var inputStream = Files.newInputStream(propsFile)) {
rawProps.load(inputStream)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
/*
* 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.plugin;

import org.elasticsearch.gradle.Version;
import org.elasticsearch.gradle.VersionProperties;
import org.elasticsearch.gradle.dependencies.CompileOnlyResolvePlugin;
import org.elasticsearch.gradle.jarhell.JarHellPlugin;
import org.elasticsearch.gradle.test.GradleTestPolicySetupPlugin;
import org.elasticsearch.gradle.testclusters.ElasticsearchCluster;
import org.elasticsearch.gradle.testclusters.RunTask;
import org.elasticsearch.gradle.testclusters.TestClustersPlugin;
import org.elasticsearch.gradle.util.GradleUtils;
import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.Transformer;
import org.gradle.api.artifacts.type.ArtifactTypeDefinition;
import org.gradle.api.file.CopySpec;
import org.gradle.api.file.FileCollection;
import org.gradle.api.file.RegularFile;
import org.gradle.api.plugins.BasePlugin;
import org.gradle.api.plugins.JavaPlugin;
import org.gradle.api.plugins.JavaPluginExtension;
import org.gradle.api.provider.Provider;
import org.gradle.api.provider.ProviderFactory;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.SourceSetContainer;
import org.gradle.api.tasks.Sync;
import org.gradle.api.tasks.TaskProvider;
import org.gradle.api.tasks.bundling.Zip;

import java.io.File;
import java.util.Map;
import java.util.concurrent.Callable;

import javax.inject.Inject;

/**
* Common logic for building ES plugins.
* Requires plugin extension to be created before applying
*/
public class BasePluginBuildPlugin implements Plugin<Project> {

public static final String PLUGIN_EXTENSION_NAME = "esplugin";
public static final String BUNDLE_PLUGIN_TASK_NAME = "bundlePlugin";
public static final String EXPLODED_BUNDLE_PLUGIN_TASK_NAME = "explodedBundlePlugin";
public static final String EXPLODED_BUNDLE_CONFIG = "explodedBundleZip";

protected final ProviderFactory providerFactory;

@Inject
public BasePluginBuildPlugin(ProviderFactory providerFactory) {
this.providerFactory = providerFactory;
}

@Override
public void apply(final Project project) {
project.getPluginManager().apply(JavaPlugin.class);
project.getPluginManager().apply(TestClustersPlugin.class);
project.getPluginManager().apply(CompileOnlyResolvePlugin.class);
project.getPluginManager().apply(JarHellPlugin.class);
project.getPluginManager().apply(GradleTestPolicySetupPlugin.class);

var extension = (BasePluginPropertiesExtension) project.getExtensions().getByName(BasePluginBuildPlugin.PLUGIN_EXTENSION_NAME);

final var bundleTask = createBundleTasks(project, extension);
project.getConfigurations().getByName("default").extendsFrom(project.getConfigurations().getByName("runtimeClasspath"));

// allow running ES with this plugin in the foreground of a build
var testClusters = testClusters(project, TestClustersPlugin.EXTENSION_NAME);
var runCluster = testClusters.register("runTask", c -> {
// TODO: use explodedPlugin here for modules
if (GradleUtils.isModuleProject(project.getPath())) {
c.module(bundleTask.flatMap((Transformer<Provider<RegularFile>, Zip>) zip -> zip.getArchiveFile()));
} else {
c.plugin(bundleTask.flatMap((Transformer<Provider<RegularFile>, Zip>) zip -> zip.getArchiveFile()));
}
});

project.getTasks().register("run", RunTask.class, r -> {
r.useCluster(runCluster);
r.dependsOn(project.getTasks().named(BUNDLE_PLUGIN_TASK_NAME));
});
}

@SuppressWarnings("unchecked")
private static NamedDomainObjectContainer<ElasticsearchCluster> testClusters(Project project, String extensionName) {
return (NamedDomainObjectContainer<ElasticsearchCluster>) project.getExtensions().getByName(extensionName);
}

/**
* Adds bundle tasks which builds the dir and zip containing the plugin jars,
* metadata, properties, and packaging files
*/
private TaskProvider<Zip> createBundleTasks(final Project project, BasePluginPropertiesExtension extension) {
final var pluginMetadata = project.file("src/main/plugin-metadata");

final var buildProperties = project.getTasks().register("pluginProperties", GeneratePluginPropertiesTask.class, task -> {
task.getPluginName().set(providerFactory.provider(extension::getName));
task.getPluginDescription().set(providerFactory.provider(extension::getDescription));
task.getPluginVersion().set(providerFactory.provider(extension::getVersion));
task.getElasticsearchVersion().set(Version.fromString(VersionProperties.getElasticsearch()).toString());
var javaExtension = project.getExtensions().getByType(JavaPluginExtension.class);
task.getJavaVersion().set(providerFactory.provider(() -> javaExtension.getTargetCompatibility().toString()));
task.getExtendedPlugins().set(providerFactory.provider(extension::getExtendedPlugins));
task.getHasNativeController().set(providerFactory.provider(extension::isHasNativeController));
task.getRequiresKeystore().set(providerFactory.provider(extension::isRequiresKeystore));
task.getIsLicensed().set(providerFactory.provider(extension::isLicensed));

var mainSourceSet = project.getExtensions().getByType(SourceSetContainer.class).getByName(SourceSet.MAIN_SOURCE_SET_NAME);
FileCollection moduleInfoFile = mainSourceSet.getOutput().getAsFileTree().matching(p -> p.include("module-info.class"));
task.getModuleInfoFile().setFrom(moduleInfoFile);

});
// add the plugin properties and metadata to test resources, so unit tests can
// know about the plugin (used by test security code to statically initialize the plugin in unit tests)
var testSourceSet = project.getExtensions().getByType(SourceSetContainer.class).getByName("test");
Map<String, Object> map = Map.of("builtBy", buildProperties);
testSourceSet.getOutput().dir(map, new File(project.getBuildDir(), "generated-resources"));
testSourceSet.getResources().srcDir(pluginMetadata);

var bundleSpec = createBundleSpec(project, pluginMetadata, buildProperties);
extension.setBundleSpec(bundleSpec);
// create the actual bundle task, which zips up all the files for the plugin
final var bundle = project.getTasks().register("bundlePlugin", Zip.class, zip -> zip.with(bundleSpec));
project.getTasks().named(BasePlugin.ASSEMBLE_TASK_NAME).configure(task -> task.dependsOn(bundle));

// also make the zip available as a configuration (used when depending on this project)
var configuration = project.getConfigurations().create("zip");
configuration.getAttributes().attribute(ArtifactTypeDefinition.ARTIFACT_TYPE_ATTRIBUTE, ArtifactTypeDefinition.ZIP_TYPE);
project.getArtifacts().add("zip", bundle);

var explodedBundle = project.getTasks().register(EXPLODED_BUNDLE_PLUGIN_TASK_NAME, Sync.class, sync -> {
sync.with(bundleSpec);
sync.into(new File(project.getBuildDir(), "explodedBundle/" + extension.getName()));
});

// also make the exploded bundle available as a configuration (used when depending on this project)
var explodedBundleZip = project.getConfigurations().create(EXPLODED_BUNDLE_CONFIG);
explodedBundleZip.setCanBeResolved(false);
explodedBundleZip.setCanBeConsumed(true);
explodedBundleZip.getAttributes().attribute(ArtifactTypeDefinition.ARTIFACT_TYPE_ATTRIBUTE, ArtifactTypeDefinition.DIRECTORY_TYPE);
project.getArtifacts().add(EXPLODED_BUNDLE_CONFIG, explodedBundle);
return bundle;
}

private static CopySpec createBundleSpec(
Project project,
File pluginMetadata,
TaskProvider<GeneratePluginPropertiesTask> buildProperties
) {
var bundleSpec = project.copySpec();
bundleSpec.from(buildProperties);
bundleSpec.from(pluginMetadata, copySpec -> {
// metadata (eg custom security policy)
// the codebases properties file is only for tests and not needed in production
copySpec.exclude("plugin-security.codebases");
});
bundleSpec.from(
(Callable<TaskProvider<Task>>) () -> project.getPluginManager().hasPlugin("com.github.johnrengelman.shadow")
? project.getTasks().named("shadowJar")
: project.getTasks().named("jar")
);
bundleSpec.from(
project.getConfigurations()
.getByName("runtimeClasspath")
.minus(project.getConfigurations().getByName(CompileOnlyResolvePlugin.RESOLVEABLE_COMPILE_ONLY_CONFIGURATION_NAME))
);

// extra files for the plugin to go into the zip
bundleSpec.from("src/main/packaging");// TODO: move all config/bin/_size/etc into packaging
bundleSpec.from("src/main", copySpec -> {
copySpec.include("config/**");
copySpec.include("bin/**");
});
return bundleSpec;
}
}
Loading

0 comments on commit f135b63

Please sign in to comment.