Skip to content

Commit 2afe7ca

Browse files
Fix NPEs in CO2Calculator.getKiloWattsPerCore() (#110024) (#110308)
Co-authored-by: Elastic Machine <[email protected]>
1 parent d37e8c0 commit 2afe7ca

File tree

2 files changed

+38
-3
lines changed

2 files changed

+38
-3
lines changed

x-pack/plugin/profiling/src/main/java/org/elasticsearch/xpack/profiling/action/HostMetadata.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,9 +25,9 @@ final class HostMetadata implements ToXContentObject {
2525
final int profilingNumCores; // number of cores on the profiling host machine
2626

2727
HostMetadata(String hostID, InstanceType instanceType, String hostArchitecture, Integer profilingNumCores) {
28-
this.hostID = hostID;
29-
this.instanceType = instanceType;
30-
this.hostArchitecture = hostArchitecture;
28+
this.hostID = hostID != null ? hostID : "";
29+
this.instanceType = instanceType != null ? instanceType : new InstanceType("", "", "");
30+
this.hostArchitecture = hostArchitecture != null ? hostArchitecture : "";
3131
this.profilingNumCores = profilingNumCores != null ? profilingNumCores : DEFAULT_PROFILING_NUM_CORES;
3232
}
3333

x-pack/plugin/profiling/src/test/java/org/elasticsearch/xpack/profiling/action/CO2CalculatorTests.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,41 @@ public void testCreateFromRegularSource() {
8282
checkCO2Calculation(co2Calculator.getAnnualCO2Tons(HOST_ID_D, samples), annualCoreHours, 1.7d, 0.000379069d, 2.8d);
8383
}
8484

85+
// Make sure that malformed data doesn't cause the CO2 calculation to fail.
86+
public void testCreateFromMalformedSource() {
87+
// tag::noformat
88+
Map<String, HostMetadata> hostsTable = Map.ofEntries(
89+
Map.entry(HOST_ID_A,
90+
// known datacenter and instance type
91+
new HostMetadata(HOST_ID_A,
92+
new InstanceType(
93+
"aws",
94+
"eu-west-1",
95+
"c5n.xlarge"
96+
),
97+
null,
98+
null
99+
)
100+
),
101+
Map.entry(HOST_ID_B,
102+
new HostMetadata(HOST_ID_B,
103+
null,
104+
null,
105+
null
106+
)
107+
)
108+
);
109+
// end::noformat
110+
111+
double samplingDurationInSeconds = 1_800.0d; // 30 minutes
112+
long samples = 100_000L; // 100k samples
113+
double annualCoreHours = CostCalculator.annualCoreHours(samplingDurationInSeconds, samples, 20.0d);
114+
CO2Calculator co2Calculator = new CO2Calculator(hostsTable, samplingDurationInSeconds, null, null, null, null);
115+
116+
checkCO2Calculation(co2Calculator.getAnnualCO2Tons(HOST_ID_A, samples), annualCoreHours, 1.135d, 0.0002786d, 7.0d);
117+
checkCO2Calculation(co2Calculator.getAnnualCO2Tons(HOST_ID_B, samples), annualCoreHours, 1.7d, 0.000379069d, 7.0d);
118+
}
119+
85120
private void checkCO2Calculation(
86121
double calculatedAnnualCO2Tons,
87122
double annualCoreHours,

0 commit comments

Comments
 (0)