Skip to content

Commit

Permalink
Add health check; pings the DB
Browse files Browse the repository at this point in the history
  • Loading branch information
tstenner committed Nov 21, 2023
1 parent 3457f6c commit e843503
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 1 deletion.
5 changes: 4 additions & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ package main

import (
"flag"
"net/http"
"os"

// Import all Kubernetes client auth plugins (e.g. Azure, GCP, OIDC, etc.)
Expand Down Expand Up @@ -137,7 +138,9 @@ func main() {
}
//+kubebuilder:scaffold:builder

if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
if err := mgr.AddHealthzCheck("healthz", func(req *http.Request) error {
return pg.Ping(req.Context())
}); err != nil {
setupLog.Error(err, "unable to set up health check")
os.Exit(1)
}
Expand Down
15 changes: 15 additions & 0 deletions internal/postgres/mock/postgres.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions internal/postgres/postgres.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package postgres

import (
"context"
"database/sql"
"fmt"
"log"
Expand All @@ -25,6 +26,7 @@ type PG interface {
GetUser() string
GetHost() string
GetDefaultDatabase() string
Ping(ctx context.Context) error
}

type pg struct {
Expand Down Expand Up @@ -81,6 +83,10 @@ func (c *pg) GetDefaultDatabase() string {
return c.default_database
}

func (c *pg) Ping(ctx context.Context) error {
return c.db.PingContext(ctx)
}

func GetConnection(user, password, host, database, uri_args string) (*sql.DB, error) {
db, err := sql.Open("postgres", fmt.Sprintf("postgresql://%s:%s@%s/%s?%s", user, password, host, database, uri_args))
if err != nil {
Expand Down

0 comments on commit e843503

Please sign in to comment.