Merge branch 'develop' into admin-be
[akkoma] / lib / pleroma / config / transfer_task.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.Config.TransferTask do
6 use Task
7
8 alias Pleroma.ConfigDB
9 alias Pleroma.Repo
10
11 require Logger
12
13 def start_link(_) do
14 load_and_update_env()
15 if Pleroma.Config.get(:env) == :test, do: Ecto.Adapters.SQL.Sandbox.checkin(Repo)
16 :ignore
17 end
18
19 def load_and_update_env do
20 with true <- Pleroma.Config.get(:configurable_from_database),
21 true <- Ecto.Adapters.SQL.table_exists?(Repo, "config"),
22 started_applications <- Application.started_applications() do
23 # We need to restart applications for loaded settings take effect
24 ConfigDB
25 |> Repo.all()
26 |> Enum.map(&update_env(&1))
27 |> Enum.uniq()
28 # TODO: some problem with prometheus after restart!
29 |> Enum.reject(&(&1 in [:pleroma, nil, :prometheus]))
30 |> Enum.each(&restart(started_applications, &1))
31 end
32 end
33
34 defp update_env(setting) do
35 try do
36 key = ConfigDB.from_string(setting.key)
37 group = ConfigDB.from_string(setting.group)
38 value = ConfigDB.from_binary(setting.value)
39
40 default = Pleroma.Config.Holder.config(group, key)
41
42 merged_value =
43 if can_be_merged?(default, value) do
44 ConfigDB.merge_group(group, key, default, value)
45 else
46 value
47 end
48
49 :ok = Application.put_env(group, key, merged_value)
50
51 if group != :logger do
52 group
53 else
54 # change logger configuration in runtime, without restart
55 if Keyword.keyword?(merged_value) and
56 key not in [:compile_time_application, :backends, :compile_time_purge_matching] do
57 Logger.configure_backend(key, merged_value)
58 else
59 Logger.configure([{key, merged_value}])
60 end
61
62 nil
63 end
64 rescue
65 e ->
66 Logger.warn(
67 "updating env causes error, group: #{inspect(setting.group)}, key: #{
68 inspect(setting.key)
69 }, value: #{inspect(ConfigDB.from_binary(setting.value))}, error: #{inspect(e)}"
70 )
71
72 nil
73 end
74 end
75
76 defp restart(started_applications, app) do
77 with {^app, _, _} <- List.keyfind(started_applications, app, 0),
78 :ok <- Application.stop(app) do
79 :ok = Application.start(app)
80 else
81 nil ->
82 Logger.warn("#{app} is not started.")
83
84 error ->
85 error
86 |> inspect()
87 |> Logger.warn()
88 end
89 end
90
91 defp can_be_merged?(val1, val2) when is_list(val1) and is_list(val2) do
92 Keyword.keyword?(val1) and Keyword.keyword?(val2)
93 end
94
95 defp can_be_merged?(_val1, _val2), do: false
96 end