logo

pleroma

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

base_migrator.ex (6084B)


  1. # Pleroma: A lightweight social networking server
  2. # Copyright © 2017-2022 Pleroma Authors <https://pleroma.social/>
  3. # SPDX-License-Identifier: AGPL-3.0-only
  4. defmodule Pleroma.Migrators.Support.BaseMigrator do
  5. @moduledoc """
  6. Base background migrator functionality.
  7. """
  8. @callback perform() :: any()
  9. @callback retry_failed() :: any()
  10. @callback feature_config_path() :: list(atom())
  11. @callback query() :: Ecto.Query.t()
  12. @callback fault_rate_allowance() :: integer() | float()
  13. defmacro __using__(_opts) do
  14. quote do
  15. use GenServer
  16. require Logger
  17. import Ecto.Query
  18. alias __MODULE__.State
  19. alias Pleroma.Config
  20. alias Pleroma.Repo
  21. @behaviour Pleroma.Migrators.Support.BaseMigrator
  22. defdelegate data_migration(), to: State
  23. defdelegate data_migration_id(), to: State
  24. defdelegate state(), to: State
  25. defdelegate persist_state(), to: State, as: :persist_to_db
  26. defdelegate get_stat(key, value \\ nil), to: State, as: :get_data_key
  27. defdelegate put_stat(key, value), to: State, as: :put_data_key
  28. defdelegate increment_stat(key, increment), to: State, as: :increment_data_key
  29. @reg_name {:global, __MODULE__}
  30. def whereis, do: GenServer.whereis(@reg_name)
  31. def start_link(_) do
  32. case whereis() do
  33. nil ->
  34. GenServer.start_link(__MODULE__, nil, name: @reg_name)
  35. pid ->
  36. {:ok, pid}
  37. end
  38. end
  39. @impl true
  40. def init(_) do
  41. {:ok, nil, {:continue, :init_state}}
  42. end
  43. @impl true
  44. def handle_continue(:init_state, _state) do
  45. {:ok, _} = State.start_link(nil)
  46. data_migration = data_migration()
  47. manual_migrations = Config.get([:instance, :manual_data_migrations], [])
  48. cond do
  49. Config.get(:env) == :test ->
  50. update_status(:noop)
  51. is_nil(data_migration) ->
  52. message = "Data migration does not exist."
  53. update_status(:failed, message)
  54. Logger.error("#{__MODULE__}: #{message}")
  55. data_migration.state == :manual or data_migration.name in manual_migrations ->
  56. message = "Data migration is in manual execution or manual fix mode."
  57. update_status(:manual, message)
  58. Logger.warning("#{__MODULE__}: #{message}")
  59. data_migration.state == :complete ->
  60. on_complete(data_migration)
  61. true ->
  62. send(self(), :perform)
  63. end
  64. {:noreply, nil}
  65. end
  66. @impl true
  67. def handle_info(:perform, state) do
  68. State.reinit()
  69. update_status(:running)
  70. put_stat(:iteration_processed_count, 0)
  71. put_stat(:started_at, NaiveDateTime.utc_now())
  72. perform()
  73. fault_rate = fault_rate()
  74. put_stat(:fault_rate, fault_rate)
  75. fault_rate_allowance = fault_rate_allowance()
  76. cond do
  77. fault_rate == 0 ->
  78. set_complete()
  79. is_float(fault_rate) and fault_rate <= fault_rate_allowance ->
  80. message = """
  81. Done with fault rate of #{fault_rate} which doesn't exceed #{fault_rate_allowance}.
  82. Putting data migration to manual fix mode. Try running `#{__MODULE__}.retry_failed/0`.
  83. """
  84. Logger.warning("#{__MODULE__}: #{message}")
  85. update_status(:manual, message)
  86. on_complete(data_migration())
  87. true ->
  88. message = "Too many failures. Try running `#{__MODULE__}.retry_failed/0`."
  89. Logger.error("#{__MODULE__}: #{message}")
  90. update_status(:failed, message)
  91. end
  92. persist_state()
  93. {:noreply, state}
  94. end
  95. defp on_complete(data_migration) do
  96. if data_migration.feature_lock || feature_state() == :disabled do
  97. Logger.warning(
  98. "#{__MODULE__}: migration complete but feature is locked; consider enabling."
  99. )
  100. :noop
  101. else
  102. Config.put(feature_config_path(), :enabled)
  103. :ok
  104. end
  105. end
  106. @doc "Approximate count for current iteration (including processed records count)"
  107. def count(force \\ false, timeout \\ :infinity) do
  108. stored_count = get_stat(:count)
  109. if stored_count && !force do
  110. stored_count
  111. else
  112. processed_count = get_stat(:processed_count, 0)
  113. max_processed_id = get_stat(:max_processed_id, 0)
  114. query = where(query(), [entity], entity.id > ^max_processed_id)
  115. count = Repo.aggregate(query, :count, :id, timeout: timeout) + processed_count
  116. put_stat(:count, count)
  117. persist_state()
  118. count
  119. end
  120. end
  121. def failures_count do
  122. with {:ok, %{rows: [[count]]}} <-
  123. Repo.query(
  124. "SELECT COUNT(record_id) FROM data_migration_failed_ids WHERE data_migration_id = $1;",
  125. [data_migration_id()]
  126. ) do
  127. count
  128. end
  129. end
  130. def feature_state, do: Config.get(feature_config_path())
  131. def force_continue do
  132. send(whereis(), :perform)
  133. end
  134. def force_restart do
  135. :ok = State.reset()
  136. force_continue()
  137. end
  138. def set_complete do
  139. update_status(:complete)
  140. persist_state()
  141. on_complete(data_migration())
  142. end
  143. defp update_status(status, message \\ nil) do
  144. put_stat(:state, status)
  145. put_stat(:message, message)
  146. end
  147. defp fault_rate do
  148. with failures_count when is_integer(failures_count) <- failures_count(),
  149. true <- failures_count > 0 do
  150. failures_count / Enum.max([get_stat(:affected_count, 0), 1])
  151. else
  152. _ -> 0
  153. end
  154. end
  155. defp records_per_second do
  156. get_stat(:iteration_processed_count, 0) / Enum.max([running_time(), 1])
  157. end
  158. defp running_time do
  159. NaiveDateTime.diff(
  160. NaiveDateTime.utc_now(),
  161. get_stat(:started_at, NaiveDateTime.utc_now())
  162. )
  163. end
  164. end
  165. end
  166. end