logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma

healthcheck.ex (1749B)


      1 # Pleroma: A lightweight social networking server
      2 # Copyright © 2017-2019 Pleroma Authors <https://pleroma.social/>
      3 # SPDX-License-Identifier: AGPL-3.0-only
      4 
      5 defmodule Pleroma.Healthcheck do
      6   @moduledoc """
      7   Module collects metrics about app and assign healthy status.
      8   """
      9   alias Pleroma.Healthcheck
     10   alias Pleroma.Repo
     11 
     12   defstruct pool_size: 0,
     13             active: 0,
     14             idle: 0,
     15             memory_used: 0,
     16             healthy: true
     17 
     18   @type t :: %__MODULE__{
     19           pool_size: non_neg_integer(),
     20           active: non_neg_integer(),
     21           idle: non_neg_integer(),
     22           memory_used: number(),
     23           healthy: boolean()
     24         }
     25 
     26   @spec system_info() :: t()
     27   def system_info do
     28     %Healthcheck{
     29       memory_used: Float.round(:erlang.memory(:total) / 1024 / 1024, 2)
     30     }
     31     |> assign_db_info()
     32     |> check_health()
     33   end
     34 
     35   defp assign_db_info(healthcheck) do
     36     database = Pleroma.Config.get([Repo, :database])
     37 
     38     query =
     39       "select state, count(pid) from pg_stat_activity where datname = '#{database}' group by state;"
     40 
     41     result = Repo.query!(query)
     42     pool_size = Pleroma.Config.get([Repo, :pool_size])
     43 
     44     db_info =
     45       Enum.reduce(result.rows, %{active: 0, idle: 0}, fn [state, cnt], states ->
     46         if state == "active" do
     47           Map.put(states, :active, states.active + cnt)
     48         else
     49           Map.put(states, :idle, states.idle + cnt)
     50         end
     51       end)
     52       |> Map.put(:pool_size, pool_size)
     53 
     54     Map.merge(healthcheck, db_info)
     55   end
     56 
     57   @spec check_health(Healthcheck.t()) :: Healthcheck.t()
     58   def check_health(%{pool_size: pool_size, active: active} = check)
     59       when active >= pool_size do
     60     %{check | healthy: false}
     61   end
     62 
     63   def check_health(check), do: check
     64 end