diff --git a/pkg/server/main.go b/pkg/server/main.go index b5e43047dd..8dab23d571 100644 --- a/pkg/server/main.go +++ b/pkg/server/main.go @@ -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" ) @@ -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"` } @@ -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) @@ -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 {