Skip to content

Commit

Permalink
chore: (pre-release) add health check command
Browse files Browse the repository at this point in the history
  • Loading branch information
alessio-form3 committed Nov 20, 2024
1 parent b0d16dc commit dd91327
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions cmd/postgres_exporter/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
package main

import (
"errors"
"fmt"
"net"

Check failure on line 19 in cmd/postgres_exporter/main.go

View workflow job for this annotation

GitHub Actions / test

"net" imported and not used
"net/http"
"os"
"strings"
Expand Down Expand Up @@ -46,6 +48,7 @@ var (
autoDiscoverDatabases = kingpin.Flag("auto-discover-databases", "Whether to discover the databases on a server dynamically. (DEPRECATED)").Default("false").Envar("PG_EXPORTER_AUTO_DISCOVER_DATABASES").Bool()
queriesPath = kingpin.Flag("extend.query-path", "Path to custom queries to run. (DEPRECATED)").Default("").Envar("PG_EXPORTER_EXTEND_QUERY_PATH").String()
onlyDumpMaps = kingpin.Flag("dumpmaps", "Do not run, simply dump the maps.").Bool()
health = kingpin.Flag("health", "Do not run, just return if up and running.").Bool()
constantLabelsList = kingpin.Flag("constantLabels", "A list of label=value separated by comma(,). (DEPRECATED)").Default("").Envar("PG_EXPORTER_CONSTANT_LABELS").String()
excludeDatabases = kingpin.Flag("exclude-databases", "A list of databases to remove when autoDiscoverDatabases is enabled (DEPRECATED)").Default("").Envar("PG_EXPORTER_EXCLUDE_DATABASES").String()
includeDatabases = kingpin.Flag("include-databases", "A list of databases to include when autoDiscoverDatabases is enabled (DEPRECATED)").Default("").Envar("PG_EXPORTER_INCLUDE_DATABASES").String()
Expand Down Expand Up @@ -81,6 +84,17 @@ func main() {
return
}

if *health {
healthy, err := runHealthCheck(webConfig)
if err != nil {
level.Error(logger).Log("msg", "Error running helath check", "err", err)
}
if healthy {
os.Exit(0)
}
os.Exit(1)
}

if err := c.ReloadConfig(*configFile, logger); err != nil {
// This is not fatal, but it means that auth must be provided for every dsn.
level.Warn(logger).Log("msg", "Error loading config", "err", err)
Expand Down Expand Up @@ -174,3 +188,23 @@ func main() {
os.Exit(1)
}
}

func runHealthCheck(webConfig *web.FlagConfig) (bool, error) {
if len(*webConfig.WebListenAddresses) == 0 {
return false, errors.New("no listen addresses to run the request to")
}
addr := (*webConfig.WebListenAddresses)[0]
url := fmt.Sprintf("http://%s/", &addr)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return false, err
}

resp, err := http.DefaultClient.Do(req)
if err != nil {
return false, err
}

defer resp.Body.Close()
return resp.StatusCode == 200, nil
}

0 comments on commit dd91327

Please sign in to comment.