Skip to content

Instantly share code, notes, and snippets.

@sshaaf
Created August 17, 2024 10:24
Show Gist options
  • Save sshaaf/1abea9946214546d3b304a4e9ec3ca1e to your computer and use it in GitHub Desktop.
Save sshaaf/1abea9946214546d3b304a4e9ec3ca1e to your computer and use it in GitHub Desktop.
curl -Ls https://sh.jbang.dev | bash -s - app setup
vi MemoryRequestSum.java
##(paste from below..) (esc :wq!)
jbang MemoryRequestSum.java
///usr/bin/env jbang "$0" "$@" ; exit $?
//DEPS com.fasterxml.jackson.core:jackson-databind:2.13.3
//DEPS com.fasterxml.jackson.core:jackson-core:2.13.3
//DEPS com.fasterxml.jackson.core:jackson-annotations:2.13.3
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Iterator;
public class MemoryRequestSum {
public static void main(String[] args) throws Exception {
String nodeName = "node-name"; // Replace with your node name
// Run the kubectl command to get pod information
Process process = Runtime.getRuntime().exec("kubectl get pods --all-namespaces --field-selector spec.nodeName=" + nodeName + " -o json");
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
StringBuilder jsonOutput = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
jsonOutput.append(line);
}
// Parse the JSON output
ObjectMapper objectMapper = new ObjectMapper();
JsonNode pods = objectMapper.readTree(jsonOutput.toString());
long totalMemoryRequest = 0;
// Iterate over each pod and sum the memory requests
for (JsonNode pod : pods.get("items")) {
for (JsonNode container : pod.get("spec").get("containers")) {
JsonNode memoryRequestNode = container.get("resources").get("requests").get("memory");
if (memoryRequestNode != null) {
String memoryRequest = memoryRequestNode.asText();
totalMemoryRequest += convertMemoryToBytes(memoryRequest);
}
}
}
System.out.println("Total Memory Requested on Node " + nodeName + ": " + (totalMemoryRequest / (1024 * 1024)) + " MiB");
}
// Convert memory requests to bytes
private static long convertMemoryToBytes(String memoryRequest) {
if (memoryRequest.endsWith("Mi")) {
return Long.parseLong(memoryRequest.replace("Mi", "")) * 1024 * 1024;
} else if (memoryRequest.endsWith("Gi")) {
return Long.parseLong(memoryRequest.replace("Gi", "")) * 1024 * 1024 * 1024;
} else {
return 0; // Add more conversions if needed
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment