Last active
September 26, 2024 22:40
Overhead memory tracking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"fmt" | |
v1 "k8s.io/api/core/v1" | |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
"k8s.io/client-go/kubernetes" | |
"k8s.io/client-go/tools/clientcmd" | |
"math/big" | |
) | |
func main() { | |
kubeconfig := "/path/to/kubeconfig" | |
// Create the client config | |
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig) | |
if err != nil { | |
fmt.Printf("Error building kubeconfig: %v\n", err) | |
return | |
} | |
// Create the Kubernetes client | |
clientset, err := kubernetes.NewForConfig(config) | |
if err != nil { | |
fmt.Printf("Error creating Kubernetes client: %v\n", err) | |
return | |
} | |
// Get the list of nodes | |
nodes, err := clientset.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{}) | |
if err != nil { | |
fmt.Printf("Error listing nodes: %v\n", err) | |
return | |
} | |
// Map to group nodes by instance type | |
instanceTypeMemoryMap := make(map[string][]*big.Int) | |
// Iterate through each node and group by instance type | |
for _, node := range nodes.Items { | |
// Retrieve the memory capacity of the node | |
// Retrieve the instance type label | |
instanceType, labelExists := node.Labels["node.kubernetes.io/instance-type"] | |
if !labelExists { | |
instanceType = "Unknown" | |
} | |
memory := node.Status.Capacity[v1.ResourceMemory] | |
memoryMiB := memory.Value() / 1024 / 1024 | |
// Convert memory to big.Int for accurate comparison | |
memoryBig := new(big.Int) | |
memoryBig.SetInt64(memoryMiB) | |
// Add memory to the list for the given instance type | |
instanceTypeMemoryMap[instanceType] = append(instanceTypeMemoryMap[instanceType], memoryBig) | |
} | |
// Check for variance in memory capacities within each instance type | |
for instanceType, memoryList := range instanceTypeMemoryMap { | |
if len(memoryList) > 1 { | |
fmt.Printf("Instance Type: %s\n", instanceType) | |
hasVariance := false | |
firstMemory := memoryList[0] | |
// Compare all memory values with the first one | |
for _, mem := range memoryList[1:] { | |
if firstMemory.Cmp(mem) != 0 { | |
hasVariance = true | |
break | |
} | |
} | |
if hasVariance { | |
fmt.Println("Variance detected in memory capacities:") | |
for _, mem := range memoryList { | |
fmt.Printf(" - %s\n", mem.String()) | |
} | |
} else { | |
fmt.Println("No variance, all nodes have the same memory capacity.") | |
} | |
fmt.Println() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment