Created
March 8, 2022 17:18
-
-
Save richkeenan/7238ed2c741469ee9ea8f726c47090ea to your computer and use it in GitHub Desktop.
K8s pod density check
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
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 | |
) |
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" | |
"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