From e2a91aa06d9cf0817877a190e625d25088923b76 Mon Sep 17 00:00:00 2001 From: Jussi Maki Date: Mon, 18 Mar 2024 09:53:26 +0100 Subject: [PATCH] Add http handlers Signed-off-by: Jussi Maki --- demo/handlers.go | 28 ++++++++++++++++++++++++++++ demo/main.go | 40 +++++++++++++++++++++++++++++++++++++--- 2 files changed, 65 insertions(+), 3 deletions(-) create mode 100644 demo/handlers.go diff --git a/demo/handlers.go b/demo/handlers.go new file mode 100644 index 0000000..b1a0b25 --- /dev/null +++ b/demo/handlers.go @@ -0,0 +1,28 @@ +package main + +import ( + "fmt" + "net/http" + "text/tabwriter" + "time" + + "github.com/cilium/statedb" + v1 "k8s.io/api/core/v1" +) + +func registerStateDBHTTPHandler(mux *http.ServeMux, db *statedb.DB) { + mux.Handle("/statedb", db) +} + +func registerPodHTTPHandler(mux *http.ServeMux, db *statedb.DB, pods statedb.Table[*Pod]) { + mux.HandleFunc("/pods/running", func(w http.ResponseWriter, req *http.Request) { + txn := db.ReadTxn() + iter, _ := pods.Get(txn, PodPhaseIndex.Query(v1.PodRunning)) + t := tabwriter.NewWriter(w, 10, 4, 2, ' ', 0) + fmt.Fprintf(t, "NAME\tSTARTED\tPOD IP\tSTATUS\n") + for pod, _, ok := iter.Next(); ok; pod, _, ok = iter.Next() { + fmt.Fprintf(t, "%s/%s\t%s ago\t%s\t%s\n", pod.Namespace, pod.Name, time.Since(pod.Status.StartTime.Time), pod.Status.PodIP, pod.ReconciliationStatus()) + } + t.Flush() + }) +} diff --git a/demo/main.go b/demo/main.go index cd7df2b..be55c84 100644 --- a/demo/main.go +++ b/demo/main.go @@ -1,6 +1,8 @@ package main import ( + "log/slog" + "net/http" "path" "time" @@ -21,20 +23,37 @@ var Hive = hive.New( statedb.Cell, cell.SimpleHealthCell, + // Kubernetes client cell.Provide( - NewPodTable, newClientset, + ), + + // HTTP server + cell.Provide( + http.NewServeMux, + ), + cell.Invoke( + registerHTTPServer, + registerStateDBHTTPHandler, + ), + + // Pod tables and the reconciler + cell.Provide( + NewPodTable, + statedb.RWTable[*Pod].ToTable, podReflectorConfig, podReconcilerConfig, ), + reflector.KubernetesCell[*Pod](), + cell.Invoke( statedb.RegisterTable[*Pod], reconciler.Register[*Pod], - ), - reflector.KubernetesCell[*Pod](), + registerPodHTTPHandler, + ), ) func main() { @@ -66,3 +85,18 @@ func newClientset() (*kubernetes.Clientset, error) { return kubernetes.NewForConfig(cfg) } + +func registerHTTPServer(log *slog.Logger, mux *http.ServeMux, lc cell.Lifecycle) { + s := &http.Server{Addr: ":8080", Handler: mux} + lc.Append(cell.Hook{ + OnStart: func(cell.HookContext) error { + log.Info("Serving HTTP", "addr", s.Addr) + go s.ListenAndServe() + return nil + }, + OnStop: func(ctx cell.HookContext) error { + return s.Shutdown(ctx) + }, + }) + +}