Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider;
import com.google.auth.Credentials;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Strings;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import io.grpc.ManagedChannelBuilder;
Expand All @@ -45,17 +44,14 @@
import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder;
import io.opentelemetry.sdk.metrics.export.MetricExporter;
import io.opentelemetry.sdk.resources.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.net.UnknownHostException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
Expand Down Expand Up @@ -86,6 +82,14 @@ class BuiltInMetricsProvider {

private static final String default_location = "global";

private static final int DEFAULT_GCP_CHECK_TIMEOUT_MS = 5000;

private static final String DEFAULT_GCP_METADATA_PROJECT_ID_URL =
"http://metadata.google.internal/computeMetadata/v1/project/project-id";

@VisibleForTesting
static volatile String gcpMetadataProjectIdUrl = DEFAULT_GCP_METADATA_PROJECT_ID_URL;

private final Object lock = new Object();
private OpenTelemetry openTelemetry;
private boolean ownsOpenTelemetry;
Expand Down Expand Up @@ -302,32 +306,68 @@ private static void shutdownMeterProvider(
}
}

/**
* Parses the {@code spanner.check_is_running_on_gcp_timeout} system property in milliseconds.
* Returns {@link #DEFAULT_GCP_CHECK_TIMEOUT_MS} silently when unset, or logs a warning and falls
* back to the default when the value is blank, non-numeric, overflows {@code int}, or is
* non-positive ({@code <= 0}).
*/
@VisibleForTesting
static int parseGcpCheckTimeoutMs() {
String rawTimeout = System.getProperty("spanner.check_is_running_on_gcp_timeout");
if (rawTimeout == null) {
return DEFAULT_GCP_CHECK_TIMEOUT_MS;
}
try {
int parsed = Integer.parseInt(rawTimeout.trim());
if (parsed > 0) {
return parsed;
}
} catch (NumberFormatException ignore) {
// Fall through to the warning and default timeout below.
}
// URLConnection treats 0 as an infinite timeout and throws IllegalArgumentException on
// negative values, so reject any non-positive or unparseable configuration.
logger.log(
Level.WARNING,
"Invalid value \"{0}\" for system property spanner.check_is_running_on_gcp_timeout;"
+ " using default {1} ms",
new Object[] {rawTimeout, DEFAULT_GCP_CHECK_TIMEOUT_MS});
return DEFAULT_GCP_CHECK_TIMEOUT_MS;
}

// TODO: Remove when
// https://github.com/GoogleCloudPlatform/opentelemetry-operations-java/issues/421
// has been fixed.
/**
* Performs a bounded HTTP probe against the GCE metadata endpoint to determine whether the
* process is running on GCP before invoking {@link GCPResourceProvider}.
*/
static boolean quickCheckIsRunningOnGcp() {
int timeout = 5000;
int timeout = parseGcpCheckTimeoutMs();
HttpURLConnection connection = null;
try {
timeout =
Integer.parseInt(System.getProperty("spanner.check_is_running_on_gcp_timeout", "5000"));
} catch (NumberFormatException ignore) {
// ignore
}
try {
URL url = new URL("http://metadata.google.internal/computeMetadata/v1/project/project-id");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
URL url = new URL(gcpMetadataProjectIdUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(timeout);
connection.setReadTimeout(timeout);
connection.setInstanceFollowRedirects(false);
connection.setRequestProperty("Metadata-Flavor", "Google");
if (connection.getResponseCode() == 200
&& ("Google").equals(connection.getHeaderField("Metadata-Flavor"))) {
InputStream input = connection.getInputStream();
try (BufferedReader reader =
new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8))) {
return !Strings.isNullOrEmpty(reader.readLine());
&& "Google".equals(connection.getHeaderField("Metadata-Flavor"))) {
try (InputStream input = connection.getInputStream()) {
// CR and LF are single-byte in UTF-8, so inspecting only the first byte matches
// non-empty first-line semantics without unbounded line buffering or decoder read-ahead.
int firstByte = input.read();
return firstByte != -1 && firstByte != '\r' && firstByte != '\n';
}
}
} catch (IOException ignore) {
// ignore
// Non-GCP hosts or stalled/unreachable metadata endpoints fall back to non-GCP.
} finally {
if (connection != null) {
connection.disconnect();
}
}
return false;
}
Expand Down
Loading
Loading