ha-handler/lib/ha_handler/pgsql/watcher.ex
2022-02-19 10:18:05 +01:00

42 lines
1.2 KiB
Elixir

defmodule HAHandler.PGSQL.Watcher do
use GenServer
require Logger
def start_link(opts) do
GenServer.start_link(__MODULE__, opts, name: __MODULE__)
end
@impl true
def init(opts) do
# Starts a Postgrex child but does not means the connection was
# successful.
# TODO: set dbconnections backoff and connect hooks
# See https://github.com/elixir-ecto/db_connection/blob/master/lib/db_connection.ex#L343
{:ok, pid} = Postgrex.start_link(opts)
state = %{
backend: pid,
hostname: Keyword.get(opts, :hostname)
}
{:ok, state}
end
@impl true
def handle_call(:status, _from, %{backend: backend, hostname: hostname} = state) do
result = case Postgrex.query(backend, "SELECT version();", []) do
{:ok, %Postgrex.Result{rows: [[raw_version_string]]}} ->
version = case Regex.run(~r/^PostgreSQL (\d+\.\d+)/, raw_version_string) do
[_, version_number] -> version_number
_ -> "unknown"
end
%{hostname: hostname, version: version, status: "up"}
{:error, %DBConnection.ConnectionError{message: _msg, reason: err}} ->
%{hostname: hostname, version: "unknown", status: err}
_ ->
%{hostname: hostname, version: "unknown", status: "Unhandled error"}
end
{:reply, result, state}
end
end