-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
111 lines (94 loc) · 2.63 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
import (
"flag"
"fmt"
"os"
"path/filepath"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
"k8s.io/client-go/tools/clientcmd"
)
type clusterNamespace struct {
name string
numPods int
numDeployments int
numServices int
}
type totalClusterStats struct {
totalPods int
totalDeployments int
totalServices int
}
func printClusterInfo(m map[int]clusterNamespace) {
var t totalClusterStats
for _, ns := range m {
fmt.Printf("Namespace: %s\n", ns.name)
fmt.Printf("\tPods: %d\n", ns.numPods)
fmt.Printf("\tDeployments: %d\n", ns.numDeployments)
fmt.Printf("\tServices: %d\n", ns.numServices)
t.totalPods += ns.numPods
t.totalDeployments += ns.numDeployments
t.totalServices += ns.numServices
}
fmt.Printf("\nCluster totals:\n")
fmt.Printf("\tPods: %d\n", t.totalPods)
fmt.Printf("\tDeployments: %d\n", t.totalDeployments)
fmt.Printf("\tServices: %d\n", t.totalServices)
}
func homeDir() string {
if h := os.Getenv("HOME"); h != "" {
return h
}
return os.Getenv("USERPROFILE") // windows
}
func main() {
var kubeconfig *string
if home := 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()
// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", *kubeconfig)
if err != nil {
panic(err.Error())
}
// create the clientset
clientset, err := kubernetes.NewForConfig(config)
if err != nil {
panic(err.Error())
}
// get the namespaces
namespaces, err := clientset.CoreV1().Namespaces().List(metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
clusterInfo := make(map[int]clusterNamespace)
// loop through the namespaces
for i, namespace := range namespaces.Items {
namespaceName := namespace.Name
// get the pods
pods, err := clientset.CoreV1().Pods(namespaceName).List(metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
// get the services
services, err := clientset.CoreV1().Services(namespaceName).List(metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
// get the deployments
deployments, err := clientset.ExtensionsV1beta1().Deployments(namespaceName).List(metav1.ListOptions{})
if err != nil {
panic(err.Error())
}
clusterInfo[i] = clusterNamespace{
name: namespaceName,
numPods: len(pods.Items),
numDeployments: len(deployments.Items),
numServices: len(services.Items),
}
}
printClusterInfo(clusterInfo)
}