forked from Jont828/cluster-api-visualizer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
400 lines (320 loc) · 11.7 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
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package main
import (
"bytes"
"context"
"encoding/json"
"flag"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"os"
"strings"
"github.com/Jont828/cluster-api-visualizer/internal"
"github.com/Jont828/cluster-api-visualizer/version"
"k8s.io/client-go/tools/clientcmd"
"k8s.io/client-go/tools/clientcmd/api"
"k8s.io/klog/v2"
"sigs.k8s.io/cluster-api/cmd/clusterctl/client"
"sigs.k8s.io/cluster-api/cmd/clusterctl/client/cluster"
"sigs.k8s.io/cluster-api/cmd/clusterctl/client/config"
ctrl "sigs.k8s.io/controller-runtime"
ctrlclient "sigs.k8s.io/controller-runtime/pkg/client"
configclient "sigs.k8s.io/controller-runtime/pkg/client/config"
)
type Client struct {
ClusterctlClient client.Client // The clusterctl client needed to run clusterctl operations like `c.DescribeCluster()`
ClusterClient cluster.Client // The client used by clusterctl to interact with the management cluster
ControllerRuntimeClient ctrlclient.Client // The Kubernetes controller-runtime client needed to run `external.Get()` to fetch any CRD as a JSON object
K8sConfigClient *api.Config // This is the Kubernetes config client needed to access information from the kubeconfig like the namespace and context
CurrentNamespace string
}
var c *Client
var kubeconfigPath = ""
var kubeContext = ""
var clusterctlConfigPath = ""
func newClient(ctx context.Context) (*Client, *internal.HTTPError) {
log := ctrl.LoggerFrom(ctx)
c := &Client{}
var err error
clusterKubeconfig := cluster.Kubeconfig{Path: kubeconfigPath, Context: kubeContext}
c.ClusterctlClient, err = client.New(ctx, clusterctlConfigPath)
if err != nil {
log.Error(err, "failed to create client")
return nil, internal.NewInternalError(err)
}
configClient, err := config.New(ctx, clusterctlConfigPath)
if err != nil {
log.Error(err, "failed to create client")
return nil, internal.NewInternalError(err)
}
clusterClient := cluster.New(clusterKubeconfig, configClient)
c.ClusterClient = clusterClient
err = clusterClient.Proxy().CheckClusterAvailable()
if err != nil {
log.Error(err, "failed to check cluster availability for cluster client")
return nil, &internal.HTTPError{Status: http.StatusNotFound, Message: err.Error()}
}
c.ControllerRuntimeClient, err = clusterClient.Proxy().NewClient()
if err != nil {
log.Error(err, "failed to create client")
return nil, internal.NewInternalError(err)
}
c.CurrentNamespace, err = clusterClient.Proxy().CurrentNamespace()
if err != nil {
log.Error(err, "failed to create client")
return nil, internal.NewInternalError(err)
}
rules := clientcmd.NewDefaultClientConfigLoadingRules()
rules.ExplicitPath = clusterClient.Kubeconfig().Path
c.K8sConfigClient, err = rules.Load()
if err != nil {
log.Error(err, "failed to create client")
return nil, internal.NewInternalError(err)
} else if c.K8sConfigClient == nil {
log.Error(err, "failed to create client")
return nil, internal.NewInternalError(err)
}
return c, nil
}
func main() {
var host string
var port int
var generateConfig bool
flag.StringVar(&host, "host", "localhost", "Host to listen on")
flag.IntVar(&port, "port", 8081, "The port to listen on")
flag.BoolVar(&generateConfig, "generate-config", false, "Generate a kubeconfig file and write it to disk. Useful for running inside a pod within a cluster.")
klog.InitFlags(nil)
flag.Set("v", "2")
flag.Parse()
ctrl.SetLogger(klog.Background())
ctx := ctrl.SetupSignalHandler()
log := ctrl.LoggerFrom(ctx)
log.Info("Starting app with version", "version", version.Get().String())
if generateConfig {
log.V(2).Info("Generating kubeconfig file")
restConfig := configclient.GetConfigOrDie()
apiConfig, err := internal.ConstructInClusterKubeconfig(ctx, restConfig, "")
if err != nil {
log.Error(err, "error constructing in-cluster kubeconfig")
return
}
filePath := "tmp/management.kubeconfig"
if err = internal.WriteKubeconfigToFile(ctx, filePath, *apiConfig); err != nil {
log.Error(err, "error writing kubeconfig to file")
return
}
kubeconfigPath = filePath
kubeContext = apiConfig.CurrentContext
}
var httpErr *internal.HTTPError
c, httpErr = newClient(ctx)
if httpErr != nil {
log.Error(httpErr, "failed to initialize client, will allow frontend to start") // Try to initialize client but allow GUI to start anyway even if it fails
}
http.Handle("/api/v1/management-cluster/", http.HandlerFunc(handleManagementClusterTree))
http.Handle("/api/v1/custom-resource-definition/", http.HandlerFunc(handleCustomResourceDefinitionTree))
http.Handle("/api/v1/resource-logs/", http.HandlerFunc(handleGetResourceLogs))
http.Handle("/api/v1/describe-cluster/", http.HandlerFunc(handleDescribeClusterTree))
http.Handle("/api/v1/version/", http.HandlerFunc(handleGetVersion))
var frontend fs.FS = os.DirFS("web/dist")
httpFS := http.FS(frontend)
fileServer := http.FileServer(httpFS)
serveIndex := serveFileContents(ctx, "index.html", httpFS)
http.Handle("/", intercept404(fileServer, serveIndex))
uri := fmt.Sprintf("%s:%d", host, port)
log.V(2).Info(fmt.Sprintf("Listening at http://%s", uri))
if host == "0.0.0.0" {
log.V(2).Info(fmt.Sprintf("View at http://localhost:%d in browser", port))
}
srv := &http.Server{
Addr: uri,
// Pass root context to the server so it gets propagated to all requests.
BaseContext: func(net.Listener) context.Context { return ctx },
}
// srv.Handler is nil so it uses default serve mux, which http.Handle configures by default.
srv.ListenAndServe()
}
type hookedResponseWriter struct {
http.ResponseWriter
got404 bool
}
func (hrw *hookedResponseWriter) WriteHeader(status int) {
if status == http.StatusNotFound {
// Don't actually write the 404 header, just set a flag.
hrw.got404 = true
} else {
hrw.ResponseWriter.WriteHeader(status)
}
}
func (hrw *hookedResponseWriter) Write(p []byte) (int, error) {
if hrw.got404 {
// No-op, but pretend that we wrote len(p) bytes to the writer.
return len(p), nil
}
return hrw.ResponseWriter.Write(p)
}
func intercept404(handler, on404 http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hookedWriter := &hookedResponseWriter{ResponseWriter: w}
handler.ServeHTTP(hookedWriter, r)
if hookedWriter.got404 {
on404.ServeHTTP(w, r)
}
})
}
func serveFileContents(ctx context.Context, file string, files http.FileSystem) http.HandlerFunc {
log := ctrl.LoggerFrom(ctx)
log.V(4).Info("Serving file", "filename", file)
return func(w http.ResponseWriter, r *http.Request) {
// Restrict only to instances where the browser is looking for an HTML file
if !strings.Contains(r.Header.Get("Accept"), "text/html") {
log.V(4).Info("404 file not found", "filename", file)
w.WriteHeader(http.StatusNotFound)
fmt.Fprint(w, "404 not found")
return
}
// Open the file and return its contents using http.ServeContent
index, err := files.Open(file)
if err != nil {
log.Error(err, "open file error")
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "`%s` not found", file)
return
}
fi, err := index.Stat()
if err != nil {
log.Error(err, "stat file error")
w.WriteHeader(http.StatusNotFound)
fmt.Fprintf(w, "`%s` not found", file)
return
}
r = r.WithContext(ctx)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
http.ServeContent(w, r, fi.Name(), fi.ModTime(), index)
}
}
func handleManagementClusterTree(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
log := ctrl.LoggerFrom(ctx)
log.V(2).Info("GET call to url", "url", r.URL.Path)
// Attempt to initialize clients
c, httpErr := newClient(ctx)
if httpErr != nil {
log.Error(httpErr, "failed to initialize clients")
http.Error(w, httpErr.Error(), httpErr.Status)
return
}
tree, httpErr := internal.ConstructMultiClusterTree(ctx, c.ControllerRuntimeClient, c.K8sConfigClient)
if httpErr != nil {
log.Error(httpErr, "failed to construct management cluster tree view")
http.Error(w, httpErr.Error(), httpErr.Status)
return
}
if tree != nil {
marshalled, err := json.MarshalIndent(*tree, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
io.Copy(w, bytes.NewReader(marshalled))
}
}
func handleDescribeClusterTree(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
log := ctrl.LoggerFrom(ctx)
log.V(2).Info("GET call to url", "url", r.URL.Path)
log.V(2).Info("GET call params are", "params", r.URL.Query())
name := r.URL.Query().Get("name")
namespace := r.URL.Query().Get("namespace")
dcOptions := client.DescribeClusterOptions{
Kubeconfig: client.Kubeconfig{Path: kubeconfigPath, Context: kubeContext},
Namespace: namespace,
ClusterName: name,
ShowOtherConditions: "",
ShowMachineSets: true,
Echo: true,
Grouping: false,
AddTemplateVirtualNode: true,
ShowClusterResourceSets: true,
ShowTemplates: true,
}
tree, httpErr := internal.ConstructClusterResourceTree(ctx, c.ClusterctlClient, c.ControllerRuntimeClient, dcOptions)
if httpErr != nil {
log.Error(httpErr, "failed to construct resource tree for target cluster", "clusterName", name)
http.Error(w, httpErr.Error(), httpErr.Status)
return
}
if tree != nil {
marshalled, err := json.MarshalIndent(*tree, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
io.Copy(w, bytes.NewReader(marshalled))
}
}
func handleCustomResourceDefinitionTree(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
log := ctrl.LoggerFrom(ctx)
log.V(2).Info("GET call to url", "url", r.URL.Path)
log.V(2).Info("GET call params are", "params", r.URL.Query())
kind := r.URL.Query().Get("kind")
apiVersion := r.URL.Query().Get("apiVersion")
name := r.URL.Query().Get("name")
namespace := r.URL.Query().Get("namespace")
// TODO: should the runtimeClient be regenerated here?
object, httpErr := internal.GetCustomResource(ctx, c.ControllerRuntimeClient, kind, apiVersion, namespace, name)
if httpErr != nil {
log.Error(httpErr, "failed to construct tree for custom resource", "kind", kind, "name", name)
http.Error(w, httpErr.Error(), httpErr.Status)
return
}
data, err := object.MarshalJSON()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
io.Copy(w, bytes.NewReader(data))
}
func handleGetResourceLogs(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
log := ctrl.LoggerFrom(ctx)
log.V(2).Info("GET call to url", "url", r.URL.Path)
log.V(2).Info("GET call params are", "params", r.URL.Query())
kind := r.URL.Query().Get("kind")
name := r.URL.Query().Get("name")
namespace := r.URL.Query().Get("namespace")
config, err := c.ClusterClient.Proxy().GetConfig()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
logs, err := internal.GetPodLogsForResource(ctx, c.ControllerRuntimeClient, config, kind, namespace, name)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
data, err := json.Marshal(logs)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
io.Copy(w, bytes.NewReader(data))
}
func handleGetVersion(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
log := ctrl.LoggerFrom(ctx)
log.V(2).Info("GET call to url", "url", r.URL.Path)
versionInfo := version.Get()
data, err := json.MarshalIndent(versionInfo, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
io.Copy(w, bytes.NewReader(data))
}