Przeglądaj źródła

Improve health check endpoint to test database connection

Frédéric Guillot 5 lat temu
rodzic
commit
e3c28a6c96
4 zmienionych plików z 29 dodań i 14 usunięć
  1. 7 3
      cli/cli.go
  2. 5 0
      service/httpd/httpd.go
  3. 0 11
      storage/feed.go
  4. 17 0
      storage/storage.go

+ 7 - 3
cli/cli.go

@@ -126,17 +126,21 @@ func Parse() {
 		config.Opts.DatabaseMaxConns(),
 	)
 	if err != nil {
-		logger.Fatal("Unable to connect to the database: %v", err)
+		logger.Fatal("Unable to initialize database connection pool: %v", err)
 	}
 	defer db.Close()
 
+	store := storage.NewStorage(db)
+
+	if err := store.Ping(); err != nil {
+		logger.Fatal("Unable to connect to the database: %v", err)
+	}
+
 	if flagMigrate {
 		database.Migrate(db)
 		return
 	}
 
-	store := storage.NewStorage(db)
-
 	if flagResetFeedErrors {
 		store.ResetFeedErrors()
 		return

+ 5 - 0
service/httpd/httpd.go

@@ -184,6 +184,11 @@ func setupHandler(store *storage.Storage, pool *worker.Pool) *mux.Router {
 	ui.Serve(router, store, pool)
 
 	router.HandleFunc("/healthcheck", func(w http.ResponseWriter, r *http.Request) {
+		if err := store.Ping(); err != nil {
+			http.Error(w, "Database Connection Error", http.StatusInternalServerError)
+			return
+		}
+
 		w.Write([]byte("OK"))
 	}).Name("healthcheck")
 

+ 0 - 11
storage/feed.go

@@ -79,17 +79,6 @@ func (s *Storage) CountFeeds(userID int64) int {
 	return result
 }
 
-// DatabaseVersion returns the version of the database which is in use
-func (s *Storage) DatabaseVersion() string {
-	var dbVersion string
-	err := s.db.QueryRow(`SELECT current_setting('server_version')`).Scan(&dbVersion)
-	if err != nil {
-		return err.Error()
-	}
-
-	return dbVersion
-}
-
 // CountUserFeedsWithErrors returns the number of feeds with parsing errors that belong to the given user.
 func (s *Storage) CountUserFeedsWithErrors(userID int64) int {
 	pollingParsingErrorLimit := config.Opts.PollingParsingErrorLimit()

+ 17 - 0
storage/storage.go

@@ -17,3 +17,20 @@ type Storage struct {
 func NewStorage(db *sql.DB) *Storage {
 	return &Storage{db}
 }
+
+// DatabaseVersion returns the version of the database which is in use.
+func (s *Storage) DatabaseVersion() string {
+	var dbVersion string
+	err := s.db.QueryRow(`SELECT current_setting('server_version')`).Scan(&dbVersion)
+	if err != nil {
+		return err.Error()
+	}
+
+	return dbVersion
+}
+
+// Ping checks if the database connection works.
+func (s *Storage) Ping() error {
+	_, err := s.db.Exec(`SELECT true`)
+	return err
+}