Avoid NPE when getting build information

When the Elasticsearch code is loaded in an unusual classloading
environment (e.g., when using the high-level REST client) in Jetty, the
code source can be null and we trip with an NPE. This commit addresses
this.

Relates #27442
This commit is contained in:
Jason Tedor 2017-11-18 07:19:22 -05:00 committed by GitHub
parent 4f711a828b
commit 56540281a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 10 additions and 6 deletions

View File

@ -26,6 +26,7 @@ import org.elasticsearch.common.io.stream.StreamOutput;
import java.io.IOException;
import java.net.URL;
import java.security.CodeSource;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
@ -45,8 +46,8 @@ public class Build {
final boolean isSnapshot;
final String esPrefix = "elasticsearch-" + Version.CURRENT;
final URL url = getElasticsearchCodebase();
final String urlStr = url.toString();
final URL url = getElasticsearchCodeSourceLocation();
final String urlStr = url == null ? "" : url.toString();
if (urlStr.startsWith("file:/") && (urlStr.endsWith(esPrefix + ".jar") || urlStr.endsWith(esPrefix + "-SNAPSHOT.jar"))) {
try (JarInputStream jar = new JarInputStream(FileSystemUtils.openFileURLStream(url))) {
Manifest manifest = jar.getManifest();
@ -88,10 +89,13 @@ public class Build {
private final boolean isSnapshot;
/**
* Returns path to elasticsearch codebase path
* The location of the code source for Elasticsearch
*
* @return the location of the code source for Elasticsearch which may be null
*/
static URL getElasticsearchCodebase() {
return Build.class.getProtectionDomain().getCodeSource().getLocation();
static URL getElasticsearchCodeSourceLocation() {
final CodeSource codeSource = Build.class.getProtectionDomain().getCodeSource();
return codeSource == null ? null : codeSource.getLocation();
}
private final String shortHash;

View File

@ -30,7 +30,7 @@ public class BuildTests extends ESTestCase {
/** Asking for the jar metadata should not throw exception in tests, no matter how configured */
public void testJarMetadata() throws IOException {
URL url = Build.getElasticsearchCodebase();
URL url = Build.getElasticsearchCodeSourceLocation();
// throws exception if does not exist, or we cannot access it
try (InputStream ignored = FileSystemUtils.openFileURLStream(url)) {}
// these should never be null