Skip to content

Commit

Permalink
fix: Move the logic of getting systemProductName from static block to…
Browse files Browse the repository at this point in the history
… static method (#2874)

The static field `systemProductName` should only be used for testing
purposes. In production environment, the logic of checking
`isOnComputeEngine` should be exactly the same as before
#2614.

Fixes b/346215860
  • Loading branch information
blakeli0 authored Jun 12, 2024
1 parent af10a9e commit 536f1eb
Showing 1 changed file with 17 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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());
Expand Down Expand Up @@ -345,13 +333,29 @@ 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);
}
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() {
Expand Down

0 comments on commit 536f1eb

Please sign in to comment.