Skip to content

Apache Lucene open-source search software

Add custom URL patterns for downloading gradle distribution and gradle wrapper (#16543)

Dawid Weissc2f95d9c193e
diff --git a/.github/workflows/run-checks-gradle-upgrade.yml b/.github/workflows/run-checks-gradle-upgrade.yml
index 06bd638315e..4732bcb070f 100644
--- a/.github/workflows/run-checks-gradle-upgrade.yml
+++ b/.github/workflows/run-checks-gradle-upgrade.yml
@@ -10,6 +10,9 @@ on:
paths:
- '.github/workflows/run-checks-gradle-upgrade.yml'
- 'gradle/wrapper/**'
+ - 'gradlew'
+ - 'gradlew.bat'
+ - 'build-tools/build-infra/src/main/java/org/apache/lucene/gradle/*.java'
push:
branches:
@@ -18,6 +21,9 @@ on:
paths:
- '.github/workflows/run-checks-gradle-upgrade.yml'
- 'gradle/wrapper/**'
+ - 'gradlew'
+ - 'gradlew.bat'
+ - 'build-tools/build-infra/src/main/java/org/apache/lucene/gradle/*.java'
permissions: {}
@@ -53,6 +59,85 @@ jobs:
exit 1
fi
+ gradleMirrorCheck:
+ name: "Check gradle bootstrap from an intranet mirror (LUCENE_GRADLE_*_URL)."
+ timeout-minutes: 30
+ runs-on: ubuntu-latest
+ steps:
+ - name: Checkout repository
+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
+ with:
+ persist-credentials: false
+
+ - uses: ./.github/actions/prepare-for-build
+ with:
+ java-version: '25'
+ use-cache: false
+
+ - name: Build a local mirror from the official distribution and wrapper jar
+ run: |
+ set -e
+ MIRROR="$RUNNER_TEMP/gradle-mirror"
+ VERSION=$(grep -oP 'gradle-\K[^-]+(?=-bin\.zip)' gradle/wrapper/gradle-wrapper.properties)
+ echo "Gradle version: $VERSION"
+ mkdir -p "$MIRROR/$VERSION"
+ curl -sSfL -o "$MIRROR/$VERSION/gradle-$VERSION-bin.zip" \
+ "https://services.gradle.org/distributions/gradle-$VERSION-bin.zip"
+ curl -sSfL -o "$MIRROR/$VERSION/gradle-wrapper.jar" \
+ "https://raw.githubusercontent.com/gradle/gradle/v$VERSION/gradle/wrapper/gradle-wrapper.jar"
+ # A tampered copy for the negative test.
+ cp -r "$MIRROR" "$MIRROR-bad"
+ echo x >> "$MIRROR-bad/$VERSION/gradle-wrapper.jar"
+ echo x >> "$MIRROR-bad/$VERSION/gradle-$VERSION-bin.zip"
+
+ - name: Make the official download hosts unreachable
+ run: echo "127.0.0.1 services.gradle.org raw.githubusercontent.com" | sudo tee -a /etc/hosts
+
+ # The ${gradleVersion} placeholder below is expanded by GradleMirrorSetup, not by GitHub.
+ - name: gradlew must bootstrap from the mirror only
+ env:
+ GRADLE_USER_HOME: ${{ runner.temp }}/gradle-user-home
+ LUCENE_GRADLE_WRAPPER_URL: file://${{ runner.temp }}/gradle-mirror/${gradleVersion}/gradle-wrapper.jar
+ LUCENE_GRADLE_DISTRIBUTION_URL: file://${{ runner.temp }}/gradle-mirror/${gradleVersion}/gradle-${gradleVersion}-bin.zip
+ run: |
+ rm -f gradle/wrapper/gradle-wrapper.jar
+ ./gradlew help
+
+ - name: gradlew must reject a mirror with wrong checksums
+ env:
+ GRADLE_USER_HOME: ${{ runner.temp }}/gradle-user-home-bad
+ LUCENE_GRADLE_WRAPPER_URL: file://${{ runner.temp }}/gradle-mirror-bad/${gradleVersion}/gradle-wrapper.jar
+ LUCENE_GRADLE_DISTRIBUTION_URL: file://${{ runner.temp }}/gradle-mirror-bad/${gradleVersion}/gradle-${gradleVersion}-bin.zip
+ run: |
+ set +e
+ rm -f gradle/wrapper/gradle-wrapper.jar
+ output=$(./gradlew --version 2>&1); status=$?
+ if [ $status -ne 0 ] && [[ "$output" == *"does not match"* ]]; then
+ echo "Passed (rejected as expected)."
+ else
+ echo "Expected a checksum failure, got status $status. gradlew output echoed below:"
+ echo -e "\n$output\n\n---(end of output)"
+ exit 1
+ fi
+
+ - name: gradlew must refuse LUCENE_GRADLE_VERIFY_CHECKSUMS=false in CI
+ env:
+ GRADLE_USER_HOME: ${{ runner.temp }}/gradle-user-home-bad
+ LUCENE_GRADLE_VERIFY_CHECKSUMS: false
+ LUCENE_GRADLE_WRAPPER_URL: file://${{ runner.temp }}/gradle-mirror-bad/${gradleVersion}/gradle-wrapper.jar
+ LUCENE_GRADLE_DISTRIBUTION_URL: file://${{ runner.temp }}/gradle-mirror-bad/${gradleVersion}/gradle-${gradleVersion}-bin.zip
+ run: |
+ set +e
+ test -n "$CI" || { echo "Expected the CI variable to be set."; exit 1; }
+ output=$(./gradlew --version 2>&1); status=$?
+ if [ $status -ne 0 ] && [[ "$output" == *"not allowed when the CI environment variable is set"* ]]; then
+ echo "Passed (rejected as expected)."
+ else
+ echo "Expected a refusal, got status $status. gradlew output echoed below:"
+ echo -e "\n$output\n\n---(end of output)"
+ exit 1
+ fi
+
gradleWindowsSanityCheck:
name: "Check gradlew help works on Windows."
timeout-minutes: 30
@@ -76,7 +161,7 @@ jobs:
gradleSanityCheck:
name: "Run tasks (java: ${{ matrix.java-version }}, alt-java: ${{ matrix.uses-alt-java }})"
timeout-minutes: 30
- needs: [gradleScriptBootstrapCheck, gradleWindowsSanityCheck]
+ needs: [gradleScriptBootstrapCheck, gradleMirrorCheck, gradleWindowsSanityCheck]
strategy:
matrix:
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/GradleMirrorSetup.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/GradleMirrorSetup.java
new file mode 100644
index 00000000000..22623fc67eb
--- /dev/null
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/GradleMirrorSetup.java
@@ -0,0 +1,582 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF 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.apache.lucene.gradle;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Reader;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+import java.math.BigInteger;
+import java.net.HttpURLConnection;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URLConnection;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileLock;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.StandardOpenOption;
+import java.nio.file.attribute.PosixFilePermissions;
+import java.security.MessageDigest;
+import java.util.Comparator;
+import java.util.List;
+import java.util.Locale;
+import java.util.Properties;
+import java.util.concurrent.TimeUnit;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * Standalone class run by {@code gradlew}/{@code gradlew.bat} (before the gradle wrapper) when the
+ * {@value #LUCENE_GRADLE_DISTRIBUTION_URL_ENV} and/or {@value #LUCENE_GRADLE_WRAPPER_URL_ENV}
+ * environment variables are set. This should be used in environments that cannot reach GitHub
+ * and/or services.gradle.org.
+ *
+ * <p>This class downloads (each step only if the corresponding variable is set):
+ *
+ * <ul>
+ * <li>{@code gradle-wrapper.jar} from {@value #LUCENE_GRADLE_WRAPPER_URL_ENV} into {@code
+ * gradle/wrapper/} (otherwise GradleWrapperDownloader would fetch it from GitHub),
+ * <li>the gradle distribution from {@value #LUCENE_GRADLE_DISTRIBUTION_URL_ENV}, installing it in
+ * the gradle user home exactly where the gradle wrapper would install the "official"
+ * distribution so that the wrapper considers it already installed.
+ * </ul>
+ *
+ * <p>Both URLs may contain a {@code ${gradleVersion}} placeholder, replaced with the version parsed
+ * from {@code distributionUrl} in {@code gradle-wrapper.properties}. For example:
+ *
+ * <pre>
+ * LUCENE_GRADLE_DISTRIBUTION_URL=file:///tmp/local-gradle-mirror/${gradleVersion}/gradle-${gradleVersion}-bin.zip
+ * LUCENE_GRADLE_WRAPPER_URL=file:///tmp/local-gradle-mirror/${gradleVersion}/gradle-wrapper.jar
+ * </pre>
+ *
+ * <p>By default, checksums of the distribution and/or the wrapper must match those that are present
+ * in {@code gradle-wrapper.properties}. Setting {@value #LUCENE_GRADLE_VERIFY_CHECKSUMS_ENV} to
+ * {@code false} disables all checksum verification: an existing {@code gradle-wrapper.jar} is used
+ * as-is and downloads are installed unverified. This is refused if the {@code CI} environment
+ * variable is set (an unverified distribution would be trusted by all subsequent builds sharing the
+ * same gradle user home).
+ *
+ * <p>This class must not have any dependencies outside of standard java libraries as it's run
+ * directly from source.
+ *
+ * <p>The code in this class is based on automated analysis of gradle wrapper sources from gradle
+ * v9.7.1.
+ */
+public class GradleMirrorSetup {
+ public static final String LUCENE_GRADLE_DISTRIBUTION_URL_ENV = "LUCENE_GRADLE_DISTRIBUTION_URL";
+ public static final String LUCENE_GRADLE_WRAPPER_URL_ENV = "LUCENE_GRADLE_WRAPPER_URL";
+ public static final String LUCENE_GRADLE_VERIFY_CHECKSUMS_ENV = "LUCENE_GRADLE_VERIFY_CHECKSUMS";
+
+ /** Inline this annotation to keep this class self-contained. */
+ @Retention(RetentionPolicy.CLASS)
+ @Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.TYPE})
+ private @interface SuppressForbidden {
+ String reason();
+ }
+
+ /**
+ * Checksum verification is on unless {@value #LUCENE_GRADLE_VERIFY_CHECKSUMS_ENV} is set to
+ * "false".
+ */
+ private static final boolean VERIFY_CHECKSUMS =
+ !"false".equalsIgnoreCase(System.getenv(LUCENE_GRADLE_VERIFY_CHECKSUMS_ENV));
+
+ /** Used when {@code networkTimeout} is not set in {@code gradle-wrapper.properties}. */
+ private static final int DEFAULT_NETWORK_TIMEOUT_MILLIS = (int) TimeUnit.SECONDS.toMillis(10);
+
+ /**
+ * Read timeout while a download is actively streaming. Deliberately much larger than the connect
+ * timeout.
+ */
+ private static final int READ_TIMEOUT_MILLIS = (int) TimeUnit.SECONDS.toMillis(60);
+
+ private static final Pattern DISTRIBUTION_NAME =
+ Pattern.compile("gradle-(?<version>.+?)-(bin|all)\\.zip");
+ private static final Pattern PLACEHOLDER = Pattern.compile("\\$\\{(?<varname>[^}]*)\\}");
+
+ private static final boolean IS_WINDOWS =
+ System.getProperty("os.name").toLowerCase(Locale.ROOT).contains("windows");
+
+ private final Path projectDir;
+ private final Path gradleUserHome;
+
+ public static void main(String[] args) {
+ if (args.length < 1) {
+ System.err.println("Usage: java GradleMirrorSetup.java <project dir> [gradle arguments]");
+ System.exit(2);
+ }
+
+ try {
+ checkVersion();
+ checkVerificationAllowed();
+ new GradleMirrorSetup(Paths.get(args[0]), args).run();
+ } catch (Exception e) {
+ System.err.println("ERROR: " + e.getMessage());
+ System.exit(3);
+ }
+ }
+
+ public static void checkVersion() {
+ int major = Runtime.version().feature();
+ if (major < 17) {
+ throw new IllegalStateException("java version must be 17 or later, your version: " + major);
+ }
+ }
+
+ /** Refuses to run with checksum verification disabled in CI environments. */
+ static void checkVerificationAllowed() {
+ String ci = System.getenv("CI");
+ if (!VERIFY_CHECKSUMS && ci != null && !ci.isEmpty()) {
+ throw new IllegalStateException(
+ LUCENE_GRADLE_VERIFY_CHECKSUMS_ENV
+ + "=false is not allowed when the CI environment variable is set.");
+ }
+ }
+
+ GradleMirrorSetup(Path projectDir, String[] gradleArgs) {
+ this.projectDir = projectDir.toAbsolutePath().normalize();
+
+ // Gradle user home: -g/--gradle-user-home, GRADLE_USER_HOME or ~/.gradle.
+ String userHome = null;
+ for (int i = 1; i < gradleArgs.length; i++) {
+ String arg = gradleArgs[i];
+ if ((arg.equals("-g") || arg.equals("--gradle-user-home")) && i + 1 < gradleArgs.length) {
+ userHome = gradleArgs[++i];
+ } else if (arg.startsWith("--gradle-user-home=")) {
+ userHome = arg.substring("--gradle-user-home=".length());
+ }
+ }
+ if (userHome == null) {
+ userHome = System.getenv("GRADLE_USER_HOME");
+ }
+ this.gradleUserHome =
+ userHome != null
+ ? Paths.get(userHome)
+ : Paths.get(System.getProperty("user.home"), ".gradle");
+ }
+
+ void run() throws Exception {
+ Path wrapperDir = projectDir.resolve("gradle").resolve("wrapper");
+ Path propertiesFile = wrapperDir.resolve("gradle-wrapper.properties");
+ if (!Files.exists(propertiesFile)) {
+ throw new IOException("Wrapper property file not found: " + propertiesFile);
+ }
+ Properties props = new Properties();
+ try (Reader reader = Files.newBufferedReader(propertiesFile, StandardCharsets.UTF_8)) {
+ props.load(reader);
+ }
+ String distributionUrl = props.getProperty("distributionUrl");
+ if (distributionUrl == null) {
+ throw new IOException("No 'distributionUrl' in " + propertiesFile);
+ }
+ Matcher m = DISTRIBUTION_NAME.matcher(distributionUrl);
+ if (!m.find()) {
+ throw new IOException(
+ "Could not parse the gradle version from distributionUrl in "
+ + propertiesFile
+ + ": "
+ + distributionUrl);
+ }
+ String gradleVersion = m.group("version");
+ int timeout =
+ Integer.parseInt(
+ props
+ .getProperty("networkTimeout", String.valueOf(DEFAULT_NETWORK_TIMEOUT_MILLIS))
+ .trim());
+
+ URI wrapperUrl = expand(LUCENE_GRADLE_WRAPPER_URL_ENV, gradleVersion);
+ URI mirrorDistributionUrl = expand(LUCENE_GRADLE_DISTRIBUTION_URL_ENV, gradleVersion);
+
+ if (!VERIFY_CHECKSUMS) {
+ log(
+ "NOTE: checksum verification disabled ("
+ + LUCENE_GRADLE_VERIFY_CHECKSUMS_ENV
+ + "=false).");
+ }
+
+ if (wrapperUrl != null) {
+ setupWrapperJar(wrapperDir, wrapperUrl, timeout);
+ }
+ if (mirrorDistributionUrl != null) {
+ setupDistribution(props, distributionUrl, mirrorDistributionUrl, gradleVersion, timeout);
+ }
+ }
+
+ /**
+ * Replaces {@code ${gradleVersion}} and parses the result as a URI; null/blank input yields null.
+ */
+ private static URI expand(String envName, String gradleVersion) throws IOException {
+ String template = System.getenv(envName);
+ if (template == null || template.trim().isEmpty()) {
+ return null;
+ }
+ Matcher m = PLACEHOLDER.matcher(template.trim());
+ StringBuilder sb = new StringBuilder();
+ while (m.find()) {
+ if (!m.group("varname").equals("gradleVersion")) {
+ throw new IOException(
+ "Unknown placeholder "
+ + m.group()
+ + " (only ${gradleVersion} is supported) in: "
+ + template);
+ }
+ m.appendReplacement(sb, Matcher.quoteReplacement(gradleVersion));
+ }
+ try {
+ return new URI(m.appendTail(sb).toString());
+ } catch (URISyntaxException e) {
+ // Don't echo the input: it may contain credentials.
+ throw new IOException(
+ "Invalid URL in " + envName + ": " + e.getReason() + " (at index " + e.getIndex() + ").");
+ }
+ }
+
+ /**
+ * Makes sure gradle/wrapper/gradle-wrapper.jar is present and matches gradle-wrapper.jar.sha256,
+ * downloading it from the mirror if needed. With checksum verification disabled, any existing jar
+ * is used as-is and downloads are not verified.
+ */
+ private void setupWrapperJar(Path wrapperDir, URI wrapperUrl, int timeout) throws Exception {
+ Path jar = wrapperDir.resolve("gradle-wrapper.jar");
+ Path checksumFile = wrapperDir.resolve("gradle-wrapper.jar.sha256");
+ String expectedChecksum = null;
+ if (VERIFY_CHECKSUMS) {
+ for (String line : Files.readAllLines(checksumFile, StandardCharsets.UTF_8)) {
+ // sha256sum format: "<checksum> *gradle-wrapper.jar" ('*' marks binary mode).
+ String[] parts = line.trim().split("\\s+");
+ if (parts.length == 2 && parts[1].replaceFirst("^\\*", "").equals("gradle-wrapper.jar")) {
+ expectedChecksum = parts[0];
+ }
+ }
+ if (expectedChecksum == null) {
+ throw new IOException("No checksum for gradle-wrapper.jar in " + checksumFile);
+ }
+ }
+
+ if (Files.exists(jar)
+ && (!VERIFY_CHECKSUMS || sha256(jar).equalsIgnoreCase(expectedChecksum))) {
+ return;
+ }
+
+ log("Downloading gradle-wrapper.jar from " + withoutUserInfo(wrapperUrl));
+ Path temp = Files.createTempFile(wrapperDir, ".gradle-wrapper", ".tmp");
+ try {
+ download(wrapperUrl, temp, timeout);
+ if (VERIFY_CHECKSUMS) {
+ String actualChecksum = sha256(temp);
+ if (!actualChecksum.equalsIgnoreCase(expectedChecksum)) {
+ throw new IOException(
+ "The gradle-wrapper.jar downloaded from "
+ + withoutUserInfo(wrapperUrl)
+ + " does not match "
+ + checksumFile
+ + " (expected: "
+ + expectedChecksum
+ + ", actual: "
+ + actualChecksum
+ + ").");
+ }
+ }
+ Files.move(temp, jar, StandardCopyOption.REPLACE_EXISTING);
+ } finally {
+ Files.deleteIfExists(temp);
+ }
+ }
+
+ /**
+ * Downloads the distribution from the mirror and installs it where the gradle wrapper would
+ * install the official one: {@code <base>/<path>/<name>/<md5 of the official url as base36>/}.
+ */
+ private void setupDistribution(
+ Properties props, String distributionUrl, URI mirrorUrl, String gradleVersion, int timeout)
+ throws Exception {
+ String expectedSha256 = props.getProperty("distributionSha256Sum");
+ if (expectedSha256 == null || expectedSha256.trim().isEmpty()) {
+ if (VERIFY_CHECKSUMS) {
+ throw new IOException(
+ "No 'distributionSha256Sum' in gradle-wrapper.properties; refusing to install a gradle"
+ + " distribution without checksum verification.");
+ }
+ expectedSha256 = null;
+ } else {
+ expectedSha256 = expectedSha256.trim();
+ }
+
+ URI official = new URI(distributionUrl);
+ String zipName = official.getPath().replaceAll(".*/", "");
+ String distName = zipName.replaceAll("\\.[^.]*$", "");
+ String hash =
+ new BigInteger(
+ 1,
+ MessageDigest.getInstance("MD5")
+ .digest(withoutUserInfo(official).getBytes(StandardCharsets.UTF_8)))
+ .toString(36);
+ Path distDir =
+ baseDir(props.getProperty("distributionBase", "GRADLE_USER_HOME"))
+ .resolve(props.getProperty("distributionPath", "wrapper/dists"))
+ .resolve(distName)
+ .resolve(hash);
+ Path zip =
+ baseDir(props.getProperty("zipStoreBase", "GRADLE_USER_HOME"))
+ .resolve(props.getProperty("zipStorePath", "wrapper/dists"))
+ .resolve(distName)
+ .resolve(hash)
+ .resolve(zipName);
+ Path marker = zip.resolveSibling(zipName + ".ok");
+ Path lockFile = zip.resolveSibling(zipName + ".lck");
+ Files.createDirectories(zip.getParent());
+
+ // The same lock file the gradle wrapper uses, in case several builds start concurrently.
+ long deadline = System.nanoTime() + TimeUnit.MINUTES.toNanos(2);
+ while (true) {
+ try (FileChannel channel =
+ FileChannel.open(lockFile, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
+ FileLock lock = channel.tryLock();
+ if (lock != null) {
+ try {
+ if (Files.exists(marker) && findLauncherJar(distDir) != null) {
+ return;
+ }
+
+ log("Downloading gradle distribution from " + withoutUserInfo(mirrorUrl));
+ download(mirrorUrl, zip, timeout);
+ if (VERIFY_CHECKSUMS) {
+ String actual = sha256(zip);
+ if (!actual.equalsIgnoreCase(expectedSha256)) {
+ Files.delete(zip);
+ throw new IOException(
+ "The distribution downloaded from "
+ + withoutUserInfo(mirrorUrl)
+ + " does not match distributionSha256Sum in gradle-wrapper.properties"
+ + " (expected: "
+ + expectedSha256
+ + ", actual: "
+ + actual
+ + ").");
+ }
+ }
+
+ // Remove leftovers of previous installations, then unpack.
+ if (Files.isDirectory(distDir)) {
+ try (Stream<Path> s = Files.list(distDir)) {
+ for (Path p : s.filter(Files::isDirectory).collect(Collectors.toList())) {
+ deleteRecursively(p);
+ }
+ }
+ }
+ unzip(zip, distDir);
+ Path launcherJar = findLauncherJar(distDir);
+ if (launcherJar == null) {
+ throw new IOException(
+ "The archive downloaded from "
+ + withoutUserInfo(mirrorUrl)
+ + " is not a gradle distribution?");
+ }
+ Path gradleCommand = launcherJar.getParent().resolveSibling("bin").resolve("gradle");
+ if (!IS_WINDOWS && Files.exists(gradleCommand)) {
+ try {
+ Files.setPosixFilePermissions(
+ gradleCommand, PosixFilePermissions.fromString("rwxr-xr-x"));
+ } catch (IOException | UnsupportedOperationException e) {
+ log("Could not set executable permissions for: " + gradleCommand + " (" + e + ")");
+ }
+ }
+ if (!Files.exists(marker)) {
+ Files.createFile(marker);
+ }
+ Files.delete(zip);
+ log("Gradle " + gradleVersion + " installed in " + distDir);
+ return;
+ } finally {
+ lock.release();
+ }
+ }
+ }
+ if (System.nanoTime() > deadline) {
+ throw new IOException("Timed out waiting for the lock on " + lockFile);
+ }
+ sleep(500);
+ }
+ }
+
+ private Path baseDir(String base) throws IOException {
+ switch (base) {
+ case "GRADLE_USER_HOME":
+ return gradleUserHome;
+ case "PROJECT":
+ return projectDir;
+ default:
+ throw new IOException("Unknown base directory in gradle-wrapper.properties: " + base);
+ }
+ }
+
+ /**
+ * Rebuilds the URI from its components, without any user info. Used for all logged URLs (so that
+ * credentials never end up in build logs) and for the distribution directory hash (the gradle
+ * wrapper hashes the distribution URL with user info stripped, this recreates such an URL).
+ *
+ * <p>The URI is rebuilt from scheme, host, port, path, query and fragment; the authority (where
+ * user info lives) is never copied over. Opaque URIs ({@code mailto:}, {@code jar:} etc.) have no
+ * authority and are returned as-is.
+ */
+ @SuppressWarnings("unused") // keep the source compatible with older Java versions (no '_').
+ private static String withoutUserInfo(URI uri) {
+ if (uri.isOpaque()) {
+ return uri.toASCIIString();
+ }
+ try {
+ return new URI(
+ uri.getScheme(),
+ null,
+ uri.getHost(),
+ uri.getPort(),
+ uri.getPath(),
+ uri.getQuery(),
+ uri.getFragment())
+ .toASCIIString();
+ } catch (URISyntaxException e) {
+ // Cannot happen for a hierarchical URI parsed from a string, but never fall back to the
+ // original (it may contain credentials).
+ return uri.getScheme() + ":<unprintable>";
+ }
+ }
+
+ /** Downloads to a temporary ".part" file first; retries a few times on failures. */
+ private void download(URI uri, Path target, int connectTimeout) throws Exception {
+ Path part = target.resolveSibling(target.getFileName() + ".part");
+ for (int attempt = 1; ; attempt++) {
+ try {
+ // Proxies are configured using the standard HTTP(S) proxy system properties.
+ URLConnection conn = uri.toURL().openConnection();
+ conn.setConnectTimeout(connectTimeout);
+ conn.setReadTimeout(READ_TIMEOUT_MILLIS);
+ if (conn instanceof HttpURLConnection
+ && ((HttpURLConnection) conn).getResponseCode() != HttpURLConnection.HTTP_OK) {
+ throw new IOException(
+ "Server returned HTTP " + ((HttpURLConnection) conn).getResponseCode());
+ }
+ try (InputStream in = conn.getInputStream();
+ OutputStream out = Files.newOutputStream(part)) {
+ in.transferTo(out);
+ }
+ Files.move(part, target, StandardCopyOption.REPLACE_EXISTING);
+ return;
+ } catch (IOException e) {
+ Files.deleteIfExists(part);
+ if (attempt >= 3 || !uri.getScheme().startsWith("http")) {
+ throw new IOException(
+ "Could not download " + withoutUserInfo(uri) + ": " + e.getMessage(), e);
+ }
+ log(
+ "Could not download "
+ + withoutUserInfo(uri)
+ + " ("
+ + e.getMessage()
+ + "), will retry in 10 seconds.");
+ sleep(TimeUnit.SECONDS.toMillis(10));
+ }
+ }
+ }
+
+ private static String sha256(Path path) throws Exception {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ try (InputStream in = Files.newInputStream(path)) {
+ byte[] buffer = new byte[64 * 1024];
+ for (int n; (n = in.read(buffer)) != -1; ) {
+ digest.update(buffer, 0, n);
+ }
+ }
+ return String.format(Locale.ROOT, "%064x", new BigInteger(1, digest.digest()));
+ }
+
+ private static void unzip(Path zip, Path dest) throws IOException {
+ try (FileSystem zipFs = FileSystems.newFileSystem(zip, (ClassLoader) null)) {
+ for (Path root : zipFs.getRootDirectories()) {
+ try (Stream<Path> entries = Files.walk(root)) {
+ for (Path entry : entries.collect(Collectors.toList())) {
+ String name = root.relativize(entry).toString();
+ // this corresponds to checks from PathTraversalChecker
+ if (name.startsWith("/")
+ || name.startsWith("\\")
+ || (IS_WINDOWS && name.contains(":"))
+ || Stream.of(name.replace('\\', '/').split("/")).anyMatch(".."::equals)) {
+ throw new IOException("Unsafe zip entry: " + name);
+ }
+ Path target = dest.resolve(name);
+ if (Files.isDirectory(entry)) {
+ Files.createDirectories(target);
+ } else {
+ Files.copy(entry, target, StandardCopyOption.REPLACE_EXISTING);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ private static void deleteRecursively(Path dir) throws IOException {
+ try (Stream<Path> s = Files.walk(dir)) {
+ for (Path p : s.sorted(Comparator.reverseOrder()).collect(Collectors.toList())) {
+ Files.delete(p);
+ }
+ }
+ }
+
+ /**
+ * Returns lib/gradle-launcher-*.jar if distDir contains exactly one directory with exactly one
+ * such jar (this is how the gradle wrapper validates an installation), null otherwise.
+ */
+ private static Path findLauncherJar(Path distDir) throws IOException {
+ if (!Files.isDirectory(distDir)) {
+ return null;
+ }
+ List<Path> dirs;
+ try (Stream<Path> s = Files.list(distDir)) {
+ dirs = s.filter(Files::isDirectory).collect(Collectors.toList());
+ }
+ if (dirs.size() != 1 || !Files.isDirectory(dirs.get(0).resolve("lib"))) {
+ return null;
+ }
+ try (Stream<Path> s = Files.list(dirs.get(0).resolve("lib"))) {
+ List<Path> jars =
+ s.filter(p -> p.getFileName().toString().matches("gradle-launcher-.*\\.jar"))
+ .collect(Collectors.toList());
+ return jars.size() == 1 ? jars.get(0) : null;
+ }
+ }
+
+ private static void log(String message) {
+ System.err.println(message);
+ }
+
+ @SuppressForbidden(reason = "Valid use of thread.sleep.")
+ private static void sleep(long millis) throws InterruptedException {
+ Thread.sleep(millis);
+ }
+}
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/WrapperDownloader.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/GradleWrapperDownloader.java
similarity index 97%
rename from build-tools/build-infra/src/main/java/org/apache/lucene/gradle/WrapperDownloader.java
rename to build-tools/build-infra/src/main/java/org/apache/lucene/gradle/GradleWrapperDownloader.java
index 40de43f4f52..8add39998a5 100644
--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/WrapperDownloader.java
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/GradleWrapperDownloader.java
@@ -45,7 +45,7 @@ import java.util.regex.Pattern;
*
* <p>Ensure this class has no dependencies outside of standard java libraries as it's used direct
*/
-public class WrapperDownloader {
+public class GradleWrapperDownloader {
/**
* Copied to keep the class isolated from any other classes.
*
@@ -60,13 +60,13 @@ public class WrapperDownloader {
public static void main(String[] args) {
if (args.length != 1) {
- System.err.println("Usage: java WrapperDownloader.java <destination>");
+ System.err.println("Usage: java GradleWrapperDownloader.java <destination>");
System.exit(2);
}
try {
checkVersion();
- new WrapperDownloader().run(Paths.get(args[0]));
+ new GradleWrapperDownloader().run(Paths.get(args[0]));
} catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
System.exit(3);
@@ -105,7 +105,7 @@ public class WrapperDownloader {
}
}
- Logger.getLogger(WrapperDownloader.class.getName())
+ Logger.getLogger(GradleWrapperDownloader.class.getName())
.warning(
"Something is wrong with the checksum file. Regenerate with "
+ "'sha256sum -b gradle-wrapper.jar > gradle-wrapper.jar.sha256'");
diff --git a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/CheckEnvironmentPlugin.java b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/CheckEnvironmentPlugin.java
index cb49afc0d61..7789cdabac7 100644
--- a/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/CheckEnvironmentPlugin.java
+++ b/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/plugins/misc/CheckEnvironmentPlugin.java
@@ -16,6 +16,16 @@
*/
package org.apache.lucene.gradle.plugins.misc;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UncheckedIOException;
+import java.math.BigInteger;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Collectors;
@@ -54,6 +64,37 @@ public class CheckEnvironmentPlugin extends LuceneGradlePlugin {
task -> {
task.setDistributionType(Wrapper.DistributionType.BIN);
task.setGradleVersion(expectedGradleVersion);
+ // gradle-wrapper.properties carries gradle distribution's checksum. Unless provided
+ // explicitly
+ // (--gradle-distribution-sha256-sum), fetch the checksum published next to the
+ // distribution so that it stays in sync on wrapper upgrades.
+ task.doFirst(
+ _ -> {
+ if (task.getDistributionSha256Sum() == null) {
+ task.setDistributionSha256Sum(
+ fetchDistributionSha256Sum(task.getDistributionUrl()));
+ }
+ });
+ // Keep gradle-wrapper.jar.sha256 (used by gradlew scripts to verify/download the
+ // wrapper jar) in sync with the jar written by this task.
+ Path jar = task.getJarFile().toPath();
+ Path checksumFile = jar.resolveSibling(jar.getFileName() + ".sha256");
+ task.getOutputs().file(checksumFile);
+ task.doLast(
+ _ -> {
+ try {
+ String expected = sha256(jar) + " *" + jar.getFileName() + "\n";
+ if (!Files.exists(checksumFile)
+ || !Files.readString(checksumFile, StandardCharsets.UTF_8)
+ .equals(expected)) {
+ Files.writeString(checksumFile, expected, StandardCharsets.UTF_8);
+ task.getLogger()
+ .lifecycle("Updated wrapper jar checksum: {}", checksumFile);
+ }
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ });
});
JavaVersion currentJavaVersion = JavaVersion.current();
@@ -163,4 +204,29 @@ public class CheckEnvironmentPlugin extends LuceneGradlePlugin {
});
});
}
+
+ private static String sha256(Path file) throws IOException {
+ try {
+ MessageDigest digest = MessageDigest.getInstance("SHA-256");
+ digest.update(Files.readAllBytes(file));
+ return String.format(Locale.ROOT, "%064x", new BigInteger(1, digest.digest()));
+ } catch (NoSuchAlgorithmException e) {
+ throw new RuntimeException(e);
+ }
+ }
+
+ private static String fetchDistributionSha256Sum(String distributionUrl) {
+ URI checksumUri = URI.create(distributionUrl + ".sha256");
+ try (InputStream is = checksumUri.toURL().openStream()) {
+ String checksum = new String(is.readAllBytes(), StandardCharsets.UTF_8).trim();
+ if (!checksum.matches("[0-9a-fA-F]{64}")) {
+ throw new GradleException(
+ "Unexpected content of the distribution checksum at " + checksumUri + ": " + checksum);
+ }
+ return checksum;
+ } catch (IOException e) {
+ throw new UncheckedIOException(
+ "Could not fetch the distribution checksum from " + checksumUri, e);
+ }
+ }
}
diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties
index ad7845be306..00fba3d33c8 100644
--- a/gradle/wrapper/gradle-wrapper.properties
+++ b/gradle/wrapper/gradle-wrapper.properties
@@ -7,3 +7,4 @@ retryBackOffMs=500
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
+distributionSha256Sum=acd53f1edaf02f1a8ff99879f8a34b302661a057d9b063ae9e35b552f804d20a
diff --git a/gradlew b/gradlew
index 88520aab1ae..ba9f3ff33d7 100755
--- a/gradlew
+++ b/gradlew
@@ -211,25 +211,38 @@ if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
fi
DEFAULT_JVM_OPTS="$DEFAULT_JVM_OPTS \"-Djava.io.tmpdir=$GRADLE_TEMPDIR\""
-# LUCENE-9266: verify and download the gradle wrapper jar if we don't have one.
if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then
APP_HOME=`cygpath --path --mixed "$APP_HOME"`
fi
-GRADLE_WRAPPER_JAR="$APP_HOME/gradle/wrapper/gradle-wrapper.jar"
-if "$darwin"; then
- shasumcmd=shasum
-else
- shasumcmd=sha256sum
+# Intranet mirrors for gradle-wrapper.jar and the gradle distribution, see GradleMirrorSetup.java
+# and 'gradlew helpLocalSettings'.
+if [ -n "$LUCENE_GRADLE_DISTRIBUTION_URL" ] || [ -n "$LUCENE_GRADLE_WRAPPER_URL" ]; then
+ "$JAVACMD" $JAVA_OPTS "$APP_HOME/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/GradleMirrorSetup.java" "$APP_HOME" "$@"
+ SETUP_STATUS=$?
+ if [ "$SETUP_STATUS" -ne 0 ]; then
+ exit $SETUP_STATUS
+ fi
fi
-if [ ! -e "$GRADLE_WRAPPER_JAR" ] || ! ( cd "$APP_HOME/gradle/wrapper" && "$shasumcmd" --status -c "${GRADLE_WRAPPER_JAR}.sha256" ); then
- "$JAVACMD" $JAVA_OPTS "$APP_HOME/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/WrapperDownloader.java" "$GRADLE_WRAPPER_JAR"
- WRAPPER_STATUS=$?
- if [ "$WRAPPER_STATUS" -eq 1 ]; then
- echo "ERROR: Something went wrong. Make sure you're using Java version of exactly 25."
- exit $WRAPPER_STATUS
- elif [ "$WRAPPER_STATUS" -ne 0 ]; then
- exit $WRAPPER_STATUS
+
+# LUCENE-9266: verify and download the gradle wrapper jar if we don't have one.
+# Skipped entirely if LUCENE_GRADLE_VERIFY_CHECKSUMS=false, see 'gradlew helpLocalSettings'.
+GRADLE_WRAPPER_JAR="$APP_HOME/gradle/wrapper/gradle-wrapper.jar"
+if [ "$LUCENE_GRADLE_VERIFY_CHECKSUMS" != "false" ]; then
+ if "$darwin"; then
+ shasumcmd=shasum
+ else
+ shasumcmd=sha256sum
+ fi
+ if [ ! -e "$GRADLE_WRAPPER_JAR" ] || ! ( cd "$APP_HOME/gradle/wrapper" && "$shasumcmd" --status -c "${GRADLE_WRAPPER_JAR}.sha256" ); then
+ "$JAVACMD" $JAVA_OPTS "$APP_HOME/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/GradleWrapperDownloader.java" "$GRADLE_WRAPPER_JAR"
+ WRAPPER_STATUS=$?
+ if [ "$WRAPPER_STATUS" -eq 1 ]; then
+ echo "ERROR: Something went wrong. Make sure you're using Java version of exactly 25."
+ exit $WRAPPER_STATUS
+ elif [ "$WRAPPER_STATUS" -ne 0 ]; then
+ exit $WRAPPER_STATUS
+ fi
fi
fi
diff --git a/gradlew.bat b/gradlew.bat
index 9a4928299a9..533b67f9cb0 100644
--- a/gradlew.bat
+++ b/gradlew.bat
@@ -77,7 +77,20 @@ SET GRADLE_TEMPDIR=%DIRNAME%\.gradle\tmp
IF NOT EXIST "%GRADLE_TEMPDIR%" MKDIR "%GRADLE_TEMPDIR%"
SET DEFAULT_JVM_OPTS=%DEFAULT_JVM_OPTS% "-Djava.io.tmpdir=%GRADLE_TEMPDIR%"
+@rem Intranet mirrors for gradle-wrapper.jar and the gradle distribution, see GradleMirrorSetup.java
+@rem and 'gradlew helpLocalSettings'.
+IF DEFINED LUCENE_GRADLE_DISTRIBUTION_URL goto intranetSetup
+IF DEFINED LUCENE_GRADLE_WRAPPER_URL goto intranetSetup
+goto wrapperJar
+
+:intranetSetup
+"%JAVA_EXE%" %JAVA_OPTS% "%APP_HOME%/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/GradleMirrorSetup.java" "%APP_HOME%" %*
+IF %ERRORLEVEL% NEQ 0 goto exitWithErrorLevel
+
+:wrapperJar
@rem LUCENE-9266: verify and download the gradle wrapper jar if we don't have one.
+@rem Skipped entirely if LUCENE_GRADLE_VERIFY_CHECKSUMS=false, see 'gradlew helpLocalSettings'.
+IF /I "%LUCENE_GRADLE_VERIFY_CHECKSUMS%"=="false" goto gradleProperties
set GRADLE_WRAPPER_JAR=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
set GRADLE_WRAPPER_CHECKSUM=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar.sha256
@@ -91,11 +104,12 @@ for /f "tokens=* delims=" %%H in ('certutil -hashfile "%GRADLE_WRAPPER_JAR%" SHA
)
if /i "%ACTUAL%" NEQ "%EXPECTED%" (
- "%JAVA_EXE%" -XX:TieredStopAtLevel=1 %JAVA_OPTS% "%APP_HOME%/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/WrapperDownloader.java" "%GRADLE_WRAPPER_JAR%"
+ "%JAVA_EXE%" -XX:TieredStopAtLevel=1 %JAVA_OPTS% "%APP_HOME%/build-tools/build-infra/src/main/java/org/apache/lucene/gradle/GradleWrapperDownloader.java" "%GRADLE_WRAPPER_JAR%"
IF %ERRORLEVEL% EQU 1 goto failWithJvmMessage
IF %ERRORLEVEL% NEQ 0 goto exitWithErrorLevel
)
+:gradleProperties
@rem Generate gradle.properties if it does not exist
IF NOT EXIST "%APP_HOME%\gradle.properties" (
@rem local expansion is needed to check ERRORLEVEL inside control blocks.
diff --git a/help/localSettings.md b/help/localSettings.md
index 0caab07ab00..c6b7d3b10de 100644
--- a/help/localSettings.md
+++ b/help/localSettings.md
@@ -33,3 +33,30 @@ values can be overridden by, in order of priority:
If you'd like to tweak some of the build options permanently, use the `build-options.local.properties` file. For
temporary overrides, use cli parameters (preferably gradle parameters `-Pxyz=value`).
+
+## Intranet mirrors for gradle (wrapper and distribution)
+
+Lucene's `gradlew` scripts download `gradle-wrapper.jar` (from GitHub) and the gradle distribution (from
+services.gradle.org) on first use. If these hosts are not reachable, you can point to mirrors using environment
+variables (both are optional and may contain a `${gradleVersion}` placeholder, replaced with the current gradle's
+version read from `gradle/wrapper/gradle-wrapper.properties`). For example:
+
+```bash
+LUCENE_GRADLE_WRAPPER_URL=https://mirror.example.com/gradle/${gradleVersion}/gradle-wrapper.jar
+LUCENE_GRADLE_DISTRIBUTION_URL=https://mirror.example.com/gradle/gradle-${gradleVersion}-bin.zip
+```
+
+If any of these variables are set, `gradlew` will download `gradle-wrapper.jar` into `gradle/wrapper/` (the jar must
+match the checksum in `gradle-wrapper.jar.sha256`) and installs the distribution (which must match
+`distributionSha256Sum` in `gradle-wrapper.properties`) into the gradle user home (`GRADLE_USER_HOME` or `~/.gradle`)
+at the location the gradle wrapper expects for the "official" distribution.
+
+Local URLs work too, for example:
+
+```bash
+LUCENE_GRADLE_DISTRIBUTION_URL=file:///path/to/gradle-9.7.1-bin.zip
+```
+
+Setting `LUCENE_GRADLE_VERIFY_CHECKSUMS=false` disables checksum verification in these bootstrap steps. Use this only if
+you trust the origin of the jar and the mirror URLs. This setting is refused (`gradlew` fails) if the `CI` environment
+variable is set.
diff --git a/lucene/CHANGES.txt b/lucene/CHANGES.txt
index 86797feadca..9da6884f163 100644
--- a/lucene/CHANGES.txt
+++ b/lucene/CHANGES.txt
@@ -548,6 +548,14 @@ Bug Fixes
* GITHUB#16577: Fix incorrect position increment generated by FixedShingleFilter. (Kishor Kharbas)
+Build
+---------------------
+
+* GITHUB#16543, GITHUB#16521, GITHUB#16483: allow custom gradle-wrapper.jar
+ and gradle distribution mirrors (via environment variables LUCENE_GRADLE_WRAPPER_URL,
+ LUCENE_GRADLE_DISTRIBUTION_URL), see './gradlew helpLocalSettings' for more
+ information. (David Smiley, Dawid Weiss)
+
Other
---------------------
* GITHUB#16266: Remove deprecated search(Query, Collector) calls in QueryUtils by replacing