logo

pleroma

My custom branche(s) on git.pleroma.social/pleroma/pleroma git clone https://anongit.hacktivis.me/git/pleroma.git/

healthcheck.ex (2035B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2024 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.Search.Healthcheck do
  5. @doc """
  6. Monitors health of search backend to control processing of events based on health and availability.
  7. """
  8. use GenServer
  9. require Logger
  10. @queue :search_indexing
  11. @tick :timer.seconds(5)
  12. @timeout :timer.seconds(2)
  13. def start_link(_) do
  14. GenServer.start_link(__MODULE__, [], name: __MODULE__)
  15. end
  16. @impl true
  17. def init(_) do
  18. state = %{healthy: false}
  19. {:ok, state, {:continue, :start}}
  20. end
  21. @impl true
  22. def handle_continue(:start, state) do
  23. tick()
  24. {:noreply, state}
  25. end
  26. @impl true
  27. def handle_info(:check, state) do
  28. urls = Pleroma.Search.healthcheck_endpoints()
  29. new_state =
  30. if check(urls) do
  31. Oban.resume_queue(queue: @queue)
  32. Map.put(state, :healthy, true)
  33. else
  34. Oban.pause_queue(queue: @queue)
  35. Map.put(state, :healthy, false)
  36. end
  37. maybe_log_state_change(state, new_state)
  38. tick()
  39. {:noreply, new_state}
  40. end
  41. @impl true
  42. def handle_call(:state, _from, state) do
  43. {:reply, state, state, :hibernate}
  44. end
  45. def state, do: GenServer.call(__MODULE__, :state)
  46. def check([]), do: true
  47. def check(urls) when is_list(urls) do
  48. Enum.all?(
  49. urls,
  50. fn url ->
  51. case Pleroma.HTTP.get(url, [], recv_timeout: @timeout) do
  52. {:ok, %{status: 200}} -> true
  53. _ -> false
  54. end
  55. end
  56. )
  57. end
  58. def check(_), do: true
  59. defp tick do
  60. Process.send_after(self(), :check, @tick)
  61. end
  62. defp maybe_log_state_change(%{healthy: true}, %{healthy: false}) do
  63. Logger.error("Pausing Oban queue #{@queue} due to search backend healthcheck failure")
  64. end
  65. defp maybe_log_state_change(%{healthy: false}, %{healthy: true}) do
  66. Logger.info("Resuming Oban queue #{@queue} due to search backend healthcheck pass")
  67. end
  68. defp maybe_log_state_change(_, _), do: :ok
  69. end