-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
202 lines (166 loc) Β· 5.79 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
package main
import (
"context"
"flag"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/alexellis/kubetrim/pkg"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
_ "k8s.io/client-go/plugin/pkg/client/auth/azure"
_ "k8s.io/client-go/plugin/pkg/client/auth/exec"
_ "k8s.io/client-go/plugin/pkg/client/auth/gcp" // Import for GCP auth
_ "k8s.io/client-go/plugin/pkg/client/auth/oidc" // Import for OIDC (often used with EKS)
"k8s.io/client-go/tools/clientcmd"
clientcmdapi "k8s.io/client-go/tools/clientcmd/api"
"k8s.io/client-go/util/homedir"
)
var (
writeFile bool
force bool
keepFile string
)
func main() {
// set usage:
flag.Usage = func() {
fmt.Printf("kubetrim (%s %s) Copyright Alex Ellis (c) 2024\n\n", pkg.Version, pkg.GitCommit)
fmt.Print("Sponsor Alex on GitHub: https://github.com/sponsors/alexellis\n\n")
fmt.Fprintf(flag.CommandLine.Output(), "Usage of %s:\n", os.Args[0])
fmt.Fprintf(flag.CommandLine.Output(), "kubetrim removes contexts & clusters from your kubeconfig if they are not accessible.\n\n")
fmt.Fprintf(flag.CommandLine.Output(), "Set the kubeconfig file to use through the KUBECONFIG environment variable\n")
fmt.Fprintf(flag.CommandLine.Output(), "or the default location will be used: ~/.kube/config\n\n")
fmt.Fprintf(flag.CommandLine.Output(), "For partially available contexts, add each name on its own line in:\n~/.local/kubetrim/keep.txt\n\n")
fmt.Fprintf(flag.CommandLine.Output(), "Options:\n")
flag.PrintDefaults()
}
flag.BoolVar(&writeFile, "write", true, "Write changes to the kubeconfig file, set to false for a dry-run.")
flag.BoolVar(&force, "force", false, "Force delete all contexts, even if all are unreachable")
flag.StringVar(&keepFile, "keep-file", "$HOME/.local/kubetrim/keep.txt", "Path to the keep file for clusters that are partially available")
flag.Parse()
keepFile = os.ExpandEnv(keepFile)
var keepContexts []string
if _, err := os.Stat(keepFile); err == nil {
contexts, err := loadKeepContexts(keepFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Error loading %s: error: %s", keepFile, err)
os.Exit(1)
}
keepContexts = contexts
}
// Load the kubeconfig file
kubeconfig := filepath.Join(homedir.HomeDir(), ".kube", "config")
if configPath := os.Getenv("KUBECONFIG"); configPath != "" {
kubeconfig = configPath
}
// Load the kubeconfig
config, err := clientcmd.LoadFromFile(kubeconfig)
if err != nil {
fmt.Printf("Error loading kubeconfig: %v\n", err)
os.Exit(1)
}
fmt.Printf("kubetrim (%s %s) by Alex Ellis \n\nLoaded: %s. Checking..\n", pkg.Version, pkg.GitCommit, kubeconfig)
st := time.Now()
// List of ckeepContextsontexts to be deleted
var contextsToDelete []string
// Enumerate and check all contexts
for contextName := range config.Contexts {
fmt.Printf(" - %s: ", contextName)
skip := false
for _, keep := range keepContexts {
if keep == contextName {
skip = true
break
}
}
if skip {
fmt.Printf("skipping due to keep list β©\n")
continue
}
// Set the context for the current iteration
clientConfig := clientcmd.NewNonInteractiveClientConfig(*config, contextName, &clientcmd.ConfigOverrides{}, nil)
restConfig, err := clientConfig.ClientConfig()
if err != nil {
fmt.Printf("Failed to create REST config (%v)\n", err)
contextsToDelete = append(contextsToDelete, contextName)
continue
}
// Create Kubernetes client
clientset, err := kubernetes.NewForConfig(restConfig)
if err != nil {
fmt.Printf("Failed to create clientset (%v)\n", err)
contextsToDelete = append(contextsToDelete, contextName)
continue
}
// Check if the context is working
err = checkCluster(clientset)
if err != nil {
fmt.Printf("β - (%v)\n", err)
contextsToDelete = append(contextsToDelete, contextName)
} else {
fmt.Println("β
")
}
}
// Delete the contexts that are not working
for _, contextName := range contextsToDelete {
deleteContextAndCluster(config, contextName)
}
if writeFile {
if len(contextsToDelete) == len(config.Contexts) && !force {
fmt.Println("No contexts are working, the Internet may be down, use --force to delete all contexts anyway.")
os.Exit(1)
}
if len(contextsToDelete) > 0 {
// Save the modified kubeconfig
if err = clientcmd.WriteToFile(*config, kubeconfig); err != nil {
fmt.Printf("Error saving updated kubeconfig: %v\n", err)
os.Exit(1)
}
}
fmt.Printf("Updated: %s (in %s).\n", kubeconfig, time.Since(st).Round(time.Millisecond))
}
}
// checkCluster tries to list nodes in the cluster to verify if the context is working
func checkCluster(clientset *kubernetes.Clientset) error {
_, err := clientset.CoreV1().Nodes().List(context.TODO(), metav1.ListOptions{})
if err != nil {
return fmt.Errorf("failed to connect to cluster: %v", err)
}
return nil
}
// deleteContextAndCluster removes the context and its associated cluster from the config
func deleteContextAndCluster(config *clientcmdapi.Config, contextName string) {
// Get the cluster name associated with the context
clusterName := config.Contexts[contextName].Cluster
// Delete the context
delete(config.Contexts, contextName)
// Check if any other contexts use this cluster
clusterUsed := false
for _, ctx := range config.Contexts {
if ctx.Cluster == clusterName {
clusterUsed = true
break
}
}
// If the cluster is not used by any other context, delete it
if !clusterUsed {
delete(config.Clusters, clusterName)
}
}
func loadKeepContexts(path string) ([]string, error) {
keep := []string{}
data, err := os.ReadFile(path)
if err != nil {
return keep, err
}
lines := strings.Split(strings.TrimSpace(string(data)), "\n")
for _, line := range lines {
ln := strings.TrimSpace(line)
if len(ln) > 0 && !strings.HasPrefix(ln, "#") {
keep = append(keep, ln)
}
}
return keep, nil
}