Skip to content

Commit

Permalink
Add http handlers
Browse files Browse the repository at this point in the history
Signed-off-by: Jussi Maki <[email protected]>
joamaki committed Mar 18, 2024
1 parent e36c0f9 commit e2a91aa
Showing 2 changed files with 65 additions and 3 deletions.
28 changes: 28 additions & 0 deletions demo/handlers.go
Original file line number Diff line number Diff line change
@@ -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()
})
}
40 changes: 37 additions & 3 deletions demo/main.go
Original file line number Diff line number Diff line change
@@ -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)
},
})

}

0 comments on commit e2a91aa

Please sign in to comment.