Skip to content

Instantly share code, notes, and snippets.

@richkeenan
Created March 8, 2022 17:18
Show Gist options
  • Save richkeenan/7238ed2c741469ee9ea8f726c47090ea to your computer and use it in GitHub Desktop.
Save richkeenan/7238ed2c741469ee9ea8f726c47090ea to your computer and use it in GitHub Desktop.
K8s pod density check
module podchecker
go 1.16
require (
github.com/olekukonko/tablewriter v0.0.5 // indirect
k8s.io/api v0.22.4 // indirect
k8s.io/apimachinery v0.22.4 // indirect
k8s.io/client-go v0.22.4 // indirect
)
package main
import (
"context"
"flag"
"fmt"
"github.com/olekukonko/tablewriter"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
"os"
"path/filepath"
)
func main() {
var kubeconfig *string
if home := homedir.HomeDir(); home != "" {
kubeconfig = flag.String("kubeconfig", filepath.Join(home, ".kube", "config"), "(optional) absolute path to the kubeconfig file")
} else {
kubeconfig = flag.String("kubeconfig", "", "absolute path to the kubeconfig file")
}
flag.Parse()
config, err := buildConfigFromFlags("development", *kubeconfig)
if err != nil {
panic(err.Error())
}
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
table := tablewriter.NewWriter(os.Stdout)
table.SetHeader([]string{"Node", "AZ", "Capacity", "Used"})
nodes, err := clientset.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
for _, node := range nodes.Items {
podCapacity := node.Status.Capacity.Pods().Value()
az := node.Labels["topology.kubernetes.io/zone"]
nodeName := node.Name
pods, _ := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{
FieldSelector: "spec.nodeName=" + nodeName,
})
podsOnNode := len(pods.Items)
table.Append([]string{nodeName, az, fmt.Sprintf("%d", podCapacity), fmt.Sprintf("%d", podsOnNode)})
}
table.Render()
}
func buildConfigFromFlags(context, kubeconfigPath string) (*rest.Config, error) {
return clientcmd.NewNonInteractiveDeferredLoadingClientConfig(
&clientcmd.ClientConfigLoadingRules{ExplicitPath: kubeconfigPath},
&clientcmd.ConfigOverrides{
CurrentContext: context,
}).ClientConfig()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment