Skip to content

Commit 536f1eb

Browse files
authoredJun 12, 2024··
fix: Move the logic of getting systemProductName from static block to 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
1 parent af10a9e commit 536f1eb

File tree

1 file changed

+17
-13
lines changed

1 file changed

+17
-13
lines changed
 

‎gax-java/gax-grpc/src/main/java/com/google/api/gax/grpc/InstantiatingGrpcChannelProvider.java

+17-13
Original file line numberDiff line numberDiff line change
@@ -83,19 +83,7 @@
8383
*/
8484
public final class InstantiatingGrpcChannelProvider implements TransportChannelProvider {
8585

86-
static String systemProductName;
87-
88-
static {
89-
try {
90-
systemProductName =
91-
Files.asCharSource(new File("/sys/class/dmi/id/product_name"), StandardCharsets.UTF_8)
92-
.readFirstLine();
93-
} catch (IOException e) {
94-
// If not on Compute Engine, FileNotFoundException will be thrown. Use empty string
95-
// as it won't match with the GCE_PRODUCTION_NAME constants
96-
systemProductName = "";
97-
}
98-
}
86+
private static String systemProductName;
9987

10088
@VisibleForTesting
10189
static final Logger LOG = Logger.getLogger(InstantiatingGrpcChannelProvider.class.getName());
@@ -345,13 +333,29 @@ boolean isCredentialDirectPathCompatible() {
345333
static boolean isOnComputeEngine() {
346334
String osName = System.getProperty("os.name");
347335
if ("Linux".equals(osName)) {
336+
String systemProductName = getSystemProductName();
348337
// systemProductName will be empty string if not on Compute Engine
349338
return systemProductName.contains(GCE_PRODUCTION_NAME_PRIOR_2016)
350339
|| systemProductName.contains(GCE_PRODUCTION_NAME_AFTER_2016);
351340
}
352341
return false;
353342
}
354343

344+
private static String getSystemProductName() {
345+
// The static field systemProductName should only be set in tests
346+
if (systemProductName != null) {
347+
return systemProductName;
348+
}
349+
try {
350+
return Files.asCharSource(new File("/sys/class/dmi/id/product_name"), StandardCharsets.UTF_8)
351+
.readFirstLine();
352+
} catch (IOException e) {
353+
// If not on Compute Engine, FileNotFoundException will be thrown. Use empty string
354+
// as it won't match with the GCE_PRODUCTION_NAME constants
355+
return "";
356+
}
357+
}
358+
355359
// Universe Domain configuration is currently only supported in the GDU
356360
@VisibleForTesting
357361
boolean canUseDirectPathWithUniverseDomain() {

0 commit comments

Comments
 (0)
Please sign in to comment.