Created
April 20, 2020 10:16
-
-
Save surajnarwade/5e8cdba46b34b22c88919dea98d7e3ec to your computer and use it in GitHub Desktop.
Number of pods per namespace
This file contains hidden or 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 ( | |
"fmt" | |
"log" | |
"os" | |
"text/tabwriter" | |
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" | |
"k8s.io/client-go/kubernetes" | |
"k8s.io/client-go/tools/clientcmd" | |
) | |
type Client struct { | |
kubeClient kubernetes.Interface | |
kubeConfig clientcmd.ClientConfig | |
namespace string | |
} | |
func main() { | |
var client Client | |
// initialize client-go clients | |
loadingRules := clientcmd.NewDefaultClientConfigLoadingRules() | |
configOverrides := &clientcmd.ConfigOverrides{} | |
client.kubeConfig = clientcmd.NewNonInteractiveDeferredLoadingClientConfig(loadingRules, configOverrides) | |
config, err := client.kubeConfig.ClientConfig() | |
clientset, err := kubernetes.NewForConfig(config) | |
if err != nil { | |
log.Fatal(err) | |
} | |
namespace, _, err := client.kubeConfig.Namespace() | |
if err != nil { | |
log.Fatal(err) | |
} | |
client.namespace = namespace | |
coreAPI := clientset.CoreV1() | |
ns, err := coreAPI.Namespaces().List(metav1.ListOptions{}) | |
w := tabwriter.NewWriter(os.Stdout, 5, 2, 3, ' ', tabwriter.TabIndent) | |
fmt.Fprintln(w, "NAMESPACE", "\t", "TOTAL", "\t", "RUNNING", "\t", "SUCCEEDED", "\t", "FAILED", "\t", "UNKNOWN", "\t", "PENDING") | |
for _, n := range ns.Items { | |
pods, err := coreAPI.Pods(n.Name).List(metav1.ListOptions{}) | |
if err != nil { | |
log.Fatal(err) | |
} | |
var running, succeeded, failed, unknown, pending int32 | |
for _, p := range pods.Items { | |
if p.Status.Phase == "Running" { | |
running++ | |
} | |
if p.Status.Phase == "Succeeded" { | |
succeeded++ | |
} | |
if p.Status.Phase == "Failed" { | |
failed++ | |
} | |
if p.Status.Phase == "Unknown" { | |
unknown++ | |
} | |
if p.Status.Phase == "Pending" { | |
pending++ | |
} | |
} | |
fmt.Fprintln(w, n.Name, "\t", len(pods.Items), "\t", running, "\t", succeeded, "\t", failed, "\t", unknown, "\t", pending) | |
} | |
w.Flush() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment