Вот несколько способов составить список всех модулей в кластере Kubernetes и отсортировать их по убыванию на основе запросов ЦП.
Метод 1: использование инструмента командной строки kubectl
kubectl get pods --all-namespaces --sort-by='.spec.containers[].resources.requests.cpu'
Метод 2. Использование kubectl и jq (легкого и гибкого процессора JSON командной строки)
kubectl get pods --all-namespaces -o json | jq '.items | sort_by(.spec.containers[].resources.requests.cpu) | reverse'
Метод 3. Использование Kubernetes API и Python
from kubernetes import client, config
# Load the Kubernetes configuration
config.load_kube_config()
# Create an API client
v1 = client.CoreV1Api()
# Get all pods in the cluster
pods = v1.list_pod_for_all_namespaces().items
# Sort pods based on CPU requests
sorted_pods = sorted(pods, key=lambda pod: pod.spec.containers[0].resources.requests['cpu'], reverse=True)
# Print the sorted pods
for pod in sorted_pods:
print(pod.metadata.name)
Метод 4. Использование Kubernetes API и Go
package main
import (
"fmt"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/util/homedir"
"path/filepath"
"sort"
)
func main() {
// Get the kubeconfig file path
home := homedir.HomeDir()
kubeconfig := filepath.Join(home, ".kube", "config")
// Load the kubeconfig file
config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
if err != nil {
panic(err)
}
// Create a Kubernetes clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err)
}
// Get all pods in the cluster
pods, err := clientset.CoreV1().Pods("").List(context.TODO(), metav1.ListOptions{})
if err != nil {
panic(err)
}
// Sort pods based on CPU requests
sort.Slice(pods.Items, func(i, j int) bool {
cpu1 := pods.Items[i].Spec.Containers[0].Resources.Requests[corev1.ResourceCPU]
cpu2 := pods.Items[j].Spec.Containers[0].Resources.Requests[corev1.ResourceCPU]
return cpu1.Cmp(cpu2) == 1
})
// Print the sorted pods
for _, pod := range pods.Items {
fmt.Println(pod.ObjectMeta.Name)
}
}