Simplify jdk downloads via artifact transforms (#60713) (#60803)

* Simplify jdk downloads via artifact transforms

This reworks the jdk download plugin to use artifact transforms.
That allows us to simplify the jdk download plugin by a lot. The
benefits of using artifact transforms are:

- they transform an artifact to an upacked folder on the fly as part
of the dependenc resolution allowing us to remove all the custom created unpack tasks
and configurations

- Artifact transforms support gradle build cache. Requesting a jdk folder on a clean machine
will likely be resolved from the build cache

- The manual mingling about not extracting jdks multiple times by all jdks channeling through
root project configurations can be removed as they support up-to-date checking and build cache
which will ensure these archives are only resolved once per build at max.

Also the test coverage has been ported to Spock that supports data driven testing. This porting
includes an introduction to a wiremock fixture that can be used later on for mocking repository
urls in other integration tests

* Simplify artifact transform registration

* Change jdk finalization and repository setup

Jdk finalization is now done via `configuration.defaultDependencies`.
This has two benefits:
- we only configure and finalize the JDKs we actually use during the build
- afterEvaluate hooks are problematic in combination with task avoidance api.
Relying on task avoidance api in Gradle moves more configuration logic into the materialization
of tasks which is, with task avoidance api, is done ideally during the task graph calculation.
Anything created (e.g. jdks) created late in this task graph calculation would never be finalized
via afterEvaluate hooks as this has been fired before already with the jdk not there yet.

Furthermore we now only configure repositories in the projects where the jdk is declared
(aka the jdk-download plugin is applied) and only if the jdk is actually requested during the build.

* Fix javadoc

* Fix jdk download repo content filtering

* Minor cleanup

* Apply review feedback and cleanup
This commit is contained in:
Rene Groeschke 2020-08-06 12:34:20 +02:00 committed by GitHub
parent 9163c9ce36
commit 91e956e96a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
16 changed files with 652 additions and 743 deletions

View File

@ -0,0 +1,237 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.gradle
import com.github.tomakehurst.wiremock.WireMockServer
import org.elasticsearch.gradle.fixtures.AbstractGradleFuncTest
import org.elasticsearch.gradle.fixtures.WiremockFixture
import org.elasticsearch.gradle.transform.SymbolicLinkPreservingUntarTransform
import org.elasticsearch.gradle.transform.UnzipTransform
import spock.lang.Unroll
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.util.regex.Matcher
import java.util.regex.Pattern
import static org.elasticsearch.gradle.JdkDownloadPlugin.VENDOR_ADOPTOPENJDK
import static org.elasticsearch.gradle.JdkDownloadPlugin.VENDOR_OPENJDK
class JdkDownloadPluginFuncTest extends AbstractGradleFuncTest {
private static final String OPENJDK_VERSION_OLD = "1+99"
private static final String ADOPT_JDK_VERSION = "12.0.2+10"
private static final String OPEN_JDK_VERSION = "12.0.1+99@123456789123456789123456789abcde"
private static final Pattern JDK_HOME_LOGLINE = Pattern.compile("JDK HOME: (.*)");
@Unroll
def "jdk #jdkVendor for #platform#suffix are downloaded and extracted"() {
given:
def mockRepoUrl = urlPath(jdkVendor, jdkVersion, platform);
def mockedContent = filebytes(jdkVendor, platform)
buildFile.text = """
plugins {
id 'elasticsearch.jdk-download'
}
jdks {
myJdk {
vendor = '$jdkVendor'
version = '$jdkVersion'
platform = "$platform"
architecture = "x64"
}
}
tasks.register("getJdk") {
dependsOn jdks.myJdk
doLast {
println "JDK HOME: " + jdks.myJdk
}
}
"""
when:
def result = WiremockFixture.withWireMock(mockRepoUrl, mockedContent) { server ->
buildFile << repositoryMockSetup(server, jdkVendor, jdkVersion)
gradleRunner("getJdk").build()
}
then:
assertExtraction(result.output, expectedJavaBin);
where:
platform | jdkVendor | jdkVersion | expectedJavaBin | suffix
"linux" | VENDOR_ADOPTOPENJDK | ADOPT_JDK_VERSION | "bin/java" | ""
"linux" | VENDOR_OPENJDK | OPEN_JDK_VERSION | "bin/java" | ""
"linux" | VENDOR_OPENJDK | OPENJDK_VERSION_OLD | "bin/java" | "(old version)"
"windows" | VENDOR_ADOPTOPENJDK | ADOPT_JDK_VERSION | "bin/java" | ""
"windows" | VENDOR_OPENJDK | OPEN_JDK_VERSION | "bin/java" | ""
"windows" | VENDOR_OPENJDK | OPENJDK_VERSION_OLD | "bin/java" | "(old version)"
"darwin" | VENDOR_ADOPTOPENJDK | ADOPT_JDK_VERSION | "Contents/Home/bin/java" | ""
"darwin" | VENDOR_OPENJDK | OPEN_JDK_VERSION | "Contents/Home/bin/java" | ""
"darwin" | VENDOR_OPENJDK | OPENJDK_VERSION_OLD | "Contents/Home/bin/java" | "(old version)"
}
def "transforms are reused across projects"() {
given:
def mockRepoUrl = urlPath(jdkVendor, jdkVersion, platform)
def mockedContent = filebytes(jdkVendor, platform)
10.times {
settingsFile << """
include ':sub-$it'
"""
}
buildFile.text = """
plugins {
id 'elasticsearch.jdk-download' apply false
}
subprojects {
apply plugin: 'elasticsearch.jdk-download'
jdks {
myJdk {
vendor = '$jdkVendor'
version = '$jdkVersion'
platform = "$platform"
architecture = "x64"
}
}
tasks.register("getJdk") {
dependsOn jdks.myJdk
doLast {
println "JDK HOME: " + jdks.myJdk
}
}
}
"""
when:
def result = WiremockFixture.withWireMock(mockRepoUrl, mockedContent) { server ->
buildFile << repositoryMockSetup(server, jdkVendor, jdkVersion)
gradleRunner('getJdk', '-i', '-g', testProjectDir.newFolder().toString()).build()
}
then:
result.tasks.size() == 10
result.output.count("Unpacking linux-12.0.2-x64.tar.gz using SymbolicLinkPreservingUntarTransform.") == 1
where:
platform | jdkVendor | jdkVersion | expectedJavaBin
"linux" | VENDOR_ADOPTOPENJDK | ADOPT_JDK_VERSION | "bin/java"
}
@Unroll
def "transforms of type #transformType are kept across builds"() {
given:
def mockRepoUrl = urlPath(VENDOR_ADOPTOPENJDK, ADOPT_JDK_VERSION, platform)
def mockedContent = filebytes(VENDOR_ADOPTOPENJDK, platform)
buildFile.text = """
plugins {
id 'elasticsearch.jdk-download'
}
apply plugin: 'elasticsearch.jdk-download'
jdks {
myJdk {
vendor = '$VENDOR_ADOPTOPENJDK'
version = '$ADOPT_JDK_VERSION'
platform = "$platform"
architecture = "x64"
}
}
tasks.register("getJdk") {
dependsOn jdks.myJdk
doLast {
println "JDK HOME: " + jdks.myJdk
}
}
"""
when:
def result = WiremockFixture.withWireMock(mockRepoUrl, mockedContent) { server ->
buildFile << repositoryMockSetup(server, VENDOR_ADOPTOPENJDK, ADOPT_JDK_VERSION)
def commonGradleUserHome = testProjectDir.newFolder().toString()
// initial run
gradleRunner('getJdk', '-g', commonGradleUserHome).build()
// run against up-to-date transformations
gradleRunner('getJdk', '-i', '-g', commonGradleUserHome).build()
}
then:
assertOutputContains(result.output, "Skipping $transformType")
where:
platform | transformType
"linux" | SymbolicLinkPreservingUntarTransform.class.simpleName
"windows" | UnzipTransform.class.simpleName
}
static boolean assertExtraction(String output, String javaBin) {
Matcher matcher = JDK_HOME_LOGLINE.matcher(output);
assert matcher.find() == true;
String jdkHome = matcher.group(1);
Path javaPath = Paths.get(jdkHome, javaBin);
assert Files.exists(javaPath) == true;
true
}
private static String urlPath(final String vendor, final String version, final String platform) {
if (vendor.equals(VENDOR_ADOPTOPENJDK)) {
final String module = platform.equals("darwin") ? "mac" : platform;
return "/jdk-12.0.2+10/" + module + "/x64/jdk/hotspot/normal/adoptopenjdk";
} else if (vendor.equals(VENDOR_OPENJDK)) {
final String effectivePlatform = platform.equals("darwin") ? "osx" : platform;
final boolean isOld = version.equals(OPENJDK_VERSION_OLD);
final String versionPath = isOld ? "jdk1/99" : "jdk12.0.1/123456789123456789123456789abcde/99";
final String filename = "openjdk-" + (isOld ? "1" : "12.0.1") + "_" + effectivePlatform + "-x64_bin." + extension(platform);
return "/java/GA/" + versionPath + "/GPL/" + filename;
}
}
private static byte[] filebytes(final String vendor, final String platform) throws IOException {
final String effectivePlatform = platform.equals("darwin") ? "osx" : platform;
if (vendor.equals(VENDOR_ADOPTOPENJDK)) {
return JdkDownloadPluginFuncTest.class.getResourceAsStream("fake_adoptopenjdk_" + effectivePlatform + "." + extension(platform)).getBytes()
} else if (vendor.equals(VENDOR_OPENJDK)) {
JdkDownloadPluginFuncTest.class.getResourceAsStream("fake_openjdk_" + effectivePlatform + "." + extension(platform)).getBytes()
}
}
private static String extension(String platform) {
platform.equals("windows") ? "zip" : "tar.gz";
}
private static String repositoryMockSetup(WireMockServer server, String jdkVendor, String jdkVersion) {
"""allprojects{ p ->
// wire the jdk repo to wiremock
p.repositories.all { repo ->
if(repo.name == "jdk_repo_${jdkVendor}_${jdkVersion}") {
repo.setUrl('${server.baseUrl()}')
}
}
}"""
}
}

View File

@ -36,7 +36,7 @@ abstract class AbstractGradleFuncTest extends Specification{
def setup() {
settingsFile = testProjectDir.newFile('settings.gradle')
settingsFile << "rootProject.name = 'hello-world'"
settingsFile << "rootProject.name = 'hello-world'\n"
buildFile = testProjectDir.newFile('build.gradle')
}

View File

@ -0,0 +1,70 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.gradle.fixtures
import com.github.tomakehurst.wiremock.WireMockServer
import org.gradle.testkit.runner.BuildResult
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse
import static com.github.tomakehurst.wiremock.client.WireMock.get
import static com.github.tomakehurst.wiremock.client.WireMock.head
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo
/**
* A test fixture that allows running testkit builds with wiremock
* */
class WiremockFixture {
/**
* the buildRunClosure has passed an instance of WireMockServer that can be used to access e.g. the baseUrl of
* the configured server:
*
* <pre>
* WiremockFixture.withWireMock(mockRepoUrl, mockedContent) { server ->
* buildFile << """
* // wire a gradle repository with wiremock
* repositories {
* maven {
* url = '${server.baseUrl()}'
* }
* }
* }
* gadleRunner('myTask').build()
* </pre>
* */
static BuildResult withWireMock(String expectedUrl, byte[] expectedContent, Closure<BuildResult> buildRunClosure) {
WireMockServer wireMock = new WireMockServer(0);
try {
wireMock.stubFor(head(urlEqualTo(expectedUrl)).willReturn(aResponse().withStatus(200)));
wireMock.stubFor(
get(urlEqualTo(expectedUrl)).willReturn(aResponse().withStatus(200).withBody(expectedContent))
)
wireMock.start();
return buildRunClosure.call(wireMock);
} catch (Exception e) {
// for debugging
System.err.println("missed requests: " + wireMock.findUnmatchedRequests().getRequests());
throw e;
} finally {
wireMock.stop();
}
}
}

View File

@ -1,50 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.gradle;
import java.io.IOException;
import java.io.InputStream;
public class AdoptOpenJdkDownloadPluginIT extends JdkDownloadPluginIT {
@Override
public String jdkVersion() {
return "12.0.2+10";
}
@Override
public String jdkVendor() {
return "adoptopenjdk";
}
@Override
protected String urlPath(final String version, final String platform, final String extension) {
final String module = platform.equals("osx") ? "mac" : platform;
return "/jdk-12.0.2+10/" + module + "/x64/jdk/hotspot/normal/adoptopenjdk";
}
@Override
protected byte[] filebytes(final String platform, final String extension) throws IOException {
try (InputStream stream = JdkDownloadPluginIT.class.getResourceAsStream("fake_adoptopenjdk_" + platform + "." + extension)) {
return stream.readAllBytes();
}
}
}

View File

@ -1,119 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.gradle;
import com.github.tomakehurst.wiremock.WireMockServer;
import org.elasticsearch.gradle.test.GradleIntegrationTestCase;
import org.gradle.testkit.runner.BuildResult;
import org.gradle.testkit.runner.GradleRunner;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.client.WireMock.get;
import static com.github.tomakehurst.wiremock.client.WireMock.head;
import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo;
import static org.hamcrest.CoreMatchers.equalTo;
public abstract class JdkDownloadPluginIT extends GradleIntegrationTestCase {
private static final Pattern JDK_HOME_LOGLINE = Pattern.compile("JDK HOME: (.*)");
private static final Pattern NUM_CONFIGS_LOGLINE = Pattern.compile("NUM CONFIGS: (.*)");
protected abstract String jdkVersion();
protected abstract String jdkVendor();
public final void testLinuxExtraction() throws IOException {
assertExtraction("getLinuxJdk", "linux", "bin/java", jdkVendor(), jdkVersion());
}
public final void testDarwinExtraction() throws IOException {
assertExtraction("getDarwinJdk", "osx", "Contents/Home/bin/java", jdkVendor(), jdkVersion());
}
public final void testWindowsExtraction() throws IOException {
assertExtraction("getWindowsJdk", "windows", "bin/java", jdkVendor(), jdkVersion());
}
public final void testCrossProjectReuse() throws IOException {
runBuild("numConfigurations", "linux", result -> {
Matcher matcher = NUM_CONFIGS_LOGLINE.matcher(result.getOutput());
assertTrue("could not find num configs in output: " + result.getOutput(), matcher.find());
assertThat(Integer.parseInt(matcher.group(1)), equalTo(6)); // 3 import configs, 3 export configs
}, jdkVendor(), jdkVersion());
}
protected void assertExtraction(String taskname, String platform, String javaBin, String vendor, String version) throws IOException {
runBuild(taskname, platform, result -> {
Matcher matcher = JDK_HOME_LOGLINE.matcher(result.getOutput());
assertTrue("could not find jdk home in output: " + result.getOutput(), matcher.find());
String jdkHome = matcher.group(1);
Path javaPath = Paths.get(jdkHome, javaBin);
assertTrue(javaPath.toString(), Files.exists(javaPath));
}, vendor, version);
}
protected abstract String urlPath(String version, String platform, String extension);
protected abstract byte[] filebytes(String platform, String extension) throws IOException;
private void runBuild(String taskname, String platform, Consumer<BuildResult> assertions, String vendor, String version)
throws IOException {
WireMockServer wireMock = new WireMockServer(0);
try {
String extension = platform.equals("windows") ? "zip" : "tar.gz";
wireMock.stubFor(head(urlEqualTo(urlPath(version, platform, extension))).willReturn(aResponse().withStatus(200)));
wireMock.stubFor(
get(urlEqualTo(urlPath(version, platform, extension))).willReturn(
aResponse().withStatus(200).withBody(filebytes(platform, extension))
)
);
wireMock.start();
GradleRunner runner = GradleRunner.create()
.withProjectDir(getProjectDir("jdk-download"))
.withArguments(
taskname,
"-Dtests.jdk_vendor=" + vendor,
"-Dtests.jdk_version=" + version,
"-Dtests.jdk_repo=" + wireMock.baseUrl(),
"-i"
)
.withPluginClasspath();
BuildResult result = runner.build();
assertions.accept(result);
} catch (Exception e) {
// for debugging
System.err.println("missed requests: " + wireMock.findUnmatchedRequests().getRequests());
throw e;
} finally {
wireMock.stop();
}
}
}

View File

@ -1,68 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.gradle;
import java.io.IOException;
import java.io.InputStream;
public class OpenJdkDownloadPluginIT extends JdkDownloadPluginIT {
public String oldJdkVersion() {
return "1+99";
}
@Override
public String jdkVersion() {
return "12.0.1+99@123456789123456789123456789abcde";
}
@Override
protected String jdkVendor() {
return "openjdk";
}
@Override
protected String urlPath(final String version, final String platform, final String extension) {
final boolean isOld = version.equals(oldJdkVersion());
final String versionPath = isOld ? "jdk1/99" : "jdk12.0.1/123456789123456789123456789abcde/99";
final String filename = "openjdk-" + (isOld ? "1" : "12.0.1") + "_" + platform + "-x64_bin." + extension;
return "/java/GA/" + versionPath + "/GPL/" + filename;
}
@Override
protected byte[] filebytes(final String platform, final String extension) throws IOException {
try (InputStream stream = JdkDownloadPluginIT.class.getResourceAsStream("fake_openjdk_" + platform + "." + extension)) {
return stream.readAllBytes();
}
}
public final void testLinuxExtractionOldVersion() throws IOException {
assertExtraction("getLinuxJdk", "linux", "bin/java", jdkVendor(), oldJdkVersion());
}
public final void testDarwinExtractionOldVersion() throws IOException {
assertExtraction("getDarwinJdk", "osx", "Contents/Home/bin/java", jdkVendor(), oldJdkVersion());
}
public final void testWindowsExtractionOldVersion() throws IOException {
assertExtraction("getWindowsJdk", "windows", "bin/java", jdkVendor(), oldJdkVersion());
}
}

View File

@ -19,68 +19,116 @@
package org.elasticsearch.gradle;
import org.elasticsearch.gradle.tar.SymbolicLinkPreservingUntarTask;
import org.gradle.api.Action;
import org.elasticsearch.gradle.transform.SymbolicLinkPreservingUntarTransform;
import org.elasticsearch.gradle.transform.UnzipTransform;
import org.gradle.api.GradleException;
import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ConfigurationContainer;
import org.gradle.api.artifacts.dsl.DependencyHandler;
import org.gradle.api.artifacts.dsl.RepositoryHandler;
import org.gradle.api.artifacts.repositories.IvyArtifactRepository;
import org.gradle.api.file.CopySpec;
import org.gradle.api.file.Directory;
import org.gradle.api.file.FileTree;
import org.gradle.api.file.RelativePath;
import org.gradle.api.provider.Provider;
import org.gradle.api.tasks.Copy;
import org.gradle.api.tasks.TaskProvider;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.stream.StreamSupport;
import static org.elasticsearch.gradle.util.GradleUtils.findByName;
import static org.elasticsearch.gradle.util.GradleUtils.maybeCreate;
import org.gradle.api.artifacts.type.ArtifactTypeDefinition;
import org.gradle.api.internal.artifacts.ArtifactAttributes;
public class JdkDownloadPlugin implements Plugin<Project> {
public static final String VENDOR_ADOPTOPENJDK = "adoptopenjdk";
public static final String VENDOR_OPENJDK = "openjdk";
private static final String REPO_NAME_PREFIX = "jdk_repo_";
private static final String EXTENSION_NAME = "jdks";
@Override
public void apply(Project project) {
NamedDomainObjectContainer<Jdk> jdksContainer = project.container(
Jdk.class,
name -> new Jdk(name, project.getConfigurations().create("jdk_" + name), project.getObjects())
);
project.getExtensions().add(EXTENSION_NAME, jdksContainer);
project.afterEvaluate(p -> {
for (Jdk jdk : jdksContainer) {
jdk.finalizeValues();
// depend on the jdk directory "artifact" from the root project
DependencyHandler dependencies = project.getDependencies();
Map<String, Object> depConfig = new HashMap<>();
depConfig.put("path", ":"); // root project
depConfig.put(
"configuration",
configName("extracted_jdk", jdk.getVendor(), jdk.getVersion(), jdk.getPlatform(), jdk.getArchitecture())
);
project.getDependencies().add(jdk.getConfigurationName(), dependencies.project(depConfig));
// ensure a root level jdk download task exists
setupRootJdkDownload(project.getRootProject(), jdk);
}
project.getDependencies().getArtifactTypes().maybeCreate(ArtifactTypeDefinition.ZIP_TYPE);
project.getDependencies().registerTransform(UnzipTransform.class, transformSpec -> {
transformSpec.getFrom().attribute(ArtifactAttributes.ARTIFACT_FORMAT, ArtifactTypeDefinition.ZIP_TYPE);
transformSpec.getTo().attribute(ArtifactAttributes.ARTIFACT_FORMAT, ArtifactTypeDefinition.DIRECTORY_TYPE);
});
ArtifactTypeDefinition tarArtifactTypeDefinition = project.getDependencies().getArtifactTypes().maybeCreate("tar.gz");
project.getDependencies().registerTransform(SymbolicLinkPreservingUntarTransform.class, transformSpec -> {
transformSpec.getFrom().attribute(ArtifactAttributes.ARTIFACT_FORMAT, tarArtifactTypeDefinition.getName());
transformSpec.getTo().attribute(ArtifactAttributes.ARTIFACT_FORMAT, ArtifactTypeDefinition.DIRECTORY_TYPE);
});
NamedDomainObjectContainer<Jdk> jdksContainer = project.container(Jdk.class, name -> {
Configuration configuration = project.getConfigurations().create("jdk_" + name);
configuration.getAttributes().attribute(ArtifactAttributes.ARTIFACT_FORMAT, ArtifactTypeDefinition.DIRECTORY_TYPE);
Jdk jdk = new Jdk(name, configuration, project.getObjects());
configuration.defaultDependencies(dependencies -> {
jdk.finalizeValues();
setupRepository(project, jdk);
dependencies.add(project.getDependencies().create(dependencyNotation(jdk)));
});
return jdk;
});
project.getExtensions().add(EXTENSION_NAME, jdksContainer);
}
private void setupRepository(Project project, Jdk jdk) {
RepositoryHandler repositories = project.getRepositories();
/*
* Define the appropriate repository for the given JDK vendor and version
*
* For Oracle/OpenJDK/AdoptOpenJDK we define a repository per-version.
*/
String repoName = REPO_NAME_PREFIX + jdk.getVendor() + "_" + jdk.getVersion();
String repoUrl;
String artifactPattern;
if (jdk.getVendor().equals(VENDOR_ADOPTOPENJDK)) {
repoUrl = "https://api.adoptopenjdk.net/v3/binary/version/";
if (jdk.getMajor().equals("8")) {
// legacy pattern for JDK 8
artifactPattern = "jdk"
+ jdk.getBaseVersion()
+ "-"
+ jdk.getBuild()
+ "/[module]/[classifier]/jdk/hotspot/normal/adoptopenjdk";
} else {
// current pattern since JDK 9
artifactPattern = "jdk-"
+ jdk.getBaseVersion()
+ "+"
+ jdk.getBuild()
+ "/[module]/[classifier]/jdk/hotspot/normal/adoptopenjdk";
}
} else if (jdk.getVendor().equals(VENDOR_OPENJDK)) {
repoUrl = "https://download.oracle.com";
if (jdk.getHash() != null) {
// current pattern since 12.0.1
artifactPattern = "java/GA/jdk"
+ jdk.getBaseVersion()
+ "/"
+ jdk.getHash()
+ "/"
+ jdk.getBuild()
+ "/GPL/openjdk-[revision]_[module]-[classifier]_bin.[ext]";
} else {
// simpler legacy pattern from JDK 9 to JDK 12 that we are advocating to Oracle to bring back
artifactPattern = "java/GA/jdk"
+ jdk.getMajor()
+ "/"
+ jdk.getBuild()
+ "/GPL/openjdk-[revision]_[module]-[classifier]_bin.[ext]";
}
} else {
throw new GradleException("Unknown JDK vendor [" + jdk.getVendor() + "]");
}
// Define the repository if we haven't already
if (repositories.findByName(repoName) == null) {
repositories.ivy(repo -> {
repo.setName(repoName);
repo.setUrl(repoUrl);
repo.metadataSources(IvyArtifactRepository.MetadataSources::artifact);
repo.patternLayout(layout -> layout.artifact(artifactPattern));
repo.content(repositoryContentDescriptor -> repositoryContentDescriptor.includeGroup(groupName(jdk)));
});
}
}
@SuppressWarnings("unchecked")
@ -88,192 +136,9 @@ public class JdkDownloadPlugin implements Plugin<Project> {
return (NamedDomainObjectContainer<Jdk>) project.getExtensions().getByName(EXTENSION_NAME);
}
private static void setupRootJdkDownload(Project rootProject, Jdk jdk) {
String extractTaskName = String.format(
Locale.ROOT,
"extract-%s-%s-jdk-%s-%s",
jdk.getPlatform(),
jdk.getArchitecture(),
jdk.getVendor(),
jdk.getVersion()
);
// Skip setup if we've already configured a JDK for this platform, vendor and version
if (findByName(rootProject.getTasks(), extractTaskName) == null) {
RepositoryHandler repositories = rootProject.getRepositories();
/*
* Define the appropriate repository for the given JDK vendor and version
*
* For Oracle/OpenJDK/AdoptOpenJDK we define a repository per-version.
*/
String repoName = REPO_NAME_PREFIX + jdk.getVendor() + "_" + jdk.getVersion();
String repoUrl;
String artifactPattern;
if (jdk.getVendor().equals("adoptopenjdk")) {
repoUrl = "https://api.adoptopenjdk.net/v3/binary/version/";
if (jdk.getMajor().equals("8")) {
// legacy pattern for JDK 8
artifactPattern = "jdk"
+ jdk.getBaseVersion()
+ "-"
+ jdk.getBuild()
+ "/[module]/[classifier]/jdk/hotspot/normal/adoptopenjdk";
} else {
// current pattern since JDK 9
artifactPattern = "jdk-"
+ jdk.getBaseVersion()
+ "+"
+ jdk.getBuild()
+ "/[module]/[classifier]/jdk/hotspot/normal/adoptopenjdk";
}
} else if (jdk.getVendor().equals("openjdk")) {
repoUrl = "https://download.oracle.com";
if (jdk.getHash() != null) {
// current pattern since 12.0.1
artifactPattern = "java/GA/jdk"
+ jdk.getBaseVersion()
+ "/"
+ jdk.getHash()
+ "/"
+ jdk.getBuild()
+ "/GPL/openjdk-[revision]_[module]-[classifier]_bin.[ext]";
} else {
// simpler legacy pattern from JDK 9 to JDK 12 that we are advocating to Oracle to bring back
artifactPattern = "java/GA/jdk"
+ jdk.getMajor()
+ "/"
+ jdk.getBuild()
+ "/GPL/openjdk-[revision]_[module]-[classifier]_bin.[ext]";
}
} else {
throw new GradleException("Unknown JDK vendor [" + jdk.getVendor() + "]");
}
// Define the repository if we haven't already
if (repositories.findByName(repoName) == null) {
IvyArtifactRepository ivyRepo = repositories.ivy(repo -> {
repo.setName(repoName);
repo.setUrl(repoUrl);
repo.metadataSources(IvyArtifactRepository.MetadataSources::artifact);
repo.patternLayout(layout -> layout.artifact(artifactPattern));
});
repositories.exclusiveContent(exclusiveContentRepository -> {
exclusiveContentRepository.forRepositories(ivyRepo);
exclusiveContentRepository.filter(config -> config.includeGroup(groupName(jdk)));
});
}
// Declare a configuration and dependency from which to download the remote JDK
final ConfigurationContainer configurations = rootProject.getConfigurations();
String downloadConfigName = configName(jdk.getVendor(), jdk.getVersion(), jdk.getPlatform(), jdk.getArchitecture());
Configuration downloadConfiguration = maybeCreate(configurations, downloadConfigName);
rootProject.getDependencies().add(downloadConfigName, dependencyNotation(jdk));
// Create JDK extract task
final Provider<Directory> extractPath = rootProject.getLayout()
.getBuildDirectory()
.dir("jdks/" + jdk.getVendor() + "-" + jdk.getBaseVersion() + "_" + jdk.getPlatform() + "_" + jdk.getArchitecture());
TaskProvider<?> extractTask = createExtractTask(
extractTaskName,
rootProject,
jdk.getPlatform(),
downloadConfiguration,
extractPath
);
// Declare a configuration for the extracted JDK archive
String artifactConfigName = configName(
"extracted_jdk",
jdk.getVendor(),
jdk.getVersion(),
jdk.getPlatform(),
jdk.getArchitecture()
);
maybeCreate(configurations, artifactConfigName);
rootProject.getArtifacts().add(artifactConfigName, extractPath, artifact -> artifact.builtBy(extractTask));
}
}
private static TaskProvider<?> createExtractTask(
String taskName,
Project rootProject,
String platform,
Configuration downloadConfiguration,
Provider<Directory> extractPath
) {
if (platform.equals("windows")) {
final Callable<FileTree> fileGetter = () -> rootProject.zipTree(downloadConfiguration.getSingleFile());
// TODO: look into doing this as an artifact transform, which are cacheable starting in gradle 5.3
Action<CopySpec> removeRootDir = copy -> {
// remove extra unnecessary directory levels
copy.eachFile(details -> {
Path newPathSegments = trimArchiveExtractPath(details.getRelativePath().getPathString());
String[] segments = StreamSupport.stream(newPathSegments.spliterator(), false)
.map(Path::toString)
.toArray(String[]::new);
details.setRelativePath(new RelativePath(true, segments));
});
copy.setIncludeEmptyDirs(false);
};
return rootProject.getTasks().register(taskName, Copy.class, copyTask -> {
copyTask.doFirst(new Action<Task>() {
@Override
public void execute(Task t) {
rootProject.delete(extractPath);
}
});
copyTask.into(extractPath);
copyTask.from(fileGetter, removeRootDir);
});
} else {
/*
* Gradle TarFileTree does not resolve symlinks, so we have to manually extract and preserve the symlinks.
* cf. https://github.com/gradle/gradle/issues/3982 and https://discuss.gradle.org/t/tar-and-untar-losing-symbolic-links/2039
*/
return rootProject.getTasks().register(taskName, SymbolicLinkPreservingUntarTask.class, task -> {
task.getTarFile().fileProvider(rootProject.provider(downloadConfiguration::getSingleFile));
task.getExtractPath().set(extractPath);
task.setTransform(JdkDownloadPlugin::trimArchiveExtractPath);
});
}
}
/*
* We want to remove up to the and including the jdk-.* relative paths. That is a JDK archive is structured as:
* jdk-12.0.1/
* jdk-12.0.1/Contents
* ...
*
* and we want to remove the leading jdk-12.0.1. Note however that there could also be a leading ./ as in
* ./
* ./jdk-12.0.1/
* ./jdk-12.0.1/Contents
*
* so we account for this and search the path components until we find the jdk-12.0.1, and strip the leading components.
*/
private static Path trimArchiveExtractPath(String relativePath) {
final Path entryName = Paths.get(relativePath);
int index = 0;
for (; index < entryName.getNameCount(); index++) {
if (entryName.getName(index).toString().matches("jdk-?\\d.*")) {
break;
}
}
if (index + 1 >= entryName.getNameCount()) {
// this happens on the top-level directories in the archive, which we are removing
return null;
}
// finally remove the top-level directories from the output path
return entryName.subpath(index + 1, entryName.getNameCount());
}
private static String dependencyNotation(Jdk jdk) {
String platformDep = jdk.getPlatform().equals("darwin") || jdk.getPlatform().equals("osx")
? (jdk.getVendor().equals("adoptopenjdk") ? "mac" : "osx")
? (jdk.getVendor().equals(VENDOR_ADOPTOPENJDK) ? "mac" : "osx")
: jdk.getPlatform();
String extension = jdk.getPlatform().equals("windows") ? "zip" : "tar.gz";
@ -284,7 +149,4 @@ public class JdkDownloadPlugin implements Plugin<Project> {
return jdk.getVendor() + "_" + jdk.getMajor();
}
private static String configName(String... parts) {
return String.join("_", parts);
}
}

View File

@ -1,170 +0,0 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.gradle.tar;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.gradle.api.DefaultTask;
import org.gradle.api.GradleException;
import org.gradle.api.file.DirectoryProperty;
import org.gradle.api.file.RegularFileProperty;
import org.gradle.api.model.ObjectFactory;
import org.gradle.api.tasks.InputFile;
import org.gradle.api.tasks.Internal;
import org.gradle.api.tasks.OutputDirectory;
import org.gradle.api.tasks.TaskAction;
import javax.inject.Inject;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
import java.util.function.Function;
/**
* A custom task that explodes a tar archive that preserves symbolic links.
*
* This task is necessary because the built-in task {@link org.gradle.api.internal.file.archive.TarFileTree} does not preserve symbolic
* links.
*/
public class SymbolicLinkPreservingUntarTask extends DefaultTask {
private final RegularFileProperty tarFile;
@InputFile
public RegularFileProperty getTarFile() {
return tarFile;
}
private final DirectoryProperty extractPath;
@OutputDirectory
public DirectoryProperty getExtractPath() {
return extractPath;
}
private Function<String, Path> transform;
@Internal
public Function<String, Path> getTransform() {
return transform;
}
/**
* A transform to apply to the tar entry, to derive the relative path from the entry name. If the return value is null, the entry is
* dropped from the exploded tar archive.
*
* @param transform the transform
*/
public void setTransform(Function<String, Path> transform) {
this.transform = transform;
}
@Inject
public SymbolicLinkPreservingUntarTask(final ObjectFactory objectFactory) {
this.tarFile = objectFactory.fileProperty();
this.extractPath = objectFactory.directoryProperty();
this.transform = name -> Paths.get(name);
}
@TaskAction
final void execute() {
// ensure the target extraction path is empty
getProject().delete(extractPath);
try (
TarArchiveInputStream tar = new TarArchiveInputStream(
new GzipCompressorInputStream(new FileInputStream(tarFile.getAsFile().get()))
)
) {
final Path destinationPath = extractPath.get().getAsFile().toPath();
TarArchiveEntry entry = tar.getNextTarEntry();
while (entry != null) {
final Path relativePath = transform.apply(entry.getName());
if (relativePath == null) {
entry = tar.getNextTarEntry();
continue;
}
final Path destination = destinationPath.resolve(relativePath);
final Path parent = destination.getParent();
if (Files.exists(parent) == false) {
Files.createDirectories(parent);
}
if (entry.isDirectory()) {
Files.createDirectory(destination);
} else if (entry.isSymbolicLink()) {
Files.createSymbolicLink(destination, Paths.get(entry.getLinkName()));
} else {
// copy the file from the archive using a small buffer to avoid heaping
Files.createFile(destination);
try (FileOutputStream fos = new FileOutputStream(destination.toFile())) {
tar.transferTo(fos);
}
}
if (entry.isSymbolicLink() == false) {
// check if the underlying file system supports POSIX permissions
final PosixFileAttributeView view = Files.getFileAttributeView(destination, PosixFileAttributeView.class);
if (view != null) {
final Set<PosixFilePermission> permissions = PosixFilePermissions.fromString(
permissions((entry.getMode() >> 6) & 07) + permissions((entry.getMode() >> 3) & 07) + permissions(
(entry.getMode() >> 0) & 07
)
);
Files.setPosixFilePermissions(destination, permissions);
}
}
entry = tar.getNextTarEntry();
}
} catch (final IOException e) {
throw new GradleException("unable to extract tar [" + tarFile.getAsFile().get().toPath() + "]", e);
}
}
private String permissions(final int permissions) {
if (permissions < 0 || permissions > 7) {
throw new IllegalArgumentException("permissions [" + permissions + "] out of range");
}
final StringBuilder sb = new StringBuilder(3);
if ((permissions & 4) == 4) {
sb.append('r');
} else {
sb.append('-');
}
if ((permissions & 2) == 2) {
sb.append('w');
} else {
sb.append('-');
}
if ((permissions & 1) == 1) {
sb.append('x');
} else {
sb.append('-');
}
return sb.toString();
}
}

View File

@ -0,0 +1,110 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.gradle.transform;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.gradle.api.logging.Logging;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.PosixFilePermissions;
import java.util.Set;
public abstract class SymbolicLinkPreservingUntarTransform implements UnpackTransform {
public void unpack(File tarFile, File targetDir) throws IOException {
Logging.getLogger(SymbolicLinkPreservingUntarTransform.class)
.info("Unpacking " + tarFile.getName() + " using " + SymbolicLinkPreservingUntarTransform.class.getSimpleName() + ".");
TarArchiveInputStream tar = new TarArchiveInputStream(new GzipCompressorInputStream(new FileInputStream(tarFile)));
final Path destinationPath = targetDir.toPath();
TarArchiveEntry entry = tar.getNextTarEntry();
while (entry != null) {
final Path relativePath = UnpackTransform.trimArchiveExtractPath(entry.getName());
if (relativePath == null) {
entry = tar.getNextTarEntry();
continue;
}
final Path destination = destinationPath.resolve(relativePath);
final Path parent = destination.getParent();
if (Files.exists(parent) == false) {
Files.createDirectories(parent);
}
if (entry.isDirectory()) {
Files.createDirectory(destination);
} else if (entry.isSymbolicLink()) {
Files.createSymbolicLink(destination, Paths.get(entry.getLinkName()));
} else {
// copy the file from the archive using a small buffer to avoid heaping
Files.createFile(destination);
try (FileOutputStream fos = new FileOutputStream(destination.toFile())) {
tar.transferTo(fos);
}
}
if (entry.isSymbolicLink() == false) {
// check if the underlying file system supports POSIX permissions
final PosixFileAttributeView view = Files.getFileAttributeView(destination, PosixFileAttributeView.class);
if (view != null) {
final Set<PosixFilePermission> permissions = PosixFilePermissions.fromString(
permissions((entry.getMode() >> 6) & 07) + permissions((entry.getMode() >> 3) & 07) + permissions(
(entry.getMode() >> 0) & 07
)
);
Files.setPosixFilePermissions(destination, permissions);
}
}
entry = tar.getNextTarEntry();
}
}
private static String permissions(final int permissions) {
if (permissions < 0 || permissions > 7) {
throw new IllegalArgumentException("permissions [" + permissions + "] out of range");
}
final StringBuilder sb = new StringBuilder(3);
if ((permissions & 4) == 4) {
sb.append('r');
} else {
sb.append('-');
}
if ((permissions & 2) == 2) {
sb.append('w');
} else {
sb.append('-');
}
if ((permissions & 1) == 1) {
sb.append('x');
} else {
sb.append('-');
}
return sb.toString();
}
}

View File

@ -0,0 +1,85 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.gradle.transform;
import org.gradle.api.artifacts.transform.InputArtifact;
import org.gradle.api.artifacts.transform.TransformAction;
import org.gradle.api.artifacts.transform.TransformOutputs;
import org.gradle.api.artifacts.transform.TransformParameters;
import org.gradle.api.file.FileSystemLocation;
import org.gradle.api.provider.Provider;
import org.gradle.api.tasks.PathSensitive;
import org.gradle.api.tasks.PathSensitivity;
import org.gradle.internal.UncheckedException;
import java.io.File;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public interface UnpackTransform extends TransformAction<TransformParameters.None> {
@PathSensitive(PathSensitivity.NAME_ONLY)
@InputArtifact
Provider<FileSystemLocation> getArchiveFile();
@Override
default void transform(TransformOutputs outputs) {
File archiveFile = getArchiveFile().get().getAsFile();
File unzipDir = outputs.dir(archiveFile.getName());
try {
unpack(archiveFile, unzipDir);
} catch (IOException e) {
throw UncheckedException.throwAsUncheckedException(e);
}
}
void unpack(File archiveFile, File targetDir) throws IOException;
/*
* We want to remove up to the and including the jdk-.* relative paths. That is a JDK archive is structured as:
* jdk-12.0.1/
* jdk-12.0.1/Contents
* ...
*
* and we want to remove the leading jdk-12.0.1. Note however that there could also be a leading ./ as in
* ./
* ./jdk-12.0.1/
* ./jdk-12.0.1/Contents
*
* so we account for this and search the path components until we find the jdk-12.0.1, and strip the leading components.
*/
static Path trimArchiveExtractPath(String relativePath) {
final Path entryName = Paths.get(relativePath);
int index = 0;
for (; index < entryName.getNameCount(); index++) {
if (entryName.getName(index).toString().matches("jdk-?\\d.*")) {
break;
}
}
if (index + 1 >= entryName.getNameCount()) {
// this happens on the top-level directories in the archive, which we are removing
return null;
}
// finally remove the top-level directories from the output path
return entryName.subpath(index + 1, entryName.getNameCount());
}
}

View File

@ -0,0 +1,54 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.gradle.transform;
import org.apache.commons.io.IOUtils;
import org.gradle.api.logging.Logging;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public abstract class UnzipTransform implements UnpackTransform {
public void unpack(File zipFile, File targetDir) throws IOException {
Logging.getLogger(UnzipTransform.class)
.info("Unpacking " + zipFile.getName() + " using " + UnzipTransform.class.getSimpleName() + ".");
try (ZipInputStream inputStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(zipFile)))) {
ZipEntry entry;
while ((entry = inputStream.getNextEntry()) != null) {
if (entry.isDirectory()) {
continue;
}
String child = UnpackTransform.trimArchiveExtractPath(entry.getName()).toString();
File outFile = new File(targetDir, child);
outFile.getParentFile().mkdirs();
try (FileOutputStream outputStream = new FileOutputStream(outFile)) {
IOUtils.copyLarge(inputStream, outputStream);
}
}
}
}
}

View File

@ -21,8 +21,6 @@ package org.elasticsearch.gradle.util;
import org.elasticsearch.gradle.ElasticsearchJavaPlugin;
import org.gradle.api.Action;
import org.gradle.api.GradleException;
import org.gradle.api.NamedDomainObjectContainer;
import org.gradle.api.PolymorphicDomainObjectContainer;
import org.gradle.api.Project;
import org.gradle.api.Task;
import org.gradle.api.UnknownTaskException;
@ -47,7 +45,6 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;
public abstract class GradleUtils {
@ -60,28 +57,6 @@ public abstract class GradleUtils {
return project.getConvention().getPlugin(JavaPluginConvention.class).getSourceSets();
}
public static <T> T maybeCreate(NamedDomainObjectContainer<T> collection, String name) {
return Optional.ofNullable(collection.findByName(name)).orElse(collection.create(name));
}
public static <T> T maybeCreate(NamedDomainObjectContainer<T> collection, String name, Action<T> action) {
return Optional.ofNullable(collection.findByName(name)).orElseGet(() -> {
T result = collection.create(name);
action.execute(result);
return result;
});
}
public static <T> T maybeCreate(PolymorphicDomainObjectContainer<T> collection, String name, Class<T> type, Action<T> action) {
return Optional.ofNullable(collection.findByName(name)).orElseGet(() -> {
T result = collection.create(name, type);
action.execute(result);
return result;
});
}
public static <T extends Task> TaskProvider<T> maybeRegister(TaskContainer tasks, String name, Class<T> clazz, Action<T> action) {
try {
return tasks.named(name, clazz);

View File

@ -1,16 +0,0 @@
project.gradle.projectsEvaluated {
// wire the jdk repo to wiremock
String fakeJdkRepo = Objects.requireNonNull(System.getProperty('tests.jdk_repo'))
String fakeJdkVendor = Objects.requireNonNull(System.getProperty('tests.jdk_vendor'))
String fakeJdkVersion = Objects.requireNonNull(System.getProperty('tests.jdk_version'))
println rootProject.repositories.asMap.keySet()
IvyArtifactRepository repository =
(IvyArtifactRepository) rootProject.repositories.getByName("jdk_repo_${fakeJdkVendor}_${fakeJdkVersion}")
repository.setUrl(fakeJdkRepo)
}
tasks.register("numConfigurations") {
doLast {
println "NUM CONFIGS: ${project.configurations.size()}"
}
}

View File

@ -1,12 +0,0 @@
evaluationDependsOn ':subproj'
String fakeJdkVendor = Objects.requireNonNull(System.getProperty('tests.jdk_vendor'))
String fakeJdkVersion = Objects.requireNonNull(System.getProperty('tests.jdk_version'))
jdks {
linux_jdk {
vendor = fakeJdkVendor
version = fakeJdkVersion
platform = "linux"
architecture = "x64"
}
}

View File

@ -1 +0,0 @@
include 'subproj'

View File

@ -1,48 +0,0 @@
plugins {
id 'elasticsearch.jdk-download'
}
String fakeJdkVendor = Objects.requireNonNull(System.getProperty('tests.jdk_vendor'))
String fakeJdkVersion = Objects.requireNonNull(System.getProperty('tests.jdk_version'))
jdks {
linux {
vendor = fakeJdkVendor
version = fakeJdkVersion
platform = "linux"
architecture = "x64"
}
darwin {
vendor = fakeJdkVendor
version = fakeJdkVersion
platform = "darwin"
architecture = "x64"
}
windows {
vendor = fakeJdkVendor
version = fakeJdkVersion
platform = "windows"
architecture = "x64"
}
}
tasks.register("getLinuxJdk") {
dependsOn jdks.linux
doLast {
println "JDK HOME: " + jdks.linux
}
}
tasks.register("getDarwinJdk") {
dependsOn jdks.darwin
doLast {
println "JDK HOME: " + jdks.darwin
}
}
tasks.register("getWindowsJdk") {
dependsOn jdks.windows
doLast {
println "JDK HOME: " + jdks.windows
}
}