From 3a5fd6a33d81cef9f92edc4a1dc3de44c199cec2 Mon Sep 17 00:00:00 2001 From: Drew Michel Date: Sat, 26 Jan 2019 13:05:49 -0500 Subject: [PATCH] Set connect/read timeout when calling the metadata service Otherwise callers of these methods can be waiting indefinitely. https://github.com/googleapis/google-cloud-java/issues/4398 --- .../src/main/java/com/google/cloud/MetadataConfig.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/MetadataConfig.java b/google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/MetadataConfig.java index 81e95eda41a8..867b0253acef 100644 --- a/google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/MetadataConfig.java +++ b/google-cloud-clients/google-cloud-core/src/main/java/com/google/cloud/MetadataConfig.java @@ -34,6 +34,7 @@ public class MetadataConfig { private static final String METADATA_URL = "http://metadata.google.internal/computeMetadata/v1/"; + private static final int TIMEOUT_MS = 5000; private MetadataConfig() {} @@ -69,6 +70,8 @@ public static String getAttribute(String attributeName) { try { URL url = new URL(METADATA_URL + attributeName); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); + connection.setConnectTimeout(TIMEOUT_MS); + connection.setReadTimeout(TIMEOUT_MS); connection.setRequestProperty("Metadata-Flavor", "Google"); InputStream input = connection.getInputStream(); if (connection.getResponseCode() == 200) {