From 51fdfcc507ec12ce5de2db0b1ac58363bd1a5dcf Mon Sep 17 00:00:00 2001 From: Blake Li Date: Mon, 10 Jun 2024 18:49:36 -0400 Subject: [PATCH] fix: Move the logic of getting systemProductName from static block to static method. The static field systemProductName should only be used for testing purposes. In production environment, the logic of getting systemProductName is now exactly the same as before. --- .../InstantiatingGrpcChannelProvider.java | 30 +++++++++++-------- 1 file changed, 17 insertions(+), 13 deletions(-) diff --git a/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProvider.java b/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProvider.java index af5ef2648d..539e06cd69 100644 --- a/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProvider.java +++ b/gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProvider.java @@ -83,19 +83,7 @@ */ public final class InstantiatingGrpcChannelProvider implements TransportChannelProvider { - static String systemProductName; - - static { - try { - systemProductName = - Files.asCharSource(new File("/sys/class/dmi/id/product_name"), StandardCharsets.UTF_8) - .readFirstLine(); - } catch (IOException e) { - // If not on Compute Engine, FileNotFoundException will be thrown. Use empty string - // as it won't match with the GCE_PRODUCTION_NAME constants - systemProductName = ""; - } - } + private static String systemProductName; @VisibleForTesting static final Logger LOG = Logger.getLogger(InstantiatingGrpcChannelProvider.class.getName()); @@ -345,6 +333,7 @@ boolean isCredentialDirectPathCompatible() { static boolean isOnComputeEngine() { String osName = System.getProperty("os.name"); if ("Linux".equals(osName)) { + String systemProductName = getSystemProductName(); // systemProductName will be empty string if not on Compute Engine return systemProductName.contains(GCE_PRODUCTION_NAME_PRIOR_2016) || systemProductName.contains(GCE_PRODUCTION_NAME_AFTER_2016); @@ -352,6 +341,21 @@ static boolean isOnComputeEngine() { return false; } + private static String getSystemProductName() { + // The static field systemProductName should only be set in tests + if (systemProductName != null) { + return systemProductName; + } + try { + return Files.asCharSource(new File("/sys/class/dmi/id/product_name"), StandardCharsets.UTF_8) + .readFirstLine(); + } catch (IOException e) { + // If not on Compute Engine, FileNotFoundException will be thrown. Use empty string + // as it won't match with the GCE_PRODUCTION_NAME constants + return ""; + } + } + // Universe Domain configuration is currently only supported in the GDU @VisibleForTesting boolean canUseDirectPathWithUniverseDomain() {