Merge remote-tracking branch 'origin/develop' into reactions
[akkoma] / lib / pleroma / healthcheck.ex
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 @derive Jason.Encoder
13 defstruct pool_size: 0,
14 active: 0,
15 idle: 0,
16 memory_used: 0,
17 healthy: true
18
19 @type t :: %__MODULE__{
20 pool_size: non_neg_integer(),
21 active: non_neg_integer(),
22 idle: non_neg_integer(),
23 memory_used: number(),
24 healthy: boolean()
25 }
26
27 @spec system_info() :: t()
28 def system_info do
29 %Healthcheck{
30 memory_used: Float.round(:erlang.memory(:total) / 1024 / 1024, 2)
31 }
32 |> assign_db_info()
33 |> check_health()
34 end
35
36 defp assign_db_info(healthcheck) do
37 database = Pleroma.Config.get([Repo, :database])
38
39 query =
40 "select state, count(pid) from pg_stat_activity where datname = '#{database}' group by state;"
41
42 result = Repo.query!(query)
43 pool_size = Pleroma.Config.get([Repo, :pool_size])
44
45 db_info =
46 Enum.reduce(result.rows, %{active: 0, idle: 0}, fn [state, cnt], states ->
47 if state == "active" do
48 Map.put(states, :active, states.active + cnt)
49 else
50 Map.put(states, :idle, states.idle + cnt)
51 end
52 end)
53 |> Map.put(:pool_size, pool_size)
54
55 Map.merge(healthcheck, db_info)
56 end
57
58 @spec check_health(Healthcheck.t()) :: Healthcheck.t()
59 def check_health(%{pool_size: pool_size, active: active} = check)
60 when active >= pool_size do
61 %{check | healthy: false}
62 end
63
64 def check_health(check), do: check
65 end