Skip to content

Commit

Permalink
feat: add simple health endpoint
Browse files Browse the repository at this point in the history
Signed-off-by: Thomas Schuetz <thomas.schuetz@t-sc.eu>
  • Loading branch information
thschue committed Apr 13, 2023
1 parent 336ec2a commit 26c0cb2
Showing 1 changed file with 32 additions and 6 deletions.
38 changes: 32 additions & 6 deletions pkg/server/main.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package server

import (
json "encoding/json"
"fmt"
"github.com/fatih/color"
"github.com/k8sgpt-ai/k8sgpt/pkg/analysis"
"net/http"
"os"
"strconv"
"strings"
)
Expand All @@ -18,6 +18,18 @@ type Config struct {
Output string
}

type Health struct {
Status string `json:"status"`
Success int `json:"success"`
Failure int `json:"failure"`
}

var health = Health{
Status: "ok",
Success: 0,
Failure: 0,
}

type Result struct {
Analysis []analysis.Analysis `json:"analysis"`
}
Expand All @@ -31,35 +43,40 @@ func (s *Config) analyzeHandler(w http.ResponseWriter, r *http.Request) {

config, err := analysis.NewAnalysis(s.Backend, language, []string{}, namespace, nocache, explain)
if err != nil {
health.Failure++
fmt.Fprintf(w, err.Error())
}

err = config.RunAnalysis()
if err != nil {
color.Red("Error: %v", err)
os.Exit(1)
health.Failure++
fmt.Fprintf(w, err.Error())
}

if explain {
err := config.GetAIResults(s.Output, anonymize)
if err != nil {
color.Red("Error: %v", err)
os.Exit(1)
health.Failure++
fmt.Fprintf(w, err.Error())
}
}

output, err := config.JsonOutput()
if err != nil {
color.Red("Error: %v", err)
os.Exit(1)
health.Failure++
fmt.Fprintf(w, err.Error())
}
health.Success++
fmt.Fprintf(w, string(output))

}

func (s *Config) Serve() error {
http.HandleFunc("/analyze", s.analyzeHandler)
color.Green("Starting server on port %d", s.Port)
http.HandleFunc("/healthz", s.healthzHandler)
color.Green("Starting server on port %s", s.Port)
err := http.ListenAndServe(":"+s.Port, nil)
if err != nil {
fmt.Printf("error starting server: %s\n", err)
Expand All @@ -68,6 +85,15 @@ func (s *Config) Serve() error {
return nil
}

func (s *Config) healthzHandler(w http.ResponseWriter, r *http.Request) {
js, err := json.MarshalIndent(health, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, string(js))
}

func getBoolParam(param string) bool {
b, err := strconv.ParseBool(strings.ToLower(param))
if err != nil {
Expand Down

0 comments on commit 26c0cb2

Please sign in to comment.